Dataset Viewer (First 5GB)
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
|
---|---|---|---|---|---|---|---|
Python
|
UTF-8
| 986 | 2.65625 | 3 |
[] |
no_license
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Feb 29 20:13:41 2020
@author: rian-van-den-ander
"""
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.ensemble import RandomForestClassifier
df = pd.read_csv('../../data/aita/aita_clean.csv')
X = df['body'].values
y = df['is_asshole'].values
X_train, X_test, y_train, y_test = train_test_split(X,y,test_size=0.2)
vectorizer = CountVectorizer()
vectorizer.fit(X_train.astype('U'))
X_train = vectorizer.transform(X_train.astype('U'))
X_test = vectorizer.transform(X_test.astype('U'))
classifier = RandomForestClassifier()
classifier.fit(X_train, y_train)
score = classifier.score(X_test, y_test)
print("Accuracy:", score) #72%
n=20
feature_names = vectorizer.get_feature_names()
coefs_with_fns = sorted(zip(classifier.feature_importances_, feature_names))
coefs_with_fns = coefs_with_fns[-20:]
print(coefs_with_fns)
|
Python
|
UTF-8
| 1,359 | 3.671875 | 4 |
[] |
no_license
|
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 14 01:52:14 2020
@author: Sourabh
"""
import pandas as pd
file=r'C:\Users\mahesh\Desktop\Python Assign\Data.csv'
df=pd.read_csv(file)
print(df)
print("----------------------------------------------------")
#Find Male Employee
print("MALE EMPLOYEE")
male = df.loc[(df['Gender']=='M')].Name
print(male)
print("----------------------------------------------------")
#Find Female Employee
print("FEMALE EMPLOYEE")
female = df.loc[(df['Gender']=='F')].Name
print(female)
print("----------------------------------------------------")
# find Male emp with miminum sal
print("Male emp with miminum sal")
print(df.loc[(df.Salary==min(df.Salary))&(df['Gender']=='M')])
print("----------------------------------------------------")
# find Female emp with Maximum sal
print("Female emp with Maximum sal")
print(df.loc[(df.Salary==max(df.Salary))&(df['Gender']=='F')])
print("----------------------------------------------------")
# find emp with Same location
print("Same Loaction")
print(df[df.duplicated('Location')])
print("-----------------------------------------------------")
# find emp with same salary
print("Same Salary")
print(df[df.duplicated('Salary')])
print("----------------------------------------------------")
# find emp with same name
print("Same Name")
print(df[df.duplicated('Name')])
|
Java
|
UTF-8
| 1,395 | 3.515625 | 4 |
[] |
no_license
|
package com.pigcanfly.leetcoding.s442;
import java.util.ArrayList;
import java.util.List;
/**
* @author tobbyquinn
* @date 2019/11/29
*/
public class FindAllDuplicatesinanArray {
public List<Integer> findDuplicates(int[] nums) {
int left = 0;
while (left < nums.length) {
if (nums[left] != left + 1) {
int curr = nums[left];
if (nums[curr - 1] == curr) {
left++;
} else {
nums[left] = nums[curr - 1];
nums[curr - 1] = curr;
}
} else {
left++;
}
}
ArrayList<Integer> res = new ArrayList<>();
for (int i = 0; i < nums.length; i++) {
if (nums[i] != i + 1) {
res.add(nums[i]);
}
}
return res;
}
// when find a number i, flip the number at position i-1 to negative.
// if the number at position i-1 is already negative, i is the number that occurs twice.
public List<Integer> findDuplicates1(int[] nums) {
List<Integer> res = new ArrayList<>();
for (int i = 0; i < nums.length; ++i) {
int index = Math.abs(nums[i])-1;
if (nums[index] < 0)
res.add(Math.abs(index+1));
nums[index] = -nums[index];
}
return res;
}
}
|
Java
|
UTF-8
| 1,224 | 2.328125 | 2 |
[] |
no_license
|
package app.core;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import app.core.login.LoginManager;
import app.core.services.TraficService;
@Configuration // if you want bean methods
@ComponentScan // scan classes with @Component
@EnableAspectJAutoProxy // activate AOP proxy
public class SpringApp2Trafic {
public static void main(String[] args) {
try (AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(SpringApp2Trafic.class)) {
LoginManager lm = ctx.getBean(LoginManager.class);
lm.login("name", "password");
TraficService traficService = ctx.getBean(TraficService.class);
System.out.println(traficService.getClass());
try {
// String msg = traficService.fetchTraficFoecast();
System.out.println(traficService.fetchTraficFoecast());
} catch (Exception e) {
System.out.println(e);
}
System.out.println("#################");
traficService.fetchTraficFoecastAnnotated();
System.out.println("END");
}
}
}
|
TypeScript
|
UTF-8
| 8,240 | 3.609375 | 4 |
[] |
no_license
|
import * as _ from "lodash";
export class StringPoc {
public test() {
this.camelCaseFunc();
}
public camelCaseFunc() {
_.camelCase("Foo Bar");
// => 'fooBar'
_.camelCase("--foo-bar--");
// => 'fooBar'
_.camelCase("__FOO_BAR__");
// => 'fooBar'
_.capitalize("FRED");
// => 'Fred'
_.deburr("déjà vu");
// => 'deja vu'
_.endsWith("abc", "c");
// => true
_.endsWith("abc", "b");
// => false
_.endsWith("abc", "b", 2);
// => true
_.escape("fred, barney, & pebbles");
// => 'fred, barney, & pebbles'
_.escapeRegExp("[lodash](https://lodash.com/)");
// => '\[lodash\]\(https://lodash\.com/\)'
_.kebabCase("Foo Bar");
// => 'foo-bar'
_.kebabCase("fooBar");
// => 'foo-bar'
_.kebabCase("__FOO_BAR__");
// => 'foo-bar'
_.lowerCase("--Foo-Bar--");
// => 'foo bar'
_.lowerCase("fooBar");
// => 'foo bar'
_.lowerCase("__FOO_BAR__");
// => 'foo bar'
_.lowerFirst("Fred");
// => 'fred'
_.lowerFirst("FRED");
// => 'fRED'
_.pad("abc", 8);
// => ' abc '
_.pad("abc", 8, "_-");
// => '_-abc_-_'
_.pad("abc", 3);
// => 'abc'
_.padEnd("abc", 6);
// => 'abc '
_.padEnd("abc", 6, "_-");
// => 'abc_-_'
_.padEnd("abc", 3);
// => 'abc'
_.padStart("abc", 6);
// => ' abc'
_.padStart("abc", 6, "_-");
// => '_-_abc'
_.padStart("abc", 3);
// => 'abc'
_.parseInt("08");
// => 8
_.map(["6", "08", "10"], _.parseInt);
// => [6, 8, 10]
}
public repeatFunc() {
_.repeat("*", 3);
// => '***'
_.repeat("abc", 2);
// => 'abcabc'
_.repeat("abc", 0);
// => ''
_.replace("Hi Fred", "Fred", "Barney");
// => 'Hi Barney'
_.snakeCase("Foo Bar");
// => 'foo_bar'
_.snakeCase("fooBar");
// => 'foo_bar'
_.snakeCase("--FOO-BAR--");
// => 'foo_bar'
_.split("a-b-c", "-", 2);
// => ['a', 'b']
_.startCase("--foo-bar--");
// => 'Foo Bar'
_.startCase("fooBar");
// => 'Foo Bar'
_.startCase("__FOO_BAR__");
// => 'FOO BAR'
_.startsWith("abc", "a");
// => true
_.startsWith("abc", "b");
// => false
_.startsWith("abc", "b", 1);
// => true
}
public templateFunc() {
// Use the "interpolate" delimiter to create a compiled template.
let compiled = _.template("hello <%= user %>!");
compiled({ user: "fred" });
// => 'hello fred!'
// Use the HTML "escape" delimiter to escape data property values.
compiled = _.template("<b><%- value %></b>");
compiled({ value: "<script>" });
// => '<b><script></b>'
// Use the "evaluate" delimiter to execute JavaScript and generate HTML.
compiled = _.template("<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>");
compiled({ users: ["fred", "barney"] });
// => '<li>fred</li><li>barney</li>'
// Use the internal `print` function in "evaluate" delimiters.
compiled = _.template('<% print("hello " + user); %>!');
compiled({ user: "barney" });
// => 'hello barney!'
// Use the ES template literal delimiter as an "interpolate" delimiter.
// Disable support by replacing the "interpolate" delimiter.
compiled = _.template("hello ${ user }!");
compiled({ user: "pebbles" });
// => 'hello pebbles!'
// Use backslashes to treat delimiters as plain text.
compiled = _.template('<%= "\\<%- value %\\>" %>');
compiled({ value: "ignored" });
// => '<%- value %>'
// // Use the `imports` option to import `jQuery` as `jq`.
// const text = "<% jq.each(users, function(user) { %><li><%- user %></li><% }); %>";
// compiled = _.template(text, { imports: { jq: jQuery } });
// compiled({ users: ["fred", "barney"] });
// // => '<li>fred</li><li>barney</li>'
// // Use the `sourceURL` option to specify a custom sourceURL for the template.
// compiled = _.template("hello <%= user %>!", { sourceURL: "/basic/greeting.jst" });
// compiled(data);
// // => Find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector.
// // Use the `variable` option to ensure a with-statement isn't used in the compiled template.
// compiled = _.template("hi <%= data.user %>!", { variable: "data" });
// compiled.source;
// // => function(data) {
// // var __t, __p = '';
// // __p += 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '!';
// // return __p;
// // }
// Use custom template delimiters.
_.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
compiled = _.template("hello {{ user }}!");
compiled({ user: "mustache" });
// => 'hello mustache!'
// Use the `source` property to inline compiled templates for meaningful
// line numbers in error messages and stack traces.
// fs.writeFileSync(path.join(process.cwd(), "jst.js"), '\
// var JST = {\
// "main": ' + _.template(mainText).source + "\
// };\
// ");
}
public toLowerFunc() {
_.toLower("--Foo-Bar--");
// => '--foo-bar--'
_.toLower("fooBar");
// => 'foobar'
_.toLower("__FOO_BAR__");
// => '__foo_bar__'
_.toUpper("--foo-bar--");
// => '--FOO-BAR--'
_.toUpper("fooBar");
// => 'FOOBAR'
_.toUpper("__foo_bar__");
// => '__FOO_BAR__'
_.trim(" abc ");
// => 'abc'
_.trim("-_-abc-_-", "_-");
// => 'abc'
_.map([" foo ", " bar "], _.trim);
// => ['foo', 'bar']
_.trimEnd(" abc ");
// => ' abc'
_.trimEnd("-_-abc-_-", "_-");
// => '-_-abc'
_.trimStart(" abc ");
// => 'abc '
_.trimStart("-_-abc-_-", "_-");
// => 'abc-_-'
_.truncate("hi-diddly-ho there, neighborino");
// => 'hi-diddly-ho there, neighbo...'
_.truncate("hi-diddly-ho there, neighborino", {
length: 24,
separator: " ",
});
// => 'hi-diddly-ho there,...'
_.truncate("hi-diddly-ho there, neighborino", {
length: 24,
separator: /,? +/,
});
// => 'hi-diddly-ho there...'
_.truncate("hi-diddly-ho there, neighborino", {
omission: " [...]",
});
// => 'hi-diddly-ho there, neig [...]'
_.unescape("fred, barney, & pebbles");
// => 'fred, barney, & pebbles'
_.upperCase("--foo-bar");
// => 'FOO BAR'
_.upperCase("fooBar");
// => 'FOO BAR'
_.upperCase("__foo_bar__");
// => 'FOO BAR'
_.upperFirst("fred");
// => 'Fred'
_.upperFirst("FRED");
// => 'FRED'
_.words("fred, barney, & pebbles");
// => ['fred', 'barney', 'pebbles']
_.words("fred, barney, & pebbles", /[^, ]+/g);
// => ['fred', 'barney', '&', 'pebbles']
}
}
|
C#
|
UTF-8
| 2,752 | 2.90625 | 3 |
[
"MIT"
] |
permissive
|
namespace SRF
{
using System.Collections.Generic;
using UnityEngine;
public static class SRFTransformExtensions
{
public static IEnumerable<Transform> GetChildren(this Transform t)
{
var i = 0;
while (i < t.childCount)
{
yield return t.GetChild(i);
++i;
}
}
/// <summary>
/// Reset all local values on a transform to identity
/// </summary>
/// <param name="t"></param>
public static void ResetLocal(this Transform t)
{
t.localPosition = Vector3.zero;
t.localRotation = Quaternion.identity;
t.localScale = Vector3.one;
}
/// <summary>
/// Create an empty child object of this transform
/// </summary>
/// <param name="t"></param>
/// <param name="name"></param>
/// <returns></returns>
public static GameObject CreateChild(this Transform t, string name)
{
var go = new GameObject(name);
go.transform.parent = t;
go.transform.ResetLocal();
go.gameObject.layer = t.gameObject.layer;
return go;
}
/// <summary>
/// Set the parent of this transform, but maintain the localScale, localPosition, localRotation values.
/// </summary>
/// <param name="t"></param>
/// <param name="parent"></param>
public static void SetParentMaintainLocals(this Transform t, Transform parent)
{
t.SetParent(parent, false);
}
/// <summary>
/// Copy local position,rotation,scale from other transform
/// </summary>
/// <param name="t"></param>
/// <param name="from"></param>
public static void SetLocals(this Transform t, Transform from)
{
t.localPosition = from.localPosition;
t.localRotation = from.localRotation;
t.localScale = from.localScale;
}
/// <summary>
/// Set position/rotation to from. Scale is unchanged
/// </summary>
/// <param name="t"></param>
/// <param name="from"></param>
public static void Match(this Transform t, Transform from)
{
t.position = from.position;
t.rotation = from.rotation;
}
/// <summary>
/// Destroy all child game objects
/// </summary>
/// <param name="t"></param>
public static void DestroyChildren(this Transform t)
{
foreach (var child in t)
{
Object.Destroy(((Transform) child).gameObject);
}
}
}
}
|
C++
|
UTF-8
| 1,815 | 3.1875 | 3 |
[] |
no_license
|
#ifndef _COMPUTER_HPP
#define _COMPUTER_HPP
#include "player.hpp"
class Computer : public Player
{
public:
int x;
int y;
int xPiece;
int yPiece;
bool makeMove(int x, int y, Board* board){return false;}
bool select(int x, int y, Board* board){return false;}
void makeMove(std::vector<Piece*> piece, Board *board)
{
std::vector<std::vector<int>> posMove;
Piece *tmpPiece;
//get the pieces
int x = std::rand() % (piece.size());
posMove = board->possibleMoves(piece[x]);
while(posMove.empty()){
int x = std::rand() % (piece.size());
posMove = board->possibleMoves(piece[x]);
}
tmpPiece = piece[x];
int randCord = std::rand()%(posMove.size());
std::vector<int> destination = posMove[randCord];
tmpPiece->setPostion(destination[0], destination[1]);
board->movePiece(*tmpPiece);
}
//generate the random move
std::vector<Piece *> selectValidPieces(Board *board)
{
/*
After called
go through board and select the invalid pieces
in this case black and return a piece vector
then generate rando
*/
std::vector<Piece *> validPieces;
for (int i = 0; i < board->grids.size(); i++)
{
for (int j = 0; j < board->grids[i].size(); j++)
{
if(board->grids[i][j]->getPiece()!= nullptr)
{
if (board->grids[i][j]->getPiece()->getColor() == false)
validPieces.push_back(board->grids[i][j]->getPiece());
}
}
}
return validPieces;
}
};
#endif //_COMPUTER_HPP
|
Java
|
UTF-8
| 511 | 3.578125 | 4 |
[] |
no_license
|
package objects_classes_methods.labs;
import java.awt.*;
/**
* Objects, Classes and Methods Exercise 4:
*
* Demonstrate method overloading with at least three overloaded methods.
*
*/
class Overload{
public void makePost(String text){
//Makes a post containing only text.
}
public void makePost(Image image){
//Makes a post containing only an image.
}
public void makePost(String text, Image image){
//Makes a post containing both text and an image.
}
}
|
C++
|
UTF-8
| 2,056 | 2.765625 | 3 |
[] |
no_license
|
#include <algorithm>
#include "truck.h"
#include "MPRNG.h"
#include <iostream>
using namespace std;
extern MPRNG mprng;
Truck::Truck( Printer & prt, NameServer & nameServer, BottlingPlant & plant, unsigned int numVendingMachines, unsigned int maxStockPerFlavour ) :
printer(prt),
nameServer(nameServer),
plant(plant),
numVendingMachines(numVendingMachines),
maxStockPerFlavour(maxStockPerFlavour) {}
void Truck::main() {
printer.print(Printer::Truck, 'S');
VendingMachine **machines = nameServer.getMachineList();
unsigned int lastMachineIndex = -1; // last machine the truck restocked
unsigned int cargo[4]; // cargo for shipment
for (;;) {
yield(mprng(1, 10)); // coffee
try {
plant.getShipment(cargo);
} catch (BottlingPlant::Shutdown) {
break;
}
unsigned int total = 0;
for (unsigned int i = 0; i < 4; ++i) {
total += cargo[i];
}
printer.print(Printer::Truck, 'P', total);
for (unsigned int i = 0; i < numVendingMachines; ++i) {
if (total == 0) break;
lastMachineIndex = (lastMachineIndex + 1) % numVendingMachines; // next machine
unsigned int *inventory = machines[lastMachineIndex]->inventory(); // restock start
printer.print(Printer::Truck, 'd', lastMachineIndex, total);
unsigned int missing = 0; // keep track of unreplenished bottles
for (unsigned int f = 0; f <4; ++f) {
unsigned int numRestocked = min(maxStockPerFlavour - inventory[f], cargo[f]);
inventory[f] += numRestocked;
cargo[f] -= numRestocked;
total -= numRestocked;
missing += ( maxStockPerFlavour - inventory[f] );
}
machines[lastMachineIndex]->restocked(); // restock end
if (missing > 0) { // print machines that are not fully stocked
printer.print(Printer::Truck, 'U', lastMachineIndex, missing);
}
printer.print(Printer::Truck, 'D', lastMachineIndex, total);
}
}
printer.print(Printer::Truck, 'F');
}
|
Python
|
UTF-8
| 3,524 | 3.125 | 3 |
[
"MIT"
] |
permissive
|
from abc import ABCMeta, abstractmethod
import numpy as np
class LossFunction:
__metaclass__ = ABCMeta
@abstractmethod
def __init__(self, **kwargs):
pass
@abstractmethod
def loss(self, edges_batch, distance_info):
return 0.
@abstractmethod
def loss_gradient(self, edges_batch, distance_info):
pass
class SmoothEdgePredictor:
def predict(self, d, r, beta):
return 1. / (1 + np.exp((d - r) * float(beta)))
def prediction_gradient_d(self, d, r, beta):
p = self.predict(d, r, beta)
return -np.exp((d - r) * float(beta)) * beta * p ** 2
def prediction_gradient_r(self, d, r, beta):
return -self.prediction_gradient_d(d, r, beta)
class SmoothEdgeLoss(LossFunction):
__metaclass__ = ABCMeta
def __init__(self, binary_edges=False, beta=1.):
self.binary_edges = binary_edges
self.edge_predictor = SmoothEdgePredictor()
self.beta = beta
self.EPS = 1e-15
@abstractmethod
def elementary_loss(self, true, predicted):
"""
Loss in individual object (e.g. (true - predicted)**2 for MSE)
:param true: true value
:param predicted: predicted value
:return: value of loss
"""
return 0.
@abstractmethod
def elementary_loss_gradient(self, true, predicted):
"""
Gradient of loss wrt predicted value (e.g. 2. * (predicted - true) for MSE)
:param true: true value
:param predicted: predicted value
:return: value of gradient
"""
return 0.
def loss(self, edges_batch, distance_info):
r = distance_info['radius']
total_loss = 0.
for e, w, mult in edges_batch:
if self.binary_edges:
w = 1. if w else 0.
d = distance_info['distances'][e]
p = self.edge_predictor.predict(d, r, self.beta)
total_loss += self.elementary_loss(w, p) * mult
return total_loss
def loss_gradient(self, edges_batch, distance_info):
r = distance_info['radius']
grad = None
for e, w, mult in edges_batch:
if self.binary_edges:
w = 1. if w else 0.
if e not in distance_info['distances']:
continue
d = distance_info['distances'][e]
p = self.edge_predictor.predict(d, r, self.beta)
dp = self.edge_predictor.prediction_gradient_d(d, r, self.beta)
dd = distance_info['distance_gradients'][e].toarray()[0]
d_grad = dd * dp * mult * self.elementary_loss_gradient(w, p)
if distance_info['fit_radius']:
d_grad[-1] = self.edge_predictor.prediction_gradient_r(d, r, self.beta) * mult * self.elementary_loss_gradient(w, p)
if grad is None:
grad = d_grad
else:
grad += d_grad
return grad
class MSE(SmoothEdgeLoss):
def elementary_loss(self, true, predicted):
return (predicted - true)**2
def elementary_loss_gradient(self, true, predicted):
return 2.*(predicted - true)
class LogLoss(SmoothEdgeLoss):
def elementary_loss(self, true, predicted):
p = max(self.EPS, predicted)
p = min(p, 1-self.EPS)
return - true * np.log(p) - (1. - true) * np.log(1 - p)
def elementary_loss_gradient(self, true, predicted):
p = max(self.EPS, predicted)
p = min(p, 1 - self.EPS)
return (p - true) / p / (1-p)
|
C#
|
UTF-8
| 451 | 2.84375 | 3 |
[] |
no_license
|
public void UpdateCategory(Category category)
{
using (var Context = new AppDbContext())
{
Context.Entry(category).State = System.Data.Entity.EntityState.Modified;
Context.SaveChanges();
}
}
-> you use two different `DbContext`'s together (which can cause problems with change tracking)!
**Solution:**
Try to use DependencyInjection for all `DbContext`'s instead of creating them locally to prevent problems with change tracking.
|
Java
|
UTF-8
| 1,682 | 2.515625 | 3 |
[
"Apache-2.0"
] |
permissive
|
package com.github.TKnudsen.infoVis.view.painters.string;
import com.github.TKnudsen.infoVis.view.frames.SVGFrame;
import com.github.TKnudsen.infoVis.view.frames.SVGFrameTools;
import com.github.TKnudsen.infoVis.view.painters.grid.Grid2DPainterPainter;
import com.github.TKnudsen.infoVis.view.painters.string.StringPainter.VerticalStringAlignment;
import com.github.TKnudsen.infoVis.view.panels.InfoVisChartPanel;
/**
* <p>
* InfoVis
* </p>
*
* <p>
* Copyright: (c) 2018-2019 Juergen Bernard,
* https://github.com/TKnudsen/InfoVis<br>
* </p>
*
* @author Juergen Bernard
* @version 1.01
*/
public class StringPainterTester {
public static void main(String[] args) {
final VerticalStringAlignment va = VerticalStringAlignment.UP;
StringPainter stringPainter1 = new StringPainter("1");
// stringPainter.setHorizontalStringAlignment(HorizontalStringAlignment.LEFT);
stringPainter1.setVerticalOrientation(true);
stringPainter1.setVerticalStringAlignment(va);
StringPainter stringPainter2 = new StringPainter("2");
// stringPainter.setHorizontalStringAlignment(HorizontalStringAlignment.LEFT);
stringPainter2.setVerticalOrientation(true);
stringPainter2.setVerticalStringAlignment(va);
StringPainter[][] painters = new StringPainter[1][2];
painters[0][0] = stringPainter1;
painters[0][1] = stringPainter2;
Grid2DPainterPainter<StringPainter> grid = new Grid2DPainterPainter<>(painters);
grid.setDrawOutline(true);
InfoVisChartPanel panel = new InfoVisChartPanel();
panel.addChartPainter(grid);
SVGFrame frame = SVGFrameTools.dropSVGFrame(panel, "asdf", 300, 200);
frame.isAlwaysOnTop();
}
}
|
TypeScript
|
UTF-8
| 269 | 3.109375 | 3 |
[
"MIT"
] |
permissive
|
function toStringSet(thing: unknown): Set<string> {
const set = new Set<string>();
if (Array.isArray(thing)) {
for (const item of thing) {
if (typeof item === 'string') {
set.add(item);
}
}
}
return set;
}
export { toStringSet };
|
Java
|
UTF-8
| 491 | 2.28125 | 2 |
[
"MIT"
] |
permissive
|
package com.projectx.sdk.user.impl;
public class LoginCredentials {
String login;
String password;
public LoginCredentials() {
}
public LoginCredentials(String login, String password ) {
setLogin( login );
setPassword( password );
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
|
Python
|
UTF-8
| 682 | 4 | 4 |
[] |
no_license
|
# Iterative Apprach
def gcdIter(a, b):
'''
a, b: positive integers
returns: a positive integer, the greatest common divisor of a & b.
'''
# Your code here
min = 0
if a < b:
min = a
max = b
else:
min = b
max = a
for i in range(min,0,-1):
if (max%i == 0 and min%i == 0):
return i
#Recursive Approach
def gcdRecur(a, b):
'''
a, b: positive integers
returns: a positive integer, the greatest common divisor of a & b.
'''
# Your code here
if b == 0:
return a
else:
return gcdRecur(b,a%b)
print(gcdRecur(6,12))
|
C#
|
UTF-8
| 963 | 2.9375 | 3 |
[] |
no_license
|
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;
using System.Linq;
namespace HelloWorldFromDB
{
public class HelloWorldRepositoryContext : DbContext
{
public DbSet<Messages> Messages { get; set; }
public HelloWorldRepositoryContext(DbContextOptions<HelloWorldRepositoryContext> options) : base(options)
{
if (Database.GetPendingMigrations().Any())
{
Database.Migrate();
}
}
public HelloWorldRepositoryContext()
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema("HELLO_WORLD");
modelBuilder.Entity<Messages>().HasKey(i => i.Author);
}
}
public class Messages
{
[Required]
public string Author { get; set; }
[Required]
public string Message { get; set; }
}
}
|
Markdown
|
UTF-8
| 6,897 | 2.609375 | 3 |
[] |
no_license
|
tags: read
title: 《RESTful Web APIs中文版》-目录
### 第1 章 网上冲浪 1
场景1 :广告牌 2
资源和表述 2
可寻址性 3
场景2 :主页 3
短会话(Short Session) 5
自描述消息(self-descriptive message) 5
场景3 :链接 6
标准方法 8
场景4 :表单和重定向 9
应用状态(Application State) 11
资源状态(resource state) 12
连通性(connectedness) 13
与众不同的Web 14
Web API 落后于Web 15
语义挑战 16
### 第2 章 一个简单的API 17
HTTP GET :安全的投注 18
如何读取HTTP 响应 19
JSON 20
Collection+JSON 21
向API 写入数据 23
HTTP POST: 资源是如何生成的 24
由约束带来解放 26
应用语义所产生的语义鸿沟 27
### 第3 章 资源和表述 29
万物皆可为资源 30
表述描述资源状态 30
往来穿梭的表述 31
资源有多重表述 32
HTTP 协议语义(Protocol Semantics) 33
GET 35
DELETE 36
幂等性(Idempotence) 36
POST-to-Append 37
PUT 38
PATCH 39
LINK 和UNLINK 40
HEAD 40
OPTIONS 41
Overloaded POST 41
应该使用哪些方法? 42
### 第4 章 超媒体 45
将HTML 作为超媒体格式 46
URI 模板 49
URI vs URL 50
Link 报头 51
超媒体的作用 52
引导请求 52
对响应做出承诺 54
工作流控制 55
当心冒牌的超媒体! 56
语义挑战:我们该怎么做? 57
### 第5 章 领域特定设计 59
Maze+XML :领域特定设计 60
Maze+XML 是如何工作的 61
链接关系 62
访问链接来改变应用状态 64
迷宫集合 65
Maze+XML 是API 吗? 67
客户端1 :游戏 68
Maze+XML 服务器 72
客户端2 :地图生成器 74
客户端3 :吹牛者 76
客户端做自己想要做的事 77
对标准进行扩展 77
地图生成器的缺陷 80
修复(以及修复后的瑕疵) 81
迷宫的暗喻 83
解决语义鸿沟 83
领域特定设计在哪里? 83
最终的奖赏 84
报头中的超媒体 84
抄袭应用语义 84
如果找不到相关的领域特定设计,不要自己制造 86
API 客户端的种类 86
人类驱动的客户端 86
自动化客户端 87
### 第6 章 集合模式(Collection Pattern) 91
什么是集合? 93
链向子项的集合 93
Collection+JSON 94
子项的表示 95
写入模板(Write Template) 98
搜索模板 99
一个(通用的)集合是如何工作的 100
GET 101
POST-to-Append 101
PUT 和PATCH 101
DELETE 102
分页 102
搜索表单 103
Atom 发布协议(AtomPub) 103
AtomPub 插件标准 105
为什么不是每个人都选择使用AtomPub ? 106
语义挑战:我们应该怎么做? 107
### 第7 章 纯- 超媒体设计 111
为什么是HTML? 111
HTML 的能力 112
超媒体控件 112
应用语义插件 113
微格式 115
hMaze 微格式 116
微数据 118
改变资源状态 119
为表单添加应用语义 121
与超媒体相对是普通媒体 125
HTML 的局限性 126
拯救者HTML5? 127
超文本应用语言 128
Siren 131
语义挑战:我们现在要怎么做? 133
### 第8 章 Profile 135
客户端如何找寻文档? 136
什么是Profile ? 137
链接到Profile 137
Profile 链接关系 137
Profile 媒体类型参数 138
特殊用途的超媒体控件 139
Profile 对协议语义的描述 139
Profile 对应用语义的描述 140
链接关系 141
不安全的链接关系 142
语义描述符 142
XMDP :首个机器可读的Profile 格式 143
ALPS 146
ALPS 的优势 150
ALPS 并不是万金油 152
JSON-LD 153
内嵌的文档 156
总结 158
### 第9 章 API 设计流程 161
两个步骤的设计流程 161
七步骤设计流程 162
第1 步:罗列语义描述符 163
第2 步:画状态图 164
第3 步:调整命名 168
第4 步:选择一种媒体类型 172
第5 步:编写Profile 173
第6 步:实现 174
第7 步:发布 174
实例:You Type It, We Post It 177
罗列语义描述符 177
画状态图 178
调整名称 179
选择一种媒体类型 180
编写Profile 181
设计建议 182
资源是实现的内部细节 182
不要掉入集合陷阱 183
不要从表述格式着手 184
URL 设计并不重要 184
标准名称优于自定义名称 186
设计媒体类型 187
当你的API 改变时 189
为现有API 添加超媒体 194
改进基于XML 的API 195
值不值得? 196
Alice 的第二次探险 196
场景1 :没有意义的表述 196
场景2 :Profile 198
Alice 明白了 200
### 第10 章 超媒体动物园 203
领域特定格式 204
Maze+XML 204
OpenSearch 205
问题细节文档 205
SVG 206
VoiceXML 208
集合模式的格式 210
Collection+JSON 211
Atom 发布协议 211
OData 212
纯超媒体格式 219
HTML 219
HAL 220
Link 报头 222
Location 和Content-Location 报头 222
URL 列表 223
JSON 主文档(Home Documents) 223
Link-Template 报头 224
WADL 225
XLink 226
XForms 227
GeoJSON :一个令人困惑的类型 228
GeoJSON 没有通用的超媒体控件 230
GeoJSON 没有媒体类型 232
从GeoJSON 学习到的经验 233
语义动物园 234
链接关系的IANA 注册表 234
微格式WiKi 235
来自微格式Wiki 的链接关系 236
### 第11 章 API 中的HTTP 241
新HTTP/1.1 规范 242
响应码 242
报头 243
表述选择 243
内容协商(Content Negotiation) 243
超媒体菜单 244
标准URL(Canonical URL) 245
HTTP 性能 246
缓存(Caching) 246
条件GET 请求(Conditional GET) 247
Look-Before-You-Leap 请求 249
压缩 250
部分GET 请求(Partial GET) 250
Pipelining 251
避免更新丢失问题 252
认证 254
WWW-Authenticate 报头和Authorization 报头 255
Basic 认证 255
OAuth 1.0 256
OAuth 1.0 的缺点 259
OAuth 2.0 260
何时不采用OAuth 261
HTTP 扩展 261
PATCH 方法 262
LINK 和UNLINK 方法 262
WebDAV 263
HTTP 2.0 264
### 第12 章 资源描述和Linked Data 267
RDF 268
RDF 将URL 作为URI 对待 270
什么时候使用描述策略 271
资源类型 273
RDF Schema 274
Linked Data 运动 277
JSON-LD 278
将JSON-LD 作为一种表述格式 279
Hydra 280
XRD 家族 285
XRD 和JRD 285
Web 主机元数据文档 286
WebFinger 287
本体动物园(Ontology Zoo) 289
schema.org RDF 289
FOAF 290
vocab.org 290
总结:描述策略生机盎然! 290
### 第13 章 CoAP: 嵌入式系统的REST 293
CoAP 请求 294
CoAP 响应 294
消息种类 295
延迟响应(Delayed Response) 296
多播消息(Multicast Message) 296
CoRE Link Format 297
结论:非HTTP 协议的REST 298
#### 附录A 状态法典 301
#### 附录B HTTP 报头法典 325
#### 附录C 为API 设计者准备的Fielding 论文导读 349
#### 词汇表 365
|
Java
|
UTF-8
| 4,712 | 2.859375 | 3 |
[
"Unlicense"
] |
permissive
|
package training.concurrency.ex_3.cache;
import net.jcip.annotations.ThreadSafe;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;
import static training.concurrency.utils.LogMessageTools.getNameCurrentThread;
/**
* Class is intended to provide lazy-cache which is able to load its value on demand.
* For more details please see to {@link LoadableCache}.
*
* @author Alexey Boznyakov
*/
@ThreadSafe
public class LoadableCacheImpl<V> implements LoadableCache<V> {
/**
* Logger.
*/
private static final Logger log = LogManager.getLogger(LoadableCacheImpl.class);
/**
* Loader.
*/
private final LoadableCache.Loader<V> loader;
/**
* Expiration timeout.
*/
private final long cachedValueExpirationTimeout;
/**
* Internal data structure for caching calculated values.
*/
private final ConcurrentMap<String, LazyLoadingValue<V>> cache = new ConcurrentHashMap<>();
/**
* Constructor.
*
* @param loader loader for loading values
* @param cachedValueExpirationTimeout cached values expiration timeout
* @throws IllegalArgumentException if loader is null or
* if expirationTimeout less or equals zero
*/
public LoadableCacheImpl(final LoadableCache.Loader<V> loader, final long cachedValueExpirationTimeout) {
if (loader == null) {
throw new IllegalArgumentException("Loader is null");
}
this.loader = loader;
if (cachedValueExpirationTimeout <= 0) {
throw new IllegalArgumentException("Expiration timeout should be more than zero.");
}
this.cachedValueExpirationTimeout = cachedValueExpirationTimeout;
}
@Override
public V get(final String key) throws InterruptedException {
if (key == null) {
throw new NullPointerException("Key is null");
}
log.debug("Thread {}. Get value for key {}.", getNameCurrentThread(), key);
LazyLoadingValue<V> existingCachedValue = cache.get(key);
if (existingCachedValue == null) {
log.debug("Thread {}. Cached value isn't found in cache. Create new cached value.", getNameCurrentThread());
LazyLoadingValue<V> newValueForCache = new LazyLoadingValue<>(() -> loader.load(key),
cachedValueExpirationTimeout);
existingCachedValue = cache.putIfAbsent(key, newValueForCache);
if (existingCachedValue == null) {
log.debug("Thread {}. Cached value isn't found in cache, during attempt to putting it to cache. " +
"Run this task.", getNameCurrentThread());
existingCachedValue = newValueForCache;
existingCachedValue.calculate();
} else {
log.debug("Thread {}. Cached value is found in cache, during attempt to putting it to cache.",
getNameCurrentThread());
}
}
try {
return existingCachedValue.retrieveResult();
} catch (ExecutionException ex) {
cache.remove(key); // give chance to other threads to compute value later
throw new IllegalStateException("Thread " + getNameCurrentThread() + "Error occurred during computation.");
}
}
@Override
public void reset(final String key) {
if (key == null) {
throw new NullPointerException("Key is null");
}
LazyLoadingValue<V> cachedValue = cache.get(key);
if (cachedValue == null) {
log.debug("Thread {}. Cached value isn't found in cache. Nothing to reset.", getNameCurrentThread());
return;
}
if (cachedValue.isValueExpired()) {
LazyLoadingValue<V> removedCachedValue = cache.remove(key);
if (removedCachedValue != null) {
log.debug("Thread {}. Cached value is removed from cache.", getNameCurrentThread());
} else {
log.debug("Thread {}. Cached value isn't removed from cache. It has been removed earlier in another thread.",
getNameCurrentThread());
}
}
}
@Override
public void resetAllExpiredValues() {
// no need full copy key set, because keySet method for ConcurrentHashMap returns weakly consistent iterator and
// there isn't java.util.ConcurrentModificationException during exec this method.
cache.keySet().forEach(this::reset);
}
}
|
C#
|
UTF-8
| 18,245 | 2.71875 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Numerics;
using System.Text;
using System.Threading.Tasks;
namespace PbrResourceUtils.Model
{
public static class SegmentedCylinder
{
//All directions are assumed to be normalized
public class Segment
{
public Vector3 Center;
public Vector3 ForwardDirection;
public Vector3 ForwardBefore, ForwardAfter; //Used only when !ContinuousNormal
public Vector3 UpDirection;
public float RadiusX, RadiusY;
public float Rotation0Fraction; //In fraction of 2Pi
public float RotationStepFraction;
public float UStep;
public bool ContinuousNormal;
}
private class GeneratingModel
{
//public List<RayTracingVertex> rtv = new List<RayTracingVertex>();
public List<ModelVertex> rdv = new List<ModelVertex>();
public List<Triangle> triangles = new List<Triangle>();
public SingleMaterialModel ToModel()
{
return new SingleMaterialModel
{
Vertices = rdv.ToArray(),
Triangles = triangles.ToArray(),
};
}
public void UpdateNormal(int rdvIndex, Vector3 n)
{
ModelVertex v = rdv[rdvIndex];
v.Normal = n / n.Length();
rdv[rdvIndex] = v;
}
//public int AddRTV(RayTracingVertex v)
//{
// var ret = rtv.Count;
// rtv.Add(v);
// return ret;
//}
public int AddRDV(ModelVertex v)
{
var ret = rdv.Count;
rdv.Add(v);
return ret;
}
public void AddTriangle(int v1, int v2, int v3)
{
triangles.Add(new Triangle
{
V1 = v1,
V2 = v2,
V3 = v3,
});
}
}
public static SingleMaterialModel Generate(List<Segment> segments)
{
if (segments.Count < 2)
{
throw new InvalidOperationException();
}
var totalUDistance = segments.Sum(x => x.UStep);
var currentU = 0f;
GeneratingModel model = new GeneratingModel();
List<int> lastSegment = new List<int>(); //rdv index
List<int> thisSegment = new List<int>();
int lastWrapPoint, thisWrapPoint;
int GetLast(int index)
{
if (index == lastSegment.Count) return lastWrapPoint;
return lastSegment[index];
}
int GetThis(int index)
{
if (index == thisSegment.Count) return thisWrapPoint;
return thisSegment[index];
}
CreateVertices(segments, 0, currentU / totalUDistance, model, lastSegment, out lastWrapPoint);
for (int i = 1; i < segments.Count; ++i)
{
//Creating new vertices
currentU += segments[i].UStep;
CreateVertices(segments, i, currentU / totalUDistance, model, thisSegment, out thisWrapPoint);
//Clone old vertices
if (!segments[i - 1].ContinuousNormal)
{
CloneVertices(segments, i - 1, model, lastSegment, ref lastWrapPoint);
}
//Check index mapping
bool lastF = segments[i - 1].Rotation0Fraction != 0;
bool thisF = segments[i].Rotation0Fraction != 0;
int lastN = lastSegment.Count - (lastF ? 1 : 0);
int thisN = thisSegment.Count - (thisF ? 1 : 0);
if (lastN != 1 && thisN != 1 && lastN != thisN)
{
throw new ArgumentException("Vertices number mismatch");
}
if (lastN == 1 && thisN == 1)
{
throw new ArgumentException("Invalid segment");
}
if (segments[i].Rotation0Fraction > segments[i].RotationStepFraction)
{
throw new ArgumentException("Invalid rotation");
}
//Create triangles
if (lastN == 1)
{
//TODO make the order same for F and non-F
if (thisF)
{
model.AddTriangle(lastSegment[0], GetThis(0), GetThis(thisSegment.Count - 1));
for (int j = 0; j < thisSegment.Count - 2; ++j)
{
model.AddTriangle(lastSegment[0], GetThis(j + 1), GetThis(j));
}
model.AddTriangle(lastSegment[0], GetThis(thisSegment.Count), GetThis(thisSegment.Count - 2));
}
else
{
for (int j = 0; j < thisSegment.Count; ++j)
{
model.AddTriangle(lastSegment[0], GetThis(j + 1), GetThis(j));
}
}
}
else if (thisN == 1)
{
if (lastF)
{
model.AddTriangle(thisSegment[0], GetLast(lastSegment.Count - 1), GetLast(0));
for (int j = 0; j < lastSegment.Count - 2; ++j)
{
model.AddTriangle(thisSegment[0], GetLast(j), GetLast(j + 1));
}
model.AddTriangle(thisSegment[0], GetLast(lastSegment.Count - 2), GetLast(lastSegment.Count));
}
else
{
for (int j = 0; j < lastSegment.Count; ++j)
{
model.AddTriangle(thisSegment[0], GetLast(j), GetLast(j + 1));
}
}
}
else
{
bool old0new1 = lastF && !thisF;
int normalN = thisN;
if (lastF || thisF) normalN -= 1;
for (int j = 0; j < normalN; ++j)
{
var old0 = GetLast(j);
var old1 = GetLast(j + 1);
var new0 = GetThis(j);
var new1 = GetThis(j + 1);
if (old0new1)
{
model.AddTriangle(old0, old1, new1);
model.AddTriangle(old0, new1, new0);
}
else
{
model.AddTriangle(old0, old1, new0);
model.AddTriangle(new0, old1, new1);
}
}
if (lastF && thisF)
{
//ignore old0new1 flag
var old0 = lastSegment[normalN];
var old1 = lastSegment[normalN + 1];
var old1r = lastWrapPoint;
var old2 = lastSegment[0];
var new0 = thisSegment[normalN];
var new1 = thisSegment[normalN + 1];
var new1r = thisWrapPoint;
var new2 = thisSegment[0];
//ignore old0new1 flag
model.AddTriangle(old0, old1r, new1r);
model.AddTriangle(old0, new1r, new0);
model.AddTriangle(old1, old2, new2);
model.AddTriangle(old1, new2, new1);
}
else if (lastF)
{
var old0 = lastSegment[normalN];
var old1 = lastSegment[normalN + 1];
var old1r = lastWrapPoint;
var old2 = lastSegment[0];
var new0 = thisSegment[normalN];
var new2 = thisSegment[0];
var new2r = thisWrapPoint;
model.AddTriangle(old0, old1r, new2r);
model.AddTriangle(old1, old2, new2);
model.AddTriangle(new0, old0, new2r);
}
else if (thisF)
{
var old0 = lastSegment[normalN];
var old2 = lastSegment[0];
var old2r = lastWrapPoint;
var new0 = thisSegment[normalN];
var new1 = thisSegment[normalN + 1];
var new1r = thisWrapPoint;
var new2 = thisSegment[0];
model.AddTriangle(old0, old2r, new0);
model.AddTriangle(old2, new2, new1);
model.AddTriangle(old2r, new1r, new0);
}
}
//Move vertex list
{
var e = lastSegment;
lastSegment = thisSegment;
thisSegment = e;
lastWrapPoint = thisWrapPoint;
}
}
return model.ToModel();
}
private static void CreateVertices(List<Segment> segments, int segIndex, float u, GeneratingModel model, List<int> output, out int wrapPoint)
{
var seg = segments[segIndex];
output.Clear();
for (int i = 0; seg.Rotation0Fraction + seg.RotationStepFraction * i < 1; ++i)
{
var frac = seg.Rotation0Fraction + seg.RotationStepFraction * i;
var pos = CalculatePosition(seg, frac);
var rdx = model.AddRDV(new ModelVertex
{
Position = pos,
Normal = CalculateNormal(segments, segIndex, frac, false),
UV = new Vector2(u, frac),
});
output.Add(rdx);
}
if (seg.Rotation0Fraction != 0)
{
if (output.Count < 2)
{
throw new ArgumentException("Invalid segment");
}
var pos = (model.rdv[output[0]].Position + model.rdv[output[output.Count - 1]].Position) / 2;
var rdx = model.AddRDV(new ModelVertex
{
Position = pos,
Normal = CalculateNormal(segments, segIndex, 0, false),
UV = new Vector2(u, 0),
});
output.Add(rdx);
}
if (output.Count == 1)
{
wrapPoint = -1;
//Move v to 0.5
var rtv = model.rdv[output[0]];
rtv.UV.Y = 0.5f;
model.rdv[output[0]] = rtv;
}
else
{
var zero = output.Where(ii => model.rdv[ii].UV.Y == 0).First();
var rdx = model.AddRDV(new ModelVertex
{
Position = model.rdv[zero].Position,
Normal = model.rdv[zero].Normal,
UV = new Vector2(u, 1),
});
wrapPoint = rdx;
}
}
private static void CloneVertices(List<Segment> segments, int segIndex, GeneratingModel model, List<int> output, ref int wrapPoint)
{
var input = output.ToArray();
output.Clear();
var seg = segments[segIndex];
bool wrapProcessed = false;
for (int i = 0; i < input.Length; ++i)
{
var rdv = model.rdv[input[i]];
var deg = seg.Rotation0Fraction + seg.RotationStepFraction * i;
if (deg >= 1)
{
if (i != input.Length - 1) continue; //should never happen
deg = 0;
}
rdv.Normal = CalculateNormal(segments, segIndex, deg, true);
output.Add(model.AddRDV(rdv));
if (rdv.UV.Y == 0 && wrapPoint != -1)
{
if (wrapProcessed) throw new Exception();
var rdv2 = new ModelVertex
{
Position = model.rdv[wrapPoint].Position,
Normal = rdv.Normal,
UV = model.rdv[wrapPoint].UV,
};
wrapPoint = model.AddRDV(rdv2);
wrapProcessed = true;
}
}
if (!wrapProcessed && wrapPoint != -1) throw new Exception();
}
private static Vector3 CalculateNormal(List<Segment> segments, int segIndex, float rotationFrac, bool overrideContinuous)
{
Segment seg = segments[segIndex];
if (seg.RotationStepFraction + seg.Rotation0Fraction >= 1)
{
//Single vertex
var f = seg.ForwardDirection;
int otherIndex;
if (segIndex == 0)
{
otherIndex = 1;
}
else if (segIndex == segments.Count - 1)
{
otherIndex = segIndex - 1;
}
else
{
//In the middle, return (0, 0, 0)
return new Vector3();
}
if (f.LengthSquared() == 0)
{
f = segments[otherIndex].ForwardDirection;
}
if (otherIndex > segIndex)
{
return -f;
}
return f;
}
//Normal case
var nn = new Vector3();
var surfaceF = new Vector3();
if (segIndex > 0 && !overrideContinuous)
{
surfaceF += CalculateForward(segments, segIndex, rotationFrac);
nn += CalculateRingNormal(seg, rotationFrac, true);
}
if (overrideContinuous ||
segIndex < segments.Count - 1 && segments[segIndex].ContinuousNormal)
{
surfaceF += CalculateForward(segments, segIndex + 1, rotationFrac);
nn += CalculateRingNormal(seg, rotationFrac, false);
}
var sflen = surfaceF.Length();
if (sflen == 0) return new Vector3();
surfaceF = surfaceF / sflen;
var realn = nn - Vector3.Dot(nn, surfaceF) * surfaceF;
var nnlen = realn.Length();
if (nnlen == 0)
{
return new Vector3();
}
realn /= nnlen;
return realn;
}
//surface forward direction segIndex-1 -> segIndex
private static Vector3 CalculateForward(List<Segment> segments, int segIndex, float rotationFrac)
{
var seg1 = segments[segIndex - 1];
var seg2 = segments[segIndex];
var f1 = seg1.ForwardDirection;
var ry1 = seg1.RadiusY;
if (!seg1.ContinuousNormal)
{
f1 = seg1.ForwardAfter;
ry1 *= Vector3.Dot(f1, seg1.ForwardDirection);
}
var f2 = seg2.ForwardDirection;
var ry2 = seg2.RadiusY;
if (!seg2.ContinuousNormal)
{
f2 = seg2.ForwardBefore;
ry2 *= Vector3.Dot(f2, seg2.ForwardDirection);
}
var x1 = seg1.UpDirection;
var tr1 = Matrix4x4.CreateFromAxisAngle(f1, (float)Math.PI / 2);
var y41 = Vector4.Transform(x1, tr1);
var y1 = new Vector3(y41.X, y41.Y, y41.Z);
var x2 = seg2.UpDirection;
var tr2 = Matrix4x4.CreateFromAxisAngle(f2, (float)Math.PI / 2);
var y42 = Vector4.Transform(x2, tr2);
var y2 = new Vector3(y42.X, y42.Y, y42.Z);
var sin = (float)Math.Sin(rotationFrac * Math.PI * 2);
var cos = (float)Math.Cos(rotationFrac * Math.PI * 2);
var pos1 = x1 * seg1.RadiusX * cos + y1 * ry1 * sin;
var pos2 = x2 * seg2.RadiusX * cos + y2 * ry2 * sin;
var a = seg1.Center + pos1;
var b = seg2.Center + pos2;
var dir = b - a;
return dir / dir.Length();
}
//isBefore=true: use 'before'; isBefore=false: use 'after'
private static Vector3 CalculateRingNormal(Segment seg, float rotationFrac, bool isBefore)
{
var x = seg.UpDirection;
var f = seg.ForwardDirection;
var ry = seg.RadiusY;
if (!seg.ContinuousNormal)
{
f = isBefore ? seg.ForwardBefore : seg.ForwardAfter;
ry *= Vector3.Dot(f, seg.ForwardDirection);
}
var tr = Matrix4x4.CreateFromAxisAngle(f, (float)Math.PI / 2);
var y4 = Vector4.Transform(x, tr);
var y = new Vector3(y4.X, y4.Y, y4.Z);
var sin = (float)Math.Sin(rotationFrac * Math.PI * 2);
var cos = (float)Math.Cos(rotationFrac * Math.PI * 2);
return x * ry * cos + y * seg.RadiusX * sin;
}
private static Vector3 CalculatePosition(Segment seg, float rotationFrac)
{
var x = seg.UpDirection;
var tr = Matrix4x4.CreateFromAxisAngle(seg.ForwardDirection, (float)Math.PI / 2);
var y4 = Vector4.Transform(x, tr);
var y = new Vector3(y4.X, y4.Y, y4.Z);
var sin = (float)Math.Sin(rotationFrac * Math.PI * 2);
var cos = (float)Math.Cos(rotationFrac * Math.PI * 2);
return seg.Center + x * seg.RadiusX * cos + y * seg.RadiusY * sin;
}
}
}
|
PHP
|
UTF-8
| 12,192 | 2.59375 | 3 |
[] |
no_license
|
<?php
$currentLocation = "";
// ---------------------------------------------------------------------------------------------------------------------
// Here comes your script for loading from the database.
// ---------------------------------------------------------------------------------------------------------------------
// Remove this example in your live site and replace it with a connection to database //////////////////////////////////
ob_start();
include 'data.php';
ob_end_clean();
for( $i=0; $i < count($data); $i++){
if( $data[$i]['id'] == $_POST['id'] ){
$currentLocation = $data[$i]; // Loaded data must be stored in the "$currentLocation" variable
header('Content-Type: application/json');
echo json_encode($currentLocation);
}
}
/*
for( $i=0; $i < count($data); $i++){
if( $data[$i]['id'] == $_POST['id'] ){
$currentLocation = $data[$i]; // Loaded data must be stored in the "$currentLocation" variable
}
}
// End of example //////////////////////////////////////////////////////////////////////////////////////////////////////
// Modal HTML code
$latitude = "";
$longitude = "";
$address = "";
if( !empty($currentLocation['latitude']) ){
$latitude = $currentLocation['latitude'];
}
if( !empty($currentLocation['longitude']) ){
$longitude = $currentLocation['longitude'];
}
if( !empty($currentLocation['address']) ){
$address = $currentLocation['address'];
}
echo
'<div class="modal-item-detail modal-dialog" role="document" data-latitude="'. $latitude .'" data-longitude="'. $longitude .'" data-address="'. $address .'">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<div class="section-title">
<h2>'. $currentLocation['title'] .'</h2>
<div class="label label-default">'. $currentLocation['category'] .'</div>';
// Ribbon ------------------------------------------------------------------------------------------
if( !empty($currentLocation['ribbon']) ){
echo
'<figure class="ribbon">'. $currentLocation['ribbon'] .'</figure>';
}
// Rating ------------------------------------------------------------------------------------------
if( !empty($currentLocation['rating']) ){
echo
'<div class="rating-passive" data-rating="'. $currentLocation['rating'] .'">
<span class="stars"></span>
<span class="reviews">'. $currentLocation['reviews_number'] .'</span>
</div>';
}
echo
'<div class="controls-more">
<ul>
<li><a href="#">Add to favorites</a></li>
<li><a href="#">Add to watchlist</a></li>
</ul>
</div>
<!--end controls-more-->
</div>
<!--end section-title-->
</div>
<!--end modal-header-->
<div class="modal-body">
<div class="left">';
// Gallery -----------------------------------------------------------------------------------------
if( !empty($currentLocation['gallery']) ){
$gallery = "";
for($i=0; $i < count($currentLocation['gallery']); $i++){
$gallery .= '<img src="'. $currentLocation['gallery'][$i] .'" alt="">';
}
echo
'<div class="gallery owl-carousel" data-owl-nav="1" data-owl-dots="0">'. $gallery .'</div>
<!--end gallery-->';
}
echo
'<div class="map" id="map-modal"></div>
<!--end map-->
<section>
<h3>Contact</h3>';
// Contact -----------------------------------------------------------------------------------------
if( !empty($currentLocation['location']) ){
echo
'<h5><i class="fa fa-map-marker"></i>'. $currentLocation['location'] .'</h5>';
}
// Phone -------------------------------------------------------------------------------------------
if( !empty($currentLocation['phone']) ){
echo
'<h5><i class="fa fa-phone"></i>'. $currentLocation['phone'] .'</h5>';
}
// Email -------------------------------------------------------------------------------------------
if( !empty($currentLocation['email']) ){
echo
'<h5><i class="fa fa-envelope"></i>'. $currentLocation['email'] .'</h5>';
}
echo
'</section>
<section>
<h3>Social Share</h3>
<div class="social-share"></div>
</section>
</div>
<!--end left -->
<div class="right">
<section>
<h3>About</h3>
<p>'. $currentLocation['description'] .'</p>
<a href="#" class="btn btn-primary btn-framed btn-light-frame btn-rounded btn-xs">Show More</a>
</section>
<!--end about-->';
// Tags ----------------------------------------------------------------------------------------------------------------
if( !empty($currentLocation['tags']) ){
$tags = "";
for($i=0; $i < count($currentLocation['tags']); $i++){
$tags .= '<li>'. $currentLocation['tags'][$i] .'</li>';
}
echo
'<section>
<h3>Features</h3>
<ul class="tags">'. $tags .'</ul>
</section>
<!--end tags-->';
}
// Today Menu --------------------------------------------------------------------------------------
if( !empty($currentLocation['today_menu']) ){
echo
'<section>
<h3>Today menu</h3>';
for($i=0; $i < count($currentLocation['today_menu']); $i++){
echo
'<ul class="list-unstyled list-descriptive icon">
<li>
<i class="fa fa-cutlery"></i>
<div class="description">
<strong>'. $currentLocation['today_menu'][$i]['meal_type'] .'</strong>
<p>'. $currentLocation['today_menu'][$i]['meal'] .'</p>
</div>
</li>
</ul>
<!--end list-descriptive-->';
}
echo
'</section>
<!--end today-menu-->';
}
// Schedule ----------------------------------------------------------------------------------------
if( !empty($currentLocation['schedule']) ){
echo
'<section>
<h3>Schedule</h3>';
for($i=0; $i < count($currentLocation['schedule']); $i++){
echo
'<ul class="list-unstyled list-schedule">
<li>
<div class="left">
<strong class="promoted">'. $currentLocation['schedule'][$i]['date'] .'</strong>
<figure>'. $currentLocation['schedule'][$i]['time'] .'</figure>
</div>
<div class="right">
<strong>'. $currentLocation['schedule'][$i]['location_title'] .'</strong>
<figure>'. $currentLocation['schedule'][$i]['location_address'] .'</figure>
</div>
</li>
</ul>
<!--end list-schedule-->';
}
echo
'</section>
<!--end schedule-->';
}
// Video -------------------------------------------------------------------------------------------
if( !empty($currentLocation['video']) ){
echo
'<section>
<h3>Video presentation</h3>
<div class="video">'. $currentLocation['video'] .'</div>
</section>
<!--end video-->';
}
// Description list --------------------------------------------------------------------------------
if( !empty($currentLocation['description_list']) ){
echo
'<section>
<h3>Listing Details</h3>';
for($i=0; $i < count($currentLocation['description_list']); $i++){
echo
'<dl>
<dt>'. $currentLocation['description_list'][$i]['title'] .'</dt>
<dd>'. $currentLocation['description_list'][$i]['value'] .'</dd>
</dl>
<!--end property-details-->';
}
echo
'</section>
<!--end description-list-->';
}
// Reviews -----------------------------------------------------------------------------------------
if( !empty($currentLocation['reviews']) ){
echo
'<section>
<h3>Latest reviews</h3>';
for($i=0; $i < 2; $i++){
echo
'<div class="review">
<div class="image">
<div class="bg-transfer" style="background-image: url('. $currentLocation['reviews'][$i]['author_image'] .')"></div>
</div>
<div class="description">
<figure>
<div class="rating-passive" data-rating="'. $currentLocation['reviews'][$i]['rating'] .'">
<span class="stars"></span>
</div>
<span class="date">'. $currentLocation['reviews'][$i]['date'] .'</span>
</figure>
<p>'. $currentLocation['reviews'][$i]['review_text'] .'</p>
</div>
</div>
<!--end review-->';
}
echo
'</section>
<!--end reviews-->';
}
echo
'</div>
<!--end right-->
</div>
<!--end modal-body-->
</div>
<!--end modal-content-->
</div>
<!--end modal-dialog-->
';
*/
|
Markdown
|
UTF-8
| 9,006 | 3.53125 | 4 |
[] |
no_license
|
# 第824期 | 为什么会有「法币」制度?
> 罗辑思维
2019-10-07
上周,我们有一期节目讨论了银行和国家之间的关系。银行并不是自由市场竞争的参与者,恰恰相反,它是国家赋予了特权的垄断经营者。没有国家撑腰,根本就没有现代银行。那你说自由市场竞争里的金融业什么样呢?就是中国传统的钱庄票号的样子。在现代银行的面前,它们根本就没有丝毫竞争力。
那今天,我们再来聊聊货币,为什么国家也要把货币牢牢控制在自己手里?
有一个词,叫「法币」,法定货币的意思。你拿到了这种货币,国家不承诺一定会兑换成多少黄金或者实物,这张纸的背后只有一样东西,那就是国家的信用。现在的美元是法币,人民币也是法币。
很多人就说了,这种法币制度不好,肯定不如原来的金本位、银本位制度好。为啥?因为政府信用这个东西,靠不住啊。可能滥发法币。
咱们不拿什么发生过恶性通货膨胀的国家说事,就说美国。美国政府在印钱这个事上是非常克制的,但是你知道过去 100 年,美元贬值了多少吗?今天的 23 美元,只相当于 100 年前的 1 美元。政府想搞钱,除了收税,最重要的手段就是印钞票。有了法币这个轻松的手段,对政府的诱惑太大了,根本管不住自己。
在中国人的历史记忆里面,「法币」这个词就尤其糟糕。国民党政府发行的法币,最恶性的时候,导致物价上涨几千万倍。国民党政府失掉了人心,这是一个重要的因素。
那为什么不退回到金本位、银本位呢?在金本位、银本位下,政府不能胡乱印钞票,不是有利于金融稳定吗?其实,现在也有经济学家在这么呼吁,为啥金本位、银本位就是搞不成呢?今天我们就来聊聊,法币对于现代政府到底意味着什么。
我们拿中国现代史上的一件事来举例子。
在 1935 年之前,中国实行的就是银本位制,通用的货币是银元。知道一些老货币知识的人,知道什么「袁大头」「孙大头」之类的。
那这是一种很稳定的货币吗?不是。你想,当时重要大国中,只有中国实行银本位。这就意味着,在其他国家看来只是普通商品的白银,在中国却是核心货币。国际商品市场,尤其是银市场一波动,中国的货币制度就跟着波动,这哪儿受得了?
这种事,在上个世纪 30 年代真就发生了。导致中国经济灾难的,不是什么敌国,而是关系看起来还不错的美国。
1934 年,美国总统罗斯福签署了一个法案,授权美国财政部高价收购白银。他为啥这么做呢?主要是两个原因:
第一,你想 1934 年,美国还在大萧条的过程中,为了稳定美国的经济,罗斯福也是在试各种方案,其中一条就是补充白银储备,所以要大量收购白银。
第二个原因呢?是为了美国国内政治需要,罗斯福作为总统,要讨好几个白银生产州,把白银的价格炒上去。你看,不能说罗斯福这么干有啥问题吧?人家不是冲着搞垮中国经济来的。
这个法案一出台,当时把白银从上海运到纽约,可以获利 15%。这么稳赚不赔的生意,商人哪儿忍得住?很快,大量白银从中国流失,1934 年当年,中国白银净出口 2.57 亿元。再说一遍,白银对美国只是一种商品,对中国可是货币,是经济的血液。人家只是想多喝点果汁,结果却成了对中国的抽血。
这真是一场中国经济的无妄之灾。市场没了货币,这叫通货紧缩,交易没有中介了,交易效率大大下降,经济自然就垮了。当时工厂关门、银行挤兑大量出现。蒋介石在日记里写的,急得不得了。
那怎么办?国民政府派人去向美国求情,结果罗斯福无动于衷,他说:「这是中国自己的事,并非我们美国的事。他们如果愿意,尽可制止白银外流,而我们不能只因为中国人不能保护自己就改变我们的政策。」这话听着也对,罗斯福毕竟是个政治家,国内那几个白银生产州对他的支持,远比中国这个国家要重要得多。
连关系友好的国家尚且如此,对中国心怀恶意的日本,就更不会手下留情了。
日本也看中了中国经济的这个软肋。1932 年一·二八事变以后,日本就开始大量收购市面上流通的银元,运到日本或者日本占领区囤积起来。南京政府一点辙都没有。银元是货物,你就算是有严厉的管制措施,私藏银元、运输银元很难堵得住。更何况,日本人当时还用军舰来运输。有一本名著叫《银元时代生活史》,他的作者陈存仁说,这简直等于人身上的血液,一天一天地被人抽走。跟日本人斗,不用上战场打,金融市场上就已经输掉了。
你看,用白银这种商品作为货币,这是当时中国的一项重大战略劣势。怎么办?1935 年,国民政府只好搞法币改革,禁止银元流通,货币发行由政府垄断。从此,中国摆脱了银本位。
一发行法币,最恨的是谁?当然就是日本人。他们囤积了 5 千多万银元,这下子全砸在手里了。他们囤积的不是货币了,就是普通的一种商品。日本军部甚至发话,说中国的币制改革是对日本的「公开挑战」。你看,敌人不乐意的事,是不是对我们来说就是件好事?
而对中国来说呢?有几个好处显而易见。
首先,货币这个事彻底操控在中央政府的手里了。发行多少,政府说了算。外部力量对金融市场的影响大幅度降低。陈存仁先生在《银元时代生活史》里就写道:「全面抗战之后最初三年,实实在在可以说法币坚挺。老百姓对它的信心,一点也没有动摇,购买力也一如其旧,一般人都不知道什么叫做囤积,更不知道什么叫做外汇。」
其次,银元不再流通了。银子就是一笔财富。国民政府把国内的银元收集起来。你美国不是要银子吗?卖给你们。前后中国政府总共卖过美国大约 2 亿盎司的白银。中国抗战初期的财政,主要靠这笔巨款支持。
更重要的是,当时全民抗战,就是要集中全国的人力物力财力和日本拼死一搏。如果集中力量的手段还只有收税这一种的话,不仅征收成本极高,还极容易激化政府和民众的矛盾。现在有了印钞票这个手段,政府汲取财富的效率一下子就高起来了。
事后想想,也是很可怕。国民政府 1935 年才实行法币制度,两年以后的 1937 年就爆发了全面抗战。如果当时国内流通的货币还是银元,那可能仗还没打,战时经济可能就崩溃了。
日本 NHK 拍摄过一部纪录片《圆的战争》,其中就提到:如果不是在 1937 年之前进行币制改革,中国也许不会抵抗那么久,历史也将会改写。
当然,你可能会说,法币的下场不怎么好啊。到 1937 年抗战爆发,法币一共发行总额不过 14 亿元,所以币值坚挺。但是到了日本投降前呢?也就是 1945 年,法币发行已经超过 5 千亿元。到了 1948 年,发行了多少?660 万亿。那当然就是废纸了。蒋介石要打内战要花钱,手里又有了这么好用的货币工具,哪能忍得住不用?但问题是,这是蒋介石政治的失败,不是法币这种货币制度本身的失败。
今天我们回顾这个过程,你发现没有?当年国民政府的这项改革,和 1971 年尼克松让美元和黄金脱钩,底层的理由是一样的。按照布雷顿森林体系,也就是二战结束的时候美国对全世界的承诺,你手里有 35 美元,就可以找美国兑付 1 盎司的黄金。但是到了 1971 年的时候呢?美国手里的黄金只剩下 102 亿美元了,但是要到期的短期外债呢?有 520 亿美元。为啥呢?因为各国都不相信美元,都要兑换黄金,搁在自己家金库里才放心。这和当年日本收购中国的银元,逻辑和危害是一样的。
所以,尼克松马上就宣布,不玩了。美元和黄金脱钩。美元也正式成为一种「法币」,只靠国家信用担保的货币。
独立的国家,必须把命运掌握在自己的手中,而不能受制于任何一项实体的货物,所谓「我命由我不由天」。这不是什么货币的命运,这是在激烈对抗和残酷竞争的民族国家的必然命运。为什么金本位、银本位不可能恢复?这不是个金融问题,这是一个非常严肃的政治问题。
好,这个话题就聊到这里,罗辑思维,明天见。
荐书:《白银帝国》
为什么说白银短缺,导致了明朝的灭亡?
|
Go
|
UTF-8
| 2,914 | 3.015625 | 3 |
[] |
no_license
|
package builder
import (
"bytes"
"image"
"image/color"
"image/draw"
"image/gif"
"io"
"os"
)
type MatrixToken uint32
const (
WALL MatrixToken = 1 << iota
PATH
BORDER
START
END
)
type MazeImageMatrix struct {
M [][]MatrixToken
I *MazeImageBuilder
}
func (i MazeImageMatrix) Has(x, y int, t MatrixToken) bool {
return t == (t & i.M[y][x])
}
// String prints the the matrix to the stdout in visula way
func (i MazeImageMatrix) String() string {
buff := new(bytes.Buffer)
for _, data := range i.M {
for _, token := range data {
switch true {
case WALL == (WALL & token):
buff.Write([]byte{'#'})
case PATH == (PATH & token), BORDER == (BORDER & token):
buff.Write([]byte{' '})
}
}
buff.Write([]byte{'\n'})
}
return string(buff.Bytes())
}
// isWall check if the given colors is matching the config wallcolors
func (i *MazeImageMatrix) isWall(r, g, b uint8) bool {
return i.I.wall_color.R == r && i.I.wall_color.G == g && i.I.wall_color.B == b
}
// NewMazeImageMatrix creates a image matrix base on fetched body
func NewMazeImageMatrix(r io.Reader, m *MazeImageBuilder) (*MazeImageMatrix, error) {
MazeImageMatrix := &MazeImageMatrix{I: m}
img, err := gif.Decode(r)
if err != nil {
return nil, err
}
rect := img.Bounds()
rgba := image.NewRGBA(rect)
draw.Draw(rgba, rect, img, rect.Min, draw.Src)
reader := bytes.NewReader(rgba.Pix)
matrix := make([][]MatrixToken, rect.Max.Y)
for y := 0; y < rect.Max.Y; y++ {
for x := 0; x < rect.Max.X; x++ {
if len(matrix[y]) == 0 {
matrix[y] = make([]MatrixToken, rect.Max.X)
}
part := make([]byte, 4)
reader.Read(part)
if y == 0 || x == 0 {
matrix[y][x] = BORDER
} else {
if MazeImageMatrix.isWall(part[0], part[1], part[2]) {
matrix[y][x] = WALL
} else {
matrix[y][x] = PATH
}
}
}
}
MazeImageMatrix.M = matrix
return MazeImageMatrix, nil
}
// ToFile will push the drawing created with DrawImage to the given fd
func (i MazeImageMatrix) ToFile(file *os.File) error {
return gif.Encode(file, i.DrawImage(), &gif.Options{NumColors: 256})
}
// DrawImage draws a new image beased on matrix and config ration
func (i MazeImageMatrix) DrawImage() draw.Image {
rect := image.Rect(0, 0, len(i.M[0])*int(i.I.ratio), len(i.M)*int(i.I.ratio))
rgba := image.NewRGBA(rect)
draw.Draw(rgba, rgba.Bounds(), &image.Uniform{color.White}, image.ZP, draw.Src)
for y := 0; y < len(i.M)*int(i.I.ratio); y += int(i.I.ratio) {
for x := 0; x < len(i.M[y/int(i.I.ratio)])*int(i.I.ratio); x += int(i.I.ratio) {
switch i.M[y/int(i.I.ratio)][x/int(i.I.ratio)] {
case WALL:
draw.Draw(rgba, image.Rect(x, y, x+int(i.I.ratio), y+int(i.I.ratio)), &image.Uniform{i.I.wall_color}, image.ZP, draw.Src)
case PATH, BORDER:
draw.Draw(rgba, image.Rect(x, y, x+int(i.I.ratio), y+int(i.I.ratio)), &image.Uniform{i.I.path_color}, image.ZP, draw.Src)
}
}
}
return rgba
}
|
Go
|
UTF-8
| 3,914 | 2.84375 | 3 |
[
"Apache-2.0"
] |
permissive
|
package xchacha20poly1305
import (
"bytes"
"encoding/hex"
"testing"
)
func toHex(bits []byte) string {
return hex.EncodeToString(bits)
}
func fromHex(bits string) []byte {
b, err := hex.DecodeString(bits)
if err != nil {
panic(err)
}
return b
}
func TestHChaCha20(t *testing.T) {
for i, v := range hChaCha20Vectors {
var key [32]byte
var nonce [16]byte
copy(key[:], v.key)
copy(nonce[:], v.nonce)
HChaCha20(&key, &nonce, &key)
if !bytes.Equal(key[:], v.keystream) {
t.Errorf("test %d: keystream mismatch:\n \t got: %s\n \t want: %s", i, toHex(key[:]), toHex(v.keystream))
}
}
}
var hChaCha20Vectors = []struct {
key, nonce, keystream []byte
}{
{
fromHex("0000000000000000000000000000000000000000000000000000000000000000"),
fromHex("000000000000000000000000000000000000000000000000"),
fromHex("1140704c328d1d5d0e30086cdf209dbd6a43b8f41518a11cc387b669b2ee6586"),
},
{
fromHex("8000000000000000000000000000000000000000000000000000000000000000"),
fromHex("000000000000000000000000000000000000000000000000"),
fromHex("7d266a7fd808cae4c02a0a70dcbfbcc250dae65ce3eae7fc210f54cc8f77df86"),
},
{
fromHex("0000000000000000000000000000000000000000000000000000000000000001"),
fromHex("000000000000000000000000000000000000000000000002"),
fromHex("e0c77ff931bb9163a5460c02ac281c2b53d792b1c43fea817e9ad275ae546963"),
},
{
fromHex("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f"),
fromHex("000102030405060708090a0b0c0d0e0f1011121314151617"),
fromHex("51e3ff45a895675c4b33b46c64f4a9ace110d34df6a2ceab486372bacbd3eff6"),
},
{
fromHex("24f11cce8a1b3d61e441561a696c1c1b7e173d084fd4812425435a8896a013dc"),
fromHex("d9660c5900ae19ddad28d6e06e45fe5e"),
fromHex("5966b3eec3bff1189f831f06afe4d4e3be97fa9235ec8c20d08acfbbb4e851e3"),
},
}
func TestVectors(t *testing.T) {
for i, v := range vectors {
if len(v.plaintext) == 0 {
v.plaintext = make([]byte, len(v.ciphertext))
}
var nonce [24]byte
copy(nonce[:], v.nonce)
aead, err := New(v.key)
if err != nil {
t.Error(err)
}
dst := aead.Seal(nil, nonce[:], v.plaintext, v.ad)
if !bytes.Equal(dst, v.ciphertext) {
t.Errorf("test %d: ciphertext mismatch:\n \t got: %s\n \t want: %s", i, toHex(dst), toHex(v.ciphertext))
}
open, err := aead.Open(nil, nonce[:], dst, v.ad)
if err != nil {
t.Error(err)
}
if !bytes.Equal(open, v.plaintext) {
t.Errorf("test %d: plaintext mismatch:\n \t got: %s\n \t want: %s", i, string(open), string(v.plaintext))
}
}
}
var vectors = []struct {
key, nonce, ad, plaintext, ciphertext []byte
}{
{
[]byte{
0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87, 0x88, 0x89, 0x8a,
0x8b, 0x8c, 0x8d, 0x8e, 0x8f, 0x90, 0x91, 0x92, 0x93, 0x94, 0x95,
0x96, 0x97, 0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
},
[]byte{0x07, 0x00, 0x00, 0x00, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b},
[]byte{0x50, 0x51, 0x52, 0x53, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7},
[]byte(
"Ladies and Gentlemen of the class of '99: If I could offer you only one tip for the future, sunscreen would be it.",
),
[]byte{
0x45, 0x3c, 0x06, 0x93, 0xa7, 0x40, 0x7f, 0x04, 0xff, 0x4c, 0x56,
0xae, 0xdb, 0x17, 0xa3, 0xc0, 0xa1, 0xaf, 0xff, 0x01, 0x17, 0x49,
0x30, 0xfc, 0x22, 0x28, 0x7c, 0x33, 0xdb, 0xcf, 0x0a, 0xc8, 0xb8,
0x9a, 0xd9, 0x29, 0x53, 0x0a, 0x1b, 0xb3, 0xab, 0x5e, 0x69, 0xf2,
0x4c, 0x7f, 0x60, 0x70, 0xc8, 0xf8, 0x40, 0xc9, 0xab, 0xb4, 0xf6,
0x9f, 0xbf, 0xc8, 0xa7, 0xff, 0x51, 0x26, 0xfa, 0xee, 0xbb, 0xb5,
0x58, 0x05, 0xee, 0x9c, 0x1c, 0xf2, 0xce, 0x5a, 0x57, 0x26, 0x32,
0x87, 0xae, 0xc5, 0x78, 0x0f, 0x04, 0xec, 0x32, 0x4c, 0x35, 0x14,
0x12, 0x2c, 0xfc, 0x32, 0x31, 0xfc, 0x1a, 0x8b, 0x71, 0x8a, 0x62,
0x86, 0x37, 0x30, 0xa2, 0x70, 0x2b, 0xb7, 0x63, 0x66, 0x11, 0x6b,
0xed, 0x09, 0xe0, 0xfd, 0x5c, 0x6d, 0x84, 0xb6, 0xb0, 0xc1, 0xab,
0xaf, 0x24, 0x9d, 0x5d, 0xd0, 0xf7, 0xf5, 0xa7, 0xea,
},
},
}
|
Java
|
UTF-8
| 622 | 2.046875 | 2 |
[] |
no_license
|
package com.github.guilhermesgb.steward.mvi.customer.schema;
import android.arch.persistence.room.Dao;
import android.arch.persistence.room.Insert;
import android.arch.persistence.room.OnConflictStrategy;
import android.arch.persistence.room.Query;
import java.util.List;
import io.reactivex.Single;
@Dao
public interface CustomerDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insertAll(List<Customer> customers);
@Query("SELECT * FROM customer")
Single<List<Customer>> findAll();
@Query("SELECT * FROM customer WHERE id = :id LIMIT 1")
Single<Customer> findById(String id);
}
|
Python
|
UTF-8
| 1,225 | 2.921875 | 3 |
[] |
no_license
|
import numpy as np
# functions to create elementary matrices for gaussian elimination row ops
size = 5
u = np.random.uniform(-1, 1, size=(size, 1)) + np.random.uniform(-1, 1, size=(size, 1)) * 1j
v = np.random.uniform(-1, 1, size=(size, 1)) + np.random.uniform(-1, 1, size=(size, 1)) * 1j
A = np.eye(size) - u @ v.T
# all elementary matrices are invertible
print(np.allclose(np.linalg.inv(A), np.eye(size) - u @ v.T / (u.T @ v - 1)))
# elementary matrix row operations for RREF
def elementary_1(size):
i, j = np.random.choice(range(size), size=2, replace=False)
trans = np.eye(size)[i] - np.eye(size)[j]
return np.eye(size) - np.einsum('i,j->ij', trans, trans)
def elementary_2(size, alpha):
i = np.random.randint(size)
return np.eye(size) - (1 - alpha) * np.einsum('i,j->ij', np.eye(size)[i], np.eye(size)[i])
def elementary_3(size, alpha):
i, j = np.random.choice(range(size), size=2, replace=False)
return np.eye(size) - alpha * np.einsum('i,j->ij', np.eye(size)[i], np.eye(size)[j])
print(elementary_3(size, .5))
# Set all rows but i equal to zero
def filter_row(A, i):
return np.einsum('i,j,jk->ik', np.eye(A.shape[0])[i], np.eye(A.shape[0])[i], A)
print(filter_row(A, 2))
|
Python
|
UTF-8
| 800 | 2.53125 | 3 |
[
"MIT"
] |
permissive
|
#!/usr/bin/python3
# config_exceptions.py
class ConfigError(Exception):
def __init__(self, message='Invalid configuration for environment variable conversion'):
super(ConfigError, self).__init__(message)
class PythonConfigError(ConfigError):
def __init__(self, message='Invalid Python configuration for environment variable conversion'):
super(PythonConfigError, self).__init__(message)
class JSONConfigError(ConfigError):
def __init__(self, message='Invalid JSON configuration for environment variable conversion'):
super(JSONConfigError, self).__init__(message)
class EnvConfigError(ConfigError):
def __init__(self, message='Invalid .env file configuration for environment variable conversion'):
super(EnvConfigError, self).__init__(message)
|
Markdown
|
UTF-8
| 11,021 | 2.765625 | 3 |
[
"MIT"
] |
permissive
|
title: CodePush
date: 2016-03-23 11:24:22
tags: [iOS,ReactNative]
---
## 简介
[CodePush](http://codepush.tools)是提供给 React Native 和 Cordova 开发者直接部署移动应用更新给用户设备的云服务。CodePush 作为一个中央仓库,开发者可以推送更新到 (JS, HTML, CSS and images),应用可以从客户端 SDKs 里面查询更新。CodePush 可以让应用有更多的可确定性,也可以让你直接接触用户群。在修复一些小问题和添加新特性的时候,不需要经过二进制打包,可以直接推送代码进行实时更新。
[Git](https://github.com/Microsoft/code-push)
## 博主肺腑
比如一个ReactNative项目,发布后,根据产品需求我们需要修改一些东西,这时候需要更新App中的jsbundle文件(也有可能是一些图片资源)。起初我是自己处理的,程序启动取得jsbundle的md5,然后发给服务器,服务器再取出服务器中的jsbundle文件的md5进行对比,如不同则App后台下载jsbundle文件,下载完成后将路径写入UserDefault中以备下次载入的时候使用该路径的新文件。这里我们先不考虑加密压缩的问题,虽然满足正常的需求,不过当我遇见了CodePush,我就把我之前写的这些处理都注释掉了。
这里我说几点CodePush给我带来的惊喜:
1.CodePush集成到项目非常简单,推荐用RNPM,或者CocoaPods。
2.有History,就比如Git的log。
3.可以创建多个部署,可以按照需求针对不同的部署发布版本更新。
4.有回滚功能,并且有记录哪些用户更新了,哪些用户回滚了。
5.合作者功能。
## [CodePush CLI(终端工具)](https://github.com/Microsoft/code-push/blob/master/cli/README.md)
### 安装
```bash
npm install -g code-push-cli
```
### 注册账号/登录(Register/Login)
```bash
code-push register
```
终端输入以上命令会自动打开浏览器,进入注册界面,我使用的GitHub账号注册的。
注册成功后。终端`Ctrl`+`C`
```bash
Usage: code-push login [--accessKey <accessKey>]
示例:
code-push login
code-push login --acccessKey 7YHPoQSNBGkaEYTh3ln6HUPJz8EBVyB4C3Fal
```
终端输入`code-push login`命令还是会自动打开浏览器,但是会显示Access Key。这时候我们需要复制这个Key。
回到终端,可以看到提示你输入这个Access Key。复制粘贴进去,回车即可。
这里我解释下Access Key:可以简单的理解为Token(如果你们不知道Token,可以百度搜下)。CodePush CLI是允许你在多个设备登录你的账号,每个设备登录都会有一个唯一的Access Key,并且你可以管理这些Access Key,控制其它设备是否可以登录。
管理Access Key的命令:
```bash
Usage: code-push access-key <command>
命令:
add 添加一个新的Access Key
remove 删除一个已经存在的Access key
rm 删除一个已经存在的Access key
list 列出与你账户关联的所有Access key
ls 列出与你账户关联的所有Access key
```
#### 合作者(Collaborator)
这个功能还是很不错的。一个项目的开发肯定有很多人,也许有的人会负责一些部署的发布更新工作。你的账号又不可能都给他们吧,你可以通过这个功能让其他人也能参与到这个项目中。
命令:
```bash
Usage: code-push collaborator <command>
命令:
add 对指定的项目添加一个新的合作者
remove 删除指定的项目中的合作者
rm 删除指定的项目中的合作者
list 列出指定项目中的所有合作者
ls 列出指定项目中的所有合作者
示例:
code-push collaborator add AppDemo foo@bar.com 添加一个合作者foo@bar.com到AppDemo这个App中
```
### 在CodePush里创建App
```bash
Usage: code-push app add <AppName>
示例:
code-push app add AppDemo
```
其它命令:
```bash
Usage: code-push app <command>
命令:
add 创建一个新的App
remove 删除App
rm 删除App
rename 重命名已经存在App
list 列出与你账户关联的所有App
ls 列出与你账户关联的所有App
transfer 将一个App的所有权转让给另一个帐户
```
### 部署(Deployment)
App创建成功后会默认显示两个部署:`Production`和`Staging`。
这里解释下什么是部署:简单的说就是环境(如果你懂Git,你可以理解成Branch),比如ReactNative的jsbundle,iOS和Android是不可以共用一个的,所以我们需要生成两个jsbundle,而我们可以通过部署这个功能,创建两个部署:`AppDemo-iOS`和`AppDemo-Android`,并且App中分别使用这两个部署的Key,之后我们上传jsbundle只要分别上传到这两个部署中就可以了。
命令:
```bash
Usage: code-push deployment <command>
命令:
add 在已存在的App中创建一个部署
clear 清除与部署相关的发布历史记录
remove 在App中删除一个部署
rm 在App中删除一个部署
rename 重命名一个已存在的部署
list 列出App中的所有部署
ls 列出App中的所有部署
history 列出一个部署的发布历史记录
h 列出一个部署的发布历史记录
```
每个部署都有一个对应的`Deployment Key`,需要在项目中使用对应的Key。
#### 创建部署
```bash
Usage: code-push deployment add <appName> <deploymentName>
示例:
deployment add MyApp MyDeployment 添加一个部署"MyDeployment"到App"MyApp"中
```
#### 列出App中所有部署
```bash
Usage: code-push deployment ls <appName> [--format <format>] [--displayKeys]
选项:
--format 终端打印格式 ("json" or "table") [string] [默认值: "table"]
--displayKeys, -k 是否显示Deployment Key [boolean] [默认值: false]
示例:
code-push deployment ls MyApp
code-push deployment ls MyApp --format json
```
#### 查看部署的发布历史
```bash
Usage: code-push deployment h <appName> <deploymentName> [--format <format>] [--displayAuthor]
选项:
--format 终端打印格式 ("json" or "table") [string] [默认值: "table"]
--displayAuthor, -a 是否显示谁发布的 [boolean] [默认值: false]
示例:
code-push deployment h MyApp MyDeployment
code-push deployment h MyApp MyDeployment --format json
```
### 发布(Release)
官方的文档里写了三种:General,ReactNative,Cordova。
我这里就先将一个通用的,如果有时间再补上其它的。
#### 通用发布
```bash
Usage: code-push release <appName> <updateContentsPath> <targetBinaryVersion> [--deploymentName <deploymentName>] [--description <description>] [--mandatory] [--rollout <rolloutPercentage>]
选项:
--deploymentName, -d 部署名 [string] [默认值: "Staging"]
--description, --des 描述 [string] [默认值: null]
--disabled, -x 是否禁用该更新 [boolean] [默认值: false]
--mandatory, -m 是否强制更新 [boolean] [默认值: false]
--rollout, -r 此更新推送的的用户百分比 [string] [默认值: null]
示例:
code-push release MyApp app.js "*" 发布 "app.js"文件到"MyApp"的"Staging"部署中,针对任何二进制版本,它使用"*"通配符范围语法。
code-push release MyApp ./platforms/ios/www 1.0.3 -d Production 发布 "./platforms/ios/www"文件夹里的所有内容到"MyApp"的"Production"部署中, 只针对1.0.3的二进制版本
code-push release MyApp ./platforms/ios/www 1.0.3 -d Production -r 20 发布 "./platforms/ios/www"文件夹里的所有内容到"MyApp"的"Production"部署中, 只针对1.0.3的二进制版本,并且只推给20%的用户
```
说明下关于二进制版本的问题。
范围表达式|哪些会被更新
---|---
`1.2.3`|仅仅只有`1.2.3`的版本
`*`|所有版本
`1.2.x`|主要版本`1`,次要版本`2`的任何修补程序版本
`1.2.3 - 1.2.7`|`1.2.3`版本到`1.2.7`版本
`>=1.2.3 <1.2.7`|大于等于`1.2.3`版本小于`1.2.7`的版本
`~1.2.3`|大于等于`1.2.3`版本小于`1.3.0`的版本
`^1.2.3`|大于等于`1.2.3`版本小于`2.0.0`的版本
#### 修改更新(Patching Updates)
```bash
Usage: code-push patch <appName> <deploymentName> [--label <label>] [--description <description>] [--disabled] [--mandatory] [--rollout <rolloutPercentage>]
选项:
--label, -l 指定标签版本更新,默认最新版本 [string] [默认值: null]
--description, --des 描述 [string] [默认值: null]
--disabled, -x 是否禁用该更新 [boolean] [默认值: null]
--mandatory, -m 是否强制更新 [boolean] [默认值: null]
--rollout, -r 此更新推送用户的百分比,此值仅可以从先前的值增加。 [string] [默认值: null]
示例:
code-push patch MyApp Production --des "Updated description" -r 50 修改"MyApp"的"Production"部署中最新更新的描述 ,并且更新推送范围为50%
code-push patch MyApp Production -l v3 --des "Updated description for v3" 修改"MyApp"的"Production"部署中标签为v3的更新的描述
```
#### 促进更新(Promoting Updates)
也就是把其它部署中的最新更新发布到其它的部署中
```bash
Usage: code-push promote <appName> <sourceDeploymentName> <destDeploymentName> [--description <description>] [--mandatory] [--rollout <rolloutPercentage>]
选项:
--description, --des 描述 [string] [默认值: null]
--disabled, -x 是否禁用该更新 [boolean] [默认值: null]
--mandatory, -m 是否强制更新 [boolean] [默认值: null]
--rollout, -r 此促进更新推送用户的百分比 [string] [默认值: null]
示例:
code-push promote MyApp Staging Production "MyApp"中"Staging"部署的最新更新发布到"Production"部署中
code-push promote MyApp Staging Production --des "Production rollout" -r 25 "MyApp"中"Staging"部署的最新更新发布到"Production"部署中, 并且只推送25%的用户
```
#### 回滚更新(Rolling Back Updates)
```bash
Usage: code-push rollback <appName> <deploymentName> [--targetRelease <releaseLabel>]
选项:
--targetRelease, -r 指定回归到哪个标签,默认是回滚到上一个更新 [string] [默认值: null]
示例:
code-push rollback MyApp Production "MyApp"中"Production"部署执行回滚
code-push rollback MyApp Production --targetRelease v4 "MyApp"中"Production"部署执行回滚,回滚到v4这个标签版本
```
官方的列子:
Release|Description|Mandatory
---|---|---
v1|Initial release!|Yes
v2|Added new feature|No
v3|Bug fixes|Yes
v3这个更新出了点问题,需要回滚操作,回滚到v2.
执行回滚操作后History就变成这个样子了
Release|Description|Mandatory
---|---|---
v1|Initial release!|Yes
v2|Added new feature|No
v3|Bug fixes|Yes
v4 (Rollback from v3 to v2)|Added new feature|No
## 未完待续
|
Python
|
UTF-8
| 2,626 | 3.15625 | 3 |
[] |
no_license
|
import os
import re
#Divido el texto por oraciones
def div_oraciones(x):
return x.split('.')
#Me quedo solo con las oraciones con números, que son los que tienen datos
def numeros(x):
L =[]
for i in x:
if any(map(str.isdigit, i)):
L.append(i)
return(L)
#Uno los valores que estaban separados porque las unidades de millar estaban separadas por punto
def union(x):
i = 0
while i<len(x):
try:
if x[i][len(x[i])-1].isdigit():
if x[i+1][0].isdigit():
x[i]= x[i]+x[i+1]
x.remove(x[i+1])
else:
i+=1
else:
i+=1
except IndexError:
return(x)
return(x)
#Muestro mi lista con las oraciones con números
def printear(x):
for i in x:
print(i)
print(x)
print(len(x))
print('')
#Creo una lista que contiene las frases que tienen %, ya que para generar datos necesito proporciones
def porcentajes(x):
P = []
for i in x:
for j in i:
if j == '%':
P.append(i)
break
return(P)
#Compruebo si hay nombres de bancos con cifras, ya que me podrían indicar promedio o valor absoluto de viviendas que tienen ocupadas
def banks(x):
Bancos=['BBVA', 'Santander', 'Bankia', 'Caixa', 'Sabadell', 'Bankinter', 'Abanca', 'Caja Madrid']
B=[]
for i in x:
for j in Bancos:
if j in i:
B.append(i)
break
return(B)
#Guardar en un txt
def guardar_txt(x, y):
file = open("C:/Users/Fran/Desktop/tfg/Textos_procesados/"+y+".txt", "w",encoding='utf-8')
for i in x:
file.write(i+'\n')
file.close()
#Guardo en una variable el número de archivos de texto que tengo guardados para procesar
num_arch = sum([len(files) for r, d, files in os.walk("C:/Users/Fran/Desktop/tfg/Textos_bruto")])
#Creo un contador en 1, con el que recorreré todos los archivos
cont = 1
#Accedo a los archivos que hay en la carpeta de Textos_bruto, los proceso y los guardo en Textos_procesados
while cont<=num_arch:
cont_str = str(cont)
f = open ('C:/Users/Fran/Desktop/tfg/Textos_bruto/texto'+cont_str+'.txt','r',encoding='latin-1')
tx = f.read()
f.close()
aux = div_oraciones(tx)
L = numeros(aux)
L = union(L)
T = banks(L)
if len(T)!=0:
guardar_txt(T,'bancos'+cont_str+'')
L = porcentajes(L)
guardar_txt(L,'porcentajes_texto'+cont_str+'')
cont+=1
|
C++
|
UTF-8
| 388 | 2.546875 | 3 |
[] |
no_license
|
#ifndef GL_CYLINDER_H
#define GL_CYLINDER_H
#include "Mesh.h"
/* A mesh that represents a cylinder. The level of detail/smoothness
* can be specified in the constructor. */
class Cylinder : public Mesh
{
public:
Cylinder(float height, float radius, int numSegments);
virtual ~Cylinder();
TexCoord computeTexCoord(float angle, float currentHeight, float totalHeight);
};
#endif
|
Markdown
|
UTF-8
| 1,072 | 2.578125 | 3 |
[] |
no_license
|
---
layout: page
title: About
---
# About
Roboism is a podcast about robots, technology, and feminism, but mostly robots.
### Hosts
Alex and Savannah work out of the same co-working space. In the summer of 2015, they discovered a mutual love of robots, and figured the world ought to know. Thus, we have Roboism.
Shortly after launch, Roboism joined the Chicago Podcast Cooperative and have been happily affiliated ever since.
### Contact Us
If you'd like to get in touch, you can email <roboismcast@gmail.com>. Alternately you can reach out on twitter to both of us [@roboismcast](https://twitter.com/roboismcast) or individually, [@alexcox](https://twitter.com/alexcox) and [@savannahmillion](https://twitter.com/savannahmillion).
### Other Stuff
- Our catchy theme song is from [David and Kevin](http://davidandkevin.bandcamp.com/).
- Our site icons are from [Icomoon](https://icomoon.io/).
- This site was built with [Jekyll](http://jekyllrb.com/) and is hosted on [Github](https://github.com/savannahmillion/roboism) and [Soundcloud](https://soundcloud.com/roboismcast).
|
SQL
|
UTF-8
| 6,862 | 3.0625 | 3 |
[] |
no_license
|
-- phpMyAdmin SQL Dump
-- version 4.8.5
-- https://www.phpmyadmin.net/
--
-- Servidor: 127.0.0.1
-- Tiempo de generación: 21-04-2019 a las 17:26:54
-- Versión de PHP: 7.3.4
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Base de datos: `patacon_app`
--
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `administrator`
--
CREATE TABLE `administrator` (
`run` varchar(13) NOT NULL,
`name` text NOT NULL,
`email` varchar(320) NOT NULL,
`password` varchar(10) NOT NULL,
`position` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `driver`
--
CREATE TABLE `driver` (
`run` varchar(13) NOT NULL,
`name` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `job`
--
CREATE TABLE `job` (
`code` int(11) NOT NULL,
`location` text NOT NULL,
`variety` text NOT NULL,
`kilos` int(6) NOT NULL,
`container` text NOT NULL,
`harvest` int(11) NOT NULL,
`quality` int(11) NOT NULL,
`freight` int(11) NOT NULL,
`comment` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `location`
--
CREATE TABLE `location` (
`id_location` int(11) NOT NULL,
`ref_producer` varchar(13) NOT NULL,
`location_info` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `perform`
--
CREATE TABLE `perform` (
`ref_driver` varchar(13) NOT NULL,
`ref_trip` int(11) NOT NULL,
`ref_truck` varchar(6) NOT NULL,
`currentLoad` int(6) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `predefined_route`
--
CREATE TABLE `predefined_route` (
`id_route` int(11) NOT NULL,
`initalPoint` text NOT NULL,
`finalPoint` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `producer`
--
CREATE TABLE `producer` (
`rut` varchar(13) NOT NULL,
`name` text NOT NULL,
`manager` text NOT NULL,
`telephone` varchar(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `request_by`
--
CREATE TABLE `request_by` (
`ref_job` int(11) NOT NULL,
`ref_producer` varchar(13) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `trip`
--
CREATE TABLE `trip` (
`id_trip` int(11) NOT NULL,
`state` text NOT NULL,
`ref_job` int(11) NOT NULL,
`departurePlace` text NOT NULL,
`arrivalPlace` text NOT NULL,
`departureTime` time NOT NULL,
`arrivalTime` time NOT NULL,
`date` date NOT NULL,
`load` int(5) NOT NULL,
`coordinatedBy` varchar(13) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Estructura de tabla para la tabla `truck`
--
CREATE TABLE `truck` (
`licencePlate` varchar(6) NOT NULL,
`brand` text NOT NULL,
`model` text NOT NULL,
`year` int(4) NOT NULL,
`maxLoad` int(6) NOT NULL,
`color` text NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Índices para tablas volcadas
--
--
-- Indices de la tabla `administrator`
--
ALTER TABLE `administrator`
ADD PRIMARY KEY (`run`);
--
-- Indices de la tabla `driver`
--
ALTER TABLE `driver`
ADD PRIMARY KEY (`run`);
--
-- Indices de la tabla `job`
--
ALTER TABLE `job`
ADD PRIMARY KEY (`code`);
--
-- Indices de la tabla `location`
--
ALTER TABLE `location`
ADD PRIMARY KEY (`id_location`),
ADD KEY `location_ibfk_1` (`ref_producer`);
--
-- Indices de la tabla `perform`
--
ALTER TABLE `perform`
ADD KEY `ref_driver` (`ref_driver`),
ADD KEY `ref_trip` (`ref_trip`),
ADD KEY `ref_truck` (`ref_truck`);
--
-- Indices de la tabla `predefined_route`
--
ALTER TABLE `predefined_route`
ADD PRIMARY KEY (`id_route`);
--
-- Indices de la tabla `producer`
--
ALTER TABLE `producer`
ADD PRIMARY KEY (`rut`);
--
-- Indices de la tabla `request_by`
--
ALTER TABLE `request_by`
ADD KEY `ref_job` (`ref_job`),
ADD KEY `ref_producer` (`ref_producer`);
--
-- Indices de la tabla `trip`
--
ALTER TABLE `trip`
ADD PRIMARY KEY (`id_trip`),
ADD KEY `ref_job` (`ref_job`),
ADD KEY `coordinatedBy` (`coordinatedBy`);
--
-- Indices de la tabla `truck`
--
ALTER TABLE `truck`
ADD PRIMARY KEY (`licencePlate`);
--
-- AUTO_INCREMENT de las tablas volcadas
--
--
-- AUTO_INCREMENT de la tabla `job`
--
ALTER TABLE `job`
MODIFY `code` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT de la tabla `location`
--
ALTER TABLE `location`
MODIFY `id_location` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT de la tabla `predefined_route`
--
ALTER TABLE `predefined_route`
MODIFY `id_route` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT de la tabla `trip`
--
ALTER TABLE `trip`
MODIFY `id_trip` int(11) NOT NULL AUTO_INCREMENT;
--
-- Restricciones para tablas volcadas
--
--
-- Filtros para la tabla `location`
--
ALTER TABLE `location`
ADD CONSTRAINT `location_ibfk_1` FOREIGN KEY (`ref_producer`) REFERENCES `producer` (`rut`) ON DELETE CASCADE;
--
-- Filtros para la tabla `perform`
--
ALTER TABLE `perform`
ADD CONSTRAINT `perform_ibfk_1` FOREIGN KEY (`ref_driver`) REFERENCES `driver` (`run`),
ADD CONSTRAINT `perform_ibfk_2` FOREIGN KEY (`ref_trip`) REFERENCES `trip` (`id_trip`),
ADD CONSTRAINT `perform_ibfk_3` FOREIGN KEY (`ref_truck`) REFERENCES `truck` (`licencePlate`);
--
-- Filtros para la tabla `request_by`
--
ALTER TABLE `request_by`
ADD CONSTRAINT `request_by_ibfk_1` FOREIGN KEY (`ref_job`) REFERENCES `job` (`code`),
ADD CONSTRAINT `request_by_ibfk_2` FOREIGN KEY (`ref_producer`) REFERENCES `producer` (`rut`);
--
-- Filtros para la tabla `trip`
--
ALTER TABLE `trip`
ADD CONSTRAINT `trip_ibfk_1` FOREIGN KEY (`ref_job`) REFERENCES `job` (`code`),
ADD CONSTRAINT `trip_ibfk_2` FOREIGN KEY (`coordinatedBy`) REFERENCES `administrator` (`run`);
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
|
SQL
|
UTF-8
| 807 | 3.625 | 4 |
[] |
no_license
|
--This query joins on the address Base plus data we loaded with a polygon shape stored in the myshapes table
--This isn't necessary for the discovery tool to work. It is just an example of how to do a spatial join using the Addressbase data
SELECT pt.*, py.*
FROM os_address.addressbase pt
JOIN os_address.myshapes py
ON ST_Intersects(py.geom, pt.geom)
WHERE py.objectid = 1;
--This query identifies the max UPRN in the first 10M rows of data to allow the data to be extracted in batches of 10M
select max(subquery.uprn) from (select uprn from os_address.addressbase order by UPRN limit 10000000) as subquery;
--Use the result of that to adjust the where query
COPY (select * from os_address.addressbase where uprn > 100070163174) TO 'C:\OS\AddressBase\20200715_ABFLGB_p4.CSV' DELIMITER ',' CSV HEADER;
|
TypeScript
|
UTF-8
| 1,287 | 2.765625 | 3 |
[] |
no_license
|
// 在此处添加您的代码
enum PIN {
P0 = 3,
P1 = 2,
P2 = 1,
P8 = 18,
//P9 = 10,
P12 = 20,
P13 = 23,
P14 = 22,
P15 = 21,
};
//color=#6699CC
//% weight=10 color=#378CE1 icon="\uf101" block="URM09 Trig"
namespace trig {
//%block="get %pin pin ultrasonic sensor range units(cm)"
export function ultraSonic(pin: PIN): number {
let _pin;
switch (pin) {
case PIN.P0: _pin = DigitalPin.P0; break;
case PIN.P1: _pin = DigitalPin.P1; break;
case PIN.P2: _pin = DigitalPin.P2; break;
case PIN.P8: _pin = DigitalPin.P8; break;
case PIN.P12: _pin = DigitalPin.P12; break;
// case PIN.P10: _T = DigitalPin.P10; break;
case PIN.P13: _pin = DigitalPin.P13; break;
case PIN.P14: _pin = DigitalPin.P14; break;
case PIN.P15: _pin = DigitalPin.P15; break;
default: _pin = DigitalPin.P0; break;
}
pins.digitalWritePin(_pin, 0)
pins.digitalWritePin(_pin, 1)
control.waitMicros(10)
pins.digitalWritePin(_pin, 0)
let ultraSonic_d = pins.pulseIn(_pin, PulseValue.High,35000)
basic.pause(100)
return Math.round((0.03435*ultraSonic_d)/2.0)
}
}
|
Python
|
UTF-8
| 123 | 2.828125 | 3 |
[] |
no_license
|
def is_subset(lst1, lst2):
for i in lst1:
if i not in lst2:
return False
break
else:
return True
|
C#
|
UTF-8
| 5,256 | 2.609375 | 3 |
[
"MIT"
] |
permissive
|
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using RecipeApp.Shared.Models;
using RecipeApp.Shared.Settings;
using RecipeApp.UI.WPF.Models;
using RecipeApp.UI.WPF.Settings;
namespace RecipeApp.UI.WPF.Services
{
public class RecipeService: IRecipeService
{
private readonly IHttpClientService _httpClientService;
private readonly ApiSettings _settings;
/// <summary>
/// Creates a new instance of the <see cref="RecipeService"/>
/// </summary>
/// <param name="httpClientService"></param>
/// <param name="settings"></param>
public RecipeService(IHttpClientService httpClientService, ISettings settings)
{
_httpClientService = httpClientService;
_settings = settings.GetSection<ApiSettings>("RestApi");
}
/// <inheritdoc />
public async Task<ICollection<Recipe>> GetLastAddedRecipesAsync(int count)
{
var queryStrings = new List<QueryString>
{
new QueryString {QueryParameter = "Count", Value = count.ToString()},
new QueryString {QueryParameter = "From", Value = DateTime.UtcNow.AddDays(-30).ToString("yyyy-MM-dd HH:mm:ss")},
new QueryString {QueryParameter = "To", Value = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss")},
new QueryString {QueryParameter = "Sort", Value = "Date"},
new QueryString {QueryParameter = "SortOrder", Value = "1"}
};
var request = new Request
{
RequestUrl = _settings.ServerUrl,
Endpoint = _settings.RecipeEndpoint,
QueryStrings = queryStrings
};
return await GetRecipesAsync(request).ConfigureAwait(false);
}
/// <inheritdoc />
public async Task<ICollection<Recipe>> GetLatestTopRatedRecipesAsync(int count)
{
var queryStrings = new List<QueryString>
{
new QueryString {QueryParameter = "Count", Value = count.ToString()},
new QueryString {QueryParameter = "From", Value = DateTime.UtcNow.AddYears(-1).ToString("yyyy-MM-dd HH:mm:ss")},
new QueryString {QueryParameter = "To", Value = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss")},
new QueryString {QueryParameter = "Sort", Value = "Rating"},
new QueryString {QueryParameter = "SortOrder", Value = "1"}
};
var request = new Request
{
RequestUrl = _settings.ServerUrl,
Endpoint = _settings.RecipeEndpoint,
QueryStrings = queryStrings
};
return await GetRecipesAsync(request);
}
/// <inheritdoc />
public async Task<ICollection<Recipe>> GetLatestWorstRatedRecipesAsync(int count)
{
var queryStrings = new List<QueryString>
{
new QueryString {QueryParameter = "Count", Value = count.ToString()},
new QueryString {QueryParameter = "From", Value = DateTime.UtcNow.AddYears(-1).ToString("yyyy-MM-dd HH:mm:ss")},
new QueryString {QueryParameter = "To", Value = DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss")},
new QueryString {QueryParameter = "Sort", Value = "Rating"},
new QueryString {QueryParameter = "SortOrder", Value = "-1"}
};
var request = new Request
{
RequestUrl = _settings.ServerUrl,
Endpoint = _settings.RecipeEndpoint,
QueryStrings = queryStrings
};
return await GetRecipesAsync(request);
}
/// <inheritdoc />
public async Task<ICollection<Recipe>> GetTopRatedRecipesAsync(int count)
{
var queryStrings = new List<QueryString>
{
new QueryString {QueryParameter = "Count", Value = count.ToString()},
new QueryString {QueryParameter = "Sort", Value = "Rating"},
new QueryString {QueryParameter = "SortOrder", Value = "1"}
};
var request = new Request
{
RequestUrl = _settings.ServerUrl,
Endpoint = _settings.RecipeEndpoint,
QueryStrings = queryStrings
};
return await GetRecipesAsync(request);
}
/// <summary>
/// Gets a list of recipes based on a specific request with query strings
/// </summary>
/// <param name="request">The request with query strings</param>
/// <returns>A list of <see cref="Recipe"/>s or null if failure occurs.</returns>
private async Task<ICollection<Recipe>> GetRecipesAsync(Request request)
{
try
{
var result = await _httpClientService.GetAsync<ICollection<Recipe>>(request).ConfigureAwait(false);
return result;
}
catch (HttpRequestException hre)
{
Console.WriteLine(hre.Message);
return null;
}
}
}
}
|
Python
|
UTF-8
| 283 | 2.84375 | 3 |
[] |
no_license
|
import cv2
import imutils
img = cv2.imread("image.png")
cv2.imshow("origin", img)
#rotate 45도
rotated = imutils.rotate(img, 45)
cv2.imshow("rotate 45", rotated)
#rotate bound 45도
rotated = imutils.rotate_bound(img, 45)
cv2.imshow("rotate bound 45", rotated)
cv2.waitKey(0)
|
Java
|
UTF-8
| 2,592 | 2.28125 | 2 |
[] |
no_license
|
package pages;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.support.FindBy;
import org.openqa.selenium.support.ui.ExpectedConditions;
import java.util.List;
import java.util.logging.Logger;
public class SearchPage extends Page {
private static final Logger log = Logger.getLogger(String.valueOf(SearchPage.class));
public SearchPage(PageManager pages) {
super(pages);
}
@FindBy(xpath = "//div[contains(@class, 'col-md-6')]/p")
WebElement searchedForProductCount;
@FindBy(xpath = "//span[@class = 'discount-percentage']")
List<WebElement> discountOfProductWithDiscount;
@FindBy(xpath = "//span[@class = 'discount-percentage']/preceding-sibling::span")
List<WebElement> productWithDiscountRegularPrice;
@FindBy(xpath = "//span[@class = 'discount-percentage']/following-sibling::span")
List<WebElement> productWithDiscountPriceWithDiscount;
@FindBy(xpath = "//div[@class = 'product-price-and-shipping']")
List<WebElement> searchedProductsList;
@FindBy(xpath = "//div[@class = 'product-price-and-shipping']/span[1]")
List<WebElement> productRegularPriceList;
@FindBy(xpath = "//div[@class = 'product-price-and-shipping']/span[contains(@itemprop, 'price')]")
List<WebElement> searchedProductsListPrice;
@FindBy(xpath = "(//i[@class = 'material-icons pull-xs-right'])")
WebElement sortingButton;
@FindBy(xpath = "(//div[@class = 'dropdown-menu']/a)[last()]")
WebElement fromHighToLowPriceField;
public String getTextFromSearchedForField(){
return searchedForProductCount.getText();
}
public List getSearchedProductList(){
return searchedProductsList;
}
public List getSearchedProductListPrice(){
return searchedProductsListPrice;
}
public void clickOnSortingButton(){
sortingButton.click();
log.info("click on the sorting field");
}
public void clickOnFromHighToLowSortingField(){
wait.until(ExpectedConditions.visibilityOf(fromHighToLowPriceField));
fromHighToLowPriceField.click();
log.info("click on the sorting from High to Low price field");
}
public List getProductRegularPriceList(){
return productRegularPriceList;
}
public List getDiscountOfSaleProduct(){
return discountOfProductWithDiscount;
}
public List getDiscountProductRegularPrice(){
return productWithDiscountRegularPrice;
}
public List getDiscountProductPriceWithDiscount(){
return productWithDiscountPriceWithDiscount;
}
}
|
Python
|
UTF-8
| 284 | 2.65625 | 3 |
[] |
no_license
|
# -*- coding: utf-8 -*-
import math
import sys
import collections
last = (4, 6)
for i in xrange(1):
print 0 + last[0], 0 + last[1]
print -3 + last[0], 0 + last[1]
print -3 + last[0], -4 + last[1]
print -2 + last[0], -1 + last[1]
last = (2 + last[0], 4 + last[1])
|
Python
|
UTF-8
| 530 | 2.9375 | 3 |
[] |
no_license
|
import json
import requests
from binascii import unhexlify
encrypted_flag = requests.get(f'http://aes.cryptohack.org/block_cipher_starter/encrypt_flag/')
ciphertext = json.loads(encrypted_flag.content)['ciphertext']
print("Ciphertext : {}".format(ciphertext))
plaintext_hex = requests.get(f'http://aes.cryptohack.org/block_cipher_starter/decrypt/{ciphertext}/')
plaintext = (json.loads(plaintext_hex.content)['plaintext'])
print("Plaintext : {}".format(plaintext))
print("Flag : {}".format(unhexlify(plaintext)))
|
C++
|
UTF-8
| 3,445 | 3.265625 | 3 |
[] |
no_license
|
class max_heap {
vector<int> index; // id -> index into values
vector<pair<int, int>> values; // first is the height, second is id
int size;
void swap_node(int index1, int index2) {
swap(index[values[index1].second], index[values[index2].second]);
swap(values[index1], values[index2]);
}
// idx for values vector
void heapify_up(int idx) {
while (idx != 0) {
int parent = (idx - 1) / 2;
if (values[idx].first <= values[parent].first)
return;
swap_node(idx, parent);
idx = parent;
}
}
// idx for values vector
void heapify_down(int idx) {
while (true) {
int l = idx * 2 + 1;
int r = idx * 2 + 2;
int largest = idx;
if (l < size && values[l].first > values[idx].first)
largest = l;
if (r < size && values[r].first > values[largest].first)
largest = r;
if (largest == idx)
return;
swap_node(largest, idx);
idx = largest;
}
}
public:
max_heap(int s): index(s), values(s), size(0) {}
// O(1)
int max() const {
return values[0].first;
}
// O(logn)
void insert(int height, int id) {
index[id] = size;
values[size] = {height, id};
++size;
heapify_up(index[id]);
}
// O(logn)
void remove(int id) {
int index_to_remove = index[id];
swap_node(index_to_remove, size - 1);
--size;
// heapify_up(index_to_remove);
heapify_down(index_to_remove);
}
};
class Solution {
public:
// Time: O(nlogn)
// Space: O(n)
// entering and leaving point with the same x, process the entering point first -> set height of entering point to a negative value, and set height of leaving point to a positive value
// entering point with same x, process the highest point first -> set height of entering point to a negative value
// leaving point with same x, process the lowest point first -> set height of leaving point to a positive value
vector<vector<int>> getSkyline(vector<vector<int>>& buildings) {
vector<vector<int>> res;
vector<Point> points;
for (int i = 0; i < buildings.size(); ++i) {
const auto & b = buildings[i];
points.push_back(Point{i + 1, b[0], -b[2]});
points.push_back(Point{i + 1, b[1], b[2]});
}
sort(points.begin(), points.end());
max_heap heap(buildings.size() + 1); // plus one for the zero
heap.insert(0, 0); // height 0, id 0
int pre = 0, cur = 0;
for (auto & p : points) {
if (p.h < 0) {
if (-p.h > heap.max())
res.push_back({p.x, -p.h});
heap.insert(-p.h, p.id);
} else {
heap.remove(p.id);
if (p.h > heap.max())
res.push_back({p.x, heap.max()});
}
}
return res;
}
private:
struct Point {
int id;
int x;
int h;
bool operator<(const Point & rhs) const {
if (x == rhs.x) {
return h < rhs.h;
}
return x < rhs.x;
}
};
};
|
Markdown
|
UTF-8
| 893 | 2.671875 | 3 |
[] |
no_license
|
# flutter-web-example project
## Architecture
Bloc architecture is used for flutter-web-example. Bloc architecture separates the view (main_page.dart) from the business logic (model/letter_creator.dart) through a bloc class (bloc/letter_bloc.dart) that is inherited in child widgets through a provider pattern. A stream and function call to update the printed letters is exposed to the view by the bloc, and by using a StreamBuilder widget, only the text widget is rebuilt on each update call. This is done without any handlers or calls to setState() in the view class.
Fonts and icons are in the top level assets/ folder.
## Deployment
To deploy flutter-web-example, run the command "flutter build web", and host the contents of build/web/ on the platform of your choice.
## Dev
To run in debug mode, run the command "flutter run -d chrome". You can hot restart with "r" in the terminal.
|
JavaScript
|
UTF-8
| 1,138 | 3.765625 | 4 |
[] |
no_license
|
/**
* @param {ListNode} l1
* @param {ListNode} l2
* @return {ListNode}
*/
function ListNode(val) {
this.val = val;
this.next = null;
}
const mergeTwoLists = function (l1, l2) {
let new_node;
if (l1 && l2) {
if (l1.val < l2.val) {
new_node = l1;
l1 = l1.next
}
else {
new_node = l2;
l2 = l2.next
}
} else if (l1) return l1; else return l2;
let head = new_node;
while (l1 || l2) {
if (!l1) {
new_node.next = l2;
return head;
}
if (!l2) {
new_node.next = l1;
return head;
}
if (l1.val < l2.val) {
new_node.next = l1;
new_node = new_node.next;
l1 = l1.next;
} else {
new_node.next = l2;
new_node = new_node.next;
l2 = l2.next;
}
}
return head;
};
let a = new ListNode(1);
a.next = new ListNode(2);
a.next.next = new ListNode(4);
let b = new ListNode(1);
b.next = new ListNode(3);
b.next.next = new ListNode(4);
console.log(mergeTwoLists(a, b));
|
Ruby
|
UTF-8
| 631 | 3.390625 | 3 |
[] |
no_license
|
class PhoneNumber
attr_reader :number
def initialize(value)
clean_number(value)
end
def area_code
@number[0..2]
end
def to_s
"(#{area_code}) #{@number[3..5]}-#{@number[6..9]}"
end
private
def clean_number(value)
@number = value.to_s
remove_non_digits
pop_one_off_eleven_digits
validate_length
end
private
def remove_non_digits
@number.gsub!(/\D/, '')
end
private
def pop_one_off_eleven_digits
@number.sub!(/^./,'') if @number.size == 11 && number[0] == '1'
end
private
def validate_length
@number = '0000000000' unless @number.size == 10
end
end
|
Shell
|
UTF-8
| 766 | 3.484375 | 3 |
[] |
no_license
|
#!/bin/bash
pushd ${0%/*}
ZOTONIC_SRC=${ZOTONIC_SRC:=/home/kaos/zotonic}
# /path/to/zotonic/modules/<mod>/scomps/scomp_<mod>_scomp_name.erl
for f in `find $ZOTONIC_SRC/modules -name scomp_\*`
do
read -r mod scomp <<EOF
`echo $f | sed -e 's,.*/mod_\([^/]*\).*/scomp_\1_\(.*\).erl,mod_\1 \2,'`
EOF
echo mod: $mod scomp: $scomp
cat <<EOF > scomp_$scomp.rst
.. This file is generated.
To document this scomp, edit the doc-$scomp.rst file, which is included in this file.
$scomp
${scomp//?/=}
* Module: :doc:\`../$mod\`
.. include:: doc-$scomp.rst
EOF
cat <<EOF >> ../meta-$mod.rst
* Scomp: :doc:\`scomps/scomp_$scomp\`
EOF
if [ ! -e doc-$scomp.rst ]; then
cat <<EOF > doc-$scomp.rst
Not yet documented.
EOF
fi
done
popd
|
JavaScript
|
UTF-8
| 326 | 3.203125 | 3 |
[
"Apache-2.0"
] |
permissive
|
timer = null; // stores ID of interval timer
function delayMsg() {
if (timer === null) {
timer = setInterval(rudy, 1000);
} else {
clearInterval(timer);
timer = null;
}
}
function rudy() { // called each time the timer goes off
document.getElementById("output").innerHTML += "Rudy!";
}
|
Python
|
UTF-8
| 16,841 | 3.171875 | 3 |
[] |
no_license
|
# imports
import pandas
import numpy
import matplotlib.pyplot as plt
from pip._vendor.distlib.compat import raw_input
import sklearn.model_selection
def perceptron(x, t, maxepochs, beta): # perceptron function
w = numpy.random.randn(len(x[0]), 1) # filling the w by random numbers
flag = True # initializing the flag
epoch = 1 # initializing the epoch
u = numpy.zeros(len(x)) # initializing the u array
predict = numpy.zeros(len(x)) # initializing the predict list
while (maxepochs >= epoch) & flag:
flag = False
for i in range(len(x)): # for each i in x len
u[i] = sum(w[j] * x[i, j] for j in range(len(x[0]))) # finding the stimulation
if u[i] < 0: # if u[0] is lower than 0
predict[i] = 0 # we give predict the value of 0
else: # in any other case
predict[i] = 1 # we give predict the value of 1
if predict[i] != t[i]: # if predict is not equal to t
for j in range(0, len(w)): # for each w
w[j] = w[j] + beta * (t[i] - predict[i]) * x[i, j] # giving new value to our w
flag = True # if we find an error, we make the flag true again
epoch += 1
plt.figure() # creating new figure
plt.plot(predict, 'ro', t, 'b.') # red circles for the predict array and blue dots for the t array
plt.title('perceptron view') # just the title of our plt figure
plt.show() # showing our plt figure
def adaline(x, t, maxepochs, beta, minmse):
w = numpy.random.randn(len(x[0]), 1) # filling the w by random numbers
epoch = 1 # initializing the epoch
u = numpy.zeros(len(x)) # initializing the u array
predict = numpy.zeros(len(x)) # initializing the predict list
while maxepochs >= epoch:
error = 0
for i in range(len(x)): # for each i in x len
u[i] = sum(w[j] * x[i, j] for j in range(len(x[0]))) # finding the stimulation
if u[i] < 0: # if u[0] is lower than 0
predict[i] = -1 # we give predict the value of 0
else: # in any other case
predict[i] = 1 # we give predict the value of 1
error = error + (t[i] - predict[i]) ** 2 # adding the error for each loop
for j in range(0, len(w)): # for each w
w[j] = w[j] + beta * (t[i] - predict[i]) * x[i, j] # giving new value to our w
if error / len(x) <= minmse:
break
epoch += 1
plt.figure() # creating new figure
plt.plot(predict, 'ro', t, 'b.') # red circles for the predict array and blue dots for the t array
plt.title('adaline view') # just the title of our plt figure
plt.show() # showing our plt figure
if __name__ == '__main__':
data = pandas.read_csv('iris.data', header=None).values # reading from the csv file
flowerInfo = {
'numberOfPatterns': numpy.shape(data)[0], # dictionary array for patterns
'numberOfAttributes': numpy.shape(data)[1] # and attributes
}
x = data[:, :4] # giving the values of the flowers without the name
names = data[:, 4] # giving the names without the values
plt.plot(x[0:50, 0], x[0:50, 2],
'b.') # blue dot, different colors for different types that change every 50 in this case
plt.plot(x[50:100, 0], x[50:100, 2], 'r.') # red dot
plt.plot(x[100:150, 0], x[100:150, 2], 'g.') # green dot
plt.title('Graph of all Patterns') # title of the graph
plt.show() # showing the graph
t = numpy.zeros(flowerInfo['numberOfPatterns'], dtype=int) # giving the table t the value of 150 with zeros
ans = 'y' # giving the ans the value of y
flag = True
while ans == 'y': # while ans is y
print('1.Διαχωρισμός Iris-setosa από (Iris-versicolor και Iris-virginica)\n'
'2.Διαχωρισμός Iris-virginica από (Iris-setosa και Iris-versicolor)\n'
'3.Διαχωρισμός Iris-versicolor από (Iris-setosaκαιIris-virginica)') # printing the menu
userInput = int(raw_input()) # user input
if userInput == 1: # if user input = 1
map_dictionary = { # creating dictionary 1 0 0
"Iris-setosa": 1,
"Iris-versicolor": 0,
"Iris-virginica": 0
}
for i in range(0, len(t)): # for i from 0 to length of t
t[i] = map_dictionary[names.item(i)] # did stuff that I cannot explain
elif userInput == 2: # for i from 0 to length of t
map_dictionary = { # creating dictionary 0 1 0
"Iris-setosa": 0,
"Iris-versicolor": 0,
"Iris-virginica": 1
}
for i in range(0, len(t)):
t[i] = map_dictionary[names.item(i)] # did stuff that I cannot explain
elif userInput == 3: # for i from 0 to length of t
map_dictionary = { # creating dictionary 0 0 1
"Iris-setosa": 0,
"Iris-versicolor": 1,
"Iris-virginica": 0
}
for i in range(0, len(t)):
t[i] = map_dictionary[names.item(i)] # did stuff that I cannot explain
if flag:
x = numpy.hstack((x, numpy.atleast_2d(numpy.ones(150)).T)) # adding one more column of 1 in the x list
flag = False
xtrain = x[0:40] # initializing the xtrain array
xtrain = numpy.vstack((xtrain, x[50:90], x[100:140])) # extending the array
xtest = x[40:50] # initializing the xtest array
xtest = numpy.vstack((xtest, x[90:100], x[140:150])) # extending the array
ttrain = t[0:40] # initializing the array
ttrain = numpy.hstack((ttrain, t[50:90], t[100:140])) # extending the array
ttest = t[40:50] # initializing the xtest array
ttest = numpy.hstack((ttest, t[90:100], t[140:150])) # extending the array
plt.plot(xtrain[:, 0], xtrain[:, 2], 'b.') # creating the diagrams
plt.plot(xtest[:, 0], xtest[:, 2], 'r.') # creating the diagrams
plt.title('xtrain ttest patterns') # giving a title to our graph
plt.show() # showing the graph
while True:
print('1. Υλοποίηση με Perceptron\n' +
'2. Υλοποίηση με Adaline\n' +
'3. Υλοποίηση με Λύση Ελαχίστων Τετραγώνων\n' +
'4. Επιστροφή στο αρχικό Menu') # printing the available options
userInput = int(raw_input()) # user input
if userInput == 4: # if userInput is 4, we break the while
break
elif userInput == 1:
maxepochs = int(raw_input('Max Epochs:')) # max seasons
beta = float(raw_input('Beta:')) # beta variable
perceptron(xtrain, ttrain, maxepochs, beta) # calling the perceptron for both xtrain, ttrain
perceptron(xtest, ttest, maxepochs, beta) # and xtest, ttest
for i in range(9):
x_train, x_test, t_train, t_test = sklearn.model_selection.train_test_split(x, t,
test_size=0.1) # train_test_split
plt.figure() # creating a new view or something
plt.subplot(211) # just like a plot, but different, rows, cols
plt.plot(x_train[:, 0], x_train[:, 2], "b.") # x, y, color
plt.title("x_train with Train_Test_Split Perceptron") # the title of our plt graph
plt.subplot(212) # just like a plot, but different, rows, cols
plt.plot(x_test[:, 0], x_test[:, 2], "r.") # x, y, color
plt.title("x_test with Train_Test_Split Perceptron") # the title of our plt graph
plt.tight_layout() # to make it appear normal
plt.show() # showing the graph
perceptron(x_train, t_train, maxepochs, beta) # calling the perceptron for both x_train, t_train
perceptron(x_test, t_test, maxepochs, beta) # calling the perceptron for both x_test, t_test
elif userInput == 2:
ttrain2 = [i if i != 0 else -1 for i in ttrain] # changing 0 values to -1
ttest2 = [i if i != 0 else -1 for i in ttest] # changing 0 values to -1
maxepochs = int(raw_input('Max Epochs:')) # max seasons
beta = float(raw_input('Beta:')) # beta variable
minmse = float(raw_input('MinMSE:')) # minmse input
adaline(xtrain, ttrain2, maxepochs, beta, minmse) # calling the adaline for both xtrain and ttrain
adaline(xtest, ttest2, maxepochs, beta, minmse) # and xtest, ttest
for i in range(9):
x_train, x_test, t_train, t_test = sklearn.model_selection.train_test_split(x, t,
test_size=0.1) # train_test_split
t_train = [i if i != 0 else -1 for i in t_train] # changing 0 values to -1
t_test = [i if i != 0 else -1 for i in t_test] # changing 0 values to -1
plt.figure() # creating a new view or something
plt.subplot(211) # just like a plot, but different, rows, cols
plt.plot(x_train[:, 0], x_train[:, 2], "b.") # x, y, color
plt.title("x_train with Train_Test_Split Adaline") # the title of our plt graph
plt.subplot(212) # just like a plot, but different, rows, cols
plt.plot(x_test[:, 0], x_test[:, 2], "r.") # x, y, color
plt.title("x_test with Train_Test_Split Adaline") # the title of our plt graph
plt.tight_layout() # to make it appear normal
plt.show() # showing the graph
adaline(x_train, t_train, maxepochs, beta, minmse) # calling the adaline for both x_train, t_train
adaline(x_test, t_test, maxepochs, beta, minmse) # calling the adaline for both x_test, t_test
elif userInput == 3:
ttrain2 = [i if i != 0 else -1 for i in ttrain] # changing 0 values to -1
ttest2 = [i if i != 0 else -1 for i in ttest] # changing 0 values to -1
xtrain2 = numpy.linalg.pinv(xtrain.astype(float)) # pinv = pseudo inverse
w = numpy.zeros(len(xtrain[0])) # giving 0 to the w array
predict = numpy.zeros(len(xtrain)) # initializing
for i in range(len(w)): # for each of the 4 elements in our w array
w[i] = sum(xtrain2[i, j] * ttrain2[j] for j in range(len(xtrain))) # finding the weights
for i in range(len(xtrain)): # for each pattern
u = sum(w[j] * xtrain[i, j] for j in range(len(w))) # initializing the stimulation
if u < 0:
predict[i] = -1 # giving the proper value
else:
predict[i] = 1 # giving the proper value
plt.figure() # creating new figure
plt.plot(predict, 'ro', ttrain2,
'b.') # red circles for the predict array and blue dots for the ttrain2 array
plt.title('least square solution view') # just the title of our plt figure
plt.show() # showing our plt figure
# edw stamatise o kosmos
xtest2 = numpy.linalg.pinv(xtest.astype(float)) # pinv = pseudo inverse
w2 = numpy.zeros(len(xtest[0])) # giving 0 to the w array
predict2 = numpy.zeros(len(xtest)) # initializing
for i in range(len(w2)): # for each of the 4 elements in our w array
w2[i] = sum(xtest2[i, j] * ttest2[j] for j in range(len(xtest))) # finding the weights
for i in range(len(xtest)): # for each pattern
u = sum(w2[j] * xtest[i, j] for j in range(len(w2))) # initializing the stimulation
if u < 0:
print(u)
predict2[i] = -1 # giving the proper value
else:
print(u)
predict2[i] = 1 # giving the proper value
plt.figure() # creating new figure
plt.plot(predict2, 'ro', ttest2,
'b.') # red circles for the predict array and blue dots for the ttrain2 array
plt.title('least square solution view') # just the title of our plt figure
plt.show() # showing our plt figure
for i in range(9):
x_train, x_test, t_train, t_test = sklearn.model_selection.train_test_split(x, t,
test_size=0.1) # train_test_split
t_train = [i if i != 0 else -1 for i in t_train] # changing 0 values to -1
t_test = [i if i != 0 else -1 for i in t_test] # changing 0 values to -1
plt.figure() # creating a new view or something
plt.subplot(211) # just like a plot, but different, rows, cols
plt.plot(x_train[:, 0], x_train[:, 2], "b.") # x, y, color
plt.title("x_train with Train_Test_Split Adaline") # the title of our plt graph
plt.subplot(212) # just like a plot, but different, rows, cols
plt.plot(x_test[:, 0], x_test[:, 2], "r.") # x, y, color
plt.title("x_test with Train_Test_Split Adaline") # the title of our plt graph
plt.tight_layout() # to make it appear normal
plt.show() # showing the graph
xtrain2 = numpy.linalg.pinv(x_train.astype(float)) # pinv = pseudo inverse
w = numpy.zeros(len(x_train[0])) # giving 0 to the w array
predict = numpy.zeros(len(x_train)) # initializing
for i in range(len(w)): # for each of the 4 elements in our w array
w[i] = sum(xtrain2[i, j] * t_train[j] for j in range(len(x_train))) # finding the weights
for i in range(len(x_train)): # for each pattern
u = sum(w[j] * x_train[i, j] for j in range(len(w))) # initializing the stimulation
if u < 0:
predict[i] = -1 # giving the proper value
else:
predict[i] = 1 # giving the proper value
plt.figure() # creating new figure
plt.plot(predict, 'ro', t_train,
'b.') # red circles for the predict array and blue dots for the ttrain2 array
plt.title('least square solution view') # just the title of our plt figure
plt.show() # showing our plt figure
# edw stamatise o kosmos
xtest2 = numpy.linalg.pinv(x_test.astype(float)) # pinv = pseudo inverse
w2 = numpy.zeros(len(x_test[0])) # giving 0 to the w array
predict2 = numpy.zeros(len(x_test)) # initializing
for i in range(len(w2)): # for each of the 4 elements in our w array
w2[i] = sum(xtest2[i, j] * t_test[j] for j in range(len(x_test))) # finding the weights
for i in range(len(x_test)): # for each pattern
u = sum(w2[j] * x_test[i, j] for j in range(len(w2))) # initializing the stimulation
if u < 0:
print(u) # just a print
predict2[i] = -1 # giving the proper value
else:
print(u) # just a print
predict2[i] = 1 # giving the proper value
plt.figure() # creating new figure
plt.plot(predict2, 'ro', t_test,
'b.') # red circles for the predict array and blue dots for the ttrain2 array
plt.title('least square solution view') # just the title of our plt figure
plt.show() # showing our plt figure
elif userInput == 4:
break
ans = raw_input("Θέλετε να Συνεχίσετε(Y/n); ").lower()
# THIS IS THE END
|
C#
|
UTF-8
| 1,609 | 2.578125 | 3 |
[] |
no_license
|
using Microsoft.Kinect;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Numerics;
using System.Xml.Serialization;
namespace Kinect_ing_Pepper.Models
{
public class BodyFrameWrapper
{
public System.Numerics.Vector4 FloorClipPlane;
private TimeSpan _relativeTime;
[XmlIgnore]
public TimeSpan RelativeTime
{
get { return _relativeTime; }
set { _relativeTime = value; }
}
public long RelativeTimeTicks
{
get { return _relativeTime.Ticks; }
set { _relativeTime = new TimeSpan(value); }
}
private string _relativeTimeString;
public string RelativeTimeString
{
get
{
_relativeTimeString = RelativeTime.ToString();
return _relativeTimeString;
}
set { _relativeTimeString = value; }
}
public List<BodyWrapper> TrackedBodies;
public BodyFrameWrapper() { }
public BodyFrameWrapper(BodyFrame bodyFrame)
{
FloorClipPlane = new System.Numerics.Vector4(bodyFrame.FloorClipPlane.X, bodyFrame.FloorClipPlane.Y, bodyFrame.FloorClipPlane.Z, bodyFrame.FloorClipPlane.W);
RelativeTime = bodyFrame.RelativeTime;
Body[] bodies = new Body[bodyFrame.BodyCount];
bodyFrame.GetAndRefreshBodyData(bodies);
TrackedBodies = bodies.Where(x => x.IsTracked).Select(x => new BodyWrapper(x)).ToList();
}
}
}
|
JavaScript
|
UTF-8
| 4,328 | 2.515625 | 3 |
[
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
/*
Copyright 2019 Adobe Inc. All rights reserved.
This file is licensed to you 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 REPRESENTATIONS
OF ANY KIND, either express or implied. See the License for the specific language
governing permissions and limitations under the License.
*/
const TheHelper = require('../src/runtime-helpers.js')
describe('RuntimeHelper has the right functions', () => {
test('exports', () => {
expect(typeof TheHelper).toEqual('object')
expect(typeof TheHelper.createKeyValueArrayFromFile).toEqual('function')
expect(typeof TheHelper.createKeyValueArrayFromFlag).toEqual('function')
expect(typeof TheHelper.createKeyValueObjectFromFile).toEqual('function')
expect(typeof TheHelper.createKeyValueObjectFromFlag).toEqual('function')
expect(typeof TheHelper.parsePathPattern).toEqual('function')
})
})
beforeAll(() => {
const json = {
'file.json': fixtureFile('/trigger/parameters.json')
}
fakeFileSystem.addJson(json)
})
afterAll(() => {
// reset back to normal
fakeFileSystem.reset()
})
describe('createKeyValueArrayFromFlag', () => {
test('fail when flag length is odd', (done) => {
try {
TheHelper.createKeyValueArrayFromFlag(['key1'])
done.fail('should throw an error')
} catch (err) {
expect(err).toMatchObject(new Error('Please provide correct values for flags'))
done()
}
})
test('array of key:value (string) pairs', () => {
const res = TheHelper.createKeyValueArrayFromFlag(['name1', 'val1', 'name2', 'val2'])
expect(res).toMatchObject([{ key: 'name1', value: 'val1' }, { key: 'name2', value: 'val2' }])
})
test('array of key:value (object) pairs', () => {
const res = TheHelper.createKeyValueArrayFromFlag(['name1', '["val0","val1"]', 'name2', 'val2'])
expect(typeof res[0].value).toEqual('object')
expect(res).toMatchObject([{ key: 'name1', value: ['val0', 'val1'] }, { key: 'name2', value: 'val2' }])
})
})
describe('createKeyValueObjectFromFlag', () => {
test('fail when flag length is odd', (done) => {
try {
TheHelper.createKeyValueObjectFromFlag(['key1'])
done.fail('should throw an error')
} catch (err) {
expect(err).toMatchObject(new Error('Please provide correct values for flags'))
done()
}
})
test('array of key:value (string) pairs', () => {
const res = TheHelper.createKeyValueObjectFromFlag(['name1', 'val1', 'name2', 'val2'])
expect(res).toMatchObject({ name1: 'val1', name2: 'val2' })
})
test('array of key:value (object) pairs', () => {
const res = TheHelper.createKeyValueObjectFromFlag(['name1', '["val0","val1"]', 'name2', 'val2'])
expect(typeof res).toEqual('object')
expect(res).toMatchObject({ name1: ['val0', 'val1'], name2: 'val2' })
})
})
describe('createKeyValueArrayFromFile', () => {
test('array of key:value pairs', () => {
const res = TheHelper.createKeyValueArrayFromFile('/file.json')
expect(typeof res).toEqual('object')
expect(res).toMatchObject([{ key: 'param1', value: 'param1value' }, { key: 'param2', value: 'param2value' }])
})
})
describe('createKeyValueObjectFromFile', () => {
test('object with key:value pairs', () => {
const res = TheHelper.createKeyValueObjectFromFile('/file.json')
expect(typeof res).toEqual('object')
expect(res).toMatchObject({ param1: 'param1value', param2: 'param2value' })
})
})
describe('parsePathPattern', () => {
// expect(Vishal)toWriteThis()
test('test with namespace and name in path', () => {
const [, namespace, name] = TheHelper.parsePathPattern('/53444_28782/name1')
expect(typeof namespace).toEqual('string')
expect(namespace).toEqual('53444_28782')
expect(typeof name).toEqual('string')
expect(name).toEqual('name1')
})
test('test with only name in path', () => {
const [, namespace, name] = TheHelper.parsePathPattern('name1')
expect(namespace).toEqual(null)
expect(typeof name).toEqual('string')
expect(name).toEqual('name1')
})
})
|
C++
|
UTF-8
| 1,892 | 2.78125 | 3 |
[] |
no_license
|
#pragma once
#include "input_layer.h"
namespace tiny_cnn {
class layers {
public:
layers() { add(std::make_shared<input_layer>()); }
layers(const layers& rhs) { construct(rhs); }
layers& operator = (const layers& rhs) {
layers_.clear();
construct(rhs);
return *this;
}
/**** input new_tail to layers ********/
void add(std::shared_ptr<layer_base> new_tail) {
if (tail()) tail()->connect(new_tail);
layers_.push_back(new_tail);
}
//getter
size_t depth() const {
return layers_.size() - 1;
}
bool empty() const { return layers_.size() == 0; }
layer_base* head() const { return empty() ? 0 : layers_[0].get(); }
layer_base* tail() const { return empty() ? 0 : layers_[layers_.size() - 1].get(); }
template <typename T>
const T& at(size_t index) const {
const T* v = dynamic_cast<const T*>(layers_[index + 1].get());
if (v) return *v;
throw nn_error("failed to cast");
}
const layer_base* operator[](size_t index) const {
return layers_[index + 1].get();
}
layer_base* operator[] (size_t index) {
return layers_[index + 1].get();
}
void init_weight() {
for (auto p1 : layers_) {
p1->init_weight();
}
}
bool is_exploded() const {
for (auto pl : layers_) {
if (pl->is_exploded()) return true;
}
return false;
}
template <typename Optimizer>
void update_weights(Optimizer *o, size_t worker_size, size_t batch_size) {
for (auto pl : layers_) {
pl->update_weight(o, worker_size, batch_size);
}
}
void set_parallelize(bool parallelize) {
for (auto pl : layers_) {
pl->set_parallelize(parallelize);
}
}
public:
void construct(const layers& rhs) {
add(std::make_shared<input_layer>());
for (size_t i = 1; i < rhs.layers_.size(); i++)
add(rhs.layers_[i]);
}
std::vector<std::shared_ptr<layer_base>> layers_;
};
}//namespace tiny_cnn
|
JavaScript
|
UTF-8
| 1,500 | 3.046875 | 3 |
[
"MIT"
] |
permissive
|
/*
存储localstorage时候最好是封装一个自己的键值,在这个值里存储自己的内容对象,封装一个方法针对自己对象进行操作。避免冲突也会在开发中更方便。
*/
export default (function mystorage () {
let ms = 'mystorage'
let storage = window.localStorage
if (!window.localStorage) {
alert('浏览器支持localstorage')
return false
}
let set = function (key, value) {
// 存储
let mydata = storage.getItem(ms)
if (!mydata) {
this.init()
mydata = storage.getItem(ms)
}
mydata = JSON.parse(mydata)
mydata.data[key] = value
storage.setItem(ms, JSON.stringify(mydata))
return mydata.data
}
let get = function (key) {
// 读取
let mydata = JSON.parse(storage.getItem(ms))
// console.log('mydata:', mydata)
if (!mydata) {
return false
}
// console.log("mystorage",mydata)
// mydata = JSON.parse(mydata)
return mydata.data[key]
}
let remove = function (key) {
// 读取
let mydata = storage.getItem(ms)
if (!mydata) {
return false
}
mydata = JSON.parse(mydata)
delete mydata.data[key]
storage.setItem(ms, JSON.stringify(mydata))
return mydata.data
}
let clear = function () {
// 清除对象
storage.removeItem(ms)
}
let init = function () {
storage.setItem(ms, '{"data":{}}')
}
return {
set: set,
get: get,
remove: remove,
init: init,
clear: clear
}
})()
|
Python
|
UTF-8
| 1,157 | 2.8125 | 3 |
[] |
no_license
|
#!/usr/bin/env python
import sys
if len(sys.argv[1:]) < 2:
sys.stderr.write("ERROR: missing argument\nUsage:\nparse_csv_tree.py <tree.csv> <tree.new.csv>\n\n")
sys.exit(1)
it,ot = sys.argv[1:]
f = open(it,'r')
f = f.readlines()
o = open(ot,'w')
dic_h = {}
c = 0
for branch in f:
branch = branch.split(',')
dic_h[c]=''
for x in xrange(len(branch)):
if branch[x] == '':
pass
else:
if branch[x] != "NoLabel" and branch[x][0].isupper():
dic_h[c] = (x,branch[x])
print dic_h[c],c,branch
new_line = map(lambda x:str(x),branch)
new_line = ','.join(new_line).strip()
o.write(new_line+'\n')
break
elif branch[x] == "NoLabel":
print 'Here is the problem',c,x
z = c-1
while z > 0:
print dic_h[z],z,branch[x],x
if dic_h[z][0] < x:
distance = str(c-z)
print "distance",distance
new_label = dic_h[z][1]+"_"+str(branch[x+1]).strip()
dic_h[c] = (x,new_label)
branch[x] = new_label
new_line = map(lambda x:str(x),branch)
new_line = ','.join(new_line).strip()
break
o.write(new_line+'\n')
else:
z = z-1
else:
pass
c += 1
o.close()
|
Java
|
UTF-8
| 683 | 1.703125 | 2 |
[] |
no_license
|
package com.shoniz.saledistributemobility.data.sharedpref.api;
import com.shoniz.saledistributemobility.data.api.retrofit.ApiException;
import com.shoniz.saledistributemobility.data.model.order.OrderDetailEntity;
import com.shoniz.saledistributemobility.data.model.order.OrderEntity;
import com.shoniz.saledistributemobility.data.sharedpref.SettingEntity;
import com.shoniz.saledistributemobility.framework.InOutError;
import com.shoniz.saledistributemobility.framework.exception.newexceptions.BaseException;
import java.util.List;
/**
* Created by 921235 on 5/12/2018.
*/
public interface ISettingApi {
public List<SettingEntity> getUserSettings() throws BaseException;
}
|
Ruby
|
UTF-8
| 276 | 3.296875 | 3 |
[] |
no_license
|
puts "What is your email?"
email = gets.chomp
File.read('email-list.txt').each_line do |l|
if l.include? email
l.slice! email
l.slice! "name: "
l.slice! "email: "
puts "Hello " + l.capitalize
exit
end
end
puts "Your email address is not on the list."
|
C#
|
UTF-8
| 1,098 | 3.328125 | 3 |
[] |
no_license
|
using System;
namespace Mankind
{
class Program
{
static void Main(string[] args)
{
string[] singleStudent = Console.ReadLine().Split();
string firstStudentName = singleStudent[0];
string lastStudentName = singleStudent[1];
string facultyNumber = singleStudent[2];
string[] singleWorker = Console.ReadLine().Split();
string firstWorkerName = singleWorker[0];
string lastWorkerName = singleWorker[1];
decimal salary = decimal.Parse(singleWorker[2]);
decimal workingHours = decimal.Parse(singleWorker[3]);
try
{
Student student = new Student(firstStudentName, lastStudentName, facultyNumber);
Worker worker = new Worker(firstWorkerName, lastWorkerName, salary, workingHours);
Console.WriteLine(student);
Console.WriteLine(worker);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
|
C#
|
UTF-8
| 1,807 | 2.640625 | 3 |
[] |
no_license
|
namespace EGift.Services.Merchants.Extensions
{
using System;
using System.Data;
using EGift.Services.Merchants.Messages;
using EGift.Services.Merchants.Models;
public static class DataTableExtension
{
public static GetAllMerchantResponse AsGetAllMerchantResponse(this DataTable data)
{
var result = new GetAllMerchantResponse();
result.RawData = data;
foreach (DataRow row in data.Rows)
{
var merchant = new Merchant
{
Id = new Guid(row.ItemArray[0].ToString()),
Name = row.ItemArray[1].ToString(),
Address = row.ItemArray[2].ToString(),
Slug = row.ItemArray[3].ToString()
};
result.Merchants.Add(merchant);
result.Successful = true;
}
return result;
}
public static GetMerchantProductResponse AsGetMerchantProductsResponse(this DataTable data)
{
var result = new GetMerchantProductResponse();
result.RawData = data;
foreach (DataRow row in data.Rows)
{
var product = new Product
{
Id = new Guid(row.ItemArray[1].ToString()),
Name = row.ItemArray[2].ToString(),
Description = row.ItemArray[3].ToString(),
Price = Convert.ToDouble(row.ItemArray[4].ToString())
};
result.Products.Add(product);
result.MerchantName = row.ItemArray[0].ToString();
result.Successful = true;
}
return result;
}
}
}
|
Swift
|
UTF-8
| 3,306 | 2.890625 | 3 |
[] |
no_license
|
//
// JSONHelper.swift
// What to Pack
//
// Created by MoXiafang on 3/12/16.
// Copyright © 2016 Momo. All rights reserved.
//
import Foundation
import SwiftyJSON
class JSONHelper: NSObject {
static let sharedInstance = JSONHelper()
func jsonParsingFromFile() {
var mainJSON: JSON!
var extraJSON: JSON!
if let packingListJSON = NSBundle.mainBundle().URLForResource("PackingList", withExtension: "json") {
if let rawData = NSData(contentsOfURL: packingListJSON) {
let json = JSON(data: rawData)
if json != nil {
mainJSON = json
}
}
}
if let extraPackingListJSON = NSBundle.mainBundle().URLForResource("ExtraPackingList", withExtension: "json") {
if let rawData = NSData(contentsOfURL: extraPackingListJSON) {
let json = JSON(data: rawData)
if json != nil {
switch TravelParameters.sharedInstance.travelType {
case "Business": extraJSON = json[1]
case "Beach": extraJSON = json[2]
case "Adventure": extraJSON = json[0]
case "Vacation": extraJSON = json[3]
default: break
}
}
}
}
let completeArray = mainJSON.arrayValue + extraJSON.arrayValue
PackingListModel.sharedInstance.packingList = completeArray
}
func getSectionTitle(section: Int) -> String! {
var sectionTitle: String?
for (key, _) in PackingListModel.sharedInstance.packingList[section] {
sectionTitle = key
}
return sectionTitle
}
func getItemsCount(section: Int) -> Int {
var count = 0
for (_, value) in PackingListModel.sharedInstance.packingList![section] {
if let arr = value.array {
count = arr.count
} else if let dic = value.dictionary {
for (_, dicValue) in dic {
count += dicValue.arrayValue.count
}
}
}
return count
}
func getItemsList(section: Int) {
PackingListModel.sharedInstance.originalList = dealWithJSON(section)
}
func getItemsFullList() {
var fullItems = [String]()
let count = PackingListModel.sharedInstance.packingList.count
for n in 0...count - 1 {
fullItems += dealWithJSON(n)
}
PackingListModel.sharedInstance.editableList = fullItems
}
func dealWithJSON(number: Int) -> [String] {
var items = [String]()
for (_, value) in PackingListModel.sharedInstance.packingList![number] {
if let arr = value.array {
for item in arr {
items.append(item.stringValue)
}
} else if let dic = value.dictionary {
for (_, dicValue) in dic {
for item in dicValue.arrayValue {
items.append(item.stringValue)
}
}
}
}
return items
}
}
|
JavaScript
|
UTF-8
| 6,044 | 2.578125 | 3 |
[] |
no_license
|
var io = require('socket.io')(3000);
var Firebase = require('firebase');
var p2p = require('socket.io-p2p-server').Server;
//we use peer ti peer to peer connection
io.use(p2p);
//we get a reference to our database
var reference = new Firebase('https://webtogocameroon.firebaseio.com/');
io.on('connection', function(socket){
var date = new Date();
date.setTime(date.getTime()+(2*24*60*60*1000)); // set day value to expiry
var expires = "; expires="+date.toGMTString();
socket.on('join:room', function(data){
// var room_name = data.room_name;
console.log(socket.request.headers.cookie);
socket.join(data);
});
socket.on('leave:room', function(msg){
msg.text = msg.user + " has left the room";
socket.in(msg.room).emit('exit', msg);
socket.leave(msg.room); });
socket.on('send:message', function(msg){
socket.in(msg.room).emit('message', msg);
});
//we list the rooms available
socket.on('app:login',function(data){
reference.authWithPassword({
email : data.email,
password : data.password
}, function(error, authData) {
if(error){
socket.emit("app:login:failure");
}else socket.emit("app:login:success");
}, {
remember: "default"
});
});
//signups the user
socket.on('app:signup',function(data){
//we geT the data of the user
//we check if it is a new user
var data =JSON.parse(data);
reference.createUser({
"email" : data.email,
"password" : data.password
}, function(error, userData) {
if (error) {
console.log("Error creating user:", error);
socket.emit("app:signup:failure");
} else {
var usersReference = new Firebase('https://webtogocameroon.firebaseio.com/users')
usersReference.push({ "userid" : userData.uid,
"location" : data.location,
"username" :data.username});
}
socket.emit('app:signup:success',userData.uid);
});
});
socket.on('app:verify:username',function(username){});
socket.on('get:rooms',function(positionObject1){
//we form a rooms of all users
var arrayUser = [];
var reference_users = new Firebase('https://webtogocameroon.firebaseio.com/users/');
reference_users.on("value", function(snapshot) {
var users = snapshot.val();
arrayUser=[];
if(users){
Object.keys(users).forEach(function(key){
//users
reference_users.child(key+"/location/").once('value',function(snapshot2){
/* var positionObject2 = snapshot2.val();
*/
if(snapshot2.val()) {
var dist = getDistance(positionObject1,snapshot2.val().latitude,snapshot2.val().longitude);
console.log('dist is',dist);
if( dist <= 1)
arrayUser.push(users[key]["username"]);
}
});
socket.emit('found:rooms',JSON.stringify([{ "users" : arrayUser }]));
});
}
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
});
/**All calls related operations */
socket.on('join:call_room', function(data){
var reference_rooms = new Firebase('https://webtogocameroon.firebaseio.com/callrooms/');
//we check if a room already exist for the the two users
reference_rooms.on("value", function(snapshot,previous) {
var room_name="";
var rooms = snapshot.val();
if(rooms){
Object.keys(rooms).forEach(function(key){
//users
if( (rooms[key]['receiver'] == data.user2 && rooms[key]['caller'] == data.user1 ) || (rooms[key]['receiver'] == data.user1 && rooms[key]['caller'] == data.user2)){
room_name = key;
}
});
socket.emit("found:call_room",{ "key" : key,"user" : user2});
socket.join(key);
}else{
reference.push({ caller:user1 , receiver : user2});
//create a temporal room
socket.emit("found:call_room",{ "key" : user1+user2,"user" : user2});
socket.join(user1+user2);
//we create a temporal room
}
}, function (errorObject) {
console.log("The read failed: " + errorObject.code);
});
});
socket.on("accept:call",function(roomname){
socket.join(roomname);
socket.in(roomname).emit('accepted:call', "connected");
});
socket.on("place:call",function(data){
socket.in(data.room_name).emit('stream_back:call',data);
});
});
function getDistance(positionObject1,latitude2,longitude2){
var lat1 = parseFloat(positionObject1.latitude);
// console.log("lat1 ",lat1);
var lon1 = parseFloat(positionObject1.longitude);
// console.log("lon1 ",lon1);
var lat2 = parseFloat(latitude2);
// console.log("lat2 ",lat2);
var lon2 = parseFloat(longitude2);
//console.log("lon2 ",longitude2);
var radlat1 = Math.PI * lat1/180;
var radlat2 = Math.PI * lat2/180;
var theta = lon1-lon2;
var radtheta = Math.PI * theta/180;
var dist = Math.sin(radlat1) * Math.sin(radlat2) + Math.cos(radlat1) * Math.cos(radlat2) * Math.cos(radtheta);
dist = Math.acos(dist)
dist = dist * 180/Math.PI;
dist = dist * 60 * 1.1515 * 1.609344;
/*if (unit=="K") { dist = dist * 1.609344 }
if (unit=="N") { dist = dist * 0.8684 }*/
return dist
}
|
Markdown
|
UTF-8
| 962 | 3.1875 | 3 |
[] |
no_license
|
# IntegralFunction
**Задача**
Реализуйте метод, выполняющий численное интегрирование заданной функции на заданном интервале по формуле левых прямоугольников.
**Подробнее**
Функция задана объектом, реализующим интерфейс java.util.function.DoubleUnaryOperator. Его метод applyAsDouble() принимает значение аргумента и возвращает значение функции в заданной точке.
Интервал интегрирования задается его конечными точками aa и bb, причем a \lt = ba<=b. Для получения достаточно точного результата используйте шаг сетки не больше 10^(-6)
*Пример. Вызов*
```
integrate(x -> 1, 0, 10)
```
|
Markdown
|
UTF-8
| 831 | 2.65625 | 3 |
[
"MIT"
] |
permissive
|
---
layout: post
microblog: true
audio:
photo:
date: 2018-08-02 18:44:38 +0100
guid: http://lukas.micro.blog/2018/08/02/you-have-never.html
---
You have never created a machine-readable API specification with OpenAPI because you didn't know how to start?! Lucky for you, I've written a practical tutorial that does a little hand-holding and takes you step-by-step through your first OpenAPI file. It uses [Stoplight](https://stoplight.io/)'s visual editor, so you don't have to code it in YAML or JSON manually, but I also show you how it looks like under the hood, so you better understand how OpenAPI works.
You can [find my tutorial in the Stoplight API Corner on Medium](https://blog.stoplight.io/getting-started-with-api-design-using-stoplight-and-openapi-90fc8f37ac2e).
_Disclosure: This work was paid for by Stoplight._
|
Python
|
UTF-8
| 1,587 | 2.96875 | 3 |
[] |
no_license
|
import numpy as np
from math import exp
def init_network():
layers=list()
input_layer=np.array([[-1.0,1.0],[1.0,1.0]])
hidden_layer=np.array([[1.0,1.0],[-1.0,1.0]])
layers.append(input_layer)
layers.append(hidden_layer)
return layers
def forward_prop(network,inputs,activator):
outputs=list()
for layer in network:
temp=[sum(inputs*layer[i]) for i in range(len(layer))]
inputs=[activator(temp[i]) for i in range(len(temp))]
outputs.append(inputs)
return outputs
def backward_prop(network,outputs,exception,act_derivative,rate):
for i in reversed(range(len(network))):
layer=network[i]
if i==len(network)-1:
d=list()
for j in range(len(layer)):
delta=exception[j]-outputs[i][j]
d_temp=sigmoid_derivative(outputs[i][j])*delta
d.append(d_temp)
for k in range(len(layer[j])):
layer[j][k]+=rate*d_temp*outputs[i][j]
else:
d_t=list(d)
d=list()
layer=network[i]
next_layer=network[i+1]
for j in range(len(layer)):
delta=0.0
for k in range(len(next_layer)):
delta+=next_layer[j][k]*d_t[j]
d_temp=sigmoid_derivative(outputs[i][j])*delta
d.append(d_temp)
for k in range(len(layer[j])):
layer[j][k]+=rate*d_temp*outputs[i][j]
return network
def sigmoid(x):
return 1/(1+exp(-x))
def sigmoid_derivative(value):
return value*(1-value)
if __name__ == '__main__':
inputs=np.array([1,-1]).T
network=init_network()
outputs=forward_prop(network,inputs,sigmoid)
print(outputs)
exception=np.array([1,0]).T
network=backward_prop(network,outputs,exception,sigmoid_derivative,0.1)
print(network)
|
Markdown
|
UTF-8
| 3,401 | 4.03125 | 4 |
[] |
no_license
|
###07-08
#函数
##函数参数
```
<script type="text/javascript">
// 自定义函数后的括号里面写参数
function show(name){
alert('Hi'+name);
}
// 调用函数,把括号里面的值传到参数里面去
show('Jo');
</script>
```
###css函数
* 修改样式时直接调用css函数即可
```
// obj接收修改的元素 attr接收修改元素的属性 value接收修改的具体值
function css(obj,attr,value){
// 注意此处必须用中括号,不能用点,用点必须有该属性
obj.style[attr]=value;
}
```
##函数的不定参数
>arguments
```
<script type="text/javascript">
// 求和
// function会自动创建一个arguments数组
function sum(){
// 定义初始值
var result=0;
// arguments是一个数组,用来接收在调用函数的时候传递的参数,也可以事先定义好要传什么数据
for(var i=0;i<arguments.length;i++){
result+=arguments[i];
}
alert(result);
}
// 调用函数,里面的参数传递给arguments数组
sum(1,21,123,111,12,3,13);
function suml(a,b){
return a+b;
}
// 结果是3,因为没有传递3对应的参数
alert(suml(1,2,3));
</script>
```
##函数的作用域
```
<script type="text/javascript">
// 花括号括起来的叫一个块儿
// JS是一个函数级作用域
function show(){
if(true){
var a=-1;
}
alert(a);
}
show();
// 在函数当中任意一个地方定义的变量在该函数当中都可以被使用
function say(){
for(i=0;i<5;i++){
alert(i);
}
alert(i);
}
say();
</script>
```
##函数的返回值
###return
return返回的类型: js中函数的返回值类型有数字、字符串、布尔值、函数、 对象(元素、[]、{}、null)、未定义
* 返回控制与函数结果
>语法为:return 表达式;
>语句结束函数执行,返回调用函数,而且把表达式的值作为函数的结果
* 返回控制
>return false一般表示阻止事件的默认行为
>return ture相当于执行符
>return把控制权返回给页面
* 返回一个json对象
>return {a1:a,b1:b,c1:c};
* return只能返回一个值
```
<script type="text/javascript">
// 参数可以有多个
function show(){
var a=1;
// 当函数执行到return,以下的函数就不会再被执行
// return返回值只能返回一个值,要想返回多个值,可以返回json
return a;
// 不会被执行
alert('abc');
}
// msg被定义,此处也是调用show()函数
var msg=show();
alert(msg);
</script>
```
###return返回值
* sort()函数排序
```
<script type="text/javascript">
// arr.sort()自动排序,字母从头到尾
var arr=['yellow','oppo','red','blue','yellow'];
// 直接使用sort()进行排序,将会按照字符处理
var arr0=[22,3,1,33,21,55,63,25];
// 法一
// sort括号里面接收一个函数,这个函数是sort的两个个参数
// function括号里面n1和n2是接收的参数,是数组里面的元素
arr0.sort(function(n1,n2){
if(n1<n2){
return -100;
}else if(n1>n2){
return 1999;
}else{
return 0;
}
})
console.log(arr0);
// return回去的值为一个数值,sort();方法会根据数值的正负对数组的各个部分进行排序。
// 法二 n2-n1递减 n1-n2递增
arr0.sort(function(n1,n2){
return n2-n1;
})
console.log(arr0);
</script>
```
|
End of preview. Expand
in Data Studio
No dataset card yet
- Downloads last month
- -