language
stringclasses 15
values | src_encoding
stringclasses 34
values | length_bytes
int64 6
7.85M
| score
float64 1.5
5.69
| int_score
int64 2
5
| detected_licenses
listlengths 0
160
| license_type
stringclasses 2
values | text
stringlengths 9
7.85M
|
---|---|---|---|---|---|---|---|
Java
|
UTF-8
| 477 | 1.882813 | 2 |
[] |
no_license
|
package com.survey.surveyapp.repository;
import javax.transaction.Transactional;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.survey.surveyapp.entity.SurveyAnswer;
/**
* @author Harsh Jain
*
*
*/
@Repository
@Transactional
public interface SurveyAnswerRepository extends JpaRepository<SurveyAnswer, Long> {
SurveyAnswer getSurveyAnswerByQuestionIdAndAnsweredBy(int questionId, int userId);
}
|
Java
|
UTF-8
| 4,701 | 2.40625 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.example.customview.telescope;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapShader;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Path;
import android.graphics.Shader;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.OvalShape;
import android.graphics.drawable.shapes.PathShape;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import androidx.annotation.Nullable;
import com.example.customview.R;
import com.example.customview.loading.FallingBallImageView;
/**
* @author: LiuSaiSai
* @date: 2020/08/18 20:21
* @description: BUG: 放大镜的位置不合适;解决:半径和放大倍数设置为静态,即可;
* 收获:activity 向 自定义 View 传值:在View中写set()方法,在activity中初始化后调用set();
* 问题:为什么不设置静态就会出错?
*/
public class MyTelescopeView extends View {
private Bitmap mBitmap;
private ShapeDrawable mShapeDrawable;
private int radius = 320;
private int factor = 3;
private Matrix mMatrix = new Matrix();
private static final String TAG = MyTelescopeView.class.getSimpleName();
private Bitmap mDecodeResource;
private Path mPath;
public MyTelescopeView(Context context) {
super(context);
init();
}
public MyTelescopeView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init();
}
public MyTelescopeView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
setLayerType(LAYER_TYPE_SOFTWARE, null);
mPath = new Path();
mPath.moveTo(radius / 2, radius / 4);
mPath.cubicTo((radius * 6) / 7, radius / 9, (radius * 12) / 13, (radius * 2) / 5, radius / 2, (radius * 7) / 12);
mPath.moveTo(radius / 2, radius / 4);
mPath.cubicTo(radius / 7, radius / 9, radius / 13, (radius * 2) / 5, radius / 2, (radius * 7) / 12);
}
/**
* 通过 activity 向 自定义 View 传递参数;
* @param radius 监听 SeekBar 的半径
* @param factor 监听 SeekBar 的放大倍率
* @param isFlush 是否需要刷新页面?只有 放大倍数发生改变才刷新页面(刷新放大镜),
*/
public void setParameter(int radius, int factor,boolean isFlush) {
this.radius = radius;
this.factor = factor;
//解决,更新放大倍率、放大镜半径后,镜子位置岔劈的问题;
if (isFlush)mBitmap = null;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_MOVE:
final int x = (int) event.getX();
final int y = (int) event.getY();
//待办事项:表示的是绘制 Shader 的起始位置
mMatrix.setTranslate(radius - factor * x, radius - factor * y);
mShapeDrawable.getPaint().getShader().setLocalMatrix(mMatrix);
// bounds,圆的外切矩形
mShapeDrawable.setBounds(x - radius, y - radius, x + radius, y + radius);
invalidate();
break;
case MotionEvent.ACTION_UP:
mShapeDrawable.setBounds(-10, -10, 0, 0);
invalidate();
break;
default:
break;
}
return true;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (mBitmap == null) {
mDecodeResource = BitmapFactory.decodeResource(getResources(), R.drawable.advance_woods_path);
//根据源图像生成一个指定宽度和高度的 Bitmap;将源图像缩放到当前控件大小。
mBitmap = Bitmap.createScaledBitmap(mDecodeResource, getWidth(), getHeight(), false);
BitmapShader shader = new BitmapShader(Bitmap.createScaledBitmap(mBitmap,
mBitmap.getWidth() * factor, mBitmap.getHeight() * factor, true),
Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
mShapeDrawable = new ShapeDrawable(new OvalShape());
//mShapeDrawable = new ShapeDrawable(new PathShape(mPath,radius,radius));
mShapeDrawable.getPaint().setShader(shader);
}
canvas.drawBitmap(mBitmap, 0, 0, null);
mShapeDrawable.draw(canvas);
}
}
|
Java
|
UTF-8
| 131 | 1.625 | 2 |
[] |
no_license
|
package com.estg.masters.pedwm.smarthome.model.notification;
public enum ComparingTypeEnum {
BIGGER,
LESSER,
EQUALS
}
|
Java
|
GB18030
| 656 | 2.03125 | 2 |
[] |
no_license
|
package cn;
import org.openjdk.jmh.annotations.*;
public class TestPS {
// һδ
@Benchmark
// ԤȣJVMжضŻػԤȶڲԽҪ
// iterations Ԥ1 time Ԥʱ 3
@Warmup(iterations = 1, time = 3)
// öٸ߳ȥִǵij
@Fork(5)
// Եģʽ
// Throught
@BenchmarkMode(Mode.Throughput)
// ִܹжٴβ
// iterations time ʱ
@Measurement(iterations = 1, time = 3)
public void testForEach() {
Ps.foreach();
}
}
|
Java
|
UTF-8
| 9,472 | 2.171875 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.daedafusion.iconfactory.framework.providers;
import com.daedafusion.iconfactory.framework.providers.util.TranscoderUtil;
import org.apache.batik.bridge.BridgeContext;
import org.apache.batik.bridge.GVTBuilder;
import org.apache.batik.bridge.UserAgentAdapter;
import org.apache.batik.dom.svg.SAXSVGDocumentFactory;
import org.apache.batik.dom.svg.SVGDOMImplementation;
import org.apache.batik.gvt.GraphicsNode;
import org.apache.batik.transcoder.TranscoderException;
import org.apache.batik.util.XMLResourceDescriptor;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.junit.Test;
import org.w3c.dom.*;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
/**
* Created by mphilpot on 7/23/14.
*/
public class BatikDriver
{
private static final Logger log = Logger.getLogger(BatikDriver.class);
@Test
public void transcode() throws IOException, TranscoderException
{
InputStream in = BatikDriver.class.getClassLoader().getResourceAsStream("question37.svg");
FileOutputStream out = new FileOutputStream(new File("/tmp/test.png"));
TranscoderUtil.toPNG(in, 128, out);
out.close();
}
@Test
public void compositeTest() throws TranscoderException, IOException
{
System.setProperty("java.awt.headless", "true");
long a = System.currentTimeMillis();
InputStream iconIn = BatikDriver.class.getClassLoader().getResourceAsStream("icon_twitter.svg");
InputStream ornamentIn = BatikDriver.class.getClassLoader().getResourceAsStream("ornament_warning.svg");
ByteArrayOutputStream iconBaos = new ByteArrayOutputStream();
ByteArrayOutputStream ornamentBaos = new ByteArrayOutputStream();
TranscoderUtil.toPNG(iconIn, 32, iconBaos);
TranscoderUtil.toPNG(ornamentIn, 16, ornamentBaos);
ByteArrayInputStream iconBais = new ByteArrayInputStream(iconBaos.toByteArray());
ByteArrayInputStream ornamentBais = new ByteArrayInputStream(ornamentBaos.toByteArray());
BufferedImage iconImage = ImageIO.read(iconBais);
BufferedImage ornamentImage = ImageIO.read(ornamentBais);
//Try coloring the ornament red
int width = ornamentImage.getWidth();
int height = ornamentImage.getHeight();
for(int xx = 0; xx < width; xx++)
{
for(int yy = 0; yy < height; yy++)
{
Color originalColor = new Color(ornamentImage.getRGB(xx, yy), true);
if(originalColor.getAlpha() != 0)
{
Color newColor = new Color(255, 0, 0, originalColor.getAlpha());
ornamentImage.setRGB(xx, yy, newColor.getRGB());
}
}
}
BufferedImage finalIcon = new BufferedImage(64, 64, BufferedImage.TYPE_INT_ARGB);
Graphics2D graphics = finalIcon.createGraphics();
graphics.drawImage(iconImage, 16, 16, null);
graphics.drawImage(ornamentImage, 0, 0, null);
ImageIO.write(finalIcon, "png", new FileOutputStream(new File("test.png")));
long b = System.currentTimeMillis();
System.out.println(b-a);
}
// @Test
// public void superimpose() throws IOException, TranscoderException
// {
// DOMImplementation impl = SVGDOMImplementation.getDOMImplementation();
// String parser = XMLResourceDescriptor.getXMLParserClassName();
// SAXSVGDocumentFactory factory = new SAXSVGDocumentFactory(parser);
//
// Document icon = factory.createSVGDocument(SVGDOMImplementation.SVG_NAMESPACE_URI, BatikDriver.class.getClassLoader().getResourceAsStream("icon_twitter.svg"));
// Document ornament = factory.createSVGDocument(SVGDOMImplementation.SVG_NAMESPACE_URI, BatikDriver.class.getClassLoader().getResourceAsStream("ornament_warning.svg"));
//
// Node e = icon.importNode(ornament.getDocumentElement(), true);
//
// Node attX = e.getOwnerDocument().createAttribute("x");
// attX.setNodeValue("0");
// e.getAttributes().setNamedItem(attX);
// Node attY = e.getOwnerDocument().createAttribute("y");
// attY.setNodeValue("0");
// e.getAttributes().setNamedItem(attY);
//
// Node width = e.getOwnerDocument().createAttribute("width");
// width.setNodeValue("16");
// e.getAttributes().setNamedItem(width);
// Node height = e.getOwnerDocument().createAttribute("height");
// height.setNodeValue("16");
// e.getAttributes().setNamedItem(height);
//
// icon.getDocumentElement().appendChild(e);
//
// FileOutputStream out = new FileOutputStream(new File("test.png"));
//
// TranscoderUtil.toPNG(icon, 64, out);
//
// out.close();
// }
//
// @Test
// public void moreAdvanced() throws IOException, TranscoderException
// {
// DOMImplementation impl = SVGDOMImplementation.getDOMImplementation();
// String svgNS = SVGDOMImplementation.SVG_NAMESPACE_URI;
// Document wrapper = impl.createDocument(svgNS, "svg", null);
//
// Element svgRoot = wrapper.getDocumentElement();
//
// svgRoot.setAttributeNS(null, "width", "64");
// svgRoot.setAttributeNS(null, "height", "64");
//
// String parser = XMLResourceDescriptor.getXMLParserClassName();
// SAXSVGDocumentFactory factory = new SAXSVGDocumentFactory(parser);
//
// Document icon = factory.createSVGDocument(SVGDOMImplementation.SVG_NAMESPACE_URI, BatikDriver.class.getClassLoader().getResourceAsStream("icon_twitter.svg"));
// Document ornament = factory.createSVGDocument(SVGDOMImplementation.SVG_NAMESPACE_URI, BatikDriver.class.getClassLoader().getResourceAsStream("ornament_warning.svg"));
//
// icon.getDocumentElement().getChildNodes();
//
// Node iconImport = wrapper.importNode(icon.getDocumentElement(), true);
// Node ornamentImport = wrapper.importNode(ornament.getDocumentElement(), true);
//
// setAttribute(iconImport, "x", "16");
// setAttribute(iconImport, "y", "16");
// setAttribute(iconImport, "width", "32");
// setAttribute(iconImport, "height", "32");
//
// wrapper.getDocumentElement().appendChild(iconImport);
//
// setAttribute(ornamentImport, "x", "0");
// setAttribute(ornamentImport, "y", "0");
// setAttribute(ornamentImport, "width", "16");
// setAttribute(ornamentImport, "height", "16");
//
// wrapper.getDocumentElement().appendChild(ornamentImport);
//
// OutputFormat format = new OutputFormat(wrapper);
// StringWriter writer = new StringWriter();
// XMLSerializer serial = new XMLSerializer(writer, format);
// serial.serialize(wrapper);
//
// System.out.println(writer.toString());
//
// FileOutputStream out = new FileOutputStream(new File("test.png"));
//
// TranscoderUtil.toPNG(icon, 64, out);
//
// out.close();
// }
//
// @Test
// public void boundingBox() throws IOException
// {
// String parser = XMLResourceDescriptor.getXMLParserClassName();
// SAXSVGDocumentFactory factory = new SAXSVGDocumentFactory(parser);
//
// Document icon = factory.createSVGDocument(SVGDOMImplementation.SVG_NAMESPACE_URI, BatikDriver.class.getClassLoader().getResourceAsStream("icon_twitter.svg"));
//
// GVTBuilder builder = new GVTBuilder();
// BridgeContext context = new BridgeContext(new UserAgentAdapter());
//
// GraphicsNode gvtRoot = builder.build(context, icon);
//
// System.out.println("width = " + Math.ceil(gvtRoot.getSensitiveBounds().getWidth()));
// System.out.println("height = " + Math.ceil(gvtRoot.getSensitiveBounds().getHeight()));
// }
//
// @Test
// public void compose() throws IOException
// {
// String parser = XMLResourceDescriptor.getXMLParserClassName();
// SAXSVGDocumentFactory factory = new SAXSVGDocumentFactory(parser);
//
// Document icon = factory.createSVGDocument(SVGDOMImplementation.SVG_NAMESPACE_URI, BatikDriver.class.getClassLoader().getResourceAsStream("icon_twitter.svg"));
// Document ornament = factory.createSVGDocument(SVGDOMImplementation.SVG_NAMESPACE_URI, BatikDriver.class.getClassLoader().getResourceAsStream("ornament_warning.svg"));
//
// DOMImplementation impl = SVGDOMImplementation.getDOMImplementation();
// String svgNS = SVGDOMImplementation.SVG_NAMESPACE_URI;
// Document wrapper = impl.createDocument(svgNS, "svg", null);
//
// Element svgRoot = wrapper.getDocumentElement();
//
// svgRoot.setAttributeNS(null, "width", "64");
// svgRoot.setAttributeNS(null, "height", "64");
//
//
// }
//
// private double getMaxDimension(Document doc)
// {
// GVTBuilder builder = new GVTBuilder();
// BridgeContext context = new BridgeContext(new UserAgentAdapter());
//
// GraphicsNode gvtRoot = builder.build(context, doc);
//
// return Math.max(Math.ceil(gvtRoot.getSensitiveBounds().getWidth()),
// Math.ceil(gvtRoot.getSensitiveBounds().getHeight()));
// }
//
// private void setAttribute(Node node, String attribute, String value)
// {
// Node attr = node.getOwnerDocument().createAttribute(attribute);
// attr.setNodeValue(value);
// node.getAttributes().setNamedItem(attr);
// }
}
|
Java
|
GB18030
| 1,973 | 2.46875 | 2 |
[] |
no_license
|
package com.example.testfinalmvp;
import com.org.finalmvp.view.BaseView;
import com.presenter.UserPresenter;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity implements BaseView, OnClickListener {
Context context = MainActivity.this;
UserPresenter userpresenter;
TextView tv_info;
Button btStart;
Button btStop;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
userpresenter = new UserPresenter(this);
}
private void initView() {
tv_info = (TextView) findViewById(R.id.tv_info);
btStart = (Button) findViewById(R.id.bt_start);
btStart.setOnClickListener(this);
btStop = (Button) findViewById(R.id.bt_stop);
btStop.setOnClickListener(this);
}
/**
* ֪ͨؼ״̬ı ûзݵ
*/
@Override
public void onDataChanage(int dataId) {
tv_info.setText(String.valueOf(dataId));
}
/**
* ص ıؼ
*/
@Override
public void onChanageUi(int tag, Object msg) {
switch (tag) {
case UserPresenter.START_LOAD_DATA:
tv_info.setText("start action...");
break;
case UserPresenter.STOP_LOAD_DATA:
tv_info.setText("stop action....");
break;
default:
break;
}
Toast.makeText(MainActivity.this, msg + " tab:=" + tag, Toast.LENGTH_SHORT).show();
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bt_start:
startOnclick(v);
break;
case R.id.bt_stop:
stopOnclick(v);
break;
default:
break;
}
}
private void stopOnclick(View v) {
userpresenter.stopAction();
}
private void startOnclick(View v) {
userpresenter.startAction();
}
}
|
C++
|
UTF-8
| 729 | 3.34375 | 3 |
[] |
no_license
|
#include "LeetCode.hpp"
/*
409. Longest Palindrome
Easy
Given a string which consists of lowercase or uppercase letters, find the length of the longest palindromes that can be built with those letters.
This is case sensitive, for example "Aa" is not considered a palindrome here.
Note:
Assume the length of given string will not exceed 1,010.
Example:
Input:
"abccccdd"
Output:
7
Explanation:
One longest palindrome that can be built is "dccaccd", whose length is 7.
Tags:
1. Hash Table
Similar Questions:
1. Palindrome Permutation
*/
class Solution {
public:
int longestPalindrome(string s) {
}
};
TEST_CASE("longest-palindrome", "[409][Easy][hash-table]") {
//TODO
CHECK(true);
}
|
C#
|
UTF-8
| 1,021 | 2.671875 | 3 |
[] |
no_license
|
using Graphics.Contracts;
using OpenTK.Graphics.OpenGL;
namespace Graphics
{
public sealed class TextureChanger : ITextureChanger
{
private int _textureId;
public TextureChanger()
{
_textureId = -1;
}
void ITextureChanger.SetTexture(int textureId, int channel)
{
if (_textureId == textureId)
return;
_textureId = textureId;
switch(channel)
{
case 0:
GL.ActiveTexture(TextureUnit.Texture0);
break;
case 1:
GL.ActiveTexture(TextureUnit.Texture1);
break;
case 2:
GL.ActiveTexture(TextureUnit.Texture2);
break;
case 3:
GL.ActiveTexture(TextureUnit.Texture3);
break;
}
GL.BindTexture(TextureTarget.Texture2D, textureId);
}
}
}
|
Java
|
UTF-8
| 8,995 | 2.46875 | 2 |
[] |
no_license
|
/*******************************************************************************
* Copyright (c) 2000, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.swt.graphics;
import org.eclipse.swt.internal.win32.*;
import org.eclipse.swt.*;
public final class Font extends Resource {
/**
* the handle to the OS font resource
* (Warning: This field is platform dependent)
* <p>
* <b>IMPORTANT:</b> This field is <em>not</em> part of the SWT
* public API. It is marked public only so that it can be shared
* within the packages provided by SWT. It is not available on all
* platforms and should never be accessed from application code.
* </p>
*/
public int handle;
/**
* Prevents uninitialized instances from being created outside the package.
*/
Font() {
}
/**
* Constructs a new font given a device and font data
* which describes the desired font's appearance.
* <p>
* You must dispose the font when it is no longer required.
* </p>
*
* @param device the device to create the font on
* @param fd the FontData that describes the desired font (must not be null)
*
* @exception IllegalArgumentException <ul>
* <li>ERROR_NULL_ARGUMENT - if device is null and there is no current device</li>
* <li>ERROR_NULL_ARGUMENT - if the fd argument is null</li>
* </ul>
* @exception SWTError <ul>
* <li>ERROR_NO_HANDLES - if a font could not be created from the given font data</li>
* </ul>
*/
public Font(Device device, FontData fd) {
if (device == null)
device = Device.getDevice();
if (device == null)
SWT.error(SWT.ERROR_NULL_ARGUMENT);
init(device, fd);
if (device.tracking)
device.new_Object(this);
}
/**
* Constructs a new font given a device and an array
* of font data which describes the desired font's
* appearance.
* <p>
* You must dispose the font when it is no longer required.
* </p>
*
* @param device the device to create the font on
* @param fds the array of FontData that describes the desired font (must not be null)
*
* @exception IllegalArgumentException <ul>
* <li>ERROR_NULL_ARGUMENT - if device is null and there is no current device</li>
* <li>ERROR_NULL_ARGUMENT - if the fds argument is null</li>
* <li>ERROR_INVALID_ARGUMENT - if the length of fds is zero</li>
* <li>ERROR_NULL_ARGUMENT - if any fd in the array is null</li>
* </ul>
* @exception SWTError <ul>
* <li>ERROR_NO_HANDLES - if a font could not be created from the given font data</li>
* </ul>
*
* @since 2.1
*/
public Font(Device device, FontData[] fds) {
if (device == null)
device = Device.getDevice();
if (device == null)
SWT.error(SWT.ERROR_NULL_ARGUMENT);
if (fds == null)
SWT.error(SWT.ERROR_NULL_ARGUMENT);
if (fds.length == 0)
SWT.error(SWT.ERROR_INVALID_ARGUMENT);
for (int i = 0; i < fds.length; i++) {
if (fds[i] == null)
SWT.error(SWT.ERROR_INVALID_ARGUMENT);
}
init(device, fds[0]);
if (device.tracking)
device.new_Object(this);
}
/**
* Constructs a new font given a device, a font name,
* the height of the desired font in points, and a font
* style.
* <p>
* You must dispose the font when it is no longer required.
* </p>
*
* @param device the device to create the font on
* @param name the name of the font (must not be null)
* @param height the font height in points
* @param style a bit or combination of NORMAL, BOLD, ITALIC
*
* @exception IllegalArgumentException <ul>
* <li>ERROR_NULL_ARGUMENT - if device is null and there is no current device</li>
* <li>ERROR_NULL_ARGUMENT - if the name argument is null</li>
* <li>ERROR_INVALID_ARGUMENT - if the height is negative</li>
* </ul>
* @exception SWTError <ul>
* <li>ERROR_NO_HANDLES - if a font could not be created from the given arguments</li>
* </ul>
*/
public Font(Device device, String name, int height, int style) {
if (device == null)
device = Device.getDevice();
if (device == null)
SWT.error(SWT.ERROR_NULL_ARGUMENT);
if (name == null)
SWT.error(SWT.ERROR_NULL_ARGUMENT);
init(device, new FontData(name, height, style));
if (device.tracking)
device.new_Object(this);
}
/**
* Disposes of the operating system resources associated with
* the font. Applications must dispose of all fonts which
* they allocate.
*/
public void dispose() {
if (handle == 0)
return;
if (device.isDisposed())
return;
OS.DeleteObject(handle);
handle = 0;
if (device.tracking)
device.dispose_Object(this);
device = null;
}
/**
* Compares the argument to the receiver, and returns true
* if they represent the <em>same</em> object using a class
* specific comparison.
*
* @param object the object to compare with this object
* @return <code>true</code> if the object is the same as this object and <code>false</code> otherwise
*
* @see #hashCode
*/
public boolean equals(Object object) {
if (object == this)
return true;
if (!(object instanceof Font))
return false;
Font font = (Font) object;
return device == font.device && handle == font.handle;
}
/**
* Returns an array of <code>FontData</code>s representing the receiver.
* On Windows, only one FontData will be returned per font. On X however,
* a <code>Font</code> object <em>may</em> be composed of multiple X
* fonts. To support this case, we return an array of font data objects.
*
* @return an array of font data objects describing the receiver
*
* @exception SWTException <ul>
* <li>ERROR_GRAPHIC_DISPOSED - if the receiver has been disposed</li>
* </ul>
*/
public FontData[] getFontData() {
if (isDisposed())
SWT.error(SWT.ERROR_GRAPHIC_DISPOSED);
LOGFONT logFont = OS.IsUnicode ? (LOGFONT) new LOGFONTW() : new LOGFONTA();
OS.GetObject(handle, LOGFONT.sizeof, logFont);
return new FontData[] { FontData.win32_new(logFont, device.computePoints(logFont, handle)) };
}
/**
* Returns an integer hash code for the receiver. Any two
* objects that return <code>true</code> when passed to
* <code>equals</code> must return the same value for this
* method.
*
* @return the receiver's hash
*
* @see #equals
*/
public int hashCode() {
return handle;
}
void init(Device device, FontData fd) {
if (fd == null)
SWT.error(SWT.ERROR_NULL_ARGUMENT);
this.device = device;
LOGFONT logFont = fd.data;
int lfHeight = logFont.lfHeight;
logFont.lfHeight = device.computePixels(fd.height);
handle = OS.CreateFontIndirect(logFont);
logFont.lfHeight = lfHeight;
if (handle == 0)
SWT.error(SWT.ERROR_NO_HANDLES);
}
/**
* Returns <code>true</code> if the font has been disposed,
* and <code>false</code> otherwise.
* <p>
* This method gets the dispose state for the font.
* When a font has been disposed, it is an error to
* invoke any other method using the font.
*
* @return <code>true</code> when the font is disposed and <code>false</code> otherwise
*/
public boolean isDisposed() {
return handle == 0;
}
/**
* Returns a string containing a concise, human-readable
* description of the receiver.
*
* @return a string representation of the receiver
*/
public String toString() {
if (isDisposed())
return "Font {*DISPOSED*}";
return "Font {" + handle + "}";
}
/**
* Invokes platform specific functionality to allocate a new font.
* <p>
* <b>IMPORTANT:</b> This method is <em>not</em> part of the public
* API for <code>Font</code>. It is marked public only so that it
* can be shared within the packages provided by SWT. It is not
* available on all platforms, and should never be called from
* application code.
* </p>
*
* @param device the device on which to allocate the color
* @param handle the handle for the font
* @return a new font object containing the specified device and handle
*/
public static Font win32_new(Device device, int handle) {
if (device == null)
device = Device.getDevice();
Font font = new Font();
font.handle = handle;
font.device = device;
return font;
}
}
|
Java
|
UTF-8
| 3,014 | 2.28125 | 2 |
[] |
no_license
|
/**
* Copyright 2018 SinoSoft. All Rights Reserved.
*/
package com.sinosoft.station.modules.station.service;
import java.util.List;
import com.sinosoft.station.modules.station.model.Station;
/**
* <B>系统名称:</B><BR>
* <B>模块名称:</B><BR>
* <B>中文类名:</B><BR>
* <B>概要说明:</B><BR>
*
* @author 中科软科技 lihaiyi
* @since 2018年8月8日
*/
public interface StationService {
/**
*
* <B>方法名称:findAllByTime</B><BR>
* <B>概要说明:查询当前时间的前3分钟数据</B><BR>
*
* @author:lihaiyi
* @cretetime:2018年8月14日 上午8:56:08
* @param time
* @return List<Station>
*/
List<Station> findAllByTime(Long time);
/** 默认库 */
Station findByOne(String id);
/** 第一 **/
Boolean update1(Station s);
Station findByOne1(String id);
/** 第二 **/
Boolean update2(Station s);
Station findByOne2(String id);
/** 第三 **/
Boolean update3(Station s);
Station findByOne3(String id);
/** 4 **/
Boolean update4(Station s);
Station findByOne4(String id);
/** 第5 **/
Boolean update5(Station s);
Station findByOne5(String id);
/** 第6 **/
Boolean update6(Station s);
Station findByOne6(String id);
/** 第7 **/
Boolean update7(Station s);
Station findByOne7(String id);
/** 第8 **/
Boolean update8(Station s);
Station findByOne8(String id);
/** 第9 **/
Boolean update9(Station s);
Station findByOne9(String id);
/** 第10 **/
Boolean update10(Station s);
Station findByOne10(String id);
/** 第11 **/
Boolean update11(Station s);
Station findByOne11(String id);
/** 第12 **/
Boolean update12(Station s);
Station findByOne12(String id);
/** 第13 **/
Boolean update13(Station s);
Station findByOne13(String id);
/** 第14 **/
Boolean update14(Station s);
Station findByOne14(String id);
/** 第15 **/
Boolean update15(Station s);
Station findByOne15(String id);
/** 第16 **/
Boolean update16(Station s);
Station findByOne16(String id);
/** 第17 **/
Boolean update17(Station s);
Station findByOne17(String id);
/** 第18 **/
Boolean update18(Station s);
Station findByOne18(String id);
/** 第19 **/
Boolean update19(Station s);
Station findByOne19(String id);
/** 第20 **/
Boolean update20(Station s);
Station findByOne20(String id);
/** 第21 **/
Boolean update21(Station s);
Station findByOne21(String id);
/** 第22 **/
Boolean update22(Station s);
Station findByOne22(String id);
/** 第23 **/
Boolean update23(Station s);
Station findByOne23(String id);
}
|
Java
|
UTF-8
| 18,108 | 1.820313 | 2 |
[] |
no_license
|
package minecrafttransportsimulator.items.instances;
import java.util.Iterator;
import java.util.List;
import minecrafttransportsimulator.baseclasses.BoundingBox;
import minecrafttransportsimulator.baseclasses.Point3d;
import minecrafttransportsimulator.blocks.components.ABlockBase.Axis;
import minecrafttransportsimulator.blocks.tileentities.components.ATileEntityBase;
import minecrafttransportsimulator.blocks.tileentities.instances.TileEntityDecor;
import minecrafttransportsimulator.blocks.tileentities.instances.TileEntityPole;
import minecrafttransportsimulator.entities.components.AEntityA_Base;
import minecrafttransportsimulator.entities.components.AEntityD_Interactable.PlayerOwnerState;
import minecrafttransportsimulator.entities.instances.APart;
import minecrafttransportsimulator.entities.instances.EntityVehicleF_Physics;
import minecrafttransportsimulator.entities.instances.PartEngine;
import minecrafttransportsimulator.entities.instances.PartInteractable;
import minecrafttransportsimulator.entities.instances.PartSeat;
import minecrafttransportsimulator.items.components.AItemPack;
import minecrafttransportsimulator.items.components.AItemPart;
import minecrafttransportsimulator.items.components.IItemFood;
import minecrafttransportsimulator.items.components.IItemVehicleInteractable;
import minecrafttransportsimulator.jsondefs.JSONItem;
import minecrafttransportsimulator.jsondefs.JSONPotionEffect;
import minecrafttransportsimulator.mcinterface.WrapperEntity;
import minecrafttransportsimulator.mcinterface.WrapperNBT;
import minecrafttransportsimulator.mcinterface.WrapperPlayer;
import minecrafttransportsimulator.mcinterface.WrapperWorld;
import minecrafttransportsimulator.packets.components.InterfacePacket;
import minecrafttransportsimulator.packets.instances.PacketEntityGUIRequest;
import minecrafttransportsimulator.packets.instances.PacketEntityVariableToggle;
import minecrafttransportsimulator.packets.instances.PacketGUIRequest;
import minecrafttransportsimulator.packets.instances.PacketPartEngine;
import minecrafttransportsimulator.packets.instances.PacketPartEngine.Signal;
import minecrafttransportsimulator.packets.instances.PacketPartInteractable;
import minecrafttransportsimulator.packets.instances.PacketPlayerChatMessage;
import minecrafttransportsimulator.packets.instances.PacketVehicleControlAnalog;
import minecrafttransportsimulator.packloading.JSONParser.JSONDescription;
import minecrafttransportsimulator.systems.ConfigSystem;
import net.minecraft.item.ItemStack;
public class ItemItem extends AItemPack<JSONItem> implements IItemVehicleInteractable, IItemFood{
/*Current page of this item, if it's a booklet. Kept here locally as only one item class is constructed for each booklet definition.*/
public int pageNumber;
/*First engine clicked for jumper cable items. Kept here locally as only one item class is constructed for each jumper cable definition.*/
private static PartEngine firstEngineClicked;
/*First part clicked for fuel hose items. Kept here locally as only one item class is constructed for each jumper cable definition.*/
private static PartInteractable firstPartClicked;
public ItemItem(JSONItem definition){
super(definition, null);
}
@Override
public boolean canBreakBlocks(){
return !definition.item.type.equals(ItemComponentType.WRENCH);
}
@Override
public CallbackType doVehicleInteraction(EntityVehicleF_Physics vehicle, APart part, WrapperPlayer player, PlayerOwnerState ownerState, boolean rightClick){
switch(definition.item.type){
case WRENCH : {
if(!vehicle.world.isClient()){
//If the player isn't the owner of the vehicle, they can't interact with it.
if(!ownerState.equals(PlayerOwnerState.USER)){
if(rightClick){
if(ConfigSystem.configObject.clientControls.devMode.value && vehicle.equals(player.getEntityRiding())){
player.sendPacket(new PacketEntityGUIRequest(vehicle, player, PacketEntityGUIRequest.EntityGUIType.PACK_EXPORTER));
}else if(player.isSneaking()){
player.sendPacket(new PacketEntityGUIRequest(vehicle, player, PacketEntityGUIRequest.EntityGUIType.TEXT_EDITOR));
}else{
player.sendPacket(new PacketEntityGUIRequest(vehicle, player, PacketEntityGUIRequest.EntityGUIType.INSTRUMENTS));
}
}else if(!vehicle.world.isClient()){
if(part != null && !player.isSneaking() && !part.placementDefinition.isPermanent && part.isValid){
//Player can remove part, spawn item in the world and remove part.
//Make sure to remove the part before spawning the item. Some parts
//care about this order and won't spawn items unless they've been removed.
part.disconnectAllConnections();
vehicle.removePart(part, null);
AItemPart droppedItem = part.getItem();
if(droppedItem != null){
WrapperNBT partData = new WrapperNBT();
part.save(partData);
vehicle.world.spawnItem(droppedItem, partData, part.position);
}
}else if(player.isSneaking()){
//Attacker is a sneaking player with a wrench.
//Remove this vehicle if possible.
if((!ConfigSystem.configObject.general.opPickupVehiclesOnly.value || ownerState.equals(PlayerOwnerState.ADMIN)) && (!ConfigSystem.configObject.general.creativePickupVehiclesOnly.value || player.isCreative()) && vehicle.isValid){
vehicle.disconnectAllConnections();
for(APart vehiclePart : vehicle.parts){
vehiclePart.disconnectAllConnections();
}
ItemVehicle vehicleItem = vehicle.getItem();
WrapperNBT vehicleData = new WrapperNBT();
vehicle.save(vehicleData);
vehicle.world.spawnItem(vehicleItem, vehicleData, vehicle.position);
vehicle.remove();
}
}
}
}else{
player.sendPacket(new PacketPlayerChatMessage(player, "interact.failure.vehicleowned"));
}
}
return CallbackType.NONE;
}
case PAINT_GUN : {
if(!vehicle.world.isClient() && rightClick){
//If the player isn't the owner of the vehicle, they can't interact with it.
if(!ownerState.equals(PlayerOwnerState.USER)){
if(part != null){
player.sendPacket(new PacketEntityGUIRequest(part, player, PacketEntityGUIRequest.EntityGUIType.PAINT_GUN));
}else{
player.sendPacket(new PacketEntityGUIRequest(vehicle, player, PacketEntityGUIRequest.EntityGUIType.PAINT_GUN));
}
}else{
player.sendPacket(new PacketPlayerChatMessage(player, "interact.failure.vehicleowned"));
}
}
return CallbackType.NONE;
}
case KEY : {
if(!vehicle.world.isClient() && rightClick){
if(player.isSneaking()){
//Try to change ownership of the vehicle.
if(vehicle.ownerUUID.isEmpty()){
vehicle.ownerUUID = player.getID();
player.sendPacket(new PacketPlayerChatMessage(player, "interact.key.info.own"));
}else{
if(!ownerState.equals(PlayerOwnerState.USER)){
vehicle.ownerUUID = "";
player.sendPacket(new PacketPlayerChatMessage(player, "interact.key.info.unown"));
}else{
player.sendPacket(new PacketPlayerChatMessage(player, "interact.key.failure.alreadyowned"));
}
}
}else{
//Try to lock the vehicle.
//First check to see if we need to set this key's vehicle.
ItemStack stack = player.getHeldStack();
WrapperNBT data = new WrapperNBT(stack);
String keyVehicleUUID = data.getString("vehicle");
if(keyVehicleUUID.isEmpty()){
//Check if we are the owner before making this a valid key.
if(!vehicle.ownerUUID.isEmpty() && ownerState.equals(PlayerOwnerState.USER)){
player.sendPacket(new PacketPlayerChatMessage(player, "interact.key.failure.notowner"));
return CallbackType.NONE;
}
keyVehicleUUID = vehicle.uniqueUUID;
data.setString("vehicle", keyVehicleUUID);
stack.setTagCompound(data.tag);
}
//Try to lock or unlock this vehicle.
//If we succeed, send callback to clients to change locked state.
if(!keyVehicleUUID.equals(vehicle.uniqueUUID)){
player.sendPacket(new PacketPlayerChatMessage(player, "interact.key.failure.wrongkey"));
}else{
if(vehicle.locked){
vehicle.locked = false;
player.sendPacket(new PacketPlayerChatMessage(player, "interact.key.info.unlock"));
//If we aren't in this vehicle, and we clicked a seat, start riding the vehicle.
if(part instanceof PartSeat && player.getEntityRiding() == null){
part.interact(player);
}
}else{
vehicle.locked = true;
player.sendPacket(new PacketPlayerChatMessage(player, "interact.key.info.lock"));
}
return CallbackType.ALL;
}
}
}else{
vehicle.locked = !vehicle.locked;
}
return CallbackType.NONE;
}
case TICKET : {
if(!vehicle.world.isClient() && rightClick){
if(player.isSneaking()){
Iterator<WrapperEntity> iterator = vehicle.locationRiderMap.inverse().keySet().iterator();
while(iterator.hasNext()){
WrapperEntity entity = iterator.next();
if(!(entity instanceof WrapperPlayer)){
vehicle.removeRider(entity, iterator);
}
}
}else{
vehicle.world.loadEntities(new BoundingBox(player.getPosition(), 8D, 8D, 8D), vehicle);
}
}
return CallbackType.NONE;
}
case FUEL_HOSE : {
if(!vehicle.world.isClient() && rightClick){
if(firstPartClicked == null){
if(part instanceof PartInteractable){
PartInteractable interactable = (PartInteractable) part;
if(interactable.tank != null){
if(interactable.linkedPart == null && interactable.linkedVehicle == null){
firstPartClicked = interactable;
player.sendPacket(new PacketPlayerChatMessage(player, "interact.fuelhose.firstlink"));
}else{
player.sendPacket(new PacketPlayerChatMessage(player, "interact.fuelhose.alreadylinked"));
}
}
}
}else{
if(part instanceof PartInteractable){
PartInteractable interactable = (PartInteractable) part;
if(interactable.tank != null && !interactable.equals(firstPartClicked)){
if(interactable.linkedPart == null && interactable.linkedVehicle == null){
if(part.position.distanceTo(firstPartClicked.position) < 15){
if(interactable.tank.getFluid().isEmpty() || firstPartClicked.tank.getFluid().isEmpty() || interactable.tank.getFluid().equals(firstPartClicked.tank.getFluid())){
firstPartClicked.linkedPart = interactable;
InterfacePacket.sendToAllClients(new PacketPartInteractable(firstPartClicked, player));
player.sendPacket(new PacketPlayerChatMessage(player, "interact.fuelhose.secondlink"));
firstPartClicked = null;
}else{
firstPartClicked = null;
player.sendPacket(new PacketPlayerChatMessage(player, "interact.fuelhose.differentfluids"));
}
}else{
firstPartClicked = null;
player.sendPacket(new PacketPlayerChatMessage(player, "interact.fuelhose.toofar"));
}
}else{
firstPartClicked = null;
player.sendPacket(new PacketPlayerChatMessage(player, "interact.fuelhose.alreadylinked"));
}
}
}else if(part == null){
if(vehicle.position.distanceTo(firstPartClicked.position) < 15){
if(vehicle.fuelTank.getFluid().isEmpty() || firstPartClicked.tank.getFluid().isEmpty() || vehicle.fuelTank.getFluid().equals(firstPartClicked.tank.getFluid())){
firstPartClicked.linkedVehicle = vehicle;
InterfacePacket.sendToAllClients(new PacketPartInteractable(firstPartClicked, player));
player.sendPacket(new PacketPlayerChatMessage(player, "interact.fuelhose.secondlink"));
firstPartClicked = null;
}else{
firstPartClicked = null;
player.sendPacket(new PacketPlayerChatMessage(player, "interact.fuelhose.differentfluids"));
}
}else{
firstPartClicked = null;
player.sendPacket(new PacketPlayerChatMessage(player, "interact.fuelhose.toofar"));
}
}
}
}
return CallbackType.NONE;
}
case JUMPER_CABLES : {
if(!vehicle.world.isClient() && rightClick){
if(part instanceof PartEngine){
PartEngine engine = (PartEngine) part;
if(engine.linkedEngine == null){
if(firstEngineClicked == null){
firstEngineClicked = engine;
player.sendPacket(new PacketPlayerChatMessage(player, "interact.jumpercable.firstlink"));
}else if(!firstEngineClicked.equals(engine)){
if(firstEngineClicked.entityOn.equals(engine.entityOn)){
firstEngineClicked = null;
player.sendPacket(new PacketPlayerChatMessage(player, "interact.jumpercable.samevehicle"));
}else if(engine.position.distanceTo(firstEngineClicked.position) < 15){
engine.linkedEngine = firstEngineClicked;
firstEngineClicked.linkedEngine = engine;
InterfacePacket.sendToAllClients(new PacketPartEngine(engine, firstEngineClicked));
InterfacePacket.sendToAllClients(new PacketPartEngine(firstEngineClicked, engine));
firstEngineClicked = null;
player.sendPacket(new PacketPlayerChatMessage(player, "interact.jumpercable.secondlink"));
}else{
firstEngineClicked = null;
player.sendPacket(new PacketPlayerChatMessage(player, "interact.jumpercable.toofar"));
}
}
}else{
player.sendPacket(new PacketPlayerChatMessage(player, "interact.jumpercable.alreadylinked"));
}
}
}
return CallbackType.NONE;
}
case JUMPER_PACK : {
if(rightClick){
//Use jumper on vehicle.
vehicle.electricPower = 12;
if(!vehicle.world.isClient()){
InterfacePacket.sendToPlayer(new PacketPlayerChatMessage(player, "interact.jumperpack.success"), player);
if(!player.isCreative()){
player.getInventory().removeStack(player.getHeldStack(), 1);
}
return CallbackType.ALL;
}
}
return CallbackType.NONE;
}
default : return CallbackType.SKIP;
}
}
@Override
public boolean onBlockClicked(WrapperWorld world, WrapperPlayer player, Point3d position, Axis axis){
if(definition.item.type.equals(ItemComponentType.PAINT_GUN)){
if(!world.isClient()){
ATileEntityBase<?> tile = world.getTileEntity(position);
if(tile instanceof TileEntityDecor){
player.sendPacket(new PacketEntityGUIRequest(tile, player, PacketEntityGUIRequest.EntityGUIType.PAINT_GUN));
return true;
}else if(tile instanceof TileEntityPole){
TileEntityPole pole = (TileEntityPole) tile;
//Change the axis to match the 8-dim axis for poles. Blocks only get a 4-dim axis.
axis = Axis.getFromRotation(player.getYaw(), pole.definition.pole.allowsDiagonals).getOpposite();
if(pole.components.containsKey(axis)){
player.sendPacket(new PacketEntityGUIRequest(pole.components.get(axis), player, PacketEntityGUIRequest.EntityGUIType.PAINT_GUN));
}
return true;
}
}
}
return false;
}
@Override
public boolean onUsed(WrapperWorld world, WrapperPlayer player){
if(definition.item.type.equals(ItemComponentType.BOOKLET)){
if(!world.isClient()){
player.sendPacket(new PacketGUIRequest(player, PacketGUIRequest.GUIType.BOOKELET));
}
}else if(definition.item.type.equals(ItemComponentType.Y2K_BUTTON)){
if(!world.isClient() && player.isOP()){
for(AEntityA_Base entity : AEntityA_Base.getEntities(world)){
if(entity instanceof EntityVehicleF_Physics){
EntityVehicleF_Physics vehicle = (EntityVehicleF_Physics) entity;
vehicle.throttle = 0;
InterfacePacket.sendToAllClients(new PacketVehicleControlAnalog(vehicle, PacketVehicleControlAnalog.Controls.THROTTLE, (short) 0, (byte) 0));
if(!vehicle.parkingBrakeOn){
vehicle.variablesOn.add(EntityVehicleF_Physics.PARKINGBRAKE_VARIABLE);
InterfacePacket.sendToAllClients(new PacketEntityVariableToggle(vehicle, EntityVehicleF_Physics.PARKINGBRAKE_VARIABLE));
}
for(PartEngine engine : vehicle.engines.values()){
engine.setMagnetoStatus(false);
InterfacePacket.sendToAllClients(new PacketPartEngine(engine, Signal.MAGNETO_OFF));
}
for(String variable : vehicle.variablesOn){
InterfacePacket.sendToAllClients(new PacketEntityVariableToggle(vehicle, variable));
}
}
}
}
}
return true;
}
@Override
public int getTimeToEat(){
return definition.item.type.equals(ItemComponentType.FOOD) ? definition.food.timeToEat : 0;
}
@Override
public boolean isDrink(){
return definition.food.isDrink;
}
@Override
public int getHungerAmount(){
return definition.food.hungerAmount;
}
@Override
public float getSaturationAmount(){
return definition.food.saturationAmount;
}
@Override
public List<JSONPotionEffect> getEffects(){
return definition.food.effects;
}
public static enum ItemComponentType{
@JSONDescription("Creates an item with no functionality.")
NONE,
@JSONDescription("Creates a booklet, which is a book-like item.")
BOOKLET,
@JSONDescription("Creates an item that can be eaten.")
FOOD,
@JSONDescription("Creates an item that can be used as a weapon.")
WEAPON,
@JSONDescription("Creates an item that works as a part scanner.")
SCANNER,
@JSONDescription("Creates an item that works as a wrench.")
WRENCH,
@JSONDescription("Creates an item that works as a paint gun.")
PAINT_GUN,
@JSONDescription("Creates an item that works as a key.")
KEY,
@JSONDescription("Creates an item that works as a ticket.")
TICKET,
@JSONDescription("Creates an item that works as a fuel hose.")
FUEL_HOSE,
@JSONDescription("Creates an item that works as jumper cables.")
JUMPER_CABLES,
@JSONDescription("Creates an item that works as a jumper pack.")
JUMPER_PACK,
@JSONDescription("Creates an item that works as a Y2K button.")
Y2K_BUTTON;
}
}
|
Python
|
UTF-8
| 1,390 | 3.171875 | 3 |
[] |
no_license
|
"""Dojo Model
Usage:
andela.py create_office <room_names>
andela.py create_livingspace <room_names>
andela.py add_fellow <name>
andela.py add_staff <name>
andela.py print_office <room>
andela.py print_livingspace <room>
py andela.py -h | --help
Examples:
python andela.py create_office Nairobi
python andela.py create_livingspace kigali
python andela.py add_fellow musa
python andela.py add_staff kim
python andela.py print_office blue
python andela.py print_livingspace red
Options:
-h, --help Show this screen and exit.
"""
import methods
from docopt import docopt
if __name__ == '__main__':
arguments = docopt(__doc__)
if arguments['create_office']:
office = arguments['<room_names>']
methods.create_office(office)
elif arguments['create_livingspace']:
livingspace = arguments['<room_names>']
methods.livingspace(livingspace)
elif arguments['add_fellow']:
fellow = arguments['<name>']
methods.add_felllow(fellow)
elif arguments['add_staff']:
staff = arguments['<name>']
methods.add_staff(staff)
elif arguments['print_office']:
room = arguments['<room>']
methods.print_office(room)
elif arguments['print_livingspace']:
room = arguments['<room>']
methods.living(room)
|
Python
|
UTF-8
| 414 | 3.09375 | 3 |
[
"MIT"
] |
permissive
|
# best solution
# https://leetcode.com/problems/contains-duplicate-ii/discuss/61375/Python-concise-solution-with-dictionary.
class Solution:
def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
dct = {}
for i, num in enumerate(nums):
if num in dct and i - dct[num] <= k:
return True
dic[num] = i
return False
|
C++
|
UTF-8
| 1,811 | 2.6875 | 3 |
[] |
no_license
|
#pragma once
namespace dae
{
void SetColor( const Color4f& color );
void DrawPoint( float x, float y, float pointSize = 1.0f );
void DrawPoint( const Point2f & p, float pointSize = 1.0f );
void DrawPoints( Point2f *pVertices, int nrVertices, float pointSize = 1.0f );
void DrawLine( float x1, float y1, float x2, float y2, float lineWidth = 1.0f );
void DrawLine( const Point2f & p1, const Point2f & p2, float lineWidth = 1.0f );
void DrawRect(float left, float bottom, float width, float height, float lineWidth = 1.0f);
void DrawRect(const Point2f & bottomLeft, float width, float height, float lineWidth = 1.0f);
void DrawRect(const Rectf & rect, float lineWidth = 1.0f);
void FillRect(float left, float bottom, float width, float height);
void FillRect(const Point2f & bottomLeft, float width, float height);
void FillRect(const Rectf & rect);
void DrawEllipse(float centerX, float centerY, float radX, float radY, float lineWidth = 1.0f);
void DrawEllipse(const Point2f & center, float radX, float radY, float lineWidth = 1.0f);
void FillEllipse(float centerX, float centerY, float radX, float radY);
void FillEllipse(const Point2f & center, float radX, float radY);
void DrawArc( float centerX, float centerY, float radX, float radY, float fromAngle, float tillAngle, float lineWidth = 1.0f );
void DrawArc( const Point2f & center, float radX, float radY, float fromAngle, float tillAngle, float lineWidth = 1.0f );
void FillArc( float centerX, float centerY, float radX, float radY, float fromAngle, float tillAngle );
void FillArc( const Point2f & center, float radX, float radY, float fromAngle, float tillAngle );
void DrawPolygon( Point2f *pVertices, int nrVertices, bool closed = true, float lineWidth = 1.0f );
void FillPolygon( Point2f *pVertices, int nrVertices);
}
|
Java
|
UTF-8
| 282 | 1.609375 | 2 |
[] |
no_license
|
package ru.ppr.cppk.ui.activity.pdrepeal.poscancel;
import ru.ppr.core.ui.mvp.view.MvpView;
/**
* @author Aleksandr Brazhkin
*/
interface PosCancelView extends MvpView {
void showConnectingState(long timeout);
void showConnectionTimeoutState();
void showConnectedState();
}
|
Markdown
|
UTF-8
| 6,860 | 2.6875 | 3 |
[] |
no_license
|
---
description: "Recipe of Award-winning Potato and Mentaiko Mayo Stir Fry"
title: "Recipe of Award-winning Potato and Mentaiko Mayo Stir Fry"
slug: 512-recipe-of-award-winning-potato-and-mentaiko-mayo-stir-fry
date: 2020-08-15T11:03:07.842Z
image: https://img-global.cpcdn.com/recipes/5543121229185024/751x532cq70/potato-and-mentaiko-mayo-stir-fry-recipe-main-photo.jpg
thumbnail: https://img-global.cpcdn.com/recipes/5543121229185024/751x532cq70/potato-and-mentaiko-mayo-stir-fry-recipe-main-photo.jpg
cover: https://img-global.cpcdn.com/recipes/5543121229185024/751x532cq70/potato-and-mentaiko-mayo-stir-fry-recipe-main-photo.jpg
author: Emily Simon
ratingvalue: 5
reviewcount: 25151
recipeingredient:
- "2 Potatoes"
- "1/2 of a pair Mentaiko saltcured spicy pollack or cod roe"
- "2 tbsp Mayonnaise"
- "1 tbsp Olive oil"
- "1 Lemon juice"
- "1 dash for garnish Daikon radish sprouts"
recipeinstructions:
- "Slice the potatoes into fine julienne, put into a bowl and rinse. When all the surface starch has gone and the water is clear, drain well."
- "Microwave the shredded and soaked potato for 2 to 3 minutes. (Cover with plastic wrap beforehand.)"
- "Take the mentaiko out of the membrane, and combine with the mayonnaise! The ratio is 1: 1."
- "Heat the olive oil in a frying pan and stir fry the drained potato."
- "When the potato is transparent, add the combined sauce from Step 3 and mix well. (Lower the heat before mixing.)"
- "When the sauce is evenly distributed, add the lemon juice."
- "Finished. Transfer to serving plates, and sprinkle on top with daikon radish sprouts or chopped green onions as garnish to make it look pretty."
categories:
- Recipe
tags:
- potato
- and
- mentaiko
katakunci: potato and mentaiko
nutrition: 287 calories
recipecuisine: American
preptime: "PT30M"
cooktime: "PT39M"
recipeyield: "3"
recipecategory: Dinner
---

Hello everybody, I hope you are having an incredible day today. Today, I will show you a way to make a special dish, potato and mentaiko mayo stir fry. One of my favorites. This time, I'm gonna make it a little bit tasty. This is gonna smell and look delicious.
Potato and Mentaiko Mayo Stir Fry is one of the most popular of recent trending foods on earth. It's appreciated by millions daily. It is easy, it is fast, it tastes yummy. They're fine and they look wonderful. Potato and Mentaiko Mayo Stir Fry is something which I've loved my whole life.
To begin with this particular recipe, we have to prepare a few components. You can cook potato and mentaiko mayo stir fry using 6 ingredients and 7 steps. Here is how you can achieve it.
<!--inarticleads1-->
##### The ingredients needed to make Potato and Mentaiko Mayo Stir Fry:
1. Make ready 2 Potatoes
1. Make ready 1/2 of a pair Mentaiko (salt-cured spicy pollack or cod roe)
1. Make ready 2 tbsp Mayonnaise
1. Take 1 tbsp Olive oil
1. Get 1 Lemon juice
1. Make ready 1 dash for garnish Daikon radish sprouts
<!--inarticleads2-->
##### Instructions to make Potato and Mentaiko Mayo Stir Fry:
1. Slice the potatoes into fine julienne, put into a bowl and rinse. When all the surface starch has gone and the water is clear, drain well.
1. Microwave the shredded and soaked potato for 2 to 3 minutes. (Cover with plastic wrap beforehand.)
1. Take the mentaiko out of the membrane, and combine with the mayonnaise! The ratio is 1: 1.
1. Heat the olive oil in a frying pan and stir fry the drained potato.
1. When the potato is transparent, add the combined sauce from Step 3 and mix well. (Lower the heat before mixing.)
1. When the sauce is evenly distributed, add the lemon juice.
1. Finished. Transfer to serving plates, and sprinkle on top with daikon radish sprouts or chopped green onions as garnish to make it look pretty.
Discover How to Boost Your Mood with Food
Many of us think that comfort foods are bad for us and that we ought to keep away from them. But if your comfort food is candy or junk food this holds true. Soemtimes, comfort foods can be utterly nutritious and good for us to consume. There are several foods that, when you consume them, could improve your mood. When you are feeling a little down and are needing an emotional pick-me-up, try a couple of these.
Eggs, believe it or not, are terrific for helping you fight depression. You should see to it, however, that what you make includes the egg yolk. The egg yolk is the part of the egg that matters most in terms of helping you cheer up. Eggs, the yolk especially, are rich in B vitamins. These B vitamins are wonderful for helping to raise your mood. This is because they increase the function of your brain's neural transmitters (the parts of the brain that affect how you feel). Try eating an egg and cheer up!
Put together a trail mixout of different seeds and nuts. Peanuts, cashews, sunflower seeds, almonds, pumpkin seeds, and so on are all terrific for helping to boost your mood. This is possible because these foods have a bunch of magnesium which boosts your production of serotonin. Serotonin is a feel-good chemical substance that tells the brain how to feel at any given point in time. The more serotonin you have, the happier you are going to feel. Not only that, nuts, specifically, are a terrific source of protein.
Cold water fish are excellent if you want to feel happier. Cold water fish including tuna, trout and wild salmon are high in DHA and omega-3 fatty acids. These are two substances that boost the quality and function of the grey matter in your brain. It's true: chomping on a tuna fish sandwich can really help you overcome depression.
Some grains are really wonderful for repelling bad moods. Quinoa, millet, teff and barley are all really wonderful for helping boost your happiness levels. These grains fill you up better and that can help you with your moods as well. It's not difficult to feel depressed when you are starving! These grains can help your mood elevate since it's easy for your body to digest them. You digest these grains more quickly than other foods which can help increase your blood sugar levels, which, in turn, helps make you feel better, mood wise.
Green tea is actually great for your mood. You were just waiting to read that here, weren't you? Green tea is loaded with an amino acid called L-theanine. Studies show that this specific amino acid can actually stimulate brain waves. This will better your brain's focus while also loosening up the rest of your body. You probably already knew it is not difficult to be healthy when you consume green tea. Now you know that applies to your mood as well!
So you see, you don't need to eat all that junk food when you want to feel better! Test out these tips instead!
|
Java
|
UTF-8
| 292 | 1.796875 | 2 |
[] |
no_license
|
package org.gradle.test.performance49_3;
import static org.junit.Assert.*;
public class Test49_248 {
private final Production49_248 production = new Production49_248("value");
@org.junit.Test
public void test() {
assertEquals(production.getProperty(), "value");
}
}
|
Markdown
|
UTF-8
| 4,187 | 3.390625 | 3 |
[] |
no_license
|
---
title: 显式锁
date: 2017-8-29
categories:
- Java
tags:
- java
- 多线程
- 读书笔记
---
# 显式锁
## Lock与ReentrantLock
```java
public interface Lock {
void lock();
void lockInterruptibly() throws InterruptedException;
boolean tryLock();
boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException;
void unlock;
Condition newCondition();
}
```
与内置加锁机制不同,Lock提供了一种无条件的、可轮询的、定时的以及可中断的锁获取操作,所有加锁和解锁的方法都是显式的。
Lock的标准使用形式:
```java
Lock lock = new ReentrantLock();
...
lock.lock();
try {
// 更新对象状态
// 捕获异常,并在必要时恢复不变性条件
} finally {
lock.unlock();
}
```
**必须在finally块中释放锁,否则相当于启动了一个定时炸弹。**
### 轮询锁与定时锁
与无条件的锁获取模式相比,可定时的、可轮询的锁获取模式具有更完善的错误恢复机制,来避免死锁。
如果不能获得所有需要的锁,那么可以使用定时的或可轮询的锁获取方式,从而使你重新获得控制权,它会释放已经获得的锁,然后重新尝试获取所有锁。
```java
public boolean transferMoney(Account from, Account to
DollarAmount amount, long timeout, Timeunit unit) {
while(true) {
if (from.lock.tryLock()) {
try {
if (to.lock.tryLock()) {
try {
return transfer(from, to, amount);
} finally {
to.lock.unlock();
}
}
} finally {
from.lock.unlock();
}
}
if (retry too many times) {
return false;
}
Thread.sleep(random time);
}
}
```
在实现具有时间限制的操作时,定时锁非常有用。当时用内置锁时,在开始请求锁后,这个操作将无法取消。可使用`tryLock(timeout, timeunit)`方法来实现。
### 可中断的锁获取操作
请求内置锁时,无法响应中断。这些不可中断的阻塞机制,将使得实现可取消任务变得复杂。`lockInterruptibly()`方法能够在获得锁的同时保持对中断的响应。
### 非块结构的加锁
连锁式加锁Hand-Over-Hand Locking
锁耦合Lock Coupling
## 性能考虑因素
> 性能是个不断变化的指标,如果昨天的测试基准中发现X比Y快,那么在今天就可能已经过时了。
## 公平性
非公平的锁允许插队:当一个线程请求非公平锁时,如何在发出请求的同时该锁的状态可用,那么这个线程将跳过队列中所有的等待线程,并获得这个锁。
非公平锁的性能高于公平锁。公平性将由于挂起线程和恢复线程时存在的开销而极大降低性能,实际情况下,统计上的公平性保证————确保被阻塞的线程能最终获得锁,已经够用了,并且开销小得多。
在持有锁的时间相对较长,或者请求锁的平均时间间隔较长,那么应该使用公平锁。这种情况下,插队带来的吞吐量提升则可能不会出现。
与默认ReentrantLock一样,内置锁不会提供确定的公平性保证,大多数情况下,实现统计上的公平性保证就已经足够了。
## 在synchronized和ReentrantLock之间进行选择
> 在内置锁无法满足需求的情况下,ReentrantLock可作为一种高级工具,如可定时的、可轮询的、可中断的锁获取操作,公平队列,以及非块结构的锁,才是用ReentrantLock。否则还是优先使用synchronized。
## 读写锁
如果能够放宽互斥的加锁策略,允许多个执行读操作的线程同时访问数据,那么将提升程序的性能。
ReentrantReadWriteLock在构造时,可选择非公平(默认)还是公平锁。写线程降级为读线程是可以的,但从读线程升级为写线程则不可以(会导致死锁)。
当锁的持有时间较长,且大部分操作都不会修改被守护的资源时,那么读写锁能提供并发性。
|
Java
|
UTF-8
| 10,398 | 2.109375 | 2 |
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package views;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import models.Paciente;
/**
*
* @author Jessele Durán
*/
public class PacienteRegisterView extends javax.swing.JFrame {
/**
* Creates new form AdminRegisterView
*/
public PacienteRegisterView() {
super("Registrar Paciente");
initComponents();
restringirTeclas();
setDefaultCloseOperation(DISPOSE_ON_CLOSE);
}
/**
* This method is called from within the constructor to initialize the form.
* WARNING: Do NOT modify this code. The content of this method is always
* regenerated by the Form Editor.
*/
@SuppressWarnings("unchecked")
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
jLabel2 = new javax.swing.JLabel();
jLabel1 = new javax.swing.JLabel();
registrarButton = new javax.swing.JButton();
cancelarButton = new javax.swing.JButton();
nameField = new javax.swing.JTextField();
jLabel3 = new javax.swing.JLabel();
apellidoField = new javax.swing.JTextField();
jLabel5 = new javax.swing.JLabel();
telefonoField = new javax.swing.JTextField();
ciField = new javax.swing.JTextField();
jLabel6 = new javax.swing.JLabel();
setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
jLabel2.setFont(new java.awt.Font("Roboto", 0, 14)); // NOI18N
jLabel2.setText("Apellido");
jLabel1.setFont(new java.awt.Font("Roboto", 0, 14)); // NOI18N
jLabel1.setText("Nombre");
registrarButton.setFont(new java.awt.Font("Roboto", 0, 14)); // NOI18N
registrarButton.setText("Registrar");
registrarButton.setActionCommand("RegistrarPaciente");
cancelarButton.setFont(new java.awt.Font("Roboto", 0, 14)); // NOI18N
cancelarButton.setText("Cancelar");
cancelarButton.setActionCommand("CancelarPaciente");
nameField.setFont(new java.awt.Font("Roboto", 0, 14)); // NOI18N
jLabel3.setFont(new java.awt.Font("Roboto", 0, 24)); // NOI18N
jLabel3.setText("Registrar Paciente");
apellidoField.setFont(new java.awt.Font("Roboto", 0, 14)); // NOI18N
apellidoField.addActionListener(new java.awt.event.ActionListener() {
public void actionPerformed(java.awt.event.ActionEvent evt) {
apellidoFieldActionPerformed(evt);
}
});
jLabel5.setFont(new java.awt.Font("Roboto", 0, 14)); // NOI18N
jLabel5.setText("Teléfono");
telefonoField.setFont(new java.awt.Font("Roboto", 0, 14)); // NOI18N
ciField.setFont(new java.awt.Font("Roboto", 0, 14)); // NOI18N
jLabel6.setFont(new java.awt.Font("Roboto", 0, 14)); // NOI18N
jLabel6.setText("Cédula");
javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
getContentPane().setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addGap(73, 73, 73)
.addComponent(jLabel3))
.addGroup(layout.createSequentialGroup()
.addGap(28, 28, 28)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(ciField, javax.swing.GroupLayout.PREFERRED_SIZE, 289, javax.swing.GroupLayout.PREFERRED_SIZE))
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGroup(layout.createSequentialGroup()
.addGap(10, 10, 10)
.addComponent(cancelarButton, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(registrarButton, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE))
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 138, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(nameField, javax.swing.GroupLayout.DEFAULT_SIZE, 289, Short.MAX_VALUE)
.addComponent(apellidoField)
.addComponent(telefonoField, javax.swing.GroupLayout.DEFAULT_SIZE, 289, Short.MAX_VALUE)))))
.addContainerGap(25, Short.MAX_VALUE))
);
layout.setVerticalGroup(
layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addComponent(jLabel3)
.addGap(18, 18, 18)
.addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(nameField, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
.addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(1, 1, 1)
.addComponent(apellidoField, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(18, 18, 18)
.addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(ciField, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
.addGap(14, 14, 14)
.addComponent(jLabel5, javax.swing.GroupLayout.PREFERRED_SIZE, 19, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
.addComponent(telefonoField, javax.swing.GroupLayout.PREFERRED_SIZE, 32, javax.swing.GroupLayout.PREFERRED_SIZE)
.addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 21, Short.MAX_VALUE)
.addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
.addComponent(cancelarButton, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)
.addComponent(registrarButton, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE))
.addContainerGap())
);
pack();
}// </editor-fold>//GEN-END:initComponents
private void apellidoFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_apellidoFieldActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_apellidoFieldActionPerformed
// Variables declaration - do not modify//GEN-BEGIN:variables
public javax.swing.JTextField apellidoField;
public javax.swing.JButton cancelarButton;
public javax.swing.JTextField ciField;
private javax.swing.JLabel jLabel1;
private javax.swing.JLabel jLabel2;
private javax.swing.JLabel jLabel3;
private javax.swing.JLabel jLabel5;
private javax.swing.JLabel jLabel6;
public javax.swing.JTextField nameField;
public javax.swing.JButton registrarButton;
public javax.swing.JTextField telefonoField;
// End of variables declaration//GEN-END:variables
public KeyListener eventosDeTeclaOnlyLetters;
public KeyListener eventosDeTecla;
private void restringirTeclas() {
eventosDeTeclaOnlyLetters = new KeyListener() {
@Override
public void keyTyped(KeyEvent ke) {
char caracter = ke.getKeyChar();
if ((Character.isLetter(caracter)) == false) {
ke.consume();
}
}
@Override
public void keyPressed(KeyEvent ke) {
}
@Override
public void keyReleased(KeyEvent ke) {
}
};
eventosDeTecla = new KeyListener()
{
@Override
public void keyTyped(KeyEvent ke)
{
char caracter = ke.getKeyChar();
if(((caracter < '0') || (caracter > '9')) && (caracter != '\b' /*corresponde a BACK_SPACE*/))
ke.consume();
}
@Override
public void keyPressed(KeyEvent ke) {
}
@Override
public void keyReleased(KeyEvent ke) {
}
};
apellidoField.addKeyListener(eventosDeTeclaOnlyLetters);
nameField.addKeyListener(eventosDeTeclaOnlyLetters);
ciField.addKeyListener(eventosDeTecla);
telefonoField.addKeyListener(eventosDeTecla);
}
public void setPaciente(Paciente p)
{
this.apellidoField.setText(p.getApellido());
this.ciField.setText(p.getCi());
this.nameField.setText(p.getNombre());
this.telefonoField.setText(p.getTelefono());
}
}
|
C#
|
UTF-8
| 1,039 | 2.765625 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
namespace geometrifessor.Models
{
public class Emner // Her defineres klassen 'Emner'
{
public string Id { get; set; } // Her fåes string Id fra vores emner.json fil
[JsonPropertyName("img")] // her omformateres emner.json img tag til at blive kaldt når stringen 'Image' kaldes.
public string Image { get; set; } // her defineres string Image
public string Title { get; set; } // Her kalder vi titel tag fra emner.json
public string shortDescription { get; set; } // Her kalder vi shortDescription tag fra emner.json
public string Description { get; set; } // Her kalder vi Description tag fra emner.json
public override string ToString() => JsonSerializer.Serialize<Emner>(this); // her konverteres alle vores strings til en string, hvis man kalder klassen 'Emner' får man alt vores data fra emner.json
}
}
|
PHP
|
UTF-8
| 1,051 | 2.53125 | 3 |
[
"MIT"
] |
permissive
|
<?php
/**
* Class BasicTest.
*
* Long
*/
class BasicTest extends PHPUnit\Framework\TestCase
{
public function testBasic1()
{
$this->assertTrue(true);
}
public function testBasic2()
{
$this->assertTrue(true);
}
public function testBasic3()
{
$this->assertTrue(true);
}
public function testBasic4()
{
$this->assertTrue(true);
}
public function testBasic5()
{
$this->assertTrue(true);
}
public function testBasic6()
{
$this->assertTrue(true);
}
public function testBasic7()
{
$this->assertTrue(true);
}
public function testBasic8()
{
$this->assertTrue(true);
}
public function testBasic9()
{
$this->assertTrue(true);
}
public function testBasic10()
{
$this->assertTrue(true);
}
public function testBasic11()
{
$this->assertTrue(true);
}
public function testBasic12()
{
$this->assertTrue(true);
}
}
|
C#
|
UTF-8
| 7,937 | 2.609375 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.IO;
namespace WindowsFormsApp2
{
public partial class Form5 : Form
{
string _connectionString = $"Server={Properties.Settings.Default.Server};Initial Catalog={Properties.Settings.Default.Database};Persist Security Info=False;User ID={Properties.Settings.Default.UserName};Password={Properties.Settings.Default.Password};MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=True;Connection Timeout=30;";
public Form5()
{
InitializeComponent();
}
private void Form5_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the '_fcl_weighDataSet4.SlaughterData' table. You can move, or remove it, as needed.
this.slaughterDataTableAdapter.Fill(this._fcl_weighDataSet4.SlaughterData);
}
private void fillByToolStripButton_Click(object sender, EventArgs e)
{
try
{
this.slaughterDataTableAdapter.FillBy(this._fcl_weighDataSet4.SlaughterData);
}
catch (System.Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
}
private void SlaughterDate_ValueChanged(object sender, EventArgs e)
{
SlaughterDate.Format = DateTimePickerFormat.Custom;
SlaughterDate.CustomFormat = "yyyy-MM-dd";
DateTime endDate = Convert.ToDateTime(this.SlaughterDate.Text);
endDate=endDate.AddDays(1);
//MessageBox.Show(SlaughterDate.Text + "|" + endDate.ToString());
using (SqlConnection conn = new SqlConnection(_connectionString))
{
try
{
conn.Open();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return;
}
String q = "SELECT SlaughterTime,ReceiptNo,ItemNo,StockWeight,MeatPercent,[Classification Code] FROM [dbo].[SlaughterData] where " +
"SlaughterTime >='" + SlaughterDate.Text + "'"
+ " AND SlaughterTime<'" + endDate + "'";
var table = new DataTable();
using (var da = new SqlDataAdapter(q, _connectionString))
{
try
{
da.Fill(table);
}
catch ( Exception ex)
{
MessageBox.Show(ex.Message);
}
}
conn.Close();
this.dataGridView1.DataSource = table;
}
//MessageBox.Show(SlaughterDate.Text+" 00:00:00.000");
}
private void ExportTextFile_Click(object sender, EventArgs e)
{
string path = "",refine="";
SaveFileDialog saveFileDialog = new SaveFileDialog();
if (saveFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
path=saveFileDialog.FileName;
refine = (path + DateTime.Now.ToString("yyyy-MM-dd") + ".txt");
TextWriter writer = new StreamWriter(refine);
string input = ""; ; int index=0;
string date,time="";
DateTime sd;
for (int i=0; i<dataGridView1.Rows.Count-1;i++)
{
for(int j = 0; j < dataGridView1.Columns.Count; j++)
{
input = dataGridView1.Rows[i].Cells[j].Value.ToString();
//truncate the weight and meat percent
input.Replace(@"G0110", @"G0101");
input.Replace(@"G0111", @"G0102");
input.Replace(@"G0113", @"G0104");
if (j == 0)
{
time = Convert.ToDateTime(input).ToString("HH:mm");
date = Convert.ToDateTime(input).ToString("dd-MM-yyyy");
input = date + "|" + time;
}
if (j==1)
{
input = input.Replace(" ", "");
input.Replace(@"G0110", @"G0101");
input.Replace(@"G0111", @"G0102");
input.Replace(@"G0113", @"G0104");
}
if (j == 3 || j == 4)
{
input = input.Remove(input.LastIndexOf(".") + 1).Replace(".", "");
}
// if (j!=5)
writer.Write(input+"|");
}
writer.WriteLine("");
}
writer.Close();
MessageBox.Show("Data Exported Successfully");
}
else
{
MessageBox.Show("Invalid Export Location");
}
}
private void fillBy1ToolStripButton_Click(object sender, EventArgs e)
{
try
{
this.slaughterDataTableAdapter.FillBy1(this._fcl_weighDataSet4.SlaughterData);
}
catch (System.Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
}
}
private void ExportExcel_Click(object sender, EventArgs e)
{
string path = "", refine = "";
SaveFileDialog saveFileDialog = new SaveFileDialog();
if (saveFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
path = saveFileDialog.FileName;
refine = (path + DateTime.Now.ToString("yyyy-MM-dd") + ".csv");
TextWriter writer = new StreamWriter(refine);
string input = ""; ; int index = 0;
string date, time = "";
//DateTime sd;
for (int i = 0; i < dataGridView1.Rows.Count - 1; i++)
{
for (int j = 0; j < dataGridView1.Columns.Count; j++)
{
input = dataGridView1.Rows[i].Cells[j].Value.ToString();
//truncate the weight and meat percent
input.Replace(@"G0110", @"G0101");
input.Replace(@"G0111", @"G0102");
input.Replace(@"G0113", @"G0104");
if (j == 0)
{
time = Convert.ToDateTime(input).ToString("HH:mm");
date = Convert.ToDateTime(input).ToString("dd-MM-yyyy");
input = date + "," + time;
}
if (j == 1)
{
input = input.Replace(" ", "");
}
if (j == 3 || j == 4)
{
input = input.Remove(input.LastIndexOf(".") + 1).Replace(".", "");
}
//if (j != 4)
writer.Write(input + ",");
}
writer.WriteLine("");
}
writer.Close();
MessageBox.Show("Data Exported Successfully");
}
else
{
MessageBox.Show("Invalid Export Location");
}
}
}
}
|
C++
|
UTF-8
| 400 | 3.25 | 3 |
[] |
no_license
|
#include <iostream>
using namespace std;
template<class T, int n>
class STACK
{
private: T a[n];
int counter;
public:
void MakeStack(){counter = 0;}
bool FullStack()
{return (counter==n)? true:false;}
bool EmptyStack()
{return (counter==0)? true:false;}
void PushStack(T x)
{ a[counter] = x; counter++; }
T PopStack()
{counter--; return a[counter];}
};
|
C#
|
UTF-8
| 679 | 3.375 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ObjectArray
{
class Program
{
static void Main(string[] args)
{
Object[] oArrObjects = new Object[3];
oArrObjects[0] = "1st Element";
oArrObjects[1] = 101;
Customer oCustomer = new Customer();
oCustomer.ID = 1002;
oCustomer.Name = "Sreemonta";
oArrObjects[2] = oCustomer;
foreach (object item in oArrObjects)
{
Console.WriteLine(item);
}
Console.Read();
}
}
}
|
Java
|
UTF-8
| 2,456 | 1.960938 | 2 |
[] |
no_license
|
/**
* Project Name:esearch
* File Name:YougoPoiServiceImpl.java
* Package Name:com.xinguang.esearch.dubbo.impl
* Date:2016年9月29日下午5:31:20
*
*/
package com.xinguang.esearch.dubbo.impl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.alibaba.fastjson.JSONObject;
import com.xinguang.esearch.beans.GeoCondition;
import com.xinguang.esearch.constant.CommonConstant;
import com.xinguang.esearch.controller.YougoController;
import com.xinguang.esearch.enums.HttpCodeEnum;
import com.xinguang.esearch.service.ClientPoiQueryService;
import com.xinguang.esearch.utils.JsonUtil;
import com.xinguang.esearch.utils.POIBeansUtil;
import com.xinguang.esearchcenter.inter.YougoPoiService;
import com.xinguang.esearchcenter.request.GeoRequest;
import org.springframework.stereotype.Service;
/**
*
* ClassName: YougoPoiServiceImpl <br/>
* Function: TODO ADD FUNCTION. <br/>
* Reason: TODO ADD REASON(可选). <br/>
* date: 2016年10月19日 上午11:32:09 <br/>
*
* @author Administrator-lengxing
* @version
* @since JDK 1.7
*/
@Service("yougoPoiService")
public class YougoPoiServiceImpl implements YougoPoiService{
private static final Logger LOGGER = LoggerFactory.getLogger(YougoController.class);
@Autowired
private ClientPoiQueryService clientPoiQueryService;
@Override
public String PoiSearch(String index, String type, GeoRequest request) {
// TODO Auto-generated method stub
LOGGER.info("function={}, index={}, type={}, request={}", "queryScenicSpots", index, type, request);
GeoCondition gc = POIBeansUtil.setGeoCondition(request);
JSONObject queryResult = null;
if (gc != null) {
queryResult = clientPoiQueryService.poiQuery(index, type, gc);
}
LOGGER.info("function={}, index ={}, type ={}, request ={}, response={}", "queryScenicSpots", index, type, request, queryResult);
if (queryResult == null || queryResult.getIntValue(CommonConstant.COUNT) == 0) {
return JsonUtil.getResultJsonStr(HttpCodeEnum.HTTPCODE_204.getStatusCode(),
HttpCodeEnum.HTTPCODE_204.getStatusMsg() + ",query result is null ", null);
} else {
return JsonUtil.getResultJsonStr(HttpCodeEnum.HTTPCODE_200.getStatusCode(),
HttpCodeEnum.HTTPCODE_200.getStatusMsg(), queryResult);
}
}
}
|
C++
|
UTF-8
| 3,482 | 2.59375 | 3 |
[
"MIT"
] |
permissive
|
#ifndef SPARSEASSEMBLYNATIVE_H
#define SPARSEASSEMBLYNATIVE_H
#include <algorithm>
#include <cstdint>
#include <cstdlib>
#ifndef LL_TYPES
#define LL_TYPES
using Real = double;
using Integer = std::int64_t;
using UInteger = std::uint64_t;
#endif
#ifndef BINARY_LOCATE_DEF_
#define BINARY_LOCATE_DEF_
template<class RandomIt, class T>
inline RandomIt binary_locate(RandomIt first, RandomIt last, const T& val) {
if(val == *first) return first;
auto d = std::distance(first, last);
if(d==1) return first;
auto center = (first + (d/2));
if(val < *center) return binary_locate(first, center, val);
return binary_locate(center, last, val);
}
#endif
inline void SparseAssemblyNativeCSR_(
const double *coeff,
const int *data_local_indices,
const int *data_global_indices,
int elem,
int local_capacity,
double *data
) {
// FILL DATA VALUES FOR CSR
for (int i=0; i<local_capacity; ++i) {
data[data_global_indices[local_capacity*elem+i]] += coeff[data_local_indices[local_capacity*elem+i]];
}
}
inline void SparseAssemblyNativeCSR_RecomputeDataIndex_(
const double *coeff,
int *indices,
int *indptr,
double *data,
int elem,
int nvar,
int nodeperelem,
const UInteger *elements,
const Integer *sorter) {
int ndof = nvar*nodeperelem;
int local_capacity = ndof*ndof;
int *current_row_column = (int*)malloc(sizeof(int)*ndof);
int *full_current_column = (int*)malloc(sizeof(int)*local_capacity);
for (int counter=0; counter<nodeperelem; ++ counter) {
const int const_elem_retriever = nvar*elements[elem*nodeperelem+counter];
for (int ncounter=0; ncounter<nvar; ++ncounter) {
current_row_column[nvar*counter+ncounter] = const_elem_retriever+ncounter;
}
}
int *current_row_column_local = (int*)malloc(sizeof(int)*ndof);
int *full_current_column_local = (int*)malloc(sizeof(int)*local_capacity);
for (int counter=0; counter<nodeperelem; ++ counter) {
const int node = sorter[elem*nodeperelem+counter];
for (int ncounter=0; ncounter<nvar; ++ncounter) {
current_row_column_local[nvar*counter+ncounter] = node*nvar+ncounter;
}
}
for (int i=0; i<ndof; ++i) {
const int current_local_ndof = current_row_column_local[i]*ndof;
const int current_global_ndof = current_row_column[i];
const int current_global_row = indptr[current_global_ndof];
const int nnz = indptr[current_global_ndof+1] - current_global_row;
int *search_space = (int*)malloc(sizeof(int)*nnz);
for (int k=0; k<nnz; ++k) {
search_space[k] = indices[current_global_row+k];
}
for (int j=0; j<ndof; ++j) {
// int Iterr = std::find(search_space,search_space+nnz,current_row_column[j]) - search_space;
int Iterr = binary_locate(search_space,search_space+nnz,current_row_column[j]) - search_space;
full_current_column[i*ndof+j] = current_global_row + Iterr;
full_current_column_local[i*ndof+j] = current_local_ndof+current_row_column_local[j];
}
free(search_space);
}
// FILL DATA VALUES FOR CSR
for (int i=0; i<local_capacity; ++i) {
data[full_current_column[i]] += coeff[full_current_column_local[i]];
}
free(current_row_column);
free(full_current_column);
free(current_row_column_local);
free(full_current_column_local);
}
#endif
|
Java
|
UTF-8
| 2,548 | 2.5625 | 3 |
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package Karhabti.modeles;
import java.util.Objects;
/**
*
* @author Mohamed
*/
public class Rate {
private int id;
private Double nbrVote;
private User idUser;
private Annonces idAnnonce;
public Rate() {
}
public Rate(Double nbrVote) {
this.nbrVote = nbrVote;
}
public Rate(Double nbrVote, User idUser, Annonces idAnnonce) {
this.nbrVote = nbrVote;
this.idUser = idUser;
this.idAnnonce = idAnnonce;
}
public Rate(int id, Double nbrVote, User idUser, Annonces idAnnonce) {
this.id = id;
this.nbrVote = nbrVote;
this.idUser = idUser;
this.idAnnonce = idAnnonce;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Double getNbrVote() {
return nbrVote;
}
public void setNbrVote(Double nbrVote) {
this.nbrVote = nbrVote;
}
public User getIdUser() {
return idUser;
}
public void setIdUser(User idUser) {
this.idUser = idUser;
}
public Annonces getIdAnnonce() {
return idAnnonce;
}
public void setIdAnnonce(Annonces idAnnonce) {
this.idAnnonce = idAnnonce;
}
@Override
public int hashCode() {
int hash = 7;
hash = 79 * hash + this.id;
hash = 79 * hash + Objects.hashCode(this.idUser);
hash = 79 * hash + Objects.hashCode(this.idAnnonce);
return hash;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Rate other = (Rate) obj;
if (this.id != other.id) {
return false;
}
if (this.nbrVote != other.nbrVote) {
return false;
}
if (!Objects.equals(this.idUser, other.idUser)) {
return false;
}
if (!Objects.equals(this.idAnnonce, other.idAnnonce)) {
return false;
}
return true;
}
@Override
public String toString() {
return "Rate{" + "id=" + id + ", nbrVote=" + nbrVote + ", idUser=" + idUser + ", idAnnonce=" + idAnnonce + '}';
}
}
|
Java
|
UTF-8
| 806 | 2.15625 | 2 |
[] |
no_license
|
package com.apirest.octoevents.entity;
public class IssueDTO {
private String title;
private String body;
private String number;
private String created_at;
private String updated_at;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public String getCreated_at() {
return created_at;
}
public void setCreated_at(String created_at) {
this.created_at = created_at;
}
public String getUpdated_at() {
return updated_at;
}
public void setUpdated_at(String updated_at) {
this.updated_at = updated_at;
}
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
}
|
Java
|
UTF-8
| 7,459 | 2.6875 | 3 |
[] |
no_license
|
package org.streaminer.stream.frequency;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import org.streaminer.stream.frequency.util.CountEntry;
import org.streaminer.util.hash.HashUtils;
/**
* Combinatorial Group Testing to Find Frequent Items.
*
* Reference:
* G. Cormode. What's Hot and What's Not: Tracking Frequent Items Dynamically, PODS 2003
*
* <a href="http://www.cs.rutgers.edu/~muthu/massdal-code-index.html">Original code</a>
*
* @author Maycon Viana Bordin <mayconbordin@gmail.com>
*/
public class CGT implements IBaseFrequency<Integer>, IFrequencyList<Integer> {
public static final int DEFAULT_THRESHOLD = 1;
private int tests;
private int logn;
private int gran;
private int buckets;
private int subbuckets;
private int count;
private int[][] counts;
private long[] testa;
private long[] testb;
private Random random = new Random();
/**
* Create the data structure for Combinatorial Group Testing.
*
* @param buckets Each test has buckets buckets
* @param tests Keep T tests
* @param logn logn is the bit depth of the items which will arrive, this
* code assumes lgn <= 32 since it manipulates unsigned ints
* @param gran gran is the granularity at which to perform the testing
* gran = 1 means to do one bit at a time,
* gran = 4 means to do one nibble at time
* gran = 8 means to do one octet at a time, etc.
*/
public CGT(int buckets, int tests, int logn, int gran) {
this.tests = tests;
this.logn = logn;
this.gran = gran;
this.buckets = buckets;
subbuckets = 1 + (logn/gran) * ((1 << gran) - 1);
count = 0;
testa = new long[tests];
testb = new long[tests];
counts = new int[buckets*tests][subbuckets];
// initialise the hash functions
for (int i=0; i<tests; i++) {
testa[i] = random.nextLong();
if (testa[i] < 0)
testa[i]= -testa[i];
testb[i] = random.nextLong();
if (testb[i] < 0)
testb[i] = -testb[i];
}
}
public boolean add(Integer item) throws FrequencyException {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
public boolean add(Integer item, long incrementCount) throws FrequencyException {
long hash;
int offset = 0;
count += incrementCount;
for (int i=0; i<tests; i++) {
hash = HashUtils.hash31(testa[i], testb[i], item);
hash = hash % buckets;
logInsert((int)(offset+hash), item, (int)incrementCount);
offset += buckets;
}
return true;
}
public long size() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
public List<CountEntry<Integer>> getFrequentItems(double minSupport) {
Map<Integer,CountEntry<Integer>> results = new HashMap<Integer,CountEntry<Integer>>();
int thresh = (int) minSupport;
int testval=0, hash=0, guess = 0;
boolean pass;
for (int i=0; i<tests; i++) {
for (int j=0; j<buckets; j++) {
guess = (int) findOne(testval, thresh);
// go into the group, and see if there is a frequent item there
// then check item does hash into that group...
if (guess > 0) {
hash = (int) HashUtils.hash31(testa[i], testb[i], guess);
hash = hash % buckets;
}
if (guess > 0 && hash == j) {
pass = true;
for (int k=0; k<tests; k++) {
// check every hash of that item is above threshold...
hash = (int) HashUtils.hash31(testa[k], testb[k], guess);
hash = (buckets * k) + (hash % buckets);
//System.out.println("item="+guess+"; freq="+counts[hash][0]);
if (counts[hash][0] < thresh)
pass = false;
}
if (pass) {
// if the item passes all the tests, then output it
results.put(guess, new CountEntry<Integer>(guess, counts[hash][0]));
}
}
testval++;
}
}
return new ArrayList(results.values());
}
/**
*
* @param pos
* @param thresh
* @return The identity of the frequent item if there was one or zero if there was none.
*/
private long findOne(int pos, int thresh) {
int k = 0;
int offset, countabove, sum, last;
// if the count is not above threshold, then reject
if (counts[pos][0] >= thresh) {
offset = 1;
for (int i=logn; i>0; i-=gran) {
k <<= gran;
countabove=0; sum=0; last=0;
for (int l=1; l<(1 << gran); l++) {
if (counts[pos][offset] >= thresh) {
countabove++;
last = l;
}
sum += counts[pos][offset++];
}
if (counts[pos][0] - sum >= thresh)
countabove++;
// check: if both halves of a group are above threshold,
// then reject the whole group
if (countabove != 1) {
k = 0;
break;
}
// Update the record of the identity of the frequent item
k += last;
}
}
return k;
}
private void logInsert(int pos, int val, int inc) {
int bitmask = (1 << gran) - 1;
int offset = ((logn/gran)*bitmask) - bitmask;
// add the increment to the count of the group
counts[pos][0] += inc;
for (int i=logn; i>0; i-=gran) {
if ((val & bitmask) != 0) // if the lsb = 1, then add on to that group
counts[pos][offset + (val&bitmask)] += inc;
val >>= gran; // look at the next set of bits
offset -= bitmask;
}
}
public Set<Integer> keySet() {
return null;
}
public List<CountEntry<Integer>> peek(int k) {
return peek(k, DEFAULT_THRESHOLD);
}
public List<CountEntry<Integer>> peek(int k, double minSupport) {
List<CountEntry<Integer>> items = getFrequentItems(minSupport);
Collections.sort(items);
if (items.size() > k)
return items.subList(0, k);
else
return items;
}
public List<CountEntry<Integer>> getFrequentItems() {
return getFrequentItems(DEFAULT_THRESHOLD);
}
}
|
Markdown
|
UTF-8
| 2,228 | 2.890625 | 3 |
[
"Unlicense"
] |
permissive
|
# ביהד: הבינלאומי יכיר בוועד בנק אוצר החייל לאחר המיזוג
Published at: **2019-11-06T00:00:00+00:00**
Author: **בילי פרנקל**
Original: [כלכליסט - www.calcalist.co.il](https://www.calcalist.co.il/money/articles/0,7340,L-3773190,00.html)
בית הדין האזורי לעבודה בתל אביב קבע אתמול (ג') כי על הנהלת הבינלאומי לכבד את ההסכמים הקיבוציים שהושגו על ידי ועד עובדי בנק אוצר החייל, לפני המיזוג בין שני הבנקים.
בכך נרשם ניצחון לוועד עובדי בנק אוצר החייל, שעתרו נגד הנהלת הבנק כי אינו מכיר בוועד לאחר המיזוג.
פסק הדין התקבל בהמשך לעתירה שהוגשה על ידי ועד עובדי בנק אוצר החייל, בעקבות מיזוג הבנק אל תוך הבינלאומי בתחילת 2019. באי כוחם של העותרים, עו"ד בני כהן וקרן קוטס-אמיתי, טענו כי ההנהלה לא עמדה בסיכומים לפיהם הצדדים ייכנסו למו"מ הסדרת תנאי עובדים והטמעתם בבינלאומי, ואף פגעה בזכויות העובדים המעוגנות הסכמים הקיבוציים.
הבנק הבינלאומי טען באמצעות עו"ד נחום פינברג וקרן שליט, כי אין מקום לחייבו להמשיך לקיים את ההסכמים הקיבוציים שהיו נהוגים בבנק אוצר החייל, וכי לאור העובדה שהבנק כבר לא קיים, הרי שלא קיים גם ועד עובדים וההסתדרות אינה יכולה להחיותו באופן מלאכותי.
בית הדין דחה את טענות הבנק והורה לו לכבד את ההסכמים הקיבוציים שהושגו על ידי ועד העובדים קודם למיזוג במהלך השנה הקרובה.
בנוסף, הורה בית הדין להנהלה לנהל מו"מ עם ועד עובדי בנק אוצר החייל על זכויותיהם של העובדים המוטמעים בבינלאומי, ולא עם הוועדים הקיימים בבינלאומי.
|
C++
|
UTF-8
| 431 | 2.640625 | 3 |
[] |
no_license
|
/*
muddler.h
Author: C. Painter-Wakefield
Course and Assignment: CSCI 262 Lab 1
Description: Header for the muddler class.
*/
#ifndef _MUDDLER_H
#define _MUDDLER_H
#include <string>
using namespace std;
/**********************************************************
class muddler
Muddles strings.
**********************************************************/
class muddler {
public:
string muddle(string s);
};
#endif
|
JavaScript
|
UTF-8
| 724 | 4.1875 | 4 |
[] |
no_license
|
// Clase 6 ¿Que se implemento en ES7?
// En esta version se incorporan dos cambios muy particulares
// 1 El valor de include
// 2 Operaciones en forma exponencial (POW)
// Sustitulle index of
// Iclude metodo que trabaja sonbre un arreglo o string, nos permite saber si hay un elemento dentro de este valor
let numbers = [1,2,3,7,8]
// Validamos si dentro del arreglo se incluye el numero 7
if (numbers.includes(9)) {
console.log('Si se encuentra el valor 7')
} else {
console.log('No se encuentra')
}
// -----------------------------------------------------------------------------------
// Como vamos a elevar a una potencia.
let base = 4
let exponent = 4
let result = base ** exponent
console.log(result)
|
C#
|
UTF-8
| 721 | 2.875 | 3 |
[] |
no_license
|
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public enum Size {
none = 0,
small = 70,
medium = 100,
large = 130
}
public enum Tea {
black,
green,
oolong
}
public enum Topping {
boba
}
public class Order
{
// Size of the current cup
public Size size;
// How full the current cup is
public int totalAmount = 0;
// How much of each tea is in the cup
public Dictionary<Tea, int> teaAmounts = new Dictionary<Tea, int>();
// Toppings in the cup
public List<Topping> toppings = new List<Topping>();
public Order() {
this.size = Size.none;
}
public Order(Size size) {
this.size = size;
}
}
|
Java
|
UTF-8
| 353 | 1.625 | 2 |
[] |
no_license
|
package com.example.cassandra.repository.table;
import java.sql.Timestamp;
/**
* Created by Menaka on 10/14/16.
*/
public interface LoginEventTable {
String PERSON_ID = "person_id";
String EVENT_TIME = "event_time";
String EVENT_CODE = "event_code";
String IP_ADDRESS = "ip_address";
String LOGIN_EVENT_TABLE = "login_event";
}
|
PHP
|
UTF-8
| 518 | 2.5625 | 3 |
[] |
no_license
|
<?php
namespace Tests\Infrastructure\Persistence;
use Infrastructure\Persistence\AbstractEntity;
use Infrastructure\Persistence\AbstractRepository;
use Infrastructure\ValueObject\Identity\Uuid;
class UserRepository extends AbstractRepository
{
/**
* @param Uuid $uuid
* @return AbstractEntity
*/
public function find(Uuid $uuid)
{
/** @var $entity UserEntity */
$entity = $this->entityManager->find(UserEntity::class, $uuid->toString());
return $entity;
}
}
|
Python
|
UTF-8
| 314 | 2.890625 | 3 |
[] |
no_license
|
import sprites
class mario():
def __init__(self,x,y):
self.x = x
self.y = y
self.vel = {x:0,y:0}
self.marioSprite = sprites.sprites().mario
def drawMario(self,screen):
screen.blit(self.marioSprite,(self.x*32,self.y*32))
def updateMario(self):
pass
|
PHP
|
UTF-8
| 4,843 | 2.875 | 3 |
[] |
no_license
|
<?php
require_once "conexion.php";
class ModeloActividad{
/*============================================
Mostrar todas los actividades
============================================*/
static public function index($tabla, $cantidad, $desde){
//$stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla");
if ($cantidad != null) {
$stmt = Conexion::conectar()->prepare("SELECT $tabla.ID_USUARIO, $tabla.ID_PERIODO, $tabla.NOMBRE, $tabla.OBJETIVO_GENERAL, $tabla.COMPETENCIA, $tabla.TEMARIO, $tabla.AUTORIZADA, $tabla.ID_ORGANIGRAMA, $tabla.NO_CREDITOS FROM $tabla LIMIT $desde, $cantidad");
}else{
$stmt = Conexion::conectar()->prepare("SELECT $tabla.ID_USUARIO, $tabla.ID_PERIODO, $tabla.NOMBRE, $tabla.OBJETIVO_GENERAL, $tabla.COMPETENCIA, $tabla.TEMARIO, $tabla.AUTORIZADA, $tabla.ID_ORGANIGRAMA, $tabla.NO_CREDITOS FROM $tabla");
}
$stmt -> execute();
return $stmt -> fetchAll(PDO::FETCH_CLASS);
$stmt -> close();
$stmt = null;
}
/*============================================
Creacion de una actividad
============================================*/
static public function create($tabla, $datos){
$stmt = Conexion::conectar()->prepare("INSERT INTO $tabla(ID_USUARIO, ID_PERIODO, NOMBRE, OBJETIVO_GENERAL, COMPETENCIA, TEMARIO, AUTORIZADA, ID_ORGANIGRAMA, NO_CREDITOS) VALUES (:ID_USUARIO, :ID_PERIODO, :NOMBRE, :OBJETIVO_GENERAL, :COMPETENCIA, :TEMARIO, :AUTORIZADA, :ID_ORGANIGRAMA, :NO_CREDITOS)");
$stmt -> bindParam(":ID_USUARIO", $datos["ID_USUARIO"], PDO::PARAM_STR);
$stmt -> bindParam(":ID_PERIODO", $datos["ID_PERIODO"], PDO::PARAM_STR);
$stmt -> bindParam(":NOMBRE", $datos["NOMBRE"], PDO::PARAM_STR);
$stmt -> bindParam(":OBJETIVO_GENERAL", $datos["OBJETIVO_GENERAL"], PDO::PARAM_STR);
$stmt -> bindParam(":COMPETENCIA", $datos["COMPETENCIA"], PDO::PARAM_INT);
$stmt -> bindParam(":TEMARIO", $datos["TEMARIO"], PDO::PARAM_INT);
$stmt -> bindParam(":AUTORIZADA", $datos["AUTORIZADA"], PDO::PARAM_INT);
$stmt -> bindParam(":ID_ORGANIGRAMA", $datos["ID_ORGANIGRAMA"], PDO::PARAM_STR);
$stmt -> bindParam(":NO_CREDITOS", $datos[" NO_CREDITOS"], PDO::PARAM_STR);
if ($stmt -> execute()) {
return "ok";
}else{
print_r(Conexion::conectar()->errorInfo());
}
$stmt-> close();
$stmt= null;
}
/*============================================
Mostrar una sola actividad
============================================*/
static public function show($tabla, $id){
//$stmt = Conexion::conectar()->prepare("SELECT * FROM $tabla WHERE id=:id");
$stmt = Conexion::conectar()->prepare("SELECT $tabla.ID_ACTIVIDAD, $tabla.ID_USUARIO, $tabla.ID_PERIODO, $tabla.NOMBRE, $tabla.OBJETIVO_GENERAL, $tabla.COMPETENCIA, $tabla.TEMARIO, $tabla.AUTORIZADA, $tabla.ID_ORGANIGRAMA, $tabla.NO_CREDITOS FROM $tabla WHERE $tabla.ID_ACTIVIDAD =:ID_ACTIVIDAD");
$stmt -> bindParam(":ID_ACTIVIDAD", $id, PDO::PARAM_INT);
$stmt -> execute();
return $stmt -> fetchAll(PDO::FETCH_CLASS);
$stmt -> close();
$stmt = null;
}
/*============================================
Actualizacion de una actividad
============================================*/
static public function update($tabla, $datos){
$stmt = Conexion::conectar()->prepare("UPDATE $tabla SET ID_ACTIVIDAD=:ID_ACTIVIDAD,ID_USUARIO=:ID_USUARIO,ID_PERIODO=:ID_PERIODO,NOMBRE=:NOMBRE,OBJETIVO_GENERAL=:OBJETIVO_GENERAL,COMPETENCIA=:COMPETENCIA,TEMARIO=:TEMARIO,AUTORIZADA= AUTORIZADA,ID_ORGANIGRAMA=:ID_ORGANIGRAMA,NO_CREDITOS=:NO_CREDITOS WHERE ID_ACTIVIDAD= :ID_ACTIVIDAD");
$stmt -> bindParam(":ID_USUARIO", $datos["ID_USUARIO"], PDO::PARAM_STR);
$stmt -> bindParam(":ID_PERIODO", $datos["ID_PERIODO"], PDO::PARAM_STR);
$stmt -> bindParam(":NOMBRE", $datos["NOMBRE"], PDO::PARAM_STR);
$stmt -> bindParam(":OBJETIVO_GENERAL", $datos["OBJETIVO_GENERAL"], PDO::PARAM_STR);
$stmt -> bindParam(":COMPETENCIA", $datos["COMPETENCIA"], PDO::PARAM_INT);
$stmt -> bindParam(":TEMARIO", $datos["TEMARIO"], PDO::PARAM_INT);
$stmt -> bindParam(":AUTORIZADA", $datos["AUTORIZADA"], PDO::PARAM_INT);
$stmt -> bindParam(":ID_ORGANIGRAMA", $datos["ID_ORGANIGRAMA"], PDO::PARAM_STR);
$stmt -> bindParam(":NO_CREDITOS", $datos[" NO_CREDITOS"], PDO::PARAM_STR);
if ($stmt -> execute()) {
return "ok";
}else{
print_r(Conexion::conectar()->errorInfo());
}
$stmt-> close();
$stmt= null;
}
/*============================================
Borrar actividad
============================================*/
static public function delete($tabla, $id){
$stmt = Conexion::conectar()->prepare("DELETE FROM $tabla WHERE ID_ACTIVIDAD = :ID_ACTIVIDAD");
$stmt -> bindParam(":ID_ACTIVIDAD", $id, PDO::PARAM_INT);
if ($stmt -> execute()) {
return "ok";
}else{
print_r(Conexion::conectar()->errorInfo());
}
$stmt-> close();
$stmt= null;
}
}
|
Python
|
UTF-8
| 84 | 3.484375 | 3 |
[
"Apache-2.0"
] |
permissive
|
a=int(input())
b=int(input())
print (a//b)
print (a%b)
c=divmod(a, b)
print (c)
|
Markdown
|
UTF-8
| 7,948 | 2.890625 | 3 |
[
"MIT"
] |
permissive
|
---
layout: category
title: PCA
---
```python
%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns; sns.set()
def np_summary(np_array):
if np_array is None:
print('\nNone')
else:
dim = np.ndim(np_array)
print('\nndim: %s / shape: %s / size: %s' %(np.ndim(np_array), np.shape(np_array), np.size(np_array)))
if dim > 1:
t = 'np_array[:5'
for i in range(dim-1):
if i == 0:
t += ',:20'
else: t += ',:5'
t += ']'
print(eval(t))
else:
print(np_array[:20])
```
```python
rng= np.random.RandomState(1)
X = np.dot(rng.rand(2,2), rng.randn(2,200)).T
plt.scatter(X[:,0], X[:,1])
plt.axis('equal')
plt.show()
np_summary(X)
np.var(X[:,0])+ np.var(X[:,1])
```

ndim: 2 / shape: (200, 2) / size: 400
[[-0.62530162 -0.17006366]
[ 0.96069503 0.5909006 ]
[-0.59854339 -0.40259339]
[-2.22805938 -0.53257674]
[-0.46143006 -0.49886724]]
0.77710434941419326
```python
from sklearn.decomposition import PCA
pca = PCA(n_components=2, whiten=True)
pca.fit(X)
```
PCA(copy=True, iterated_power='auto', n_components=2, random_state=None,
svd_solver='auto', tol=0.0, whiten=True)
```python
print(pca.components_)
print(pca.explained_variance_)
np.power(0.9445,2) + np.power(0.3286,2)
```
[[-0.94446029 -0.32862557]
[-0.32862557 0.94446029]]
[ 0.7625315 0.0184779]
1.0000582099999999
```python
def draw_vector(v0, v1, ax=None):
ax = ax or plt.gca()
arrowprops = dict(arrowstyle = '->',
linewidth = 2,
shrinkA = 0,
shrinkB = 0)
ax.annotate('', v1, v0, arrowprops = arrowprops)
fig, ax = plt.subplots(1, 2, figsize=(16, 6))
fig.subplots_adjust(left=0.0625, right=0.95, wspace=0.1)
# plot data
ax[0].scatter(X[:, 0], X[:, 1], alpha=0.2)
for length, vector in zip(pca.explained_variance_, pca.components_):
v = vector * 3 * np.sqrt(length)
draw_vector(pca.mean_, pca.mean_ + v, ax=ax[0])
ax[0].axis('equal');
ax[0].set(xlabel='x', ylabel='y', title='input')
# plot principal components
X_pca = pca.transform(X)
ax[1].scatter(X_pca[:, 0], X_pca[:, 1], alpha=0.2)
draw_vector([0, 0], [0, 3], ax=ax[1])
draw_vector([0, 0], [3, 0], ax=ax[1])
ax[1].axis('equal')
ax[1].set(xlabel='component 1', ylabel='component 2',
title='principal components',
xlim=(-5, 5), ylim=(-3, 3.1))
plt.show()
print(list(zip(pca.explained_variance_, pca.components_)))
```

[(0.76253150088261124, array([-0.94446029, -0.32862557])), (0.018477895513562572, array([-0.32862557, 0.94446029]))]
ndim: 2 / shape: (200, 2) / size: 400
[[ 0.77501786 0.43946956]
[-1.22672528 1.89239746]
[ 0.8335856 -1.24082757]
[ 2.64493895 1.79548612]
[ 0.72151892 -2.24121269]]
```python
#pca.transform?
print(X[0])
print(np.mean(X, axis=0))
print(X[0]-np.mean(X, axis=0))
print(pca.components_[0])
print(X[0,0]-np.mean(X[:,0]))
print(X[0,1]-np.mean(X[:,1]))
print(np.sqrt(pca.explained_variance_))
print(np.dot(X[0]-np.mean(X,axis=0), pca.components_[0].T)/np.sqrt(pca.explained_variance_[0]))
np_summary(X_pca)
```
[-0.62530162 -0.17006366]
[ 0.03351168 -0.00408072]
[-0.6588133 -0.16598294]
[-0.94446029 -0.32862557]
-0.658813298008
-0.165982939521
[ 0.8732305 0.13593342]
0.775017864414
ndim: 2 / shape: (200, 2) / size: 400
[[ 0.77501786 0.43946956]
[-1.22672528 1.89239746]
[ 0.8335856 -1.24082757]
[ 2.64493895 1.79548612]
[ 0.72151892 -2.24121269]]
```python
#PCA 응용 - 차원 축소
pca = PCA(n_components=1)
pca.fit(X)
X_pca = pca.transform(X)
X_new = pca.inverse_transform(X_pca)
plt.scatter(X[:,0], X[:, 1], alpha=0.2)
plt.scatter(X_new[:,0], X_new[:,1], alpha=0.8)
plt.axis('equal')
plt.show()
```

```python
#PCA 시각화
from sklearn.datasets import load_digits
digits = load_digits()
np_summary(digits.data)
digits.data.shape
```
ndim: 2 / shape: (1797, 64) / size: 115008
[[ 0. 0. 5. 13. 9. 1. 0. 0. 0. 0. 13. 15. 10. 15.
5. 0. 0. 3. 15. 2.]
[ 0. 0. 0. 12. 13. 5. 0. 0. 0. 0. 0. 11. 16. 9.
0. 0. 0. 0. 3. 15.]
[ 0. 0. 0. 4. 15. 12. 0. 0. 0. 0. 3. 16. 15. 14.
0. 0. 0. 0. 8. 13.]
[ 0. 0. 7. 15. 13. 1. 0. 0. 0. 8. 13. 6. 15. 4.
0. 0. 0. 2. 1. 13.]
[ 0. 0. 0. 1. 11. 0. 0. 0. 0. 0. 0. 7. 8. 0.
0. 0. 0. 0. 1. 13.]]
(1797, 64)
```python
pca = PCA(2)
projected = pca.fit_transform(digits.data)
np_summary(projected)
plt.scatter(projected[:,0], projected[:,1],
c = digits.target, edgecolor = 'none', alpha=0.5,
cmap = plt.cm.get_cmap('nipy_spectral',10))
plt.xlabel('component 1')
plt.ylabel('component 2')
plt.colorbar()
```
ndim: 2 / shape: (1797, 2) / size: 3594
[[ -1.25946726 21.27488068]
[ 7.95759879 -20.76871407]
[ 6.99192842 -9.95597973]
[-15.90611388 3.33244683]
[ 23.30687029 4.26907436]]
<matplotlib.colorbar.Colorbar at 0x207b1b75940>

```python
pca = PCA().fit(digits.data)
plt.plot(np.cumsum(pca.explained_variance_ratio_))
plt.xlabeldef plot_digits(data):
fig, axes = plt.subplots(4, 10, figsize=(10, 4),
subplot_kw={'xticks':[], 'yticks':[]},
gridspec_kw=dict(hspace=0.1, wspace=0.1))
for i, ax in enumerate(axes.flat):
ax.imshow(data[i].reshape(8, 8),
cmap='binary', interpolation='nearest',
clim=(0, 16))
plot_digits(digits.data)('number of components')
plt.xlabel('cumulative explained variance')
```
Text(0.5,0,'cumulative explained variance')

```python
def plot_digits(data):
fig, axes = plt.subplots(4, 10, figsize=(10, 4),
subplot_kw={'xticks':[], 'yticks':[]},
gridspec_kw=dict(hspace=0.1, wspace=0.1))
for i, ax in enumerate(axes.flat):
ax.imshow(data[i].reshape(8, 8),
cmap='binary', interpolation='nearest',
clim=(0, 16))
plot_digits(digits.data)
plt.show()
```

```python
np.random.seed(42)
noisy = np.random.normal(digits.data, 4)
plot_digits(noisy)
```

```python
#분산의 50%만 보존
from sklearn.decomposition import PCA
pca =PCA(0.5).fit(noisy)
pca.n_components_
```
12
```python
components = pca.transform(noisy)
np_summary(components)
filtered = pca.inverse_transform(components)
plot_digits(filtered)
#단, 원데이터 필요
```
ndim: 2 / shape: (1797, 12) / size: 21564
[[ -9.82613291 19.60311879 -3.49445446 15.18944378 -9.68064658
-3.97375366 4.83158325 6.98797984 -4.74026972 7.26107832
0.58419145 1.8438046 ]
[ 14.65827166 -15.58079811 11.61685625 -11.40062003 5.42066782
-11.28323994 -1.61040501 -7.19254252 4.97865027 5.96816258
1.69008628 -7.38319027]
[ 5.30646513 -14.73205492 0.26421735 -10.775562 -21.95361945
-2.70060087 0.50853871 -10.59058661 2.31744836 -4.26313868
-2.47186264 -7.46461662]
[-17.97946614 8.78339229 16.15549567 -10.49900793 5.11905111
-1.17078704 -6.49141465 9.17915766 2.71205485 4.53905962
-7.80508389 -4.1612774 ]
[ 19.36434407 8.86888193 0.98957224 -11.32526702 -1.81013857
-1.36043328 -0.9054773 14.95422147 -5.28846675 15.04119777
6.65367902 -3.32977948]]

|
Java
|
UTF-8
| 551 | 2.09375 | 2 |
[] |
no_license
|
package ua.study.command.impl.info;
import ua.study.command.Command;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Created by dima on 13.05.17.
*/
public class NewsCommand implements Command {
@Override
public void execute(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("/WEB-INF/jsp/news.jsp").include(request, response);
}
}
|
C#
|
UTF-8
| 2,327 | 2.609375 | 3 |
[] |
no_license
|
using CattleCompanion.Core;
using CattleCompanion.Core.Models;
using CattleCompanion.Core.Repositories;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
namespace CattleCompanion.Persistence.Repositories
{
public class CowRepository : ICowRepository
{
private readonly IApplicationDbContext _context;
public CowRepository(ApplicationDbContext context)
{
_context = context;
}
public void Add(Cow cow)
{
_context.Cattle.Add(cow);
}
public Cow GetCow(int id)
{
return _context.Cattle
.Include(c => c.Farm)
.SingleOrDefault(c => c.Id == id);
}
public Cow GetCowWithAll(int id)
{
return _context.Cattle
.Include(c => c.Farm)
.Include(c => c.CowEvents)
.Include(c => c.ParentRelationships)
.Include(c => c.ChildrenRelationships)
.SingleOrDefault(c => c.Id == id);
}
public IEnumerable<Cow> GetSiblings(int id)
{
var parents = _context.Relationships
.Where(r => r.Cow2Id == id)
.Select(r => r.Cow1Id)
.ToList();
var siblings = _context.Relationships
.Where(r => parents.Contains(r.Cow1Id) && r.Cow2Id != id)
.Select(r => r.Cow2)
.Include(c => c.ParentRelationships)
.Include(c => c.ChildrenRelationships)
.OrderBy(c => c.GivenId)
.ToList();
return siblings.GroupBy(c => c.Id).Select(g => g.First()).ToList();
}
public IEnumerable<Cow> GetAllByFarm(int id)
{
return _context.Cattle
.Where(c => c.FarmId == id)
.OrderBy(c => c.GivenId)
.ToList();
}
public IEnumerable<Cow> GetAllByUserId(string userId)
{
var farmIds = _context.UserFarms.Where(uf => uf.UserId == userId).Select(uf => uf.FarmId).ToList();
return _context.Cattle.Where(c => farmIds.Contains(c.FarmId)).ToList();
}
public void Remove(Cow cow)
{
_context.Cattle.Remove(cow);
}
}
}
|
Java
|
UTF-8
| 1,465 | 2.203125 | 2 |
[] |
no_license
|
package model;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@PrimaryKeyJoinColumn
int id;
String name;
String username;
String password;
String email;
String role;
String expiry;
@OneToOne(targetEntity = Fine.class, cascade = CascadeType.ALL)
Fine fine;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getExpiry() {
return expiry;
}
public void setExpiry(String expiry) {
this.expiry = expiry;
}
public Fine getFine() {
return fine;
}
public void setFine(Fine fine) {
this.fine = fine;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
}
|
Java
|
UTF-8
| 150 | 1.921875 | 2 |
[] |
no_license
|
package digitcashiermvc.models;
public class AdminEmployee extends Employee{
public AdminEmployee(String password) {
super(password);
}
}
|
PHP
|
UTF-8
| 1,518 | 2.65625 | 3 |
[] |
no_license
|
<?php
require_once 'inc/header.php';
require_once 'classes/Product.php';
require_once 'classes/helpers/Str.php';
use helpers\Str;
//call func getAllProducts from
$prod=new Product;
$products=$prod->getAllProducts();
?>
<div class="container py-4">
<div class="row">
<?php if($products!=[]) {?>
<?php foreach($products as $product) { ?>
<div class="col-md-4 p-2">
<div class="card" >
<img style="height:300px" src="images/<?php echo $product['img']?>" class="card-img-top" alt="<?php echo $product['name']?>">
<div class="card-body">
<h5 class="card-title"> <?php echo $product['name']?> </h5>
<p class="text-muted">$<?php echo $product['price']?></p>
<p class="card-text"><?php echo Str::limit($product['desc']) ?> </p>
<a href="showProd.php?id=<?php echo $product['id']?>" class="btn btn-primary">Show</a>
<?php if(isset($_SESSION['id'])){ ?>
<a href="edit.php?id=<?php echo $product['id']?>" class="btn btn-info">Edit</a>
<a href="handlers/handleDelete.php?id=<?php echo $product['id']?>" class="btn btn-danger">Delete</a>
<?php }?>
</div>
</div>
</div>
<?php } ?>
<?php } else {?>
<p>No Proudct Found</p>
<?php } ?>
</div>
</div>
<?php require_once 'inc/footer.php';?>
|
Java
|
UTF-8
| 548 | 2.75 | 3 |
[] |
no_license
|
package sample;
import javafx.beans.property.SimpleStringProperty;
import javafx.beans.property.StringProperty;
public class Faculty_data {
final private StringProperty Subject;
final private StringProperty Class1;
Faculty_data(String subject,String Class)
{
this.Subject=new SimpleStringProperty(subject);
this.Class1=new SimpleStringProperty(Class);
}
public String getSubject()
{
return Subject.get();
}
public String getClass1()
{
return Class1.get();
}
}
|
JavaScript
|
UTF-8
| 3,581 | 3.015625 | 3 |
[] |
no_license
|
/**
* @file - make fetch requests
*/
// Third party imports
// Local imports
// Global contants
const fetchOptions = {
method: "",
// mode: 'no-cors', // Uncheck for cors
// cache: 'no-cahce' // valid options default, no-cache, reload, force-cache, only-if-chached
// credentials: 'same-origin', // include, same-origin, omit
headers: {
"Content-Type": "application/json; charset=utf-8"
// "Content-Type": "application/x-www-form-urlencoded",
},
body: {} // call JSON.stringify on body
};
const [contentTypeLabel, applicationJson, multipartFormData] = [
"content-type",
"application/json;charset=utf-8",
"multipart/form-data"
];
/**
* @method - pass in a string of the content type returned from a fetch httprequest and
* and the
* @param {Promise<object>} returned - Returned from an http request
* @return { Promise } returns a promise called with the appropraite response header helper
*/
const switchResponseData = returned => {
const contentType = returned.headers.get(contentTypeLabel).toLowerCase();
let promiseReturnValue;
switch (contentType) {
case "text/xml;charset=UTF-8":
promiseReturnValue = returned.text();
return promiseReturnValue;
case /^text/.test(contentType):
promiseReturnValue = returned.text();
return promiseReturnValue;
case applicationJson ||
"application/json;charset=UTF-8" ||
"application/json":
promiseReturnValue = returned.json();
return promiseReturnValue;
case "application/json; charset=utf-8":
promiseReturnValue = returned.json();
return promiseReturnValue;
case new RegExp(multipartFormData).test(contentType):
promiseReturnValue = returned.formData();
return promiseReturnValue;
default:
promiseReturnValue = returned.blob();
return promiseReturnValue;
}
};
/**
* @method - makes an http request
* @param {string} url
* @param { Options { url: string, inputData: Object, Context: {String - Type of GET, PATCH, POST, PUT } }
* @return { Promise<{Object}>}
*/
export const getData = ({ url, inputData, context = "GET" }) => {
return new Promise((resolve, reject) => {
if (context === "GET") {
fetch(url)
.then(data => {
const { ok, statusText, status } = data;
if (!ok) {
reject({
statement: `The server encountered an error on ${context} of status ${statusText}`,
status: status
});
}
const promiseReturnValue = switchResponseData(data);
promiseReturnValue
.then(val => {
resolve(val);
})
.catch(err => reject(err));
})
.catch(err => reject(err));
} else {
if (!inputData) {
throw new Error("Please pass in an option parameter");
}
const httpOptions = {
...fetchOptions,
body: JSON.stringify(inputData),
method: context
};
fetch(url, httpOptions)
.then(returned => {
const { ok, statusText, status } = returned;
if (!ok) {
reject({
statement: `The server encountered an error on ${context} of status ${statusText}`,
status: status
});
}
const promiseReturnValue = switchResponseData(returned);
promiseReturnValue
.then(parsed => resolve(parsed))
.catch(err => {
reject(err);
});
})
.catch(err => {
reject(err);
});
}
});
};
|
C++
|
UTF-8
| 2,647 | 2.671875 | 3 |
[] |
no_license
|
// ****************************************************************************
// LOAD BALANCING
// Copyright (C) 2012 Gerasimov, Smoryakova, Katerov, Afanasov, Kulakovich, Sobolev
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// ****************************************************************************
#ifndef _IINPUTFILE_H
#define _IINPUTFILE_H
#include <stddef.h>
/**
* \class IInputFile
*
* \brief Input file interface. Absraction for read-only file.
*/
class IInputFile
{
public:
/**
* \fn virtual size_t IInputFile::Read(void *buffer, size_t elementSize, size_t count) = 0;
*
* \brief Reads an array of \a count elements, each one with a size of \a elementSize bytes, from the file and stores them in the block of memory specified by \a buffer.
*
* \param [out] buffer Pointer to a block of memory with a minimum size of (\a elementSize * \a count) bytes.
* \param elementSize Size in bytes of each element to be read.
* \param count Number of elements, each one with a size of \a elementSize bytes.
*
* \return The total number of elements successfully read.
*/
virtual size_t Read(void *buffer, size_t elementSize, size_t count) = 0;
/**
* \fn virtual int IInputFile::Seek(long offset, int origin) = 0;
*
* \brief Sets the position indicator associated with the stream to a new position defined by adding offset to a reference position specified by origin.
*
* \param offset Number of bytes to offset from origin.
* \param origin Position from where offset is added. It is specified by one of the following constants:
* \a SEEK_SET Beginning of file
* \a SEEK_CUR Current position of the file pointer
* \a SEEK_END End of file
*
* \return If successful, the function returns a zero value.
* Otherwise, it returns nonzero value.
*/
virtual int Seek(long offset, int origin) = 0;
};
#endif
|
Java
|
UTF-8
| 576 | 2.0625 | 2 |
[] |
no_license
|
package top.cyixlq.core.net.bean;
import androidx.annotation.Nullable;
public class DnsConfig {
private String url;
@Nullable
private String[] hosts;
public DnsConfig(String url, @Nullable String[] hosts) {
this.url = url;
this.hosts = hosts;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
@Nullable
public String[] getHosts() {
return hosts;
}
public void setHosts(@Nullable String[] hosts) {
this.hosts = hosts;
}
}
|
Java
|
UTF-8
| 1,152 | 3.734375 | 4 |
[] |
no_license
|
package com.damladincer.oop.userinteraction;
import java.util.Scanner;
public class GuessTheNumberGame {
public static void main(String[] args) {
int guessNumber;
int random = randomNumber();
boolean win=false;
System.out.println("I have randomly choosen a number between [1,100]");
System.out.println("Try to guess it..");
Scanner scanner = new Scanner(System.in);
for (int i = 1; i <= 10; i++) {
guessNumber = scanner.nextInt();
System.out.println("You have " + (10 - i) + " guess(es) left");
System.out.println("Your guess is : " + guessNumber);
if(guessNumber>random) {
System.out.println("Your guess is greater than the number");
}else if(guessNumber<random) {
System.out.println("Your guess is smaller than the number");
}else{
win=true;
break;
}
}
if(win) {
System.out.println("You win");
}else {
System.out.println("The nummber is: " );
System.out.println("You lost");
}
scanner.close();
}
public static int randomNumber() {
double number = Math.random();
number *= 100;
number += 1;
return (int) number;
}
}
|
Java
|
UTF-8
| 6,806 | 2.59375 | 3 |
[] |
no_license
|
package lk.rgd.prs.core.service;
import junit.framework.Assert;
import junit.framework.TestCase;
import lk.rgd.UnitTestManager;
import lk.rgd.prs.api.dao.PINNumberDAO;
import lk.rgd.prs.api.service.PINGenerator;
import org.springframework.context.ApplicationContext;
import java.util.Calendar;
import java.util.GregorianCalendar;
/**
* @author asankha
*/
public class PINGeneratorImplTest extends TestCase {
private final ApplicationContext ctx = UnitTestManager.ctx;
private final PINGenerator pinGenerator;
@Override
protected void setUp() throws Exception {
super.setUp();
PINNumberDAO pinNumberDAO = (PINNumberDAO) ctx.getBean("pinNumberDAOImpl", PINNumberDAO.class);
try {
pinNumberDAO.deleteLastPINNumber(pinNumberDAO.getLastPINNumber(75210));
} catch (Exception ignore) {}
try {
pinNumberDAO.deleteLastPINNumber(pinNumberDAO.getLastPINNumber(75710));
} catch (Exception ignore) {}
try {
pinNumberDAO.deleteLastPINNumber(pinNumberDAO.getLastPINNumber(110210));
} catch (Exception ignore) {}
try {
pinNumberDAO.deleteLastPINNumber(pinNumberDAO.getLastPINNumber(110710));
} catch (Exception ignore) {}
}
public PINGeneratorImplTest() {
pinGenerator = (PINGenerator) ctx.getBean("pinGeneratorService", PINGenerator.class);
}
public void testPINGeneration() throws Exception {
// generate a PIN for a birth in 1900's
try {
GregorianCalendar cal = new GregorianCalendar();
cal.set(1975, Calendar.JULY, 29, 20, 15, 00);
long pin = pinGenerator.generatePINNumber(cal.getTime(), true, null);
Assert.assertEquals("wrong pin generated", 197521120007L, pin);
pin = pinGenerator.generatePINNumber(cal.getTime(), true, null);
Assert.assertEquals("wrong pin generated", 197521120015L, pin);
pin = pinGenerator.generatePINNumber(cal.getTime(), false, null);
Assert.assertEquals("wrong pin generated", 197571120005L, pin);
pin = pinGenerator.generatePINNumber(cal.getTime(), false, null);
Assert.assertEquals("wrong pin generated", 197571120013L, pin);
} catch (Exception e) {
e.printStackTrace();
fail("Did not expect a failure");
}
// generate a PIN for a birth in 2000's
try {
GregorianCalendar cal = new GregorianCalendar();
cal.set(2010, Calendar.JULY, 29, 20, 15, 00);
long pin = pinGenerator.generatePINNumber(cal.getTime(), true, null);
Assert.assertEquals("wrong pin generated", 201021100019L, pin);
pin = pinGenerator.generatePINNumber(cal.getTime(), true, null);
Assert.assertEquals("wrong pin generated", 201021100027L, pin);
pin = pinGenerator.generatePINNumber(cal.getTime(), false, null);
Assert.assertEquals("wrong pin generated", 201071100017L, pin);
pin = pinGenerator.generatePINNumber(cal.getTime(), false, null);
Assert.assertEquals("wrong pin generated", 201071100025L, pin);
} catch (Exception e) {
e.printStackTrace();
fail("Did not expect a failure");
}
// generate a PIN for a birth in 2000's - check 28th February 2011 and 31 January 2011
try {
GregorianCalendar cal = new GregorianCalendar();
cal.set(2011, Calendar.FEBRUARY, 28, 20, 15, 00);
long pin = pinGenerator.generatePINNumber(cal.getTime(), true, null);
Assert.assertEquals("wrong pin generated", 201105900011L, pin);
cal.set(2011, Calendar.JANUARY, 31, 20, 15, 00);
pin = pinGenerator.generatePINNumber(cal.getTime(), true, null);
Assert.assertEquals("wrong pin generated", 201103100019L, pin);
} catch (Exception e) {
e.printStackTrace();
fail("Did not expect a failure");
}
// generate temporary PINs for a birth in 2000's
try {
GregorianCalendar cal = new GregorianCalendar();
cal.set(2010, Calendar.JULY, 29, 20, 15, 00);
long pin = pinGenerator.generateTemporaryPINNumber(cal.getTime(), true);
Assert.assertEquals("wrong pin generated", 701021100012L, pin);
pin = pinGenerator.generateTemporaryPINNumber(cal.getTime(), true);
Assert.assertEquals("wrong pin generated", 701021100021L, pin);
pin = pinGenerator.generateTemporaryPINNumber(cal.getTime(), false);
Assert.assertEquals("wrong pin generated", 701071100011L, pin);
pin = pinGenerator.generateTemporaryPINNumber(cal.getTime(), false);
Assert.assertEquals("wrong pin generated", 701071100029L, pin);
} catch (Exception e) {
e.printStackTrace();
fail("Did not expect a failure");
}
// generate a PIN for someone with a NIC, but born before cutOverDate
try {
GregorianCalendar cal = new GregorianCalendar();
cal.set(1971, Calendar.MARCH, 1, 20, 15, 00);
long pin = pinGenerator.generatePINNumber(cal.getTime(), false, "715601231V");
Assert.assertEquals("wrong pin generated", 197156001231L, pin);
// will get similar PIN
cal.set(1971, Calendar.FEBRUARY, 1, 20, 15, 00);
pin = pinGenerator.generatePINNumber(cal.getTime(), false, "715322366V");
Assert.assertEquals("wrong pin generated", 197153202366L, pin);
cal.set(1971, Calendar.JANUARY, 31, 20, 15, 00);
pin = pinGenerator.generatePINNumber(cal.getTime(), false, "715311232V");
Assert.assertEquals("wrong pin generated", 197153101232L, pin);
// check a duplicate - must get a number in the new range
cal.set(1978, Calendar.JANUARY, 17, 20, 15, 00);
pin = pinGenerator.generatePINNumber(cal.getTime(), false, "785170903V");
Assert.assertEquals("wrong pin generated", 197851720005L, pin);
cal.set(1975, Calendar.JULY, 29, 20, 15, 00);
// check for generation of a new PIN for wrong ID (e.g. DOB)
pin = pinGenerator.generatePINNumber(cal.getTime(), true, "752101430V");
Assert.assertEquals("wrong pin generated", 197521120023L, pin);
// check for generation of a new PIN for wrong ID (e.g. gender)
pin = pinGenerator.generatePINNumber(cal.getTime(), true, "757111430V");
Assert.assertEquals("wrong pin generated", 197521120031L, pin);
} catch (Exception e) {
e.printStackTrace();
fail("Did not expect a failure");
}
}
}
|
Shell
|
UTF-8
| 2,318 | 3.8125 | 4 |
[] |
no_license
|
#!/bin/bash
# Basic script to install gcc5.2 on ubuntu 14.04
# For CMPE 275 class 2015
# Author: Ashish Bende
# Source: https://gist.github.com/maxlevesque/5813df2fcee107c757f4#file-howto-gcc-5-2-ubuntu15-04-sh
#
# Use it at your own risk.
# This script doesn't run testsuites from gcc package.
[ "$(whoami)" != "root" ] && exec sudo -- "$0" "$@"
if [ $EUID -ne 0 ]; then printf "\nPlease run this script as root\n"; exit 1; fi
printf "\n\n ---- Adding ubuntu latest toolchain ppa ----\n"
apt-add-repository -y ppa:ubuntu-toolchain-r/test
echo "press any key to continue ..."
read -n 1 -s
printf "\n\n ---- Installing necessary packages ---- \n"
apt-get update && apt-get -y install wget build-essential libgmp-dev libmpc-dev libisl-dev libmpfr-dev
apt-get -y dist-upgrade
printf "\n\n ---- Now lets install gcc5.2 ----\n"
printf "\n Installation location is /usr/local/gnu/gcc-5.2/"
printf " If this script doesnt work for you, delete gnu directory from installation location"
mkdir -p /usr/local/gnu/gcc-5.2.0/
printf "\n\n Now we will download gcc5.2 source package \n"
echo "press any key to continue ..."
read -n 1 -s
wget -c http://mirror1.babylon.network/gcc/releases/gcc-5.2.0/gcc-5.2.0.tar.bz2
tar jxvf gcc-5.2.0.tar.bz2
cd gcc-5.2.0
mkdir build
cd build
printf "\n\n Now lets get ready for some serious cpu action \n"
echo "press any key to continue ..."
read -n 1 -s
# Note u can remove --disable-multilib option if you are running 64 bit system. Added this option to work on ec2
../configure --prefix=/usr/local/gnu/gcc-5.2.0/ --disable-multilib --disable-werror --with-system-zlib --enable-checking=release --enable-languages=c,c++,fortran
printf "\n This may take a while. Go grab a coffee or take a nap :D"
#NPROC=$(nproc)
read -n 1 -s
ulimit -s 32768 && make -j 2 #$NPROC
make install
if [ $? -eq 0 ];then
printf "\n\n Lets create link to run gcc-5.2 directly from terminal"
printf "\n Use gcc-5.2,cpp-5.2 to run compiler"
ln -sv /usr/local/gnu/gcc-5.2.0/bin/gcc /usr/bin/gcc-5.2
ln -sv /usr/local/gnu/gcc-5.2.0/bin/g++ /usr/bin/g++-5.2
ln -sv /usr/local/gnu/gcc-5.2.0/bin/cpp /usr/bin/cpp-5.2
ln -sv /usr/local/gnu/gcc-5.2.0/bin/c++ /usr/bin/c++-5.2
printf "\n\n All Done!"
else
printf " \n Sorry 'make' failed on this system \n."
exit 1
fi
exit 0
|
JavaScript
|
UTF-8
| 2,323 | 3.234375 | 3 |
[] |
no_license
|
const { map, filter, findIndex , reduce} = require('./index');
describe('array methods', () => {
describe('map function', () => {
it('returns an array', () => {
const numbers = [1, 2, 3];
const mapped = map(numbers, number => number * 2);
expect(mapped).toEqual(expect.any(Array));
});
it('returns a mapped array with the same length as arr', () => {
const colors = ['red', 'green', 'blue', 'yellow'];
const mapped = map(colors, color => color.toUpperCase());
// expect(mapped.length).toEqual(colors.length);
expect(mapped).toHaveLength(colors.length);
});
it('returns a mapped array with uppercase colors', () => {
const colors = ['red', 'green', 'blue', 'yellow'];
const mapped = map(colors, color => color.toUpperCase());
expect(mapped).toEqual([
'RED',
'GREEN',
'BLUE',
'YELLOW'
]);
});
it('returns a mapped array with doubled numbers', () => {
const numbers = [1, 2, 3, 4];
const mapped = map(numbers, number => number * 2);
expect(mapped).toEqual([
2,
4,
6,
8
]);
});
});
describe('filter function', () => {
it('returns an array', () => {
const numbers = [1, 2, 3];
const filtered = filter(
numbers,
number => number % 2 === 0
);
expect(filtered).toEqual(expect.any(Array));
});
});
it('filters out odd numbers', () => {
const numbers = [1, 2, 3, 4];
const evens = filter(
numbers,
number => number % 2 === 0
);
expect(evens).toEqual([2, 4]);
});
describe('findIndex', () => {
it('returns a number', () => {
const colors = ['red', 'blue', 'green'];
const index = findIndex(colors, color => color.includes('l'));
expect(index).toEqual(expect.any(Number));
});
it('returns the index of a matching item', () => {
const colors = ['red', 'blue', 'green'];
const index = findIndex(colors, color => color.includes('l'));
expect(index).toEqual(1);
});
it('returns -1 if no match', () => {
const colors = ['red', 'blue', 'green'];
const index = findIndex(colors, color => color.includes('y'));
expect(index).toEqual(-1);
});
});
describe('')
});
|
Markdown
|
UTF-8
| 1,565 | 2.578125 | 3 |
[] |
no_license
|
### Keybase proof
I hereby claim:
* I am bryceryan-docker on github.
* I am bryceryan (https://keybase.io/bryceryan) on keybase.
* I have a public key whose fingerprint is 5137 5FC9 35F0 F060 7C01 B07C B104 38E6 072F 47A8
To claim this, I am signing this object:
```json
{
"body": {
"key": {
"eldest_kid": "01012026c631f3fce7dd04f94b344a5c4b432de66bb2a268061d04a9bd25cee2f68c0a",
"fingerprint": "51375fc935f0f0607c01b07cb10438e6072f47a8",
"host": "keybase.io",
"key_id": "b10438e6072f47a8",
"kid": "01012026c631f3fce7dd04f94b344a5c4b432de66bb2a268061d04a9bd25cee2f68c0a",
"uid": "59ac1dd2fef7a6d8d1cc81f18e8b5d19",
"username": "bryceryan"
},
"service": {
"name": "github",
"username": "bryceryan-docker"
},
"type": "web_service_binding",
"version": 1
},
"ctime": 1469810106,
"expire_in": 157680000,
"prev": "39f632a7520bfd99e6358b9c923d21d9571c2bc3db4a27665c5180a2d1a80765",
"seqno": 4,
"tag": "signature"
}
```
with the key [5137 5FC9 35F0 F060 7C01 B07C B104 38E6 072F 47A8](https://keybase.io/bryceryan), yielding the signature:
```
-----BEGIN PGP MESSAGE-----
Version: Keybase OpenPGP v2.0.53
Comment: https://keybase.io/crypto
yMIXAnicrVJZSFVBGL5WSmnBLSHUqGxQKtCambPfSCvaJakoSrIusx093Dr3du7V
cgkMk4wQbSHNrCdBKqMEQzCihUjJlyLowQhaSaSeyhbDaI7UW701DzPM/y18/8//
YNbUQGqS1jjT5D25C5OG7rVVBHZdaOivATTKq0CoBkTE5CP2cxFPhCMOByEAEUQY
Yp3pCrIVmwmDc6jalkoVVSUaU6mqYC50nVJMsG5CHUmcWJRjjQmBbd1kkIA8YDtu
mfBinuMmpK2GFEOzmaVoNrShDg0GEZU3RVBVTCEL2FYNYkpheTTuK2Q4SuJimROV
NfkJT8b7C/8/566YtNMswhDn2Ba2QXRucsSYiWxkCpNqHFk+MS48lxwQfiqvigmv
irjgSB6Q5UqHCX+yv+EyJ1FeQf8hyedRFhGer0xUxXzokKDh3yZh6rhcDlJqK4UX
d6IuCCHJZAnHd0GqbpmycajnAXE45ngi7PgMzZANypMHYp6olJaKZesKJoaGIbW5
ZQld0UxqMQsrHCNuaQZimDKFU5VgQ9c1piETEswRMaGha8Bv66AbBSFVxiRl0jLu
lLkkUeEJcOT+3dJpgaTUQEryFH/BAqkzgn/Wbiw2PdDSXvelPDj+Ifv11Sdjw5mN
Ny4vbKmv/77ue8nXd2s7D/bvDfYd7wq8LK0lrx9fPFN5Z37rhutFbgE9EUxXtkc2
Zi951L57aVHJaGFB9fORVj4Wa2m7ld843lM7b/aCrT9yBoNzT3a8yOneVD/wuDix
PZLW9KqreHNG3UgDuJW55mzD6qyJw7eHendOfP6WjucU5j4sevbpS9LtV7y7NWX6
vjfrztVtm6FcSo+vR8eWZy0v3AOy2pN3jD9ZEOmEL5pXbEnmGenN/cGb3QNw/enu
0kZ18Gi2sqr60Pu0nB1P85s6Th4NXRmqGTuf+aYkOzpMN/a2tPWd+thDF43+rI4t
frvy2tJf8Q06LQ==
=1oZh
-----END PGP MESSAGE-----
```
And finally, I am proving ownership of the github account by posting this as a gist.
### My publicly-auditable identity:
https://keybase.io/bryceryan
### From the command line:
Consider the [keybase command line program](https://keybase.io/download).
```bash
# look me up
keybase id bryceryan
```
|
Java
|
UTF-8
| 1,529 | 2.796875 | 3 |
[] |
no_license
|
package pe.edu.pucp.congresoft.model;
import java.sql.Date;
public class Congreso{
private int idCongreso;
private String nombre;
private Date fechaInicio;
private Date fechaFin;
private String pais;
private boolean activo;
public Congreso(){
}
public Congreso( String nombre, Date fechaInicio, Date fechaFin, String pais, boolean activo){
this.nombre=nombre;
this.fechaInicio= fechaInicio;
this.fechaFin=fechaFin;
this.pais=pais;
this.activo=activo;
}
public int getIdCongreso(){
return idCongreso;
}
public void setIdCongreso(int idCongreso){
this.idCongreso = idCongreso;
}
public void setNombre(String nombre){
this.nombre = nombre;
}
public String getNombre(){
return nombre;
}
public void setFechaInicio(Date fechaInicio){
this.fechaInicio = fechaInicio;
}
public Date getFechaInicio(){
return fechaInicio;
}
public void setFechaFin(Date fechaFin){
this.fechaFin = fechaFin;
}
public Date getFechaFin(){
return fechaFin;
}
public String getPais(){
return pais;
}
public void setPais(String pais){
this.pais = pais;
}
public boolean isActivo() {
return activo;
}
public void setActivo(boolean activo) {
this.activo = activo;
}
public String mostrarDatos(){
return idCongreso + " - " + nombre + " - " + fechaInicio + " - " + fechaFin + " - " + pais ;
}
}
|
C++
|
UTF-8
| 716 | 3.484375 | 3 |
[] |
no_license
|
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* sortedArrayToBST(vector<int>& nums) {
return sortedArrayToBSTStep(nums,0,nums.size()-1);
}
TreeNode* sortedArrayToBSTStep(vector<int>& nums, int i, int j){
if(i<=j){
int mid = (i+j+1)/2;
TreeNode* root = new TreeNode(nums[mid]);
root->left = sortedArrayToBSTStep(nums,i,mid-1);
root->right = sortedArrayToBSTStep(nums,mid+1,j);
return root;
}else{
return 0;
}
}
};
|
Python
|
UTF-8
| 1,590 | 2.90625 | 3 |
[] |
no_license
|
#!/usr/local/bin/python
# -*- coding: utf-8 -*-
"""
pyapp.py
去除log日志的某行-带'抛弃原文'的去掉
Version: 1.0
Author: LC
DateTime: 2019年2月18日12:29:06
UpdateTime: None
一加壹博客最Top-一起共创1+1>2的力量!~LC
LC博客url: http://oneplusone.top/index.html
"""
def main():
with open("pyapp.log", "r", encoding="utf-8") as f:
lines = f.readlines()
# print(lines)
with open("pyapp_ok.log", "w", encoding="utf-8") as f_w:
all_line_counts = 0
for line in lines:
if "抛弃原文" in line:
print('剔除的数据:-->' + line)
all_line_counts = all_line_counts + 1
continue # 符合的抛弃
f_w.write(line) # 不符合的重新写入
print('总删除行' + str(all_line_counts))
close_str_msg = input('Press Enter to exit...')
print(close_str_msg)
def maintxt():
with open("txt.txt", "r", encoding="utf-8") as f:
lines = f.readlines()
# print(lines)
with open("txt_ok.txt", "w", encoding="utf-8") as f_w:
all_line_counts = 0
for line in lines:
if "tasting" in line:
print('剔除的数据:-->' + line)
all_line_counts = all_line_counts + 1
continue # 符合的抛弃
f_w.write(line) # 不符合的重新写入
print('总删除行' + str(all_line_counts))
close_str_msg = input('Press Enter to exit...')
print(close_str_msg)
if __name__ == '__main__':
# maintxt()
main()
|
PHP
|
UTF-8
| 2,819 | 2.625 | 3 |
[
"Apache-2.0"
] |
permissive
|
<?php
// +-----------------------------------------------------------------------------------
// | TangFrameWork 致力于WEB快速解决方案
// +-----------------------------------------------------------------------------------
// | Copyright (c) 2012-2014 http://www.tangframework.com All rights reserved.
// +-----------------------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +-----------------------------------------------------------------------------------
// | HomePage ( http://www.tangframework.com/ )
// +-----------------------------------------------------------------------------------
// | Author: wujibing<283109896@qq.com>
// +-----------------------------------------------------------------------------------
// | Version: 1.0
// +-----------------------------------------------------------------------------------
namespace Tang\GD\Effects;
use Tang\GD\Draws\Base;
use Tang\GD\IDraw;
use Tang\GD\Image;
use Tang\GD\Resource as ImageResource;
/**
* 添加一个图形资源到图形上
* Class AppendImage
* @package Tang\Gd\Effects
*/
class AppendImage extends Base implements IDraw
{
/**
* 添加的图形资源
* @var ImageResource
*/
protected $resource;
protected $opacity;
/**
* @param ImageResource $resource 添加的资源
* @param $x X
* @param $y Y
* @param int $opacity 透明度
*/
public function __construct(ImageResource $resource,$x,$y,$opacity = 100)
{
$this->setXY($x,$y)->setResource($resource)->setOpacity($opacity);
}
/**
* 设置添加的图片资源
* @param ImageResource $resource
* @return $this
*/
public function setResource(ImageResource $resource)
{
$this->resource = $resource;
return $this;
}
/**
* 设置 透明度
* @param int $opacity
* @return $this
*/
public function setOpacity($opacity = 100)
{
$this->opacity = $this->getIntValue($opacity,100);
return $this;
}
public function draw(Image $image)
{
$dstResource = $image->getResource()->resource;
$srcResource = $this->resource->resource;
$srcWidth = $this->resource->getWidth();
$srcHeight = $this->resource->getHeight();
$cutResource = imagecreatetruecolor($srcWidth, $srcHeight);
imagecopy($cutResource, $dstResource, 0, 0, $this->x, $this->y, $srcWidth, $srcHeight);
imagecopy($cutResource, $srcResource, 0, 0, 0, 0, $srcWidth, $srcHeight);
imagecopymerge($dstResource, $cutResource, $this->x, $this->y, 0, 0, $srcWidth, $srcHeight, $this->opacity);
imagedestroy($cutResource);
}
}
|
Java
|
UTF-8
| 514 | 2.515625 | 3 |
[] |
no_license
|
package com.tec.datos1.gameofsorts.game;
import com.badlogic.gdx.Game;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
public class Games extends Game {
SpriteBatch batch;
Texture img;
MainScreen main;
@Override
public void create () {
batch = new SpriteBatch();
main = new MainScreen(this);
setScreen(main);
}
@Override
public void render () {
super.render();
}
public void dispose (int width, int height) {
super.resize(width, height);
}
}
|
C#
|
UTF-8
| 586 | 2.578125 | 3 |
[
"MIT"
] |
permissive
|
using Newtonsoft.Json.Linq;
using System;
namespace DataStorage.DataObjects.Events
{
public class PlayerLeftEvent : Event
{
public PlayerLeftEvent(Guid sessionId, string playerName) : base(sessionId, EventType.PlayerLeft, $"Player {playerName} left", $"Player {playerName} left the session.")
{
Context = JObject.FromObject(new PlayerLeftContext
{
PlayerName = playerName
});
}
private class PlayerLeftContext
{
public string PlayerName { get; set; }
}
}
}
|
C++
|
UTF-8
| 1,053 | 2.53125 | 3 |
[] |
no_license
|
#include <Vaango_UIComponentBase.h>
#define STB_IMAGE_IMPLEMENTATION
#include <stb_image.h>
using namespace VaangoUI;
Vaango_UIIcon
Vaango_UIComponentBase::creatIconTextureFromImageFile(const std::string& fileName)
{
Vaango_UIIcon icon;
int textureComp;
void* textureData =
stbi_load(fileName.c_str(), &icon.width, &icon.height, &textureComp, 0);
if (textureData == nullptr || textureComp < 3) {
std::cout << "Failed to load image: " << fileName << std::endl;
icon.id = -1;
return icon;
}
glGenTextures(1, &icon.id);
glBindTexture(GL_TEXTURE_2D, icon.id);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, textureComp == 3 ? GL_RGB : GL_RGBA,
icon.width, icon.height, 0,
textureComp == 3 ? GL_RGB : GL_RGBA, GL_UNSIGNED_BYTE,
static_cast<GLubyte*>(textureData));
glBindTexture(GL_TEXTURE_2D, 0);
stbi_image_free(textureData);
return icon;
}
|
Python
|
UTF-8
| 2,332 | 2.65625 | 3 |
[] |
no_license
|
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sn
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix
#Import necessary libraries
from tensorflow.keras import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Dense, Flatten
from tensorflow.keras import layers
from tensorflow.keras import optimizers
import tensorflow as tf
df = pd.read_pickle('org_imgs_newcrop.pkl')
# Get data
#df = pd.read_pickle('10_thumbs_expanded_dataset.pkl')
# Choose which columns to be data (X) and target (y)
X_name = "Image" # The data to be categorized, should be "Image"
y_name = "Identity" # The target label. In the end, Identity
X = list(df[X_name])
y = df[y_name]
print(np.shape(X))
X = [x/255 for x in X] # Scale the data to be in range [0,1]
# Divide into training and test sets
X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.2)
X_train= np.array(X_train)
X_test= np.array(X_test)
sample_shape = np.shape(X_train)
img_width, img_height = sample_shape[0], sample_shape[1]
input_shape = (img_width, img_height, 1,1)
sample_shape2 = np.shape(X_test)
img_width2, img_height2 = sample_shape2[0], sample_shape2[1]
input_shape2 = (img_width2, img_height2, 1,1)
# Reshape data
X_train = X_train.reshape(len(X_train), input_shape[1], 1, 1)
X_test = X_test.reshape(len(X_test), input_shape2[1], 1, 1)
model = Sequential([
Conv2D(32, 3, padding='same', activation='relu',kernel_initializer='he_uniform', input_shape = [97, 90, 1]),
MaxPooling2D(2),
Conv2D(32, 3, padding='same', kernel_initializer='he_uniform', activation='relu'),
MaxPooling2D(2),
Flatten(),
Dense(128, kernel_initializer='he_uniform',activation = 'relu'),
Dense(2, activation = 'softmax'),
])
model.compile(optimizer = optimizers.Adam(1e-3), loss = 'categorical_crossentropy', metrics = ['accuracy'])
early_stopping_cb = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=10)
history = model.fit(X_train, y_train,epochs = 10, callbacks = [early_stopping_cb], verbose = 1,validation_data=(X_test, y_test))
|
Swift
|
UTF-8
| 11,654 | 2.6875 | 3 |
[
"MIT"
] |
permissive
|
//
// InterfaceElement.swift
// AR MultiPendulum
//
// Created by Philip Turner on 7/28/21.
//
import SwiftUI
import simd
extension InterfaceRenderer {
struct InterfaceElement {
private var centralObject: CentralObject
private var inverseScale: simd_float4
private(set) var radius: Float
private(set) var controlPoints: simd_float4x2
private(set) var normalTransform: simd_half3x3
var surfaceColor: simd_packed_half3 {
get { centralObject.color }
set { centralObject.color = newValue }
}
var surfaceShininess: Float16 {
get { centralObject.shininess }
set { centralObject.shininess = newValue }
}
var surfaceOpacity: Float
var baseSurfaceColor: simd_half3
var highlightedSurfaceColor: simd_half3
var baseSurfaceOpacity: Float
var highlightedSurfaceOpacity: Float
private var _isHighlighted = false
var isHighlighted: Bool {
get { _isHighlighted }
set {
surfaceColor = .init(newValue ? highlightedSurfaceColor : baseSurfaceColor)
surfaceOpacity = newValue ? highlightedSurfaceOpacity : baseSurfaceOpacity
_isHighlighted = newValue
}
}
var textColor: simd_half3
var textShininess: Float16
var textOpacity: Float16
var hidden = false
var characterGroups: [CharacterGroup?]
static func createOrientation(forwardDirection: simd_float3, orthogonalUpDirection: simd_float3) -> simd_quatf {
let xAxis = cross(orthogonalUpDirection, forwardDirection)
return simd_quatf(simd_float3x3(xAxis, orthogonalUpDirection, forwardDirection))
}
init(position: simd_float3, forwardDirection: simd_float3, orthogonalUpDirection: simd_float3,
width: Float, height: Float, depth: Float, radius: Float,
highlightColor: simd_float3 = [0.2, 0.2, 0.9], highlightOpacity: Float = 1.0,
surfaceColor: simd_float3 = [0.1, 0.1, 0.8], surfaceShininess: Float = 32, surfaceOpacity: Float = 1.0,
textColor: simd_float3 = [0.9, 0.9, 0.9], textShininess: Float = 32, textOpacity: Float = 1.0,
characterGroups: [CharacterGroup?])
{
let orientation = Self.createOrientation(forwardDirection: forwardDirection,
orthogonalUpDirection: orthogonalUpDirection)
centralObject = CentralObject(shapeType: .cube,
position: position,
orientation: orientation,
scale: simd_float3(width, height, depth),
color: surfaceColor,
shininess: surfaceShininess)
centralObject.updateTransforms()
self.radius = max(min(radius, min(width, height) * 0.5), 0)
inverseScale = simd_precise_recip(simd_float4(width, height, depth, self.radius))
controlPoints = Self.getControlPoints(width: width, height: height, radius: self.radius)
normalTransform = simd_half3x3(simd_float3x3(orientation))
baseSurfaceColor = .init(surfaceColor)
highlightedSurfaceColor = .init(highlightColor)
baseSurfaceOpacity = surfaceOpacity
highlightedSurfaceOpacity = highlightOpacity
self.surfaceOpacity = surfaceOpacity
self.textColor = .init(textColor)
self.textShininess = .init(textShininess)
self.textOpacity = .init(textOpacity)
self.characterGroups = characterGroups
}
private static func getControlPoints(width: Float, height: Float, radius: Float) -> simd_float4x2 {
let outerX = width * 0.5
let outerY = height * 0.5
let innerX = outerX - radius
let innerY = outerY - radius
return simd_float4x2(
.init(innerX, outerX),
.init(innerY, outerY),
.init(innerX, outerX),
.init(innerY, outerY)
)
}
var position: simd_float3 { centralObject.position }
var orientation: simd_quatf { centralObject.orientation }
var scale: simd_float3 { centralObject.scale }
mutating func setProperties(position: simd_float3? = nil,
orientation: simd_quatf? = nil,
scale: simd_float3? = nil,
radius: Float? = nil) {
if let position = position {
centralObject.position = position
}
if let orientation = orientation {
centralObject.orientation = orientation
normalTransform = simd_half3x3(simd_float3x3(orientation))
}
if let scale = scale {
centralObject.scale = scale
}
if let radius = radius {
self.radius = max(radius, 0)
}
if scale != nil || radius != nil {
inverseScale = simd_precise_recip(simd_float4(centralObject.scale, self.radius))
controlPoints = Self.getControlPoints(width: centralObject.scale.x,
height: centralObject.scale.y,
radius: self.radius)
}
if position != nil || orientation != nil || scale != nil {
centralObject.updateTransforms()
}
}
var modelToWorldTransform: simd_float4x4 {
centralObject.assertTransformsUpdated()
var output = centralObject.modelToWorldTransform
output[0] *= inverseScale.x
output[1] *= inverseScale.y
return output
}
func frontIsVisible(projectionTransform: simd_float4x4) -> Bool {
let worldSpacePointA = simd_make_float3(centralObject.modelToWorldTransform * [-0.5, -0.5, 0.5, 1])
let worldSpacePointB = simd_make_float3(centralObject.modelToWorldTransform * [ 0.5, 0.5, 0.5, 1])
let worldSpacePointC = simd_make_float3(centralObject.modelToWorldTransform * [-0.5, 0.5, 0.5, 1])
let pointA = projectionTransform * simd_float4(worldSpacePointA, 1)
let pointB = projectionTransform * simd_float4(worldSpacePointB, 1)
let pointC = projectionTransform * simd_float4(worldSpacePointC, 1)
let reciprocalW = simd_precise_recip(simd_float3(pointA.w, pointB.w, pointC.w))
let clipCoords = simd_float3x2(
pointA.lowHalf * reciprocalW[0],
pointB.lowHalf * reciprocalW[1],
pointC.lowHalf * reciprocalW[2]
)
return simd_orient(clipCoords[1] - clipCoords[0], clipCoords[2] - clipCoords[0]) >= 0
}
func frontIsVisible(cameraMeasurements: CameraMeasurements) -> Bool {
if cameraMeasurements.doingMixedRealityRendering {
if frontIsVisible(projectionTransform: cameraMeasurements.worldToLeftClipTransform) {
return true
}
return frontIsVisible(projectionTransform: cameraMeasurements.worldToRightClipTransform)
} else {
return frontIsVisible(projectionTransform: cameraMeasurements.worldToScreenClipTransform)
}
}
func shouldPresent(cullTransform worldToClipTransform: simd_float4x4) -> Bool {
!hidden && centralObject.shouldPresent(cullTransform: worldToClipTransform)
}
func shouldPresent(cameraMeasurements: CameraMeasurements) -> Bool {
guard !hidden else { return false }
let cullTransform = cameraMeasurements.renderer.centralRenderer.cullTransform
return centralObject.shouldPresent(cullTransform: cullTransform)
}
}
}
extension InterfaceRenderer.InterfaceElement: RayTraceable {
func rayTrace(ray worldSpaceRay: RayTracing.Ray) -> Float? {
guard !hidden, let initialProgress = centralObject.rayTrace(ray: worldSpaceRay) else {
return nil
}
if radius == 0 { return initialProgress }
var modelToWorldTransform = self.modelToWorldTransform
modelToWorldTransform[2] *= inverseScale.z
let worldToModelTransform = modelToWorldTransform.inverseRotationTranslation
let worldSpaceIntersection = worldSpaceRay.project(progress: initialProgress)
var modelSpaceIntersection = simd_make_float3(worldToModelTransform * simd_float4(worldSpaceIntersection, 1))
let controlX = controlPoints[0][0]
let controlY = controlPoints[1][0]
if abs(modelSpaceIntersection.x) <= controlX ||
abs(modelSpaceIntersection.y) <= controlY {
return initialProgress
}
var modelSpaceOrigin = simd_make_float3(worldToModelTransform * simd_float4(worldSpaceRay.origin, 1))
modelSpaceOrigin = .init(modelSpaceOrigin.x, modelSpaceOrigin.z, modelSpaceOrigin.y)
modelSpaceIntersection = .init(modelSpaceIntersection.x, modelSpaceIntersection.z, modelSpaceIntersection.y)
let radiusMultiplier = inverseScale.w * 0.5
let rayScaleMultiplier = simd_float3(radiusMultiplier, inverseScale.z, radiusMultiplier)
let rayDirection = (modelSpaceIntersection - modelSpaceOrigin) * rayScaleMultiplier
var finalProgress = Float.greatestFiniteMagnitude
func testCorner(x: Float, z: Float) {
let rayOrigin = (modelSpaceOrigin - simd_float3(x, 0, z)) * rayScaleMultiplier
let testRay = RayTracing.Ray(origin: rayOrigin, direction: rayDirection)
guard testRay.passesInitialBoundingBoxTest() else { return }
if let testProgress = testRay.getCentralCylinderProgress(), testProgress < finalProgress {
finalProgress = testProgress
}
}
func testSide(x: Float) {
if modelSpaceIntersection.z > controlY || controlY <= 1e-8 {
testCorner(x: x, z: controlY)
}
if modelSpaceIntersection.z < -controlY, controlY > 1e-8 {
testCorner(x: x, z: -controlY)
}
}
if modelSpaceIntersection.x > controlX || controlX <= 1e-8 {
testSide(x: controlX)
}
if modelSpaceIntersection.x < -controlX, controlX > 1e-8 {
testSide(x: -controlX)
}
if finalProgress < .greatestFiniteMagnitude {
return initialProgress * finalProgress
} else {
return nil
}
}
}
|
Python
|
UTF-8
| 189 | 2.859375 | 3 |
[] |
no_license
|
# -*- coding: UTF-8 -*-
import time
import datetime
import sys
a = sys.argv[1]
t = time.strptime(a, "%Y-%m-%d")
y, m, d = t[0:3]
print(datetime.date(y, m, d) + datetime.timedelta(days=1))
|
Java
|
UTF-8
| 2,016 | 2.6875 | 3 |
[] |
no_license
|
package Enumeration;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import READ_TXT.Read_INPUT_TXT_filter;
import READ_TXT.Read_distance;
public class Enumeration {
public static int d;
public static void main() throws Exception {
Read_INPUT_TXT_filter.loadData(); //讀取SQL資料
Read_distance.Read_distance(); //讀取距離矩陣DistanceMatrix
select_Neighborhood_rule1.main(); //根據 距離判斷 司機 分配哪些乘客
for(int i=0;i<select_Neighborhood_rule1.DP().size();i++){
for(int j=0;j<select_Neighborhood_rule1.DP().get(i).size();j++)
System.out.print(select_Neighborhood_rule1.DP().get(i).get(j)+" ");
System.out.println();}
for (d = 0; d < Read_INPUT_TXT_filter.getD(); d++) {
// if(select_Neighborhood.DP().get(d).size()==0) //如果司機沒有分配到乘客的話就跳到下一位司機
// continue;
System.out.println(" step1 開始");
step1_C.main(); //進行組合
System.out.println(" step1 結束");
System.out.println(" step2 開始");
step2_P.main(); //進行排列
System.out.println(" step2 OK");
System.out.println(" step3 開始");
step3_select_P.main(); //判斷先上車後下車順序
System.out.println(" step3 OK");
System.out.println(" step4 開始");
step4_select_time.main(); //判斷時間是否符合
System.out.println(" step4 OK");
System.out.println(" step5 開始");
step5_checkTXT.main(); //判斷第三、四步驟所對應的TXT
System.out.println(" step5 OK"); //並產生投標資料
}
System.out.println(" step6 開始");
step6_create_GA_input.main(); //將第五步產生投標資料統整為一個TXT
System.out.println(" step6 OK");
step7_check_Odj.main(); //將第五步產生投標資料統整為一個TXT
System.out.println(" step7 OK");
System.out.println("Enumeration程式結束");
}
}
|
Java
|
UTF-8
| 127 | 1.640625 | 2 |
[] |
no_license
|
package com.tengke.android.interfaces;
public interface ITabBarShowListener {
void showTabBar();
void hideTabBar();
}
|
Java
|
UTF-8
| 1,851 | 3.765625 | 4 |
[] |
no_license
|
/**
* this class describes the customer's information
* @author veronicaL5
*
*/
public class Customer {
private String secretLairLocation;
private String name;
private double evilFunds;
// stores values to variables (values are nothing really)
public Customer () {
secretLairLocation = "BMHS";
name = "Med";
evilFunds = 10000;
}
/**
* uses this. method
* @param secretLairLocation
* @param name
* @param evilFunds
*/
public Customer (String secretLairLocation, String name, double evilFunds) {
this.secretLairLocation = secretLairLocation;
this.name = name;
this.evilFunds = evilFunds;
}
/**
* returns the secret lair location, name, and how much evil funds are
*/
public String toString() {
return "Secret lair location: " + secretLairLocation + " " + "Name: " + name + " " + "Evil Funds: " + evilFunds;
}
/**
* uses this.method, adds funds to customer's evilFunds
* @param evilFunds
*/
public void addFunds (double evilFunds) {
this.evilFunds = evilFunds;
}
public String getsecretLairLocation() { // accessor
return secretLairLocation;
}
/**
* uses this. method
* @param secretlairLocation
*/
public void setsecretLairLocation(String secretlairLocation) {
this.secretLairLocation = secretLairLocation;
}
public String getname() { //accessor
return name;
}
/**
* uses this. method
* @param name
*/
public void setname(String name) {
this.name = name;
}
public double getevilFunds() { //accessor
return evilFunds;
}
/**
* uses this. method
* @param evilFunds
*/
public void setevilFunds(double evilFunds) {
this.evilFunds = evilFunds;
}
}
|
C++
|
UTF-8
| 639 | 3.171875 | 3 |
[] |
no_license
|
#include<iostream>
#include<algorithm>
using namespace std ;
int main()
{
int m ;
cin >> m ;
while(m--)
{
int i ;
int L,n ;
cin >> L >> n ;
int *ants = new int[n] ;
int max=0,min=0 ;
for(i=0 ; i<n ; ++i)
{
cin >> ants[i] ;
if( L-ants[i] > ants[i])
{
if( ants[i]>min )
min = ants[i] ;
}
else
{
if( L-ants[i] > min)
min = L-ants[i] ;
}
}
sort(ants,ants+n) ;
for(i=1;i<n;++i)
max += ants[i]-ants[i-1] ;
if( L-ants[n-1] > ants[0] )
max += L-ants[n-1] ;
else
max += ants[0] ;
cout << min << ' ' << max << endl ;
delete [] ants ;
}
return 0 ;
}
|
Markdown
|
UTF-8
| 3,020 | 3.328125 | 3 |
[] |
no_license
|
---
title: 顺序执行的异步操作:命名,Promise,任务,非队列
summary: 针对比特币的交易,涉及到收集UTXO,创建交易,发送交易,获取网络反馈,进入内存池,打包进入区块,等等一系列的异步操作。而每一步都需要等待之前的步骤完成
date: 2020-07-28 12:37:45
tags:
- Javascript
- node.js
---
针对比特币的交易,涉及到收集UTXO,创建交易,发送交易,获取网络反馈,进入内存池,打包进入区块,等等一系列的异步操作。而每一步都需要等待之前的步骤完成。
下面这个刚刚创建的库,可以帮助解决部分异步等待问题
[https://www.npmjs.com/package/named-promise-task](https://www.npmjs.com/package/named-promise-task)
顺序执行的异步操作,“异步任务队列“是一个需要记住的词。
可以先看一下[async.series](http://caolan.github.io/async/v3/docs.html#series)要解决的问题
```javascript
async.series([
function(callback) {
// do some stuff ...
callback(null, 'one');
},
function(callback) {
// do some more stuff ...
callback(null, 'two');
}
],
// optional callback
function(err, results) {
// results is now equal to ['one', 'two']
});
```
两个异步函数,在async.series的包裹下,可以顺序执行。
使用 Promise, 可以用 Promise.each 顺序执行一系列异步函数。
异步函数如果很复杂,包含很多步骤。我们称为一个任务。在我们做好的库中是这么用的
```javascript
const PromiseTask = require('named-promise-task')
const sleep = ( ms ) => new Promise( ( resolve, _ ) => setTimeout( () => resolve(), ms ) )
const that = 'outer'
const fetch = async ( p1 ) => {
await sleep( 1000 )
console.log( 'fetch', p1, this, that )
return 'fetch result'
}
async function fetch2 ( p1, p2 ) {
await sleep( 1000 )
//"this" is context
console.log( 'fetch2', p1, p2 )
}
const error = async ( ...values ) => {
await sleep( 1000 )
throw 'error'
}
async function test () {
const that = 'inner'
const upload = async ( p1, p2, p3 ) => {
await sleep( 1000 )
console.log( 'upload', p1, p2, p3 )
}
const manager = new PromiseTask( this, {
fetch: fetch,
fetch2: fetch2,
upload: upload,
error: error
} )
manager.addTask( 'fetch', 1 ).then( console.log )
manager.addTask( 'fetch2', 2, "str" )
manager.addTask( 'error', 3, "str", { options: 3 } ).then( console.log ).catch( console.error )
manager.addTask( 'upload', 4, "str", { options: 4 } )
await sleep( 1000 )
manager.addTask( 'fetch', 5, "str", { options: 5 } )
}
test()
```
每一个异步任务,随时追加到管理器中,顺序执行。不必使用数组,随时添加随时执行,前一个执行完,执行后一个。
比特币开发,涉及到非常多的技术细节,简单而且优美的解决方案是我们尽力去追求的。
在开发[Note.SV](https://noet.sv)时,我们创作这种优美
|
C++
|
GB18030
| 2,069 | 3.734375 | 4 |
[
"Apache-2.0"
] |
permissive
|
/************************************************************************/
/*
https://oj.leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/
Follow up for problem "Populating Next Right Pointers in Each Node".
What if the given tree could be any binary tree? Would your previous solution still work?
Note:
You may only use constant extra space.
For example,
Given the following binary tree,
1
/ \
2 3
/ \ \
4 5 7
After calling your function, the tree should look like:
1 -> NULL
/ \
2 -> 3 -> NULL
/ \ \
4-> 5 -> 7 -> NULL
*/
/************************************************************************/
#include <iostream>
#include <vector>
using namespace std;
struct TreeLinkNode {
int val;
TreeLinkNode *left, *right, *next;
TreeLinkNode(int x) : val(x), left(NULL), right(NULL), next(NULL) {}
};
class Solution {
public:
void connect(TreeLinkNode *root) {
if (root == NULL)
return;
TreeLinkNode* p = root;
TreeLinkNode* q = NULL; // ŵǰڵͬڵеһڵ㣬ʼΪ
TreeLinkNode* next_level = NULL; // ŸòڵĵһЧڵ㡣Чڵһεݹ鿪ʼʼڵ
// ÿһڵ㣬ٶڽڵѾɣֻҪҵӽڵ㿪ʼݹ鼴
while (p != NULL)
{
if (p->left != NULL)
{
if (q != NULL)
q->next = p->left;
q = p->left;
if (next_level == NULL)
next_level = p->left;
}
if (p->right != NULL)
{
if (q != NULL)
q->next = p->right;
q = p->right;
if (next_level == NULL)
next_level = p->right;
}
p = p->next;
}
connect(next_level);
}
};
int main()
{
TreeLinkNode *root = NULL;
root = new TreeLinkNode(1);
root->left = new TreeLinkNode(2);
root->right = new TreeLinkNode(3);
root->left->left = new TreeLinkNode(4);
root->left->right = new TreeLinkNode(5);
//root->right->right = new TreeLinkNode(7);
Solution solution;
solution.connect(root);
system("pause");
return 0;
}
|
Markdown
|
UTF-8
| 1,492 | 3.375 | 3 |
[] |
no_license
|
# Yuk mengenal Babel
Pernah nggak kamu mau menggunakan fitur yang keren dan simpel banget tapi browser nggak dukung?
Misalnya aja kamu mau menggunakan arrow function bersamaan dengan string literal di Javascript seperti contoh di bawah ini:
```javascript
let sebut = nama => console.log(`Halo ${nama}`)
```
Tapi sayang sih untuk browser-browser lawas yang nggak update-update, fitur itu nggak bisa digunakan. Jadi ya harus menggunakan kode seperti di bawah ini:
```javascript
"use strict";
var sebut = function sebut(nama) {
return console.log("Halo ".concat(nama));
};
```
Lebih ribet dan nggak indah ya? Tapi ya memang begitu sih kodenya kalau mau mendukung berbagai macam browser.
> Tapi untungnya sekarang ada Babel...
Dengan Babel, kamu bisa mengetik kode seperti biasa. Entah itu kamu menggunakan Ecmascript versi 2015, 2016, 2017, dan berbagai versi lainnya, Babel akan mengkonversinya menjadi format Javascript yang paling lawas sehingga kamu nggak perlu khawatir apakah kodemu bisa dijalankan atau nggak. Serahkan saja semua ke Babel.
## Contoh menggunakan Babel
### Input
```javascript
var sebut = nama => console.log(`Halo ${nama}`)
```
### Output
```javascript
"use strict";
var sebut = function sebut(nama) {
return console.log("Halo " + nama);
};
```
### Input
```javascript
console.log(2 ** 3)
```
### Output
```javascript
"use strict";
console.log(Math.pow(2, 3));
```
Untuk mulai menggunakan Babel, silahkan [kunjungi situsnya.](https://babeljs.io/)
|
Java
|
UTF-8
| 1,059 | 2.09375 | 2 |
[] |
no_license
|
package com.jrmf.domain;
import java.io.Serializable;
/**
* @author 种路路
* @version 创建时间:2017年11月23日 14:49:49
* 类说明 日结利息
*/
public class Interest implements Serializable{
/**
* @Fields serialVersionUID : TODO()
*/
private static final long serialVersionUID = 3787502829679696582L;
/**
* @Fields serialVersionUID : TODO()
*/
private String transAmount;//利息金额
private String createTime;//生成时间
private String userNo;//用户id
public String getTransAmount() {
return transAmount;
}
public void setTransAmount(String transAmount) {
this.transAmount = transAmount;
}
public String getCreateTime() {
return createTime;
}
public void setCreateTime(String createTime) {
this.createTime = createTime;
}
public String getUserNo() {
return userNo;
}
public void setUserNo(String userNo) {
this.userNo = userNo;
}
@Override
public String toString() {
return "Interest [transAmount=" + transAmount + ", createTime=" + createTime + ", userNo=" + userNo + "]";
}
}
|
Python
|
UTF-8
| 320 | 3.9375 | 4 |
[] |
no_license
|
#Pedirle al usuario que ingrese su nombre, horas trabajadas en el mes y precio por hora.
#Devolver lo que cobra esa persona
name = input("Ingrese su nombre\n")
hours = int(input("Ingrese cantidad de horas trabajadas\n"))
price = int(input("Ingrese precio por hora\n"))
print(name, "este mes vas a cobrar: ", price*hours)
|
Java
|
UTF-8
| 1,766 | 2.40625 | 2 |
[] |
no_license
|
package net.minemora.eggwarscore.extras;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import net.minemora.eggwarscore.config.Config;
public abstract class IExtraManager extends ExtraManager {
private Map<String, IExtra> iExtras = new HashMap<>();
protected IExtraManager(Config config, String path, String tableName, String columnName, boolean store) {
super(config, path, tableName, columnName, store);
}
@Override
public void load() {
if(getIExtraList().isEmpty()) {
return;
}
getExtras().clear();
getIExtras().clear();
loadIExtras();
for(String path : getIExtraList()) {
if(!getIExtras().containsKey(path)) {
continue;
}
IExtra iExtra = getIExtras().get(path);
getExtras().put(iExtra.getId(), iExtra);
}
for(Extra extra : getExtras().values()) {
if(extra.getUnlockType() == UnlockType.PERMISSION) {
if(getPermissionExtras().containsKey(extra.getPermission())) {
getPermissionExtras().get(extra.getPermission()).add(extra);
}
else {
getPermissionExtras().put(extra.getPermission(), new HashSet<Extra>());
getPermissionExtras().get(extra.getPermission()).add(extra);
}
}
}
}
public Set<String> getIExtraList() {
Set<String> IExtraList = new HashSet<>();
if (getConfig().getConfig().get(getPath()) != null) {
for (String id : getConfig().getConfig().getConfigurationSection(getPath()).getValues(false).keySet()) {
IExtraList.add(id);
}
}
return IExtraList;
}
public abstract void loadIExtras();
public Map<String, IExtra> getIExtras() {
return iExtras;
}
@Override
public Extra getNewExtra(int id) {
return null;
}
}
|
Java
|
UTF-8
| 1,843 | 2.3125 | 2 |
[] |
no_license
|
package co.com.rempe.impresiones.negocio.delegado;
import co.com.rempe.impresiones.negocio.constantes.ECodigoRespuesta;
import co.com.rempe.impresiones.negocio.respuesta.Respuesta;
import co.com.rempe.impresiones.persistencia.dao.ModoImpresionDAO;
import co.com.rempe.impresiones.persistencia.entidades.ModoImpresion;
import co.com.rempe.impresiones.persistencia.entidades.conexion.BDConexion;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
/**
*
* @author jhonjaider1000
*/
public class ModoImpresionDelegado {
private static ModoImpresionDelegado instancia = new ModoImpresionDelegado();
private ModoImpresionDelegado() {
}
public static ModoImpresionDelegado getInstancia() {
return instancia;
}
public Respuesta listarModoImpresion() {
EntityManager em;
Respuesta respuesta = new Respuesta();
try {
em = BDConexion.getEntityManager();
ModoImpresionDAO dao = new ModoImpresionDAO(em);
List<ModoImpresion> listaModoImpresion = dao.buscarTodos();
int codigo = (listaModoImpresion.isEmpty()) ? ECodigoRespuesta.VACIO.getCodigo() : ECodigoRespuesta.CORRECTO.getCodigo();
respuesta.setCodigo(codigo);
respuesta.setDatos(listaModoImpresion);
respuesta.setMensaje(ECodigoRespuesta.CORRECTO.getDescripcion());
return respuesta;
} catch (Exception ex) {
Logger.getLogger(ModoImpresionDelegado.class.getName()).log(Level.SEVERE, null, ex);
respuesta.setCodigo(ECodigoRespuesta.ERROR.getCodigo());
respuesta.setMensaje("Error al consultar los modos de impresión");
return respuesta;
}
}
}
|
C
|
UTF-8
| 1,264 | 2.625 | 3 |
[] |
no_license
|
// Copyright 2013 Mats Ekberg
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef INTSET_H
#define INTSET_H
#include <stdint.h>
typedef struct _Bucket {
uint64_t mask; // The OR of all values in this bucket
uint32_t used_slots;
uint32_t slot_count;
uint64_t* slots; // An array of size "slot_count" where the first "used_slots" contains valid data.
} Bucket;
typedef struct _IntSet {
uint32_t value_count;
uint32_t bucket_count; // Must be a power of 2
Bucket* buckets; // An array of bucket_count buckets
uint32_t magic;
} IntSet;
IntSet* create_intset(uint32_t bucket_count);
void add_intset(IntSet* intset, uint64_t int_to_add);
int contains_intset(IntSet* intset, uint64_t int_to_find);
void destroy_intset(IntSet* intset);
#endif
|
Markdown
|
UTF-8
| 2,611 | 3.078125 | 3 |
[] |
no_license
|
# CMPEN/EE 454: Computer Vision I Fall 2020
#### Course Description:
Introduction to computer vision topics, including image formation, feature extraction, matching, stereo, motion, tracking and object recognition.
#### Goal and Objectives:
- Introduce the fundamental problems of computer vision.
- Introduce the main concepts and techniques used to solve those problems.
- Enable students to implement vision algorithms.
- Enable students to make sense of the vision literature.
#### [Project 1 CNN for object recognition](Project1_CNN%20for%20object%20recognition)
This project was divided into different operational blocks while basic algorithm stages that include image normalization, ReLU, maxpool,convolution, fully connected and softmax. Then, putting all these together and implementing an 18-layer CNN to produce 10 object class. Finally, by collecting data from evaluation and passing debugging test, we can easily compare the accuracy of each algorithm and verify the expected results with ours from each layer.
#### [Project 2 Project2 triangluation](Project2_triangluation)
The goal of this project is to work on the implementation of the camera projection from 3D point to 2D point and inverse which from 2D point to 3D point and also triangulation and some matrix transformation. Doing this project let us have a clear understanding of 2D image coordinates and 3D world coordinates and the chain of transformations that make up the pinhole camera model. We create many different Matlab function in order to finish the task such as projecting 3D points into 2D pixel locations, triangulation back into a set of 3D scene point, reconstruction of 3D locations by triangular from two camera views, measure the 3D construction error and computing epistolary lines between the two views. All these team-work we have done not only enrich the experience in Matlab programming but also let us have a deeper understanding of the knowledge in the field of 3D and 2D image.
#### [Project 3 four simple motion detection](Project3_four%20simple%20motion%20detection)
The goal of this project is to implement the four simple motion detection algorithms described in
Lecture 24 and run them on short video sequences. As described (and pseudocoded) in Lecture
24, the four algorithms are:
- Simple Background Subtraction
- Simple Frame Differencing
- Adaptive Background Subtraction
- Persistent Frame Differencing
##### [Results](Project3_four%20simple%20motion%20detection/Team_(member%20%231%20Li)_(member%20%232%20Mao)_(member%20%233%20Wang)_(member%20%234%20Chen).mp4)
- 
|
Python
|
UTF-8
| 1,713 | 4.3125 | 4 |
[] |
no_license
|
"""
Find Pivot Index
Given an array of integers nums, write a method that returns the "pivot" index of this array.
We define the pivot index as the index where the sum of the numbers to the left of the index is equal to the sum of the numbers to the right of the index.
If no such index exists, we should return -1. If there are multiple pivot indexes, you should return the left-most pivot index.
Example 1:
Input:
nums = [1, 7, 3, 6, 5, 6]
Output: 3
Explanation:
The sum of the numbers to the left of index 3 (nums[3] = 6) is equal to the sum of numbers to the right of index 3.
Also, 3 is the first index where this occurs.
Example 2:
Input:
nums = [1, 2, 3]
Output: -1
Explanation:
There is no index that satisfies the conditions in the problem statement.
Note:
The length of nums will be in the range [0, 10000].
Each element nums[i] will be an integer in the range [-1000, 1000].
"""
"""
Prefix Sum, Get accumulative sum from left to right and vice versa
Time: O(N)
Space: O(1)
"""
class Solution:
def pivotIndex(self, nums: List[int]) -> int:
left_sum = []
curr = 0
for n in nums:
curr += n
left_sum.append(curr)
curr = 0
res = float('inf')
for idx, n in enumerate(nums[::-1]):
curr += n
if curr == left_sum[len(nums)-idx-1]:
res = min(res, len(nums)-idx-1)
return -1 if res == float('inf') else res
class Solution(object):
def pivotIndex(self, nums):
S = sum(nums)
leftsum = 0
for i, x in enumerate(nums):
if leftsum == (S - leftsum - x):
return i
leftsum += x
return -1
|
JavaScript
|
UTF-8
| 1,102 | 2.515625 | 3 |
[] |
no_license
|
const User = require('../models/user');
module.exports.getUsers = (req, res) => {
User.find({})
.then((users) => res.send({ data: users }))
.catch(() => res.status(500).send({ message: 'Произошла ошибка' }));
};
module.exports.getUsersId = (req, res) => {
User.find({ _id: req.params.userId })
.orFail(new Error('WrongId'))
.then((user) => res.send({ data: user }))
.catch((err) => {
if (err.message === 'WrongId') {
res.status(404).send({ message: 'Нет пользователя с таким id' });
} else { res.status(500).send({ message: 'Ошибка сервера' }); }
});
};
module.exports.createUser = (req, res) => {
const { name, about, avatar } = req.body;
User.create({ name, about, avatar })
.then((user) => res.send({ data: user }))
.catch((err) => {
if (err.name === 'ValidationError') {
res.status(400).send({ message: 'Переданы некорректные данные' });
} else {
res.status(500).send({ message: 'Ошибка сервера' });
}
});
};
|
Java
|
UTF-8
| 846 | 1.992188 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.tal.file.transform.common.rest.client;
/**
* RESTClient的配置信息类
*
* @author lazycathome
*
*/
public class RestConfig {
private static final String DEFAULT_USER_AGENT = "xes-en/0.1 RestClient/0.1";
private int socketTimeout = 10000;
private int connectTimeout = 10000;
private String userAgent = DEFAULT_USER_AGENT;
public int getSocketTimeout() {
return socketTimeout;
}
public void setSocketTimeout(int socketTimeout) {
this.socketTimeout = socketTimeout;
}
public int getConnectTimeout() {
return connectTimeout;
}
public void setConnectTimeout(int connectTimeout) {
this.connectTimeout = connectTimeout;
}
public String getUserAgent() {
return userAgent;
}
public void setUserAgent(String userAgent) {
this.userAgent = userAgent;
}
}
|
Markdown
|
UTF-8
| 5,346 | 3.296875 | 3 |
[] |
no_license
|
I needed to implement a keyboard autocompletion algorithm recently. Given a set of training words, it can provide autocomplete suggestions for a given typed word. For example, if trained on previously typed words like "the thing I like is the thing over there", typing the prefix "th" would result in "the", "thing", and "there" as possible autocompletions, with "the" and "there" weighted more heavily since they appear twice in the set of all previously typed words.
If you had to design this algorithm for a relatively resource-constrained device, like a smartphone keyboard, how would you do it? You would need something that could recommend autocompleted words fast - fast enough to keep up with a user typing - and not take up much memory with whatever data structure(s) you need to maintain stored autocompletions.
This repository is my attempt at a design for such a system. There are two main approaches:
- Use a dictionary (associative array) to map each possible word prefix to the set of possible autocompletions and their frequencies for that word prefix.
- Use a trie to efficiently store all prefixes and obtain autocompletions by traversing the subtrie depth-first for a given prefix.
The dictionary approach is simple to implement but I thought might require too much memory to be practical, so I tried another implementation with tries in order to compare performance and memory usage. I initially implemented the trie by storing children nodes for each node in a `Dictionary<char, Trie>`. I benchmarked the two approaches and found that this initial trie approach actually used more memory.
I then tried two different trie implementations, one using arrays and one using `List<T>`. I experienced much lower memory usage with both over the approach using `Dictionary<char, Trie>`.
The array approach builds an ad-hoc dictionary by creating an array of 26 tries and mapping each character to an index in the array. However, if a node only uses, say, 3 of those buckets, then 23 of the array elements are null and a waste of space. That's 92 bytes in 32-bit land I could've saved if I had a more compact representation.
I tried implementing a trie using a `List<T>` (internally backed by a resized array) of tries at each node to attempt to get a more compact trie. Without using an array index to store the character for the node, I needed a way to explicitly store the character for each node. This meant adding a `char` instance field to each trie. Hopefully the space saved by using a `List<T>`, I thought, would make up for the extra field in each trie. Unfortunately this wasn't the case, and it ends up using just barely more memory than the approach using an array to store tries for each node. Additionally, searching children using a `List<T>` means parts of trie traversal are now O(n) instead of O(1).
I benchmarked each approach on a copy of War and Peace by Leo Tolstoy obtained from [Project Gutenberg](http://www.gutenberg.org/ebooks/2600), which is about 568,000 words. The results are below.
```
Benchmarking PrefixDictionaryAutocompleteProvider
1526 ms to train war_and_peace.txt
5020 ms to get autocompletions 1000 times for 'th'.
Trained provider uses roughly 60603 KB.
Benchmarking TrieAutocompleteProvider<DictionaryTrie>
822 ms to train war_and_peace.txt
9908 ms to get autocompletions 1000 times for 'th'.
Trained provider uses roughly 78895 KB.
Benchmarking TrieAutocompleteProvider<ArrayTrie>
682 ms to train war_and_peace.txt
8720 ms to get autocompletions 1000 times for 'th'.
Trained provider uses roughly 18441 KB.
Benchmarking TrieAutocompleteProvider<ListTrie>
914 ms to train war_and_peace.txt
7863 ms to get autocompletions 1000 times for 'th'.
Trained provider uses roughly 20288 KB.
```
3071 autocompletions are returned for 'th' for War and Peace.
`PrefixDictionaryAutocompleteProvider` was the first approach I tried. It uses a whopping 60.6 MB to store its autocompletions. I tried `TrieAutocompleteProvider<DictionaryTrie>` next and thought it would use less memory, but it turns out it actually takes up about 30% more. It's a little faster to train, but it provides autocompletions more slowly too.
I tried `TrieAutocompleteProvider<ArrayTrie>` and `TrieAutocompleteProvider<ListTrie>` next. They both use much less memory, with `ArrayTrie` using the least. It's also the fastest to train. I switched to using an iterative traversal hoping for additional speed gains when finding autocompletions.
I declare `TrieAutocompleteProvider<ArrayTrie>` the all-around winner.
I'm not comfortable with the time it takes to find autocompletions for any of these approaches. For a single word instead of a thousand like in the benchmark above we're still only talking tens of milliseconds, but for slower phones this will probably stretch out to be far too long. Even tens of milliseconds is a perceptible and annoying delay.
Autocompleting a short word, such as "th" or even "t" will find many, many autocompletions. Most of these are not useful. A secondary data structure could be maintained for very short words that only keep the most likely autocompletions and do not contain the full set. As the word size increases, the algorithm could defer to the full set which will find them very quickly. I think this could ameliorate any concern about autocompletion retrieval time.
|
Python
|
UTF-8
| 660 | 3.734375 | 4 |
[] |
no_license
|
#multiple inheritance
class Base1:
def __init__(self):
self.i=10
self.j=20
print("inside base1 constructor")
class Base2:
def __init__(self):
self.x=11
self.y=21
print("inside base2 constructor")
class Derived(Base1,Base2):
def __init__(self):
Base1.__init__(self)
Base2.__init__(self)
self.a=20
self.b=30
print("inside Derived constructor")
def main():
dobj=Derived()
print(dobj.i)
print(dobj.j)
print(dobj.x)
print(dobj.y)
print(dobj.a)
print(dobj.b)
if __name__=="__main__":
main()
|
JavaScript
|
UTF-8
| 6,537 | 3.078125 | 3 |
[] |
no_license
|
function changeGraph(graphSource) {
var imgagecontainer = document.getElementById("GraphBase");
imgagecontainer.src = graphSource;
document.getElementById("GraphBase").innerHtml = imgagecontainer;
}
// function appendData(data) {
// var mainContainer = document.getElementById("testData");
// for (var i = 0; i < data.length; i++) {
// var div = document.createElement("div");
// div.innerHTML = 'DateTime: ' + data[i].DateTime + ' ' ;
// mainContainer.appendChild(div);
// }
// }
const json = (() => {
var json = null;
$.ajax({
async: false,
global: false,
url: "testdata.json", //Json file location
dataType: "json",
success: function (data) {
json = data;
},
});
return json;
})();
document.getElementById("windspeed").textContent = `${json.WindSpeed} knots`;
document.getElementById(
"winddirection"
).textContent = `${json.WindDirection} degrees`;
document.getElementById("airtemp").textContent = `${json.AirTemp} °F`;
document.getElementById(
"relativehumidity"
).textContent = `${json.RelativeHumidity}%`;
document.getElementById(
"relativebarometricpressure"
).textContent = `${json.RelativeBarometricPressure} Hg`;
document.getElementById(
"raincurrently"
).textContent = `${json.RainCurrently} inches`;
document.getElementById(
"watertemp2m"
).textContent = `${json.WaterTemp2m} °F 2 meters`;
document.getElementById(
"watertemp4m"
).textContent = `${json.WaterTemp4m} °F 4 meters`;
document.getElementById(
"watertemp7m"
).textContent = `${json.WaterTemp7m} °F 7 meters`;
document.getElementById(
"watertemp9m"
).textContent = `${json.WaterTemp9m} °F 9 meters`;
document.getElementById(
"watertemp11m"
).textContent = `${json.WaterTemp11m} °F 11 meters`;
document.getElementById(
"dissolvedoxygen2m"
).textContent = `${json.DissolvedOxygen2m} mg/L 2 meters`;
document.getElementById(
"dissolvedoxygen5m"
).textContent = `${json.DissolvedOxygen5m} mg/L 5 meters`;
document.getElementById(
"dissolvedoxygen8m"
).textContent = `${json.DissolvedOxygen8m} mg/L 8 meters`;
document.getElementById(
"dissolvedoxygen11m"
).textContent = `${json.DissolvedOxygen11m} mg/L 11 meters`;
document.getElementById("Time").innerHTML = json.DateTime;
// document.querySelector('.testData').textContent = json.AirTemp;
$(document).ready(function () {
$(".gauge-wrap").simpleGauge({
width: "200",
hueLow: "1",
hueHigh: "128",
saturation: "100%",
lightness: "50%",
gaugeBG: "#1b1b1f",
parentBG: "#323138",
});
});
const gaugeElement1 = document.querySelector(".gauge1");
function setGauge1Value(gauge, value) {
gauge.querySelector(".gauge__fill1").style.transform = `rotate(${
value /
-2 /*trial and error figured out that negative numbers flipped the bar to be what I needed for this */
}turn)`;
gauge.querySelector(
".gauge__cover1"
).textContent = `${json.Chlorophyll2m}µg/L`;
}
setGauge1Value(gaugeElement1, json.Chlorophyll2m);
const gaugeElement2 = document.querySelector(".gauge2");
function setGauge2Value(gauge, value) {
gauge.querySelector(".gauge__fill2").style.transform = `rotate(${
value / -23 /*trial and error number */
}turn)`;
gauge.querySelector(
".gauge__cover2"
).textContent = `${json.Phycocyanin2m}Cells/mL`;
}
setGauge2Value(gaugeElement2, json.Phycocyanin2m);
/*https://github.com/jamesgpearce/compios5/blob/master/index.html
window.addEventListener('load', function() {
var compass = document.body.appendChild(document.createElement('article'));
compass.id='compass';
var spinner = compass.appendChild(document.createElement('article'));
spinner.id='spinner';
var pin = spinner.appendChild(document.createElement('article'));
pin.id='pin';
for (var degrees=0, degree; degrees<360; degrees+=30) {
degree = spinner.appendChild(document.createElement('label'));
degree.className='degree';
degree.innerText = degrees;
degree.style.webkitTransform = 'rotateZ(' + degrees + 'deg)'
}
['N', 'NE', 'E', 'SE', 'S', 'SW', 'W', 'NW'].forEach(function(label, index) {
var main = ((index % 2)?'':' main');
point = spinner.appendChild(document.createElement('label'));
point.className='point' + main;
point.innerText = label;
point.style.webkitTransform = 'rotateZ(' + (index * 45) + 'deg)'
arrow = spinner.appendChild(document.createElement('div'));
arrow.className='arrow' + main;
arrow.style.webkitTransform = 'rotateZ(' + (index * 45) + 'deg)'
});
var lastHeading = 0;
window.addEventListener('deviceorientation', function(e) {
var heading = e.webkitCompassHeading + window.orientation;
if (Math.abs(heading - lastHeading)<180) {
spinner.style.webkitTransition = 'all 0.2s ease-in-out';
} else {
spinner.style.webkitTransition = 'none';
}
spinner.style.webkitTransform = 'rotateZ(-' + heading + 'deg)';
lastHeading = heading;
}, false);
document.body.addEventListener('touchstart', function(e) {
e.preventDefault();
}, false);
window.addEventListener('orientationchange', function(e) {
window.scrollTo(0,1);
}, false);
setTimeout(function () {window.scrollTo(0,1);}, 0);
}, false);
*/
/*https://github.com/rheh/HTML5-canvas-projects/tree/master/compass*/
// Global variable
var img = null,
needle = null,
ctx = null,
degrees = 0;
function clearCanvas() {
// clear canvas
ctx.clearRect(0, 0, 200, 200);
}
function draw() {
clearCanvas();
// Draw the compass onto the canvas
ctx.drawImage(img, 0, 0);
// Save the current drawing state
ctx.save();
// Now move across and down half the
ctx.translate(100, 100);
// Rotate around this point
ctx.rotate(degrees * (Math.PI / 180));
// Draw the image back and up
ctx.drawImage(needle, -100, -100);
// Restore the previous drawing state
ctx.restore();
// Increment the angle of the needle by 5 degrees
degrees += 5;
}
function imgLoaded() {
// Image loaded event complete. Start the timer
setInterval(draw, 100);
}
function init() {
// Grab the compass element
var canvas = document.getElementById("compass");
// Canvas supported?
if (canvas.getContext("2d")) {
ctx = canvas.getContext("2d");
// Load the needle image
needle = new Image();
needle.src = "needle.png";
// Load the compass image
img = new Image();
img.src = "compass.png";
img.onload = imgLoaded;
} else {
alert("Canvas not supported!");
}
}
|
Go
|
UTF-8
| 11,218 | 2.65625 | 3 |
[
"Apache-2.0"
] |
permissive
|
/**
Grom
Copyright 2013 Sergio de Mingo
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package main
import (
"encoding/json"
"errors"
"fmt"
"image"
"image/jpeg"
"io"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"text/template"
"time"
)
var months = []string{
"Null",
"Enero",
"Febrero",
"Marzo",
"Abril",
"Mayo",
"Junio",
"Julio",
"Agosto",
"Septiembre",
"Octubre",
"Noviembre",
"Diciembre"}
type Articles []*Article
type Blog struct {
Dir string
ThemeDir string
Info BlogInfo
Posts Articles
Nposts int
Statics Articles
Nstatics int
Years []bool
Months []string
Selected int
BlogTags Tags //all tags
TagSelected Tag
DebugServer *WebSockServer
}
type BlogInfo map[string]string
func CreateBlog(dir string, themes string) (*Blog, error) {
b := new(Blog)
b.Info = make(BlogInfo)
b.Info["Name"] = "My new Blog"
b.Info["Owner"] = "Grom"
b.Info["Subtitle"] = "I wanna be Grom!!"
b.Info["Theme"] = "default"
b.Info["Url"] = "http://yourdomain.com"
b.Years = make([]bool, 100)
b.Months = months
b.Posts = make([]*Article, 500)
b.Nposts = 0
jb, err := json.MarshalIndent(b.Info, " ", " ")
if err != nil {
return nil, err
}
b.Dir = dir
b.ThemeDir = b.Dir + "themes/" + b.Info["Theme"]
os.Mkdir(dir, 0755)
os.Mkdir(dir+"static", 0755)
os.Mkdir(dir+"post", 0755)
os.Mkdir(dir+"html", 0755)
os.Mkdir(dir+"img", 0755)
os.Mkdir(dir+"img/thumbs", 0755)
err = createDefaultTheme(dir, themes)
if err != nil {
return nil, err
}
err = ioutil.WriteFile(dir+"config.json", jb, 0644)
if err != nil {
return nil, err
}
return b, nil
}
func createDefaultTheme(bdir string, tdir string) error {
os.Mkdir(bdir+"themes", 0755)
os.Mkdir(bdir+"themes/default", 0755)
fd, err := os.Open(tdir + "themes/default")
if err != nil {
return errors.New("Grom default theme not found\n")
}
names, _ := fd.Readdirnames(-1)
for i := range names {
f1, err := os.Open(tdir + "themes/default/" + names[i])
f2, err := os.Create(bdir + "themes/default/" + names[i])
io.Copy(f2, f1)
if err != nil {
return err
}
}
return nil
}
func LoadBlog(dir string) *Blog {
jb, err := ioutil.ReadFile(dir + "config.json")
if err != nil {
fmt.Println(err)
return nil
}
info := make(BlogInfo)
err = json.Unmarshal(jb, &info)
b := new(Blog)
b.Info = info
b.Dir = dir
b.ThemeDir = b.Dir + "themes/" + b.Info["Theme"]
b.Years = make([]bool, 100)
b.Months = months
b.Posts = make([]*Article, 500)
b.Nposts = 0
b.loadAllPosts()
b.loadAllStatics()
return b
}
func (blog *Blog) loadFilePost(fp string, fi os.FileInfo, err error) error {
if err != nil {
fmt.Println(err)
return nil
}
if fi.IsDir() {
return nil
}
//if !strings.HasSuffix(fp, ".org") {
// return nil // file is not org
//
a, err := ParseArticle(fp)
if a == nil {
fmt.Println("Error parsing " + err.Error())
return nil
}
// Array limits not controlled
blog.Posts[blog.Nposts] = a
blog.Nposts++
if a.Date.Year() >= 2000 {
blog.Years[a.Date.Year()-2000] = true
}
return nil
}
func (blog *Blog) loadAllPosts() {
err := filepath.Walk(blog.Dir+"post", blog.loadFilePost)
if err != nil {
fmt.Println(err)
}
blog.Posts = blog.Posts[:blog.Nposts]
sort.Sort(ByDate{blog.Posts})
}
func (blog *Blog) loadAllStatics() error {
fd, err := os.Open(blog.Dir + "static")
if err != nil {
return err
}
statics, _ := fd.Readdirnames(-1)
blog.Statics = make([]*Article, len(statics))
blog.Nstatics = 0
for i := range statics {
a, _ := ParseArticle(blog.Dir + "static/" + statics[i])
if a == nil {
return errors.New("Error parsing " + statics[i])
}
if a != nil {
/*
Array limits not controlled
*/
blog.Statics[i] = a
blog.Nstatics++
}
}
return err
}
func (blog *Blog) AddArticle(title string) error {
d := time.Now()
year := d.Format("2006")
month := d.Format("01")
a, _ := NewArticle(title)
file := blog.Dir + "post/" + year + "/" + month + "-" + title + ".md"
err := a.WriteNewFile(file)
if err != nil {
return err
}
return nil
}
func (blog *Blog) AddStaticPage(title string) error {
a, _ := NewArticle(title)
file := blog.Dir + "static/" + title + ".md"
err := a.WriteNewFile(file)
if err != nil {
return err
}
return nil
}
func (blog *Blog) Serve() error {
//http.HandleFunc("/ws", blog.DebugServer.WSHandler)
//fmt.Println("Añado el handler del websocket")
http.ListenAndServe(":9999", http.FileServer(http.Dir(blog.Dir)))
return nil
}
func (blog *Blog) Build() error {
fmt.Printf("Building tags ... ")
err := blog.makeTags()
if err != nil {
return err
}
fmt.Printf("\n")
fmt.Printf("Building posts ... ")
for i := range blog.Posts {
a := blog.Posts[i]
if a != nil {
err := blog.makeArticle(a)
if err != nil {
return err
}
}
}
fmt.Printf("\n")
fmt.Printf("Building statics ... ")
for i := range blog.Statics {
a := blog.Statics[i]
if a != nil {
err := blog.makeStatic(a)
if err != nil {
return err
}
}
}
fmt.Printf("\n")
fmt.Printf("Building index ... ")
err = blog.makeIndex()
if err != nil {
return err
}
fmt.Printf("\n")
fmt.Printf("Building archive ... ")
err = blog.makeArchive()
if err != nil {
return err
}
fmt.Printf("\n")
fmt.Printf("Building images and thumbs ... ")
err = blog.makeThumbs()
if err != nil {
return err
}
fmt.Printf("\n")
fmt.Printf("Building blog utils ... ")
err = blog.BuildUtils()
if err != nil {
return err
}
fmt.Printf("\n")
return nil
}
func (blog *Blog) BuildUtils() error {
err := makeSitemap(blog)
if err != nil {
return err
}
err = makeRSSFeed(blog)
if err != nil {
return err
}
return nil
}
func (blog *Blog) GetArticlesByDate(year int, month int) []*Article {
a := make([]*Article, 100)
n := 0
smonth := ""
year = year + 2000
syear := fmt.Sprintf("%d", year)
if month < 10 {
smonth = fmt.Sprintf("0%d", month)
} else {
smonth = fmt.Sprintf("%d", month)
}
for p := 0; p < blog.Nposts; p++ {
if (blog.Posts[p].GetYear() == syear) &&
strings.HasPrefix(blog.Posts[p].GetValidId(), smonth) {
a = append(a, blog.Posts[p])
n++
}
}
if n == 0 {
return nil
}
return a
}
func (blog *Blog) GetLastArticles() []*Article {
var max string
var ok bool
if max, ok = blog.Info["PostPerPage"]; !ok {
panic(errors.New("No PostPerPage defined in config.json"))
}
max_posts, err := strconv.ParseInt(max, 10, 0)
if err != nil {
panic(errors.New("Bad value for PostPerPage defined in config.json"))
}
n_post_in_index := len(blog.Posts)
if n_post_in_index > int(max_posts) {
n_post_in_index = int(max_posts)
}
return blog.Posts[:n_post_in_index]
}
func (blog *Blog) GetSelectedPost() *Article {
return blog.Posts[blog.Selected]
}
func (blog *Blog) GetSelectedStatic() *Article {
return blog.Statics[blog.Selected]
}
func (blog *Blog) GetHTMLContent(a *Article) string {
return Markdown2HTML(a.Content, blog.Info["Url"])
}
func (blog *Blog) GetPopularTags() Tags {
popular := make(TagsSlice, 0, len(blog.BlogTags))
for _, v := range blog.BlogTags {
popular = append(popular, v)
}
sort.Sort(sort.Reverse(popular))
popular = popular[:POPULAR_TAGS_TO_SHOW]
popularMap := make(Tags)
for i := range popular {
n_name := normalizeURL(popular[i].Name)
popularMap[n_name] = popular[i]
}
return popularMap
}
/*
Mecanismo de ordenación de los arrays de artículos
*/
func (s Articles) Len() int { return len(s) }
func (s Articles) Swap(i, j int) { s[i], s[j] = s[j], s[i] }
type ByDate struct{ Articles }
func (s ByDate) Less(i, j int) bool {
a := s.Articles[i]
b := s.Articles[j]
if (a == nil) || (b == nil) {
return false
}
return s.Articles[i].Date.After(s.Articles[j].Date)
}
func (blog *Blog) makeIndex() error {
f, err := os.Create(blog.Dir + "index.html")
if err != nil {
return err
}
t := template.New("main")
_, err = t.ParseFiles(blog.ThemeDir+"/main.html",
blog.ThemeDir+"/last-posts.html")
if err != nil {
return err
}
err = t.ExecuteTemplate(f, "main", blog)
if err != nil {
return err
}
return nil
}
func (blog *Blog) makeStatic(a *Article) error {
f, err := os.Create(blog.Dir + "html/static-" + a.Id + ".html")
if err != nil {
return err
}
s := -1
// search the index of the article
for i := range blog.Statics {
if a.Id == blog.Statics[i].Id {
s = i
break
}
}
if s < 0 {
return errors.New("Bad static to build")
}
blog.Selected = s
t := template.New("main")
_, err = t.ParseFiles(blog.ThemeDir+"/main.html",
blog.ThemeDir+"/static.html")
if err != nil {
return err
}
t.ExecuteTemplate(f, "main", blog)
return nil
}
func (blog *Blog) makeArticle(a *Article) error {
err := os.MkdirAll(blog.Dir+"html/"+a.GetYear(), 0755)
if err != nil {
return err
}
f, err := os.Create(blog.Dir + "html/" + a.GetYear() + "/" + a.GetValidId() + ".html")
if err != nil {
return err
}
s := -1
// search the index of the article
for i := range blog.Posts {
if (blog.Posts[i] != nil) && (a.Id == blog.Posts[i].Id) {
s = i
break
}
}
if s < 0 {
return errors.New("Bad article to build")
}
blog.Selected = s
t := template.New("main")
_, err = t.ParseFiles(blog.ThemeDir+"/main.html",
blog.ThemeDir+"/post.html")
if err != nil {
return err
}
t.ExecuteTemplate(f, "main", blog)
return nil
}
func (blog *Blog) makeTags() error {
return buildTags(blog)
}
func (blog *Blog) makeArchive() error {
f, err := os.Create(blog.Dir + "html/archive.html")
if err != nil {
return err
}
t := template.New("main")
_, err = t.ParseFiles(blog.ThemeDir+"/main.html",
blog.ThemeDir+"/archive.html")
if err != nil {
return err
}
err = t.ExecuteTemplate(f, "main", blog)
if err != nil {
return err
}
return nil
}
func (blog *Blog) makeThumbs() error {
fd, err := os.Open(blog.Dir + "img")
if err != nil {
return err
}
imgs, _ := fd.Readdirnames(-1)
for i := range imgs {
if imgs[i] != "thumbs" {
blog.createThumb(imgs[i])
}
}
return nil
}
func (blog *Blog) createThumb(file string) error {
var img1 image.Image
var delta float32
_, err := os.Stat(blog.Dir + "img/thumbs/" + file)
if err == nil {
return nil // the thumb exits. exit
}
fimg, err := os.Open(blog.Dir + "img/" + file)
img1, err = jpeg.Decode(fimg)
if err != nil {
return err
}
r := img1.Bounds()
s := r.Size()
if s.X > 500 {
delta = float32(s.X) / 500.0
} else {
delta = 1.0
}
nx := float32(s.X) / delta
ny := float32(s.Y) / delta
img2 := Resize(img1, r, int(nx), int(ny))
fimg2, _ := os.Create(blog.Dir + "img/thumbs/" + file)
jpeg.Encode(fimg2, img2, &jpeg.Options{jpeg.DefaultQuality})
return nil
}
|
C
|
UTF-8
| 1,765 | 2.78125 | 3 |
[
"MIT"
] |
permissive
|
/*********************************************************************
*
* Montagne Fractale decoupage.h
* -----------------
* 02.01.10
*
* Bertrand CHAZOT
*
*********************************************************************/
#ifndef DECOUPAGE_H
#define DECOUPAGE_H
#include "general.h"
Point3d** decoupPlan(int nbIterations, Point3d min, Point3d max);
/*
* Fonction qui crée et initialise la matrice plan, puis qui appelle la fonction
* decoupe.
* */
void decoupe(Point3d **plan,int minI, int maxI,int minJ, int maxJ);
/*
* Fonction récursive qui découpe le plan et attribue une hauteur à chaque point
* */
Point3d pointDeSeg(Point3d A,Point3d B);
/*
* Elle retourne un point situé sur le segment [A,B], à proximité du milieu du
* segment (décalé d'une distance aléatoire, dépendant de conf)
* */
Point3d pointDeQuad(Point3d A,Point3d B,Point3d D);
/*
* Retourne le centre de gravité de ABCD (approximé par un parallélogramme)
* légèrement déplacé
* */
GLfloat hauteur(Point3d a, Point3d b);
/*
* Retourne une hauteur z dépendant de la hauteur de A et B, de la pente de AB,
* de conf et d'une variable aléatoire.
* */
GLfloat hauteurCentre(Point3d a, Point3d b, Point3d c, Point3d d);
/*
* Retourne une hauteur z qui dépend de la surface de ABCD,de la moyenne des
* hauteurs de A, B, C, D, de conf ainsi que d'une variable aléatoire
* */
GLfloat surface(Point3d a, Point3d b, Point3d c, Point3d d);
GLfloat aireTriangle(Point3d a, Point3d b, Point3d c);
GLfloat borne(GLfloat a);
/*
* Vérifie que a est dans [0,conf.hauteurMax], le modifie sinon
* */
#endif
|
Shell
|
UTF-8
| 1,609 | 2.703125 | 3 |
[] |
no_license
|
# include global config
source ../_buildscripts/${current_repo}-${_arch}-cfg.conf
pkgname=kamoso
pkgver=${_kdever}
pkgrel=1
pkgdesc="Kamoso is an application to take pictures and videos out of your webcam."
url="https://userbase.kde.org/Kamoso"
arch=('x86_64')
license=('GPL' 'LGPL' 'FDL')
depends=('kconfig' 'kconfigwidgets' 'kcompletion' 'kwidgetsaddons' 'kio' 'solid'
'systemd' 'gst-plugins-bad' 'gst-plugins-good'
'phonon-qt5' 'qt5-graphicaleffects' 'qt5-quickcontrols' 'purpose')
makedepends=('extra-cmake-modules' 'kdoctools' 'boost')
groups=('multimedia')
source=("$_mirror/${pkgname}-${_kdever}.tar.xz")
md5sums=(`grep ${pkgname}-${_kdever}.tar.xz ../kde-sc.md5 | cut -d" " -f1`)
prepare() {
cd $pkgname-${pkgver}
# fix for building with gstreamer 1.14 https://bugs.kde.org/show_bug.cgi?id=392245
#sed -i -e 's|kamoso-qt5videosink|kamosoqt5videosink|' src/elements/CMakeLists.txt
}
build() {
mkdir -p build
cd build
cmake ../${pkgname}-${pkgver} \
-DCMAKE_BUILD_TYPE=Release \
-DCMAKE_INSTALL_PREFIX=/usr \
-DKDE_INSTALL_LIBDIR=lib \
-DKDE_INSTALL_PLUGINDIR=/usr/lib/qt5/plugins \
-DKDE_INSTALL_USE_QT_SYS_PATHS=ON \
-DBUILD_TESTING=OFF
make
}
package() {
cd build
make DESTDIR=${pkgdir} install
#sed -i 's|KAlgebra|Kamoso|' ${pkgdir}/usr/share/applications/org.kde.kamoso.desktop
#sed -i 's|Exec=kamoso|Exec=kamoso -qwindowtitle %c|' ${pkgdir}/usr/share/applications/org.kde.kamoso.desktop
#sed -i 's|Categories=Qt;KDE;Multimedia|Categories=Qt;KDE;AudioVideo;|' ${pkgdir}/usr/share/applications/org.kde.kamoso.desktop
}
|
TypeScript
|
UTF-8
| 878 | 2.703125 | 3 |
[] |
no_license
|
import { IUserState } from './userState'
import { IHandler, IAction } from './../../interfaces/Context'
import { ActionTypes } from './../actionTypes'
const handlers: IHandler = {
[ActionTypes.GET_USERS]: (state: IUserState, action: IAction): IUserState => ({...state, users: action.payload, loading: false}),
[ActionTypes.GET_USER]: (state: IUserState, action: IAction): IUserState => ({...state, user: action.payload, loading: false}),
[ActionTypes.CLEAR_USER]: (state: IUserState, action: IAction): IUserState => ({...state, user: null}),
[ActionTypes.SET_USER_LOADING]: (state: IUserState): IUserState => ({...state, loading: true}),
DEFAULT: (state: IUserState): IUserState => state
}
export const userReducer = (state: IUserState, action: IAction) => {
const handler = handlers[action.type] || handlers.DEFAULT
return handler(state, action)
}
|
JavaScript
|
UTF-8
| 3,660 | 2.5625 | 3 |
[] |
no_license
|
const { assert } = require('chai');
const News = artifacts.require("News"); // dependencies
// connect smart contract
require('chai') // chai
.use(require('chai-as-promised'))
.should()
contract('News', ([deployer, author, tipper]) => {
let news
before(async () => {
news = await News.deployed()
})
describe('deployment', async () => {
it('deploys successfully', async () => {
const address = news.address
assert.notEqual(address, 0x0)
assert.notEqual(address, '')
assert.notEqual(address, null)
assert.notEqual(address, undefined)
})
it('has a name', async () => {
const name = await news.name()
assert.equal(name, "ArtKDev development")
})
})
describe('posts', async () => {
let result, postCount
before(async () => {
result = await news.createPost('This is my first post', { from: author})
postCount = await news.postCount()
})
it('creates posts', async () => {
const event = await result.logs[0].args
// success
assert.equal(postCount, 1)
assert.equal(event.id.toNumber(), postCount.toNumber(), 'id is correct')
assert.equal(event.content, 'This is my first post', 'content is correct')
assert.equal(event.tipAmount, '0', 'tipAmount is correct')
assert.equal(event.author, author, 'author is correct')
await news.createPost('', { from: author}).should.be.rejected;
})
it('lists posts', async () => {
const post = await news.posts(postCount);
// success
assert.equal(post.id.toNumber(), postCount.toNumber(), 'id is correct')
assert.equal(post.content, 'This is my first post', 'content is correct')
assert.equal(post.tipAmount, '0', 'tipAmount is correct')
assert.equal(post.author, author, 'author is correct')
})
it('allows users to tip posts', async () => {
// Track the author balance before purchase
let oldAuthorBalance
oldAuthorBalance = await web3.eth.getBalance(author)
oldAuthorBalance = new web3.utils.BN(oldAuthorBalance)
result = await news.tipPost(postCount, { from :tipper, value: web3.utils.toWei('1', 'Ether')})
const event = await result.logs[0].args
// success
assert.equal(event.id.toNumber(), postCount.toNumber(), 'id is correct')
assert.equal(event.content, 'This is my first post', 'content is correct')
assert.equal(event.tipAmount, web3.utils.toWei('1', 'Ether'), 'tipAmount is correct')
assert.equal(event.author, author, 'tipper is correct')
// Check that author received funds
let newAuthorBalance
newAuthorBalance = await web3.eth.getBalance(author)
newAuthorBalance = new web3.utils.BN(newAuthorBalance)
let tipAmount
tipAmount = web3.utils.toWei('1', 'Ether')
tipAmount = new web3.utils.BN(tipAmount)
const expectedBalance = oldAuthorBalance.add(tipAmount)
// success
assert.equal(expectedBalance.toString(), newAuthorBalance.toString(), 'Amount is correct')
// Failure : Tries to tip a post that does not exist
await news.tipPost(99, { from :tipper, value: web3.utils.toWei('1', 'Ether')}).should.be.rejected;
})
})
})
|
Python
|
UTF-8
| 225 | 2.796875 | 3 |
[] |
no_license
|
import sys
output = open("locus.stripped.txt", 'w')
with open(sys.argv[1]) as file:
i = 0
for line in file:
line = line.split()
if i>0:
output.write(line[1][1:line[1].find(":")]+"\n")
i += 1
print "loci stripped"
|
SQL
|
UTF-8
| 1,110 | 3.859375 | 4 |
[] |
no_license
|
SET PAGESIZE 70;
SET LINESIZE 100;
clear col
TTITLE LEFT ' Zoznam klientov najcastejsie vyuzivajucich bankomaty podla miest';
COLUMN nazov_mesto HEADING 'Mesto' format A20;
COLUMN meno HEADING 'Meno' format A20;
COLUMN priezvisko HEADING 'Priezvisko' format A20;
COLUMN pocet HEADING 'Pocet';
select nazov_mesto, meno, priezvisko, pocet from (
select m.nazov_mesto, osoba.meno, osoba.priezvisko, count(*) as pocet
from mesto m join adresa on(m.kod_mesto=adresa.kod_mesto)
join osoba on(adresa.id_adresa=osoba.id_adresa)
join zakaznik on(osoba.rod_cislo=zakaznik.rod_cislo)
join transakcie on(osoba.rod_cislo=transakcie.rod_cislo)
group by m.nazov_mesto, osoba.meno, osoba.priezvisko, m.kod_mesto
having count(*)=(
SELECT max(count(*)) AS pocet
from mesto m2 join adresa on(m2.kod_mesto=adresa.kod_mesto)
join osoba on(adresa.id_adresa=osoba.id_adresa)
join zakaznik on(osoba.rod_cislo=zakaznik.rod_cislo)
join transakcie on(osoba.rod_cislo=transakcie.rod_cislo)
WHERE m2.kod_mesto = m.kod_mesto
GROUP BY m2.nazov_mesto, osoba.meno, osoba.priezvisko, m2.kod_mesto
)
order by pocet desc
)
;
|
Markdown
|
UTF-8
| 1,524 | 2.65625 | 3 |
[] |
no_license
|
# hyper-selenium
⚠️ ⚠️ **Go Noob Warning:** This is my first ever Go project. Please expect to see a lot of stupid noobish unidiomatic Go code in here. PRs welcome. ⚠️ ⚠️
## Architecture
<img src="https://docs.google.com/drawings/d/e/2PACX-1vSmoU3tAQIhgiMLSLD0Ut-XUBv41VqJdVbCElUL3bEAusVq3QaoORLnTXQGVsxzqx9X6ejYj29KSCCt/pub?w=899&h=223">
- **Local machine:** The machine running the E2E test.
- Contains the test scripts.
- Not powerful enough to run all of these tests at the same time.
- **Docker container:** This container runs Selenium.
- Can be spawned on-demand. e.g. 20 containers are spawned to run 20 tests simultaneously.
- For cost-effectiveness, should be billed per-second. [Hyper.sh](https://hyper.sh/) offers this.
- It might not have its own IP address, so a secure tunnel must be employed.
- **SSH server:** This server allows the Local machine and Docker container to communicate with each other.
TODO talk about agent and client.
## Development
### Agent
Building Docker container
```
docker build -t hyper-selenium-agent .
```
Running
```
docker run -ti --rm hyper-selenium-agent
```
### Local development workflow
Running a central ssh server:
```
docker run -d -p 2222:22 --name hyper-selenium-sshd rastasheep/ubuntu-sshd:18.04
```
Compiling and running the agent:
```
./scripts/run-agent-dev.sh --ssh-remote=192.168.2.62:2222 --id=test
```
Running the client:
```
go run ./cmd/hyper-selenium-client/main.go --ssh-remote=192.168.2.62:2222 bash
```
|
Java
|
UTF-8
| 1,069 | 2.375 | 2 |
[] |
no_license
|
package com.example.ismai.projectbase.Models;
public class mdlTourList {
private String bolge;
private String pax;
private String tarih;
private String tur;
private boolean selected;
public mdlTourList(String bolge, String pax, String tarih, String tur) {
this.bolge = bolge;
this.pax = pax;
this.tarih = tarih;
this.tur = tur;
}
public String getBolge() {
return bolge;
}
public void setBolge(String bolge) {
this.bolge = bolge;
}
public String getPax() {
return pax;
}
public void setPax(String pax) {
this.pax = pax;
}
public String getTarih() {
return tarih;
}
public void setTarih(String tarih) {
this.tarih = tarih;
}
public String getTur() {
return tur;
}
public void setTur(String tur) {
this.tur = tur;
}
public void setSelected(boolean selected) {
this.selected = selected;
}
public boolean isSelected() {
return selected;
}
}
|
Java
|
UTF-8
| 397 | 2.359375 | 2 |
[] |
no_license
|
package lanami.example.springsecurity.app.domain;
import java.io.Serializable;
/**
* @author lanami
* @date 2016-09-06
*/
public enum UserRoleType implements Serializable {
USER("USER"),
MANAGER ("MANAGER"),
ADMIN ("ADMIN");
String value;
private UserRoleType(String value){
this.value = value;
}
public String getValue(){
return value;
}
}
|
Python
|
UTF-8
| 6,005 | 2.53125 | 3 |
[] |
no_license
|
import dash_vtk
import numpy as np
import dash
import dash_html_components as html
try:
# v9 and above
from vtkmodules.util.numpy_support import vtk_to_numpy
from vtkmodules.vtkFiltersGeometry import vtkGeometryFilter
except:
# v8.1.2 and below
print("Can't import vtkmodules. Falling back to importing vtk.")
from vtk.util.numpy_support import vtk_to_numpy
from vtk.vtkFiltersGeometry import vtkGeometryFilter
# Numpy to JS TypedArray
to_js_type = {
"int8": "Int8Array",
"uint8": "Uint8Array",
"int16": "Int16Array",
"uint16": "Uint16Array",
"int32": "Int32Array",
"uint32": "Uint32Array",
"int64": "Int32Array",
"uint64": "Uint32Array",
"float32": "Float32Array",
"float64": "Float64Array",
}
def to_mesh_state(dataset, field_to_keep=None, point_arrays=None, cell_arrays=None):
"""Expect any dataset and extract its surface into a dash_vtk.Mesh state property"""
if dataset is None:
return None
if point_arrays is None:
point_arrays = []
if cell_arrays is None:
cell_arrays = []
# Make sure we have a polydata to export
polydata = None
if dataset.IsA("vtkPolyData"):
polydata = dataset
else:
extractSkinFilter = vtkGeometryFilter()
extractSkinFilter.SetInputData(dataset)
extractSkinFilter.Update()
polydata = extractSkinFilter.GetOutput()
if polydata.GetPoints() is None:
return None
# Extract mesh
points = vtk_to_numpy(polydata.GetPoints().GetData())
verts = (
vtk_to_numpy(polydata.GetVerts().GetData())
if polydata.GetVerts()
else []
)
lines = (
vtk_to_numpy(polydata.GetLines().GetData())
if polydata.GetLines()
else []
)
polys = (
vtk_to_numpy(polydata.GetPolys().GetData())
if polydata.GetPolys()
else []
)
strips = (
vtk_to_numpy(polydata.GetStrips().GetData())
if polydata.GetStrips()
else []
)
# Extract field
values = None
js_types = "Float32Array"
nb_comp = 1
dataRange = [0, 1]
location = None
if field_to_keep is not None:
p_array = polydata.GetPointData().GetArray(field_to_keep)
c_array = polydata.GetCellData().GetArray(field_to_keep)
if c_array:
dataRange = c_array.GetRange(-1)
nb_comp = c_array.GetNumberOfComponents()
values = vtk_to_numpy(c_array)
js_types = to_js_type[str(values.dtype)]
location = "CellData"
if p_array:
dataRange = p_array.GetRange(-1)
nb_comp = p_array.GetNumberOfComponents()
values = vtk_to_numpy(p_array)
js_types = to_js_type[str(values.dtype)]
location = "PointData"
# other arrays (points)
point_data = []
for name in point_arrays:
array = polydata.GetPointData().GetArray(name)
if array:
dataRange = array.GetRange(-1)
nb_comp = array.GetNumberOfComponents()
values = vtk_to_numpy(array)
js_types = to_js_type[str(values.dtype)]
point_data.append(
{
"name": name,
"values": values,
"numberOfComponents": nb_comp,
"type": js_types,
"location": "PointData",
"dataRange": dataRange,
}
)
# other arrays (cells)
cell_data = []
for name in point_arrays:
array = polydata.GetCellData().GetArray(name)
if array:
dataRange = array.GetRange(-1)
nb_comp = array.GetNumberOfComponents()
values = vtk_to_numpy(array)
js_types = to_js_type[str(values.dtype)]
cell_data.append(
{
"name": name,
"values": values,
"numberOfComponents": nb_comp,
"type": js_types,
"location": "CellData",
"dataRange": dataRange,
}
)
state = {
"mesh": {"points": points,},
}
if len(verts):
state["mesh"]["verts"] = verts
if len(lines):
state["mesh"]["lines"] = lines
if len(polys):
state["mesh"]["polys"] = polys
if len(strips):
state["mesh"]["strips"] = strips
if values is not None:
state.update(
{
"field": {
"name": field_to_keep,
"values": values,
"numberOfComponents": nb_comp,
"type": js_types,
"location": location,
"dataRange": dataRange,
},
}
)
if len(point_data):
state.update({"pointArrays": point_data})
if len(cell_data):
state.update({"cellArrays": cell_data})
return state
try:
# VTK 9+
from vtkmodules.vtkImagingCore import vtkRTAnalyticSource
except:
# VTK =< 8
from vtk.vtkImagingCore import vtkRTAnalyticSource
# Use VTK to get some data
data_source = vtkRTAnalyticSource()
data_source.Update() # <= Execute source to produce an output
dataset = data_source.GetOutput()
# Use helper to get a mesh structure that can be passed as-is to a Mesh
# RTData is the name of the field
mesh_state = to_mesh_state(dataset)
content = dash_vtk.View([
dash_vtk.GeometryRepresentation([
dash_vtk.Mesh(state=mesh_state)
]),
])
# Dash setup
app = dash.Dash(__name__)
server = app.server
app.layout = html.Div(
style={"width": "100%", "height": "400px"},
children=[content],
)
if __name__ == "__main__":
app.run_server(debug=True)
|
PHP
|
UTF-8
| 4,365 | 2.859375 | 3 |
[
"Apache-2.0"
] |
permissive
|
<?php
// ===============================
// 自定义扩展函数
// ===============================
/**
* id列表转换成数字
* @param string|array &$ids id列表。比如:1,2,3 或 array('1','2','3')
* @param string $delimiter 当$ids是字符串时,id之间的分隔符
* @return string|array
* @author swh <swh@admpub.com>
*/
function toInt(&$ids, $delimiter = ',') {
if (!is_array($ids)) {
$ids = array_map('intval', explode($delimiter, $ids));
$ids = array_unique($ids);
$ids = implode($delimiter, $ids);
} else {
$ids = array_map('intval', $ids);
$ids = array_unique($ids);
}
return $ids;
}
/**
* 调用插件控制器中的方法
* @param string $addon 插件英文名(首字母大写)
* @param string|array $controller 插件控制器名(首字母大写),
* 当为数组时则表示这是方法的参数,同时意味着第一个参数是由“插件名/控制器名/方法名”构成的字符串
* @param string $action 插件方法名
* @param array $params 传递给方法的参数
* @return mixed
* @author swh <swh@admpub.com>
*/
function addonA($addon, $controller = array(), $action = null, $params = array()) {
static $_addon = array();
if (is_array($controller)) {
$params = $controller;
$p = explode('/', $addon);
isset($p[2]) && $action = $p[2];
isset($p[1]) && $controller = $p[1];
$addon = $p[0];
}
$k = $addon . '/' . $controller;
isset($_addon[$k]) || $_addon[$k] = A('Addons://' . $k);
$f = array($_addon[$k], $action);
if (!is_object($_addon[$k])) {
return false;
}
if (is_null($action)) {
return $_addon[$k];
}
if (!is_callable($f)) {
return false;
}
return call_user_func_array($f, $params);
}
/**
* 获取插件中的模型
* @param string $addon 插件英文名(首字母大写)
* @param string $model 模型名(首字母大写)
* @return object
* @author swh <swh@admpub.com>
*/
function addonD($addon, $model = null) {
static $_addonM = array();
$k = $addon;
if ($model) {
$k .= '/' . $model;
}
isset($_addonM[$k]) || $_addonM[$k] = D('Addons://' . $k);
return $_addonM[$k];
}
/**
* 获取自己定义的Base模型
* @param string $name 模型名称
* @param string $tablePrefix 表前缀
* @param string $connection 数据库连接设置
* @return object
* @author swh <swh@admpub.com>
*/
function baseM($name = '', $tablePrefix = '', $connection = '') {
return M('Common\\Model\\Base:' . $name, $tablePrefix, $connection);
}
/**
* 获取所有模块的域名
* @return array
* @author swh <swh@admpub.com>
*/
if (!function_exists('moduleDomains')) {
function moduleDomains() {
static $_moduleDomains = null;
if (is_null($_moduleDomains)) {
$_moduleDomains = array();
if (C('APP_SUB_DOMAIN_DEPLOY')) {
$rules = C('APP_SUB_DOMAIN_RULES');
if ($rules) {
foreach ($rules as $key => $value) {
$value = strtolower($value);
$_moduleDomains[$value][] = $key;
}
}
}
}
return $_moduleDomains;
}
}
/**
* 根据模块及是否绑定域名来返回合适的首页网址
*/
function homeUrl() {
$domains = moduleDomains();
$module = strtolower(MODULE_NAME);
if (!empty($domains[$module . '/' . strtolower(CONTROLLER_NAME)])) {
return U('index');
}
if (!empty($domains[$module])) {
return U('Index/index');
}
if ($module=='install') return './';
return U('Home/Index/index');
}
/**
* 检查远程文件是否存在
* @param string $url 远程文章完整网址
* @return bool
*/
function check_remote_file_exists($url) {
$curl = curl_init($url);
// 不取回数据
curl_setopt($curl, CURLOPT_NOBODY, true);
// 发送请求
$result = curl_exec($curl);
$found = false;
// 如果请求没有发送失败
if ($result !== false) {
// 再检查http响应码是否为200
$statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($statusCode == 200) {
$found = true;
}
}
curl_close($curl);
return $found;
}
/**
* 缓存快捷函数
* @param string $cachedId 缓存key
* @param mixed $func 获取新数据的功能函数
* @param integer $lifeTime 生存时间(秒)
* @return mixed
*/
function cached($cachedId, $func, $lifeTime = 86400) {
defined('NOCACHE_MODE') && NOCACHE_MODE && $lifeTime = -1;
$r = $lifeTime > 0 ? S($cachedId) : null;
if (!$r) {
$r = $func();
$lifeTime && S($cachedId, $r, $lifeTime);
}
return $r;
}
|
Java
|
UTF-8
| 419 | 1.890625 | 2 |
[] |
no_license
|
package spring_extends.cn.itcast.spring0909.extend;
import org.junit.Test;
import spring_ioc.cn.itcast.spring0909.utils.SpringHelper;
public class PersonTest extends SpringHelper{
static{
path = "maven-ssm-web/src/main/java/spring/spring_extends/cn/itcast/spring0909/extend/applicationContext.xml";
}
@Test
public void test(){
Student student = (Student)context.getBean("student");
student.say();
}
}
|
Python
|
UTF-8
| 1,076 | 2.953125 | 3 |
[] |
no_license
|
import threading
import time
class RepeatedTimer(object):
def __init__(self, interval, function, *args, **kwargs):
self._timer = None
self.interval = interval
self.function = function
self.args = args
self.kwargs = kwargs
self.is_running = False
self.wait = True
self.counter = 0
self.next_call = time.perf_counter()
def _run(self):
if self.wait:
self._restart()
self.function(*self.args, **self.kwargs)
if not self.wait:
self._restart()
def _restart(self):
if self.is_running:
self._set_timer()
def _set_timer(self):
self.next_call += self.interval
self._timer = threading.Timer(self.next_call - time.perf_counter(), self._run)
self._timer.start()
def start(self, wait=True):
self.next_call = time.perf_counter()
self.wait = wait
self.is_running = True
self._set_timer()
def stop(self):
self._timer.cancel()
self.is_running = False
|
Python
|
UTF-8
| 2,882 | 2.765625 | 3 |
[] |
no_license
|
#!/usr/bin/env python3
import sys
import numpy as np
import matplotlib.pyplot as plt
'''Usage: ./plot_corr_dist_by_chr.py correlations_wrn_{}.txt'''
font = {'size' : 18}
plt.rc('font', **font)
file_base = sys.argv[1]
chroms = []
for i in range(1,20):
chroms.append('chr{}'.format(i))
chroms.append('chrX')
colors = ['dodgerblue', 'coral', 'darkslategray', 'purple', 'darkorange', 'olive', 'rosybrown','black', 'khaki','grey', 'tan', 'saddlebrown', 'darkgoldenrod', 'turquoise', 'mediumvioletred', 'cyan', 'navy', 'magenta', 'indigo', 'deeppink']
chrom_to_colors = {}
for color, chrom in zip(colors, chroms):
chrom_to_colors[chrom] = color
wanted_ticks = [-1, -0.75, -0.5, -0.25, 0, 0.25, 0.5, 0.75, 1]
correlations = []
#total_corrs = 0
#num_nan_total = 0
for chrom in chroms:
chrom_spec_corr = []
corrs = open(file_base.format(chrom)).readlines()
for x in corrs:
correlations.append(float(x))
chrom_spec_corr.append(float(x))
chrom_spec_corr = np.array(chrom_spec_corr)
subset = ~np.isnan(chrom_spec_corr)
chrom_spec_corr = chrom_spec_corr[subset]
fig, (ax1, ax2, ax3) = plt.subplots(3, 1, figsize=(7,15))
ax1.set_title('Distribution of initial Spearmanr\nof expression against ccREs within 1.5Mbp\n{}'.format(chrom))
ax1.boxplot(chrom_spec_corr)
ax1.set_yticks(wanted_ticks)
ax1.set_yticklabels(wanted_ticks)
ax1.set_ylabel('Spearmanr')
parts = ax2.violinplot(chrom_spec_corr)
ax2.set_ylabel('Spearmanr')
ax2.set_yticks(wanted_ticks)
ax2.set_yticklabels(wanted_ticks)
for pc in parts['bodies']:
pc.set_facecolor(chrom_to_colors[chrom])
pc.set_edgecolor('black')
pc.set_alpha(1)
ax3.hist(chrom_spec_corr, bins=75, color=chrom_to_colors[chrom])
ax3.set_xlabel('Spearmanr')
plt.tight_layout()
fig.savefig('dist_correlation_{}.pdf'.format(chrom), format='pdf')
fig.savefig('dist_correlation_{}.png'.format(chrom), format='png')
plt.close(fig)
#total_corrs += corrs.shape[0]
#num_nan_total += np.sum(np.isnan(corrs))
correlations = np.array(correlations)
subset = ~np.isnan(correlations)
correlations = correlations[subset]
fig, (ax1, ax2, ax3) = plt.subplots(3, 1, figsize=(7,15))
ax1.set_title('Distribution of initial Spearmanr\nof expression against ccREs within 1.5Mbp\nall chromosomes')
#boxplot
ax1.boxplot(correlations)
ax1.set_yticks(wanted_ticks)
ax1.set_yticklabels(wanted_ticks)
ax1.set_ylabel('Spearmanr')
#violinplot
ax2.violinplot(correlations)
ax2.set_ylabel('Spearmanr')
ax2.set_yticks(wanted_ticks)
ax2.set_yticklabels(wanted_ticks)
#histogram
ax3.hist(correlations, bins=75)
ax3.set_xlabel('Spearmanr')
plt.tight_layout()
fig.savefig('dist_correlation_all.pdf', format='pdf')
fig.savefig('dist_correlation_all.png', format='png')
plt.close(fig)
#print(num_nan_total) #>1159389
#print(total_corrs) #>11965860
|
Java
|
UTF-8
| 400 | 2.59375 | 3 |
[] |
no_license
|
package akrnote.core.singleton;
public class SingletonService {
//static 영역 공부하기
private static final SingletonService instance = new SingletonService();
public static SingletonService getInstance(){
return instance;
}
private SingletonService(){
}
public void logic(){
System.out.println("생글톤 객체 로직 호출"+instance);
}
}
|
PHP
|
UTF-8
| 4,385 | 2.546875 | 3 |
[
"MIT"
] |
permissive
|
<?php
namespace App\Http\Controllers;
use Illuminate\Routing\Controller as BaseController;
use Session;
use User;
use Products;
use LikesProducts;
use Likes;
use Comment;
use DB;
class ProductsController extends BaseController
{
public function products() {
if(session('user_id') != null) {
return view('products');
} else {
return redirected('login');
}
}
public function fetch_products() {
$products = Products::all();
return $products;
}
public function fetch_comments() {
$maxID = DB::table('COMMENTO')->max('ID');
$commentsArray = array();
for($i = 1; $i < ($maxID + 1); $i++) {
$comment = Comment::find($i);
if($comment) {
$user_comment = $comment->user;
$commentsArray[] = array('username' => $user_comment->username, 'testo' => $comment->testo,
'giorno' => $comment->giorno, 'ora' => $comment->ora,
'nlikes' => $comment->nlikes);
};
}
return $commentsArray;
}
public function fetch_fav() {
$favs = User::find(session('user_id'))->likes_product;
if($favs) {
$favArray = array();
for($i = 0; $i < count($favs); $i++) {
$product = Products::find($favs[$i]->prodotto);
$favArray[] = array($i => $product);
}
}
return $favArray;
}
public function fetch_likes($data) {
$likes = User::find(session('user_id'))->likes()->where('commento', $data)->first();
if($likes) {
return array('ok' => true, $likes->commento);
} else {
return array('ok' => false, $data);
}
}
public function like_product($data) {
$newLikeProduct = LikesProducts::create([
'cliente' => session('user_id'),
'prodotto' => $data
]);
if($newLikeProduct) {
return array('add' => true, 'remove' => false, 'prodotto' => $data);
} else {
return array('add' => false, 'remove' => false, 'prodotto' => $data);
}
}
public function unlike_product($data) {
$unlikeProduct = LikesProducts::where('cliente', session('user_id'))->where('prodotto', $data)->delete();
if($unlikeProduct) {
return array('remove' => true, 'add' => false, 'prodotto' => $data);
} else {
return array('remove' => false, 'add' => false, 'prodotto' => $data);
}
}
public function like_comment($data) {
$newLike = Likes::create([
'cliente' => session('user_id'),
'commento' => $data
]);
if($newLike) {
$nlikes = Comment::where('ID', $data)->first();
return array('ok' => true, 'commento' => $data, 'nlikes' => $nlikes->nlikes);
} else {
return array('ok' => false);
}
}
public function unlike_comment($data) {
$unlike = Likes::where('cliente', session('user_id'))->where('commento', $data)->delete();
if($unlike) {
$nlikes = Comment::where('ID', $data)->first();
return array('ok' => true, 'commento' => $data, 'nlikes' => $nlikes->nlikes);
} else {
return array('ok' => false);
}
}
public function new_comment($text, $date, $time) {
if(count(array($text)) != 0) {
$newComment = Comment::create([
'cliente' => session('user_id'),
'testo' => $text,
'giorno' => $date,
'ora' => $time
]);
if($newComment) {
return array('ok' => true);
} else {
return array('ok' => false);
}
}
}
}
?>
|
Markdown
|
UTF-8
| 1,495 | 2.796875 | 3 |
[] |
no_license
|
#Portfolio App Code
This is the README for my portfolio app. The screenshots below are only of this app, not of the apps in my portfolio.
You might have reached this page through the actual portfolio website:
<br>http://greggallant.net<br>or<br>http://gallantportfolio.herokuapp.com/<br>
Scroll down to see some additional comments.
#Screenshots:
<p align="center">
<span>
<img src="https://github.com/gsgallant/screenshots/blob/master/portfolio/Screen%20Shot%202016-06-17%20at%2010.38.11%20AM.png" width="48%" height="auto"/>
<img src="https://github.com/gsgallant/screenshots/blob/master/portfolio/Screen%20Shot%202016-06-17%20at%2010.38.28%20AM.png" width="48%" height="auto"/>
<img src="https://github.com/gsgallant/screenshots/blob/master/portfolio/Screen%20Shot%202016-06-17%20at%204.01.47%20PM.jpg" width="48%" height="auto"/>
<img src="https://github.com/gsgallant/screenshots/blob/master/portfolio/Screen%20Shot%202016-06-17%20at%2010.38.54%20AM.png" width="48%" height="auto"/>
</span>
</p>
#Technologies used:
Bootstrap, jQuery, CSS
#Comments
My portfolio is constantly a work in progress. I started with a bootstrap template and customized it for my own purposes. I've added some additional functionality and features as well as some personal styling.
Each app has two links: one to the github repo and one to the live deployment on heroku so that you can run the app. Just hover over the app screenshot to see the links available.
<p align="center">
© Greg Gallant
</p>
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.