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
|
---|---|---|---|---|---|---|---|
JavaScript
|
UTF-8
| 2,333 | 2.84375 | 3 |
[] |
no_license
|
const Engine = Matter.Engine;
const World = Matter.World;
const Bodies = Matter.Bodies;
const Body = Matter.Body;
const Constraint = Matter.Constraint;
var mango1,mango2,mango3,mango4,mango5,mango6,mango7,mango8,mango9,mango10;
var ground1;
var tree1;
var boy;
var elasticBand;
var stone1;
function preload()
{
boyImage=loadImage("boy.png");
}
function setup() {
createCanvas(1000, 500);
engine = Engine.create();
world = engine.world;
//Create the Bodies Here.
ground1=new Ground(500,490,1000,20);
tree1=new Tree(800,250,300,500);
mango1=new Mango(800,200,50);
mango2=new Mango(775,110,60);
mango3=new Mango(700,150,50);
mango4=new Mango(890,210,40);
mango5=new Mango(760,210,20);
mango6=new Mango(890,120,40);
mango7=new Mango(820,110,40);
mango8=new Mango(850,180,40);
mango9=new Mango(710,210,50);
mango10=new Mango(820,50,40);
stone1=new Stone(100,100,80);
boy=createSprite(250,425,80,130);
boy.addImage(boyImage);
boy.scale=0.1;
elasticBand = new Elastic(stone1.body,{x: 200,y: 360});
Engine.run(engine);
}
function draw() {
rectMode(CENTER);
background(255);
tree1.display();
mango10.display();
mango9.display();
mango8.display();
mango7.display();
mango6.display();
mango5.display();
mango4.display();
mango3.display();
mango2.display();
mango1.display();
elasticBand.display();
drawSprites();
stone1.display();
ground1.display();
detectCollision(mango1,stone1);
detectCollision(mango2,stone1);
detectCollision(mango3,stone1);
detectCollision(mango4,stone1);
detectCollision(mango5,stone1);
detectCollision(mango6,stone1);
detectCollision(mango7,stone1);
detectCollision(mango8,stone1);
detectCollision(mango9,stone1);
detectCollision(mango10,stone1);
keyPressed();
}
function mouseDragged(){
Matter.Body.setPosition(stone1.body,{x: mouseY, y: mouseY});
}
function mouseReleased(){
elasticBand.fly();
}
function detectCollision(object1,object2){
var distance=dist(object2.x,object2.y,object1.x,object1.y);
if (distance>=object2.r+object1.r){
Matter.Body.setStatic(object2.body,false);
}
//console.log("hello");
}
function keyPressed(){
if (keyCode === 32){
Matter.Body.setPosition(stone1.body,{x:200,y:360});
elasticBand.attach(stone1.body);
}
}
|
Python
|
UTF-8
| 3,043 | 2.734375 | 3 |
[
"MIT"
] |
permissive
|
"""Visualise a generated SMAL type model, producing animations of changing key parameters"""
from smbld_model.config import SMPL_DATA_PATH, SMPL_MODEL_PATH, NEW_MODEL_PATH, NEW_DATA_PATH
from smbld_model.smbld_mesh import SMBLDMesh
import numpy as np
import torch
from matplotlib import pyplot as plt
from vis import plot_mesh, save_animation, animator
models = {
"default": dict(name="default smal", data_path=SMPL_DATA_PATH, model_path=SMPL_MODEL_PATH, shape_family_id=-1,
num_betas=20),
"new": dict(name="new model", data_path=NEW_DATA_PATH, model_path=NEW_MODEL_PATH, shape_family_id=0, num_betas=18)
} # Model name : SMBLDMesh kwargs
# Set the device
if torch.cuda.is_available():
device = torch.device("cuda:0,1")
else:
device = torch.device("cpu")
def vis_shape_params(name="default", num_betas=20, fps=15, **model_kwargs):
"""Load SMBLD model. Wiggle each shape param in turn"""
mesh = SMBLDMesh(**model_kwargs, num_betas=num_betas, device=device)
fig, ax = plt.subplots(figsize=(10, 10), dpi=30, subplot_kw={"projection": "3d"})
num_steps = N = 2 * fps
## shape range goes from 0 -> 1 -> -1 -> 0 in equally spaced steps
shape_range = np.concatenate(
[np.linspace(0, 1, num_steps // 4), np.linspace(1, -1, num_steps // 2), np.linspace(-1, 0, num_steps // 4)])
shape_range = np.pad(shape_range, (0, N - len(shape_range))) # pad to size N
n_frames = num_steps * num_betas
plot_mesh(ax, mesh.get_meshes(), zoom=1.5, equalize=True) # plot blank mesh with axes equalized
@animator(ax)
def anim(i):
# update SMBLD
cur_beta_idx, cur_step = i // num_steps, i % num_steps
val = shape_range[cur_step]
mesh.multi_betas[0, cur_beta_idx] = val # Update betas
fig.suptitle(f"{name.title()}\nS{cur_beta_idx} : {val:+.2f}", fontsize=50) # update text
return dict(mesh=mesh.get_meshes(), equalize=False)
ax.axis("off")
fig.subplots_adjust(left=0, right=1, top=1, bottom=0)
save_animation(fig, anim, n_frames=n_frames, fmt="gif", title=f"{name}_betas", fps=fps)
def vis_pose_params(data_loc, name="default", num_betas=20, fps=15, **model_kwargs):
"""Given a .npz file which contains N pose params, visualise the old SMBLD model with those pose params"""
n_frames = np.load(data_loc)["joint_rot"].shape[0]
mesh = SMBLDMesh(**model_kwargs, num_betas=num_betas, device=device, n_batch=n_frames)
mesh.load_from_npz(data_loc)
mesh_list = mesh.get_meshes()
fig, ax = plt.subplots(figsize=(10, 10), dpi=30, subplot_kw={"projection": "3d"})
plot_mesh(ax, mesh_list[0], zoom=1.5, equalize=True) # plot blank mesh with axes equalized
@animator(ax)
def anim(i):
return dict(mesh=mesh_list[i], equalize=False)
ax.axis("off")
fig.subplots_adjust(left=0, right=1, top=1, bottom=0)
save_animation(fig, anim, n_frames=n_frames, fmt="gif", title=f"{name}_pose", fps=fps)
if __name__ == "__main__":
# vis_shape_params(**models["default"], fps=15)
# vis_shape_params(**models["new"], fps=15)
vis_pose_params(**models['default'], data_loc=r"animated_fits_output\smbld_params_fila_pose.npz")
|
Java
|
UTF-8
| 179 | 1.507813 | 2 |
[] |
no_license
|
package lt.vu.restapi.contracts;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class ForestDto {
private String name;
private String licenceType;
}
|
TypeScript
|
UTF-8
| 7,278 | 2.609375 | 3 |
[
"MIT"
] |
permissive
|
import { Constants } from '../constants';
import { Column } from '../interfaces/column.interface';
import { SharedService } from '../services/shared.service';
import { TranslaterService } from '../services';
import { getTranslationPrefix } from '../services/utilities';
import { Locale } from '../interfaces/locale.interface';
export class ExtensionUtility {
constructor(private readonly sharedService: SharedService, private readonly translaterService?: TranslaterService) { }
/**
* From a Grid Menu object property name, we will return the correct title output string following this order
* 1- if user provided a title, use it as the output title
* 2- else if user provided a title key, use it to translate the output title
* 3- else if nothing is provided use text defined as constants
*/
getPickerTitleOutputString(propName: string, pickerName: 'gridMenu' | 'columnPicker') {
if (this.sharedService.gridOptions && this.sharedService.gridOptions.enableTranslate && (!this.translaterService || !this.translaterService.translate)) {
throw new Error('[Slickgrid-Universal] requires a Translate Service to be installed and configured when the grid option "enableTranslate" is enabled.');
}
let output = '';
const picker = this.sharedService.gridOptions?.[pickerName] ?? {};
const enableTranslate = this.sharedService.gridOptions?.enableTranslate ?? false;
// get locales provided by user in forRoot or else use default English locales via the Constants
const locales = this.sharedService.gridOptions?.locales ?? Constants.locales;
const title = (picker as any)?.[propName];
const titleKey = (picker as any)?.[`${propName}Key`];
const gridOptions = this.sharedService.gridOptions;
const translationPrefix = getTranslationPrefix(gridOptions);
if (titleKey && this.translaterService?.translate) {
output = this.translaterService.translate(titleKey || ' ');
} else {
switch (propName) {
case 'customTitle':
output = title || enableTranslate && this.translaterService?.getCurrentLanguage && this.translaterService?.translate(`${translationPrefix}COMMANDS` || ' ') || locales?.TEXT_COMMANDS;
break;
case 'columnTitle':
output = title || enableTranslate && this.translaterService?.getCurrentLanguage && this.translaterService?.translate(`${translationPrefix}COLUMNS` || ' ') || locales?.TEXT_COLUMNS;
break;
case 'forceFitTitle':
output = title || enableTranslate && this.translaterService?.getCurrentLanguage && this.translaterService?.translate(`${translationPrefix}FORCE_FIT_COLUMNS` || ' ') || locales?.TEXT_FORCE_FIT_COLUMNS;
break;
case 'syncResizeTitle':
output = title || enableTranslate && this.translaterService?.getCurrentLanguage && this.translaterService?.translate(`${translationPrefix}SYNCHRONOUS_RESIZE` || ' ') || locales?.TEXT_SYNCHRONOUS_RESIZE;
break;
default:
output = title;
break;
}
}
return output;
}
/**
* Loop through object provided and set to null any property found starting with "onX"
* @param {Object}: obj
*/
nullifyFunctionNameStartingWithOn(obj?: any) {
if (obj) {
for (const prop of Object.keys(obj)) {
if (prop.startsWith('on')) {
obj[prop] = null;
}
}
}
}
/**
* When using ColumnPicker/GridMenu to show/hide a column, we potentially need to readjust the grid option "frozenColumn" index.
* That is because SlickGrid freezes by column index and it has no knowledge of the columns themselves and won't change the index, we need to do that ourselves whenever necessary.
* Note: we call this method right after the visibleColumns array got updated, it won't work properly if we call it before the setting the visibleColumns.
* @param {Number} frozenColumnIndex - current frozenColumn index
* @param {Array<Object>} allColumns - all columns (including hidden ones)
* @param {Array<Object>} visibleColumns - only visible columns (excluding hidden ones)
*/
readjustFrozenColumnIndexWhenNeeded(frozenColumnIndex: number, allColumns: Column[], visibleColumns: Column[]) {
if (frozenColumnIndex >= 0) {
const recalculatedFrozenColumnIndex = visibleColumns.findIndex(col => col.id === this.sharedService.frozenVisibleColumnId);
if (recalculatedFrozenColumnIndex >= 0 && recalculatedFrozenColumnIndex !== frozenColumnIndex) {
this.sharedService.gridOptions.frozenColumn = recalculatedFrozenColumnIndex;
this.sharedService.slickGrid.setOptions({ frozenColumn: recalculatedFrozenColumnIndex });
}
// to freeze columns, we need to take only the visible columns and we also need to use setColumns() when some of them are hidden
// to make sure that we only use the visible columns, not doing this would show back some of the hidden columns
if (Array.isArray(visibleColumns) && Array.isArray(allColumns) && visibleColumns.length !== allColumns.length) {
this.sharedService.slickGrid.setColumns(visibleColumns);
}
}
}
/**
* Sort items (by pointers) in an array by a property name
* @param {Array<Object>} items array
* @param {String} property name to sort with
*/
sortItems(items: any[], propertyName: string) {
// sort the custom items by their position in the list
if (Array.isArray(items)) {
items.sort((itemA: any, itemB: any) => {
if (itemA && itemB && itemA.hasOwnProperty(propertyName) && itemB.hasOwnProperty(propertyName)) {
return itemA[propertyName] - itemB[propertyName];
}
return 0;
});
}
}
/** Translate the an array of items from an input key and assign to the output key */
translateItems<T = any>(items: T[], inputKey: string, outputKey: string) {
if (Array.isArray(items)) {
for (const item of items) {
if ((item as any)[inputKey]) {
(item as any)[outputKey] = this.translaterService && this.translaterService.getCurrentLanguage && this.translaterService.translate && this.translaterService.translate((item as any)[inputKey]);
}
}
}
}
/**
* When "enabledTranslate" is set to True, we will try to translate if the Translate Service exist or use the Locales when not
* @param {String} translationKey
* @param {String} localeKey
* @param {String} textToUse - optionally provide a static text to use (that will completely override the other arguments of the method)
*/
translateWhenEnabledAndServiceExist(translationKey: string, localeKey: string, textToUse?: string): string {
let text = '';
const gridOptions = this.sharedService?.gridOptions;
// get locales provided by user in main file or else use default English locales via the Constants
const locales = gridOptions?.locales ?? Constants.locales;
if (textToUse) {
text = textToUse;
} else if (gridOptions.enableTranslate && this.translaterService?.translate) {
text = this.translaterService.translate(translationKey || ' ');
} else if (localeKey in locales) {
text = locales[localeKey as keyof Locale] as string;
} else {
text = localeKey;
}
return text;
}
}
|
PHP
|
UTF-8
| 3,323 | 3.21875 | 3 |
[] |
no_license
|
<!DOCTYPE html>
<html>
<head>
<title>
Brian Fay Unit 4 Lab 2
</title>
<meta charset="utf-8">
<style type="text/css">
body{
margin-left: 10%;
font-family: Arial;
}
.description {
font-size: 12pt;
padding-right: 30%;
color: #000;
}
.phpOutput {
position: relative;
top: 0px;
left: 0px;
background-color: #000000;
border-style:double;
border-width:5px;
padding: 20px;
margin-right: 30%;
color: #8DDB8A;
font-size: 16pt;
}
</style>
</head>
<body>
<h1>
Example 4-1:
</h1>
<p class="description">
This example evaluates four boolean expressions: (20 > 9), (5==6),
(1 == 0), and (1==1)
</p>
<div class="phpOutput">
<?php
echo "a: [" . (20 > 9) ."]<br />";
echo "b: [" . (5 == 6) . "]<br />";
echo "c: [" . (1 == 0) . "]<br />";
echo "d: [" . (1 == 1) . "]<br />";
?>
</div>
<h1>
Example 4-2
</h1>
<p class="description">
This example demonstrates the fact that "true" in PHP has the value 1, while "false" is
null.
</p>
<div class="phpOutput">
<?php
echo "a: [" . true . "]<br />";
echo "b: [" . false . "]<br />";
?>
</div>
<h1>
Example 4-12
</h1>
<p class="description">
This example shows an if statement, using a boolean expression
comparing a variable to a string literal.
</p>
<div class="phpOutput">
<?php
$month = "March";
if ($month == "March") echo "It's springtime";
?>
</div>
<h1>
Example 4-13
</h1>
<p class="description">
PHP is an interpreted language, and it can automatically
convert types depending on the context. Using "===" prevents this
sautomatic conversion.
</p>
<div class="phpOutput">
<?php
$a = "1000";
$b = "+1000";
if ($a == $b) echo "1";
if ($a === $b) echo "2";
?>
</div>
<h1>
Example 4-22
</h1>
<p class ="description">
This example shows an if-elseif chain, which could be written as a
switch statement instead. (I've taken the liberty of setting the variable
$page to "News.")
</p>
<div class="phpOutput">
<?php
$page = "News";
if ($page == "Home") echo "You selected Home";
if ($page == "About") echo "You selected About";
if ($page == "News") echo "You selected News";
if ($page == "Login") echo "You selected Login";
if ($page == "Links") echo "You selected Links";
?>
</div>
<h1>
Example 4-23
</h1>
<p class ="description">
The same idea, written as a switch statement.
</p>
<div class="phpOutput">
<?php
$page = "News";
switch($page)
{
case "Home":
echo "You selected Home";
break;
case "About":
echo "You selected About";
break;
case "News":
echo "You selected News";
break;
case "Login":
echo "You selected Login";
break;
case "Links":
echo "You selected Links";
break;
}
?>
</div>
<h1>
Challenge!
</h1>
<p class="description">
Set a variable to an integer (3), create a PHP statement to test the value of the variable,
multiply it by a set number, print out the result, increase the value of the variable by 1,
and continue until there are 10 lines displaying in the browser.
</p>
<p class="phpOutput">
<?php
$theInt = 3;
while($theInt < 13)
{
echo $theInt . " multiplied by 3 : " . ($theInt * 3) . "<br />";
$theInt++;
}
?>
</p>
</body>
</html>
|
C#
|
UTF-8
| 4,777 | 2.703125 | 3 |
[] |
no_license
|
using DataAccessLayer.Models;
using LogicLayer.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Linq;
namespace UnitTests
{
[TestClass]
public class ProductTests
{
public TestContext TestContext { get; set; }
private static TestContext _testContext;
[ClassInitialize()]
public static void ClassInit(TestContext context)
{
_testContext = context;
var options = new DbContextOptionsBuilder<AppDbContext>()
.UseInMemoryDatabase(databaseName: "master")
.Options;
_testContext.Properties.Add("options", options);
using (var con = new AppDbContext(options))
{
con.Categories.Add(new Category { ID = 1, CategoryName = "Beverage", CategoryCode = "BEV123", IsActive = true });
con.Categories.Add(new Category { ID = 2, CategoryName = "Cosmentics", CategoryCode = "COS365", IsActive = true });
con.Categories.Add(new Category { ID = 3, CategoryName = "Fruits", CategoryCode = "FRT745", IsActive = true });
con.SaveChanges();
con.Products.Add(new Product
{
ID = 1,
ProductName = "Coffee",
Price = 2,
ProductCode = "202109-001",
Category = con.Categories.Single(p => p.ID == 1)
});
con.Products.Add(new Product
{
ID = 2,
ProductName = "Milk",
Price = 36,
ProductCode = "202109-002",
Category = con.Categories.Single(p => p.ID == 1)
});
con.Products.Add(new Product
{
ID = 3,
ProductName = "Roll-On",
Price = 45,
ProductCode = "202109-008",
Category = con.Categories.Single(p => p.ID == 2)
});
con.Products.Add(new Product
{
ID = 4,
ProductName = "Banana",
Price = 10,
ProductCode = "202109-020",
Category = con.Categories.Single(p => p.ID == 3)
});
con.Products.Add(new Product
{
ID = 5,
ProductName = "Apple",
Price = 5,
ProductCode = "202109-078",
Category = con.Categories.Single(p => p.ID == 3)
});
con.SaveChanges();
}
}
[TestMethod]
public void GetProducts_Should_Return_All_Products()
{
var options = _testContext.Properties["options"] as DbContextOptions;
using (var con = new AppDbContext(options))
{
var service = new ProductService(con);
var products = service.GetProducts().ToList();
Assert.IsTrue(products.Count > 0);
}
}
[TestMethod]
public void Edit_Product_Should_Update_Product_Name()
{
var options = _testContext.Properties["options"] as DbContextOptions;
using (var con = new AppDbContext(options))
{
var service = new ProductService(con);
var coffee = con.Products.AsNoTracking()
.Include(c => c.Category)
.Single(p => p.ID == 1);
Assert.AreEqual("Coffee", coffee.ProductName);
coffee.ProductName = "Tea";
var updated = service.UpdateProduct(1, coffee).GetAwaiter().GetResult();
Assert.IsTrue(updated);
var tea = service.Get(1).GetAwaiter().GetResult();
Assert.AreEqual("Tea", tea.ProductName);
Assert.IsFalse(con.Products.Any(P => P.ProductName == "Coffee"));
}
}
[TestMethod]
public void Delete_Product_Should_Remive_Product()
{
var options = _testContext.Properties["options"] as DbContextOptions;
using (var con = new AppDbContext(options))
{
var service = new ProductService(con);
var prods = service.GetProducts();
var countBefore = prods.Count();
var deleted = service.Remove(4).GetAwaiter().GetResult();
Assert.IsTrue(deleted);
prods = service.GetProducts();
Assert.AreEqual(4, prods.Count());
}
}
}
}
|
Python
|
UTF-8
| 1,503 | 2.640625 | 3 |
[
"MIT"
] |
permissive
|
import copy, torch
import numpy as np
from deepq.memory import Memory
from deepq.utils import eps_greedy_action, preprocess
from deepq.wrapper_gym import SkipFrames
import gym
def play_atari(env_name, agent_history_length, Q, nb_episodes=10, eps=0.1):
'''
Input:
- environment (the environment is copied, so it is not modified)
- Q function
- number of episodes to play
- eps between 0 and 1. It adds some randomness.
Returns:
- list of observations (np arrays, one np array == one episode played)
'''
device = next(Q.parameters()).device
env = gym.make(env_name)
env = SkipFrames(env, agent_history_length-1, preprocess)
rewards = list()
for i in range(nb_episodes):
episode, temp_reward = list(), list()
done = False
phi_t = env.reset()
last_frames = Memory(agent_history_length)
while len(last_frames.replay_memory)<agent_history_length:
last_frames.push(phi_t)
while not done:
phi_t = torch.stack(last_frames[0:agent_history_length]).unsqueeze(0).to(device)
phi_t = phi_t.permute(0,2,3,1)
action = eps_greedy_action(phi_t, env, Q, eps)
phi_t, reward, done, _ = env.step(action)
episode.append(phi_t)
last_frames.push(phi_t)
temp_reward.append(reward)
rewards.append(float(np.sum(temp_reward)))
return torch.stack(episode), rewards
|
Python
|
UTF-8
| 891 | 2.546875 | 3 |
[] |
no_license
|
from django.db import models
from django.contrib.auth.models import User
class Student(models.Model):
DISCIPLINES = (
('MINF', 'Medieninformatik'),
('WINF', 'Wirtschaftsinformatik'),
)
userid = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, verbose_name="Benutzername")
firstname = models.CharField(max_length=30, verbose_name="Vorname")
lastname = models.CharField(max_length=30, verbose_name="Nachname")
discipline = models.CharField(max_length=4, choices=DISCIPLINES, default='MINF', null=False, blank=False,
verbose_name="Fachrichtung")
startingSemester = models.CharField(max_length=7, null=False, blank=False,
verbose_name="Startsemester (z.B WS17/18, SS19)") # WS19/20, SS19
def __str__(self):
return '{}'.format(self.userid)
|
C#
|
UTF-8
| 1,835 | 2.765625 | 3 |
[] |
no_license
|
using FluentAssertions;
using MyFish.Brain;
using MyFish.Brain.Moves;
using NUnit.Framework;
namespace MyFish.Tests.Primitives
{
[TestFixture]
public class PositionTests
{
[Test]
public void Invalid_position_member_is_not_valid()
{
Position.Invalid.IsValid.Should().BeFalse();
}
[Test]
public void Moving_off_the_board_produces_invalid_position()
{
(new Position('h', 8) + Vector.North).IsValid.Should().BeFalse();
(new Position('h', 8) + Vector.East).IsValid.Should().BeFalse();
(new Position('a', 1) + Vector.South).IsValid.Should().BeFalse();
(new Position('a', 1) + Vector.West).IsValid.Should().BeFalse();
}
[Test]
public void Moving_invalid_position_allways_produces_another_invalid_position()
{
(new Position('h', 8) + Vector.North + Vector.South).IsValid.Should().BeFalse();
(new Position('h', 8) + Vector.East + Vector.West).IsValid.Should().BeFalse();
(new Position('a', 1) + Vector.South + Vector.North).IsValid.Should().BeFalse();
(new Position('a', 1) + Vector.West + Vector.East).IsValid.Should().BeFalse();
}
[Test]
public void Invalid_position_is_equal_to_some_other_invalid_position()
{
var other = new Position('h', 8) + Vector.NorthEast;
(Position.Invalid == other).Should().BeTrue();
(Position.Invalid != other).Should().BeFalse();
}
[Test]
public void Operator_minus()
{
var d5 = new Position('d', 5);
var e4 = new Position('e', 4);
(d5 - e4).Should().Be(new Vector(-1, 1));
}
}
}
|
Java
|
UTF-8
| 4,015 | 2.765625 | 3 |
[] |
no_license
|
package wise.semivariogram.fit;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.util.Scanner;
import java.util.StringTokenizer;
public class SemivariogramFit {
//input from Semivariogram2D.java
private double[] semivar;
private double[] distance;
private double[] num;
private int nrbins;
private int nrSubbins = 100;
private double semibin;
private double lagbin;
private double maxVar;
private double maxDis;
//private double min Least Squared;
double [][] minLS = new double[nrSubbins][nrSubbins];
double [][] a0 = new double[nrSubbins][nrSubbins];
double [][] c0 = new double[nrSubbins][nrSubbins];
//b0[0] = range
//b0[1] = sill
//b0[2] = nugget
double[] b0 = new double[3];
SemivariogramFit (double[] semivar, double[] distance, double[] num, int nrbins){
this.semivar = semivar;
this.distance = distance;
this.nrbins = nrbins;
this.num = num;
//b0[0] = initial range
//b0[1] = initial sill
//b0[2] = initial nugget
maxDis = findMax(distance, nrbins);
b0 [0] = maxDis * 2 / 3;
maxVar = findMax(semivar, nrbins);
b0 [1] = maxVar;
//b0 [2] = semivar[0];
lagbin = b0[0]/nrSubbins;
semibin = b0[1]/nrSubbins;
}
public void run(){
for (int i=0 ; i<nrSubbins ; i++){
for (int j=0 ; j<nrSubbins ; j++){
b0[0] -= lagbin;
minLS[i][j] = leastsquaredSumFunc(semivar, b0, distance, nrbins);
a0[i][j]= b0[0];
c0[i][j]= b0[1];
}
b0 [0] = maxDis * 2 / 3;
b0 [1] -= semibin;
}
double min=9999999;
double a=0;
double c=0;
for (int i=0 ; i<nrSubbins ; i++){
for (int j=0 ; j<nrSubbins ; j++){
if (i==0 && j==0){
min = minLS[i][j];
}else{
if (min > minLS[i][j]){
min = minLS[i][j];
a = a0[i][j];
c = c0[i][j];
}
}
}
}
System.out.println("a = " +a);
System.out.println("c = " +c);
}
private double sphericalModel (double[] b0, double h){
return b0[1]*Math.pow( (3*h/(2*b0[0])) - 1/2*(h/b0[0]) , 3);
}
private double weight ( ){
return 0.0;
}
private double leastsquaredSumFunc (double[] semivar, double[] b0, double[] h, int nrbins){
double sum=0.0;
for (int i=0 ; i<nrbins ; i++){
if (h[i] < b0[0]){
sum+=Math.pow(sphericalModel(b0, h[i])-semivar[i], 2);//*weight(b0);
}else{
sum+=Math.pow(b0[1]-semivar[i], 2);//*weight(b0);
}
}
return sum;
}
private double findMax (double[] data, int nrbins){
double max=0.0;
for (int i=0 ; i<nrbins ; i++){
if (data[i] > max){
max = data[i];
}
}
return max;
}
public static void main(String[] args) throws FileNotFoundException{
double [] d;
double [] semivar;
double [] num;
int cntLine=0;
String pathIntermediate = "/home/seop/workspace/VariogramMR/intermediate";
String pathInput = "/home/seop/workspace/VariogramMR/output";
FileInputStream fline = new FileInputStream(pathIntermediate + "/variogram_test_nrbins.txt");
Scanner sline = new Scanner(fline);
for (int i = 0; sline.hasNext() ; i++) {
//StringTokenizer input = new StringTokenizer(sline.nextLine(), " ");
cntLine = Integer.parseInt(sline.next());
}
d=new double [cntLine];
semivar=new double [cntLine];
num=new double [cntLine];
FileInputStream fin = new FileInputStream(pathInput + "/part-r-00000");
Scanner s = new Scanner(fin);
for (int i = 0; s.hasNext() && i<cntLine ; i++) {
StringTokenizer input = new StringTokenizer(s.nextLine(), "\t");
System.out.println(input.nextToken());
semivar[i]=Double.parseDouble(input.nextToken());
d[i]=Double.parseDouble(input.nextToken());
num[i]=Double.parseDouble(input.nextToken());
}
/////////////////////////////////
//semivariogram fit start////
/////////////////////////////////
SemivariogramFit sf = new SemivariogramFit(semivar,d,num,cntLine);
sf.run();
}
}
|
Shell
|
UTF-8
| 140 | 2.828125 | 3 |
[
"MIT"
] |
permissive
|
#!/bin/bash
while true
do
read message
now=$(date +'[%F|%T]')
echo "$message -- $USER at $now" >> output.txt
done
|
C#
|
UTF-8
| 6,131 | 2.765625 | 3 |
[] |
no_license
|
using Microsoft.Extensions.Logging;
using Moq;
using System;
using System.Collections.Generic;
using System.Text;
using Xunit;
namespace pi1.Tests
{
public class RPNCalculatorTests
{
[Fact]
public void Tokenize_SingleOperation_SholdReturnThreeTokens()
{
//arrange
var calculator = new RPNCalculator();
string[] expectedTokens = new[] { "4", "5", "+" };
string input = "4+5";
//act
var actualTokens = calculator.Tokenize(input);
//assert
Assert.Equal(expectedTokens, actualTokens);
}
[Fact]
public void Tokenize_TwoOperationsWithSamePriority_SholdReturnThreeTokens()
{
//arrange
var calculator = new RPNCalculator();
string[] expectedTokens = new[] { "4", "5", "+", "1", "-" };
string input = "4+5-1";
//act
var actualTokens = calculator.Tokenize(input);
//assert
Assert.Equal(expectedTokens, actualTokens);
}
[Fact]
public void Tokenize_TwoOperationsWithLargerPriorityInFirstOperation_SholdReturnSuccess()
{
//arrange
var calculator = new RPNCalculator();
string[] expectedTokens = new[] { "4", "5", "*", "1", "-" };
string input = "4*5-1";
//act
var actualTokens = calculator.Tokenize(input);
//assert
Assert.Equal(expectedTokens, actualTokens);
}
[Fact]
public void Tokenize_TwoOperationsWithLargerPriorityInSecondOperation_SholdReturnSuccess()
{
//arrange
var calculator = new RPNCalculator();
string[] expectedTokens = new[] { "4", "5", "2", "*", "+" };
string input = "4+5*2";
//act
var actualTokens = calculator.Tokenize(input);
//assert
Assert.Equal(expectedTokens, actualTokens);
}
[Fact]
public void Tokenize_TwoOperationsWithBrackets_SholdReturnSuccess()
{
//arrange
var calculator = new RPNCalculator();
string[] expectedTokens = new[] { "4", "5", "2", "+", "*" };
string input = "4*(5+2)";
//act
var actualTokens = calculator.Tokenize(input);
//assert
Assert.Equal(expectedTokens, actualTokens);
}
[Fact]
public void Tokenize_TwoOperationsInsideWithSamePriorityBrackets_SholdReturnSuccess()
{
//arrange
var calculator = new RPNCalculator();
string[] expectedTokens = new[] { "4", "5", "2", "+", "1", "-", "*" };
string input = "4*(5+2-1)";
//act
var actualTokens = calculator.Tokenize(input);
//assert
Assert.Equal(expectedTokens, actualTokens);
}
[Fact]
public void Tokenize_TwoOperationsInsideWithGreaterFirstPriorityInBrackets_SholdReturnSuccess()
{
//arrange
var calculator = new RPNCalculator();
string[] expectedTokens = new[] { "4", "5", "2", "*", "1", "-", "*" };
string input = "4*(5*2-1)";
//act
var actualTokens = calculator.Tokenize(input);
//assert
Assert.Equal(expectedTokens, actualTokens);
}
[Fact]
public void Tokenize_PowerOfTwoBracketGroups_SholdReturnSuccess()
{
//arrange
var calculator = new RPNCalculator();
string[] expectedTokens = new[] { "4", "2", "*", "2", "-", "7", "2", "2", "*", "-", "^" };
string input = "(4*2-2)^(7-2*2)";
//act
var actualTokens = calculator.Tokenize(input);
//assert
Assert.Equal(expectedTokens, actualTokens);
}
//------------
[Fact]
public void Calculate_SingleOperation_SholdReturnThreeTokens()
{
//arrange
var calculator = new RPNCalculator();
double rightAnswer = 9;
string input = "4+5";
//act
var answer = calculator.Calculate(input);
//assert
double eps = 0.000001;
Assert.True(Math.Abs(rightAnswer - answer) < eps);
}
[Fact]
public void Calculate_TwoOperationsWithSamePriority_SholdReturnThreeTokens()
{
//arrange
var calculator = new RPNCalculator();
double rightAnswer = 8;
string input = "4+5-1";
//act
var answer = calculator.Calculate(input);
//assert
double eps = 0.000001;
Assert.True(Math.Abs(rightAnswer - answer) < eps);
}
[Fact]
public void Calculate_TwoOperationsWithLargerPriorityInFirstOperation_SholdReturnSuccess()
{
//arrange
var calculator = new RPNCalculator();
string input = "4*5-1";
double rightAnswer = 19;
//act
var answer = calculator.Calculate(input);
//assert
double eps = 0.000001;
Assert.True(Math.Abs(rightAnswer - answer) < eps);
}
[Fact]
public void Calculate_TwoOperationsWithLargerPriorityInSecondOperation_SholdReturnSuccess()
{
//arrange
var calculator = new RPNCalculator();
string input = "4+5*2";
double rightAnswer = 14;
//act
var answer = calculator.Calculate(input);
//assert
double eps = 0.000001;
Assert.True(Math.Abs(rightAnswer - answer) < eps);
}
[Fact]
public void Calculate_TwoOperationsWithBrackets_SholdReturnSuccess()
{
//arrange
var calculator = new RPNCalculator();
string input = "4*(5+2)";
double rightAnswer = 28;
//act
var answer = calculator.Calculate(input);
//assert
double eps = 0.000001;
Assert.True(Math.Abs(rightAnswer - answer) < eps);
}
[Fact]
public void Calculate_TwoOperationsInsideWithSamePriorityBrackets_SholdReturnSuccess()
{
//arrange
var calculator = new RPNCalculator();
string input = "4*(5+2-1)";
var rightAnswer = 24;
//act
var answer = calculator.Calculate(input);
//assert
double eps = 0.000001;
Assert.True(Math.Abs(rightAnswer - answer) < eps);
}
[Fact]
public void Calculate_TwoOperationsInsideWithGreaterFirstPriorityInBrackets_SholdReturnSuccess()
{
//arrange
var calculator = new RPNCalculator();
string input = "4*(5*2-1)";
double rightAnswer = 36;
//act
var answer = calculator.Calculate(input);
//assert
double eps = 0.000001;
Assert.True(Math.Abs(rightAnswer - answer) < eps);
}
[Fact]
public void Calculate_PowerOfTwoBracketGroups_SholdReturnSuccess()
{
//arrange
var calculator = new RPNCalculator();
string input = "(4*2-2)^(7-2*2)";
double rightAnswer = 216;
//act
var answer = calculator.Calculate(input);
//assert
double eps = 0.000001;
Assert.True(Math.Abs(rightAnswer - answer) < eps);
}
}
}
|
Java
|
UTF-8
| 247 | 1.898438 | 2 |
[] |
no_license
|
package pl.sda.design.pattern.singleton;
import org.junit.Test;
/**
* Created by adam.
*/
public class FileSystemReaderTest {
@Test
public void testIfContentIsEmpty() {
FileSystemReader.INSTANCE.showDiskContent("d");
}
}
|
C
|
UTF-8
| 337 | 3.53125 | 4 |
[] |
no_license
|
#include <stdio.h>
#include <stdlib.h>
int main()
{
int n, i; // Size of the array
scanf("%d", &n);
int *a; // Label for the array
a = (int *) malloc(n*sizeof(int)); // Allocating memory for the array
for (i = 0; i < n; i++) // Taking array as input
scanf("%d", &a[i]);
printf("%d\n", find_max(n, a));
return 0;
}
|
C#
|
UTF-8
| 12,358 | 3.078125 | 3 |
[
"MIT"
] |
permissive
|
using System;
using System.Text;
using System.Security.Cryptography;
using System.IO;
using System.Text.RegularExpressions;
using System.Collections;
/// <summary>
/// MySecurity(安全类) 的摘要说明。
/// </summary>
public class MySecurity
{
/// <summary>
/// 初始化安全类
/// </summary>
public MySecurity()
{
///默认密码
key = "0123456789";
}
private string key; //默认密钥
private byte[] sKey;
private byte[] sIV;
#region 加密字符串
/// <summary>
/// 加密字符串
/// </summary>
/// <param name="inputStr">输入字符串</param>
/// <param name="keyStr">密码,可以为“”</param>
/// <returns>输出加密后字符串</returns>
static public string SEncryptString(string inputStr, string keyStr)
{
MySecurity ws = new MySecurity();
return ws.EncryptString(inputStr, keyStr);
}
/// <summary>
/// 加密字符串
/// </summary>
/// <param name="inputStr">输入字符串</param>
/// <param name="keyStr">密码,可以为“”</param>
/// <returns>输出加密后字符串</returns>
public string EncryptString(string inputStr, string keyStr)
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
if (keyStr == "")
keyStr = key;
byte[] inputByteArray = Encoding.Default.GetBytes(inputStr);
byte[] keyByteArray = Encoding.Default.GetBytes(keyStr);
SHA1 ha = new SHA1Managed();
byte[] hb = ha.ComputeHash(keyByteArray);
sKey = new byte[8];
sIV = new byte[8];
for (int i = 0; i < 8; i++)
sKey[i] = hb[i];
for (int i = 8; i < 16; i++)
sIV[i - 8] = hb[i];
des.Key = sKey;
des.IV = sIV;
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
StringBuilder ret = new StringBuilder();
foreach (byte b in ms.ToArray())
{
ret.AppendFormat("{0:X2}", b);
}
cs.Close();
ms.Close();
return ret.ToString();
}
#endregion
#region 加密字符串 密钥为系统默认 0123456789
/// <summary>
/// 加密字符串 密钥为系统默认
/// </summary>
/// <param name="inputStr">输入字符串</param>
/// <returns>输出加密后字符串</returns>
static public string SEncryptString(string inputStr)
{
MySecurity ws = new MySecurity();
return ws.EncryptString(inputStr, "");
}
#endregion
#region 加密文件
/// <summary>
/// 加密文件
/// </summary>
/// <param name="filePath">输入文件路径</param>
/// <param name="savePath">加密后输出文件路径</param>
/// <param name="keyStr">密码,可以为“”</param>
/// <returns></returns>
public bool EncryptFile(string filePath, string savePath, string keyStr)
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
if (keyStr == "")
keyStr = key;
FileStream fs = File.OpenRead(filePath);
byte[] inputByteArray = new byte[fs.Length];
fs.Read(inputByteArray, 0, (int)fs.Length);
fs.Close();
byte[] keyByteArray = Encoding.Default.GetBytes(keyStr);
SHA1 ha = new SHA1Managed();
byte[] hb = ha.ComputeHash(keyByteArray);
sKey = new byte[8];
sIV = new byte[8];
for (int i = 0; i < 8; i++)
sKey[i] = hb[i];
for (int i = 8; i < 16; i++)
sIV[i - 8] = hb[i];
des.Key = sKey;
des.IV = sIV;
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
fs = File.OpenWrite(savePath);
foreach (byte b in ms.ToArray())
{
fs.WriteByte(b);
}
fs.Close();
cs.Close();
ms.Close();
return true;
}
#endregion
#region 解密字符串
/// <summary>
/// 解密字符串
/// </summary>
/// <param name="inputStr">要解密的字符串</param>
/// <param name="keyStr">密钥</param>
/// <returns>解密后的结果</returns>
static public string SDecryptString(string inputStr, string keyStr)
{
MySecurity ws = new MySecurity();
return ws.DecryptString(inputStr, keyStr);
}
/// <summary>
/// 解密字符串 密钥为系统默认
/// </summary>
/// <param name="inputStr">要解密的字符串</param>
/// <returns>解密后的结果</returns>
static public string SDecryptString(string inputStr)
{
MySecurity ws = new MySecurity();
return ws.DecryptString(inputStr, "");
}
/// <summary>
/// 解密字符串
/// </summary>
/// <param name="inputStr">要解密的字符串</param>
/// <param name="keyStr">密钥</param>
/// <returns>解密后的结果</returns>
public string DecryptString(string inputStr, string keyStr)
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
if (keyStr == "")
keyStr = key;
byte[] inputByteArray = new byte[inputStr.Length / 2];
for (int x = 0; x < inputStr.Length / 2; x++)
{
int i = (Convert.ToInt32(inputStr.Substring(x * 2, 2), 16));
inputByteArray[x] = (byte)i;
}
byte[] keyByteArray = Encoding.Default.GetBytes(keyStr);
SHA1 ha = new SHA1Managed();
byte[] hb = ha.ComputeHash(keyByteArray);
sKey = new byte[8];
sIV = new byte[8];
for (int i = 0; i < 8; i++)
sKey[i] = hb[i];
for (int i = 8; i < 16; i++)
sIV[i - 8] = hb[i];
des.Key = sKey;
des.IV = sIV;
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
StringBuilder ret = new StringBuilder();
return System.Text.Encoding.Default.GetString(ms.ToArray());
}
#endregion
#region 解密文件
/// <summary>
/// 解密文件
/// </summary>
/// <param name="filePath">输入文件路径</param>
/// <param name="savePath">解密后输出文件路径</param>
/// <param name="keyStr">密码,可以为“”</param>
/// <returns></returns>
public bool DecryptFile(string filePath, string savePath, string keyStr)
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
if (keyStr == "")
keyStr = key;
FileStream fs = File.OpenRead(filePath);
byte[] inputByteArray = new byte[fs.Length];
fs.Read(inputByteArray, 0, (int)fs.Length);
fs.Close();
byte[] keyByteArray = Encoding.Default.GetBytes(keyStr);
SHA1 ha = new SHA1Managed();
byte[] hb = ha.ComputeHash(keyByteArray);
sKey = new byte[8];
sIV = new byte[8];
for (int i = 0; i < 8; i++)
sKey[i] = hb[i];
for (int i = 8; i < 16; i++)
sIV[i - 8] = hb[i];
des.Key = sKey;
des.IV = sIV;
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
fs = File.OpenWrite(savePath);
foreach (byte b in ms.ToArray())
{
fs.WriteByte(b);
}
fs.Close();
cs.Close();
ms.Close();
return true;
}
#endregion
#region MD5加密
/// <summary>
/// 128位MD5算法加密字符串
/// </summary>
/// <param name="text">要加密的字符串</param>
public static string MD5(string text)
{
//如果字符串为空,则返回
if (string.IsNullOrEmpty(text))
{
return "";
}
//返回MD5值的字符串表示
return MD5(System.Text.Encoding.Unicode.GetBytes(text));
}
/// <summary>
/// 128位MD5算法加密Byte数组
/// </summary>
/// <param name="data">要加密的Byte数组</param>
public static string MD5(byte[] data)
{
//如果Byte数组为空,则返回
if (data.Length==0)
{
return "";
}
try
{
//创建MD5密码服务提供程序
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
//计算传入的字节数组的哈希值
byte[] result = md5.ComputeHash(data);
//释放资源
md5.Clear();
//返回MD5值的字符串表示
return Convert.ToBase64String(result);
}
catch
{
//LogHelper.WriteTraceLog(TraceLogLevel.Error, ex.Message);
return "";
}
}
public static string Md5Sum(string text)
{
//如果字符串为空,则返回
if (string.IsNullOrEmpty(text))
{
return "";
}
//返回MD5值的字符串表示
return Md5Sum(System.Text.Encoding.UTF8.GetBytes(text));
}
public static string Md5Sum(byte[] bs)
{
// 创建md5 对象
System.Security.Cryptography.MD5 md5;
md5 = System.Security.Cryptography.MD5CryptoServiceProvider.Create();
// 生成16位的二进制校验码
byte[] hashBytes = md5.ComputeHash(bs);
// 转为32位字符串
string hashString = "";
for (int i = 0; i < hashBytes.Length; i++)
{
hashString += System.Convert.ToString(hashBytes[i], 16).PadLeft(2, '0');
}
return hashString.PadLeft(32, '0');
}
#endregion
#region Base64加密
/// <summary>
/// Base64加密
/// </summary>
/// <param name="text">要加密的字符串</param>
/// <returns></returns>
public static string EncodeBase64(string text)
{
//如果字符串为空,则返回
if (string.IsNullOrEmpty(text))
{
return "";
}
try
{
char[] Base64Code = new char[]{'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T',
'U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n',
'o','p','q','r','s','t','u','v','w','x','y','z','0','1','2','3','4','5','6','7',
'8','9','+','/','='};
byte empty = (byte)0;
ArrayList byteMessage = new ArrayList(Encoding.Default.GetBytes(text));
StringBuilder outmessage;
int messageLen = byteMessage.Count;
int page = messageLen / 3;
int use = 0;
if ((use = messageLen % 3) > 0)
{
for (int i = 0; i < 3 - use; i++)
byteMessage.Add(empty);
page++;
}
outmessage = new System.Text.StringBuilder(page * 4);
for (int i = 0; i < page; i++)
{
byte[] instr = new byte[3];
instr[0] = (byte)byteMessage[i * 3];
instr[1] = (byte)byteMessage[i * 3 + 1];
instr[2] = (byte)byteMessage[i * 3 + 2];
int[] outstr = new int[4];
outstr[0] = instr[0] >> 2;
outstr[1] = ((instr[0] & 0x03) << 4) ^ (instr[1] >> 4);
if (!instr[1].Equals(empty))
outstr[2] = ((instr[1] & 0x0f) << 2) ^ (instr[2] >> 6);
else
outstr[2] = 64;
if (!instr[2].Equals(empty))
outstr[3] = (instr[2] & 0x3f);
else
outstr[3] = 64;
outmessage.Append(Base64Code[outstr[0]]);
outmessage.Append(Base64Code[outstr[1]]);
outmessage.Append(Base64Code[outstr[2]]);
outmessage.Append(Base64Code[outstr[3]]);
}
return outmessage.ToString();
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region Base64解密
/// <summary>
/// Base64解密
/// </summary>
/// <param name="text">要解密的字符串</param>
public static string DecodeBase64(string text)
{
//如果字符串为空,则返回
if (string.IsNullOrEmpty(text))
{
return "";
}
//将空格替换为加号
text = text.Replace(" ", "+");
try
{
if ((text.Length % 4) != 0)
{
return "包含不正确的BASE64编码";
}
if (!Regex.IsMatch(text, "^[A-Z0-9/+=]*$", RegexOptions.IgnoreCase))
{
return "包含不正确的BASE64编码";
}
string Base64Code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
int page = text.Length / 4;
ArrayList outMessage = new ArrayList(page * 3);
char[] message = text.ToCharArray();
for (int i = 0; i < page; i++)
{
byte[] instr = new byte[4];
instr[0] = (byte)Base64Code.IndexOf(message[i * 4]);
instr[1] = (byte)Base64Code.IndexOf(message[i * 4 + 1]);
instr[2] = (byte)Base64Code.IndexOf(message[i * 4 + 2]);
instr[3] = (byte)Base64Code.IndexOf(message[i * 4 + 3]);
byte[] outstr = new byte[3];
outstr[0] = (byte)((instr[0] << 2) ^ ((instr[1] & 0x30) >> 4));
if (instr[2] != 64)
{
outstr[1] = (byte)((instr[1] << 4) ^ ((instr[2] & 0x3c) >> 2));
}
else
{
outstr[2] = 0;
}
if (instr[3] != 64)
{
outstr[2] = (byte)((instr[2] << 6) ^ instr[3]);
}
else
{
outstr[2] = 0;
}
outMessage.Add(outstr[0]);
if (outstr[1] != 0)
outMessage.Add(outstr[1]);
if (outstr[2] != 0)
outMessage.Add(outstr[2]);
}
byte[] outbyte = (byte[])outMessage.ToArray(Type.GetType("System.Byte"));
return Encoding.Default.GetString(outbyte);
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
}
|
Java
|
UTF-8
| 476 | 1.992188 | 2 |
[] |
no_license
|
package ems.v2.service;
import ems.v2.model.Attendance;
import ems.v2.model.Employee;
import org.springframework.stereotype.Service;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
public interface AttendanceService {
Map<String, String> addAttendance(Employee employee);
List<Attendance> findAllAttendance();
// List<Attendance> getAttendanceByEmployeeId(Employee employee);
List<Attendance> getAttendanceByEmployeeId(Long id);
}
|
Python
|
UTF-8
| 3,136 | 2.921875 | 3 |
[] |
no_license
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# MayCLabel.py
#
# Copyleft 2010 Informática al Alcance de Todos (CA)
#
# 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 2 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, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
# MA 02110-1301, USA.
import pygame
import os.path
from MayCNucleo import MayCNucleo
from MayCObjeto import MayCObjeto
class MayCLabel(MayCObjeto):
def __init__(self,p_Texto,p_ID,p_Coordenadas,p_Color,p_Habilitado=True):
#Propiedades
self.Texto = p_Texto
self.Color = p_Color
self.CrearLabel()
#Tipo de Objeto
self.T_Objeto = 'Etiqueta'
p_tamano = self.Texto_Final.get_size()
MayCObjeto.__init__(self,p_ID,p_Coordenadas,p_tamano,p_Habilitado)
self.Nucleo = MayCNucleo()
self.PosenPantalla = self.Nucleo.ObtPosicion((self.pos_x,self.pos_y))
self.Nucleo.Agregar(self)
def ObtInterface(self):
return self.Texto_Final
def Insertar(self):
if (self.Contenedor == True):
self.Interface_Padre.blit(self.Texto_Final,(self.pos_x,self.pos_y))
else:
self.Nucleo.Insertar(self)
def Negrita(self, p_valor = False):
"""
Habilita el dibujado de la fuente en Negrita mientras que esta
lo soporte, en caso contrario pygame emula dicho modo.
"""
self.Fuente.set_bold(value)
def Cursiva(self, p_valor = False):
"""
Habilita la imitacion que da de texto en cursiva, por ende como en
el caso de bold() el tipo de fuente tiene que poder soportar el
mismo.
"""
self.Fuente.set_italic(value)
def CrearLabel(self):
self.Fuente = pygame.font.SysFont("arial", 16)
if self.Color == "blanco" or self.Color == "Blanco":
self.Texto_Final = self.Fuente.render(self.Texto, True, (255, 255, 255), (0, 0, 0))
elif self.Color == "rojo" or self.Color == "Rojo":
self.Texto_Final = self.Fuente.render(self.Texto, True, (224, 23, 23), (0, 0, 0))
self.CTamano(self.Texto_Final.get_size())
def Append(self, Mensaje):
self.Texto += Mensaje
self.CrearLabel()
self.Insertar()
def Text(self, Mensaje):
self.Texto = Mensaje
self.CrearLabel()
self.Insertar()
|
Python
|
UTF-8
| 219 | 3.03125 | 3 |
[] |
no_license
|
# 딕셔너리 요소 삭제
a = {'name': 'Park ISeul', 'sex': 'female', 'position': 'student'}
print('a = ', a)
print("a.pop('position') = ", a.pop('position'))
print('a = ', a)
del a['name']
print("del a['name'] = ", a)
|
Go
|
UTF-8
| 3,325 | 2.71875 | 3 |
[
"Apache-2.0"
] |
permissive
|
package server
import (
"net/http"
"plateau/store"
"sync"
"github.com/gorilla/mux"
"github.com/gorilla/sessions"
)
// ServerName is the server name.
const ServerName = "plateau"
// Server is basically the *plateau* runtime.
type Server struct {
game Game
matchRuntimesMux sync.Mutex
matchRuntimes map[string]*matchRuntime
store store.Store
sessionStore sessions.Store
router *mux.Router
httpServer *http.Server
doneWg sync.WaitGroup
}
// New initializes the `Game` *gm* and returns a new `Server`.
func New(gm Game, str store.Store) (*Server, error) {
s := &Server{
game: gm,
matchRuntimes: make(map[string]*matchRuntime),
store: str,
}
if err := gm.Init(); err != nil {
return nil, err
}
return s, nil
}
// Init returns a new `Server` with in addition the *gorilla/mux* router and the *sessionStore* initialized.
func Init(listener string, gm Game, str store.Store, sessionStore ...sessions.Store) (*Server, error) {
s, err := New(gm, str)
if err != nil {
return nil, err
}
if len(sessionStore) == 0 {
sessionStore = append(sessionStore, sessions.NewCookieStore([]byte("")))
}
s.sessionStore = sessionStore[0]
s.router = mux.NewRouter().StrictSlash(true)
s.httpServer = &http.Server{
Addr: listener,
Handler: s.router,
}
ar := s.router.PathPrefix("/api").Subrouter()
ar.Use(s.loginMiddleware)
ar.
PathPrefix("/game").
Methods("GET").
HandlerFunc(s.getGameDefinitionHandler).
Name("readGame")
ar.
PathPrefix("/players/{name}").
Methods("GET").
HandlerFunc(s.readPlayerHandler).
Name("readPlayer")
ar.
PathPrefix("/players").
Methods("GET").
HandlerFunc(s.getPlayersNameHandler).
Name("getPlayersName")
ar.
PathPrefix("/matchs/{id}/players").
Methods("GET").
HandlerFunc(s.getMatchPlayersNameHandler).
Name("getMatchPlayersName")
ar.
PathPrefix("/matchs/{id}/notifications").
Methods("GET").
HandlerFunc(s.streamMatchNotificationsHandler).
Name("streamMatchNotifications")
ar.
PathPrefix("/matchs/{id}/deals").
Methods("GET").
HandlerFunc(s.getMatchDealsHandler).
Name("getMatchDeals")
ar.
PathPrefix("/matchs/{id}").
Methods("GET").
HandlerFunc(s.readMatchHandler).
Name("readMatch")
ar.
PathPrefix("/matchs/{id}").
Methods("PATCH").
HandlerFunc(s.patchMatchHandler).
Name("patchMatch")
ar.
PathPrefix("/matchs").
Methods("GET").
HandlerFunc(s.getMatchIDsHandler).
Name("getMatchIDs")
ar.
PathPrefix("/matchs").
Methods("POST").
HandlerFunc(s.createMatchHandler).
Name("createMatch")
s.router.
PathPrefix("/user/register").
Methods("POST").
HandlerFunc(s.registerUserHandler).
Name("registerUser")
s.router.
PathPrefix("/user/login").
Methods("POST").
HandlerFunc(s.loginUserHandler).
Name("loginUser")
s.router.
PathPrefix("/user/logout").
Methods("DELETE").
HandlerFunc(s.logoutUserHandler).
Name("logoutUser")
return s, nil
}
// Start starts the server.
func (s *Server) Start() error {
if err := s.store.Open(); err != nil {
return err
}
s.doneWg.Add(1)
return nil
}
// Stop stops the server.
func (s *Server) Stop() error {
s.doneWg.Done()
s.doneWg.Wait()
return s.store.Close()
}
// Listen starts the HTTP server.
func (s *Server) Listen() error {
return s.httpServer.ListenAndServe()
}
|
Java
|
UTF-8
| 1,022 | 2.96875 | 3 |
[] |
no_license
|
package com.plf.tool.common.normal;
import cn.hutool.core.collection.CollectionUtil;
import java.util.ArrayList;
import java.util.List;
/**
* 分割数组的工具类
*/
public class SpliceArrayList<T> {
/**
* 分割数组
* @param list 需要分割的列表
* @param num 分成多少列
* @return
*/
public static <T> List<List<T>> spliceArrayList(List<T> list,int num){
if(CollectionUtil.isEmpty(list)){
return null;
}
List<List<T>> result = new ArrayList<>();
if(list.size()<=num){
result.add(list);
}else{
int size = list.size()/num;
for(int i=0;i<num;i++){
List<T> e = new ArrayList<>();
if(i<=num-2){
e.addAll(list.subList(i*size,(i+1)*size));
}else{
e.addAll(list.subList(i*size,list.size()));
}
result.add(e);
}
}
return result;
}
}
|
JavaScript
|
UTF-8
| 2,826 | 2.703125 | 3 |
[] |
no_license
|
import React from "react"
import moment from "moment"
import "./index.css"
export default class Event extends React.Component {
constructor(props) {
super(props)
this.state = {
eventInfo: {},
reply: "",
message: "",
show: false
}
}
componentDidMount() {
const { eventId } = this.props.match.params
fetch(`https://seizethepartyevents.herokuapp.com/events/${eventId}`, {
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
}
}).then(response => {
return response.json()
}).then(json => {
this.setState({
eventInfo: json
})
})
}
handleAlert = () => {
if (this.state.reply === "Yes") {
this.setState({
message: "Yey, you are joining the party!",
show: !this.state.show
})
setTimeout(() => {
this.setState({ message: "", show: "" })
}, 3500)
} else if (this.state.reply === "No") {
this.setState({
message: "See you at the next party!",
show: !this.state.show
})
setTimeout(() => {
this.setState({ message: "", show: "" })
}, 3500)
}
}
handleRSVP = event => {
event.preventDefault()
this.setState({
reply: event.target.value
}, () => {
const { eventId } = this.props.match.params
const { _id } = this.props.match.params
fetch(`https://seizethepartyevents.herokuapp.com/events/${eventId}/guests/${_id}`, {
method: "PUT",
headers: {
Accept: "application/json",
"Content-Type": "application/json"
},
body: JSON.stringify({ attending: this.state.reply })
})
this.handleAlert()
})
}
render() {
const { date } = this.state.eventInfo
const formattedData = moment(date).format("dddd MMM Do YYYY")
return (
<div>
<div className={this.state.show ? "show" : "hide"}>
<div className="message">{this.state.message}</div>
</div>
<div className="event-page" style={{ backgroundImage: `url(${this.state.eventInfo.backgroundImage})` }}>
<div className="copy-container">
<h1>{this.state.eventInfo.title}</h1>
<h2>{this.state.eventInfo.description}</h2>
<h3>Hosted by: {this.state.eventInfo.hostedBy}</h3><br />
<h3>{formattedData}, {this.state.eventInfo.startTime} – {this.state.eventInfo.endTime}</h3>
<h3>{this.state.eventInfo.location}</h3>
</div>
<div className="event-CTA-container">
<button value="Yes" onClick={this.handleRSVP}>I‘m joining</button>
<button value="No" onClick={this.handleRSVP}>I can‘t join</button>
</div>
</div>
</div>
)
}
}
|
Java
|
UTF-8
| 1,295 | 2.84375 | 3 |
[] |
no_license
|
package persistencia;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import modelo.IFacturacionDeVentas;
import modelo.Venta;
public class EnMemoriaIFacturacionDeVentas implements IFacturacionDeVentas {
private ArrayList<Venta> ventas = new ArrayList<Venta>();
@Override
public void guardarVenta(Venta venta) {
ventas.add(venta);
}
@Override
public boolean ventaGuardada(Venta venta) {
return ventas.contains(venta);
}
@Override
public ArrayList<String> obtenerVentas() {
ArrayList<String> stringsVentas = new ArrayList<String>();
for (Venta venta : ventas) {
stringsVentas.add(venta.toString());
}
return stringsVentas;
}
@Override
public ArrayList<String> obtenerVentasEnRango(LocalDate fechaInicial, LocalDate fechaFin) {
ArrayList<String> stringsVentas = new ArrayList<String>();
for (Venta venta : ventas) {
if (fechaEnRango(venta.devolverFechaYHora().toLocalDate(), fechaInicial, fechaFin)) {
stringsVentas.add(venta.toString());
}
}
return stringsVentas;
}
private boolean fechaEnRango(LocalDate fecha, LocalDate fechaInicial, LocalDate fechaFin) {
return (fechaInicial.isBefore(fecha) || fechaInicial.isEqual(fecha))
&& (fechaFin.isEqual(fecha) || fechaFin.isAfter(fecha));
}
}
|
PHP
|
UTF-8
| 3,797 | 2.53125 | 3 |
[
"Apache-2.0"
] |
permissive
|
<?php
$file = $argv[1];
$json = [];
if (is_file($file)) {
$content = file_get_contents($file);
$tokens = token_get_all($content);
// Copied from phpcpd
$tokensIgnoreList = [
T_INLINE_HTML => true,
T_COMMENT => true,
T_DOC_COMMENT => true,
T_OPEN_TAG => true,
T_OPEN_TAG_WITH_ECHO => true,
T_CLOSE_TAG => true,
T_WHITESPACE => true,
T_USE => true,
T_NS_SEPARATOR => true,
];
foreach($tokens as $token) {
if (is_array($token)) {
if (isset($tokensIgnoreList[$token[0]])) {
continue;
}
$json[] = [
'token_code' => $token[0],
'token_name' => token_name($token[0]),
'line' => $token[2],
'content' => $token[1],
'file' => $file
];
}
}
} else {
$rdi = new RecursiveDirectoryIterator($file);
foreach (new RecursiveIteratorIterator($rdi) as $file => $info) {
if ($file === '.' || $file === '..') {
} else {
$parts = pathinfo($file);
if (isset($parts['extension']) && $parts['extension'] === 'php') {
if (strpos($file, 'tests')) {
continue;
}
$content = file_get_contents($file);
$tokens = token_get_all($content);
// Copied from phpcpd
$tokensIgnoreList = [
T_INLINE_HTML => true,
T_COMMENT => true,
T_DOC_COMMENT => true,
T_OPEN_TAG => true,
T_OPEN_TAG_WITH_ECHO => true,
T_CLOSE_TAG => true,
T_WHITESPACE => true,
T_USE => true,
T_NS_SEPARATOR => true,
];
foreach($tokens as $token) {
if (is_array($token)) {
if (isset($tokensIgnoreList[$token[0]])) {
continue;
}
$json[] = [
'token_code' => $token[0],
'token_name' => token_name($token[0]),
'line' => $token[2],
'content' => $token[1],
'file' => $file
];
}
}
}
}
}
}
echo json_encode($json);
//echo "\n";
//echo "\n";
//$str = "5555555555,5556565656[565757575757,5758585858[585959595959595959]60],61],6263(63,6363),6364(64,6464,646464646464),6465(65,6565),6566(66,6666,666666666666),6667(67,6767,676767676767),6768(68,6868,686868686868),6869(69,6969,696969696969),6970(70,7070,707070707070),7071(71,7171),71727373(73,7373,737373737373),73);74}7577798080808080()80{81828282();82}8385878888888888()88{89909090(909191919191,919292929292,929393939393,939494949494,949595959595,959696969696,969797979797,979898989898,989999999999,99100100100100100,100101101101101101,101102102102102102,102103103103103103,103104104104104104,104105105105105105,105106106106106106,106107107107107107,107108108108108108,108109109109109109,109110110110110110,110111111111111111,111112112112112112,112113113113113113,113);114}115117128129129129129129()129{130131131=131131()131131131131(131,131131()131131[131]);131133133=133133133133();133134134134(134,134134134134);13";
//$str = str_replace([",", "[", "]", "(", ")", "{", "}", ";", "="], "", $str);
//$tokens = str_split($str, 3);
//foreach ($tokens as $token) {
//echo token_name($token);
//}
|
C#
|
UTF-8
| 3,432 | 2.765625 | 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;
namespace Client
{
public partial class Login : Form
{
UserService userService = new UserService();
UserServiceReference.User User;
public Login()
{
InitializeComponent();
ListAllUsers();
btnLogin.Focus();
}
//Metode som bliver kaldt hver gang se bruger fanen bliver trykket på
private void ListAllUsers()
{
List<UserServiceReference.User> users = userService.GetAllUsers().ToList();
tevAllUsers.Nodes.Clear();
foreach (var user in users)
{
TreeNode treeNode = new TreeNode();
treeNode.Text = user.Id + ", " + user.FirstName + " " + user.LastName + ", " + user.Role;
treeNode.Tag = user;
tevAllUsers.Nodes.Add(treeNode);
}
}
private void btnLogin_Click(object sender, EventArgs e)
{
int userId;
bool result = Int32.TryParse(txtUserId.Text, out userId); //smier bool ud om den kunne lave den om, og hvis ja, så smider den også tallet ud
if (result)
{
UserServiceReference.User user = userService.Login(userId, txtPassword.Text);
if(user != null)
{
ShowSelectedForm(user); //Åbner den rigitge form til user
}
else
{
string s = string.Format("Fejl i login", txtUserId.Text);
MessageBox.Show(s, "Fejl - Login");
}
}
else
{
string s = string.Format("Bruger forkert", txtUserId.Text);
MessageBox.Show(s, "Login Fejl");
}
}
private void Login_FormClosing(object sender, FormClosingEventArgs e)
{
Application.Exit(); //Lukker formen
}
private void ShowSelectedForm(UserServiceReference.User user)
{
if (user.Role == "Admin")
{
this.Hide();
AdminClientFront adminClientFront = new AdminClientFront(user);
adminClientFront.Show();
}
else if (user.Role == "Supporter")
{
this.Hide();
SupporterCalendar supporterCalendar = new SupporterCalendar(user);
supporterCalendar.Show();
}
else if (user.Role == "Sælger")
{
this.Hide();
CreateBookingSalesman createBookingSælger = new CreateBookingSalesman(user);
createBookingSælger.Show();
}
}
private void tevAllUsers_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
{
//Skriver selected user ud på labels og søgefelt id
UserServiceReference.User user = e.Node.Tag as UserServiceReference.User; //den man har klikket på
Console.WriteLine(user.FirstName);
User = user;
ShowSelectedForm(User);
}
private void Login_Load(object sender, EventArgs e)
{
}
}
}
|
Java
|
UTF-8
| 1,954 | 2.28125 | 2 |
[] |
no_license
|
package com.itemconfiguration.export.bilder.block.itemfieldconfig;
import com.itemconfiguration.domain.Item;
import com.itemconfiguration.domain.ItemFieldConfig;
import com.itemconfiguration.domain.wrapper.ItemWithFieldsMap;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Component
public class ItemFieldConfigBlockBuilder {
@Resource(name = "ItemFieldConfigWithMandatoryDataLinesBuilder")
private ItemFieldConfigLinesBuilder itemFieldConfigWithMandatoryDataLinesBuilder;
@Resource(name = "ItemFieldConfigWithoutMandatoryDataLinesBuilder")
private ItemFieldConfigLinesBuilder itemFieldConfigWithoutMandatoryDataLinesBuilder;
public List<String> build(ItemWithFieldsMap itemWraper) {
Item item = itemWraper.getItem();
if (CollectionUtils.isEmpty(item.getItemFieldConfigs())) {
return Collections.emptyList();
}
List<String> result = new ArrayList<>();
Map<Boolean, List<ItemFieldConfig>> fieldByContainsMandatoryData = groupByContainsMandatoryData(item.getItemFieldConfigs());
result.addAll(itemFieldConfigWithMandatoryDataLinesBuilder.buildLines(fieldByContainsMandatoryData.get(true), item));
result.addAll(itemFieldConfigWithoutMandatoryDataLinesBuilder.buildLines(fieldByContainsMandatoryData.get(false), item));
return result;
}
protected Map<Boolean, List<ItemFieldConfig>> groupByContainsMandatoryData(List<ItemFieldConfig> itemFieldConfigs) {
if (CollectionUtils.isEmpty(itemFieldConfigs)) {
return Collections.emptyMap();
}
return itemFieldConfigs.stream()
.collect(Collectors.partitioningBy(itemFieldConfig -> CollectionUtils.isNotEmpty(itemFieldConfig.getMandatoryFields())
|| CollectionUtils.isNotEmpty(itemFieldConfig.getMandatoryTranslations())));
}
}
|
Markdown
|
UTF-8
| 14,882 | 3.328125 | 3 |
[] |
no_license
|
---
title: K近邻法(KNN)原理小结
date: 2017-10-18 14:00:16
tags:
- KNN
---
K近邻法(k-nearst neighbors,KNN)是一种很基本的机器学习方法了,在我们平常的生活中也会不自主的应用。比如,我们判断一个人的人品,只需要观察他来往最密切的几个人的人品好坏就可以得出了。这里就运用了KNN的思想。KNN方法既可以做分类,也可以做回归,这点和决策树算法相同。
KNN做回归和分类的主要区别在于最后做预测时候的决策方式不同。KNN做分类预测时,一般是选择多数表决法,即训练集里和预测的样本特征最近的K个样本,预测为里面有最多类别数的类别。而KNN做回归时,一般是选择平均法,即最近的K个样本的样本输出的平均值作为回归预测值。由于两者区别不大,虽然本文主要是讲解KNN的分类方法,但思想对KNN的回归方法也适用。由于scikit-learn里只使用了蛮力实现(brute-force),KD树实现(KDTree)和球树(BallTree)实现,本文只讨论这几种算法的实现原理。其余的实现方法比如BBF树,MVP树等,在这里不做讨论。
## KNN算法三要素
KNN算法我们主要要考虑三个重要的要素,对于固定的训练集,只要这三点确定了,算法的预测方式也就决定了。这三个最终的要素是k值的选取,距离度量的方式和分类决策规则。
对于分类决策规则,一般都是使用前面提到的多数表决法。所以我们重点是关注与k值的选择和距离的度量方式。
对于k值的选择,没有一个固定的经验,一般根据样本的分布,选择一个较小的值,可以通过交叉验证选择一个合适的k值。
选择较小的k值,就相当于用较小的领域中的训练实例进行预测,训练误差会减小,只有与输入实例较近或相似的训练实例才会对预测结果起作用,与此同时带来的问题是泛化误差会增大,换句话说,K值的减小就意味着整体模型变得复杂,容易发生过拟合;
选择较大的k值,就相当于用较大领域中的训练实例进行预测,其优点是可以减少泛化误差,但缺点是训练误差会增大。这时候,与输入实例较远(不相似的)训练实例也会对预测器作用,使预测发生错误,且K值的增大就意味着整体的模型变得简单。
一个极端是k等于样本数m,则完全没有分类,此时无论输入实例是什么,都只是简单的预测它属于在训练实例中最多的类,模型过于简单。
对于距离的度量,我们有很多的距离度量方式,但是最常用的是欧式距离,即对于两个n维向量x和y,两者的欧式距离定义为:
$$D(x,y) = \sqrt{(x_1-y_1)^2 + (x_2-y_2)^2 + ... + (x_n-y_n)^2} = \sqrt{\sum\limits_{i=1}^{n}(x_i-y_i)^2}$$
大多数情况下,欧式距离可以满足我们的需求,我们不需要再去操心距离的度量。
当然我们也可以用他的距离度量方式。比如曼哈顿距离,定义为:
$$D(x,y) =|x_1-y_1| + |x_2-y_2| + ... + |x_n-y_n| =\sum\limits_{i=1}^{n}|x_i-y_i|$$
更加通用点,比如闵可夫斯基距离(Minkowski Distance),定义为:
$$D(x,y) =\sqrt[p]{(|x_1-y_1|)^p + (|x_2-y_2|)^p + ... + (|x_n-y_n|)^p} =\sqrt[p]{\sum\limits_{i=1}^{n}(|x_i-y_i|)^p}$$
可以看出,欧式距离是闵可夫斯基距离距离在p=2时的特例,而曼哈顿距离是p=1时的特例。
<!--more-->
## KNN算法蛮力实现
从本节起,我们开始讨论KNN算法的实现方式。首先我们看看最想当然的方式。
既然我们要找到k个最近的邻居来做预测,那么我们只需要计算预测样本和所有训练集中的样本的距离,然后计算出最小的k个距离即可,接着多数表决,很容易做出预测。这个方法的确简单直接,在样本量少,样本特征少的时候有效。但是在实际运用中很多时候用不上,为什么呢?因为我们经常碰到样本的特征数有上千以上,样本量有几十万以上,如果我们这要去预测少量的测试集样本,算法的时间效率很成问题。因此,这个方法我们一般称之为蛮力实现。比较适合于少量样本的简单模型的时候用。
既然蛮力实现在特征多,样本多的时候很有局限性,那么我们有没有其他的好办法呢?有!这里我们讲解两种办法,一个是KD树实现,一个是球树实现。
## KNN算法之KD树实现原理
KD树算法没有一开始就尝试对测试样本分类,而是先对训练集建模,建立的模型就是KD树,建好了模型再对测试集做预测。所谓的KD树就是K个特征维度的树,注意这里的K和KNN中的K的意思不同。KNN中的K代表特征输出类别,KD树中的K代表样本特征的维数。为了防止混淆,后面我们称特征维数为n。
KD树算法包括三步,第一步是建树,第二部是搜索最近邻,最后一步是预测。
### KD树的建立
我们首先来看建树的方法。KD树建树采用的是从m个样本的n维特征中,分别计算n个特征的取值的方差,用方差最大的第k维特征$n_k$来作为根节点。对于这个特征,我们选择特征$n_k$的取值的中位数$n_{kv}$对应的样本作为划分点,对于所有第k维特征的取值小于$n_{kv}$的样本,我们划入左子树,对于第k维特征的取值大于等于$n_{kv}$的样本,我们划入右子树,对于左子树和右子树,我们采用和刚才同样的办法来找方差最大的特征来做更节点,递归的生成KD树。
具体流程如下图:
{% asset_img knn_1.jpg %}
比如我们有二维样本6个,{(2,3),(5,4),(9,6),(4,7),(8,1),(7,2)},构建kd树的具体步骤为:
1. 找到划分的特征。6个数据点在x,y维度上的数据方差分别为6.97,5.37,所以在x轴上方差更大,用第1维特征建树。
2. 确定划分点(7,2)。根据x维上的值将数据排序,6个数据的中值(所谓中值,即中间大小的值)为7,所以划分点的数据是(7,2)。这样,该节点的分割超平面就是通过(7,2)并垂直于:划分点维度的直线x=7;
3. 确定左子空间和右子空间。 分割超平面x=7将整个空间分为两部分:x<=7的部分为左子空间,包含3个节点={(2,3),(5,4),(4,7)};另一部分为右子空间,包含2个节点={(9,6),(8,1)}。
4. 用同样的办法划分左子树的节点{(2,3),(5,4),(4,7)}和右子树的节点{(9,6),(8,1)}。最终得到KD树。
最后得到的KD树如下:
{% asset_img knn_2.jpg %}
### KD树搜索最近邻
当我们生成KD树以后,就可以去预测测试集里面的样本目标点了。对于一个目标点,我们首先在KD树里面找到包含目标点的叶子节点。以目标点为圆心,以目标点到叶子节点样本实例的距离为半径,得到一个超球体,最近邻的点一定在这个超球体内部。然后返回叶子节点的父节点,检查另一个子节点包含的超矩形体是否和超球体相交,如果相交就到这个子节点寻找是否有更加近的近邻,有的话就更新最近邻。如果不相交那就简单了,我们直接返回父节点的父节点,在另一个子树继续搜索最近邻。当回溯到根节点时,算法结束,此时保存的最近邻节点就是最终的最近邻。
从上面的描述可以看出,KD树划分后可以大大减少无效的最近邻搜索,很多样本点由于所在的超矩形体和超球体不相交,根本不需要计算距离。大大节省了计算时间。
我们用3.1建立的KD树,来看对点(2,4.5)找最近邻的过程。
先进行二叉查找,先从(7,2)查找到(5,4)节点,在进行查找时是由y = 4为分割超平面的,由于查找点为y值为4.5,因此进入右子空间查找到(4,7),形成搜索路径<(7,2),(5,4),(4,7)>,但 (4,7)与目标查找点的距离为3.202,而(5,4)与查找点之间的距离为3.041,所以(5,4)为查询点的最近点; 以(2,4.5)为圆心,以3.041为半径作圆,如下图所示。可见该圆和y = 4超平面交割,所以需要进入(5,4)左子空间进行查找,也就是将(2,3)节点加入搜索路径中得<(7,2),(2,3)>;于是接着搜索至(2,3)叶子节点,(2,3)距离(2,4.5)比(5,4)要近,所以最近邻点更新为(2,3),最近距离更新为1.5;回溯查找至(5,4),直到最后回溯到根结点(7,2)的时候,以(2,4.5)为圆心1.5为半径作圆,并不和x = 7分割超平面交割,如下图所示。至此,搜索路径回溯完,返回最近邻点(2,3),最近距离1.5。
对应的图如下:
{% asset_img knn_3.jpg %}
### KD树预测
有了KD树搜索最近邻的办法,KD树的预测就很简单了,在KD树搜索最近邻的基础上,我们选择到了第一个最近邻样本,就把它置为已选。在第二轮中,我们忽略置为已选的样本,重新选择最近邻,这样跑k次,就得到了目标的K个最近邻,然后根据多数表决法,如果是KNN分类,预测为K个最近邻里面有最多类别数的类别。如果是KNN回归,用K个最近邻样本输出的平均值作为回归预测值。
## KNN算法之球树实现原理
KD树算法虽然提高了KNN搜索的效率,但是在某些时候效率并不高,比如当处理不均匀分布的数据集时,不管是近似方形,还是矩形,甚至正方形,都不是最好的使用形状,因为他们都有角。一个例子如下图:
{% asset_img knn_4.jpg %}
如果黑色的实例点离目标点星点再远一点,那么虚线圆会如红线所示那样扩大,导致与左上方矩形的右下角相交,既然相 交了,那么就要检查这个左上方矩形,而实际上,最近的点离星点的距离很近,检查左上方矩形区域已是多余。于此我们看见,KD树把二维平面划分成一个一个矩形,但矩形区域的角却是个难以处理的问题。
为了优化超矩形体导致的搜索效率的问题,牛人们引入了球树,这种结构可以优化上面的这种问题。
我们现在来看看球树建树和搜索最近邻的算法。
### 球树的建立
球树,顾名思义,就是每个分割块都是超球体,而不是KD树里面的超矩形体。
{% asset_img knn_5.jpg %}
我们看看具体的建树流程:
1. 先构建一个超球体,这个超球体是可以包含所有样本的最小球体。
2. 从球中选择一个离球的中心最远的点,然后选择第二个点离第一个点最远,将球中所有的点分配到离这两个聚类中心最近的一个上,然后计算每个聚类的中心,以及聚类能够包含它所有数据点所需的最小半径。这样我们得到了两个子超球体,和KD树里面的左右子树对应。
3. 对于这两个子超球体,递归执行步骤2). 最终得到了一个球树。
可以看出KD树和球树类似,主要区别在于球树得到的是节点样本组成的最小超球体,而KD得到的是节点样本组成的超矩形体,这个超球体要与对应的KD树的超矩形体小,这样在做最近邻搜索的时候,可以避免一些无谓的搜索。
### 球树搜索最近邻
使用球树找出给定目标点的最近邻方法是首先自上而下贯穿整棵树找出包含目标点所在的叶子,并在这个球里找出与目标点最邻近的点,这将确定出目标点距离它的最近邻点的一个上限值,然后跟KD树查找一样,检查兄弟结点,如果目标点到兄弟结点中心的距离超过兄弟结点的半径与当前的上限值之和,那么兄弟结点里不可能存在一个更近的点;否则的话,必须进一步检查位于兄弟结点以下的子树。
检查完兄弟节点后,我们向父节点回溯,继续搜索最小邻近值。当回溯到根节点时,此时的最小邻近值就是最终的搜索结果。
从上面的描述可以看出,KD树在搜索路径优化时使用的是两点之间的距离来判断,而球树使用的是两边之和大于第三边来判断,相对来说球树的判断更加复杂,但是却避免了更多的搜索,这是一个权衡。
## KNN算法的扩展
这里我们再讨论下KNN算法的扩展,限定半径最近邻算法。
有时候我们会遇到这样的问题,即样本中某系类别的样本非常的少,甚至少于K,这导致稀有类别样本在找K个最近邻的时候,会把距离其实较远的其他样本考虑进来,而导致预测不准确。为了解决这个问题,我们限定最近邻的一个最大距离,也就是说,我们只在一个距离范围内搜索所有的最近邻,这避免了上述问题。这个距离我们一般称为限定半径。
接着我们再讨论下另一种扩展,最近质心算法。这个算法比KNN还简单。它首先把样本按输出类别归类。对于第 L类的ClCl个样本。它会对这ClCl个样本的n维特征中每一维特征求平均值,最终该类别所有维度的n个平均值形成所谓的质心点。对于样本中的所有出现的类别,每个类别会最终得到一个质心点。当我们做预测时,仅仅需要比较预测样本和这些质心的距离,最小的距离对于的质心类别即为预测的类别。这个算法通常用在文本分类处理上。
## KNN算法小结
KNN算法是很基本的机器学习算法了,它非常容易学习,在维度很高的时候也有很好的分类效率,因此运用也很广泛,这里总结下KNN的优缺点。
KNN的主要优点有:
1. 理论成熟,思想简单,既可以用来做分类也可以用来做回归
2. 可用于非线性分类
3. 训练时间复杂度比支持向量机之类的算法低,仅为O(n)
4. 和朴素贝叶斯之类的算法比,对数据没有假设,准确度高,对异常点不敏感
5. 由于KNN方法主要靠周围有限的邻近的样本,而不是靠判别类域的方法来确定所属类别的,因此对于类域的交叉或重叠较多的待分样本集来说,KNN方法较其他方法更为适合
6. 该算法比较适用于样本容量比较大的类域的自动分类,而那些样本容量较小的类域采用这种算法比较容易产生误分
KNN的主要缺点有:
1. 计算量大,尤其是特征数非常多的时候
2. 样本不平衡的时候,对稀有类别的预测准确率低
3. KD树,球树之类的模型建立需要大量的内存
4. 使用懒散学习方法,基本上不学习,导致预测时速度比起逻辑回归之类的算法慢
5. 相比决策树模型,KNN模型可解释性不强
以上就是KNN算法原理的一个总结,希望可以帮到朋友们,尤其是在用scikit-learn学习KNN的朋友们。
|
Markdown
|
UTF-8
| 1,033 | 2.734375 | 3 |
[] |
no_license
|
## Assignment 3- GO Implementation of RAFT's Leader Election, Log Replication and Safety Property <br/>
### Description
This is a Go implementation of the 3 major components of Raft distributed consensus protocol. Raft is a protocol by which a cluster of nodes can maintain a replicated state machine. The state machine is kept in sync through the use of replicated log.
### RAFT Protocol Overview
<code>RAFT</code> protocol works for distributed systems. Which provides multiple entry points in architecture. Any server can crash at any time or there might be network partition in cluster. So single entry point will not work in case of distributed architecture.
The way RAFT handles problem of consensus is by way of electing a leader among cluster. By which, that entry point(leader) deals with all the incoming traffic from clients. If leader by any means goes down then there will be re-election to choose the new leader and the process goes on. We make sure that safety and liveness properties are maintained throughout.
|
C#
|
UTF-8
| 578 | 2.875 | 3 |
[] |
no_license
|
using System;
namespace mcontrol
{
public class MComboboxItem
{
private string m_Display;
private object m_Value;
public MComboboxItem(string mDisplay, object mValue)
{
m_Display = mDisplay;
m_Value = mValue;
}
public string MDisplay
{
get { return m_Display; }
}
public object MValue
{
get { return m_Value; }
}
public override string ToString()
{
return m_Display;
}
}
}
|
TypeScript
|
UTF-8
| 2,064 | 2.5625 | 3 |
[] |
no_license
|
import { Test, TestingModule } from '@nestjs/testing';
import { TemplatesService } from './templates.service';
import { getRepositoryToken } from '@nestjs/typeorm';
import { Template } from './template.entity';
import { CreateTemplateDto } from './create-template.dto';
const mockTemplateRepository = {
find: jest.fn().mockImplementation(() => {
const t1 = new Template();
t1.id = '12312';
return [t1];
}),
create: jest
.fn()
.mockImplementation(
(params: { languageId: string; content: string; userId: string }) => {
const tmp = new Template();
tmp.content = params.content;
tmp.userId = params.userId;
tmp.languageId = params.languageId;
return tmp;
},
),
save: jest.fn().mockImplementation((tmp: Template) => tmp),
};
describe('TemplatesService', () => {
let service: TemplatesService;
beforeEach(async () => {
const module: TestingModule = await Test.createTestingModule({
providers: [
TemplatesService,
{
provide: getRepositoryToken(Template),
useValue: mockTemplateRepository,
},
],
}).compile();
service = module.get<TemplatesService>(TemplatesService);
});
it('should be defined', () => {
expect(service).toBeDefined();
});
it("should list templates of given user's id", async () => {
const got = await service.findAll('12312312');
expect(got).toHaveLength(1);
});
it('should insert record with given dto', async () => {
const dto = new CreateTemplateDto();
dto.languageId = '1231231';
dto.content = 'sample';
const userId = '131231312';
const got = await service.create(userId, dto);
expect(mockTemplateRepository.create).toHaveBeenCalledWith({
languageId: dto.languageId,
content: dto.content,
userId,
});
expect(mockTemplateRepository.save).toHaveBeenCalled();
expect(got.userId).toEqual(userId);
expect(got.content).toEqual(dto.content);
expect(got.languageId).toEqual(dto.languageId);
});
});
|
Markdown
|
UTF-8
| 808 | 2.5625 | 3 |
[] |
no_license
|
## QLD AI NLP Fundamnetals
### 1.0 Overview
Slides, notebooks and a down-sampled datatset from the QLD AI NLP Fundamentals workshop (21.11.19).
#### 1.1 Up and Running
Clone repo and install dependencies via:
* `pip install -r requirements.txt`
Additionally, also install the spacy medium model via:
* `python -m spacy download en_core_web_md`
#### 1.2 Notebook Overview
* `trove_scrape` - pulling content from the trove archives via the [trove API](https://trove.nla.gov.au/), API key requires creating a trove account (see website)
* `spacy_analysis` - preprocessing, processing, formatting and analysis of trove documents
* `spacy_vis_benchmarking` - visualising spacy dependency parses, NER outputs and some very rough benchmarking around the multi-core processing and simple/complex spacy pipelines
|
Python
|
UTF-8
| 548 | 2.875 | 3 |
[] |
no_license
|
#!/usr/bin/python3
#coding:utf-8
from socket import *
from threading import Thread
def single(c):
while True:
message = input("input a message for sending:")
if message == 'q':
break
else:
c.send(message.encode("utf-8"))
result = c.recv(1024)
print("receive message ",result.decode("utf-8"))
if __name__ == "__main__":
client = socket(AF_INET,SOCK_STREAM)
client.connect(('192.168.18.128',11111))
t1 = Thread(target=single,args=(client,))
t1.start()
t1.join()
|
Shell
|
UTF-8
| 421 | 3.578125 | 4 |
[
"MIT"
] |
permissive
|
#!/bin/bash
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" >/dev/null 2>&1 && pwd )"
for filepath in $(find $DIR -maxdepth 1 -name '*.kaos'); do
filename=$(basename $filepath)
testname="${filename%.*}"
rm "$DIR/$testname.out"
chaos "tests/$filename" > "$DIR/$testname.out"
echo "Updated: ${testname}"
done
for dirpath in $(find $DIR -mindepth 1 -maxdepth 1 -type d); do
$dirpath/update.sh
done
|
C++
|
UTF-8
| 667 | 3.484375 | 3 |
[] |
no_license
|
#include <array>
#include <memory>
#include <iostream>
class Base
{
public:
virtual void Print(void)
{
std::cout << "base" << std::endl;
}
int b;
};
class Derived
: public Base
{
public:
void Print(void) override
{
std::cout << "derived" << std::endl;
}
int d;
};
int main()
{
std::unique_ptr<Base> ptr0 = std::make_unique<Base>();
std::unique_ptr<Base> ptr1 = std::make_unique<Derived>();
ptr0->Print();
ptr1->Print();
std::unique_ptr<int[]> arr = std::make_unique<int[]>(5);
for (int32_t i = 0; i < 5; ++i) arr[i] = i;
for (int32_t i = 0; i < 5; ++i) std::cout << arr[i] << std::endl;
std::cin.get();
}
|
Markdown
|
UTF-8
| 2,420 | 2.53125 | 3 |
[
"MIT"
] |
permissive
|
# Smart template export
## Description
1. It is a custom action that takes an XML based template file as input and generates formatted output file as dictated by the template
2. Refer to the documentation folder for sample templates and for template documentation - Release/DataCapSmartExport_v1.0.docx
## Build and deploy (for developers)
1. Checkout this repo and open the solution in Visual studio. Visual studio should be on the same system where DataCap is installed
2. Build the solution. It generates a DLL file in the bin directory of the solution.
3. Copy the DLL into the RSS directory of DataCap
4. Open DataCap studio and find the action library under global actions
## Deploy (for end-users)
1. Copy the supplied DLL into the RSS directory of DataCap
2. Open DataCap studio and find the action library under global actions
## Usage
1. Add the custom action to an existing or new Ruleset and set the parameter of the custom action to the template file path location.
2. Run DataCap workflow as usual and post completion, find output files in the output directory specified in the template. By default it writes to the batch directory.
## Features
1. Configuration :
Enables one to specify the configuration details like the output file name, extension, locale, output directory and memCacheLines – maximum number of lines of data that can be stored in memory .
2. Data elements :
Enables one to specify the content to be printed in the output file, this could be plain text of field values extracted from the input file.
3. Looping constructs :
Enables one to execute a set of instructions for a specific number of times. This feature is supported at the batch, document, and page level of the DCO hierarchy. Data elements, looping constructs and conditional constructs can be nested within this.
4. Conditional constructs :
Enables one to execute a set of instructions if some criteria is satisfied. This feature is supported at the document, page and field level of the DCO hierarchy. Data elements, looping constructs and conditional constructs can be nested within this.
5. Smart Parameters :
Enables one to use the values of the DataCap defined variables within a file name or print their value in the file.
6. Tables :
Enables one to extract table content. This feature can be used at file, document, page and field level.
## Technology
C#
## Dependencies
Datacap.Globals.dll
|
Python
|
UTF-8
| 1,923 | 2.953125 | 3 |
[] |
no_license
|
from DBResponse import Response
class ERROR(Response):
def __init__(self, text = "No extra information given"):
self.internal = {
"type" : "ERROR",
"errorText": text
}
def __str__(self):
return "Error: " + self.internal["errorText"]
# ---------------------------------------------------------------------------
# Table errors
# ---------------------------------------------------------------------------
class KEYNOTFOUNDERROR(ERROR):
def __init__(self, key, table = None):
ERROR.__init__(self, text = "KEY ERROR: key " + str(key) + " not found in table" + ((" in table " + table) if table else "!"))
# ---------------------------------------------------------------------------
# SQL errors
# ---------------------------------------------------------------------------
class COMMANDNOTFOUNDERROR(ERROR):
def __init__(self, SQL):
ERROR.__init__(self, text = "SQL ERROR: Unknown SQL command \" " + str(SQL) + "\" ")
class TYPEERROR(ERROR):
def __init__(self, field, fieldtype, errtype):
ERROR.__init__(self, text = "Field " + str(field) + " is of type " + str(fieldtype) + ", not of type " + str(errtype))
class TYPENOTFOUNDERROR(ERROR):
def __init__(self, errtype):
ERROR.__init__(self, text = "Type " + str(errtype) + " not recognized!")
class TABLENOTFOUNDERROR(ERROR):
def __init__(self, table):
ERROR.__init__(self, text = "Table " + str(table) + " does not exist!")
# ---------------------------------------------------------------------------
# File system errors
# ---------------------------------------------------------------------------
class FileSysError(ERROR):
def __init__(self, file = None, operation = None, explanation = None):
ERROR.__init__(self, text = "FILE SYSTEM ERROR: Cannot execute " + str(operation) + " for file " + str(file) + ": " + str(explanation))
|
Java
|
UTF-8
| 338 | 3.0625 | 3 |
[
"MIT"
] |
permissive
|
package jun.prospring5.ch3;
public class MessageProviderText implements MessageProvider {
private String message;
public MessageProviderText(String message, int number) {
this.message = Integer.toString(number) + "." + message;
}
@Override
public String getMessage() {
return this.message;
}
}
|
JavaScript
|
UTF-8
| 2,926 | 2.75 | 3 |
[] |
no_license
|
import React from 'react';
import EventRow from '../../components/eventrow/eventrow';
import './dashboard.scss';
export default class Dashboard extends React.Component {
state = {
filteredEvents: this.props.events
};
//to make sure the filtered events are up to date with state in app.
componentDidUpdate (prevState) {
if (this.props.events !== prevState.events) {
this.setState({
filteredEvents: this.props.events
})
}
}
getToday = () => {
const today = new Date()
const todayArray = []
this.props.events.map(item => {
const startDay = new Date(item.start)
const endDay = new Date(item.end)
if (today >= startDay && today <= endDay) {
todayArray.push(item)
}
return todayArray
})
return this.props.getToDoList(todayArray)
}
search = (event) => {
const filteredEvents = this.props.events.filter(item => {
return item.title.toLowerCase().includes(event.target.value.toLowerCase())
})
if(event.target.value === "") {
this.setState({
filteredEvents: this.props.events
})
}
else {
this.setState({
filteredEvents: filteredEvents
})
}
}
renderRows = (array) => {
return array.map(item => {
return <EventRow event={item} key={item.id}/>
})
}
render() {
return (
<section className="dashboard">
<button className="dashboard__open-button" onClick={this.props.openModal}>+ Add Event</button>
<section className="dashboard__section">
<h1 className="dashboard__section-heading">Today's To-Do List</h1>
<div className="dashboard__section-container">
{
this.getToday()
}
</div>
</section>
<section className="dashboard__section">
<input className="dashboard__section-search" type="text" name="search" placeholder="Search event name" onChange={this.search}/>
<h1 className="dashboard__section-heading">Events</h1>
<div className="dashboard__section-table">
<article className="event event--heading">
<span className="event-field event--name">Event Name</span>
<span className="event-field event--date">Start Date</span>
<span className="event-field event--time">Start Time</span>
<span className="event-field event--date">End Date</span>
<span className="event-field event--time">End Time</span>
<span className="event-field event--status">Status</span>
</article>
{
this.state.filteredEvents ?
this.props.sortByDate(this.state.filteredEvents).map(item => {
return <EventRow event={item} key={item.id}/>
})
: null
}
</div>
</section>
</section>
)
}
}
|
Python
|
UTF-8
| 3,272 | 2.875 | 3 |
[] |
no_license
|
# -*- coding: utf-8 -*-
#usr/bin/python
import os
import copy
import cv2
import serial
import numpy as np
# constantes
ID_PORTA = "COM8" # numero porta COM do arduino.
ID_CAMERA = 0 #-1 qualquer camera
QUANT_COLUNAS = 640
QUANT_LINHAS = 480
QUANT_LIMIAR_PIXELS = 100
QUANT_FAIXAS_CORES = 3
# variaveis
cor_detectada = "branco" # "azul", "vermelho", "amarelo"
cores = {QUANT_FAIXAS_CORES - 3: "azul",
QUANT_FAIXAS_CORES - 2: "vermelho",
QUANT_FAIXAS_CORES - 1: "verde"}
faixa_azul = {'menor': np.array([99, 115, 150]), 'maior': np.array([110, 255, 255])} # ok
faixa_vermelho = {'menor': np.array([136, 87, 111]), 'maior': np.array([180, 255, 255])} # ok
faixa_verde = {'menor': np.array([65, 100, 50]), 'maior': np.array([100, 255, 255])} # testar
faixa = {QUANT_FAIXAS_CORES - 3: faixa_azul,
QUANT_FAIXAS_CORES - 2: faixa_vermelho,
QUANT_FAIXAS_CORES - 1: faixa_verde}
roi = {'inicial': (QUANT_COLUNAS/4, QUANT_LINHAS/4),
'final': (QUANT_COLUNAS/2, QUANT_LINHAS/2)}
camera = cv2.VideoCapture(ID_CAMERA)
def captura_imagem_camera(fonte):
# Captura imagem da webcam
return fonte.read()
def desenha_roi(fonte):
# Desenha o quadrado que ira avaliar a cor que estiver nele.
cv2.rectangle(fonte, roi['inicial'], roi['final'], (0,255,0), 3)
return fonte
def busca_cor_imagem(fonte):
# Realiza a busca da cor, baseado na faixa de cores da função que a chama.
contagem = 0
for i in range (roi['inicial'][1], roi['final'][1]):
for j in range (roi['inicial'][0], roi['final'][0]):
if(fonte[i, j] == 255):
contagem = contagem + 1
if (contagem > QUANT_LIMIAR_PIXELS):
return True
else:
return False
def detecta_cores(fonte):
# Detecta as cores da imagem fonte.
fonte = cv2.cvtColor(fonte, cv2.COLOR_BGR2HSV)
for i in range(QUANT_FAIXAS_CORES):
img = cv2.inRange(fonte, faixa[i]['menor'], faixa[i]['maior'])
cv2.imshow("t", img)
if(busca_cor_imagem(img)):
return cores[i]
break;
def abre_serial():
try:
canal = serial.Serial(ID_PORTA)
return canal
except:
print "Erro ao abrir porta serial, verificar numero da porta."
def envia_comando(canal, cor):
comando = None
if(cor == cores[0]):
# azul
comando = '0'
elif(cor == cores[1]):
# vermelho
comando = '1'
elif(cor == cores[2]):
# verde
comando = '2'
try:
if(comando != None and canal.isOpen()):
print comando
canal.write(comando)
except:
print "Erro na porta de comunicacao"
# --------------------------------------- EXECUCAO ---------------------------------
canal = abre_serial()
while(True):
# processamento da imagem
_, imagem = captura_imagem_camera(camera)
cv2.blur(imagem, (5,5))
desenha_roi(copy.copy(imagem))
cor_detectada = detecta_cores(copy.copy(imagem))
# comunicação serial
envia_comando(canal, cor_detectada)
# exibição da imagem
cv2.imshow("Imagem com ROI", desenha_roi(copy.copy(imagem)))
cv2.waitKey(30)
print cor_detectada
cv2.destroyAllWindows()
canal.close()
|
C#
|
UTF-8
| 2,478 | 2.5625 | 3 |
[
"Unlicense"
] |
permissive
|
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data.Entity;
using System.Security.Claims;
using System.Threading.Tasks;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
namespace Egzaminy.Models
{
// Możesz dodać dane profilu dla użytkownika, dodając więcej właściwości do klasy ApplicationUser. Odwiedź stronę https://go.microsoft.com/fwlink/?LinkID=317594, aby dowiedzieć się więcej.
public class ApplicationUser : IdentityUser
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public ApplicationUser()
{
this.Rok = new HashSet<Rok>();
this.Przedm = new HashSet<Przedmioty>();
this.Egz = new HashSet<Egzamin>();
}
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
{
// Element authenticationType musi pasować do elementu zdefiniowanego w elemencie CookieAuthenticationOptions.AuthenticationType
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
// Dodaj tutaj niestandardowe oświadczenia użytkownika
return userIdentity;
}
public string Imie { get; set; }
public string Nazwisko { get; set; }
[Display(Name = "Imię i Nazwisko")]
public string Pelne
{
get
{
return Imie + ", " + Nazwisko;
}
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Rok> Rok { get; set; }
public virtual ICollection<Przedmioty> Przedm {get; set;}
public virtual ICollection<Egzamin> Egz { get; set; }
}
public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
public ApplicationDbContext()
: base("DefaultConnection", throwIfV1Schema: false)
{
}
public DbSet<Egzamin> Egzamins { get; set; }
public DbSet<Rok> Roks { get; set; }
public DbSet<Sale> Sales { get; set; }
public DbSet<Przedmioty> Przedmioties { get; set; }
public static ApplicationDbContext Create()
{
return new ApplicationDbContext();
}
}
}
|
Python
|
UTF-8
| 991 | 4.4375 | 4 |
[] |
no_license
|
from typing import List
pets = ("dog", "cat", "rabbit", "fish", "salamander")
print(pets)
x = ("dog", 21, True)
print(x)
# ******************
# Indexing
print(pets[0])
print(pets[1])
print(pets[2])
# Range of Indexes
print(pets[1:2])
print(pets[:3])
print(pets[3:])
print(pets[-3:])
print(pets[:-3])
# *******************
# Finding Length
print("The length of the Tuple is: ",len(pets))
# *******************
# Looping through a Tuple
for pet in pets:
print(pet)
# *******************
# Checking Availability
print("dog" in pets)
print("hamster" in pets)
# *******************
# Another way of Creating a Tuple
print(tuple(("dog", "cat", "parrot", "hamster","cockatoo")))
# print(list(("dog", "cat", "parrot", "hamster","cockatoo"))) #test
# *******************
# Combining Tuples
genere1 = ("adventure", "si-fi", "action")
genere2 = ("horror", "comedy", "thriller")
all_genere = genere1 + genere2
print(all_genere)
|
C#
|
UTF-8
| 2,878 | 2.890625 | 3 |
[] |
no_license
|
using System;
namespace filtrsBMP
{
// delegate double[,] STRMOD();(*)
static class ChooseBMPclass
{//заполняем фильтры значениями
public static int n;
public static bool black;
public static bool bl;
public static int div;
public static double[,] fl;
static public void FiltrsChoose()
{
//STRMOD d1 = new STRMOD(filtrs); для многопоточнсти придётся использовать не статическое поле(*)
Filtrsname.menufiltrs();
//n = int.Parse(Console.ReadLine());
filtrs();
}
static void filtrs()//почему нельзя указать определённый размер массива
{
switch (n)
{
//black - истинна оставляй прозрачность, иначе заливай чёрным.
//bl - истина, то соблюдает границы, иначе нет.
case 1: fl = new double[3, 3] { { 1, 1, 1 }, { 1, 0, 1 }, { 1, 1, 1 } }; black = true; bl = true; div = 8; break;
case 2: fl = new double[3, 3] { { 0.5, 0.75, 0.5 }, { 0.75, 1, 0.75 }, { 0.5, 0.75, 0.5 } }; black = true; bl = true; div = 6; break;
case 3: fl = new double[3, 3] { { 0.06163058, 0.12499331, 0.06163058 }, { 0.12499331, 0.25355014, 0.12499331 }, { 0.06163058, 0.12499331, 0.06163058 } }; black = true; bl = true; div = 1; break;
case 4: fl = new double[3, 3] { { -1, 0, 1 }, { -2, 0, 2 }, { -1, 0, 1 } }; black = false; bl = true; div = 1; break;
case 5: fl = new double[3, 3] { { -1, -2, -1 }, { 0, 0, 0 }, { 1, 2, 1 } }; black = false; bl = true; div = 1; break;
case 6: fl = new double[3, 3] { { 0, 0, 0 }, { -1, 0, 1 }, { 0, 0, 0 } }; black = false; bl = true; div = 1; break;
case 7: fl = new double[3, 3] { { 0, -1, 0 }, { 0, 0, 0 }, { 0, 1, 0 } }; black = false; bl = true; div = 1; break;
case 8: fl = new double[3, 3] { { 0.5, 0.75, 0.5 }, { 0.75, 1, 0.75 }, { 0.5, 0.75, 0.5 } }; black = false; bl = false; div = 1; break;
case 9: fl = new double[3, 3] { { 0, -1, 0 }, { -1, 0, 1 }, { 0, 1, 0 } }; black = false; bl = false; div = 1; break;
case 10: fl = new double[3, 3] { { -0.5, 0.75, 0.5 }, { 0.75, 2, 0.75 }, { 0.5, 0.75, -0.5 } }; black = false; bl = false; div = 1; break;
case 11: fl = new double[3, 3] { { 2, 2, 0 }, { 2, 0, 2 }, { 0, 2, 2 } }; black = false; bl = true; div = 5; break;
case 12: fl = new double[3, 3] { { 0, -1, 0 }, { -1, 0, 1 }, { 0, 1, 0 } }; black = false; bl = true; div = 5; break;
default: fl = new double[3, 3]; break;
}
}
}
}
|
TypeScript
|
UTF-8
| 775 | 2.671875 | 3 |
[] |
no_license
|
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'Exercícios';
msg: string;
constructor() {
this.msg = 'Hello World!';
}
ngOnInit() {
print();
this.rotateText(this.msg, 1000);
}
print(): void {
console.log('HELLO WORLD Ladys and Gentlemen...');
}
rotateText(msg: string, dt: number) {
setInterval(() => this.doRotate(msg), dt);
}
doRotate(msg) {
if (msg.length > 1) {
msg = this.msg;
const aux = msg.charAt(msg.length - 1);
msg = aux + msg.substring(0, (msg.length - 1));
console.log(msg);
this.msg = msg;
}
}
}
|
TypeScript
|
UTF-8
| 1,220 | 2.828125 | 3 |
[] |
no_license
|
import { BooleanVerifier } from '../src/verifiers/boolean-verifier';
describe( 'Boolean', () => {
const booleanVerifier = new BooleanVerifier().verifyArgument;
it( 'parses booleans (true)', () => {
const result = booleanVerifier( '', true );
expect( result.valid ).toBe( true );
expect( result.value ).toBe( true );
} );
it( 'parses booleans (false)', () => {
const result = booleanVerifier( '', false );
expect( result.valid ).toBe( true );
expect( result.value ).toBe( false );
} );
it( 'parses strings (true)', () => {
const result = booleanVerifier( '', 'true' );
expect( result.valid ).toBe( true );
expect( result.value ).toBe( true );
} );
it( 'parses strings (false)', () => {
const result = booleanVerifier( '', 'false' );
expect( result.valid ).toBe( true );
expect( result.value ).toBe( false );
} );
test.each( [
[ 'abc' ], [ 'true ' ],
[ '' ], [ undefined ],
[ null ], [ 22 ],
[ 1 ], [ 0 ],
[ -1 ]
] )( 'does not allow %p', ( what ) => {
expect( booleanVerifier( '', what ).valid ).toBe( false );
} );
} );
|
Shell
|
UTF-8
| 541 | 2.671875 | 3 |
[
"MIT"
] |
permissive
|
#!/bin/bash
# Todo: Since i recently learned how to do it, make a docker-compose.yml out of it :D
echo "Kill existing Docker container"
docker stop terrastate-http \
&& docker rm terrastate-http
echo "Spin up new Docker container"
time docker build . -t terrastate-http \
&& docker run --detach \
--name terrastate-http \
--publish 8080:8080 \
--volume $(pwd)/examples/configs/config.json:/mnt/configs/config.json \
--volume $(pwd)/examples/sqlite3/:/mnt/sqlite3/ \
terrastate-http
docker logs -f terrastate-http
|
SQL
|
UTF-8
| 275 | 2.640625 | 3 |
[] |
no_license
|
CREATE DATABASE Login;
USE Login;
CREATE TABLE users (
id INT NOT NULL
name VARCHAR(255) NOT NULL
username VARCHAR(255) NOT NULL UNIQUE
email VARCHAR(255) NOT NULL UNIQUE
password VARCHAR(255) NOT NULL
PRIMARY KEY(id)
)
|
Java
|
UTF-8
| 301 | 1.960938 | 2 |
[] |
no_license
|
package com.example.shixi.dao;
import com.example.shixi.bean.People;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
@Mapper
public interface PeopleDao {
@Select("select * from people")
public List<People> findAllPeople();
}
|
Java
|
UTF-8
| 2,385 | 2.8125 | 3 |
[] |
no_license
|
package com.wip._1._4;
import static com.wip.Utils.defineInputMethod;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
/**
* This Class may not be most optimized as it could be, but I try to
* keep code organization and optimizations balanced the most I can.
*/
class Main642 {
public static void main(String[] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
String line, key;
HashMap<String, ArrayList<String>> dictionary = new HashMap<>();
ArrayList<String> list;
while ((line = bf.readLine()) != null && !line.equals("XXXXXX"))
{
key = getKey(line);
if ((list = dictionary.get(key)) != null)
{
list.add(line);
}
else
{
list = new ArrayList<>();
list.add(line);
dictionary.put(key, list);
}
}
while ((line = bf.readLine()) != null && !line.equals("XXXXXX"))
{
key = getKey(line);
if ((list = dictionary.get(key)) != null)
{
Collections.sort(list);
for (String word : list) {
sb.append(word).append("\n");
}
}
else
{
sb.append("NOT A VALID WORD\n");
}
sb.append("******\n");
}
System.out.write(sb.toString().getBytes());
}
public static String getKey(String word)
{
char[] sorted = word.toCharArray();
Arrays.sort(sorted);
return new String(sorted);
}
}
/**
* This is a wrapper for the submition class. In order to submit it in uva judge platform,
* copy just the class Main and the necessary imports.
*/
public class UVA642 {
final static String packName = UVA642.class.getPackage().getName();
final static String chapter = packName.substring(packName.indexOf("wip._") + 5).replace("_", "");
public static void main(String[] args) throws IOException {
defineInputMethod(UVA642.class, chapter);
Main642.main(args);
}
}
|
Markdown
|
UTF-8
| 1,831 | 2.515625 | 3 |
[
"MIT"
] |
permissive
|
# FreshBooks
It is a bookstore implemented using Apache Tomcat. It relies on a MYSQL database in order to pull information about anything from users to books and display it in the webpage.
The project took us a good long while and a lot of work so we hope you enjoy the experience of FreshBooks.
## Getting Started
These instructions will get you a copy of the project up and running on your local machine for development and testing purposes. See deployment for notes on how to deploy the project on a live system.
### Prerequisites
Here are some thigns you need to install to run this project
```
MYSQL
XAMPP
Java jre1.8.0_171
Apache Tomcat 8.5
```
### Installing
Here are a series of steps required to set up the development enviroment.
```
1.Install Java JDK
2.Install Apache Tomcat
3.Install MYSQL and XAMPP
4.Run the SQL script in the admin page of XAMPP
5.Import the WAR file through eclipse
6. Remove SSL requirements from the project
7. Setup Apache 8.5 server
8. Project now runs, we recommend Running start.java first
```
If you run the project it will now display the mainpage which will allow you to view books.
Add them to your cart and even order online.
## Built With
* [Apache Tomcat](http://tomcat.apache.org/) - The web framework as well as server
* [MYSQL](https://www.mysql.com/) - DBMS
* [XAMMP](https://www.apachefriends.org/index.html) - Used to administrate the database
## Authors
* **Matthew MacEachern** - [mcmaceac](https://github.com/mcmaceac)
* **Saad Saeed** - [SaeedS28](https://github.com/SaeedS28)
* **Tyler Noble** - [NobleTyler](https://github.com/NobleTyler)
## License
This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details
## Acknowledgments
* York for going on strike long enough to have us not stress out about this too much
|
Java
|
UTF-8
| 566 | 2.703125 | 3 |
[] |
no_license
|
package rate.retriever;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
public class FileReader {
public static String readEntireFile(final String filePath) {
byte[] encoded = new byte[0];
try {
encoded = Files.readAllBytes(Paths.get(filePath));
} catch (IOException e) {
System.out.println("Could not read file " + filePath);
e.printStackTrace();
}
return new String(encoded, Charset.defaultCharset());
}
}
|
SQL
|
UTF-8
| 396 | 3.359375 | 3 |
[] |
no_license
|
SELECT DISTINCT
cname,
legnum,
sname
FROM sponsors
JOIN affected_by USING(legnum)
JOIN contributes USING(sname, cname)
JOIN senators USING(sname)
JOIN corporations USING(cname)
WHERE
howafctd='Favorably'
AND corporations.stname != senators.stname
AND party='Republican'
AND totrev >= 10000000
ORDER BY cname, legnum, sname;
|
C
|
UTF-8
| 849 | 2.90625 | 3 |
[] |
no_license
|
/*
* testjit.c
*
* Created on: Jul 9, 2013
* Author: PROGMAN
*/
#include <unistd.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/mman.h>
#define FUNC_SIZE 0x40
typedef void (*FuncType)(void);
void test(void)
{
while(1)
{}
printf("this is a function\n");
}
void functobecopied(void)
{
uint64_t funcaddr = ((uint64_t)test);
(*((FuncType)funcaddr))();
return;
}
int main()
{
unsigned long pagesize = sysconf(_SC_PAGE_SIZE);
void* func_runtime = malloc(FUNC_SIZE);
printf("now alloced at %lx\n", (uint64_t)(func_runtime));
memcpy(func_runtime, functobecopied,FUNC_SIZE );
mprotect((((uint64_t)func_runtime)&(~(pagesize-1))), (FUNC_SIZE + pagesize - 1), PROT_READ | PROT_WRITE | PROT_EXEC);
(*((FuncType)func_runtime))();
return 0;
}
|
SQL
|
UTF-8
| 2,617 | 2.671875 | 3 |
[] |
no_license
|
ALTER TABLE `users`
CHANGE `user_name` `user_name` VARCHAR(100) DEFAULT '',
CHANGE `user_company` `user_company` VARCHAR(100) DEFAULT '',
CHANGE `user_address_1` `user_address_1` VARCHAR(100) DEFAULT '',
CHANGE `user_address_2` `user_address_2` VARCHAR(100) DEFAULT '',
CHANGE `user_city` `user_city` VARCHAR(45) DEFAULT '',
CHANGE `user_state` `user_state` VARCHAR(35) DEFAULT '',
CHANGE `user_zip` `user_zip` VARCHAR(15) DEFAULT '',
CHANGE `user_country` `user_country` VARCHAR(35) DEFAULT '',
CHANGE `user_phone` `user_phone` VARCHAR(20) DEFAULT '',
CHANGE `user_fax` `user_fax` VARCHAR(20) DEFAULT '',
CHANGE `user_mobile` `user_mobile` VARCHAR(20) DEFAULT '',
CHANGE `user_web` `user_web` VARCHAR(100) DEFAULT '';
ALTER TABLE `clients`
CHANGE `client_address_1` `client_address_1` VARCHAR(100) DEFAULT '',
CHANGE `client_address_2` `client_address_2` VARCHAR(100) DEFAULT '',
CHANGE `client_city` `client_city` VARCHAR(45) DEFAULT '',
CHANGE `client_state` `client_state` VARCHAR(35) DEFAULT '',
CHANGE `client_zip` `client_zip` VARCHAR(15) DEFAULT '',
CHANGE `client_country` `client_country` VARCHAR(35) DEFAULT '',
CHANGE `client_phone` `client_phone` VARCHAR(20) DEFAULT '',
CHANGE `client_fax` `client_fax` VARCHAR(20) DEFAULT '',
CHANGE `client_mobile` `client_mobile` VARCHAR(20) DEFAULT '',
CHANGE `client_email` `client_email` VARCHAR(100) DEFAULT '',
CHANGE `client_web` `client_web` VARCHAR(100) DEFAULT '';
ALTER TABLE `invoice_groups` CHANGE `invoice_group_left_pad` `invoice_group_left_pad` INT( 2 ) NOT NULL DEFAULT '0';
ALTER TABLE `invoice_amounts`
CHANGE `invoice_item_subtotal` `invoice_item_subtotal` DECIMAL(10,2) DEFAULT '0.00',
CHANGE `invoice_item_tax_total` `invoice_item_tax_total` DECIMAL(10,2) DEFAULT '0.00',
CHANGE `invoice_tax_total` `invoice_tax_total` DECIMAL(10,2) DEFAULT '0.00',
CHANGE `invoice_total` `invoice_total` DECIMAL(10,2) DEFAULT '0.00',
CHANGE `invoice_paid` `invoice_paid` DECIMAL(10,2) DEFAULT '0.00',
CHANGE `invoice_balance` `invoice_balance` DECIMAL(10,2) DEFAULT '0.00';
ALTER TABLE `quotes` CHANGE `invoice_id` `invoice_id` INT( 11 ) NOT NULL DEFAULT '0';
ALTER TABLE `quote_amounts` CHANGE `quote_total` `quote_total` DECIMAL( 10, 2 ) NOT NULL DEFAULT '0.00';
ALTER TABLE `quote_items` CHANGE `item_order` `item_order` INT( 2 ) NOT NULL DEFAULT '0';
ALTER TABLE `invoice_items` CHANGE `item_order` `item_order` INT( 2 ) NOT NULL DEFAULT '0',
CHANGE `item_tax_rate_id` `item_tax_rate_id` INT( 11 ) NOT NULL DEFAULT '0';
ALTER TABLE `payments` CHANGE `payment_method_id` `payment_method_id` INT( 11 ) NOT NULL DEFAULT '0';
|
Java
|
UTF-8
| 1,996 | 2.296875 | 2 |
[] |
no_license
|
package models;
import android.graphics.Bitmap;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
/**
* Created by LeeSan on 3/27/2016.
*/
public class PostItemModel implements Serializable {
private String _title;
private String _userName;
private Date _postDate;
private String _content;
private ArrayList<String> _comments;
private String _votes;
private String _urlAvatar;
public PostItemModel(){}
public PostItemModel(String title, String username, String urlAvatar, Date postDate, String content,
ArrayList<String> comment, String vote){
this.set_title(title);
this.set_userName(username);
this.set_urlAvatar(urlAvatar);
this.set_postDate(postDate);
this.set_content(content);
this.set_comments(comment);
this.set_votes(vote);
}
public String get_title() {
return _title;
}
public void set_title(String _title) {
this._title = _title;
}
public String get_userName() {
return _userName;
}
public void set_userName(String _userName) {
this._userName = _userName;
}
public Date get_postDate() {
return _postDate;
}
public void set_postDate(Date _postDate) {
this._postDate = _postDate;
}
public String get_content() {
return _content;
}
public void set_content(String _content) {
this._content = _content;
}
public ArrayList<String> get_comments() {
return _comments;
}
public void set_comments(ArrayList<String> _comments) {
this._comments = _comments;
}
public String get_votes() {
return _votes;
}
public void set_votes(String _votes) {
this._votes = _votes;
}
public String get_urlAvatar() {
return _urlAvatar;
}
public void set_urlAvatar(String _urlAvatar) {
this._urlAvatar = _urlAvatar;
}
}
|
Markdown
|
UTF-8
| 3,135 | 3.109375 | 3 |
[] |
no_license
|
---
layout: index
priority: 5
title: ChatbotTech's guide to choosing a chatbot building tool
image: /img/guide.png
summary: "Choosing a tool to build your chatbot can be tricky. We've chosen five
of the best and created a special infographic to help you find a
starting point in your search for the tool that's right for you."
---
There are many different types of tools that can be used to create
chatbots and conversational interfaces. It is important to understand
the different categories of tool that are available so that you can
choose the tool that is right for you.
[Choosing the right tool](/choose.html) can make a big difference. If
the tool is too complex or requires technical input, you may struggle
to use it effectively. Conversely, if the tool is designed for
building simple bot prototypes but you want to build something
sophisticated, a simple tool may not be enough.
<h3 class="text-center m-5">Non-technical vs developer tools</h3>
This site divides tools into two main categories:
- [Non-technical tools](/non-technical.html): these are tools that
anyone can use to quickly build a chatbot. These can be used to
create simple chatbots or prototypes to quickly learn whether
chatbots are a good fit for your application. You will likely not be
able to handle complex integrations with your website, and your bot
will not behave intelligently. Nevertheless, these tools are very
useful even for those that are able to code. An example of a popular
tool in this category is [Chatfuel](/reviews/chatfuel.html)
- [Developer tools](/developer.html): these are tools that require
coding to use effectively. An example of this is [Microsoft's Bot
Framework](/reviews/microsoft-bot-framework.html) which requires
coding in C# or Node.js. [Facebook's Wit.ai](/reviews/witai.html)
provides an API which developers can use to help understand user's
requests.
Some tools fall into both categories, for example [Google's
Dialogflow](/reviews/dialogflow.html) can be used without doing any
development, but provides additional capabilities for those who want
to integrate with their code.
<h3 class="text-center m-5">Tools for marketers</h3>
Within each category there are different types of tool. For example,
both [Mobile Monkey](/reviews/mobile-monkey.html) and
[ManyChat](/reviews/manychat.html) are non-technical tools aimed at
marketers.
There is a lot of potential for using chatbots for marketing. For
example, it is possible to use Facebook advertising to send users
directly to a Messenger chatbot. Users interacting with the chatbot
consent to be contacted by the bot at a later point in time. This
means that the cost-per-acquisition of Messenger contacts can be much
lower than traditional email marketing.
<h3 class="text-center m-5">Chatbots for e-commerce</h3>
If you use Shopify, you can provide users with a chatbot experience
with [their own built-in chatbot](/reviews/shopify.html), or you can
use a third party plugin such as [Octane
AI](/reviews/octane-ai.html). Either way, it makes sense to use a
chatbot platform tailored to e-commerce, and Shopify in particular.
|
JavaScript
|
UTF-8
| 1,909 | 2.671875 | 3 |
[] |
no_license
|
import * as actionTypes from '../../../constants/action-types';
const initialState = {
restaurantDetails: null,
restaurantImages:[],
menuDetails: null,
reviewDetails:null,
mode: false,
save: false,
imagemode:false,
menumode:false,
reviewmode:false,
}
const restuarantReducer = (state = initialState, action) => {
switch(action.type){
case actionTypes.SAVE_RESTAURANT_DETAILS:
return {
...state,
restaurantDetails: action.payload
}
case actionTypes.CHANGE_MODE:
return {
...state,
mode: action.payload
}
case actionTypes.ENABLE_SAVE:
return {
...state,
save: action.payload
}
case actionTypes.SAVE_RESTAURANT_IMAGES:
return {
...state,
restaurantImages: action.payload
}
case actionTypes.CHANGE_IMAGE_MODE:
return {
...state,
imagemode: action.payload
}
case actionTypes.SAVE_MENU_DETAILS:
return {
...state,
menuDetails: action.payload
}
case actionTypes.CHANGE_MENU_MODE:
return {
...state,
menumode: action.payload
}
case actionTypes.SAVE_REVIEW_DETAILS:
return {
...state,
reviewDetails: action.payload
}
case actionTypes.CHANGE_REVIEW_MODE:
return {
...state,
reviewmode: action.payload
}
default:
return initialState;
}
}
export default restuarantReducer;
|
PHP
|
UTF-8
| 358 | 2.578125 | 3 |
[] |
no_license
|
<?php
namespace MolnApps\Testing\Form;
class Checkbox extends AbstractFormElement
{
public function setValue($value)
{
$value = $value ? 'checked' : null;
$this->domElement->setAttribute('checked', $value);
}
public function getValue()
{
return ($this->domElement->getAttribute('checked')) ? $this->domElement->getAttribute('value') : '';
}
}
|
JavaScript
|
UTF-8
| 1,694 | 2.71875 | 3 |
[] |
no_license
|
jQuery(document).ready(function ($) {
var stop = false;
var width = $(window).width();
var height = $(window).height();
var interval = 1600;
var startw = 0;
var delay = 0;
var fadeTime = 0;
var b=0;
//Flakes swing animation
function swing(defaultWidth, element) {
for(var i=0; i<6; i++) {
$(element).animate({'margin-left': defaultWidth-4},249).animate({'margin-left': defaultWidth},249).animate({'margin-left': defaultWidth+4},249).animate({'margin-left': defaultWidth},249);
}
}
//Handler function
function snow() {
if (stop) {
return false;
} else { //Else start snow
var randomTime = 100 + Math.floor(Math.random() * 400);
setTimeout(function() { //Generate one flake and after randomTime generate another
one();
snow();
}, randomTime);
}
}
var one = function() { //Creates one flake
startw = 0 + Math.floor(Math.random() * width-18);
var element = $('<div class="flake"></div>');
element.appendTo($("body"));
$(element).css('margin-left', startw + 'px');
$(element).animate({
'margin-top': height - 18
}, {
duration: 6000,
easing: 'linear',
queue: false
});
swing(startw, element);
$(element).fadeOut(1000, function() {
$(this).remove().detach();
});
};
snow();
$.fn.toggleSnow = function() {
if(stop) {stop=false; snow();}
else if(!stop) {stop=true;}
};
});
|
Python
|
UTF-8
| 2,013 | 3.078125 | 3 |
[] |
no_license
|
from PyQt5.QtWidgets import QLineEdit, QApplication, QPushButton, QLabel, QDialog, QGroupBox, QHBoxLayout, QVBoxLayout, QGridLayout, QCheckBox
import sys
from PyQt5 import QtGui
from PyQt5.QtCore import QRect
from PyQt5 import QtCore
from PyQt5.QtGui import QPixmap
class Window(QDialog):
def __init__(self):
super().__init__()
self.title = "Sum"
self.left = 100
self.top = 100
self.width = 500
self.height = 500
self.IconName = "Icon/python.png"
self.InitWindow()
def InitWindow(self):
self.setWindowIcon(QtGui.QIcon(self.IconName))
self.setWindowTitle(self.title)
self.setGeometry(self.left, self.top, self.width, self.height)
self.CreateLayout()
def CreateLayout(self):
#self.groupbox = QGroupBox("Find the sum of two numbers!")
hboxOne = QHBoxLayout()
labelOne = QLabel("Enter Number One : ")
self.lineEditOne = QLineEdit()
hboxOne.addWidget(labelOne)
hboxOne.addWidget(self.lineEditOne)
hboxTwo = QHBoxLayout()
labelTwo = QLabel("Enter Number Two : ")
self.lineEditTwo = QLineEdit()
hboxTwo.addWidget(labelTwo)
hboxTwo.addWidget(self.lineEditTwo)
sumButton = QPushButton("Calculate")
sumButton.setFont(QtGui.QFont("Sanserif", 10))
sumButton.setToolTip("Calculate Sum Of Two Numbers!")
sumButton.clicked.connect(self.CalculateSum)
self.label = QLabel(self)
vbox = QVBoxLayout()
vbox.addLayout(hboxOne)
vbox.addLayout(hboxTwo)
vbox.addWidget(sumButton)
vbox.addWidget(self.label)
#self.groupbox.setLayout(vbox)
self.setLayout(vbox)
self.show()
def CalculateSum(self):
self.label.setText("Sum = " + "{}" .format(int(self.lineEditOne.text()) + int(self.lineEditTwo.text())))
if __name__ == "__main__":
App = QApplication(sys.argv)
window = Window()
sys.exit(App.exec())
|
Java
|
UTF-8
| 494 | 2.296875 | 2 |
[] |
no_license
|
package io.homework;
import static org.junit.Assert.*;
import java.io.IOException;
import org.junit.Test;
public class CountingProcessTest {
Votes vote;
@Test
public void checkAllInavalidVotes() throws IOException {
CountingProcess counting = new CountingProcess( vote);
assertEquals(0, counting.invalidVotes);
}
@Test
public void checkAllValidVotes() throws IOException{
CountingProcess counting = new CountingProcess( vote);
assertEquals(0, counting.validVotes);
}
}
|
Markdown
|
UTF-8
| 637 | 2.59375 | 3 |
[] |
no_license
|
# Proyecto XML
¡Buenas! Este es mi proyecto sobre XML en el que trabajaremos con la información de un fichero XML. Mi fichero XML trata sobre videojuegos, donde podrás preguntar por el nombre del mismo,las diferentes tiendas en las que se vende, género ,etc.
1. Muestra el nombre de todos los videojuegos.
2. Muestra la cantidad de juegos pertenecientes a un género introducido.
3. Busca el nombre de un juego y muestra las tiendas en las que se vende.
4. Muestra los juegos que tienen o no tienen ONLINE, dependiendo de la respuesta del usuario.
5. Muestra los juegos que sean compatibles con la plataforma de juego introducida.
|
Java
|
UTF-8
| 1,702 | 2.046875 | 2 |
[] |
no_license
|
package com.tech.smal.turkaf;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.CardView;
import android.view.View;
import com.tech.smal.turkaf.data.QuestionDetails;
public class FactoryActivity extends AppCompatActivity {
private CardView cardViewNew;
private CardView cardViewList;
private CardView cardViewRate;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_factory);
cardViewNew = (CardView)findViewById(R.id.cv_new);
cardViewList = (CardView)findViewById(R.id.cv_list);
cardViewRate = (CardView)findViewById(R.id.cv_rate);
cardViewNew.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(getApplication(), NewQuestionActivity.class);
startActivity(intent);
}
});
cardViewList.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(getApplication(), PropositionsActivity.class);
startActivity(intent);
}
});
cardViewRate.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(getApplication(), QuestionDetailsActivity.class);
startActivity(intent);
}
});
}
}
|
Python
|
UTF-8
| 9,244 | 2.53125 | 3 |
[
"BSD-2-Clause"
] |
permissive
|
import copy
from typing import Callable, ClassVar, List, Optional, TypeVar
from typing_extensions import TypedDict
from ..configuration_support import Step, Configuration
from ..lib.ci_exception import SilentAbortException, StepException, CriticalCiException
from ..lib.gravity import Dependency, Module
from .output import HasOutput
__all__ = [
"HasStructure"
]
class Block:
"""
>>> b1 = Block('Build for all supported platforms')
>>> str(b1)
' Build for all supported platforms - Success'
>>> b2 = Block('Build Android', b1)
>>> str(b2)
'1. Build Android - Success'
>>> b3 = Block('Build Tizen', b1)
>>> str(b3)
'2. Build Tizen - Success'
>>> b3.status = 'Failed'
>>> str(b3)
'2. Build Tizen - Failed'
>>> b3.is_successful()
False
>>> b4 = Block('Run tests', b2)
>>> str(b4)
'1.1. Run tests - Success'
>>> b4.is_successful()
True
>>> b2 is b4.parent
True
"""
def __init__(self, name: str, parent: Optional['Block'] = None) -> None:
self.name: str = name
self.status: str = "Success"
self.children: List[Block] = []
self.parent: Optional[Block] = parent
self.number: str = ''
if parent:
parent.children.append(self)
self.number = '{}{}.'.format(parent.number, len(parent.children))
def __str__(self) -> str:
result = self.number + ' ' + self.name
return '{} - {}'.format(result, self.status) if not self.children else result
def is_successful(self) -> bool:
return self.status == "Success"
class BackgroundStepInfo(TypedDict):
name: str
finalizer: Callable[[], None]
is_critical: bool
class StructureHandler(HasOutput):
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.current_block: Optional[Block] = Block("Universum")
self.configs_current_number: int = 0
self.configs_total_count: int = 0
self.active_background_steps: List[BackgroundStepInfo] = []
def open_block(self, name: str) -> None:
new_block = Block(name, self.current_block)
self.current_block = new_block
self.out.open_block(new_block.number, name)
def close_block(self) -> None:
if self.current_block is not None:
block: Block = self.current_block
self.current_block = self.current_block.parent
self.out.close_block(block.number, block.name, block.status)
def report_critical_block_failure(self) -> None:
self.out.report_skipped("Critical step failed. All further configurations will be skipped")
def report_skipped_block(self, name):
new_skipped_block = Block(name, self.current_block)
new_skipped_block.status = "Skipped"
self.out.report_skipped(new_skipped_block.number + " " + name +
" skipped because of critical step failure")
def fail_current_block(self, error: str = ""):
block: Block = self.get_current_block()
self.fail_block(block, error)
def fail_block(self, block, error: str = ""):
if error:
self.out.log_exception(error)
block.status = "Failed"
self.out.report_build_problem(block.name + " " + block.status)
def get_current_block(self):
return self.current_block
# The exact block will be reported as failed only if pass_errors is False
# Otherwise the exception will be passed to the higher level function and handled there
T = TypeVar('T')
def run_in_block(self, operation: Callable[..., T],
block_name: str, pass_errors: bool, *args, **kwargs) -> Optional[T]:
result = None
self.open_block(block_name)
try:
result = operation(*args, **kwargs)
except (SilentAbortException, StepException):
raise
except CriticalCiException as e:
self.fail_current_block(str(e))
raise SilentAbortException() from e
except Exception as e:
if pass_errors is True:
raise
self.fail_current_block(str(e))
finally:
self.close_block()
return result
def execute_one_step(self, configuration: Step,
step_executor: Callable, is_critical: bool) -> None:
# step_executor is [[Step], Step], but referring to Step creates circular dependency
process = step_executor(configuration)
process.start()
if not configuration.background:
process.finalize()
return
self.out.log("This step is marked to be executed in background")
self.active_background_steps.append({'name': configuration.name,
'finalizer': process.finalize,
'is_critical': is_critical})
def finalize_background_step(self, background_step: BackgroundStepInfo):
try:
background_step['finalizer']()
self.out.log("This background step finished successfully")
except StepException:
if background_step['is_critical']:
self.out.log_stderr("This background step failed, and as it was critical, "
"all further steps will be skipped")
return False
self.out.log_stderr("This background step failed")
return True
def execute_steps_recursively(self, parent: Optional[Step], cfg: Configuration,
step_executor: Callable,
skipped: bool = False) -> None:
# step_executor is [[Step], Step], but referring to Step creates circular dependency
if parent is None:
parent = Step()
step_num_len = len(str(self.configs_total_count))
child_step_failed = False
for obj_a in cfg.configs:
try:
item: Step = parent + copy.deepcopy(obj_a)
if obj_a.children:
# Here pass_errors=True, because any exception outside executing build step
# is not step-related and should stop script executing
numbering = " [ {:{length}}+{:{length}} ] ".format("", "", length=step_num_len)
step_name = numbering + item.name
self.run_in_block(self.execute_steps_recursively, step_name, True,
item, obj_a.children, step_executor, skipped)
else:
self.configs_current_number += 1
numbering = " [ {:>{}}/{} ] ".format(
self.configs_current_number,
step_num_len,
self.configs_total_count
)
step_name = numbering + item.name
if skipped:
self.report_skipped_block(step_name)
continue
if item.finish_background and self.active_background_steps:
self.out.log("All ongoing background steps should be finished before next step execution")
if not self.report_background_steps():
self.report_skipped_block(step_name)
skipped = True
raise StepException()
# Here pass_errors=False, because any exception while executing build step
# can be step-related and may not affect other steps
self.run_in_block(self.execute_one_step, step_name, False,
item, step_executor, obj_a.critical)
except StepException:
child_step_failed = True
if obj_a.critical:
self.report_critical_block_failure()
skipped = True
if child_step_failed:
raise StepException()
def report_background_steps(self) -> bool:
result = True
for item in self.active_background_steps:
if not self.run_in_block(self.finalize_background_step,
"Waiting for background step '" + item['name'] + "' to finish...",
True, item):
result = False
self.out.log("All ongoing background steps completed")
self.active_background_steps = []
return result
def execute_step_structure(self, configs: Configuration, step_executor) -> None:
self.configs_total_count = sum(1 for _ in configs.all())
try:
self.execute_steps_recursively(None, configs, step_executor)
except StepException:
pass
if self.active_background_steps:
self.run_in_block(self.report_background_steps, "Reporting background steps", False)
class HasStructure(Module):
structure_factory: ClassVar = Dependency(StructureHandler)
def __init__(self, *args, **kwargs) -> None:
super().__init__(*args, **kwargs)
self.structure: StructureHandler = self.structure_factory()
|
Java
|
UTF-8
| 1,782 | 2.59375 | 3 |
[] |
no_license
|
package com.atet.api.utils;
import android.text.TextUtils;
/**
* @description: 加解密工具类
*
* @author: LiuQin
* @date: 2015年7月18日 下午3:11:43
*/
public class EncryptUtilsBak {
public static String PUBLICKEY = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC1qSc4idfWls43XQp+HkF4enRu1iDCD3YKfbmIbiD6j257RfxBA3PLVWppWWRLmv1M+mTv+pRKXUzyv9VNWlfQhqEgo7AFxzPjrDKHKNicN9LtZSTRqz/p9rimzxpuJP4z9OB1GfNBR5Bs/hTK0jLEpMyCsMA8q3Su3v15cKOZiQIDAQAB";
static{
System.loadLibrary("crypto");
System.loadLibrary("_All_ATET_Market_Crypto");
PUBLICKEY=mencrypt(PUBLICKEY);
}
public static String signPostData(String content){
String result = null;
// result = "123456";
result = payEncrypt(content, PUBLICKEY);
return result;
}
public static boolean checkSign(String content, String sign){
boolean result = false;
String contentSign = payEncrypt(content, PUBLICKEY);
if(contentSign.equals(sign)){
result = true;
}
return result;
}
public static String payEncrypt(String content, String key){
if(TextUtils.isEmpty(content) || TextUtils.isEmpty(key)){
return null;
}
String txt=mencrypt(content);
return encrypt(txt, key);
}
/**
* 加密
* @param content 需要加密的内容
* @param key 加密是采用的public key
* @return 加密后的密文
*/
public static String encryptAES(String content, String key)
{
return encrypt(content, key);
}
/**
* 解密
* @param cryptograph 需要解密的密文
* @param key 加密时采用的public key
* @return 解密后的内容文本
*/
public static String decryptAES(String cryptograph, String key)
{
return decrypt(cryptograph, key);
}
public static native String encrypt(String code, String key);
public static native String decrypt(String code, String key);
public static native String mencrypt(String code);
}
|
TypeScript
|
UTF-8
| 557 | 2.796875 | 3 |
[] |
no_license
|
import { DirectionType } from "../utils/DirectionType";
import { LaserBullet } from "./bullets/LaserBullet";
import { Weapon } from "./Weapon";
class SingleLaserWeapon extends Weapon {
constructor(scene: Phaser.Scene) {
super(scene, LaserBullet);
this.fireRate = 200;
}
public shoot(direction: DirectionType, x: number, y: number): void {
let bullet: LaserBullet = this.getFirstDead(true);
if (bullet) {
bullet.fire(direction, x, y);
}
}
}
export { SingleLaserWeapon }
|
C++
|
GB18030
| 3,005 | 2.875 | 3 |
[] |
no_license
|
#include "stdio.h"
#include "math.h"
#include <iostream>
#include <time.h>
#define SUPPORT_SIZE 2 // ˹˲ڰ뾶
#define IM_WIDTH 1920 // ͼ
#define IM_HEIGHT 1080
// ˹ϵ
void calGaussCoef(double *pGaussCoef)
{
int i, j, k;
int wlen = (SUPPORT_SIZE<<1) + 1;
double sum = 0;
if(pGaussCoef)
{
for(i = -SUPPORT_SIZE; i <= SUPPORT_SIZE; i++)
{
for(j = -SUPPORT_SIZE; j <= SUPPORT_SIZE; j++)
{
//˹ϵ2.71828ΪȻe
pGaussCoef[ (i+SUPPORT_SIZE)*wlen + j+SUPPORT_SIZE ] = pow( 2.71828, (-double(i*i + j*j)/25) );
}
}
for(k = 0; k < wlen*wlen; k++)
{
sum += pGaussCoef[k];
}
for(k = 0; k < wlen*wlen; k++) //йһ
{
pGaussCoef[k] /= sum;
}
}
}
// 2άʵ2άͼ˹˲
// pGaussCoefΪ˹ϵ
// pSrcImgΪԭʼͼ
// pDstImgΪ˲ͼ
// heightͼ߶
// widthͼ
// supportSize˹˲ڰ뾶ֱΪ2*supportSize + 1
void conv2D(double *pGaussCoef, unsigned char *pSrcImg, unsigned char *pDstImg, int height, int width, int supportSize)
{
int i, j;
int m, n;
int indexI, indexG;
int sw = supportSize;
int slen = sw*2 + 1;
double sum;
double *pTemp = NULL;
pTemp = new double[height*width];
for(i = 0; i < height*width; i++)
{
pTemp[i] = (double)pSrcImg[i];
}
for(i = sw; i < height - sw; i++)
{
for(j = sw; j < width - sw; j++)
{
sum = 0;
calGaussCoef(pGaussCoef);
for(m = -sw; m <= sw; m++)
{
for(n = -sw; n <= sw; n++)
{
indexI = (i+m)*width + j+n;
indexG = (m+sw)*slen + n+sw;
sum += pSrcImg[indexI] * pGaussCoef[indexG];
}
}
pDstImg[i*width + j] = (unsigned char)(sum);
}
}
}
void main()
{
int wlen, imLen;
time_t start, end;
double *pGaussCoef = NULL;
unsigned char *pSrc = NULL, *pDst = NULL;
unsigned char buffer[1078]; //BMPͼļͷ
FILE *fin, *fout;
if( !(fin=fopen("in.bmp","rb")) ) //ԭʼͼ
{
printf("Open file %s error!\n","in.bmp");
exit(1);
}
if( !(fout=fopen("out.bmp","wb")) ) //˲ͼ
{
printf("Open file %s error!\n","out.bmp");
exit(1);
}
wlen = SUPPORT_SIZE * 2 + 1;
imLen = IM_WIDTH * IM_HEIGHT;
pGaussCoef = new double[wlen*wlen];
pSrc = new unsigned char[IM_WIDTH*IM_HEIGHT];
pDst = new unsigned char[IM_WIDTH*IM_HEIGHT];
fread(buffer, 1, 1078, fin); //ȡ1078ֽBMPͼļͷϢ
fread(pSrc, sizeof(unsigned char), imLen, fin); //ļͼ
start = clock();
conv2D(pGaussCoef, pSrc, pDst, IM_HEIGHT, IM_WIDTH, SUPPORT_SIZE); //ִ˲
end = clock();
printf("running time is %d\n", end - start);
fwrite(buffer, sizeof(unsigned char), 1078, fout);
fwrite(pDst, sizeof(unsigned char), imLen, fout); //˲дļ
delete[] pGaussCoef;
delete[] pSrc;
delete[] pDst;
fclose(fin);
fclose(fout);
}
|
C
|
UTF-8
| 859 | 3.65625 | 4 |
[] |
no_license
|
//keyword,variable and data type--------
#include<stdio.h>
int main(){
//keyword,variable and data type--------
int num1=10;
float num2=30.23467890;
double num3=40.6678888968;
char num4='x';
printf("This number is %d\n %f\n %lf\n %c\n",num1,num2,num3,num4);
//iteger data type-----
int num1=10,num2=20;
printf("Number is_ %d\n",num1);
printf("Number is_ %d\n",num2);
//float data type-----
float num1=9.33343,num2=20.9654545;
printf("Number is_ %f\n",num1);
printf("Number is_ %.3f\n",num2);
//double data type-----
double num1=339.337788,num2=20.963231;
printf("Number is_ %lf\n",num1);
printf("Number is_ %.4lf\n",num2);
//charecter data type-----
char num1='a',num2='y';
printf("cheatcter is __ %c\n",num1);
printf("cheatcter is __ %c",num2);
return 0;
}
|
C++
|
UTF-8
| 1,260 | 2.671875 | 3 |
[] |
no_license
|
#include <iostream>
using namespace std;
int reward[6][6] = {
{-1,-1,-1,-1,0,-1},
{-1,-1,-1,0,-1,100},
{-1,-1,-1,0,-1,-1},
{-1,0,0,-1,0,-1},
{0,-1,-1,0,-1,100},
{-1,0,-1,-1,0,100},
};
int q[6][6];
int old[6][6];
int Max(int s){
int max = 0;
for(int i=0; i<6; i++){
if(old[s][i] > max)
max = old[s][i];
}
return max;
}
int main(){
int episode = 1000000;
int alpha = 0.8;
int eps = 10;
int s = 0;
//1. 对于每一个 eposide
//1.1 随机初始化一个状态
//1.2 随机初始化一个action
//根据公式 q(s,a)=r(s,a)+max(s', a') 计算
//计算 state = next_state
do{
for(int i=0; i<6; i++){
for(int j=0; j<6; j++){
int val = q[i][j];
val = reward[i][j] + alpha*Max(j);
s = max(s, abs(q[i][j]-val));
}
}
//使用 old 将当前值保存起来
for(int i=0; i<6; i++){
for(int j=0; j<6; j++){
old[i][j] = q[i][j];
}
}
}while(s>eps);
for(int i=0; i<6; i++){
for(int j=0; j<6; j++){
cout<<q[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
|
Shell
|
UTF-8
| 7,015 | 3.9375 | 4 |
[] |
no_license
|
#!/bin/sh
set -euf
host="sunfire.comp.nus.edu.sg"
default_printqueue="psc008-dx"
default_script="/usr/local/bin/socprint.sh"
usage() {
cat <<EOF
NAME
socprint.sh - POSIX™-compliant, zero-dependency shell script to print stuff in NUS SoC
REQUIREMENTS
POSIX™-compliant sh, a sunfire account, and connection to SoC wifi.
USAGE
To use instantly, run the following line:
curl -s https://raw.githubusercontent.com/dlqs/SOCprint/master/socprint.sh | sh -s -- -u <username> -f <filepath> -p <printqueue>
To download and run from any directory:
sudo curl https://raw.githubusercontent.com/dlqs/SOCprint/master/socprint.sh -o $default_script
sudo chmod 755 $default_script
socprint.sh -u <username> -f <filepath> -p <printqueue>
PARAMETERS
-u, --username <username>
(required) Sunfire username, without the @sunfire.comp.nus.edu.sg part.
-i, --identity-file <filepath>
(optional) Additional identity file to use with ssh. Skip if you already set up sunfire identity files for ssh.
-f, --filepath <filepath>
(required to print) File to print. Tested with PDF/plain text files. Undefined behaviour for anything else.
-p, --printqueue <printqueue>
(required to print/show) Printqueue to send job to. Default: psc008-dx. See PRINTQUEUES.
-s, --show-printqueue
(required to show) Show list of jobs at specified printqueue.
-l, --list-printqueues
(required to list printqueues) List printqueues, i.e. valid arguments for -p.
--dry-run
(for debugging/tests) Echoes commands to be executed without executing them.
EXAMPLES
To print:
./socprint.sh -u d-lee -f ~/Downloads/cs3210_tutorial8.pdf -p psc008-dx
To list printqueues:
./socprint.sh -u d-lee -l
To show printqueue at psc008:
./socprint.sh -u d-lee -s -p psc008
DESCRIPTION
This script targets conformance to POSIX.1-2017 standards (https://pubs.opengroup.org/onlinepubs/9699919799/).
This improves portability, enterprise-gradeability, and makes printing in SoC a zero-dependency,
no-ass-sucking experience. Roughly speaking, this script will:
1. Login to sunfire using ssh.
You will be prompted for your password, unless your identity files are set up.
This script *does not* save/record your password.
2. Copy the file into your home directory in sunfire, to a temporary file.
3. Submit your job to the printqueue.
4. List the printqueue. You job *should* appear. If not, something has gone wrong.
5. Remove the temporary file.
PRINTQUEUES
Popular places:
- COM1 basement: psc008 psc008-dx psc008-sx psc011 psc011-dx psc011-sx
- COM1 L1, in front of tech svsc: psts psts-dx psts-sx pstb pstb-dx pstb-sx
- (no suffix)/-dx: double sided, -sx: single sided, -nb: no banner
- Most other printers have user restrictions.
See https://dochub.comp.nus.edu.sg/cf/guides/printing/print-queues.
- For the full list of printqueues, generate with the -l option, or view the SOURCE.
SOURCE
https://github.com/dlqs/SOCprint
File bugs or compliance issues above. We take POSIX™ conformance seriously.
POSIX™ is a Trademark of The IEEE.
CONTRIBUTORS
Donald Lee, Julius Nugroho, Sean Ng
GENERATE README
./socprint.sh -h > README \
&& echo "List of valid printqueues, generated with -l option on 5 March 2021\n" >> README \
&& ./socprint.sh -u d-lee -l >> README
EOF
exit 0
}
msg() {
# Log messages to stderr instead of stdout
# Woahhhhh %b siol
printf "%b\n" "${1-}" >&2
}
die() {
msg "$1"
exit 1
}
check_updates() {
# Calculate git hash-object hash without git, since it is not POSIX compliant
size=$( wc -c ${default_script} | cut -f 1 -d ' ' )
my_sha=$( (printf "blob %s\0" "$size" && cat ${default_script}) | shasum -a 1 | cut -f 1 -d ' ')
# Pull latest hash from master
github_sha=$( curl -s -H "Accept: application/vnd.github.v3+json" https://api.github.com/repos/dlqs/SOCprint/contents/socprint.sh | sed -n 's/.*"sha":\s"\(.*\)",/\1/p' )
if [ "$my_sha" != "$github_sha" ]; then
msg "Hint: You appear to have downloaded this script to $default_script. There's a newer version available ($( printf '%s' "$my_sha" | head -c 10) v $( printf '%s' "$github_sha" | head -c 10 ))."
msg "Run the following command to download the new script:"
msg "sudo curl https://raw.githubusercontent.com/dlqs/SOCprint/master/socprint.sh -o $default_script \n"
fi
}
parse_params() {
# default values of variables
identity_file=''
printqueue=''
list_printqueues=false
show_printqueue=false
while :; do
case "${1-}" in
-h | --help) usage ;;
-l | --list-printqueues)
list_printqueues=true
;;
-s | --show-printqueue)
show_printqueue=true
;;
-i | --identity-file)
identity_file="${2-}"
shift
;;
-p | --printqueue)
printqueue="${2-}"
shift
;;
-f | --filepath)
filepath="${2-}"
shift
;;
-u | --username)
username="${2-}"
shift
;;
--dry-run)
dry_run=true
;;
-?*) die "Unknown option: $1" ;;
*) break ;;
esac
shift
done
return 0
}
parse_params "$@"
# Only check update if downloaded to local bin and we're not dry-running, as
# this could potentially mess tests up.
[ -f "/usr/local/bin/socprint.sh" ] && [ -z "${dry_run-}" ] && check_updates
[ -z "${username}" ] && die "Missing required parameter: -u/--username"
sshcmd="${username}@${host}"
# Use the ssh identity_file if provided
[ -n "${identity_file}" ] && sshcmd="${sshcmd} -i ${identity_file}"
if [ -n "${dry_run-}" ]; then
eval_or_echo_in_dry_run='printf %b\n'
else
eval_or_echo_in_dry_run='eval'
fi
msg "Using ${username}@${host} ..."
if [ "${list_printqueues}" = true ]; then
cmd=$( cat <<EOF
ssh $sshcmd "cat /etc/printcap | grep '^p' | sed 's/^\([^:]*\).*$/\1/'"
EOF
)
$eval_or_echo_in_dry_run "$cmd"
exit 0
fi
if [ -z "${printqueue-}" ]; then
msg "Using default printqueue: ${default_printqueue}"
msg "Hint: To set a different one, use the -p option. To list all, use the -l option."
printqueue="${default_printqueue}"
fi
if [ "${show_printqueue}" = true ]; then
cmd=$( cat <<EOF
ssh $sshcmd "lpq -P ${printqueue};"
EOF
)
$eval_or_echo_in_dry_run "$cmd"
exit 0
fi
[ -z "${filepath-}" ] && die "Missing required parameter: -f/--filepath"
[ ! -f "${filepath-}" ] && die "Error: No such file"
filetype=$( file -i "${filepath}" | cut -f 2 -d ' ')
[ "${filetype}" != 'application/pdf;' ] && [ "$( printf '%s' "$filetype" | head -c 4 )" != 'text' ] && msg "Warning: File is not PDF or text. Print behaviour is undefined."
# Generate random 8 character alphanumeric string in a POSIX compliant way
tempname=$( awk 'BEGIN{srand();for(i=0;i<8;i++){r=int(61*rand());printf("%c",r<10?48+r:r<35?55+r:62+r)}}' )
tempname="SOCPrint_${tempname}"
cmd=$( cat <<EOF
ssh $sshcmd "
cat - > ${tempname};
lpr -P ${printqueue} ${tempname};
lpq -P ${printqueue};
rm ${tempname};" < "${filepath}"
EOF
)
$eval_or_echo_in_dry_run "$cmd"
exit 0
|
C#
|
UTF-8
| 1,416 | 2.859375 | 3 |
[
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
] |
permissive
|
#region using
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
#endregion
namespace Xigadee
{
/// <summary>
/// This is the standard service implementation.
/// </summary>
public interface IService
{
event EventHandler<StatusChangedEventArgs> StatusChanged;
/// <summary>
/// Starts the service and returns immediately.
/// </summary>
void Start();
/// <summary>
/// This method stops a service.
/// </summary>
void Stop();
/// <summary>
/// This method allows the statitics to be retrieved as a generic format.
/// </summary>
/// <returns></returns>
StatusBase StatisticsGet();
}
/// <summary>
/// This class holds the status change.
/// </summary>
public class StatusChangedEventArgs: EventArgs
{
/// <summary>
/// The previous service status.
/// </summary>
public ServiceStatus StatusOld { get; set; }
/// <summary>
/// The new service status.
/// </summary>
public ServiceStatus StatusNew { get; set; }
/// <summary>
/// This is an optional message describing the reason for the status change.
/// </summary>
public string Message { get; set; }
}
}
|
Java
|
UTF-8
| 379 | 2.75 | 3 |
[] |
no_license
|
package FridayClassDay08;
class B1{
B1(){
System.out.println("Parent' deafult constructor");
}
B1(int a){
}
}
public class super_practices2 extends B1 {
// child parent class
super_practices2(){
// super( 1000 ); // we have to call Reason: #12
}
public static void main(String[] args) {
new super_practices2();
}
}
|
Java
|
UTF-8
| 4,651 | 2.703125 | 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 custombrowser;
import java.io.File;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
class XmlRead {
String[] groups; //所属しているグループを保存する変数
String group; //選択したグループを保存する変数
int num; //グループ数を保存する変数
String hash_key; //ハッシュ関数で処理した鍵を保存する変数
String key; //グループ鍵を保存する変数
byte[] bytekey; //byte型に変換したグループ鍵を保存する変数
Document doc;
Element root;
NodeList nodelist;
public XmlRead(){
//System.out.println("XmlReadコンストラクタ");
}
public XmlRead(CustomBrowserTabController customBrowserTabController) {
// TODO 自動生成されたコンストラクター・スタブ
}
//xmlファイルを読み込む関数
public void Read(){
try {
System.out.println("ここは?");
/**xmlファイルを読み込む準備**/
DocumentBuilderFactory factory
= DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
//相対パスでxmlファイルを読み込む
File f = new File( "src/sglclient/conf/usr/xml_files/MyInformation.xml" );
if(!f.exists()){
return;
}
System.out.println("xmlファイルを読み込みました");
doc = builder.parse( f );
root = doc.getDocumentElement();
nodelist = root.getElementsByTagName("Group");
num = nodelist.getLength();
groups = new String[num];
//System.out.println("グループ数:"+num);
for( int i=0; i<num; i++ ) {
Node node = nodelist.item(i);
NamedNodeMap attrs = node.getAttributes();
Node attr = attrs.getNamedItem("xmlns:Name");
groups[i] = attr.getNodeValue(); //所属しているグループを配列に保存
}
}
catch( ParserConfigurationException e ) {
}
catch( SAXException e ) {
}
catch( IOException e ) {
}
}
//グループ鍵を取得する関数
public byte[] GetKey(){
//System.out.println("num:"+num);
//System.out.println("グループ:"+group);
for(int i=0; i<num; i++){
//System.out.println("groupi="+groups[i]);
if(groups[i].matches(group)){
//System.out.println("ifぶんにははいってます");
Node node = nodelist.item(i);
NamedNodeMap attrs = node.getAttributes();
Node attr = attrs.getNamedItem("xmlns:key");
key = attr.getNodeValue();
System.out.println("取得した鍵:"+key);
}
}
hash_key = sha256(key); //グループ鍵をハッシュ関数で処理する
//System.out.println("変換した鍵:"+sha256(key));
/***グループ鍵をbyte型に変換***/
bytekey = new byte[hash_key.length()/2];
//System.out.println(bytekey.length);
for(int i=0; i<bytekey.length; i++){
bytekey[i] = (byte)(Integer.parseInt(hash_key.substring(i*2,(i+1)*2),16));
}
return bytekey; //byte型に変換したグループ鍵を返す
}
//入力された文字列のSHA-256ハッシュ値を得る
public static String sha256(String input){
return hash(input,"SHA-256");
}
//ハッシュ値を計算
private static String hash(String input, String algorithm) {
MessageDigest digest;
try {
digest = MessageDigest.getInstance(algorithm);
digest.update(input.getBytes());
}
catch (NoSuchAlgorithmException e) {
return "";
}
return byte2HexString(digest.digest());
}
//バイトコードを16進数文字列に変換
public static String byte2HexString(byte[] input) {
StringBuffer buff = new StringBuffer();
int count = input.length;
for(int i= 0; i< count; i++){
buff.append(Integer.toHexString( (input[i]>> 4) & 0x0F ) );
buff.append(Integer.toHexString( input[i] & 0x0F ) );
}
return buff.toString();
}
}
|
Python
|
UTF-8
| 300 | 3.203125 | 3 |
[] |
no_license
|
# 该方法用来确认元素是否存在,如果存在返回flag=true,否则返回false
def isElementExist(self, element):
flag = True
driver = self.driver
try:
driver.find_element_by_xpath(element)
return flag
except:
flag = False
return flag
|
C
|
UTF-8
| 393 | 3.125 | 3 |
[] |
no_license
|
#include<stdio.h>
#include <stdlib.h>
int main()
{
int n,x,y,xd=0,yd=0,base=1,rem,sum=0;
scanf("%d",&n);
scanf("%d %d",&x,&y);
while(x>0)
{
rem=x%10;
xd=xd+rem*base;
x=x/10;
base=base*n;
}
while(y>0)
{
rem=y%10;
yd=yd+rem*base;
y=y/10;
base=base*n;
}
sum=xd+yd;
printf("%d",sum);
}
|
Java
|
UTF-8
| 270 | 1.679688 | 2 |
[] |
no_license
|
package com.google.ads.internal;
import java.net.HttpURLConnection;
import java.net.URL;
final class C0268s implements C0267t {
C0268s() {
}
public final HttpURLConnection mo114a(URL url) {
return (HttpURLConnection) url.openConnection();
}
}
|
Java
|
UTF-8
| 1,616 | 2.609375 | 3 |
[] |
no_license
|
package com.brainstation.bank.demo.controllers;
import com.brainstation.bank.demo.utils.CustomPasswordGenerator;
import com.brainstation.bank.demo.utils.Email;
import com.brainstation.bank.demo.utils.UserAge;
import com.brainstation.bank.demo.models.User;
import com.brainstation.bank.demo.services.UserService;
import org.springframework.web.bind.annotation.*;
import javax.mail.MessagingException;
@CrossOrigin
@RestController
@RequestMapping("/api/v1/user")
public class UserController {
private UserService userService;
private Email email;
private UserAge userAge;
private CustomPasswordGenerator customPasswordGenerator;
public UserController(UserService userService, Email email, UserAge userAge, CustomPasswordGenerator customPasswordGenerator) {
this.userService = userService;
this.email = email;
this.userAge = userAge;
this.customPasswordGenerator = customPasswordGenerator;
}
@PostMapping
public String save(@RequestBody User user) throws MessagingException {
String password = (customPasswordGenerator.generatePassayPassword());
user.setPassword(password);
user.setAge(userAge.getAge(user.getBirthDate()));
userService.save(user);
email.sendEmail(user.getEmail(), "Welcome to myBank ","Hi " + user.getName() + " " + user.getLastName() + " " + "Your password is: " + password);
return password;
}
@PutMapping("/update-password")
public String changePassword(@RequestBody User user){
return userService.updatePassword(user.getUserId(), user.getPassword());
}
}
|
C++
|
UTF-8
| 196 | 2.53125 | 3 |
[] |
no_license
|
#include "vector4.h"
Vector4::~Vector4(void)
{
}
Vector4 operator + (const Vector4& A ,const Vector4& B) {
return Vector4(A.v[0] + B.v[0], A.v[1] + B.v[1], A.v[2] + B.v[2], A.v[3] + B.v[3]);
}
|
Shell
|
UTF-8
| 3,296 | 3.1875 | 3 |
[] |
no_license
|
#/var/bin/bash
# Make sure only root can run our script
if [ "$(id -u)" != "0" ]; then
echo "This install script must be run as root" 1>&2
exit 1
fi
pushd /var/tmp/
echo "1. Download and install dependencies"
rm -rf gzip_1.10_iphoneos-arm.deb
rm -rf unrar_5.5.8_iphoneos-arm.deb
rm -rf bzip2_1.0.6-2_iphoneos-arm.deb
rm -rf zip_3.0_iphoneos-arm.deb
rm -rf p7zip_16.02_iphoneos-arm.deb
rm -rf unzip_6.0_iphoneos-arm.deb
wget http://tigisoftware.com/rootless/debs/gzip_1.10_iphoneos-arm.deb
wget http://tigisoftware.com/rootless/debs/unrar_5.5.8_iphoneos-arm.deb
wget http://tigisoftware.com/rootless/debs/bzip2_1.0.6-2_iphoneos-arm.deb
wget http://tigisoftware.com/rootless/debs/zip_3.0_iphoneos-arm.deb
wget http://tigisoftware.com/rootless/debs/p7zip_16.02_iphoneos-arm.deb
wget http://tigisoftware.com/rootless/debs/unzip_6.0_iphoneos-arm.deb
dpkg -i gzip_1.10_iphoneos-arm.deb
dpkg -i unrar_5.5.8_iphoneos-arm.deb
dpkg -i bzip2_1.0.6-2_iphoneos-arm.deb
dpkg -i zip_3.0_iphoneos-arm.deb
dpkg -i p7zip_16.02_iphoneos-arm.deb
dpkg -i unzip_6.0_iphoneos-arm.deb
rm -rf gzip_1.10_iphoneos-arm.deb
rm -rf unrar_5.5.8_iphoneos-arm.deb
rm -rf bzip2_1.0.6-2_iphoneos-arm.deb
rm -rf zip_3.0_iphoneos-arm.deb
rm -rf p7zip_16.02_iphoneos-arm.deb
rm -rf unzip_6.0_iphoneos-arm.deb
echo "2. Download Filza File Manager"
wget http://tigisoftware.com/rootless/Filza.app.tar
wget http://tigisoftware.com/rootless/FilzaBins.tar
wget http://tigisoftware.com/rootless/com.tigisoftware.filza.helper.plist
echo "3. Install Filza File Manager"
mkdir /var/containers/Bundle/tweaksupport/data
rm -rf /var/containers/Bundle/tweaksupport/data/Filza*
rm -rf /var/Apps/Filza*
rm -rf /var/libexec/filza
rm -rf /var/containers/Bundle/tweaksupport/Library/LaunchDaemons/com.tigisoftware.filza.helper.plist
tar -xf Filza.app.tar -C /var/Apps/
mkdir /var/libexec/filza
tar -xf FilzaBins.tar -C /var/libexec/filza/
cp -r /var/Apps/Filza.app /var/containers/Bundle/tweaksupport/data/
/var/containers/Bundle/iosbinpack64/usr/bin/inject /var/Apps/Filza.app/Filza
/var/containers/Bundle/iosbinpack64/usr/bin/inject /var/Apps/Filza.app/dylibs/libsmb2-ios.dylib
/var/containers/Bundle/iosbinpack64/usr/bin/inject /var/Apps/Filza.app/PlugIns/Sharing.appex/Sharing
/var/containers/Bundle/iosbinpack64/usr/bin/inject /var/libexec/filza/Filza
/var/containers/Bundle/iosbinpack64/usr/bin/inject /var/libexec/filza/FilzaHelper
/var/containers/Bundle/iosbinpack64/usr/bin/inject /var/libexec/filza/FilzaWebDAVServer
cp /var/libexec/filza/Filza /var/containers/Bundle/tweaksupport/data/
cp /var/libexec/filza/FilzaHelper /var/containers/Bundle/tweaksupport/data/
cp /var/libexec/filza/FilzaWebDAVServer /var/containers/Bundle/tweaksupport/data/
cp com.tigisoftware.filza.helper.plist /var/containers/Bundle/tweaksupport/Library/LaunchDaemons/com.tigisoftware.filza.helper.plist
launchctl unload /var/containers/Bundle/tweaksupport/Library/LaunchDaemons/com.tigisoftware.filza.helper.plist
launchctl load -w /var/containers/Bundle/tweaksupport/Library/LaunchDaemons/com.tigisoftware.filza.helper.plist
/var/containers/Bundle/iosbinpack64/usr/bin/uicache
rm -rf Filza.app.tar
rm -rf FilzaBins.tar
rm -rf com.tigisoftware.filza.helper.plist
popd
echo "4. Done"
echo "5. If you get any installation error, please copy and send to info@tigisoftware.com"
|
PHP
|
UTF-8
| 3,232 | 2.71875 | 3 |
[] |
no_license
|
<?php
include('db.php');
if(isset($_POST['update']))
{
$id = $_POST['id'];
$name=$_POST['name'];
$address=$_POST['address'];
$phone_number=$_POST['phone_number'];
$email=$_POST['email'];
if(empty($id) || empty($name) || empty($address) || empty($phone_number) || empty($email)) {
echo "Donot leave empty field";
} else {
$result = mysqli_query($conn, "UPDATE cloud SET id='$id',name='$name',address='$address',phone_number='$phone_number',email='$email' WHERE id=$id");
header("Location: datas.php");
}
}
?>
<?php
$id = $_GET['id'];
$result = mysqli_query($conn, "SELECT * FROM cloud WHERE id=$id");
while($res = mysqli_fetch_array($result))
{
$id=$res['id'];
$name = $res['name'];
$address = $res['address'];
$phone_number = $res['phone_number'];
$email = $res['email'];
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Edit Data</title>
<style>
h1 {
text-align: center;
text-effect: outline;
}
body {
font-size: 19px;
}
table {
width: 50%;
margin: 30px auto;
border-collapse: collapse;
text-align: left;
}
tr {
border-bottom: 1px solid #cbcbcb;
}
th, td {
border: none;
height: 30px;
padding: 2px;
}
tr:hover {
background: #F5F5F5;
}
form {
width: 45%;
margin: 50px auto;
text-align: left;
padding: 20px;
border: 1px solid #bbbbbb;
border-radius: 5px;
}
.input-group {
margin: 10px 0px 10px 0px;
}
.input-group label {
display: block;
text-align: left;
margin: 3px;
}
.input-group input {
height: 30px;
width: 93%;
padding: 5px 10px;
font-size: 16px;
border-radius: 5px;
border: 1px solid gray;
}
.btn {
padding: 10px;
font-size: 15px;
color: white;
background: #5F9EA0;
border: none;
border-radius: 5px;
}
</style>
</head>
<body>
<h1>Form fill up </h1>
<form method="post" action="edit.php">
<div class="input-group">
<label>ID</label>
<input type="number" name="id" value="<?php echo $id;?>">
</div>
<div class="input-group">
<label>Name</label>
<input type="text" name="name" value="<?php echo $name;?>">
</div>
<div class="input-group">
<label>Address</label>
<input type="text" name="address" value="<?php echo $address;?>">
</div>
<div class="input-group">
<label>Phone Number</label>
<input type="number" name="phone_number" value="<?php echo $phone_number;?>">
</div>
<div class="input-group">
<label>Email</label>
<input type="email" name="email" value="<?php echo $email;?>">
</div>
<div class="input-group">
<button class="btn" type="submit" name="update">Update</button>
</div>
</form>
</body>
</html>
|
Java
|
UTF-8
| 6,096 | 2.625 | 3 |
[] |
no_license
|
import com.sun.scenario.effect.impl.sw.sse.SSEBlend_SRC_OUTPeer;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Scanner;
public class WePayU {
private int day;
private int month;
private int weekday;
public void payMenu(Calendar calendar,Database database)
{
Scanner input = new Scanner(System.in);
displayPayMenu();
int choice = input.nextInt();
switch (choice)
{
case 1:
payCheck(calendar,
database.getEmployeeArrayList(),
database.getHourly_employeeArrayList(),
database.getComissioned_employeeArrayList(),
database.getSalaried_employeeArrayList()
);
break;
case 2:
calendar.add(Calendar.DAY_OF_MONTH,1);
System.out.println(calendar.getTime());
break;
}
}
public void displayPayMenu()
{
System.out.println("1: Pagamentos do dia");
System.out.println("2: Avançar um dia");
}
public void payCheck(Calendar calendar,ArrayList<Employee> employee,
ArrayList<Hourly_Employee> hourly_employee,
ArrayList<Comissioned_Employee> comissioned_employees,
ArrayList<Salaried_Employee> salaried_employee)
{
day = calendar.get(Calendar.DAY_OF_MONTH);
month = calendar.get(Calendar.MONTH);
weekday = calendar.get(Calendar.DAY_OF_WEEK);
for (int i = 0; i < hourly_employee.size() ; i++)
{
if (hourly_employee.get(i).paymentAgenda.getType().equals("mensal"))
{
if (hourly_employee.get(i).paymentAgenda.getDuedatemonth() == month)
{
if (hourly_employee.get(i).paymentAgenda.getDuedateday() == day)
{
System.out.println(hourly_employee.get(i).getAccumulatedsalary());
hourly_employee.get(i).setAccumulatedsalary(hourly_employee.get(i).getAccumulatedsalary()*-1);
}
}
}
else if (hourly_employee.get(i).paymentAgenda.getType().equals("semanal"))
{
System.out.println(hourly_employee.get(i).paymentAgenda.getDuedateday());
System.out.println(hourly_employee.get(i).paymentAgenda.getDuedatemonth());
System.out.println(hourly_employee.get(i).paymentAgenda.getDueweekday());
if (hourly_employee.get(i).paymentAgenda.getDuedateday() == day)
{
if (hourly_employee.get(i).paymentAgenda.getDueweekday() == weekday)
{
System.out.println("Pagamento efetuado!");
hourly_employee.get(i).setAccumulatedsalary(hourly_employee.get(i).getAccumulatedsalary()*-1);
}
}
}
}
for (int i = 0; i <comissioned_employees.size() ; i++)
{
if (comissioned_employees.get(i).paymentAgenda.getType().equals("mensal"))
{
if (comissioned_employees.get(i).paymentAgenda.getDuedatemonth() == month)
{
if (comissioned_employees.get(i).paymentAgenda.getDuedateday() == day)
{
System.out.println(comissioned_employees.get(i).getAccumulatedsalary());
comissioned_employees.get(i).setAccumulatedsalary(hourly_employee.get(i).getAccumulatedsalary()*-1);
}
}
}
else if (comissioned_employees.get(i).paymentAgenda.getType().equals("semanal"))
{
System.out.println(comissioned_employees.get(i).paymentAgenda.getDuedateday());
System.out.println(comissioned_employees.get(i).paymentAgenda.getDuedatemonth());
System.out.println(comissioned_employees.get(i).paymentAgenda.getDueweekday());
if (comissioned_employees.get(i).paymentAgenda.getDuedateday() == day)
{
if (comissioned_employees.get(i).paymentAgenda.getDueweekday() == weekday)
{
System.out.println("Pagamento efetuado!");
comissioned_employees.get(i).setAccumulatedsalary(comissioned_employees.get(i).getAccumulatedsalary()*-1);
}
}
}
}
for (int i = 0; i < salaried_employee.size() ; i++)
{
if (salaried_employee.get(i).paymentAgenda.getType().equals("mensal"))
{
if (salaried_employee.get(i).paymentAgenda.getDuedatemonth() == month)
{
if (salaried_employee.get(i).paymentAgenda.getDuedateday() == day)
{
System.out.println(salaried_employee.get(i).getSalary());
salaried_employee.get(i).setSalary(salaried_employee.get(i).getSalary()*-1);
}
}
}
else if (salaried_employee.get(i).paymentAgenda.getType().equals("semanal"))
{
System.out.println(salaried_employee.get(i).paymentAgenda.getDuedateday());
System.out.println(salaried_employee.get(i).paymentAgenda.getDuedatemonth());
System.out.println(salaried_employee.get(i).paymentAgenda.getDueweekday());
if (salaried_employee.get(i).paymentAgenda.getDuedateday() == day)
{
if (salaried_employee.get(i).paymentAgenda.getDueweekday() == weekday)
{
System.out.println("Pagamento efetuado!");
salaried_employee.get(i).setSalary(salaried_employee.get(i).getSalary()*-1);
}
}
}
}
}
}
|
C++
|
UTF-8
| 551 | 3.609375 | 4 |
[] |
no_license
|
/**
* Copyright(C), 2018
* Name: cycle_list
* Author: Wilson Lan
* Description:
* Given a linked list, determine if it has a cycle in it.
*/
class Solution {
public:
bool hasCycle(ListNode *head) {
ListNode *slow = head, *fast = head;
while (fast != nullptr && fast->next != nullptr) {
slow = slow->next;
fast = fast->next->next;
if (slow == fast) {
return true;
}
}
return false;
}
};
|
Markdown
|
UTF-8
| 2,018 | 3.328125 | 3 |
[
"Apache-2.0",
"MIT"
] |
permissive
|
---
layout: post
title: "Mental health is important"
date: 2021-01-18 17:14:36 +0000
permalink: mental_health_is_important
---
Taking care of yourself mentally is really important especially in the times we are in now. I think that it is easy to push the way we are feeling off as something we can deal with later, but by doing this it just accumulates.
It does not help that society has put a stigma on mental illness, but I am glad to say that it is changing. You see more and more people talking about it which is great! Mental illness is a disease that can be treated! And there is no reason to be ashamed of it!
I have been a mental health tech for the last 5 years and over my time span I have picked up on signs of mental state. A few that I have noticed are:
1. anxiety
2. unable to sleep
3. depression
4. high and lows
I am by no means a license professional, but working in the field has showed me some signs. My word of advice is that you never know what someone is going through something, so be kind.
That brings me to tech. We to have to be cautious of how we are feeling. Taking sometime to step away from the computer to take a walk or just get some fresh air is important. Now that a lot of people are working from home and there is not a lot of human interaction I think inviting your co-worker or virtual buddy to a virtual coffee, just to talk about anything other than code or work would be a good way to ease some tension. And just a good way to check in with someone to see how they are doing.
We should also check in with ourselves to see how we are doing on a daily basis maybe add something like morning pages, which is a tool I recently got introduced to. Morning pages is essentially writing three pages of whatever comes to your mind. It allows for you to get the clutter out of your mind and on to paper, which frees up your mind for the day. Another good tool is a gratitude journal, which is a classic.
With all of that said have a wonderful day! Happy coding!
|
Java
|
UTF-8
| 2,668 | 3.28125 | 3 |
[] |
no_license
|
package com.epam.konstantin.frolov.java.lesson1;
import com.epam.konstantin.frolov.java.lesson1.task1.DZ1;
import com.epam.konstantin.frolov.java.lesson1.task2.DZ2;
import com.epam.konstantin.frolov.java.lesson1.task3.DZ3;
import java.util.Scanner;
public class Solution {
public static void main(String[] args) {
System.out.println("Choose option:");
Scanner in = new Scanner (System.in);
int key=in.nextInt();
if (key==1) {
System.out.print("Enter option: ");
Scanner in1=new Scanner(System.in);
int k1=in1.nextInt();
if (k1==1) {
DZ1.genMass();
DZ1.one();
}
if (k1==2) {
DZ1.genMass();
DZ1.two();
}
if (k1==3){
DZ1.genMass();
DZ1.three();
}
if (k1==4){
DZ1.genMass();
DZ1.four();
}
if (k1==5){
DZ1.genMass();
DZ1.five();
}
if (k1==6){
DZ1.genMass();
DZ1.six();
}
}
if (key==2){
DZ2 dz2=new DZ2();
System.out.print("Enter option: ");
Scanner in1=new Scanner(System.in);
int k1=in1.nextInt();
if (k1==1) {
dz2.getString();
dz2.getMinMax();
}
if (k1==2) {
dz2.getString();
dz2.getMoreThanSRZ();
}
if (k1==3){
dz2.getString();
dz2.getLessThanSRZ();
}
if (k1==4){
dz2.getWords();
dz2.getWordsWithMinDiffEl();
}
if (k1==5){
dz2.getWords();
dz2.getWordsWithDiffEl();
}
if (k1==6){
dz2.getWords();
dz2.getWordsOnlyWithNumbers();
}
}
if (key==3){
System.out.print("Enter math operation ('+','-','*','/'): ");
Scanner in1=new Scanner(System.in);
String s=in1.next();
char k1=s.charAt(0);
if (k1=='+') {
DZ3.readEl();
DZ3.summ();
}
if (k1=='-') {
DZ3.readEl();
DZ3.sub();
}
if (k1=='*'){
DZ3.readEl();
DZ3.mul();
}
if (k1=='/'){
DZ3.readEl();
DZ3.div();
}
}
}
}
|
C#
|
UTF-8
| 326 | 2.78125 | 3 |
[] |
no_license
|
namespace PokerHandCalculator
{
public class Card
{
public enum Suit
{
Clubs, Diamonds, Hearts, Spades
}
public enum Face
{
Two=2, Three=3, Four=4, Five=5, Six=6, Seven=7, Eight=8, Nine=9, Ten=10, Jack=11, Queen=12, King=13, Ace=14
}
}
}
|
C
|
UTF-8
| 400 | 2.875 | 3 |
[] |
no_license
|
#include "ft_list.h"
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
t_list *list;
list = ft_create_elem("toto\t");
printf("%s",list->data);
printf("%d\n",ft_list_size(list));
ft_list_push_back(&list,"tutu\t");
printf("%s",list->data);
printf("%d\n",ft_list_size(list));
ft_list_push_back(&list,"tata\t");
printf("%s",list->data);
printf("%d\n",ft_list_size(list));
return (0);
}
|
C++
|
UTF-8
| 4,308 | 3.21875 | 3 |
[] |
no_license
|
#include "prog1.h"
/***************************************************************************
* Function: cmdnm
*
* Description: Displays the command string (name) that started the process
* for a user-specified process ID
*
***************************************************************************/
void cmdnm(vector<string> & command)
{
if (command.size() > 1)
{
string process = "/proc/" + command[1] + "/cmdline";
ifstream fin(process.c_str());
if (fin.is_open())
{
string pline;
getline(fin,pline);
cout << pline << endl;
}
else
{
cout << "Invalid pid number" << endl;
}
}
else
cout << "Usage: cmdnm <pid>" << endl;
return;
}
/***************************************************************************
* Function: pid
*
* Description: Displays all process IDs whose command strings contain the
* user-specified string.
*
***************************************************************************/
void pid(vector<string> & command)
{
bool pid_found = false;
if (command.size() > 1)
{
char dir_name[] = "/proc";
DIR *dir = NULL;
struct dirent *proc_entry = NULL;
dir = opendir(dir_name);
if(dir)
{
while( (proc_entry = readdir(dir)) )
{
if( (proc_entry -> d_type) == DT_DIR )
{
bool is_Proc_Number = true;
string p_temp = proc_entry -> d_name;
for(string::const_iterator k = p_temp.begin(); k != p_temp.end(); ++k)
{
if ( isdigit(*k) == false )
is_Proc_Number = false;
}
if (is_Proc_Number)
{
string temp = "/proc/" + p_temp + "/cmdline";
ifstream fin(temp.c_str());
if (fin.is_open())
{
string p;
getline(fin, p);
for(string::iterator k = p.begin(); k != p.end(); ++k)
{
if (*k == '\0')
*k = ' ';
}
if (strstr(p.c_str(), command[1].c_str()) != NULL)
{
cout << proc_entry -> d_name << endl;
pid_found = true;
}
}
}
}
}
closedir(dir);
}
else
{
cout << "Error, cannot open directory";
}
}
// Error because no pid command was entered
else
cout << "Usage: pid <command>" << endl;
// Error if no such process number was discovered
if (!pid_found)
cout << "No matching pid found" << endl;
return;
}
/***************************************************************************
* Function: pid
*
* Description: Displays process information: Linux system version,
* system uptime, memory usage information, and CPU information
*
***************************************************************************/
void systat(vector<string> & command)
{
ifstream fin("/proc/version");
if (fin.is_open())
{
string vline;
getline(fin,vline);
cout << "Version: " << vline << endl;
}
fin.close();
fin.open("/proc/uptime");
if (fin.is_open())
{
string tline;
getline(fin,tline);
cout << "Uptime: " << tline << " seconds." << endl;
}
fin.close();
fin.open("/proc/meminfo");
if (fin.is_open())
{
string mline;
getline(fin,mline);
cout << mline << endl;
}
fin.close();
fin.open("/proc/cpuinfo");
if (fin.is_open())
{
string cline;
for (int i = 0; i < 9; ++i)
{
getline(fin,cline);
cout << cline << endl;
}
}
fin.close();
return;
}
|
Markdown
|
UTF-8
| 4,001 | 2.640625 | 3 |
[] |
no_license
|
---
description: "Simple Way to Prepare Speedy Pasta"
title: "Simple Way to Prepare Speedy Pasta"
slug: 2863-simple-way-to-prepare-speedy-pasta
date: 2020-10-25T05:05:54.592Z
image: https://img-global.cpcdn.com/recipes/3f1dc5ef9670eb3e/751x532cq70/pasta-recipe-main-photo.jpg
thumbnail: https://img-global.cpcdn.com/recipes/3f1dc5ef9670eb3e/751x532cq70/pasta-recipe-main-photo.jpg
cover: https://img-global.cpcdn.com/recipes/3f1dc5ef9670eb3e/751x532cq70/pasta-recipe-main-photo.jpg
author: Billy Payne
ratingvalue: 3.1
reviewcount: 3
recipeingredient:
- "2 cup Pasta boiled"
- "1 cup Red sauce"
- "1 Onion"
- "1 Tomato"
- "1/2 teaspoon Red chilli powder"
- "to taste curd with sugar and salt"
- "as needed Oil"
recipeinstructions:
- "Take a pan"
- "Add oil in it"
- "Add onion and saute well"
- "Add tomato and saute well"
- "Add spices and mix well"
- "Add red sauce and mix well"
- "Add pasta and mix well"
- "Serve hot with bread"
categories:
- Recipe
tags:
- pasta
katakunci: pasta
nutrition: 211 calories
recipecuisine: American
preptime: "PT36M"
cooktime: "PT52M"
recipeyield: "3"
recipecategory: Dessert
---

Hey everyone, it is Brad, welcome to our recipe site. Today, I will show you a way to prepare a distinctive dish, pasta. It is one of my favorites. For mine, I am going to make it a little bit unique. This is gonna smell and look delicious.
Pasta is one of the most popular of recent trending foods on earth. It's easy, it's quick, it tastes delicious. It is enjoyed by millions every day. Pasta is something which I have loved my whole life. They're fine and they look fantastic.
Pasta is a type of food typically made from an unleavened dough of wheat flour mixed with water or eggs, and formed into sheets or other shapes, then cooked by boiling or baking. Pasta Primavera - Spring Vegetable Pasta. Pasta with Roasted Tomato Sauce - Ditalini with Roasted Tomatoes, Oregano, and Goat Cheese. Ищите рецепты пасты и пиццы? Откройте наш каталог рецептов.
To get started with this recipe, we must prepare a few components. You can have pasta using 7 ingredients and 8 steps. Here is how you can achieve that.
<!--inarticleads1-->
##### The ingredients needed to make Pasta:
1. Prepare 2 cup Pasta boiled
1. Take 1 cup Red sauce
1. Make ready 1 Onion
1. Get 1 Tomato
1. Take 1/2 teaspoon Red chilli powder
1. Take to taste curd with sugar and salt
1. Prepare as needed Oil
You've come to the right place. Here you'll find everything from Italian classics like Pasta Carbonara to Asian noodle dishes like chicken ramen. Find recipes, tips and techniques for cooking with pasta from Giada, Ellie and more Food Network chefs. There are two major classifications: pasta fresca (fresh) and pasta secca (dried).
<!--inarticleads2-->
##### Steps to make Pasta:
1. Take a pan
1. Add oil in it
1. Add onion and saute well
1. Add tomato and saute well
1. Add spices and mix well
1. Add red sauce and mix well
1. Add pasta and mix well
1. Serve hot with bread
Each of these pastas creates its own unique dining experience when properly served. En meşhur pastanelere fark atmanızı sağlayacak birbirinden lezzetli pasta tarifleri ile özel günlerinizi canlandırmaya hazırlanın. Stock up on bulk dry pasta for your restaurant - spaghetti, penne, macaroni, angel hair & more! Tuna Pasta Alfredo is a good dish to make at this time. It is quick and easy to cook, and the ingredients are easy to source.
So that is going to wrap this up with this special food pasta recipe. Thanks so much for reading. I'm sure you can make this at home. There's gonna be more interesting food at home recipes coming up. Don't forget to bookmark this page on your browser, and share it to your loved ones, colleague and friends. Thanks again for reading. Go on get cooking!
|
C++
|
UTF-8
| 547 | 3.640625 | 4 |
[] |
no_license
|
//wap to create array 10 elements accept 10 no. from the user and store it in an array
//then accept a no. from the user to search in an array.(linear search)
#include<stdio.h>
int main()
{
int num[10];
int cnt,notosearch;
for(cnt=0;cnt<10;cnt++)
{
printf("\n Enter any number : ");
scanf("%d",&num[cnt]);
}
printf("\n Enter number to search :");
scanf("%d",¬osearch);
for(cnt=0;cnt<10;cnt++)
{
printf("\n number %d is at position : %d",notosearch,cnt);
break;
}
if(cnt==9)
{
printf("\n number is not in an array ");
}
}
|
Ruby
|
UTF-8
| 947 | 4.4375 | 4 |
[] |
no_license
|
=begin
Exercise 5: Majority Element
Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊ n/2 ⌋ times.
Given assumption:
1) the array is non-empty
2) the majority element always exist in the array ( size of array >2 )
# @param {Integer[]} nums
# @return {Integer}
=end
def majority_element(nums)
table = {}
nums.each do |n| # to create a table of keys, values for each unique num in array
if table.key?(n)
table[n] += 1 #if key already exist in the table, increase its value by 1
else
table[n] = 1 #initialise a new key value
end
end
return table.key(table.values.max) #using the max value in the table to find its respective key
end
#Test conditions
p majority_element([1,1,2]) #return 1
p majority_element([0,0,2]) #return 0
p majority_element([1,1,2,3]) #return 1
p majority_element([11,11,2,3]) #return 11
p majority_element([11,11,-2,-2,-2,3]) #return -2
|
Java
|
UTF-8
| 1,323 | 1.617188 | 2 |
[
"BSD-3-Clause"
] |
permissive
|
// Part of Measurement Kit <https://measurement-kit.github.io/>.
// Measurement Kit is free software under the BSD license. See AUTHORS
// and LICENSE for more information on the copying conditions.
package io.ooni.libndt.api;
import io.ooni.libndt.swig.Libndt;
public final class NDTConstants {
public static final long versionMajor = Libndt.getVersionMajor();
public static final long versionMinor = Libndt.getVersionMinor();
public static final long versionPatch = Libndt.getVersionPatch();
public static final short nettestFlagUpload = Libndt.getNettestFlagUpload();
public static final short nettestFlagDownload = Libndt.getNettestFlagDownload();
public static final short nettestFlagDownloadExt = Libndt.getNettestFlagDownloadExt();
public static final long verbosityQuiet = Libndt.getVerbosityQuiet();
public static final long verbosityWarning = Libndt.getVerbosityWarning();
public static final long verbosityInfo = Libndt.getVerbosityInfo();
public static final long verbosityDebug = Libndt.getVerbosityDebug();
public static final long protocolFlagJSON = Libndt.getProtocolFlagJson();
public static final long protocolFlagTLS = Libndt.getProtocolFlagTls();
public static final long protocolFlagWebSockets = Libndt.getProtocolFlagWebsockets();
}
|
C
|
UTF-8
| 3,899 | 3.09375 | 3 |
[] |
no_license
|
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
void encrypt(char *a)
{
int l=strlen(a);int i=0;
while(*a!='\0')
{
if(i%2==0)
*a+=2*(l/2-i);
else
*a+=3*(l/2-i);
if(*a==',')
*a='!';
a++;i++;
}
}
void decrypt(char *a){
int l=strlen(a);int i=0;
while(*a!='\0'){
if(*a=='!')
*a=',';
if(i%2==0)
*a-=2*(l/2-i);
else
*a-=3*(l/2-i);
a++;i++;
}
}
int check_user(char user[]){
FILE* fp = fopen("user.csv", "r");
if (!fp)printf("File Empty\n");
else{
char buffer[1024];
int row = 0,column=0;
while (fgets(buffer,1024, fp)) {
column = 0;
row++;
if (row == 1)continue;
char* value = strtok(buffer, ",");
while (value){
if (column == 0&&strcmp(user,value)==0)return 1;
else break;
value = strtok(NULL, ",");
column++;
}
}
fclose(fp);
}
return 0;
}
int signup(char username[32],char password[12],char repass[12]){
if(check_user(username)){
printf("Username has already been taken!");
return 0;
}
if(strlen(password)<8){
printf("Enter a password greater than 8 characters!\n");
return 1;
}
if(strcmp(repass,password)==0){
FILE* fp = fopen("user.csv", "a");
if (!fp){
printf("Can't open file\n");
return 2;
}else{
encrypt(password);
fprintf(fp, "%s,%s\n", username, password);
// printf("\nNew Account added to record\n");
fclose(fp);
return 3;
}
}else{
printf("Re-entered password doesn't work, please try again!");
return 4;
}
}
int login_checker(char username[],char pass[])
{
FILE* fp = fopen("user.csv", "r");
if (!fp)
{
printf("File is empty!!\n");
return 0;
}
else
{
char buffer[1024];
int row = 0,column=0;
while (fgets(buffer,1024, fp))
{
column = 0;
row++;
if (row == 1)continue;
char* value = strtok(buffer, ", ");
while (value)
{
if (column == 0 && strcmp(username,value)==0)
{
value = strtok(NULL, ", ");
strcpy(pass,value);
return 1;
}
value = strtok(NULL, ", ");
}
}
fclose(fp);
}
return 0;
}
int login(char username[20], char password[12]){
char pass[12];
if(!login_checker(username,pass))
{
return 1;
}
decrypt(pass);
for(int i=0;i<strlen(pass)-1;i++)
{
if(strlen(pass)-1!=strlen(password))
{
printf("Enter valid password!\n");
return 2;
}
if(password[i]!=pass[i])
{
printf("Enter valid password!\n");
return 2;
}
}
return 0;
}
/*
int main()
{
printf("------Welcome to PES's bank simulator------- \n (1)Login \n (2)Sign up\nEnter 1 or 2 respectfully\n");
int a;
while(1)
{
scanf("%d",&a);
if(a==1)
{
printf("You will be directed to the login page.....");
break;
}
else if(a==2)
{
printf("You will be directed to the sign up page.....");
break;
}
else
{
printf("Enter your choice again as a 1 or 2\n");
}
}
if(a==1){
login();}
else {
signup();
login();}
return 0;
}
*/
|
PHP
|
UTF-8
| 2,761 | 2.890625 | 3 |
[] |
no_license
|
<?php
/**
* LoginForm class.
* LoginForm is the data structure for keeping
* user login form data. It is used by the 'login' action of 'SiteController'.
*/
class LoginForm extends CFormModel {
public $username;
public $password;
/**
*
* @var UserIdentity usuario para autenticacion
*/
private $_identity;
/**
*
* @var string url desde donde se ingresa al login
*/
public $urlReferrer;
/**
* Declares the validation rules.
* The rules state that username and password are required,
* and password needs to be authenticated.
*/
public function rules() {
return array(
// username and password are required
array('username, password', 'required', 'message' => '{attribute} no puede estar vacío'),
///array('urlReferrer', 'safe'),
array('password', 'authenticate'),
);
}
/**
* Declares attribute labels.
*/
public function attributeLabels() {
return array(
'username' => 'Cédula',
'password' => 'Contraseña',
);
}
/**
* Authenticates the password.
* This is the 'authenticate' validator as declared in rules().
*/
public function authenticate($attribute, $params) {
if (!$this->hasErrors()) {
$this->_identity = new UserIdentity($this->username, $this->password);
$this->_identity->authenticate();
switch ($this->_identity->errorCode) {
case UserIdentity::ERROR_NONE:
Yii::app()->user->login($this->_identity);
break;
case UserIdentity::ERROR_USERNAME_INVALID:
$this->addError('username', 'Usuario incorrecto');
break;
case UserIdentity::ERROR_USER_INACTIVE:
$this->addError('username', 'Usuario inactivo');
break;
case UserIdentity::ERROR_PASSWORD_INVALID:
$this->addError('password', 'Contraseña incorrecta');
break;
case UserIdentity::ERROR_USER_ACCESS:
$this->addError('username', 'Error al registrar acceso a usuario');
break;
case UserIdentity::ERROR_USER_VALIDATE:
$this->addError('username', 'Error de validación para efectuar autenticación');
break;
default:
$this->addError('password', 'Usuario o contraseñ incorrecta');
break;
}
}
}
}
|
Java
|
UTF-8
| 1,012 | 3.296875 | 3 |
[] |
no_license
|
package com.ymt.design.strategy;
import java.util.ArrayList;
/**
* @Description TODO
* @Author yangmingtian
* @Date 2019/3/15
*/
class Customer {
private final ArrayList<Integer> cloths = new ArrayList<>();
private PayStrategy payStrategy;
Customer(PayStrategy payStrategy) {
this.payStrategy = payStrategy;
}
/**
* 描述
*
* @return void
* @params [price, quantity]
* @author yangmingtian
*/
void add(int price, int quantity) {
this.cloths.add(this.payStrategy.getPrice(price * quantity));
}
/**
* 描述
*
* @return void
* @params []
* @author yangmingtian
*/
void printPay() {
System.out.println("Total:" + this.cloths.stream().mapToInt(value -> value).sum());
}
/**
* 描述
*
* @return void
* @params [payStrategy]
* @author yangmingtian
*/
void setStrategy(PayStrategy payStrategy) {
this.payStrategy = payStrategy;
}
}
|
Java
|
UTF-8
| 835 | 3.59375 | 4 |
[
"MIT"
] |
permissive
|
package nperfeitos;
public class Main {
public static void main(String[] args) {
boolean divisivel;
long a = 2L, b = 2L, n = 0L, soma;
System.out.printf("\n-> The perfect numbers between 1 and 9223372036854775807 are:\n");
for (long i = 2L; i <= 9223372036854775807L; i++) {
soma = 0L;
// Esse for é o for dos divisores
for (long j = 1L; j < i / 2; j++) {
a = i;
b = j;
// Esse for executa a divisão
for (long res = 0L; a > 0L; res++) {
a = a - b;
}
// Se for igual a zero recebe true
if (a == 0L) {
soma = soma + b;
}
}
System.out.println();
System.out.println(i);
System.out.println();
if (soma == i) {
System.out.printf("\nYeah, it's true! I found that %d is a perfect number!", i);
}
}
}
}
|
Markdown
|
UTF-8
| 5,015 | 2.859375 | 3 |
[
"Apache-2.0"
] |
permissive
|
# Private Comparison
Private Comparision library (prv_cmp) compare the magnitudes of 1-bit integers x and y while encrypting them.

* Decryptor only obtains numerical comparison results without knowing x and y
* Encryptor1 encrypts the integer x (Enc(x)) and sends it to Evaluator
* Encryptor2 encrypts the integer x (Enc(y)) and sends it to Evaluator
* Evaluator performs a magnitude comparison operation on Enc (x) and Enc (y) in an encrypted state, and sends the result (Enc(x<=y {0,1})) to Decryptor
# Prerequisites
* Linux (Cent OS 7.3, Ubuntu LTS 16.04)
* gcc7 (g++ 7) or higher
* cmake 3.5
* PALISADE version 1.2
* doxygen (to generate documentation)
* xterm (to run demo app using `demo.sh`)
# How to build
1. Build and install [PALISADE](https://gitlab.com/palisade/palisade-release/tree/PALISADE-v1.2) and create symbolic link `~/palisade-release` from installed directory.
2. Run the following commands at the root of prv_cmp.
```sh
$ git submodule update -i
$ mkdir build && cd build
$ cmake ..
$ make
```
the following files generated.
| File | Content |
|:---|:---|
| `build/prvc/prvc_dec/libprvc_dec.so` | Decryptor library |
| `build/prvc/prvc_enc/libprvc_enc.so` | Encryptor library |
| `build/prvc/prvc_eval/libprvc_eval.so` | Evaluator library |
| `build/stdsc/stdsc/libstdsc.so` | stdsc library |
| `demo/dec/dec` | Decryptor demo app |
| `demo/enc/enc` | Encryptor demo app |
| `demo/eval/eval` | Evaluator demo app |
# API Reference
1. Run the following command at the root directory to build the document.
```sh
$ cd doc && doxygen
```
2. see `doc/html/index.html`
# How to run
* Run the following command at the root directory to run demo app.
```sh
$ ./demo.sh
```
* Run the following command at the root directory to run test.
```sh
$ cd test && ./test.sh
```
# Demo App
The demo app consists of four processes: Decryptor, Encryptor1, Encryptor2 and Evaluator. These processes communicate as shown in the following figure.

## Decryptor demo app
* Behavior
* If the `-g` option is specified, Decryptor generates keys. (Fig: (1))
* Decryptor receives the public key request, then returns a public key and context. (Fig: (2))
* Decryptor receives the comparision results (Enc(x<y)), then decrypt it (-> x<y). (Fig: (6,7))
* Usage
```sh
Usage: ./dec [-p pubkey_filename] [-s seckey_filename] [-c context_filename] \
[-e emk_filename] [-a eak_filename] [-t config_filename] [-g]
```
* -p pubkey_filename : file path of public key file (OPTIONAL, Default:"pubkey.txt")
* -s seckey_filename : file path of secret key file (OPTIONAL, Default:"seckey.txt")
* -s context_filename : file path of context key file (OPTIONAL, Default:"context.txt")
* -s emk_filename : file path of eval multi key file (OPTIONAL, Default:"emk.txt")
* -s eak_filename : file path of eval automorphism key file (OPTIONAL, Default:"eak.txt")
* -t config_filename : file path of configuration file (OPTINAL)
* -g : generates FHE keys if this option is specified (OPTINAL)
* Configuration
* Specify the following PALISADE parameters in the configuration file.
```
mul_depth = 4 (Default: 4)
logN = 13 (Default: 13)
bit_len = 30 (Default: 30)
dcrt_bits = 60 (Default: 60)
rel_window = 0 (Default: 0)
sigma = 3.2 (Default: 3.2)
```
* State Transition Diagram
* 
## Evaluator demo app
* Behavior
* Evaluator sends the evk request to Decryptor, then receives the evk. (Fig: (2))
* Evaluator receives the encrypted data (Enc(x), (y)) from Encryptor, then compute comparision and send results to Decryptor. (Fig: (4,5,6))
* Usage
```sh
Usage: ./eval
```
* State Transition Diagram
* 
## Encryptor demo app
* Behavior
* Encryptor sends the public key request to Decryptor, then receives the public key. (Fig: (2))
* Encryptor encrypts the input value, then sends encrypted data to Evaluator. (Fig: (3)(4))
* Usage
```sh
Usage: ./client [-t is_neg] <value>
```
* -t is_neg : boolean (0: false, 1: true) of mononical coefficient (OPTIONAL, Default:0)
* <value> : input value
# License
Copyright 2018 Yamana Laboratory, Waseda University
Supported by JST CREST Grant Number JPMJCR1503, Japan.
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.
|
Ruby
|
UTF-8
| 3,549 | 3.140625 | 3 |
[] |
no_license
|
# Removes HTML, newlines and unneeded whitespace
# Whitespace removal from SO 7106964
def strip_html(text)
@name =
# Remove HTML from the text
Sanitize.clean(text).
# Replace newlines with a space
gsub(/\n|\r/, ' ').
# Replaces runs of spaces by a single space
squeeze(' ').
# Remove leading and trailing whitespace
strip
end
# Calls open on the passed URL, but caches the result
def cache_open(url)
Cachy.cache(url, hash_key: true) { open(url).read }
end
# Returns a cleaner version of a bill title
# Used for giving bills a unique ID.
def clean_title(title)
title.
# Take the part of the title before Bill, Act or -
split(/Bill|Act|-/, 2)[0].
# Remove any brackets
gsub(/\([a-zA-Z.\d\s'",]*\)/, '').
# Strip any trailing whitespace
rstrip
end
# Returns a cleaner version of a bill title, but doesn't split at hyphens.
# Used for comparing bills from different data sources.
def alternate_clean_title(title)
title.
# Take the part of the title before Bill or Act
split(/Bill|Act/, 2)[0].
# Remove any brackets
gsub(/\([a-zA-Z.\s\d'",-]*\)/, '').
# Strip any trailing whitespace
rstrip
end
# Return the record, with only the keys passed in the hash
# If a passed key isn't in the hash and it's in a preset list, that method is called on the hash
def select_keys(record, keys)
new_record = {}
keys.each do |key|
# If it's safe to call the key method on record
if %w{score humanized_slug large_photo date}.include? key
new_record[key] = record.send(key)
elsif record.respond_to? key
new_record[key] = record[key]
end
end
return new_record
end
# Cleans a bill title and turns it into a machine-readable slug
# Copied from SO 1302022
def generate_slug(title)
title = clean_title title
# Strip the string
ret = title.downcase.strip
# Blow away apostrophes
ret.gsub! /['`]/,""
# @ --> at, and & --> and
ret.gsub! /\s*@\s*/, " at "
ret.gsub! /\s*&\s*/, " and "
# Replace all non alphanumeric, underscore or periods with underscore
ret.gsub! /\s*[^A-Za-z0-9\.\-]\s*/, '_'
# Convert double underscores to single
ret.gsub! /_+/,"_"
# Strip off leading/trailing underscore
ret.gsub! /\A[_\.]+|[_\.]+\z/,""
ret
end
# Returns a symbol indicating whether the title is of a bill or act
def bill_or_act(title)
return :act if title.include? "Act"
:bill
end
# Return the last date for a bill given it's documents and events
def gen_date(documents, events)
today = Date.today
dates = (documents + events).map { |doc|
# For each item, parse it's last value into a date
begin
Date.parse doc.last
rescue
nil
end
# Reject any dates that are nil
# Select those dates that are before today (have already happened)
}.reject { |date| date.nil? }.select { |date| date <= today }.reverse
# Choose the most recent date
dates.last
end
# Returns the lat and lng of a constituency. Cached.
def constituency_loc(constituency)
Cachy.cache("const" + constituency, hash_key: true) {constituency_loc_real constituency }
end
# Returns the lat and lng of a constituency given it's name
def constituency_loc_real(constituency)
begin
# Use the TWFY API to get the data
location = TWFY_CLIENT.geometry name: constituency
{lat: location.centre_lat, lng: location.centre_lon}
rescue
# Return (0,0) in case of failure
{lat: 0, lng: 0}
end
end
# Turn aye/naye into for/against
def humanify_vote(vote)
return "for" if vote == "aye"
"against"
end
|
Python
|
UTF-8
| 1,682 | 3.46875 | 3 |
[] |
no_license
|
from golca import gameOfLife
from golca2 import *
from golca3 import *
from golca4 import *
def genericDriver():
try:
str1 = "Enter 1 for general linear algebra test,\n 2 for special linear"
str2 = " algebra test,\n 3 for orthogonal algebra test,\n and 4 for"
str3 = " symplectic algebra test! "
p = int(input(str1+str2+str3))
except: return
if p <= 0 and p>=5:
print("Sorry! Please try again later!")
return
else:
try: n = int(input("Enter the size of the grid! "))
except: return
if p == 1: grid, backEnd = createGLgrid(n)
elif p == 2: grid, backEnd = createSLgrid(n)
elif p == 3: grid, backEnd = createSOgrid(n)
elif p == 4: grid, backEnd = createSPgrid(n)
t = int(input("Enter the number of steps! "))
gameOfLife(grid,backEnd,t)
r1 = checkSLgrid(grid)
r2 = checkSOgrid(grid)
r3 = checkSPgrid(grid)
if p == 1: print("Initially the grid is of general linear algebra.")
elif p == 2: print("Initially the grid is of special linear algebra.")
elif p == 3: print("Initially the grid is of orthogonal algebra.")
elif p == 4: print("Initially the grid is of symplectic algebra.")
if r3: print("Finally the grid is of symplectic algebra!")
elif r2: print("Finally the grid is of orthogonal algebra!")
elif r1: print("Finally the grid is of special linear algebra!")
else: print("Finally the grid is of general linear algebra!")
while True:
genericDriver()
try:
msg = input("Do you want to continue? ").lower()
except: break
if msg != 'yes': break
|
Markdown
|
UTF-8
| 1,022 | 3.140625 | 3 |
[] |
no_license
|
# Kaggle_Mercari_competition
This repository contains the solution developed for the Kaggle Mercari competition that finished 46th on Private Leaderboard.
# Solution hardware requirements
This solution was designed to run in a hardware constrained environment (Kaggle's kernels) with the following constraints:
* 4 CPU cores
* 16 GB RAM
* 1 GB disk space
The solution takes 1 hour to run on the Kaggle environment for the first test set (Public Leaderboard) and takes 1 hour and 33 minutes for the second test set (Private Leaderboard).
# How to run the code
1. Make sure you have Python 3.6 installed and all required packages installed. You can install the packages using the following command:
```
pip install -r requirements.txt
```
2. Make sure the paths indicated in 'files_paths.py' corresponds to the ones of your system (where the data are stored, where the submission file will be output).
3. Run the file 'LeaderboardScript.py' in a terminal
```
python LeaderboardScript.py
```
4. That's it!
|
C++
|
UTF-8
| 6,683 | 2.59375 | 3 |
[] |
no_license
|
#include "chunk_renderer.hpp"
#include "../../common/world/world.hpp"
#include "../../common/world/world_generator.hpp"
#include "../../common/bounding_box.hpp"
#include "../debug/profiler.hpp"
#include "../constant/rendering.hpp"
#include <glm/gtc/matrix_transform.hpp>
#include <algorithm>
#include <iterator>
#include <random>
namespace rendering {
glm::vec3 get_rgb(uint8_t r, uint8_t g, uint8_t b) {
return {r / 255.f, g / 255.f, b / 255.f};
}
chunk_renderer::chunk_renderer(const world_chunk &chunk) noexcept
: chunk{chunk}, floor_mesh{} {
build();
}
chunk_renderer::chunk_renderer(const world_chunk& chunk, gl::buffer&& vertices, gl::buffer&& colors, gl::buffer&& uvs,
gl::buffer&& svertices, gl::buffer&& scolors, gl::buffer&& suvs) noexcept
: chunk(chunk)
, floor_mesh(std::move(vertices), std::move(uvs), std::move(colors), world::CHUNK_WIDTH * world::CHUNK_DEPTH * 6)
, sites_mesh(std::move(svertices), std::move(suvs), std::move(scolors), world::CHUNK_WIDTH * world::CHUNK_DEPTH * 36){
rebuild_floor_mesh();
rebuild_site_meshes();
}
std::map<int, glm::vec3> chunk_renderer::make_biome_colors() {
// Here we asign a color to a biome
// see https://i.stack.imgur.com/vlvQQ.png for color code
std::map<int, glm::vec3> biome_color;
biome_color[BIOME_SNOW] = get_rgb(255, 255, 255);
biome_color[BIOME_ROCK] = get_rgb(255, 255, 255);
biome_color[BIOME_GRASS] = get_rgb(255, 255, 255);
biome_color[BIOME_DESERT] = get_rgb(255, 255, 255);
biome_color[BIOME_WATER] = get_rgb(255, 255, 255);
return biome_color;
}
std::map<int, std::vector<bounding_box<float>>> make_biome_textures() {
std::map<int, std::vector<bounding_box<float>>> texture_rects;
// left, bottom, right, up
texture_rects[BIOME_SNOW] = {bounding_box<float>{0.50f, 0.00f, 0.75f, 0.25f}};
texture_rects[BIOME_ROCK] = {bounding_box<float>{0.25f, 0.00f, 0.50f, 0.25f},
bounding_box<float>{0.25f, 0.25f, 0.50f, 0.50f}};
texture_rects[BIOME_GRASS] = {bounding_box<float>{0.00f, 0.00f, 0.25f, 0.25f}};
texture_rects[BIOME_DESERT] = {bounding_box<float>{0.75f, 0.00f, 1.00f, 0.25f}};
texture_rects[BIOME_WATER] = {bounding_box<float>{0.00f, 0.25f, 0.25f, 0.50f}};
return texture_rects;
}
rendering::static_mesh_builder<world::CHUNK_WIDTH * world::CHUNK_DEPTH * 6> chunk_renderer::build_floor() {
auto biome_colors = make_biome_colors();
auto biome_textures = make_biome_textures();
std::default_random_engine engine(std::time(NULL));
rendering::static_mesh_builder<world::CHUNK_WIDTH * world::CHUNK_DEPTH * 6> floor_mesh_builder;
for (std::size_t x = 0; x < world::CHUNK_WIDTH; ++x) {
for (std::size_t z = 0; z < world::CHUNK_DEPTH; ++z) {
const int CURRENT_BIOME = chunk.biome_at(x, 0, z);
const float LEFT = x * SQUARE_SIZE;
const float BOTTOM = z * SQUARE_SIZE;
const float RIGHT = LEFT + SQUARE_SIZE;
const float TOP = BOTTOM + SQUARE_SIZE;
const glm::vec3 TILE_COLOR = biome_colors[CURRENT_BIOME];
std::uniform_int_distribution<std::size_t> texture_index_distrib(0,
biome_textures[CURRENT_BIOME].size() - 1);
const bounding_box<float> TILE_TEXTURE = biome_textures[CURRENT_BIOME][texture_index_distrib(engine)];
floor_mesh_builder.add_vertex({LEFT, 0.f, BOTTOM}, {TILE_TEXTURE.left(), TILE_TEXTURE.bottom()},
TILE_COLOR);
floor_mesh_builder.add_vertex({LEFT, 0.f, TOP}, {TILE_TEXTURE.left(), TILE_TEXTURE.top()}, TILE_COLOR);
floor_mesh_builder.add_vertex({RIGHT, 0.f, TOP}, {TILE_TEXTURE.right(), TILE_TEXTURE.top()}, TILE_COLOR);
floor_mesh_builder.add_vertex({LEFT, 0.f, BOTTOM}, {TILE_TEXTURE.left(), TILE_TEXTURE.bottom()},
TILE_COLOR);
floor_mesh_builder.add_vertex({RIGHT, 0.f, TOP}, {TILE_TEXTURE.right(), TILE_TEXTURE.top()}, TILE_COLOR);
floor_mesh_builder.add_vertex({RIGHT, 0.f, BOTTOM}, {TILE_TEXTURE.right(), TILE_TEXTURE.bottom()},
TILE_COLOR);
}
}
return floor_mesh_builder;
}
void chunk_renderer::build_floor_mesh() noexcept {
floor_mesh = build_floor().build();
}
void chunk_renderer::rebuild_floor_mesh() noexcept {
build_floor().rebuild(floor_mesh);
}
glm::vec3 get_site_color(int type) {
switch (type) {
case SITE_MAGIC_ESSENCE:
return get_rgb(59, 41, 89);
case SITE_BERRY:
return get_rgb(194, 127, 169);
case SITE_TREE:
return get_rgb(97, 58, 21);
case SITE_DEER:
return get_rgb(255, 96, 28);
case SITE_STONE:
return get_rgb(40, 15, 50);
case SITE_GOLD:
return get_rgb(246, 181, 6);
case SITE_FISH:
return get_rgb(191, 0, 84);
default:
return get_rgb(0, 0, 0);
}
}
rendering::static_mesh_builder<world::CHUNK_WIDTH * world::CHUNK_DEPTH * 36> chunk_renderer::build_sites() {
const float SITE_SIZE = SQUARE_SIZE * 0.5f;
rendering::static_mesh_builder<world::CHUNK_WIDTH * world::CHUNK_DEPTH * 36> sites_builder;
for (std::size_t x = 0; x < world::CHUNK_WIDTH; ++x) {
for (std::size_t z = 0; z < world::CHUNK_DEPTH; ++z) {
auto sites = chunk.sites_at(x, 0, z);
if (sites.size() > 0 && sites.front()->type() != SITE_NOTHING) {
const glm::vec3 SITE_COLOR = get_site_color(sites.front()->type());
rendering::make_cube(sites_builder, SITE_SIZE, SITE_COLOR,
glm::vec3{x * SQUARE_SIZE + (SQUARE_SIZE / 4.f), 0.f,
z * SQUARE_SIZE + (SQUARE_SIZE / 4.f)});
}
}
}
return sites_builder;
}
void chunk_renderer::build_site_meshes() noexcept {
sites_mesh = build_sites().build();
}
void chunk_renderer::rebuild_site_meshes() noexcept {
build_sites().rebuild(sites_mesh);
}
void chunk_renderer::build() noexcept {
build_floor_mesh();
build_site_meshes();
}
void chunk_renderer::render(mesh_rendering_system &renderer, glm::mat4 parent_model) const noexcept {
renderer.emplace(&floor_mesh, parent_model, TEXTURE_TERRAIN, PROGRAM_STANDARD, 0);
renderer.emplace(&sites_mesh, parent_model, TEXTURE_NONE, PROGRAM_STANDARD, 0);
}
const world_chunk& chunk_renderer::displayed_chunk() const {
return chunk;
}
}
|
C++
|
UTF-8
| 270 | 2.578125 | 3 |
[] |
no_license
|
//
// Created by kangdonguk on 2020/05/12.
//
// https://www.acmicpc.net/problem/2744
// 대소문자 바꾸기
#include <stdio.h>
int main() {
char s[101];
scanf("%s", s);
for (int i = 0; s[i]; i++)
printf("%c", s[i] += s[i] > 90 ? -32 : 32);
}
|
PHP
|
UTF-8
| 1,448 | 2.59375 | 3 |
[] |
no_license
|
<?php
namespace App\Modules\Api\Controllers;
use App\Controller\ApiController;
use App\Models\admin\User;
class SingController extends ApiController
{
/**
* 初始化
* @author 一根小腿毛 <1368213727@qq.com>
* @return string
*/
public function initialize()
{
parent::initialize(); // TODO: Change the autogenerated stub
}
/**
* 登录
* @author 一根小腿毛 <1368213727@qq.com>
* @return string
*/
public function loginAction()
{
$data = [];
$data['username'] = $this->request->getPost('username','trim','');
$data['password'] = $this->request->getPost('password','trim','');
$res = service('api/sing')->login($data);
if(!$res->is_success()) $this->error($res->get_message());
$this->success($res->get_data(),'登录成功');
}
/**
* 获取用户头像
* @author 一根小腿毛 <1368213727@qq.com>
* @return string
*/
public function getAvatarAction(){
$data = $this->request->getPost();
if(!isset($data['username'])) $this->error('非法请求~');
$username = trim($data['username']);
$user = User::where(['username'=>$username])->field('avatar,bg')->_find();
if($user){
return $this->success(['avatar'=>get_file_path($user->avatar),"bg"=>$user->bg],'成功');
}else{
return $this->error('找不到这个用户~');
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.