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
|
|---|---|---|---|---|---|---|---|
Markdown
|
UTF-8
| 1,340
| 2.78125
| 3
|
[
"MIT"
] |
permissive
|
RedPencil
=========
Red Pencil Kata
For up to date tasks check out the trello board
https://trello.com/b/6ruhJ5FV/red-pencil-kata
#User stories
####~~A red pencil promotion starts due to a price reduction. The price has to be reduced by at least 5% but at most bei 30% and the previous price had to be stable for at least 30 days.~~
Finished this story
####A red pencil promotion lasts 30 days as the maximum length.
Not Started
####If the price is further reduced during the red pencil promotion the promotion will not be prolonged by that reduction.
Not Started
####If the price is increased during the red pencil promotion the promotion will be ended immediately.
Created method price_increased? on Product model to check for this condition. Add this check to the before_save callback
####If the price if reduced during the red pencil promotion so that the overall reduction is more than 30% with regard to the original price, the promotion is ended immediately.
Check the price at the start of the sale against the price the product is changing to and use the price_chane_threshold? method
####After a red pencil promotion is ended additional red pencil promotions may follow – as long as the start condition is valid: the price was stable for 30 days and these 30 days don’t intersect with a previous red pencil promotion.
|
SQL
|
UTF-8
| 2,981
| 3.6875
| 4
|
[] |
no_license
|
--- public.aluno
CREATE TABLE public.aluno
(
id serial NOT NULL,
nome character varying(100) NOT NULL,
data_nascimento date NOT NULL,
created_at timestamp,
updated_at timestamp,
deleted_at timestamp,
PRIMARY KEY (id)
);
INSERT INTO public.aluno (nome, data_nascimento, created_at) VALUES ('Yuri Silva', '2000-01-01', now());
INSERT INTO public.aluno (nome, data_nascimento, created_at) VALUES ('Luiz Claudio', '01/01/2000', now());
--- public.professor
CREATE TABLE public.professor
(
id serial NOT NULL,
nome character varying(100) NOT NULL,
created_at timestamp,
updated_at timestamp,
deleted_at timestamp,
PRIMARY KEY (id)
);
INSERT INTO public.professor (nome, created_at) VALUES ('Garibaldo da Silva', now());
--- public.curso
CREATE TABLE public.curso
(
id serial NOT NULL,
professor_id integer NOT NULL,
titulo character varying(200) NOT NULL,
descricao text NOT NULL,
created_at timestamp,
updated_at timestamp,
deleted_at timestamp,
PRIMARY KEY (id),
CONSTRAINT fk_curso_professor FOREIGN KEY (professor_id)
REFERENCES public.professor (id) MATCH SIMPLE
ON UPDATE CASCADE ON DELETE CASCADE
);
CREATE INDEX idx_curso_professor_id ON public.curso (professor_id);
INSERT INTO public.curso (professor_id, titulo, descricao, created_at) VALUES (1, 'Introdução ao Node.js', 'Curso de introdução ao Node.js, utilizando o framework express e projeto swagger.', now());
--- public.aula
CREATE TABLE public.aula
(
id serial NOT NULL,
curso_id integer NOT NULL,
titulo character varying(200) NOT NULL,
conteudo text NOT NULL,
created_at timestamp,
updated_at timestamp,
deleted_at timestamp,
PRIMARY KEY (id),
CONSTRAINT fk_aula_curso FOREIGN KEY (curso_id)
REFERENCES public.curso (id) MATCH SIMPLE
ON UPDATE CASCADE ON DELETE CASCADE
);
CREATE INDEX idx_aula_curso_id ON public.aula (curso_id);
INSERT INTO public.aula (curso_id, titulo, conteudo, created_at) VALUES (1, 'Aula 1 - Introdução ao Node.js', 'Conteúdo da primeira aula.', now());
INSERT INTO public.aula (curso_id, titulo, conteudo, created_at) VALUES (1, 'Aula 2 - Gerenciamento de pacotes usando NPM', 'Conteúdo da segunda aula.', now());
--- public.curso_aluno
CREATE TABLE public.curso_aluno
(
curso_id integer NOT NULL,
aluno_id integer NOT NULL,
PRIMARY KEY (curso_id, aluno_id),
CONSTRAINT fk_curso_aluno_cu FOREIGN KEY (curso_id)
REFERENCES public.curso (id) MATCH SIMPLE
ON UPDATE CASCADE ON DELETE CASCADE,
CONSTRAINT fk_curso_aluno_al FOREIGN KEY (aluno_id)
REFERENCES public.aluno (id) MATCH SIMPLE
ON UPDATE CASCADE ON DELETE CASCADE
);
CREATE INDEX idx_curso_aluno_curso_id ON public.curso_aluno (curso_id);
CREATE INDEX idx_curso_aluno_aluno_id ON public.curso_aluno (aluno_id);
INSERT INTO public.curso_aluno (curso_id, aluno_id) VALUES (1, 1);
INSERT INTO public.curso_aluno (curso_id, aluno_id) VALUES (1, 2);
|
C++
|
UTF-8
| 4,267
| 2.546875
| 3
|
[
"MIT"
] |
permissive
|
/*
* Copyright (C) 2014 Pavel Kirienko <pavel.kirienko@gmail.com>
*/
#pragma once
#include <uavcan/time.hpp>
#include <uavcan/protocol/debug/LogMessage.hpp>
#include <uavcan/marshal/char_array_formatter.hpp>
#include <uavcan/node/publisher.hpp>
#if !defined(UAVCAN_CPP_VERSION) || !defined(UAVCAN_CPP11)
# error UAVCAN_CPP_VERSION
#endif
namespace uavcan
{
class UAVCAN_EXPORT ILogSink
{
public:
typedef typename StorageType<typename protocol::debug::LogLevel::FieldTypes::value>::Type LogLevel;
virtual ~ILogSink() { }
/**
* Logger will not sink messages with level lower than returned by this method.
*/
virtual LogLevel getLogLevel() const { return protocol::debug::LogLevel::DEBUG; }
/**
* Logger will call this method for every log message with level not less than the current level of this sink.
*/
virtual void log(const protocol::debug::LogMessage& message) = 0;
};
class UAVCAN_EXPORT Logger
{
public:
typedef ILogSink::LogLevel LogLevel;
static const LogLevel LevelAboveAll = (1 << protocol::debug::LogLevel::FieldTypes::value::BitLen) - 1;
private:
enum { DefaultTxTimeoutMs = 2000 };
Publisher<protocol::debug::LogMessage> logmsg_pub_;
protocol::debug::LogMessage msg_buf_;
LogLevel level_;
ILogSink* external_sink_;
LogLevel getExternalSinkLevel() const;
public:
explicit Logger(INode& node)
: logmsg_pub_(node)
, external_sink_(NULL)
{
level_ = protocol::debug::LogLevel::ERROR;
setTxTimeout(MonotonicDuration::fromMSec(DefaultTxTimeoutMs));
assert(getTxTimeout() == MonotonicDuration::fromMSec(DefaultTxTimeoutMs));
}
int init();
int log(const protocol::debug::LogMessage& message);
LogLevel getLevel() const { return level_; }
void setLevel(LogLevel level) { level_ = level; }
ILogSink* getExternalSink() const { return external_sink_; }
void setExternalSink(ILogSink* sink) { external_sink_ = sink; }
MonotonicDuration getTxTimeout() const { return logmsg_pub_.getTxTimeout(); }
void setTxTimeout(MonotonicDuration val) { logmsg_pub_.setTxTimeout(val); }
#if UAVCAN_CPP_VERSION >= UAVCAN_CPP11
template <typename... Args>
int log(LogLevel level, const char* source, const char* format, Args... args);
template <typename... Args>
inline int logDebug(const char* source, const char* format, Args... args)
{
return log(protocol::debug::LogLevel::DEBUG, source, format, args...);
}
template <typename... Args>
inline int logInfo(const char* source, const char* format, Args... args)
{
return log(protocol::debug::LogLevel::INFO, source, format, args...);
}
template <typename... Args>
inline int logWarning(const char* source, const char* format, Args... args)
{
return log(protocol::debug::LogLevel::WARNING, source, format, args...);
}
template <typename... Args>
inline int logError(const char* source, const char* format, Args... args)
{
return log(protocol::debug::LogLevel::ERROR, source, format, args...);
}
#else
int log(LogLevel level, const char* source, const char* text);
int logDebug(const char* source, const char* text)
{
return log(protocol::debug::LogLevel::DEBUG, source, text);
}
int logInfo(const char* source, const char* text)
{
return log(protocol::debug::LogLevel::INFO, source, text);
}
int logWarning(const char* source, const char* text)
{
return log(protocol::debug::LogLevel::WARNING, source, text);
}
int logError(const char* source, const char* text)
{
return log(protocol::debug::LogLevel::ERROR, source, text);
}
#endif
};
#if UAVCAN_CPP_VERSION >= UAVCAN_CPP11
template <typename... Args>
int Logger::log(LogLevel level, const char* source, const char* format, Args... args)
{
if (level >= level_ || level >= getExternalSinkLevel())
{
msg_buf_.level.value = level;
msg_buf_.source = source;
msg_buf_.text.clear();
CharArrayFormatter<typename protocol::debug::LogMessage::FieldTypes::text> formatter(msg_buf_.text);
formatter.write(format, args...);
return log(msg_buf_);
}
return 0;
}
#endif
}
|
Python
|
UTF-8
| 834
| 4.09375
| 4
|
[] |
no_license
|
""" There are also some special attributes that begins with double underscore (__).
For example: __doc__ attribute. It is used to fetch the docstring of that class.
When we define a class, a new class object is created with the same class name.
This new class object provides a facility to access the different attributes as well as to instantiate new objects of that class.
"""
class Student: # class Student(): works too
"This is a student class"
def __init__(self, rollno, name):
self.rollno = rollno
self.name = name
def displayStudent(self):
print("rollno: ", self.rollno, ", name: ", self.name)
def show(self, name):
print("Hello", name)
std1 = Student(1, "Raunak")
std2 = Student(2, "Patrick")
std1.displayStudent()
std2.displayStudent()
std2.show("Patrick")
|
Markdown
|
UTF-8
| 9,711
| 3.28125
| 3
|
[] |
no_license
|
# 第三章:出类拔萃-中级篇
## 3.1 二分搜索
* lower\_bound
* 假定一个解并判断是否可行
* POJ 1064 Cable Master
有N条绳子,它们的长度分别为Li。如果从他们中切割出K条长度相同的绳子的话,这K条绳子每条能有多长?答案保留小数点后两位。
用二分法来判断中间的解是否可行,然后缩小解区间。
* 最大化最小值
* POJ 2456 Aggressive cows
有N间牛舍的小屋。牛舍排在一条直线上,第i号牛舍在xi的位置。有m头牛,将每头牛都放在离其他牛就可能远的牛舍。也就是要最大化最近的两头牛之间的距离。
依然用二分法来判断中间的解是否可行,判断的时候采用贪心法,首先对牛舍的位置排序,然后第一头牛放x0,如果第i头牛放xj的话,那么的i+1头牛就要放入满足xj+d<=xk的最小的xk中。
* 最大化平均值
* 有n个物品的重量和价值分别是wi和vi。从中选出k个物品使得单位重量的价值最大。
例:n=3;k=2;\(w,v\)={\(2,2\),\(5,3\),\(2,1\)} 选0和2号物品,平均价值是0.75。
如果把物品按照单位价值进行排序,从小到大贪心的进行选取,可以从示例看到该方法是不对的。
实际上用二分法可以很好解决。
$\sum{v\_i}/\sum{w\_i}>=x$ 即 $\sum\(v\_i-x_w\_i\)>=0$,因此,可以对 $\(v\_i-x_w\_i\)$的值进行排序贪心的进行选取,使得其前k个数的和不小于0。每次判断的复杂度是O\(nlogn\),即为排序的复杂度。
## 3.2 常用技巧精选一
* 尺取法
* POJ 3061 Subsequence
给出长度为n的整数数列,求出总和不小于S的连续子序列的长度的最小值。如果解不存在,输出0.
尺取法也可以说是双指针法,反复的推进区间的开头和末尾,来求取满足条件的最小区间的方法。
* 反转(开关问题)
* POJ 3276 Face The Right Way
N头牛排成一列,每头牛朝向为前或后,为了让所有的牛都朝向前方,转牛机在购买时必须设定一个数值k,机器每操作一次恰好使K头连续的牛转向。请求出为了让所有的牛都面向前方需要的最少的操作次数M和对应的最小的K。
首先我们考虑对于一个特定的K,如何求出让所有的牛面朝前方的最小操作次数。可以看到交换区间翻转的顺序对结果没有影响,对一个区间进行两次以上的翻转是多余的。于是考虑最左端的牛,包含这个牛的区间只有一个,如果这头牛面朝前方,我们就知道这个区间不需要翻转。如果朝后,对应的区间就必须进行翻转了。而且此后,这个最左的区间就不需要考虑了,问题的规模就缩小了1.
我们需要对所有的K都求解一次,每次固定K时,要从左到右考虑N头牛,此时最坏情况下需要进行N-K+1次的翻转操作,而每次翻转操作又要翻转K头牛,于是总的复杂度是O\(N^3\)。这样的话不足以在时限内解决问题,但是区间翻转的部分是很容易进行优化的。
f\[i\]:=区间\[i,i+K-1\]进行了翻转则为1,否则为0
这样,在考虑第i头牛的时候,如果 $\sum\_{j=i+K-1}^{i-1}f\[i\]$ 为奇数的话,则这头牛的方向与起始方向相反,否则方向不变。并且该式可以在常数时间内更新,复杂度就变成了O\(N^2\)。
* POJ 3279 Fliptile
反转黑白棋,棋盘大小为M\*N,游戏要做的就是把所有的格子翻转为白色。不同的在于每次翻转时,与该格子相邻的上下左右的四个格子也会被翻转。通过尽可能少的步数将所有的格子翻转为白色,解不存在时输出IMPOSSIBLE。
如果确定了第一行的反转方式,那么,第二行及以后的反转方式都可以确定,就可以求出整个问题的最小步数,该算法最上面的一行的反转次数为 2^N 种,复杂度为 $O\(MN2^N\)$
* 折半搜索
* POJ 2785 4 Values whose Sum is 0
给定各有n个整数的四个数列A、B、C、D。要从数列中各取出1个数,使四个数的和为0.求出这样的组合的个数。当一个数列中有多个相同的数字时,把他们作为不同的数字看待。
暴力方法 n^4 不行,先将他们对半分成AB和CD再考虑,从两个数列中选择只有 n^2 种组合,所以可以进行枚举,枚举后将这些和排好序,再二分搜索。总的复杂度是 $O\(n^2 logn\)$
* 超大背包问题
有重量和价值分别为wi、vi的n个物品。从这些物品中挑选总重量不超过W的物品,求所有挑选方案中价值总和的最大值。
1<=n<=40
1<= wi,vi <=10^15
1<= W<= 10^15
这个背包问题的特点在于价值和数量都是非常大的数值,相比之下n很小。使用DP背包问题的复杂度是O\(nW\),因此不能用来解决这里的问题。
因为挑选物品的方法总共有 2^n 种,所以不能直接枚举,但是像前面一样拆成两半之后再枚举的话,因为每部分只有20个还是可行的。这样在前半部分的选取方法中对应的重量和价值即为w1、v1。在后半部分中寻找max{v2\|w2<=W-w1}。
首先需要排除所有 w2\[i\]<=w2\[j\] 且 v2\[i\]>=v2\[j\] 的 j 。**这一点可以按照 w2、v2的字典序排序后简单做到**。要计算 max{v2\|w2<=W-w1} 的话,只要寻找满足 w2\[i\]<=W-w1 的最大的i就可以了。这个过程可以用二分完成,总个数为M的话(M<=2^\(n/2\)),一次搜索需要 O\(logM\) 的时间。所以总的复杂度为 O\(2^\(n/2\) \* n\),可以在时限内解决这个问题。
* 坐标离散化
w\*h 的格子上花了n条或垂直或水平的宽度为1的直线。求出这些线将格子划分成了多少个区域。
1 <= w,h <= 1000000
1 <= n <= 500
准备好w_h的数组,并记录是否有直线通过,然后参考DFS求连通域的方法,可以求出被分隔的区域个数。但是这个问题中w和h的最大为1000000,所以没办法创建w_h的数组。因此用坐标离散化这个技巧。
请参考书中图示,离散化代码如下。
```cpp
//对x1和x2进行离散化,并返回离散化之后的宽度
int compress(int *x1 ,int *x2,int w){
vector<int> xs;
for (int i=0;i<N;i++){//N指有n条线段,每个线段两个坐标点
for(int d=-1;d<=1;d++){
int tx1 = x1[i]+d,tx2 = x2[i]+d;
if(1 <= tx1 && tx1 <= W) xs.push(tx1)
if(1 <= tx2 && tx2 <= W) xs.push(tx2)
}
}
sort(xs.begin(),xs.end());
xs.erase(unique(xs.begin(),xs.end()),xs.end());
//unique的返回值是尾指针的位置
for(int i=0;i<=M;i++){
x1[i] = find(xs.begin(),xs.end(),x1[i])-xs.begin();
x2[i] = find(xs.begin(),xs.end(),x2[i])-xs.begin();
}
return xs.size();
}
```
> 感觉这个离散化的过程和实际不太符合!!!!
## 3.3 活用各种数据结构
### 3.3.1 线段树
线段树善于处理区间问题,形式上是一颗完美二叉树,用向量存储,书中的每个节点维护一个区间。根节点维护的是整个区间,每个节点维护的是父节点的区间二等分后的其中一个区间。
RMQ(Range Minimum Query)操作的线段树主要涉及两种操作:
* 求区间最小值
* 修改指定元素的数值
两种操作的复杂度都是O\(N\)
要求某个区间的最小值,像下面这样递归处理就好了。
* 如果所查询的区间和当前节点对应的区间完全没有交集,那么就返回一个不影响答案的值(比如INT\_MAX)
* 如果所查询的区间完全包含了当前节点对应的区间,那么就返回当前节点的值
* 以上两种情况都不满足的话,就对两个儿子区间递归处理,返回两个结果中的较小值
线段树的初始化的复杂度是O\(N\),和完全二叉堆的初始化过程类似。
```cpp
const int MAX_N = 1<<17;
//存储线段树的全局数组
int n,dat[2*MAAX_N-1];
//初始化
void init(int n_){
//为了简单起见,把元素个数扩大到2的幂
n=1;
while(n<n_)n*=2;
//把所有的值都设定为INT_MAX
for(int i=0;i<2*n-1;i++)dat[i]=INT_MAX;
}
//把第k(0-(n-1))个值更新为a
void update(int k,int a){
k+=n-1;
dat[k]=a;
//向上更新
while(k>0){
k=(k-1)/2;
dat[k]=min(dat[k*2+1],dast[k*2+2]);
}
}
//求[a,b)的最小值
//后面的参数是为了计算起来方便传入的
//k是节点的编号,l,r表示这个节点对应的[l,r)区间
//在外部调用时,用query(a,b,0,0,n)
int query(int a,int b,int k,int l,int r){
//不相交
if(r<=a||b<=l)return INT_MAX;
//区间包含
if(a<=l&&r<=b)return dat[k];
else{
int vl = query(a,b,k*2+1,l,(l+r)/2)
int vr = query(a,b,k*2+2,(l+r)/2,r)
return min(vl,vr);
}
}
```
POJ 2991 Crane
每个节点表示一段连续的线段的集合,并且维护下面两个值。
* 把对应的线段集合中的第一条线段转至垂直方向之后,从第一条线段的起点指向最后一条线段的终点的向量。
* (如果该节点有儿子节点)两个儿子节点对应的部分连接之后,右儿子需要转动的角度。
待续
### 3.3.2 Binary Indexed Tree
### 3.3.3 分桶法和平方分割
## 3.4 熟练掌握动态规划
### 3.4.1 状态压缩DP
### 3.4.2 矩阵的幂
### 3.4.3 利用数据结构高效求解
## 3.5 借助水流解决问题的网络流
### 3.5.1 最大流
### 3.5.2 最小割
### 3.5.3 二分图匹配
### 3.5.4 一般图匹配
### 3.5.5 匹配、边覆盖、独立集和顶点覆盖
### 3.5.6 最小费用流
## 3.6与平面和空间打交道的计算几何
|
C
|
UTF-8
| 6,341
| 4.0625
| 4
|
[] |
no_license
|
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
struct node
{
char * data;
struct node * next;
};
struct node * node_new(char * passedData)
{
struct node * result = malloc(sizeof(struct node));
result->data = passedData;
result->next = NULL;
return result;
}
struct hashtable
{
struct node ** array;
int size;
};
unsigned hash_string(char * str)
{
unsigned hash = 0;
int i;
for (i = 0; str[i] != '\0'; i++ ) {
hash = hash * 37 + str[i];
}
return hash;
}
struct hashtable * hashtable_new(int passedSize)
{
struct hashtable * result = malloc(sizeof(struct hashtable));
result->array = malloc(sizeof(struct node *) * passedSize);
result->size = passedSize;
return result;
}
void hashtable_print(struct hashtable * this)
{
int index;
for(index = 0; index < this->size; index++)
{
printf("%d: ", index);
if(this->array[index] == NULL)
{
printf("<empty>\n");
}
else
{
struct node * currentNode = this->array[index];
while(currentNode!= NULL)
{
printf("%s ->", currentNode->data);
currentNode = currentNode->next;
}
printf(" NULL\n");
}
}
}
int hashtable_lookup(struct hashtable * this, char * item)
{
int result = 0;
struct node * currentNode = this->array[hash_string(item) % this->size];
if(currentNode != NULL)
{
while(!result && currentNode != NULL)
{
result = strcmp(item, currentNode->data) == 0;
currentNode = currentNode->next;
}
}
return result;
}
char * copyString(char * src1)
{
char * result = malloc(sizeof(src1));
assert(result != NULL);
int index;
for(index = 0; index < sizeof(src1); index++)
{
result[index] = src1[index];
}
return result;
}
//the function iterates through the chain. If the element isn't found, then it is added
//if it is, then nothing. It is mildly more efficient than calling lookup at start this way.
void hashtable_insert(struct hashtable * this, char * item)
{
char * privateItem = copyString(item);
struct node * newNode = node_new(privateItem); //privateItem ensures that the string will not be altered.
int hashtableIndex = hash_string(privateItem) % this->size;
if(this->array[hashtableIndex] == NULL) //if index is empty
{
this->array[hashtableIndex] =newNode;
}
else
{
int newElement = 1;
struct node * currentNode= this->array[hashtableIndex];
struct node * previousNode;
while(newElement && currentNode != NULL)
{
previousNode = currentNode;
newElement = strcmp(currentNode->data, privateItem); //strcmp will return true whilst items are unequal
currentNode = currentNode->next;
}
if(newElement)
{
previousNode->next = newNode;
}
//else nothing.
}
}
//the function iterates through the chain. If the element isn't found, then nothing,
//if it is, then it is removed. It is mildly more efficient than calling lookup at start this way.
void hashtable_remove(struct hashtable * this, char * item)
{
/*
OLD VERSION OF THE FUNCTION BELOW.
//I know that this function looks rather large, but it is actually extremely simple
//and runs at most a few lines of code at a time. It's size is due to the if/else
//structure required to deal with all cases, i.e. if element to be removed is
//the first element, the last element, or somewhere in between.
if(hashtable_lookup(this, item)) //if item is in hashtable
{
int hashtableIndex = hash_string(item) % this->size;
struct node * currentNode = this->array[hashtableIndex];
//I do not have to check whether currentNode == NULL, as I know for a fact that the element
//is in the hashtable (due to hashtable_lookup)
if(!strcmp(currentNode->data, item)) //if the element to be removed is the first element
{ //!strcmp because it returns 0 if equal
if(currentNode->next == NULL)
{
this->array[hashtableIndex] = NULL;
free(currentNode);
}
else
{
this->array[hashtableIndex] = currentNode->next;
free(currentNode);
}
}
else //else element is not the first element, and there is at least
{
struct node * previousNode = currentNode;
currentNode = currentNode->next; //I know for a fact that there is a next node, as the element to be deleted
//is not the first element, but it is present in table
while(strcmp(currentNode->data, item)) //again, I do not have to check whether currentNode == NULL
{
previousNode = currentNode;
currentNode = currentNode->next;
}
if(currentNode->next == NULL) //if the element to be removed is the last element
{
previousNode->next = NULL;
free(currentNode);
}
else //else the element is in the middle, neither first or last, and hence
{ //it is in the middle.
previousNode->next = currentNode->next;
free(currentNode);
}
}
}
*/
//NEW VERSION
int hashtableIndex = hash_string(item) % this->size;
struct node * currentNode = this->array[hashtableIndex];
if(currentNode == NULL)
{
//do nothing.
}
else if(!strcmp(currentNode->data, item)) //if first item is to be removed
{
if(currentNode->next == NULL) //if no other nodes
{
this->array[hashtableIndex] = NULL;
free(currentNode);
}
else //else there are nodes following it
{
this->array[hashtableIndex] = currentNode->next;
free(currentNode);
}
}
else //else the element to remove is either not present, or further in the chain
{
struct node * previousNode = currentNode;
while(currentNode != NULL && strcmp(currentNode->data, item)) //strcmp rather than !strcmp because
{ //strcmp returns 0 if equal, and true otherwise
previousNode = currentNode;
currentNode = currentNode->next;
}
if(currentNode == NULL) //means data not found
{
//do nothing.
}
else if(currentNode->next == NULL) //if element to be removed is the last in the chain
{
previousNode->next = NULL;
free(currentNode);
}
else //else the element is in the middle someplace
{
previousNode->next = currentNode->next;
free(currentNode);
}
}
}
int main(int argc, char ** argv)
{
struct hashtable * testTable = hashtable_new(9);
int index;
for(index = 1; index < argc; index++)
{
hashtable_insert(testTable, argv[index]);
}
hashtable_remove(testTable, "porridge");
hashtable_insert(testTable, "fish");
hashtable_print(testTable);
return 0;
}
|
C++
|
UTF-8
| 1,012
| 3.078125
| 3
|
[] |
no_license
|
#include "../header/myheader.h"
class LT0481
{
public:
// magical_string += string(magical_string[index++] - '0', magical_string.back() ^ 3);
// count(magical_string.begin(), magical_string.begin() + n, '1');
// ..........
//Runtime: 8 ms, faster than 79.19% of C++ online submissions for Magical String.
//Memory Usage: 13 MB, less than 100.00% of C++ online submissions for Magical String.
int lt0481a(int n)
{
queue<int> que1;
int ans = n > 0;
int t = 1;
// que1.push(1);
// que1.push(2);
que1.push(2);
int i = 3;
int qf = 0;
while (i <= n) // i+que1.size < n
{
qf = que1.front();
ans += (qf == 1);
que1.pop();
que1.push(t);
if (qf > 1)
que1.push(t);
t = t % 2 + 1;
i++;
}
return ans;
}
};
int main()
{
int n = 6;
LT0481 lt;
cout<<lt.lt0481a(n)<<endl;
return 0;
}
|
JavaScript
|
UTF-8
| 936
| 2.640625
| 3
|
[] |
no_license
|
import React, { Component } from "react";
export default class NameInput extends Component {
constructor(props) {
super(props);
this.state = { username: '' };
}
setUsername(name) {
this.setState({ username: name });
}
render() {
return (
<div className="NameInput">
<label>Enter a username:</label>
<div className="input-group">
<input type="text" className="form-control" onChange={ (e) => this.setUsername(e.target.value) }/>
<span className="input-group-btn">
<button className="btn btn-default" disabled={!this.state.username} onClick={
(e) => {
if (!this.state.username) return;
this.props.onButtonClicked(this.state.username);
e.preventDefault();
}
}>Create User <i className="fa fa-angle-double-right" /></button>
</span>
</div>
</div>
)
}
}
|
Python
|
UTF-8
| 1,138
| 3.84375
| 4
|
[
"MIT"
] |
permissive
|
from collections import Counter, defaultdict
class Solution(object):
def topKFrequent(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
freq, result = Counter(nums), []
inverse_freq = defaultdict(list)
for k1,v1 in freq.items():
inverse_freq[v1].append(k1)
for x in range(len(nums), 0, -1):
if x in inverse_freq:
result.extend(inverse_freq[x])
if len(result) >= k:
break
return result[:k]
def sort_dict_by_value(dic: dict = {'a':3, 'b':5, 'c':1, 'd':2, 'e':4}) -> list:
"""Sort the key/value pair in the dictionary by its value descendingly.
Args:
Returns:
"""
return sorted(dic.items(), key=lambda x: -x[1])
if __name__ == "__main__":
# s = Solution()
# print(s.topKFrequent([5,2,3,4], 4))
letters = ['b', 'c', 'd', 'a', 'e']
numbers = [5,1,4,2,3]
zipList = zip(letters, numbers)
dic = dict(zipList)
# print(zipList)
# print(dic)
print(sort_dict_by_value(dic))
|
JavaScript
|
UTF-8
| 2,032
| 2.703125
| 3
|
[
"MIT"
] |
permissive
|
"use strict";
const canMoveOffBoard = require("./can-move-off-board.js");
const canMoveToSpace = require("./can-move-to-space.js");
const _ = require("lodash");
const constants = require("./constants");
function findAvailableSpaces(gameState, numberOfSpaces) {
const isPlayerOne = gameState.isPlayerOne;
const activePlayer = isPlayerOne ?
{
playerObject: gameState.playerOne,
startSpace: constants.PLAYER_ONE_START_SPACE,
endSpace: constants.PLAYER_ONE_END_SPACE,
possibleStartSpaceIndex: constants.PLAYER_ONE_START_SPACE + numberOfSpaces
} :
{
playerObject: gameState.playerTwo,
startSpace: constants.PLAYER_TWO_START_SPACE,
endSpace: constants.PLAYER_TWO_END_SPACE,
possibleStartSpaceIndex: constants.PLAYER_TWO_START_SPACE - numberOfSpaces
};
const availableSpaces = gameState.board.map((space, index) => {
const possibleSpaceIndex = index + numberOfSpaces * (isPlayerOne ? 1 : -1);
const possibleSpaceIsOffBoard = isPlayerOne && possibleSpaceIndex > 23 ||
!isPlayerOne && possibleSpaceIndex < 0;
const currentSpace = gameState.board[index];
if (currentSpace.isPlayerOne === isPlayerOne && possibleSpaceIsOffBoard) {
if (!canMoveOffBoard(gameState)) {
return;
}
return index;
}
if (currentSpace.isPlayerOne === isPlayerOne && canMoveToSpace(gameState, possibleSpaceIndex).isAvailable) {
return index;
}
});
const availablePiecesOffBoard = activePlayer.playerObject.initialPieces || activePlayer.playerObject.barPieces;
if (
availablePiecesOffBoard &&
canMoveToSpace(gameState, activePlayer.possibleStartSpaceIndex).isAvailable
) {
availableSpaces.push(activePlayer.startSpace);
}
return _.without(availableSpaces, undefined);
}
module.exports = findAvailableSpaces;
|
Java
|
UTF-8
| 15,572
| 1.5
| 2
|
[
"Apache-2.0",
"MIT"
] |
permissive
|
/*
* Copyright 2012-2023 CodeLibs Project and the Others.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
* either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
package org.codelibs.fess.es.config.cbean.ca.bs;
import org.codelibs.fess.es.config.allcommon.EsAbstractConditionAggregation;
import org.codelibs.fess.es.config.allcommon.EsAbstractConditionQuery;
import org.codelibs.fess.es.config.cbean.ca.ElevateWordToLabelCA;
import org.codelibs.fess.es.config.cbean.cq.ElevateWordToLabelCQ;
import org.codelibs.fess.es.config.cbean.cq.bs.BsElevateWordToLabelCQ;
import org.opensearch.search.aggregations.bucket.filter.FilterAggregationBuilder;
import org.opensearch.search.aggregations.bucket.global.GlobalAggregationBuilder;
import org.opensearch.search.aggregations.bucket.missing.MissingAggregationBuilder;
import org.opensearch.search.aggregations.bucket.range.IpRangeAggregationBuilder;
import org.opensearch.search.aggregations.bucket.sampler.SamplerAggregationBuilder;
import org.opensearch.search.aggregations.bucket.terms.SignificantTermsAggregationBuilder;
import org.opensearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.opensearch.search.aggregations.metrics.CardinalityAggregationBuilder;
import org.opensearch.search.aggregations.metrics.ScriptedMetricAggregationBuilder;
import org.opensearch.search.aggregations.metrics.TopHitsAggregationBuilder;
import org.opensearch.search.aggregations.metrics.ValueCountAggregationBuilder;
/**
* @author ESFlute (using FreeGen)
*/
public abstract class BsElevateWordToLabelCA extends EsAbstractConditionAggregation {
// ===================================================================================
// Aggregation Set
// =========
public void filter(String name, EsAbstractConditionQuery.OperatorCall<BsElevateWordToLabelCQ> queryLambda,
ConditionOptionCall<FilterAggregationBuilder> opLambda, OperatorCall<BsElevateWordToLabelCA> aggsLambda) {
ElevateWordToLabelCQ cq = new ElevateWordToLabelCQ();
if (queryLambda != null) {
queryLambda.callback(cq);
}
FilterAggregationBuilder builder = regFilterA(name, cq.getQuery());
if (opLambda != null) {
opLambda.callback(builder);
}
if (aggsLambda != null) {
ElevateWordToLabelCA ca = new ElevateWordToLabelCA();
aggsLambda.callback(ca);
ca.getAggregationBuilderList().forEach(builder::subAggregation);
}
}
public void global(String name, ConditionOptionCall<GlobalAggregationBuilder> opLambda,
OperatorCall<BsElevateWordToLabelCA> aggsLambda) {
GlobalAggregationBuilder builder = regGlobalA(name);
if (opLambda != null) {
opLambda.callback(builder);
}
if (aggsLambda != null) {
ElevateWordToLabelCA ca = new ElevateWordToLabelCA();
aggsLambda.callback(ca);
ca.getAggregationBuilderList().forEach(builder::subAggregation);
}
}
public void sampler(String name, ConditionOptionCall<SamplerAggregationBuilder> opLambda,
OperatorCall<BsElevateWordToLabelCA> aggsLambda) {
SamplerAggregationBuilder builder = regSamplerA(name);
if (opLambda != null) {
opLambda.callback(builder);
}
if (aggsLambda != null) {
ElevateWordToLabelCA ca = new ElevateWordToLabelCA();
aggsLambda.callback(ca);
ca.getAggregationBuilderList().forEach(builder::subAggregation);
}
}
public void scriptedMetric(String name, ConditionOptionCall<ScriptedMetricAggregationBuilder> opLambda) {
ScriptedMetricAggregationBuilder builder = regScriptedMetricA(name);
if (opLambda != null) {
opLambda.callback(builder);
}
}
public void topHits(String name, ConditionOptionCall<TopHitsAggregationBuilder> opLambda) {
TopHitsAggregationBuilder builder = regTopHitsA(name);
if (opLambda != null) {
opLambda.callback(builder);
}
}
public void setElevateWordId_Terms() {
setElevateWordId_Terms(null);
}
public void setElevateWordId_Terms(ConditionOptionCall<TermsAggregationBuilder> opLambda) {
setElevateWordId_Terms("elevateWordId", opLambda, null);
}
public void setElevateWordId_Terms(ConditionOptionCall<TermsAggregationBuilder> opLambda,
OperatorCall<BsElevateWordToLabelCA> aggsLambda) {
setElevateWordId_Terms("elevateWordId", opLambda, aggsLambda);
}
public void setElevateWordId_Terms(String name, ConditionOptionCall<TermsAggregationBuilder> opLambda,
OperatorCall<BsElevateWordToLabelCA> aggsLambda) {
TermsAggregationBuilder builder = regTermsA(name, "elevateWordId");
if (opLambda != null) {
opLambda.callback(builder);
}
if (aggsLambda != null) {
ElevateWordToLabelCA ca = new ElevateWordToLabelCA();
aggsLambda.callback(ca);
ca.getAggregationBuilderList().forEach(builder::subAggregation);
}
}
public void setElevateWordId_SignificantTerms() {
setElevateWordId_SignificantTerms(null);
}
public void setElevateWordId_SignificantTerms(ConditionOptionCall<SignificantTermsAggregationBuilder> opLambda) {
setElevateWordId_SignificantTerms("elevateWordId", opLambda, null);
}
public void setElevateWordId_SignificantTerms(ConditionOptionCall<SignificantTermsAggregationBuilder> opLambda,
OperatorCall<BsElevateWordToLabelCA> aggsLambda) {
setElevateWordId_SignificantTerms("elevateWordId", opLambda, aggsLambda);
}
public void setElevateWordId_SignificantTerms(String name, ConditionOptionCall<SignificantTermsAggregationBuilder> opLambda,
OperatorCall<BsElevateWordToLabelCA> aggsLambda) {
SignificantTermsAggregationBuilder builder = regSignificantTermsA(name, "elevateWordId");
if (opLambda != null) {
opLambda.callback(builder);
}
if (aggsLambda != null) {
ElevateWordToLabelCA ca = new ElevateWordToLabelCA();
aggsLambda.callback(ca);
ca.getAggregationBuilderList().forEach(builder::subAggregation);
}
}
public void setElevateWordId_IpRange() {
setElevateWordId_IpRange(null);
}
public void setElevateWordId_IpRange(ConditionOptionCall<IpRangeAggregationBuilder> opLambda) {
setElevateWordId_IpRange("elevateWordId", opLambda, null);
}
public void setElevateWordId_IpRange(ConditionOptionCall<IpRangeAggregationBuilder> opLambda,
OperatorCall<BsElevateWordToLabelCA> aggsLambda) {
setElevateWordId_IpRange("elevateWordId", opLambda, aggsLambda);
}
public void setElevateWordId_IpRange(String name, ConditionOptionCall<IpRangeAggregationBuilder> opLambda,
OperatorCall<BsElevateWordToLabelCA> aggsLambda) {
IpRangeAggregationBuilder builder = regIpRangeA(name, "elevateWordId");
if (opLambda != null) {
opLambda.callback(builder);
}
if (aggsLambda != null) {
ElevateWordToLabelCA ca = new ElevateWordToLabelCA();
aggsLambda.callback(ca);
ca.getAggregationBuilderList().forEach(builder::subAggregation);
}
}
public void setElevateWordId_Count() {
setElevateWordId_Count(null);
}
public void setElevateWordId_Count(ConditionOptionCall<ValueCountAggregationBuilder> opLambda) {
setElevateWordId_Count("elevateWordId", opLambda);
}
public void setElevateWordId_Count(String name, ConditionOptionCall<ValueCountAggregationBuilder> opLambda) {
ValueCountAggregationBuilder builder = regCountA(name, "elevateWordId");
if (opLambda != null) {
opLambda.callback(builder);
}
}
public void setElevateWordId_Cardinality() {
setElevateWordId_Cardinality(null);
}
public void setElevateWordId_Cardinality(ConditionOptionCall<CardinalityAggregationBuilder> opLambda) {
setElevateWordId_Cardinality("elevateWordId", opLambda);
}
public void setElevateWordId_Cardinality(String name, ConditionOptionCall<CardinalityAggregationBuilder> opLambda) {
CardinalityAggregationBuilder builder = regCardinalityA(name, "elevateWordId");
if (opLambda != null) {
opLambda.callback(builder);
}
}
public void setElevateWordId_Missing() {
setElevateWordId_Missing(null);
}
public void setElevateWordId_Missing(ConditionOptionCall<MissingAggregationBuilder> opLambda) {
setElevateWordId_Missing("elevateWordId", opLambda, null);
}
public void setElevateWordId_Missing(ConditionOptionCall<MissingAggregationBuilder> opLambda,
OperatorCall<BsElevateWordToLabelCA> aggsLambda) {
setElevateWordId_Missing("elevateWordId", opLambda, aggsLambda);
}
public void setElevateWordId_Missing(String name, ConditionOptionCall<MissingAggregationBuilder> opLambda,
OperatorCall<BsElevateWordToLabelCA> aggsLambda) {
MissingAggregationBuilder builder = regMissingA(name, "elevateWordId");
if (opLambda != null) {
opLambda.callback(builder);
}
if (aggsLambda != null) {
ElevateWordToLabelCA ca = new ElevateWordToLabelCA();
aggsLambda.callback(ca);
ca.getAggregationBuilderList().forEach(builder::subAggregation);
}
}
public void setLabelTypeId_Terms() {
setLabelTypeId_Terms(null);
}
public void setLabelTypeId_Terms(ConditionOptionCall<TermsAggregationBuilder> opLambda) {
setLabelTypeId_Terms("labelTypeId", opLambda, null);
}
public void setLabelTypeId_Terms(ConditionOptionCall<TermsAggregationBuilder> opLambda,
OperatorCall<BsElevateWordToLabelCA> aggsLambda) {
setLabelTypeId_Terms("labelTypeId", opLambda, aggsLambda);
}
public void setLabelTypeId_Terms(String name, ConditionOptionCall<TermsAggregationBuilder> opLambda,
OperatorCall<BsElevateWordToLabelCA> aggsLambda) {
TermsAggregationBuilder builder = regTermsA(name, "labelTypeId");
if (opLambda != null) {
opLambda.callback(builder);
}
if (aggsLambda != null) {
ElevateWordToLabelCA ca = new ElevateWordToLabelCA();
aggsLambda.callback(ca);
ca.getAggregationBuilderList().forEach(builder::subAggregation);
}
}
public void setLabelTypeId_SignificantTerms() {
setLabelTypeId_SignificantTerms(null);
}
public void setLabelTypeId_SignificantTerms(ConditionOptionCall<SignificantTermsAggregationBuilder> opLambda) {
setLabelTypeId_SignificantTerms("labelTypeId", opLambda, null);
}
public void setLabelTypeId_SignificantTerms(ConditionOptionCall<SignificantTermsAggregationBuilder> opLambda,
OperatorCall<BsElevateWordToLabelCA> aggsLambda) {
setLabelTypeId_SignificantTerms("labelTypeId", opLambda, aggsLambda);
}
public void setLabelTypeId_SignificantTerms(String name, ConditionOptionCall<SignificantTermsAggregationBuilder> opLambda,
OperatorCall<BsElevateWordToLabelCA> aggsLambda) {
SignificantTermsAggregationBuilder builder = regSignificantTermsA(name, "labelTypeId");
if (opLambda != null) {
opLambda.callback(builder);
}
if (aggsLambda != null) {
ElevateWordToLabelCA ca = new ElevateWordToLabelCA();
aggsLambda.callback(ca);
ca.getAggregationBuilderList().forEach(builder::subAggregation);
}
}
public void setLabelTypeId_IpRange() {
setLabelTypeId_IpRange(null);
}
public void setLabelTypeId_IpRange(ConditionOptionCall<IpRangeAggregationBuilder> opLambda) {
setLabelTypeId_IpRange("labelTypeId", opLambda, null);
}
public void setLabelTypeId_IpRange(ConditionOptionCall<IpRangeAggregationBuilder> opLambda,
OperatorCall<BsElevateWordToLabelCA> aggsLambda) {
setLabelTypeId_IpRange("labelTypeId", opLambda, aggsLambda);
}
public void setLabelTypeId_IpRange(String name, ConditionOptionCall<IpRangeAggregationBuilder> opLambda,
OperatorCall<BsElevateWordToLabelCA> aggsLambda) {
IpRangeAggregationBuilder builder = regIpRangeA(name, "labelTypeId");
if (opLambda != null) {
opLambda.callback(builder);
}
if (aggsLambda != null) {
ElevateWordToLabelCA ca = new ElevateWordToLabelCA();
aggsLambda.callback(ca);
ca.getAggregationBuilderList().forEach(builder::subAggregation);
}
}
public void setLabelTypeId_Count() {
setLabelTypeId_Count(null);
}
public void setLabelTypeId_Count(ConditionOptionCall<ValueCountAggregationBuilder> opLambda) {
setLabelTypeId_Count("labelTypeId", opLambda);
}
public void setLabelTypeId_Count(String name, ConditionOptionCall<ValueCountAggregationBuilder> opLambda) {
ValueCountAggregationBuilder builder = regCountA(name, "labelTypeId");
if (opLambda != null) {
opLambda.callback(builder);
}
}
public void setLabelTypeId_Cardinality() {
setLabelTypeId_Cardinality(null);
}
public void setLabelTypeId_Cardinality(ConditionOptionCall<CardinalityAggregationBuilder> opLambda) {
setLabelTypeId_Cardinality("labelTypeId", opLambda);
}
public void setLabelTypeId_Cardinality(String name, ConditionOptionCall<CardinalityAggregationBuilder> opLambda) {
CardinalityAggregationBuilder builder = regCardinalityA(name, "labelTypeId");
if (opLambda != null) {
opLambda.callback(builder);
}
}
public void setLabelTypeId_Missing() {
setLabelTypeId_Missing(null);
}
public void setLabelTypeId_Missing(ConditionOptionCall<MissingAggregationBuilder> opLambda) {
setLabelTypeId_Missing("labelTypeId", opLambda, null);
}
public void setLabelTypeId_Missing(ConditionOptionCall<MissingAggregationBuilder> opLambda,
OperatorCall<BsElevateWordToLabelCA> aggsLambda) {
setLabelTypeId_Missing("labelTypeId", opLambda, aggsLambda);
}
public void setLabelTypeId_Missing(String name, ConditionOptionCall<MissingAggregationBuilder> opLambda,
OperatorCall<BsElevateWordToLabelCA> aggsLambda) {
MissingAggregationBuilder builder = regMissingA(name, "labelTypeId");
if (opLambda != null) {
opLambda.callback(builder);
}
if (aggsLambda != null) {
ElevateWordToLabelCA ca = new ElevateWordToLabelCA();
aggsLambda.callback(ca);
ca.getAggregationBuilderList().forEach(builder::subAggregation);
}
}
}
|
Markdown
|
UTF-8
| 2,309
| 2.859375
| 3
|
[] |
no_license
|
<a href="https://vimeo.com/167734723"></a>
Features
====
- FB login, logout
- Browse multiple pages
- Create new post(published/unpublished)
- Browse posts in each pages
Components
====
Application
- [react.js](https://github.com/facebook/react)
- [Essence](https://github.com/Evo-Forge/Essence), UI framework on react
Development Environment
- Content pipeline
- [babel](https://github.com/babel/babel)
- [webpack](https://github.com/webpack/webpack)
- [node.js](https://github.com/nodejs/node)
- [I am in the author list :smile:](https://github.com/nodejs/node/blob/c161849bfa6eba42fcc7c09d06d47eaebf37f2e3/AUTHORS#L325)
- Test
- [mocha](https://github.com/mochajs/mocha), testing framework
- [enzyme](https://github.com/airbnb/enzyme), mock library for react.js
- [sinon.js](https://github.com/sinonjs/sinon), general mock library
Design
====
UI Components
----
This is my first react.js application. I tried to understand basic ideas of react.js state management.
[App](./app/scripts/components/App.jsx)
It manages login, logout states by traditional FSM style. There are following states.

[LoginWindow](app/scripts/components/LoginWindow.jsx)
It shows FB login button with message.
[PageWindow](app/scripts/components/PageWindow.jsx)
It is the root component of manager.
- switch page
- show new posts after sending
[Post](app/scripts/components/Post.jsx)
It expands and collapses post content.
[PostComposer](app/scripts/components/PostComposer.jsx)
- send a new post
- show effects to help users
[SpinnerWindow.jsx](app/scripts/components/SpinnerWindow.jsx)
It shows spin with message.
[TitleBar](app/scripts/components/TitleBar.jsx)
It provides 2 menus.
- page list
- setting menu(logout)
Automated Tests
----
There are 2 types of tests in `tests/` directory.
- unit test: test for utility functions using mocha and sinon
- integration test: test for components using mocha, enzyme and sinon
- make sure login, logout flow
Usage
====
- install node v5.11.1
- git clone [this repo]
- npm install -d
- npm run build
- npm run prod
- open http://localtest.me:8000
and test
- npm run test:serv
- open http://localtest.me:8001
|
C
|
UTF-8
| 366
| 3.390625
| 3
|
[] |
no_license
|
#include <stdio.h>
#include <conio.h>
int main()
{
double fat, n;
printf("Insira um valor para o qual deseja calcular seu fatorial: ");
scanf("%lf", &n);
if (n <= 20)
{
for(fat = 1; n > 1; n = n - 1)
fat = fat * n;
printf("\nFatorial calculado: %lf", fat);
}
else
printf("Dados invalidos!");
getche ();
return 0;
}
|
Python
|
UTF-8
| 5,506
| 3.5625
| 4
|
[] |
no_license
|
#! /usr/bin/env python
# -*- coding: utf-8 -*-
"""
@Author: Xgz
@Date: 2020/4/12
"""
from datastructure.树.二叉树 import BinTree, BinNode, in_order_traverse
class BST(BinTree):
"""二叉搜索树,继承于二叉树"""
def __init__(self):
super().__init__()
self._hot = None # 指向命中节点的父节点
def search(self, key) -> BinNode:
"""查找关键码"""
return self.search_in(self._root, key, self._hot)
def search_in(self, current_node: BinNode, key, hot: BinNode) -> BinNode:
"""
递归形式在树(子树)中查找关键码key
:param current_node: 当前(子)树根
:param key: 查找的数据项(关键码)
:param hot: BinNode 记忆热点,指向命中节点的父节点
:return: 找不到返回None,若找到返回目标节点
"""
if not current_node or key == current_node.data:
return current_node
hot = current_node # 记下当前(非空)节点
if key < current_node.data:
return self.search_in(current_node.left_child, key, hot)
else:
return self.search_in(current_node.right_child, key, hot)
"""
算法分析:
时间复杂度:运行时间正比于返回节点的深度,不超过树高O(h),h为树的高度
"""
def insert(self, key) -> BinNode:
target_node = self.search(key) # 查找目标,另外初始化self._hot
if not target_node: # 为了禁止雷同元素,故仅在查找失败时(目标节点不存在)才实施插入操作
target_node = BinNode(key, parent=self._hot) # 在target_node处创建新节点,以_hot为父节点
self._size += 1 # 更新树的规模
self.update_height_above(target_node) # 更新target_node及其历代祖先的高度
return target_node # 无论待插入的key是否在原树中,至此总有node.data == key
"""
算法分析:
时间复杂度:search操作和更新树高操作,两者时间和也不会超过 O(h),h为树的高度,
或者表示为O(log(n)),n为元素个数。
验证:对于首个节点插入之类的边界情况,均可正确处置。
"""
def remove(self, key) -> bool:
"""删除指定关键码对应的节点,删除成功返回True,否则返回False"""
target_node = self.search(key) # 定位目标节点,并初始化self._hot
if not target_node:
return False # 目标节点不存在,直接返回False
self.remove_at(target_node, self._hot) # 分两大类情况实施删除
self._size -= 1 # 更新全树的规模
self.update_height_above(self._hot) # 更新_hot节点及其历代祖先的高度
return True # 返回成功与否,由返回值指示,True:删除成功,False:删除失败
def remove_at(self, target_node: BinNode, hot: BinNode) -> BinNode:
"""
删除目标节点target_node,返回目标节点的接替者
:param target_node: 目标节点
:param hot: 目标节点的父节点
:return: 目标节点的接替者
"""
temp_node = target_node
# successor_node = None # 实际被删除节点的接替者
if not target_node.has_left_child():
successor_node = target_node.right_child # 没有左子树,右子树根节点接替
elif not target_node.has_right_child():
successor_node = target_node.left_child # 没有右子树,左子树根节点接替
else:
# 待删除节点,左、右子树都存在,此时去找删除节点的直接后继节点
temp_node = temp_node.get_successor()
# 将目标节点的直接后继节点的数据复制到目标节点,这样最终把后继结点删掉即可。
# 注意这种“移花接木”策略
target_node.data, temp_node.data = temp_node.data, target_node.data
u = temp_node.parent
if u is target_node:
# 待删除节点是目标节点的右子树的根
u.right_child = temp_node.right_child
successor_node = temp_node.rigth_child
else:
# 待删除节点不是目标节点的右子树的根
u.left_child = temp_node.right_child
successor_node = temp_node.right_child
self.update_height_above(u)
self._hot = u # 更新self._hot
hot = temp_node.parent
if successor_node:
successor_node.parent = hot
# release(temp_node.data) # C/C++需要释放删除节点对象及其里面的数据项,Java、Python不需要
# release(temp_node)
return successor_node # 返回接替者
"""
算法分析:
时间复杂度:O(h),h为树的高度
"""
if __name__ == '__main__':
bst = BST()
root = bst.insert(9)
bst.set_root(root)
bst.insert(4)
bst.insert(40)
bst.insert(2)
bst.insert(6)
bst.insert(25)
bst.insert(50)
bst.insert(30)
in_order_traverse(bst.get_root())
|
PHP
|
UTF-8
| 383
| 3.140625
| 3
|
[] |
no_license
|
<?php
// cach 1 khai bao mang khong lien tuc
$course = array();
$course["php"] = "php"; //key: php
$course["zend"] = "Zend Framework"; //key: zend
$course["laravel"] = "Laravel"; //key: laravel
$course["symfony"] = "Symfony"; //key: symfony
$course[] = "Item 1"; // key: 1
$course[] = "Item 2"; // key: 2
echo"<pre>";
print_r($course);
echo"</pre>";
echo $course[1];
|
Python
|
UTF-8
| 3,731
| 2.765625
| 3
|
[] |
no_license
|
from flask import Flask, jsonify
import sqlalchemy
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import Session
from sqlalchemy import create_engine, func, desc
import datetime as dt
engine = create_engine("sqlite:///Resources/hawaii.sqlite")
Base = automap_base()
Base.prepare(engine, reflect=True)
Measurement = Base.classes.measurement
Station = Base.classes.station
session = Session(engine)
app = Flask(__name__)
# /
@app.route("/")
def home():
return(
"Available Routes:<br/>"
"/api/v1.0/precipitation<br/>"
"/api/v1.0/stations<br/>"
"/api/v1.0/tobs<br/>"
"/api/v1.0/start-date<br/>"
"/api/v1.0/start-date/end-date<br/>"
"Enter Date in year-month-day format, two digits each."
)
@app.route("/api/v1.0/precipitation")
def precipitation():
rain_dict = {}
# Convert the query results to a Dictionary using date as the key and prcp as the value.
for info in session.query(Measurement):
rain_dict.update({info.date : info.prcp})
# Return the JSON representation of your dictionary.
return jsonify(rain_dict)
@app.route("/api/v1.0/stations")
def stations():
station_list = []
for x in session.query(Station):
station_list.append(x.station)
return jsonify(station_list)
# Return a JSON list of stations from the dataset.
@app.route("/api/v1.0/tobs")
def tobs():
temp_list = []
#shouldn't just hardcode...
yearAgo = dt.datetime.strftime(dt.date(2016, 11,1)-dt.timedelta(days=365), '%Y-%m-%d')
# resulting_query = session.query(Measurement.tobs, Measurement.date)
for x in session.query(Measurement).filter(Measurement.date >= yearAgo).filter(Measurement.date <= '2016-11-1').limit(365):
temp_list.append(x.tobs)
return jsonify(temp_list)
# query for the dates and temperature observations from a year from the last data point.
# Return a JSON list of Temperature Observations (tobs) for the previous year.
@app.route("/api/v1.0/<start>")
def justStart(start):
#I hope this doesn't need to be in here, but I guess I am feeling paranoid about it.
if start == "start-date":
return "Please enter a date in the form Year-Month-Day, with 4 digits for the year, and two for the month and day, ex. 2016-11-1"
# start_date = dt.datetime.strptime(start, '%Y-%m-%d')
return jsonify(session.query(func.min(Measurement.tobs), func.max(Measurement.tobs), func.avg(Measurement.tobs))\
.filter(Measurement.date >= start).all())
# Return a JSON list of the minimum temperature, the average temperature, and the max temperature for a given start or start-end range.
# When given the start only, calculate TMIN, TAVG, and TMAX for all dates greater than and equal to the start date.
@app.route("/api/v1.0/<start>/<end>")
def startToEnd(start, end):
#I hope this doesn't need to be in here, but I guess I am feeling paranoid about it.
if start == "start-date" or end == "end-date":
return "Please enter a date in the form Year-Month-Day, with 4 digits for the year, and two for the month and day, ex. 2016-11-1"
# start_date = dt.datetime.strftime(start, '%Y-%m-%d')
# end_date = dt.datetime.strftime(end, '%Y-%m-%d')
return jsonify(session.query(func.min(Measurement.tobs), func.max(Measurement.tobs), func.avg(Measurement.tobs))\
.filter(Measurement.date >= start).filter(Measurement.date <= end).all())
# When given the start and the end date, calculate the TMIN, TAVG, and TMAX for dates between the start and end date inclusive.
if __name__ == '__main__':
app.run(debug=True)
|
Markdown
|
UTF-8
| 4,184
| 2.84375
| 3
|
[] |
no_license
|
---
layout: listing
title: Stanford University - Academic Technology Specialist
link:
country: United States
subrEmail: cncoleman@stanford.edu
organization: Stanford University
date: 2007-10-15
closingDate:
jobTitle: Academic Technology Specialist
published: false
postdate:
location:
name:
latitude:
longitude:
institution:
organization:
position:
---
# {{ page.title }}
## Description
<h3>Academic Technology Specialist, Visual Resources Center, Stanford University Libraries, Stanford University</h3>
<p>The Visual Resources Center (VRC) is one of several centers, schools and departments participating in the Academic Technology Specialists (ATS) Program which places technology experts with specific disciplinary training into departments where they can leverage their unique combination of skills to assists faculty in utilizing technology in the pursuit of their research and teaching goals.</p>
<p>The Visual Resources Center provides an image collection and image production services to support the instructional program of the Department of Art & Art History. Formerly aligned with the Department of Art & Art History (AAH), VRC was recently transferred to the Stanford University Libraries & Academic Information Resources (SUL/AIR), where it operates under the supervision of the Art & Architecture Library. The VRC has over 300,000 35 mm slides and 24,000 digital images and is engaged in both slide and digital image production. The collection covers all aspects of the study of art and architecture, especially Greek & Roman, European, American, Chinese and Japanese. The transfer of VRC into the SUL/AIR system provides numerous opportunities to leverage a department-based visual resource operation into a campus-wide service facility.</p>
<p>The primary goals of the University -- teaching, learning, and research -- are centered on the accumulation and distribution of information among faculty, staff, and students, and the primary goal of the ATS is to support this mission through practical and creative uses of technology. An ATS position is multifaceted, and an ATS must be comfortable managing (juggling) a range of projects and duties that may include the development of complex web applications and/or databases on the one hand while assisting faculty in acquiring new technology skills.</p>
<p>The ATS will play a central role in strategic planning and program development as VRC works to enhance and significantly expand its existing operation. The ATS will be responsible for leveraging technologies to achieve efficiencies in the digital production process, developing a back-up system for the imagebase, and designing a stable production platform from which to move forward. The recent incorporation of a Film and Media Studies program into AAH will require the addition of a digital video service for instructional support. The VRC will also need to expand its technological infrastructure to support the curricular requirements for the Electronic Media Arts program. As these VRC services grow, the ATS will be responsible for designing, developing and deploying the necessary technology solutions including a major initiative to network the imagebase, and provide VRC services online to the larger Stanford academic community.</p>
<p>The ideal candidate will have a record of innovation and creativity in leveraging technology to make resources accessible, understandable, and appealing to an academic audience and demonstrated leadership and resourcefulness in identifying and integrating technological solutions to research and pedagogical needs. The ability to work closely and respectfully with VRC staff, Art & Architecture Library staff, under the supervision of the Head of the Art & Architecture Library, in an extremely collegial, service-based, and forward-looking operation, is essential.<p>
<p>For a full job description with detailed responsibilities and necessary qualifications, visit <a href="http://jobs.stanford.edu/find_a_job.html">http://jobs.stanford.edu/find_a_job.html</a> and enter the job number, 22353 in the keyword search field. To apply for the job, select Apply at the bottom of the job page.</p>
|
Swift
|
UTF-8
| 997
| 4.0625
| 4
|
[
"Apache-2.0"
] |
permissive
|
/*
Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Note that an empty string is also considered valid.
*/
class Solution {
func isValid(_ s: String) -> Bool {
if s.isEmpty { return true }
let cs = Array.init(s)
var stack = [Character]()
for n in cs {
if n == "{" {
stack.append("}")
} else if n == "[" {
stack.append("]")
} else if n == "(" {
stack.append(")")
} else {
if stack.last == n {
stack.removeLast()
} else {
return false
}
}
}
return stack.isEmpty
}
}
var temp = Solution()
temp.isValid("{}")
|
Python
|
UTF-8
| 1,654
| 2.890625
| 3
|
[] |
no_license
|
from abc import abstractclassmethod
from pygame.event import Event
from final_project.handwritting_recognition import constants
from final_project.handwritting_recognition.pygame.misc.image_panel import ImagePanel
from final_project.handwritting_recognition.pygame.settings import Settings
class Panel():
#Constructors
def __init__(self, screen, settings:Settings, background_img_path:str = None):
"""
screen: the pygame screen
settings: the Settings object
background_img_path: path to the background image (just file name with extension)
"""
self._screen = screen
self._settings:Settings = settings
self._background_img:ImagePanel = ImagePanel(path=constants.path_img_background_folder + background_img_path) if background_img_path != None else None
#Setters and Getters
def get_screen(self):
return self._screen
def set_screen(self, screen):
self._screen = screen
def get_settings(self) -> Settings:
return self._settings
def set_settings(self, settings:Settings):
self._settings = settings
#Other Methods
def draw_components(self):
"""Method to draw the components of the screen"""
if (self._background_img != None):
self._background_img.draw(self._screen)
#Abstract Methods
@abstractclassmethod
def check_events(self, event:Event):
"""Abstract method to check for events"""
pass
@abstractclassmethod
def reset_defaults(self):
"""Reset the components to their default states"""
pass
|
Java
|
UTF-8
| 5,891
| 2.859375
| 3
|
[
"MIT"
] |
permissive
|
/**
* This software is released as part of the Pumpernickel project.
*
* All com.pump resources in the Pumpernickel project are distributed under the
* MIT License:
* https://github.com/mickleness/pumpernickel/raw/master/License.txt
*
* More information about the Pumpernickel project is available here:
* https://mickleness.github.io/pumpernickel/
*/
package com.pump.plaf;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.Line2D;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import javax.swing.JComponent;
/**
* Twelve short line segments that rotate in a clockwise direction. The line
* segments are painted in the component's foreground color, with varying levels
* of opacity.
* <p>
* <table summary="Sample Animations of AquaThrobberUI" cellpadding="10">
* <tr>
* <td><img src=
* "https://github.com/mickleness/pumpernickel/raw/master/resources/throbber/AquaThrobberUI.gif"
* alt="AquaThrobberUI"></td>
* <td><img src=
* "https://github.com/mickleness/pumpernickel/raw/master/resources/throbber/AquaThrobberUIx2.gif"
* alt="AquaThrobberUI Magnified 2x"></td>
* <td><img src=
* "https://github.com/mickleness/pumpernickel/raw/master/resources/throbber/AquaThrobberUIx4.gif"
* alt="AquaThrobberUI Magnified 4x"></td>
* </tr>
* </table>
* <p>
* On installation: the component's foreground is set to gray, but if that is
* changed then that color is used to render this animation.
* <P>
* The default period for this animation is 500, but you can modify this with
* the period client properties {@link ThrobberUI#PERIOD_KEY} or
* {@link ThrobberUI#PERIOD_MULTIPLIER_KEY}.
*/
public class AquaThrobberUI extends ThrobberUI {
/** The number of milliseconds for the default period (500). */
public static final int DEFAULT_PERIOD = 500;
private static final Line2D line = new Line2D.Float();
private static final Map<Color, Color[]> foregroundTable = new HashMap<Color, Color[]>();
private Color defaultForeground;
public AquaThrobberUI() {
this(Color.gray);
}
/**
* Create a AquaThrobberUI that will render with a default color. Note this
* color is overridden by the JComponent's foreground color, if possible.
*/
public AquaThrobberUI(Color foreground) {
super(DEFAULT_PERIOD / 12);
Objects.requireNonNull(foreground);
this.defaultForeground = foreground;
}
/**
* Paints the 12 angular lines in a circle often used to indicate progress
* in the Aqua interface.
* <p>
* It is strongly recommended that you use quality rendering hints (include
* stroke control) to achieve an aesthetic look.
*
* @param g
* the graphics to paint to
* @param fraction
* a fractional value between [0,1] indicating how far the angle
* has progress. As this value increases the highlighted line
* segment moves clockwise. The default behavior is for this
* value to iterate from [0,1] in approximately 1 second.
* @param foreground
* the color of the darkest line segment. All other line segments
* are calculated as translucent shades of this color.
* @param centerX
* the x-value of the center of this circle.
* @param centerY
* the y-value of the center of this circle.
* @param r1
* the radius of one end point of a line segment in this circle.
* The default value is 5.
* @param r2
* the radius of the other end point of a line segment in this
* circle. The default value is 8.
* @param strokeWidth
* the width of the stroke. The default value is 1.9f.
*/
public static void paint(Graphics2D g, float fraction, Color foreground,
int centerX, int centerY, int r1, int r2, float strokeWidth) {
if (fraction < 0)
throw new IllegalArgumentException(
"fraction (" + fraction + ") must be within [0, 1]");
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
int i = (int) (fraction * 12);
Color[] colors = foregroundTable.get(foreground);
if (colors == null) {
int red = foreground.getRed();
int green = foreground.getGreen();
int blue = foreground.getBlue();
colors = new Color[] { new Color(red, green, blue, 255),
new Color(red, green, blue, 240),
new Color(red, green, blue, 225),
new Color(red, green, blue, 200),
new Color(red, green, blue, 160),
new Color(red, green, blue, 130),
new Color(red, green, blue, 115),
new Color(red, green, blue, 100),
new Color(red, green, blue, 90),
new Color(red, green, blue, 80),
new Color(red, green, blue, 70),
new Color(red, green, blue, 60)
};
}
g.setStroke(new BasicStroke(strokeWidth, BasicStroke.CAP_ROUND,
BasicStroke.JOIN_BEVEL));
double theta;
for (int a = 0; a < colors.length; a++) {
g.setColor(colors[(i + a) % colors.length]);
theta = -((double) a) / (colors.length) * Math.PI * 2;
line.setLine(centerX + r1 * Math.cos(theta),
centerY + r1 * Math.sin(theta),
centerX + r2 * Math.cos(theta),
centerY + r2 * Math.sin(theta));
g.draw(line);
}
}
@Override
public Dimension getPreferredSize() {
return new Dimension(19, 19);
}
@Override
public void paintForeground(Graphics2D g, JComponent jc, Dimension size,
Float fixedFraction) {
float f;
if (fixedFraction == null) {
int p = getPeriod(jc, DEFAULT_PERIOD);
f = ((float) (System.currentTimeMillis() % p)) / ((float) p);
} else {
f = fixedFraction;
}
Color color = jc == null ? getDefaultForeground() : jc.getForeground();
paint(g, f, color, size.width / 2, size.height / 2, 5, 8, 1.9f);
}
@Override
public Color getDefaultForeground() {
return defaultForeground;
}
}
|
C
|
UTF-8
| 10,876
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <getopt.h>
#include "klp_matrix_params.h"
#include "shared/constants.h"
KLP_PARAMS init_klp_matrix_params() {
KLP_PARAMS parameters = {
.start_state = -1,
.end_state = -1,
.bp_dist = 0,
.max_dist = 0,
.epsilon = 0.,
.run_type = '!',
.energy_based = 0,
.hastings = 0,
.rate_matrix = 0,
.output_only = 0,
.run_type_count = 0
};
return parameters;
}
void parse_klp_matrix_args(KLP_PARAMS* parameters, int argc, char** argv, void (*usage)()) {
int c;
opterr = 0;
while (optind < argc) {
if ((c = getopt(argc, argv, "+A:Z:N:D:O:FTXEHRU")) != -1) {
#ifdef INPUT_DEBUG
printf("parse_klp_matrix_args: %c\n", c);
#endif
switch (c) {
case 'F':
parameters->run_type = FULLY_CONNECTED_FLAG;
parameters->run_type_count++;
break;
case 'T':
parameters->run_type = TRANSITION_INPUT_FLAG;
parameters->run_type_count++;
break;
case 'X':
parameters->run_type = DIAG_MOVES_ONLY_FLAG;
parameters->run_type_count++;
break;
case 'E':
parameters->energy_based = 1;
break;
case 'H':
parameters->hastings = 1;
break;
case 'R':
parameters->rate_matrix = 1;
break;
case 'U':
parameters->output_only = 1;
break;
case 'A':
if (!sscanf(optarg, "%d", ¶meters->start_state)) {
(*usage)();
} else if (parameters->start_state < 0) {
(*usage)();
}
break;
case 'Z':
if (!sscanf(optarg, "%d", ¶meters->end_state)) {
(*usage)();
} else if (parameters->end_state < 0) {
(*usage)();
}
break;
case 'N':
if (!sscanf(optarg, "%d", ¶meters->max_dist)) {
(*usage)();
} else if (parameters->max_dist <= 0) {
(*usage)();
}
break;
case 'D':
if (!sscanf(optarg, "%d", ¶meters->bp_dist)) {
(*usage)();
} else if (parameters->bp_dist <= 0) {
(*usage)();
}
break;
case 'O':
if (!sscanf(optarg, "%lf", ¶meters->epsilon)) {
(*usage)();
} else if (parameters->epsilon <= 1e-16) {
(*usage)();
}
break;
case '?':
#ifdef INPUT_DEBUG
printf("\tcase '?' with %c\n", optopt);
#endif
switch (optopt) {
case 'A':
case 'Z':
case 'N':
case 'D':
case 'O':
fprintf(stderr, "Option -%c requires an argument.\n", optopt);
(*usage)();
}
break;
default:
(*usage)();
}
} else {
optind++;
}
}
if (parameters->run_type == '!') {
parameters->run_type = DIAG_MOVES_ONLY_FLAG;
}
#ifdef INPUT_DEBUG
printf("Done parsing.\n\n");
#endif
if (klp_matrix_error_handling(*parameters)) {
(*usage)();
}
optind = 1;
}
int klp_matrix_error_handling(const KLP_PARAMS parameters) {
int error = 0;
// Type of run check.
if (parameters.run_type_count > 1) {
fprintf(stderr, "Error: exactly one of -T, -X or -F must be provided!\n");
error++;
}
// Transition matrix input requirements.
if (RUN_TYPE(parameters.run_type, TRANSITION_INPUT_FLAG) && !(parameters.start_state >= 0 && parameters.end_state >= 0)) {
fprintf(stderr, "Error: if the -T flag is provided, -A and -Z must be explicitly set!\n");
error++;
}
// Transition matrix input restrictions.
if (RUN_TYPE(parameters.run_type, TRANSITION_INPUT_FLAG) && (parameters.hastings || parameters.energy_based)) {
fprintf(stderr, "Error: if the -T flag is provided, -H and -E are not permitted!\n");
error++;
}
// Fully connected graph restrictions.
if (RUN_TYPE(parameters.run_type, FULLY_CONNECTED_FLAG) && (parameters.hastings || parameters.energy_based)) {
fprintf(stderr, "Error: if the -F flag is provided, -H and -E are not permitted (or -A and -Z without -D)!\n");
error++;
}
// Extending k/l/p restrictions.
if (parameters.max_dist && parameters.energy_based) {
fprintf(stderr, "Error: if the -N flag is provided, -E is not permitted!\n");
error++;
}
// If we're extending k/l/p we need to know how the user wants the zero-positions filled.
if (parameters.max_dist && !parameters.epsilon) {
fprintf(stderr, "Error: if using the full grid (bounded by -N), -O needs to be specified for populating 0-probability positions!\n");
error++;
}
// If we're willing the zero-positions, we need to know the bounding size.
if (parameters.epsilon && !parameters.max_dist) {
fprintf(stderr, "Error: if using -O, the full grid (bounded by -N) needs to be specified for populating 0-probability positions!\n");
error++;
}
// MFPT will be 0.
if (parameters.start_state == parameters.end_state && parameters.start_state >= 0) {
fprintf(stderr, "Error: if the -A and -Z flags are identical the MFPT is 0!\n");
error++;
}
if (error) {
fprintf(stderr, "\n");
}
return error;
}
void debug_klp_matrix_parameters(const KLP_PARAMS parameters) {
char* buffer = calloc(128, sizeof(char));
printf("CSV parsing parameters:\n");
printf("(F) fully_connected\t\t%s\n", RUN_TYPE(parameters.run_type, FULLY_CONNECTED_FLAG) ? "Yes" : "No");
printf("(T) transition_matrix_input\t%s\n", RUN_TYPE(parameters.run_type, TRANSITION_INPUT_FLAG) ? "Yes" : "No");
printf("(X) single_bp_moves_only\t%s\n", RUN_TYPE(parameters.run_type, DIAG_MOVES_ONLY_FLAG) ? "Yes" : "No");
printf("(E) energy_based\t\t%s\n", parameters.energy_based ? "Yes" : "No");
printf("(H) hastings\t\t\t%s\n", parameters.hastings ? "Yes" : "No");
printf("(R) rate_matrix\t\t\t%s\n", parameters.rate_matrix ? "Yes" : "No");
printf("(U) output_only\t\t\t%s\n", parameters.output_only ? "Yes" : "No");
memset(buffer, ' ', 128 * sizeof(char));
sprintf(buffer, "%d", parameters.start_state);
printf("(A) start_state\t\t\t%s\n", parameters.start_state >= 0 ? buffer : "N/A");
memset(buffer, ' ', 128 * sizeof(char));
sprintf(buffer, "%d", parameters.end_state);
printf("(Z) end_state\t\t\t%s\n", parameters.end_state >= 0 ? buffer : "N/A");
memset(buffer, ' ', 128 * sizeof(char));
sprintf(buffer, "%d", parameters.max_dist);
printf("(N) max_dist\t\t\t%s\n", parameters.max_dist ? buffer : "N/A");
memset(buffer, ' ', 128 * sizeof(char));
sprintf(buffer, "%d", parameters.bp_dist);
printf("(D) bp_dist\t\t\t%s\n", parameters.bp_dist ? buffer : "N/A");
memset(buffer, ' ', 128 * sizeof(char));
sprintf(buffer, "%.2e", parameters.epsilon);
printf("(O) epsilon\t\t\t%s\n", parameters.epsilon >= 0 ? buffer : "N/A");
printf("\n");
}
void klp_matrix_usage() {
klp_matrix_flags();
abort();
}
void klp_matrix_flags() {
fprintf(stderr, "\t-A\tstart state, default is -1 (inferred from input data as the first row in the CSV whose entry in the first column is 0). If provided, should indicate the 0-indexed line in the input CSV file representing the start state.\n");
fprintf(stderr, "\t-Z\tend state, default is -1 (inferred from input data as the first row in the CSV whose entry in the second column is 0). If provided, should indicate the 0-indexed line in the input CSV file representing the end state.\n");
fprintf(stderr, "\t-N\tsequence le(N)gth, default is disabled. This flag represents the sequence length of the sequence on which kinetics is being performed. It is used to ensure that the graph is fully connected.\n");
fprintf(stderr, "\t-D\tstart/end (D)istance, default is disabled. When provided, indicates the base pair distance between the starting / ending structures. This flag is used in conjunction with the -n flag, and is needed in cases when the base pair distance between the two structures can't be inferred from the input grid.\n");
fprintf(stderr, "\t-O\tepsil(O)n, if the graph is going to be populated with all possible moves (via the -n flag), this will inflate all 0-probability positions.\n");
fprintf(stderr, "\t-T\t(T)ransition matrix input, default is disabled. If this flag is provided, the input is expected to be a row-ordered transition probability matrix, rather than a 2D energy grid. In this case, the first two columns in the CSV file are row-order indices into the transition probability matrix, and the third (final) column is the transition probability of that cell.\n");
fprintf(stderr, "\t-R\t(R)ate matrix, default is disabled. If this flag is provided, the transition rate matrix is computed rather than the transition probability matrix.\n");
fprintf(stderr, "\t-H\t(H)astings adjustment, default is disabled. If this flag is provided, the input must be in the form of an energy grid, and only diagonally adjacent moves are permitted (in the all-to-all transition case, N(X) / N(Y) == 1). Calculating N(X) and N(Y) will respect grid boundaries and the triangle equality, and the basepair distance between the two structures for kinetics is inferred from the energy grid.\n");
fprintf(stderr, "\t-E\t(E)nergy-based transitions, default is disabled. If this flag is provided, the transition from state a to b will be calculated as (min(1, exp(-(E_b - E_a) / RT)) / n) rather than (min(1, p_b / p_a) / n).\n");
fprintf(stderr, "\t-X\tsingle basepair moves, default is enabled. If this flag is provided, the input must be in the form of an energy grid, and only diagonally adjacent moves are permitted. This option makes the assumption that the input is *not* a transition probability matrix already, and the input energy grid already satisfies the triangle inequality / parity condition.\n");
fprintf(stderr, "\t-F\t(F)ully connected, if the graph is fully connected we permit transitions between arbitrary positions in the 2D grid.\n");
fprintf(stderr, "\t-U\to(U)tput only, if enabled, the code will only output the generated transition matrix, rather than compute any downstream functions with it. Output format is identical to the CSV input format, in row-order.\n\n");
}
|
Java
|
UTF-8
| 11,339
| 1.578125
| 2
|
[
"LicenseRef-scancode-free-unknown",
"LGPL-2.1-only",
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
/*
* This file is part of Sponge, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.server.launch;
import static org.spongepowered.server.launch.VanillaCommandLine.HELP;
import static org.spongepowered.server.launch.VanillaCommandLine.NO_DOWNLOAD;
import static org.spongepowered.server.launch.VanillaCommandLine.NO_VERIFY_CLASSPATH;
import static org.spongepowered.server.launch.VanillaCommandLine.TWEAK_CLASS;
import static org.spongepowered.server.launch.VanillaCommandLine.VERSION;
import com.eclipsesource.json.Json;
import com.eclipsesource.json.JsonObject;
import com.eclipsesource.json.JsonValue;
import joptsimple.BuiltinHelpFormatter;
import joptsimple.OptionSet;
import net.minecraft.launchwrapper.Launch;
import org.jline.terminal.Terminal;
import org.jline.terminal.TerminalBuilder;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.NoSuchElementException;
public final class VanillaServerMain {
private static final String LIBRARIES_DIR = "libraries";
private static final String MINECRAFT_SERVER_VERSION = "1.12.2";
private static final String MINECRAFT_SERVER_LOCAL = "minecraft_server." + MINECRAFT_SERVER_VERSION + ".jar";
private static final String MINECRAFT_MANIFEST_REMOTE = "https://launchermeta.mojang.com/mc/game/version_manifest.json";
private static final String LAUNCHWRAPPER_PATH = "/net/minecraft/launchwrapper/1.12/launchwrapper-1.12.jar";
private static final String LAUNCHWRAPPER_LOCAL = LIBRARIES_DIR + LAUNCHWRAPPER_PATH;
private static final String LAUNCHWRAPPER_REMOTE = "https://libraries.minecraft.net" + LAUNCHWRAPPER_PATH;
private static final String LAUNCHWRAPPER_SHA1 = "111e7bea9c968cdb3d06ef4632bf7ff0824d0f36";
private static final String TWEAK_ARGUMENT = "--tweakClass";
private static final String TWEAKER = "org.spongepowered.server.launch.VanillaServerTweaker";
private VanillaServerMain() {
}
public static void main(String[] args) throws Exception {
OptionSet options = VanillaCommandLine.parse(args);
if (options.has(HELP)) {
if (System.console() == null) {
// We have no supported terminal, print help with default terminal width
VanillaCommandLine.printHelp(System.err);
} else {
// Terminal is (very likely) supported, use the terminal width provided by jline
Terminal terminal = TerminalBuilder.builder().dumb(true).build();
VanillaCommandLine.printHelp(new BuiltinHelpFormatter(terminal.getWidth(), 3), System.err);
}
return;
} else if (options.has(VERSION)) {
final Package pack = VanillaServerMain.class.getPackage();
System.out.println(pack.getImplementationTitle() + ' ' + pack.getImplementationVersion());
System.out.println(pack.getSpecificationTitle() + ' ' + pack.getSpecificationVersion());
return;
}
// Download/verify Minecraft server installation if necessary and not disabled
if (!options.has(NO_VERIFY_CLASSPATH)) {
// Get the location of our jar
Path base = Paths.get(VanillaServerMain.class.getProtectionDomain().getCodeSource().getLocation().toURI()).getParent();
try {
// Download dependencies
if (!downloadMinecraft(base, !options.has(NO_DOWNLOAD))) {
System.err.println("Failed to load all required dependencies. Please download them manually:");
System.err.println("Download the Minecraft server version " + MINECRAFT_SERVER_VERSION + " and copy it to "
+ base.resolve(MINECRAFT_SERVER_LOCAL).toAbsolutePath());
System.err.println("Download " + LAUNCHWRAPPER_REMOTE + " and copy it to "
+ base.resolve(LAUNCHWRAPPER_LOCAL).toAbsolutePath());
System.exit(1);
return;
}
} catch (IOException e) {
System.err.println("Failed to download required dependencies. Please try again later.");
e.printStackTrace();
System.exit(1);
return;
}
} else {
System.err.println("Classpath verification is disabled. The server may NOT start properly unless you have all required dependencies on "
+ "the classpath!");
}
Launch.main(getLaunchArguments(TWEAKER, options.valuesOf(TWEAK_CLASS)));
}
private static String[] getLaunchArguments(String primaryTweaker, List<String> tweakers) {
if (tweakers.isEmpty()) {
return new String[]{TWEAK_ARGUMENT, primaryTweaker};
}
String[] result = new String[tweakers.size() * 2 + 2];
result[0] = TWEAK_ARGUMENT;
result[1] = primaryTweaker;
int i = 2;
for (String tweaker : tweakers) {
result[i++] = TWEAK_ARGUMENT;
result[i++] = tweaker;
}
return result;
}
private static boolean downloadMinecraft(Path base, boolean autoDownload) throws IOException, NoSuchAlgorithmException {
// Make sure the Minecraft server is available, or download it otherwise
Path path = base.resolve(MINECRAFT_SERVER_LOCAL);
if (Files.notExists(path)) {
if (!autoDownload) {
return false;
}
System.out.println("Downloading the versions manifest...");
// Download the file with all of the Minecraft versions information
JsonValue versions = downloadJson(MINECRAFT_MANIFEST_REMOTE);
String versionManifestRemote = null;
// Find the current version manifest URL
for (JsonValue versionInfo : versions.asObject().get("versions").asArray()) {
JsonObject obj = versionInfo.asObject();
String versionId = obj.get("id").asString();
if (versionId.equals(MINECRAFT_SERVER_VERSION)) {
versionManifestRemote = obj.get("url").asString();
break;
}
}
if (versionManifestRemote == null) {
throw new NoSuchElementException("Could not find " + MINECRAFT_SERVER_VERSION + "'s manifest URL");
}
JsonValue versionManifest = downloadJson(versionManifestRemote);
JsonObject serverObj = versionManifest.asObject()
.get("downloads").asObject()
.get("server").asObject();
// Find the server URL and SHA-1 digest
String serverRemote = serverObj.get("url").asString();
String sha1 = serverObj.get("sha1").asString();
downloadAndVerify(serverRemote, path, sha1);
}
path = base.resolve(LAUNCHWRAPPER_LOCAL);
if (!Files.exists(path)) {
if (!autoDownload) {
return false;
}
// Make sure Launchwrapper is available, or download it otherwise
downloadAndVerify(LAUNCHWRAPPER_REMOTE, path, LAUNCHWRAPPER_SHA1);
}
return true;
}
private static JsonValue downloadJson(String remote) throws IOException {
URL url = new URL(remote);
try (InputStreamReader reader = new InputStreamReader(url.openStream(), StandardCharsets.UTF_8)) {
return Json.parse(reader);
}
}
/**
* Downloads a file and verify its digest.
*
* @param remote The file URL
* @param path The local path
* @param expected The SHA-1 expected digest
* @throws IOException If there is a problem while downloading the file
* @throws NoSuchAlgorithmException Never because the JVM is required to support SHA-1
*/
private static void downloadAndVerify(String remote, Path path, String expected) throws IOException, NoSuchAlgorithmException {
Files.createDirectories(path.getParent());
String name = path.getFileName().toString();
URL url = new URL(remote);
System.out.println("Downloading " + name + "... This can take a while.");
System.out.println(url);
MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
// Pipe the download stream into the file and compute the SHA-1
try (DigestInputStream stream = new DigestInputStream(url.openStream(), sha1);
ReadableByteChannel in = Channels.newChannel(stream);
FileChannel out = FileChannel.open(path, StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE)) {
out.transferFrom(in, 0, Long.MAX_VALUE);
}
String fileSha1 = toHexString(sha1.digest());
if (expected.equals(fileSha1)) {
System.out.println("Successfully downloaded " + name + " and verified checksum!");
} else {
Files.delete(path);
throw new IOException("Checksum verification failed: Expected " + expected +
", got " + fileSha1);
}
}
// From http://stackoverflow.com/questions/9655181/convert-from-byte-array-to-hex-string-in-java
private static final char[] hexArray = "0123456789abcdef".toCharArray();
private static String toHexString(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
}
|
C++
|
UTF-8
| 1,053
| 3.21875
| 3
|
[] |
no_license
|
#include <string>
#include <boost/type_traits.hpp>
#include <iostream>
class Bar;
class FooBase
{
public:
FooBase( Bar &ctx ) : _barCtx( ctx ) {};
virtual ~FooBase() {};
// Some other functions
protected:
Bar &_barCtx;
};
class Baz;
template< typename T >
class Foo : public FooBase
{
public:
Foo( Bar &ctx ) : FooBase( ctx ) {};
template<typename U = T, typename = typename boost::enable_if_c<!boost::is_same<U, Baz>::value>::type>
bool doSomething( int a ) {
std::cout << "doSomething( int a )\n";
}
template<typename U = T, typename = typename boost::enable_if_c<boost::is_same<U, Baz>::value>::type>
bool doSomething( std::string &str, int x, float g ) {
std::cout << "doSomething( std::string &str, int x, float g )\n";
}
};
class Bar{};
int main() {
Bar a;
Foo<std::string> b(a);
b.doSomething(10);
//b.doSomething("he", 2, 2.f); //Compile error
Foo<Baz> c(a);
std::string lalala("lalala");
//c.doSomething(10); //Compile error
c.doSomething(lalala, 2, 2.f);
}
|
Java
|
UTF-8
| 907
| 2.015625
| 2
|
[] |
no_license
|
package com.roshan;
import java.sql.SQLException;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.roshan.Dao.AdminDao;
import com.roshan.Entities.Doctor;
@WebServlet("/doctorList")
public class AdminDoctorController extends HttpServlet{
public void service(HttpServletRequest request,HttpServletResponse response) {
AdminDao dao = new AdminDao();
try {
List<Doctor> doctors = dao.getDoctorList();
request.setAttribute("doctors", doctors);
RequestDispatcher rd = request.getRequestDispatcher("Admindoctordisplay.jsp");
rd.forward(request, response);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
|
TypeScript
|
UTF-8
| 755
| 2.828125
| 3
|
[] |
no_license
|
import { GenerationBasedCache } from "../generation-based-cache"
it("simple #1", () => {
const cache = new GenerationBasedCache();
for (let i = 0; i < 100; i++) {
expect(cache.has(`key${i}`)).toBeFalsy();
cache.set(`key${i}`, `value${i}`);
expect(cache.has(`key${i}`)).toBeTruthy();
}
})
it("simple #2", () => {
const cache = new GenerationBasedCache(60, 3);
for (let i = 0; i < 120; i++) {
cache.set(`key${i}`, `value${i}`);
expect(cache.has(`key${i}`)).toBeTruthy();
}
for (let i = 0; i < 120; i++) {
if (i < (120 - 60)) {
expect(cache.has(`key${i}`)).toBeFalsy();
} else {
expect(cache.has(`key${i}`)).toBeTruthy();
}
}
})
|
C++
|
UTF-8
| 841
| 3.96875
| 4
|
[] |
no_license
|
/* ./p03/main.cc */
#include <iostream>
using namespace std;
/* compare(t1,t2)
* Returns a value greater than zero when t1 > t2, or
* zero when t1 == t2, or a negative value when t1 < t2.
*/
template < typename T >
int compare( const T &t1, const T &t2 )
{
return ( t1 - t2 );
}
class X {
public:
// converting constructor
X( double v ) : value{v} { }
// overloaded subtraction operator '-'
X operator - ( const X &rhs ) const;
// typecast operator (converts X to int)
inline operator int () const
{ return static_cast<int>(value); }
private:
double value ;
};
// Overloaded subtraction operator '-' for class X
X
X :: operator - ( const X &rhs ) const
{
return X{ this->value - rhs.value };
}
int main()
{
X x1{1.02}, x2{1.01};
cout << compare(x1,x2) << endl;
return 0;
}
|
SQL
|
UTF-8
| 769
| 3.53125
| 4
|
[] |
no_license
|
CREATE TABLE TwitterUser (
id INT NOT NULL AUTO_INCREMENT,
name varchar(100) NOT NULL,
profileImageUrl VARCHAR(700),
PRIMARY KEY(id),
UNIQUE KEY idx_name_profileimg(name,profileImageUrl)
) engine=innodb
CREATE TABLE Tweet (
id INT auto_increment,
tweetId VARCHAR(25) NOT NULL COMMENT 'see Twitter API Tweet ID',
text VARCHAR(250) DEFAULT "EMPTY",
createdAt timestamp,
twitterUserId INT NOT NULL,
ackState INT DEFAULT 0 COMMENT '0: not touched, 1: acked, 2: blocked',
PRIMARY KEY (id),
FOREIGN KEY (twitterUserId) REFERENCES TwitterUser(id) ON DELETE CASCADE
) engine=innodb
|
C
|
UTF-8
| 2,297
| 3.109375
| 3
|
[
"CC0-1.0"
] |
permissive
|
#include "leds.h"
#include "hardware.h"
#include <stdbool.h>
// Matrix representing the on/off state of each LED.
// each LED is row,col = anode,cathode
#define N_PINS 3
static volatile bool led_states[N_PINS + 1][N_PINS + 1] = {{0}};
void set_led(uint16_t led, bool state)
{
const uint8_t row = (led & 0xff00u) >> 8;
const uint8_t col = (led & 0x00ffu);
led_states[row][col] = state;
}
static PORT_t volatile * map_to_port(uint8_t pin)
{
switch (pin) {
case 1:
return &LED_A_PORT;
case 2:
return &LED_B_PORT;
case 3:
return &LED_C_PORT;
default:
// We're not using port R, so accidental pin pokes here
// are safe
return &PORTR;
}
}
static uint8_t map_to_bit(uint8_t pin)
{
switch (pin) {
case 1:
return bm(LED_A_bp);
case 2:
return bm(LED_B_bp);
case 3:
return bm(LED_C_bp);
default:
// PR7 doesn't even exist, so pokes here do nothing
return 0x80;
}
}
static void config_pos(uint8_t row, uint8_t col)
{
map_to_port(row)->OUTSET = map_to_bit(row);
map_to_port(row)->DIRSET = map_to_bit(row);
map_to_port(col)->OUTCLR = map_to_bit(col);
map_to_port(col)->DIRSET = map_to_bit(col);
}
static void config_blank(void)
{
for (uint8_t i = 1; i <= N_PINS; ++i) {
map_to_port(i)->DIRCLR = map_to_bit(i);
}
}
enum led_cycle_states {
STATE_CONFIG,
STATE_HOLD,
STATE_BLANK,
};
void led_cycle(void)
{
static enum led_cycle_states state = STATE_BLANK;
static const uint16_t hold_limit = 100u;
static uint16_t hold_val = 0;
static uint8_t row = 1;
static uint8_t col = 1;
switch (state) {
case STATE_CONFIG:
if (led_states[row][col]) {
config_pos(row, col);
}
hold_val = 0;
state = STATE_HOLD;
break;
case STATE_HOLD:
if (hold_val == hold_limit) {
state = STATE_BLANK;
} else {
++hold_val;
}
break;
case STATE_BLANK:
config_blank();
++col;
if (col == N_PINS + 1) {
++row;
col = 1;
}
if (row == N_PINS + 1) {
row = 1;
}
state = STATE_CONFIG;
break;
}
}
|
C++
|
UTF-8
| 9,614
| 2.859375
| 3
|
[] |
no_license
|
/*********************************************************************
* Filename: sha1_test.c
* Author: Brad Conte (brad AT bradconte.com)
* Copyright:
* Disclaimer: This code is presented "as is" without any guarantees.
* Details: Performs known-answer tests on the corresponding SHA1
implementation. These tests do not encompass the full
range of available test vectors, however, if the tests
pass it is very, very likely that the code is correct
and was compiled properly. This code also serves as
example usage of the functions.
*********************************************************************/
/*************************** HEADER FILES ***************************/
#include <stdbool.h>
#include <stdio.h>
#include <memory.h>
#include <string.h>
#include <stdlib.h>
#include <memory.h>
#include <stddef.h>
#include <new>
/****************************** MACROS ******************************/
#define SHA1_BLOCK_SIZE 20 // SHA1 outputs a 20 byte digest
/**************************** DATA TYPES ****************************/
typedef unsigned char BYTE; // 8-bit byte
typedef unsigned int WORD; // 32-bit word, change to "long" for 16-bit machines
typedef struct {
BYTE data[64];
WORD datalen;
unsigned long long bitlen;
WORD state[5];
WORD k[4];
} SHA1_CTX;
struct note {
struct note * next[256];
};
struct endnote {
unsigned char str[15];
};
/****************************** MACROS ******************************/
#define ROTLEFT(a, b) ((a << b) | (a >> (32 - b)))
/*********************** FUNCTION DEFINITIONS ***********************/
void sha1_transform(SHA1_CTX* ctx, const BYTE data[])
{
WORD a, b, c, d, e, i, j, t, m[80];
for (i = 0, j = 0; i < 16; ++i, j += 4)
m[i] = (data[j] << 24) + (data[j + 1] << 16) + (data[j + 2] << 8) + (data[j + 3]);
for (; i < 80; ++i) {
m[i] = (m[i - 3] ^ m[i - 8] ^ m[i - 14] ^ m[i - 16]);
m[i] = (m[i] << 1) | (m[i] >> 31);
}
a = ctx->state[0];
b = ctx->state[1];
c = ctx->state[2];
d = ctx->state[3];
e = ctx->state[4];
for (i = 0; i < 20; ++i) {
t = ROTLEFT(a, 5) + ((b & c) ^ (~b & d)) + e + ctx->k[0] + m[i];
e = d;
d = c;
c = ROTLEFT(b, 30);
b = a;
a = t;
}
for (; i < 40; ++i) {
t = ROTLEFT(a, 5) + (b ^ c ^ d) + e + ctx->k[1] + m[i];
e = d;
d = c;
c = ROTLEFT(b, 30);
b = a;
a = t;
}
for (; i < 60; ++i) {
t = ROTLEFT(a, 5) + ((b & c) ^ (b & d) ^ (c & d)) + e + ctx->k[2] + m[i];
e = d;
d = c;
c = ROTLEFT(b, 30);
b = a;
a = t;
}
for (; i < 80; ++i) {
t = ROTLEFT(a, 5) + (b ^ c ^ d) + e + ctx->k[3] + m[i];
e = d;
d = c;
c = ROTLEFT(b, 30);
b = a;
a = t;
}
ctx->state[0] += a;
ctx->state[1] += b;
ctx->state[2] += c;
ctx->state[3] += d;
ctx->state[4] += e;
}
void sha1_init(SHA1_CTX* ctx)
{
ctx->datalen = 0;
ctx->bitlen = 0;
ctx->state[0] = 0x67452301;
ctx->state[1] = 0xEFCDAB89;
ctx->state[2] = 0x98BADCFE;
ctx->state[3] = 0x10325476;
ctx->state[4] = 0xc3d2e1f0;
ctx->k[0] = 0x5a827999;
ctx->k[1] = 0x6ed9eba1;
ctx->k[2] = 0x8f1bbcdc;
ctx->k[3] = 0xca62c1d6;
}
void sha1_update(SHA1_CTX* ctx, const BYTE data[], size_t len)
{
size_t i;
for (i = 0; i < len; ++i) {
ctx->data[ctx->datalen] = data[i];
ctx->datalen++;
if (ctx->datalen == 64) {
sha1_transform(ctx, ctx->data);
ctx->bitlen += 512;
ctx->datalen = 0;
}
}
}
void sha1_final(SHA1_CTX* ctx, BYTE hash[])
{
WORD i;
i = ctx->datalen;
// Pad whatever data is left in the buffer.
if (ctx->datalen < 56) {
ctx->data[i++] = 0x80;
while (i < 56)
ctx->data[i++] = 0x00;
}
else {
ctx->data[i++] = 0x80;
while (i < 64)
ctx->data[i++] = 0x00;
sha1_transform(ctx, ctx->data);
memset(ctx->data, 0, 56);
}
// Append to the padding the total message's length in bits and transform.
ctx->bitlen += (int)ctx->datalen * 8;
ctx->data[63] = ctx->bitlen;
ctx->data[62] = ctx->bitlen >> 8;
ctx->data[61] = ctx->bitlen >> 16;
ctx->data[60] = ctx->bitlen >> 24;
ctx->data[59] = ctx->bitlen >> 32;
ctx->data[58] = ctx->bitlen >> 40;
ctx->data[57] = ctx->bitlen >> 48;
ctx->data[56] = ctx->bitlen >> 56;
sha1_transform(ctx, ctx->data);
// Since this implementation uses little endian byte ordering and MD uses big endian,
// reverse all the bytes when copying the final state to the output hash.
for (i = 0; i < 4; ++i) {
hash[i] = (ctx->state[0] >> (24 - i * 8)) & 0x000000ff;
hash[i + 4] = (ctx->state[1] >> (24 - i * 8)) & 0x000000ff;
hash[i + 8] = (ctx->state[2] >> (24 - i * 8)) & 0x000000ff;
hash[i + 12] = (ctx->state[3] >> (24 - i * 8)) & 0x000000ff;
hash[i + 16] = (ctx->state[4] >> (24 - i * 8)) & 0x000000ff;
}
}
/*********************** FUNCTION DEFINITIONS ***********************/
int sha1_test()
{
BYTE text1[] = { "abc" };
BYTE text2[] = { "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq" };
BYTE text3[] = { "aaaaaaaaaa" };
BYTE hash1[SHA1_BLOCK_SIZE] = { 0xa9,0x99,0x3e,0x36,0x47,0x06,0x81,0x6a,0xba,0x3e,0x25,0x71,0x78,0x50,0xc2,0x6c,0x9c,0xd0,0xd8,0x9d };
BYTE hash2[SHA1_BLOCK_SIZE] = { 0x84,0x98,0x3e,0x44,0x1c,0x3b,0xd2,0x6e,0xba,0xae,0x4a,0xa1,0xf9,0x51,0x29,0xe5,0xe5,0x46,0x70,0xf1 };
BYTE hash3[SHA1_BLOCK_SIZE] = { 0x34,0x95,0xff,0x69,0xd3,0x46,0x71,0xd1,0xe1,0x5b,0x33,0xa6,0x3c,0x13,0x79,0xfd,0xed,0xd3,0xa3,0x2a };
BYTE buf[SHA1_BLOCK_SIZE];
int idx;
SHA1_CTX ctx;
int pass = 1;
int i = 0;
sha1_init(&ctx);
sha1_update(&ctx, text1, 3);
sha1_final(&ctx, buf);
pass = pass && !memcmp(hash1, buf, SHA1_BLOCK_SIZE);
sha1_init(&ctx);
sha1_update(&ctx, text2, 56);
sha1_final(&ctx, buf);
pass = pass && !memcmp(hash2, buf, SHA1_BLOCK_SIZE);
sha1_init(&ctx);
sha1_update(&ctx, text3, 10);
sha1_final(&ctx, buf);
pass = pass && !memcmp(hash3, buf, SHA1_BLOCK_SIZE);
return(pass);
}
void construct(struct note* r) {
int i = 0;
for (i = 0; i < 256; ++i) {
(*r).next[i] = NULL;
}
}
void construct2(struct endnote* r, unsigned char * str0) {
int i = 0;
for (i = 0; i < 15; ++i)
r->str[i] = str0[i];
}
inline bool addmore(struct note* head0, BYTE* output,int index, int mode, unsigned char * record) {
int i = 0, j = 0, k = 0;
struct note** pointer1 = &head0;
struct note** pointer2 = NULL;
for(i=0;i<index;++i){
if (mode == 1) {
if ((**pointer1).next[output[i]] != 0) {
++k;
pointer1 = &(**pointer1).next[output[i]];
}
else {
if(i!=index-1){
struct note* newnote;
newnote=(struct note*)malloc(1024);
construct(newnote);
(**pointer1).next[output[i]] = newnote;
pointer1 = &(**pointer1).next[output[i]];
}
else if (i == index - 1) {
struct endnote* newnote;
newnote=(struct endnote*)malloc(15);
construct2(newnote,record);
(**pointer1).next[output[i]] = (struct note*)newnote;
pointer1 = &(**pointer1).next[output[i]];
}
}
}
else if (mode == 2) {
if ((**pointer1).next[output[i]] != 0) {
++k;
pointer1 = &(**pointer1).next[output[i]];
}
}
}
if (k == index) printf("%s\n", (**((struct endnote **)pointer1)).str);
return (k == index);
}
inline void output(unsigned char* str) {
BYTE buf[SHA1_BLOCK_SIZE];
int idx;
SHA1_CTX ctx;
sha1_init(&ctx);
sha1_update(&ctx, str, 14);
sha1_final(&ctx, buf);
for (idx = 0; idx < 20; ++idx)
printf(" %.2x", buf[idx]);
printf("\n");
}
inline void convert(long long int x, unsigned char * str) {
int length = 15;
snprintf((char *)str, length -1, "%lld", x);
if((int)x%100000==0)
printf("%s\n", str);
for (int i = 0; i < 15; ++i)
if (str[i] == '\0') {
for (int j = i; j < 15; ++j)
str[j] = '*';
break;
}
}
int main()
{
unsigned char* str;
str= (unsigned char *)malloc(15*sizeof(char));
for(int i=0;i<15;++i) str[i]='0';
output((convert(28535, str),printf("-%s-\n",str), str));
output((convert(38626, str), printf("-%s-\n", str), str));
output((convert(97809, str), printf("-%s-\n", str), str));
output((convert(3319170, str), printf("-%s-\n", str), str));
output((convert(42930, str), printf("-%s-\n", str), str));
output((convert(489314, str), printf("-%s-\n", str), str));
output((convert(114008, str), printf("-%s-\n", str), str));
output((convert(13999272, str), printf("-%s-\n", str), str));
convert(0, str);
struct note *head0;
head0=(struct note*)malloc(1024);
construct(head0);
BYTE hash1[SHA1_BLOCK_SIZE] = { 0xa9,0x99,0x3e,0x36,0x47,0x06,0x81,0x6a,0xba,0x3e,0x25,0x71,0x78,0x50,0xc2,0x6c,0x9c,0xd0,0xd8,0x9d };
BYTE hash2[SHA1_BLOCK_SIZE] = { 0xa9,0x99,0x3e,0x36,0x47,0x06,0x81,0x6a,0xba,0x3e,0x25,0x71,0x78,0x50,0xc2,0x6c,0x9c,0xd0,0xd8,0x9d };
BYTE hash3[SHA1_BLOCK_SIZE] = { 0xa9,0x89,0x3e,0x36,0x47,0x06,0x81,0x6a,0xba,0x3e,0x25,0x71,0x78,0x50,0xc2,0x6c,0x9c,0xd0,0xd8,0x9d };
BYTE hash4[SHA1_BLOCK_SIZE] = { 0xa9,0x89,0x3e,0x36,0x47,0x06,0x81,0x6a,0xba,0x3e,0x25,0x71,0x78,0x50,0xc2,0x6c,0x9c,0xd0,0xd8,0x9d };
BYTE hash5[SHA1_BLOCK_SIZE] = { 0xa9,0x99,0x3e,0x36,0x47,0x06,0x81,0x6a,0xba,0x3e,0x25,0x71,0x78,0x50,0xc2,0x6c,0x9c,0xd0,0xd8,0x9d };
BYTE hash6[SHA1_BLOCK_SIZE] = { 0xa9,0x99,0x3e,0x36,0x47,0x06,0x81,0x61,0xba,0x3e,0x25,0x71,0x78,0x50,0xc2,0x6c,0x9c,0xd0,0xd8,0x9d };
BYTE buf[SHA1_BLOCK_SIZE];
int idx;
SHA1_CTX ctx;
int pass = 1;
int i = 0;
long long int lli = 0;
for (lli = 0; lli < 123456789012345; ++lli) {
sha1_init(&ctx);
convert(lli, str);
sha1_update(&ctx, str, 14);
sha1_final(&ctx, buf);
if (lli < 200000) {
if (addmore(head0, buf, 4, 1,str)) {
printf("\n ! !!! !\n");
break;
}
}
else {
if (addmore(head0, buf, 4, 2,str)) {
printf("\n ! !!! !\n");
break;
}
}
}
printf("\n%lld\n", lli);
return(0);
}
|
Python
|
UTF-8
| 1,448
| 2.828125
| 3
|
[] |
no_license
|
from mysqlDb import mysql
from flask import Flask, render_template, url_for, request, redirect, session, flash
def tipoAnimalInicio():
print("TIPO ANIMAL:")
cur = mysql.connection.cursor()
cur.execute('SELECT * FROM tipoanimal')
data = cur.fetchall()
cur.close()
return render_template("tipoAnimal.html", animales=data)
def tipoAnimalAdd(nombre):
# Crear cursor
cur = mysql.connection.cursor()
# Preparar el query y ejecutar query
query = "INSERT INTO tipoanimal (tipoAnimalNom) VALUES ('" + \
nombre + "')"
cur.execute(query)
mysql.connection.commit()
# Cerramos Conexion
cur.close()
flash("El tipo de animal se ingreso correctamente", "alert-success")
return redirect(url_for('TipoAnimal'))
def tipoAnimalDelete(id):
cur = mysql.connection.cursor()
cur.execute(
'DELETE FROM tipoanimal WHERE tipoAnimalId = {0}'.format(id))
mysql.connection.commit()
cur.close()
flash("El tipo de animal se elimino correctamente", "alert-success")
return redirect(url_for('TipoAnimal'))
def tipoAnimalUpdate(nombre, idTipoAnimal):
cur = mysql.connection.cursor()
cur.execute(
'UPDATE tipoanimal SET tipoAnimalNom = %s WHERE tipoAnimalId = %s', (nombre, idTipoAnimal))
mysql.connection.commit()
cur.close()
flash("El tipo de animal se actualizó correctamente", "alert-success")
return redirect(url_for('TipoAnimal'))
|
C#
|
UTF-8
| 1,979
| 3.359375
| 3
|
[] |
no_license
|
using Badges;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _03_BadgeUI
{
public class ProgramUI
{
private readonly BadgeRepo _badgeRepo = new BadgeRepo();
public void Run()
{
RunMenu();
}
private void RunMenu()
{
bool continueToRun = true;
while (continueToRun)
{
Console.Clear();
Console.WriteLine("Hello Security Admin, What would you like to do? \n" +
"1. Add a badge. \n" +
"2. Edit a badge. \n" +
"3. List all badges. \n");
String userinput = Console.ReadLine();
switch (userinput)
{
case "1":
AddNewBadge();
break;
case "2":
EditBadge();
break;
case "3":
ListBadges();
break;
}
}
}
public void AddNewBadge()
{
Badge badge = new Badge();
Console.WriteLine("Waht is the number on the badge:");
badge.BadgeID = int.Parse(Console.ReadLine());
Console.WriteLine("List a door that i needs access to:");
badge.DoorNames = (Console.ReadLine());
}
public void EditBadge()
{
}
public void ShowAll(Badge badges)
{
Console.WriteLine($"Key\n" +
$"Badge #: \n{badges.BadgeID}");
}
public void ListBadges ()
{
List<Badge> listOfBadges = _badgeRepo.GetBadges();
foreach (Badge badge in listOfBadges)
{
ShowAll(badge);
}
}
}
}
|
Python
|
UTF-8
| 608
| 3.3125
| 3
|
[] |
no_license
|
import pprint # for preety print
messege='''A newly initialized Chatterbot instance starts off with no knowledge of how to communicate. To allow it to properly respond to user inputs, the instance needs to be trained to understand how conversations flow. Since Chatterbot relies on machine learning at its backend, it can very easily be taught conversations by providing it with datasets of conversations.'''
count={}
for chr in messege:
count.setdefault(chr,0)
count[chr] = count[chr] + 1
# x=pprint.pformat(count) #use pprint.pformat to get output as string value
# print(x)
pprint.pprint(count)
|
PHP
|
UTF-8
| 674
| 2.78125
| 3
|
[] |
no_license
|
<?php
/**
* Created by PhpStorm.
* User: samoilenko
* Date: 2018-12-08
* Time: 22:40
*/
declare(strict_types=1);
namespace App\Basket\Model\ERP;
use App\Basket\Model\Exception\UnknownProduct;
interface ERP
{
/**
* Get stock information for given product
*
* If stock information cannot be fetched from the ERP system
* this method returns null.
*
* If product is not known by the ERP system this method must throw an UnknownProduct exception
*
* @param ProductId $productId
* @return ProductStock|null
* @throws UnknownProduct
*/
public function getProductStock(ProductId $productId): ?ProductStock;
}
|
Java
|
UTF-8
| 2,313
| 2.15625
| 2
|
[] |
no_license
|
package com.icms.cms.web.admin;
import java.util.List;
import com.icms.cms.base.AController;
import com.icms.cms.model.Category;
import com.icms.cms.model.Topic;
import com.icms.cms.service.CategoryService;
import com.icms.cms.service.TopicService;
import com.icms.common.shiro.ShiroUtil;
import com.icms.common.util.CmsUtil;
import com.icms.config.AppConst;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.render.JsonRender;
public class TopicController extends AController {
@Override
public void index() {
int pageNumber = getParaToInt(0,1);
Page<Topic> pages = TopicService.service.getPageAll(pageNumber);
setAttr("pages", pages);
renderAdmin("topic-list");
}
@Override
public void input() {
Integer topicId = getParaToInt(0);
if(topicId!=null){
Topic t = TopicService.service.getTopicByTopicId(topicId);
setAttr("topic", t);
}
renderAdmin("topic-input");
}
@Override
public void save() {
Topic topic = getModel(Topic.class, "Topic");
if(TopicService.service.AddOrUpdate(topic)){
renderSuccess("保存成功!");
} else {
renderError("保存失败!");
}
}
@Override
public void del() {
Integer topicId = getParaToInt(0);
if(TopicService.service.delByTopicId(topicId)){
renderJson(true);
} else {
renderJson(false);
}
}
//获取分类列表
public void getCategoryList() {
Integer siteId = (Integer) ShiroUtil.getSessionAttr(AppConst.SITE_ID);
StringBuffer result = new StringBuffer();
List<Category> list = null;
result.append("[");
result.append("{id:0, pId:0, name:\"栏目分类\", open:true,nocheck:true},");
list = CategoryService.service.getCategoryListBySiteId(siteId);
for (int i = 0; i < list.size(); i++) {
Category category = list.get(i);
String jsonStr = "id:'" + category.getCategoryId() + "',name:'"+category.getCategoryName() + "',pId:"
+ category.getParentId();
result.append("{");
if(!CmsUtil.isNullOrEmpty(CategoryService.service.getCategoryBySiteIdAndParentId(siteId, category.getCategoryId()))){
jsonStr+=",nocheck:true";
}
result.append(jsonStr+=",open:true");
result.append("}");
if (i < list.size() - 1) {
result.append(",");
}
}
result.append("]");
render(new JsonRender(result.toString()).forIE());
}
}
|
Java
|
UTF-8
| 2,012
| 2.3125
| 2
|
[] |
no_license
|
package team404.restaurant.employee.controller;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import team404.restaurant.employee.dto.EmployeeDto;
import team404.restaurant.employee.dto.EmployeeWithPasswordDto;
import team404.restaurant.employee.service.EmployeeService;
import java.util.List;
import java.util.UUID;
@Tag(name = "Employee")
@RestController
@RequiredArgsConstructor
@PreAuthorize("isAuthenticated()")
@CrossOrigin(origins = "*", maxAge = 3600, allowedHeaders = "*")
public class EmployeeController {
private final EmployeeService employeeService;
@Operation(summary = "Get employees information by restaurant id")
@GetMapping("/api/employee/restaurant")
@PreAuthorize("hasAuthority('RESTAURATEUR')")
public List<EmployeeDto> getEmployeesInRestaurant(@RequestParam UUID restaurantId) {
return employeeService.getEmployeesByRestaurant(restaurantId);
}
@Operation(summary = "Get employee with password by employee id")
@GetMapping("/api/employee/account/{employeeId}")
@PreAuthorize("hasAuthority('RESTAURATEUR')")
public EmployeeWithPasswordDto getEmployeeWithPassword(@PathVariable UUID employeeId) {
return employeeService.getEmployeeWithAccount(employeeId);
}
@Operation(summary = "Get current employee")
@GetMapping("/api/employee/current")
@PreAuthorize("hasAnyAuthority('WAITER', 'COOK')")
public EmployeeDto getCurrentEmployee() {
return employeeService.getCurrentEmployee();
}
}
|
C++
|
UTF-8
| 1,004
| 2.75
| 3
|
[] |
no_license
|
#ifndef AVKeyCode_h
#define AVKeyCode_h
#include "OpenVanilla.h"
#include <ctype.h>
class AVKeyCode : public OVKeyCode {
public:
AVKeyCode (int p = 0)
{
chr = toupper(p);
isShift_ = isCapsLock_ = isCtrl_ = isAlt_ = isNum_ =0;
}
virtual int code() { return (isShift_||isCapsLock_||isCtrl_||isAlt_) ? chr : tolower(chr); }
virtual bool isShift() { return isShift_; }
virtual bool isCapslock() { return isCapsLock_; }
virtual bool isCtrl() { return isCtrl_; }
virtual bool isAlt() { return isAlt_; }
virtual bool isNum() { return isNum_; }
virtual void setCode(int x) { chr = toupper(x); }
virtual void setShift(bool x) { isShift_ = x; }
virtual void setCapslock(bool x) { isCapsLock_ = x; }
virtual void setCtrl(bool x) { isCtrl_ = x; }
virtual void setAlt(bool x) { isAlt_ = x; }
virtual void setNum(bool x) { isNum_ = x; }
protected:
int chr;
bool isShift_, isCapsLock_, isCtrl_, isAlt_, isNum_;
};
#endif // AVKeyCode_h
|
Python
|
UTF-8
| 185
| 3.140625
| 3
|
[] |
no_license
|
d=int(input())
a=[]
for i in range(0,d):
g=int(input())
a.append(g)
count=0
for i in a:
for x in a:
if i==x:
count+=2
if count==2:
print(i)
|
Markdown
|
UTF-8
| 1,524
| 3.796875
| 4
|
[
"Apache-2.0"
] |
permissive
|
# Bluffalo
Bluffalo allows you to do real mocking and stubbing in Swift.
## What does it do?
It generates a subclass of whatever class you want with some extra methods and properties that allow you to stub values and see what was called.
## Limitations
- Because this relies on subclassing, this will not work for stubs.
- Properties cannot be stubbed yet.
# Usage
## Generating a fake
```
bluffalo -file path/to/Cat.swift -outputFile path/to/FakeCat.swift -module containingModule
```
You should add the outputted file to your project. The command used to create the fake will be added as a comment to the top of the file. This will make it easier to regenerate your class if you change it.
## Using a fake
Lets say we have the following class
```
class Cat {
func numberOfLives() -> Int {
return 9
}
func meow(numberOfTimes: Int) {
while i < numberOfTimes {
print("Meow")
}
}
}
```
### Stubbing Values
```
let fakeCat = FakeCat()
print( fakeCat.numberOfLives() ) // prints 9
fakeCat.stub(.numberOfLives()).andReturn(4)
print( fakeCat.numberOfLives() ) // prints 4
```
### Mocking
```
let fakeCat = FakeCat()
let numberOfLives = fakeCat.numberOfLives()
fakeCat.meow(numberOfTimes: 5)
print( fakeCat.didCall(method: .numberOfLives()) ) // prints true
print( fakeCat.matchingMethods(.numberOfLives()) ) // prints 1
// Arguments matter
print( fakeCat.didCall(method: .meow(numberOfTimes: 5)) ) // prints true
print( fakeCat.didCall(method: .meow(numberOfTimes: 4)) ) // prints false
```
|
TypeScript
|
UTF-8
| 1,710
| 2.9375
| 3
|
[] |
no_license
|
import Point from '../math/Point';
import Screen from './Screen';
import GameObject from '../gameobject/GameObject';
export default class Camera extends GameObject {
public position: Point = new Point();
private followTarget: GameObject | null;
private followSpeed: number = 1;
private screen: Screen;
constructor(screen: Screen) {
super();
this.screen = screen;
}
sees(target: GameObject): boolean {
//followed object is always visible
if (target === this.followTarget) return true;
//translate camera position to normal canvas viewport
let selfPosition = this.position.clone().mul(-1);
let targetPosition = target.position.clone();
let camRelPosition = targetPosition.sub(selfPosition);
//if detects square collision the target is visible
let c1 = camRelPosition.y < this.screen.canvas.height;
let c2 = camRelPosition.y + target.height > 0;
let c3 = camRelPosition.x + target.width > 0;
let c4 = camRelPosition.x < this.screen.canvas.width;
return c1 && c2 && c3 && c4;
}
follow(target: GameObject, speed: number = 1): Camera {
this.followTarget = target;
this.followSpeed = speed;
return this;
}
stopFollow(): Camera {
this.followTarget = null;
return this;
}
update(delta: number) {
if (!this.followTarget) return this;
let lerpTo = this.followTarget.position
.clone().sub(this.screen.halfSize).mul(-1)
.sub(this.followTarget.width >> 1, this.followTarget.height >> 1);
this.position.lerp(lerpTo, this.followSpeed);
return this;
}
}
|
Java
|
UTF-8
| 4,341
| 2.84375
| 3
|
[] |
no_license
|
package grafika2b;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.image.BufferedImage;
import javax.swing.JFrame;
public class Transformation implements KeyListener {
private BufferedImage _tex;
private Matrix _matrix = Matrix.identity( 3 );
private final Vector[] _srcPoints; // punktu org. wspolrzednych
// private final Point[] _points; // punkty po przeksztalceniach, wyswietlane na ekranie
private final Edge[] _edges;
private Vector[] _drawPoints;
public Transformation( Vector[] points, Edge[] edges, int w, int h ) {
_srcPoints = points;
_drawPoints = new Vector[points.length];
_edges = edges;
update( w, h );
}
@Override
public void keyReleased( KeyEvent e ) {
JFrame f = ( JFrame ) e.getSource();
final float moveDist = 0.1f, angle = 30;
switch ( e.getKeyCode() ) {
case KeyEvent.VK_ESCAPE:
System.exit( 0 );
break;
case KeyEvent.VK_E:
_matrix = _matrix.translate( 0.5f, 0.5f ); // transform to center
_matrix = _matrix.rotate( angle );
_matrix = _matrix.translate( -0.5f,-0.5f ); // transform back
break;
case KeyEvent.VK_Q:
_matrix = _matrix.translate( 0.5f, 0.5f );
_matrix = _matrix.rotate( -angle );
_matrix = _matrix.translate( -0.5f,-0.5f );
break;
case KeyEvent.VK_W:
_matrix = _matrix.translate( 0, -moveDist );
break;
case KeyEvent.VK_S:
_matrix = _matrix.translate( 0, moveDist );
break;
case KeyEvent.VK_A:
_matrix = _matrix.translate( -moveDist, 0 );
break;
case KeyEvent.VK_D:
_matrix = _matrix.translate( moveDist, 0 );
break;
case KeyEvent.VK_R:
_matrix = _matrix.translate( 0.5f, 0.5f );
_matrix = _matrix.scale( 0.5f, 0.5f );
_matrix = _matrix.translate( -0.5f,-0.5f );
break;
case KeyEvent.VK_F:
_matrix = _matrix.translate( 0.5f, 0.5f );
_matrix = _matrix.scale( 2, 2 );
_matrix = _matrix.translate( -0.5f, -0.5f );
break;
}
update( f.getWidth(), f.getHeight() );
f.repaint();
f.validate();
}
public BufferedImage getImage() {
return _tex;
}
private void update( int w, int h ) {
for ( int i = 0; i < _srcPoints.length; i++ ) {
_drawPoints[i] = _matrix.mul( new Vector( _srcPoints[i].x(), _srcPoints[i].y(), 1.0f ) );
}
System.out.println( "got:\n" + _matrix ); // + "\n"
// + new Vector( _srcPoints[0].x(), _srcPoints[0].y(), 1.0f )
// + "\nres:" + _drawPoints[0] );
Graphics2D g2; // TODO
if ( _tex == null || w != _tex.getWidth() || h != _tex.getHeight() ) {
_tex = new BufferedImage( w, h, BufferedImage.TYPE_INT_RGB );
g2 = ( Graphics2D ) _tex.getGraphics();
} else {
g2 = ( Graphics2D ) _tex.getGraphics();
g2.setColor( Color.black );
g2.fillRect( 0, 0, w, h );
}
// Graphics2D g2 = ( Graphics2D ) _tex.getGraphics();
g2.setColor( Color.red );
for ( Edge e : _edges ) {
Vector v1 = _drawPoints[ e.v[0]];
Vector v2 = _drawPoints[ e.v[1]];
int x1 = ( int ) ( v1.x() * w ),
y1 = ( int ) ( v1.y() * h ),
x2 = ( int ) ( v2.x() * w ),
y2 = ( int ) ( v2.y() * h );
g2.drawLine( x1, y1, x2, y2 );
}
}
@Override
public void keyTyped( KeyEvent e ) {
}
@Override
public void keyPressed( KeyEvent e ) {
}
public static class Edge {
public Edge( int a, int b ) {
v[0] = a;
v[1] = b;
}
@Override
public String toString() {
return String.format( "%2d\t%2d", v[0], v[1] );
}
int[] v = new int[2];
}
}
|
Swift
|
UTF-8
| 1,279
| 2.734375
| 3
|
[
"MIT"
] |
permissive
|
//
// LinearLoader.swift
// Yess
//
// Created by Massimiliano on 03/04/17.
// Copyright © 2017 Digital Brain. All rights reserved.
//
import UIKit
class LinearLoader: UIView {
var timer: Timer?
func startAnimating() {
self.stopAnimating()
self.alpha = 1
self.cornerRadius = 2
self.transform = CGAffineTransform(scaleX: 0.00001, y: 1)
self.timer = Timer.scheduledTimer(timeInterval: 2, target: self, selector: #selector(animate), userInfo: nil, repeats: true)
}
func stopAnimating() {
self.alpha = 0
self.timer?.invalidate()
}
@objc func animate() {
UIView.animate(withDuration: 1, delay: 0, usingSpringWithDamping: 0.9, initialSpringVelocity: 0.8, options: .curveEaseInOut, animations: {
self.transform = .identity
self.alpha = 0.5
}) { (finish) in
DispatchQueue.main.async {
UIView.animate(withDuration: 1, delay: 0, usingSpringWithDamping: 0.9, initialSpringVelocity: 0.8, options: .curveEaseOut, animations: {
self.transform = CGAffineTransform(scaleX: 0.00001, y: 1)
self.alpha = 1
}, completion: nil)
}
}
}
}
|
PHP
|
UTF-8
| 1,046
| 2.640625
| 3
|
[
"MIT"
] |
permissive
|
<?php
namespace Oro\Bundle\MessageQueueBundle\Log\Formatter;
use Symfony\Bridge\Monolog\Formatter\ConsoleFormatter as BaseConsoleFormatter;
/**
* Formats message queue consumer related log records for the console output
* by coloring them depending on log level.
*/
class ConsoleFormatter extends BaseConsoleFormatter
{
const SIMPLE_FORMAT =
"%datetime% %start_tag%%channel%.%level_name%%end_tag%: %message%%context%%extra%\n";
const SIMPLE_DATE = 'Y-m-d H:i:s';
/**
* {@inheritdoc}
*/
public function __construct(array $options = [])
{
$options = array_replace([
'format' => self::SIMPLE_FORMAT,
'date_format' => self::SIMPLE_DATE,
'multiline' => false,
'colors' => false
], $options);
parent::__construct($options);
}
/**
* {@inheritdoc}
*/
public function format(array $record)
{
$formatted = parent::format($record);
return preg_replace('/\s+<\/>:/', '</>:', $formatted);
}
}
|
Shell
|
UTF-8
| 301
| 2.84375
| 3
|
[] |
no_license
|
#!/bin/bash
repo=$(echo $1 | sed 's/https:\/\/github.com\///')
filename=$(echo $repo | sed 's/.*\///').json
curl -s https://raw.githubusercontent.com/$repo/HEAD/README.md |
grep -o 'github.com/[-a-zA-Z0-9]\+/[-\.a-zA-Z0-9_]\+' |
sed 's/.*github.com\///g' |
jq --raw-input '[inputs]' >$filename
|
Java
|
UTF-8
| 471
| 2.296875
| 2
|
[] |
no_license
|
package database;
import android.arch.persistence.room.Room;
import android.content.Context;
public class DatabaseFactory {
private static AppDatabase db = null;
public static AppDatabase get(Context context) {
if(db == null) {
db = Room.databaseBuilder(
context,
AppDatabase.class,
"database-name"
)
.build();
}
return db;
}
}
|
Shell
|
UTF-8
| 616
| 3.65625
| 4
|
[
"MIT"
] |
permissive
|
source $stdenv/setup
set -e
if ! [ -f "$IVORY" ]; then
echo "$IVORY doesn't exist"
exit 1
fi
#
# heuristics to confirm the ivory pill is valid
#
# first 7 bytes != "version" (start of an lfs pointer)
#
if [ "$(head -c 7 "$IVORY")" = "version" ]; then
echo "$IVORY is an LFS pointer (it starts with 'version')"
echo "to fix, run: git lfs install"
exit 1
fi
# greater than 10KB
#
if ! [ $(du -k "$IVORY" | cut -f1) -gt 10 ]; then
echo "$IVORY is less than 10KB"
exit 1
fi
cat $IVORY > u3_Ivory.pill
xxd -i u3_Ivory.pill > ivory.h
mkdir -p $out/include
mv ivory.h $out/include
rm u3_Ivory.pill
|
Java
|
UTF-8
| 1,259
| 1.960938
| 2
|
[] |
no_license
|
package com.lzb.system.admin.doman;
import lombok.Data;
import javax.persistence.*;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
@Data
@Entity
@Table(name = "lzb_user")
public class User implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "user_id")
private Long id;
//账号
private String username;
//名称
private String name;
//密码
private String password;
//性别
private String sex;
//邮箱
private String email;
//电话
private String tel;
//头像
private String avatarPath;
//是否启用
private Boolean enabled;
//是否admin账号
private Boolean isAdmin = false;
//修改密码时间
private String pwdResetTime;
//创建时间
private String createTime;
//更新时间
private String updateTime;
//
@ManyToMany(targetEntity = Role.class,cascade = CascadeType.ALL,fetch = FetchType.EAGER)
@JoinTable(name = "lzb_user_role",joinColumns = {@JoinColumn(name = "user_id",referencedColumnName = "user_id")},inverseJoinColumns = {@JoinColumn(name = "role_id",referencedColumnName = "role_id")})
private Set<Role> role =new HashSet<>();
}
|
C++
|
UTF-8
| 1,115
| 2.671875
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
#ifndef _LABELS_SHARED_H_INCLUDED_
#define _LABELS_SHARED_H_INCLUDED_
#include "Reprise/Statements.h"
namespace OPS
{
namespace Shared
{
using OPS::Reprise::ReprisePtr;
using OPS::Reprise::StatementBase;
// You can use this function after replaceStatement function
// if you need to translate label from sourceStmt to destinationStmt.
// EXAMPLE: updateLabel(replaceStatement(stmt1, ReprisePtr<StatementBase>(stmt2)), &stmt2);
ReprisePtr<StatementBase> updateLabel(ReprisePtr<StatementBase> sourceStmt, StatementBase& destinationStmt);
// This function checks whether you can apply a generateNewLabels function
// to a statement statementBase.
bool isPossibleToGenerateNewLabels(StatementBase& statementBase);
// If you clone some statement from the program and want to use it in this program,
// then you have to generate new labels in cloned statement by this function.
// WARNING: If some goto outside statementBase points label inside statementBase,
// then the function will not work!!!
void generateNewLabels(StatementBase& statementBase);
} // Shared
} // OPS
#endif // _LABELS_SHARED_H_INCLUDED_
|
Ruby
|
UTF-8
| 1,178
| 3.53125
| 4
|
[] |
no_license
|
class Location
attr_accessor :x , :y, :facing
def initialize(x = 0, y = 0, facing = 'NORTH')
if x.respond_to?(:to_str)
if self.valid_instruction?(x)
set_location(x)
else
raise(InvalidLocationInputError, "Invalid initial direction:#{x}")
end
else
@x = x
@y = y
@facing = facing
end
end
def valid_instruction?(instruction)
location_regex_pattern = /^\d+,\d+,(NORTH|SOUTH|EAST|WEST)$/i
return !(location_regex_pattern.match(instruction)).nil?
end
def facing= direction
if (direction =~ /^(NORTH|EAST|SOUTH|WEST)$/i).nil?
raise(InvalidLocationInputError, "Invalid direction:#{direction}")
else
@facing = direction.upcase
end
end
def set_location(location_str)
components = location_str.split(",")
@x = components[0].to_i
@y = components[1].to_i
@facing = components[2]
end
def values
return "#{@x},#{@y},#{@facing}"
end
def ==(other)
return false unless other.instance_of?(self.class)
x == other.x && y == other.y && facing == other.facing
end
end
class InvalidLocationInputError < StandardError; end
|
Markdown
|
UTF-8
| 820
| 2.8125
| 3
|
[] |
no_license
|
Brick Game Simulator / Simulador de Mini Game
===============
[Eng]
### Description
> Web application that simulates the old minigames, using HTML5.
Documentation
> Size
The size attribute of the id div "minigame" defines the size of the minigame, values are accepted: small, medium and big;
### Example
> The examples folder contains an example of using the application with the game tetris.
Images
[pt-Br]
### Descrição
> Aplicação web que simula os antigos minigames, utilizando HTML5.
### Documentação
> Size
* O atributo size da div de id "minigame" define o tamanho do minigame, são aceitos valores: small, medium e big;
### Exemplo
> Na pasta examples contém um exemplo da utilização da aplicação com o game tetris.
### Imagens

|
PHP
|
UTF-8
| 488
| 2.515625
| 3
|
[
"BSD-2-Clause"
] |
permissive
|
<?php
namespace App\Http\Controllers\Api;
use App\Contracts\Controller;
use App\Services\EmirateService;
use Illuminate\Http\Request;
class EmirateController extends Controller
{
private $emirateSvc;
/**
* EmirateController constructor.
* @param $emirateSvc
*/
public function __construct(EmirateService $emirateSvc)
{
$this->emirateSvc = $emirateSvc;
}
public function index()
{
return $this->emirateSvc->getAll();
}
}
|
C
|
UTF-8
| 981
| 2.671875
| 3
|
[] |
no_license
|
/**
* @file calc.h
* @brief Onde fica a enum operations_t e funções que calculam dados para Stats
* @author Natália Azevedo de Brito (https://github.com/bnatalha)
* @since 10/04/2017
* @date 13/04/2017
* @sa http://www.cplusplus.com/
*/
#ifndef CALC_H
#define CALC_H
#include "header.h"
#include "comparator.h"
#include "stats.h"
#include "yearstats.h"
/**
* @enum operations_t calc.h
* @brief Menor é '-1' e Maior é '1'. Usada junto ao myCompare.
*/
enum operations_t {
Menor = -1,
Maior = 1
};
int year_peaks(
const Stats *vStats,
const int &vSize,
const int &year_pos,
const operations_t ¶m );
int sum_states(
const Stats *vStats,
const int &vSize,
const int &year_pos );
double desvp_states(
const Stats *vStats,
const int &vSize,
const int &year_pos,
const double &media_states );
double growth_rate(
const Stats *vStats,
const int &vSize,
const int &begin_year,
const int &end_year,
const operations_t ¶m,
string &municipio );
#endif
|
Java
|
UTF-8
| 2,103
| 1.882813
| 2
|
[] |
no_license
|
package com.comm.pojo;
import java.io.Serializable;
public class PageInfo implements Serializable{
/**
*
*/
private static final long serialVersionUID = 8171114812467078628L;
private String url;
private int index;
private int total;
private String name;
private String functionId;
private String pageType;
private String jsfile;
private String queryId;
private boolean isTransaction;
private int sysTrxTotalPage;
private int sysTrxPageIndex;
private String doname;
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getFunctionId() {
return functionId;
}
public void setFunctionId(String functionId) {
this.functionId = functionId;
}
public String getPageType() {
return pageType;
}
public void setPageType(String pageType) {
this.pageType = pageType;
}
public String getJsfile() {
return jsfile;
}
public void setJsfile(String jsfile) {
this.jsfile = jsfile;
}
public String getQueryId() {
return queryId;
}
public void setQueryId(String queryId) {
this.queryId = queryId;
}
public boolean isTransaction() {
return isTransaction;
}
public void setTransaction(boolean isTransaction) {
this.isTransaction = isTransaction;
}
public int getSysTrxTotalPage() {
return sysTrxTotalPage;
}
public void setSysTrxTotalPage(int sysTrxTotalPage) {
this.sysTrxTotalPage = sysTrxTotalPage;
}
public int getSysTrxPageIndex() {
return sysTrxPageIndex;
}
public void setSysTrxPageIndex(int sysTrxPageIndex) {
this.sysTrxPageIndex = sysTrxPageIndex;
}
public String getDoname() {
return doname;
}
public void setDoname(String doname) {
this.doname = doname;
}
}
|
Java
|
UTF-8
| 439
| 2.59375
| 3
|
[] |
no_license
|
package commands;
import receivers.Stereo;
public class StereoOnWithCdCommand implements Command {
private Stereo stereo;
public StereoOnWithCdCommand(Stereo stereo) {
this.stereo = stereo;
}
@Override
public void execute() {
stereo.setOn();
stereo.setCd();
stereo.setVolume(11);
}
@Override
public void undo() {
stereo.unsetCd();
stereo.setOff();
}
}
|
SQL
|
UTF-8
| 3,981
| 3.046875
| 3
|
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
-- phpMyAdmin SQL Dump
-- version 3.3.9
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Jan 18, 2017 at 07:39 AM
-- Server version: 5.5.8
-- PHP Version: 5.3.5
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
/*!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 utf8 */;
--
-- Database: `code_ignit`
--
-- --------------------------------------------------------
--
-- Table structure for table `cash_agenda`
--
CREATE TABLE IF NOT EXISTS `cash_agenda` (
`agendaId` int(5) NOT NULL AUTO_INCREMENT,
`agendaNama` varchar(30) NOT NULL,
`agendaLokasi` varchar(50) NOT NULL,
`agendaTgl` date NOT NULL,
`agendaImage` varchar(100) NOT NULL,
`agendaBiaya` int(10) NOT NULL,
PRIMARY KEY (`agendaId`),
UNIQUE KEY `agendaId` (`agendaId`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
--
-- Dumping data for table `cash_agenda`
--
-- --------------------------------------------------------
--
-- Table structure for table `cash_date`
--
CREATE TABLE IF NOT EXISTS `cash_date` (
`dateId` int(5) NOT NULL AUTO_INCREMENT,
`dateOne` int(10) NOT NULL,
`dateTwo` int(10) NOT NULL,
`dateThree` int(10) NOT NULL,
`dateFour` int(10) NOT NULL,
`dateFive` int(10) NOT NULL,
`dateSix` int(10) NOT NULL,
`dateSeven` int(10) NOT NULL,
`dateEight` int(10) NOT NULL,
`dateNine` int(10) NOT NULL,
`dateTen` int(10) NOT NULL,
`dateEleven` int(10) NOT NULL,
`dateTwelve` int(10) NOT NULL,
PRIMARY KEY (`dateId`),
UNIQUE KEY `id` (`dateId`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;
--
-- Dumping data for table `cash_date`
--
INSERT INTO `cash_date` (`dateId`, `dateOne`, `dateTwo`, `dateThree`, `dateFour`, `dateFive`, `dateSix`, `dateSeven`, `dateEight`, `dateNine`, `dateTen`, `dateEleven`, `dateTwelve`) VALUES
(1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(5, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
-- --------------------------------------------------------
--
-- Table structure for table `cash_grafik`
--
CREATE TABLE IF NOT EXISTS `cash_grafik` (
`dataY` varchar(30) NOT NULL,
`dataX` int(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `cash_grafik`
--
-- --------------------------------------------------------
--
-- Table structure for table `cash_login`
--
CREATE TABLE IF NOT EXISTS `cash_login` (
`user` varchar(20) NOT NULL,
`pass` varchar(20) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `cash_login`
--
-- --------------------------------------------------------
--
-- Table structure for table `cash_mhs`
--
CREATE TABLE IF NOT EXISTS `cash_mhs` (
`id` int(5) NOT NULL AUTO_INCREMENT,
`nrp` int(15) NOT NULL,
`nama` varchar(30) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `nrp` (`nrp`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;
--
-- Dumping data for table `cash_mhs`
--
INSERT INTO `cash_mhs` (`id`, `nrp`, `nama`) VALUES
(1, 2110151031, 'Ulfa Latifa Hanum'),
(2, 2110151033, 'Hazna At Thoriqoh'),
(3, 2110151034, 'Adi Putra Utama'),
(4, 2110141035, 'Tafaquh Fiddin Al I.'),
(5, 2110151037, 'Bagas Dewangkara');
-- --------------------------------------------------------
--
-- Table structure for table `cash_tanggal`
--
CREATE TABLE IF NOT EXISTS `cash_tanggal` (
`dateId` int(5) NOT NULL AUTO_INCREMENT,
`date1` date NOT NULL,
`date2` date NOT NULL,
`date3` date NOT NULL,
`date4` date NOT NULL,
`date5` date NOT NULL,
`date6` date NOT NULL,
`date7` date NOT NULL,
`date8` date NOT NULL,
`date9` date NOT NULL,
`date10` date NOT NULL,
`date11` date NOT NULL,
`date12` date NOT NULL,
PRIMARY KEY (`dateId`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
--
-- Dumping data for table `cash_tanggal`
--
|
Java
|
UTF-8
| 983
| 2.25
| 2
|
[] |
no_license
|
import cn.aegisa.project.trading.config.MailSender;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import java.io.File;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;
/**
* Using IntelliJ IDEA.
*
* @author XIANYINGDA at 2018/6/15 13:24
*/
public class TestMail extends BaseJunit4Test {
@Autowired
private MailSender mailSender;
@Test
public void test01() {
mailSender.sendMail(new String[]{"selext@yeah.net"}, "测试邮件1", "测试内容123" + UUID.randomUUID().toString());
}
@Test
public void test02() throws Exception {
Map<String, File> map = new LinkedHashMap<>();
map.put("aaa.jpg", new File("D:\\utils\\123.jpg"));
map.put("bbb.jpg", new File("D:\\utils\\微信图片_20180423105544.jpg"));
mailSender.sendMailWithAttachment(new String[]{"selext@yeah.net"}, "测试附件邮件2", "测试内容" + UUID.randomUUID().toString(), map);
}
}
|
Java
|
UTF-8
| 2,048
| 2.3125
| 2
|
[] |
no_license
|
/*
* The MIT License
*
* Copyright 2014 Ryan Gilera.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package com.github.daytron.flipit.data;
/**
*
* @author Ryan Gilera
*/
public enum DialogMessage {
// Confirmation Dialog
CONFIRMATION_HEAD_TITLE("Confirmation Dialog"),
CONFIRMATION_TITLE("Confirm Action"),
CONFIRM_EXIT("Are you sure you want to exit?"),
CONFIRM_NEW_GAME("You are about to leave this game.\n"
+ "Are you sure you want a new game?"),
CONFIRM_RESTART("You are about to leave this game.\n"
+ "Are you sure you want to restart the game?"),
// Error Dialog
ERROR_HEAD_TITLE("Error Dialog"),
ERROR_TITLE("Error"),
ERROR_NO_MAPS_FOUND("No available maps found."
+ "Map files are missing in the maps folder.\n"
+ "Exiting...");
private String text;
private DialogMessage(String text) {
this.text = text;
}
public String getText() {
return text;
}
}
|
Python
|
UTF-8
| 716
| 2.515625
| 3
|
[] |
no_license
|
import sql
import MySQLdb
import datetime
sql_settings = {
"ADDR": "ADDR",
"USER": "USER",
"PASS": "PASS",
"DB": "DBNAME"
}
def update(query):
db = MySQLdb.connect(sql_settings["ADDR"],
sql_settings["USER"],
sql_settings["PASS"],
sql_settings["DB"])
return_code = 1
cursor = db.cursor()
try:
cursor.execute(query)
db.commit()
except:
db.rollback()
return_code = -1
db.close()
return return_code
def fetch(query):
db = MySQLdb.connect(sql_settings["ADDR"],
sql_settings["USER"],
sql_settings["PASS"],
sql_settings["DB"])
cursor = db.cursor()
try:
cursor.execute(query)
results = cursor.fetchall()
except:
results = -1
db.close()
return results
|
Java
|
UTF-8
| 1,688
| 2.828125
| 3
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package domain;
/**
*
* @author Thibaut
*/
public class FoodType {
private int Id;
private String Description;
private boolean IsEnabled;
private String Name;
public FoodType(int Id, String Description, Boolean IsEnabled, String Name){
this.Id=Id;
this.Description=Description;
this.IsEnabled=IsEnabled;
this.Name=Name;
}
public FoodType(){
}
/**
* @return the Id
*/
public int getId() {
return Id;
}
/**
* @param Id the Id to set
*/
public void setId(int Id) {
this.Id = Id;
}
/**
* @return the Description
*/
public String getDescription() {
return Description;
}
/**
* @param Description the Description to set
*/
public void setDescription(String Description) {
this.Description = Description;
}
/**
* @return the IsEnabled
*/
public boolean isIsEnabled() {
return IsEnabled;
}
/**
* @param IsEnabled the IsEnabled to set
*/
public void setIsEnabled(boolean IsEnabled) {
this.IsEnabled = IsEnabled;
}
/**
* @return the Name
*/
public String getName() {
return Name;
}
/**
* @param Name the Name to set
*/
public void setName(String Name) {
this.Name = Name;
}
}
|
Java
|
UTF-8
| 1,664
| 2.109375
| 2
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.hasnain.travelagency.model;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Customer implements Serializable{
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int custid;
private String custname, custaddress, custphone, custgender, custemailid ;
public int getCustid() {
return custid;
}
public void setCustid(int custid) {
this.custid = custid;
}
public String getCustname() {
return custname;
}
public void setCustname(String custname) {
this.custname = custname;
}
public String getCustaddress() {
return custaddress;
}
public void setCustaddress(String custaddress) {
this.custaddress = custaddress;
}
public String getCustphone() {
return custphone;
}
public void setCustphone(String custphone) {
this.custphone = custphone;
}
public String getCustgender() {
return custgender;
}
public void setCustgender(String custgender) {
this.custgender = custgender;
}
public String getCustemailid() {
return custemailid;
}
public void setCustemailid(String custemailid) {
this.custemailid = custemailid;
}
}
|
JavaScript
|
UTF-8
| 11,153
| 2.609375
| 3
|
[] |
no_license
|
window.onload = function() {
if (window.jQuery) {
// jQuery is loaded
alert("jQuery loaded");
} else {
// jQuery is not loaded
alert("no jQuery");
}
}
var teamALeader = null;
var teamASub1 = null;
var teamASub2 = null;
var teamASub3 = null;
var teamASub4 = null;
var teamAFriend = null;
var teamBLeader = null;
var teamBSub1 = null;
var teamBSub2 = null;
var teamBSub3 = null;
var teamBSub4 = null;
var teamBFriend = null;
var teamCLeader = null;
var teamCSub1 = null;
var teamCSub2 = null;
var teamCSub3 = null;
var teamCSub4 = null;
var teamCFriend = null;
/*
* Fill Monster Overlay with entries
*/
var requestURL = 'https://raw.githubusercontent.com/QQChowey/PDC/master/monster.json';
var request = new XMLHttpRequest();
request.open('GET', requestURL);
request.responseType = 'json';
request.send();
request.onload = function() {
var monster = request.response;
var list = document.getElementById("MOlist");
var newdisplay, newleft, newpic, newtype1, newtype2, newtype3;
var newright, newrow1, newname, newrow2, newstat1, newhp, newstat2, newatk, newstat3, newrcv, newstat4, newrarity, newrow3;
for (var i = 0; i < monster.length; i++) {
newdisplay = document.createElement("div");
newdisplay.className = "display";
newdisplay.addEventListener("click", function(e) {
alert('something');
}, false);
newleft = document.createElement("span");
newleft.className = "leftContainer";
newpic = document.createElement("img");
newpic.className = "pic";
newpic.alt = monster[i]['id'];
newpic.src = "https://raw.githubusercontent.com/QQChowey/PDC/master/images/portrait/" + monster[i]['id'] + ".png";
newtyperow = document.createElement("div");
newtyperow.className = "typerow";
newtype1 = document.createElement("img");
newtype1.className = "type";
newtype1.src = "https://raw.githubusercontent.com/QQChowey/PDC/master/images/type/" + monster[i]["type"] + ".png";
newtype1.alt = monster[i]["type"]
newtype2 = document.createElement("img");
newtype2.className = "type";
if (monster[i]["type2"] != null) {
newtype2.src = "https://raw.githubusercontent.com/QQChowey/PDC/master/images/type/" + monster[i]["type2"] + ".png";
}
else {
newtype2.style.display = "none";
}
newtype2.alt = monster[i]["type2"];
newtype3 = document.createElement("img");
newtype3.className = "type";
if (monster[i]["type3"] != null) {
newtype3.src = "https://raw.githubusercontent.com/QQChowey/PDC/master/images/type/" + monster[i]["type3"] + ".png";
}
else {
newtype3.style.display = "none";
}
newtype3.alt = monster[i]["type3"];
newright = document.createElement("span");
newright.className = "rightContainer";
newrow1 = document.createElement("div");
newrow1.className = "row";
newname = document.createElement("div");
newname.className = "name";
newname.innerHTML = "No." + monster[i]['id'] + " " + monster[i]['name'];
newrow2 = document.createElement("div");
newrow2.className = "row";
newstat1 = document.createElement("span");
newstat1.className = "statText";
newstat1.innerHTML = "HP";
newhp = document.createElement("span");
newhp.className = "hp";
newhp.innerHTML = monster[i]['hp_max']
newstat2 = document.createElement("span");
newstat2.className = "statText";
newstat2.innerHTML = "ATK";
newatk = document.createElement("span");
newatk.className = "atk";
newatk.innerHTML = monster[i]['atk_max']
newstat3 = document.createElement("span");
newstat3.className = "statText";
newstat3.innerHTML = "RCV";
newrcv = document.createElement("span");
newrcv.className = "rcv";
newrcv.innerHTML = monster[i]['rcv_max']
newstat4 = document.createElement("span");
newstat4.className = "statText";
newstat4.innerHTML = "★";
newrarity = document.createElement("span");
newrarity.className = "rarity";
newrarity.innerHTML = monster[i]['rarity'];
newrow3 = document.createElement("div");
newrow3.className = "row";
newregawake = document.createElement("span");
newregawake.className = "regAwakening"
for (var j = 0; j < monster[i]['awoken_skills'].length; j++) {
newawake = document.createElement("img");
newawake.className = "awakening";
newawake.src = "https://raw.githubusercontent.com/QQChowey/PDC/master/images/awake/" + monster[i]['awoken_skills'][j] + ".png";
newawake.alt = monster[i]['awoken_skills'][j];
newregawake.append(newawake);
}
//newsuperawake = document.createElement("span");
//newsuperawake.className = "superAwakening"
list.append(newdisplay);
newdisplay.append(newleft);
newleft.append(newpic);
newleft.append(newtyperow);
newtyperow.append(newtype1);
newtyperow.append(newtype2);
newtyperow.append(newtype3);
newdisplay.append(newright);
newright.append(newrow1);
newrow1.append(newname);
newright.append(newrow2);
newrow2.append(newstat1);
newrow2.append(newhp);
newrow2.append(newstat2);
newrow2.append(newatk);
newrow2.append(newstat3);
newrow2.append(newrcv);
newrow2.append(newstat4);
newrow2.append(newrarity);
newright.append(newrow3);
newrow3.append(newregawake);
}
}
/*
* Add handleClicks for A - B - C later
* maybe prompt delete of C?
*/
var currentValue = "1";
function handleSwitchClick(switch_team) {
if (currentValue != switch_team.value) {
currentValue = switch_team.value;
if (currentValue == "1") {
document.getElementById("playerSwitch").innerHTML = "";
var parent = document.getElementById("playerSwitch");
var newform = document.createElement("form");
var newdiv = document.createElement("div");
newdiv.className = "switch_2opt";
var newinputA = document.createElement("input");
newinputA.setAttribute("type", "radio");
newinputA.setAttribute("id", "playerA");
newinputA.setAttribute("name", "switch_player");
newinputA.setAttribute("value", "1");
newinputA.setAttribute("checked", "checked");
newinputA.setAttribute("autocomplete", "off");
var newlabelA = document.createElement("label");
newlabelA.setAttribute("for", "playerA");
newlabelA.innerHTML = "A";
var newinputB = document.createElement("input");
newinputB.setAttribute("type", "radio");
newinputB.setAttribute("id", "playerB");
newinputB.setAttribute("name", "switch_player");
newinputB.setAttribute("value", "2");
newinputB.setAttribute("autocomplete", "off");
var newlabelB = document.createElement("label");
newlabelB.setAttribute("for", "playerB");
newlabelB.innerHTML = "B";
newdiv.append(newinputA);
newdiv.append(newlabelA);
newdiv.append(newinputB);
newdiv.append(newlabelB);
newform.append(newdiv);
parent.append(newform);
}
else if(currentValue == "2") {
document.getElementById("playerSwitch").innerHTML = "";
var parent = document.getElementById("playerSwitch");
var newform = document.createElement("form");
var newdiv = document.createElement("div");
newdiv.className = "switch_3opt";
var newinputA = document.createElement("input");
newinputA.setAttribute("type", "radio");
newinputA.setAttribute("id", "playerA");
newinputA.setAttribute("name", "switch_player");
newinputA.setAttribute("value", "1");
newinputA.setAttribute("checked", "checked");
newinputA.setAttribute("autocomplete", "off");
var newlabelA = document.createElement("label");
newlabelA.setAttribute("for", "playerA");
newlabelA.innerHTML = "A";
var newinputB = document.createElement("input");
newinputB.setAttribute("type", "radio");
newinputB.setAttribute("id", "playerB");
newinputB.setAttribute("name", "switch_player");
newinputB.setAttribute("value", "2");
newinputB.setAttribute("autocomplete", "off");
var newlabelB = document.createElement("label");
newlabelB.setAttribute("for", "playerB");
newlabelB.innerHTML = "B";
var newinputC = document.createElement("input");
newinputC.setAttribute("type", "radio");
newinputC.setAttribute("id", "playerC");
newinputC.setAttribute("name", "switch_player");
newinputC.setAttribute("value", "3");
newinputC.setAttribute("autocomplete", "off");
var newlabelC = document.createElement("label");
newlabelC.setAttribute("for", "playerC");
newlabelC.innerHTML = "C";
newdiv.append(newinputA);
newdiv.append(newlabelA);
newdiv.append(newinputB);
newdiv.append(newlabelB);
newdiv.append(newinputC);
newdiv.append(newlabelC);
newform.append(newdiv);
parent.append(newform);
}
}
}
/*
Left click to
select monster.
- - - - - - -
Right click for
more info.
*/
function LR_openOverlay(e, element) {
e = e || window.event;
switch(e.which) {
case 1:
openMonsterOverlay();
break;
case 3: openOptionOverlay(); break;
}
}
function openOptionOverlay() {
document.getElementById("optionOverlay").style.width = "550px";
document.getElementById("optionOverlay").style.opacity = "1";
document.getElementById("exitOptionOverlay").style.width = "100%";
}
function closeOptionOverlay() {
document.getElementById("optionOverlay").style.opacity = "0";
setTimeout(function() { document.getElementById("optionOverlay").style.width = "0"; }, 250);
document.getElementById("exitOptionOverlay").style.width = "0%";
}
function openMonsterOverlay() {
document.getElementById("searchMonsterOverlay").style.width = "550px";
document.getElementById("exitMonsterOverlay").style.width = "100%";
}
function closeMonsterOverlay() {
document.getElementById("searchMonsterOverlay").style.width = "0";
document.getElementById("exitMonsterOverlay").style.width = "0";
}
function searchFilter() {
// Declare variables
var input, filter, container, item, itemInner, name, i;
input = document.getElementById("MOsearchInput");
filter = input.value.toUpperCase();
container = document.getElementById("MOlist");
item = container.getElementsByClassName("display");
itemInner = container.getElementsByClassName("name");
for (i = 0; i < itemInner.length; i++) {
name = itemInner[i];
if (name.innerHTML.toUpperCase().indexOf(filter) > -1) {
item[i].style.display = "";
}
else {
item[i].style.display = "none";
}
}
}
function openMOfilter() {
document.getElementById("MOfilter").style.height = "100px";
document.getElementById("MOlist").style.height = "calc(100% - 200px)";
document.getElementById("filterBtn").innerHTML = "Close Filter";
document.getElementById("filterBtn").setAttribute("onclick","closeMOfilter();");
}
function closeMOfilter() {
document.getElementById("MOfilter").style.height = "0";
document.getElementById("MOlist").style.height = "calc(100% - 100px)";
document.getElementById("filterBtn").innerHTML = "Open Filter";
document.getElementById("filterBtn").setAttribute("onclick","openMOfilter();");
}
function openInheritOverlay() {
}
function closeInheritOverlay() {
}
function openLatentOverlay() {
}
function closeLatentOverlay() {
}
function openBadgeOverlay() {
}
function closeBadgeOverlay() {
}
function openDungeonOverlay() {
}
function closeDungeonOverlay() {
}
|
Java
|
UTF-8
| 2,675
| 2.203125
| 2
|
[
"MIT"
] |
permissive
|
package uk.gov.companieshouse.api.strikeoffobjections.common;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.avro.Schema;
import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.GenericDatumWriter;
import org.apache.avro.generic.GenericRecord;
import org.apache.avro.io.BinaryEncoder;
import org.apache.avro.io.DatumWriter;
import org.apache.avro.io.Encoder;
import org.apache.avro.io.EncoderFactory;
import org.apache.avro.specific.SpecificDatumWriter;
import org.apache.avro.specific.SpecificRecord;
import org.springframework.stereotype.Component;
import uk.gov.companieshouse.api.strikeoffobjections.model.email.EmailContent;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
@Component
public class AvroSerializer {
private final ObjectMapper objectMapper = new ObjectMapper();
public byte[] serialize(EmailContent emailContent, Schema schema) throws IOException {
ByteArrayOutputStream stream = new ByteArrayOutputStream();
BinaryEncoder encoder = EncoderFactory.get().binaryEncoder(stream, null);
GenericDatumWriter<GenericRecord> datumWriter = new GenericDatumWriter<>(schema);
datumWriter.write(buildAvroGenericRecord(emailContent, schema), encoder);
encoder.flush();
return stream.toByteArray();
}
public byte[] serialize(SpecificRecord data) throws IOException {
DatumWriter<SpecificRecord> datumWriter = new SpecificDatumWriter<>();
try(ByteArrayOutputStream out = new ByteArrayOutputStream()) {
Encoder encoder = EncoderFactory.get().binaryEncoder(out, null);
datumWriter.setSchema(data.getSchema());
datumWriter.write(data, encoder);
encoder.flush();
byte[] serializedData = out.toByteArray();
encoder.flush();
return serializedData;
}
}
private GenericRecord buildAvroGenericRecord(EmailContent emailContent, Schema schema)
throws JsonProcessingException {
GenericRecord documentData = new GenericData.Record(schema);
documentData.put("app_id", emailContent.getOriginatingAppId());
documentData.put("message_id", emailContent.getMessageId());
documentData.put("message_type", emailContent.getMessageType());
documentData.put("data", objectMapper.writeValueAsString(emailContent.getData()));
documentData.put("email_address", emailContent.getEmailAddress());
documentData.put("created_at", FormatUtils.formatTimestamp(emailContent.getCreatedAt()));
return documentData;
}
}
|
C#
|
UTF-8
| 517
| 2.75
| 3
|
[] |
no_license
|
using System;
namespace MoneyCategorizer
{
[System.Diagnostics.DebuggerDisplay("{Description} = {Amount}")]
public class Transaction
{
private string raw;
public DateTime Date { get; set; }
public string Description { get; set; }
public double Amount { get; set; }
public string FileName { get; set; }
public string Raw
{
get { return raw; }
set { raw = value.Trim(); }
}
}
}
|
Java
|
UTF-8
| 3,398
| 2.234375
| 2
|
[] |
no_license
|
package com.sixin.iot.service.impl;
import com.sixin.common.annotation.DataSource;
import com.sixin.common.enums.DataSourceType;
import com.sixin.common.core.text.Convert;
import com.sixin.iot.domain.LED;
import com.sixin.iot.mapper.LEDMapper;
import com.sixin.iot.service.ILEDService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class LEDServiceImpl implements ILEDService {
@Autowired
private LEDMapper LEDMapper;
/**
* 查询终端运转列表
*
* @param led 终端运转信息
* @return 终端运转集合
*/
@Override
@DataSource(value = DataSourceType.SXINFOM)
public List<LED> selectLedList(LED led)
{
return LEDMapper.selectLedList(led);
}
/**
* 查询终端运转信息
*
* @param led_id 终端运转ID
* @return 终端运转信息
*/
@Override
@DataSource(value = DataSourceType.SXINFOM)
public LED selectLedById(String led_id)
{
return LEDMapper.selectLedById(led_id);
}
/*@Override
@DataSource(value = DataSourceType.SXINFOM)
public List<LED> selectLedAll()
{
return LEDMapper.selectLedAll();
}*/
/**
* 新增终端运转
*
* @param led 终端运转信息
* @return 结果
*/
@Override
@DataSource(value = DataSourceType.SXINFOM)
public int insertLed(LED led)
{
return LEDMapper.insertLed(led);
}
/**
* 修改终端运转
*
* @param led 终端运转信息
* @return 结果
*/
@Override
@DataSource(value = DataSourceType.SXINFOM)
public int updateLed(LED led)
{
return LEDMapper.updateLed(led);
}
/**
* 删除终端运转对象
*
* @param led_ids 需要删除的数据ID
* @return 结果
@Override
@DataSource(value = DataSourceType.SXINFOM)
public int deleteLedByIds(String led_ids)
{
String[] Led_ids = Convert.toLongArray(led_ids);
/*for (Long Led_id : Led_ids)
{
LED Led = selectLedById(Led_id);
if (countUserPostById(postId) > 0)
{
throw new BusinessException(String.format("%1$s已分配,不能删除", post.getPostName()));
}
}
return LEDMapper.deleteLedByIds(Led_ids);
}
/*public int deleteLedById(String led_id)
{
return LEDMapper.deleteLedById(led_id);
}*/
/**
* 删除终端运转对象
*
* @param ids 需要删除的数据ID
* @return 结果
*/
@Override
@DataSource(value = DataSourceType.SXINFOM)
public int deleteLedByIds(String ids)
{
//return LEDMapper.deleteLedByIds(led_ids);
return LEDMapper.deleteLedByIds(Convert.toStrArray(ids));
}
/**
* 统计物联网数据条目
*
* @param led_id 终端运转ID
* @return 终端运转信息
@Override
@DataSource(value = DataSourceType.SXINFOM)
public int countall(){
return LEDMapper.countall();
}
/**
* 统计物联网设备数量
*
* @param led_id 终端运转ID
* @return 终端运转信息
@Override
@DataSource(value = DataSourceType.SXINFOM)
public int devicecount(){
return LEDMapper.devicecount();
}*/
}
|
Markdown
|
UTF-8
| 4,480
| 2.625
| 3
|
[] |
no_license
|
### github上clone到本地:
在终端输入
$ git
usage: git [--version] [--help] [-C <path>] [-c name=value]
[--exec-path[=<path>]] [--html-path] [--man-path] [--info-path]
[-p | --paginate | --no-pager] [--no-replace-objects] [--bare]
[--git-dir=<path>] [--work-tree=<path>] [--namespace=<name>]
<command> [<args>]
These are common Git commands used in various situations:
start a working area (see also: git help tutorial)
clone Clone a repository into a new directory
init Create an empty Git repository or reinitialize an existing one
work on the current change (see also: git help everyday)
add Add file contents to the index
mv Move or rename a file, a directory, or a symlink
reset Reset current HEAD to the specified state
rm Remove files from the working tree and from the index
examine the history and state (see also: git help revisions)
bisect Use binary search to find the commit that introduced a bug
grep Print lines matching a pattern
log Show commit logs
show Show various types of objects
status Show the working tree status
grow, mark and tweak your common history
branch List, create, or delete branches
checkout Switch branches or restore working tree files
commit Record changes to the repository
diff Show changes between commits, commit and working tree, etc
merge Join two or more development histories together
rebase Reapply commits on top of another base tip
tag Create, list, delete or verify a tag object signed with GPG
collaborate (see also: git help workflows)
fetch Download objects and refs from another repository
pull Fetch from and integrate with another repository or a local branch
push Update remote refs along with associated objects
在github上新建一个仓库,复制网址clone with https,输入到终端某个路径里 比如cd temp/
git clone https://github.com/mybatis/spring.git
就clone下来了,可以```ls```或```log```查看
终端输入(最常用的 每一次都要执行的:add、commit)
git add .
git commit -m "add file" #后面"本次提交的注释 每次注释本次修改大致内容"
如果user name 和password忘了 :
git commit --amend --reset-author
移除存在的github库
git config --global --edit
mv .gitconfig .gitconfig.bak
查看信息 用户名邮箱等:
ls .git*
cat .gitconfig
到路径里后,新建文件:
touch a.txt
vim a.txt
git add .
git commit -m "add a.txt
查看还有哪些步骤没做/要做
git status
东西写完了,要提交到github上:
git push
### 本地提交到github上
1. 可以把idea的project拖到那个文件夹里,
在idea界面中,对左边的大文件夹,右键git - repository - add/commit。
再push上去,就可以了。
2. idea的上方菜单栏 - ```VCS - Import into Version Control - Share Project on Github - token(会话秘匙,下次就不用输密码了) - 输入用户名密码 - new repositories``` 。
在idea里也可以查看终端:界面下方那栏有一个terminal。然后 ```git add .和git commit 和 git push```
### [!]idea 下栏切换到 Version Control 点 log 能看到历史记录,如果要回到前一版本,点选某个版本,右键 Copy Revision Number,复制编号
### 然后在切换到下栏终端 先git stash存储一下当前,再git reset 粘贴刚才的编号,就可以恢复前面的版本了。
### [!] git push 之前,要先git pull一下,因为可能有多人修改文件,pull可以查看最新修改版本,然后可选merge合并修改的版本。
### github上同步到本地
查看远程仓库
git remote -v
从远程获取最新版本到本地
git fetch origin master
git fetch origin master 这句的意思是:从远程的origin仓库的master分支下载代码到本地的origin master
比较本地的仓库和远程参考的区别
git log -p master.. origin/master
把远程下载下来的代码合并到本地仓库,远程的和本地的合并
git merge origin/master
|
PHP
|
UTF-8
| 693
| 2.953125
| 3
|
[] |
no_license
|
<?php
namespace Alexeev;
use core\EquationInterface;
class Square extends Line implements EquationInterface
{
public function solve(float $a, float $b, float $c): array
{
if($a == 0){
return parent::line($b, $c);
}
$D = $this->searchD($a, $b, $c);
if($D > 0){
return $this->x = [(-$b - sqrt($D)) / (2 * $a), (-$b + sqrt($D)) / (2 * $a)];
}
if($D==0){
return $this->x = [(-$b - sqrt($D) / (2 * $a))];
}
if($D<0)
throw new AlexeevException('Корней нет!');
}
protected function searchD($a, $b, $c){
$D = $b * $b - 4 * $a * $c;
return $D;
}
}
|
Markdown
|
UTF-8
| 19,014
| 3.1875
| 3
|
[
"MIT"
] |
permissive
|
#! https://zhuanlan.zhihu.com/p/256444986
# rust 从零开始构建区块链(Bitcoin)系列 - 交易和一些辅助工具
Github链接,包含文档和全部代码:
[https://github.com/yunwei37/blockchain-rust](https://github.com/yunwei37/blockchain-rust)
这篇文章对应着 Go 原文的第三部分和第四部分,包括 `持久化和命令行接口` 以及 `交易`。交易是一个由区块链构成的虚拟货币系统的核心,但在讨论交易之前,我们还会先着手做一些辅助的工具部分:
- 将区块链持久化到一个数据库中(在内存中肯定是不现实的);
- 提供一点命令行交互的接口;
- 除了上述在 Go 原文中的两个方面,我们还会添加一个 Rust 的日志功能,这部分在现在看来用处可能不大,但在网络交互中还是非常有必要的。
## 一些辅助工具
本阶段的代码实现在这里:[commit e2094c0](https://github.com/yunwei37/blockchain-rust/tree/e2094c0ef94fadc4e01030312a1ad890ec633d6f)
### 数据库
首先来看数据库部分,这里我选择了一个简单的 Rust 键值对数据库 [sled](https://github.com/spacejam/sled):
>Sled是基于Bw树构建的嵌入式KV数据库,其API接近于一个线程安全的BTreeMap<[u8], [u8]>。而其Bw树的数据结构加上包括crossbeam-epoch的“GC”等技术,使得Sled成为一个lock-free的数据库而在并发环境中傲视群雄。官方宣称在一台16核的机器上,在一个小数据集上可以达到每分钟10亿次操作(95%读核5%写)。
示例代码可以参考上面那个链接里面的 README 文件,它的 API 也比原文 Go 里面的更简单。这里,我们使用的键值对有两种类型:
- 32 字节的 block-hash -> block 结构体
- 'LAST' -> 链中最后一个块的 hash
实际存储的全部都是序列化的数据,这里我们可以使用 [serde](https://github.com/serde-rs/serde) 进行序列化和反序列化的操作:
>serde, 是rust语言用来序列化和反序列化数据的一个非常高效的解决方案。
>本质上,serde提供了一个序列化层的概念。可以将任何支持的数据格式反序列化成中间格式,然后序列化成任何一种支持的数据格式。
来看看代码吧!
首先,我们修改一下 Blockchain 数据结构的定义,在其中保存有一个 sled 数据库的实例:
```rs
#[derive(Debug)]
pub struct Blockchain {
tip: String,
db: sled::Db,
}
```
由于我们需要对 Block 结构体进行序列化,我们可以很简单地使用 serde 库的 derive 特性机制,只要在结构体上面添加上 `#[derive(Serialize, Deserialize)` 就好:
```rs
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Block {
timestamp: u128,
data: String,
prev_block_hash: String,
hash: String,
nonce: i32,
}
```
然后,我们可以这样创建一个 Blockchain 结构体,如果存在数据库(找到了 `LAST` 键对应的内容)的话就加载对应的区块链,不存在就创建之:
```rs
impl Blockchain {
pub fn new() -> Result<Blockchain> {
info!("Creating new blockchain");
let db = sled::open("data/blocks")?;
match db.get("LAST")? {
Some(hash) => { // 如果存在数据库(找到了 `LAST` 键对应的内容)
info!("Found block database");
let lasthash = String::from_utf8(hash.to_vec())?;
Ok(Blockchain {
tip: lasthash.clone(),
current_hash: lasthash,
db,
})
}
None => { // 数据库里面没有 LAST ,创建一个新的区块链
info!("Creating new block database");
let block = Block::new_genesis_block();
db.insert(block.get_hash(), serialize(&block)?)?; // 序列化然后插入
db.insert("LAST", block.get_hash().as_bytes())?;
let bc = Blockchain {
tip: block.get_hash(),
db,
};
bc.db.flush()?;
Ok(bc)
}
}
}
```
然后是向数据库里面添加区块,代码的逻辑很简单:找到 LAST 对应的区块,把它作为上个区块来创建新的区块,然后插入数据库,更新 LAST:
```rs
impl Blockchain {
pub fn add_block(&mut self, data: String) -> Result<()> {
info!("add new block to the chain");
let lasthash = self.db.get("LAST")?.unwrap();
let newblock = Block::new_block(data, String::from_utf8(lasthash.to_vec())?)?;
self.db.insert(newblock.get_hash(), serialize(&newblock)?)?;
self.db.insert("LAST", newblock.get_hash().as_bytes())?;
self.db.flush()?;
self.tip = newblock.get_hash();
Ok(())
}
```
为了让调用比较方便,我们可以考虑为区块链增加一个迭代器,这个迭代器能够顺序打印区块链(在数据库中是按hash存储的)。具体代码这里就忽略过去啦(毕竟也不算特别重要,可以参考源代码 blockchain.rs)。
### 命令行接口和日志
rust 没有 Go 那样原生强大的标准库,但我们还是有很多社区库可以用的,比如这个 [clap](https://github.com/clap-rs/clap):
> clap是一个简单易用,功能强大的命令行参数解析库,用于解析并验证用户在运行命令行程序时提供的命令行参数字符串。 你所需要做的只是提供有效参数的列表,clap会自动处理其余的繁杂工作。 这样工程师可以把时间和精力放在实现程序功能上,而不是参数的解析和验证上。
我们这里创建了一个简单的结构体 `Cli`:
```rs
pub struct Cli {
bc: Blockchain,
}
```
大概 clap 匹配命令的代码是这样的:
```rs
impl Cli {
pub fn run(&mut self) -> Result<()> {
let matches = App::new("blockchain-demo")
.version("0.1")
.author("yunwei37. 1067852565@qq.com")
.about("reimplement blockchain_go in rust: a simple blockchain for learning")
.subcommand(App::new("printchain").about("print all the chain blocks"))
.subcommand(
App::new("addblock")
.about("add a block in the blockchain")
.arg(Arg::from_usage("<data> 'the blockchain data'")),
)
.get_matches();
if let Some(ref matches) = matches.subcommand_matches("addblock") {
if let Some(c) = matches.value_of("data") {
self.bc.add_block(data)?;
} else {
println!("Not data...");
}
}
if let Some(_) = matches.subcommand_matches("printchain") {
let bc = Blockchain::new()?;
for b in bc.iter() {
println!("block: {:#?}", b);
}
}
....
```
我们在这里创建了两个子命令:
- `addblock <data>` 添加一个新的区块
- `printchain` 使用迭代打印区块链
最后,我们可以使用 [env_logger](http://www.eclipse.org/paho/files/rustdoc/env_logger/index.html) 来进行日志记录,具体实例就像上面提到的那样: `info!("add new block to the chain");`
在 main 函数中初始化 env_logger,指定默认日志等级为warnning,然后运行命令行处理程序:
```rs
fn main() -> Result<()> {
env_logger::from_env(Env::default().default_filter_or("warning")).init();
let mut cli = Cli::new()?;
cli.run()?;
Ok(())
}
```
这样我们就有一个看起来还行的 blockchain demo 啦,下一步就是加上交易!
## 交易
交易(transaction)是比特币的核心所在,而比特币使用区块链唯一的目的,也正是为了能够安全可靠地存储交易。在区块链中,交易一旦被创建,就没有任何人能够再去修改或是删除它;同时,由于比特币采用的是 UTXO 模型,并非账户模型,并不直接存在“余额”这个概念,余额需要通过遍历整个交易历史得来。
详细的信息可以参考:[en.bitcoin.it/wiki/Transaction](https://en.bitcoin.it/wiki/Transaction)
也可以对照原版的中文翻译看,他那关于原理的介绍比较详细:[transactions-1](https://liuchengxu.gitbook.io/blockchain/bitcoin/transactions-1#yin-yan)
首先,我们看看交易的数据结构,一笔交易由一些输入(input)和输出(output)组合而来:
```rs
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Transaction {
pub id: String,
pub vin: Vec<TXInput>,
pub vout: Vec<TXOutput>,
}
```
对于每一笔新的交易,它的输入会引用(reference)之前一笔交易的输出,不过:
- 有一些输出并没有被关联到某个输入上,对应着 coinbase;
- 一笔交易的输入可以引用之前多笔交易的输出;
- 一个输入必须引用一个输出;
这是输出,包含一定量的比特币和一个锁定脚本(这里并不会实现全面的脚本语言):
```rs
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct TXOutput {
pub value: i32,
pub script_pub_key: String,
}
```
我们将只会简单地把输出和用户定义的钱包地址(一个任意的字符串)作比较:
```rs
impl TXOutput {
/// CanBeUnlockedWith checks if the output can be unlocked with the provided data
pub fn can_be_unlock_with(&self, unlockingData: &str) -> bool {
self.script_pub_key == unlockingData
}
```
这是输入,引用(reference)之前一笔交易的输出:
```rs
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct TXInput {
pub txid: String,
pub vout: i32,
pub script_sig: String,
}
```
事实上,虚拟货币就是存储在输出中里面。由于还没有实现地址(address),所以目前我们会避免涉及逻辑相关的完整脚本。
来看看一个基本的使用场景:从一个用户向另外一个用户发送币,即创建一笔交易:
之前我们仅仅实现了简单的 `coinbase` 交易方法,也就是挖矿,现在我们需要一种通用的普通交易:
- 首先,我们需要使用 `find_spendable_outputs` 函数,找到发送方可以花费的货币数量,以及包含这些货币的未使用输出;
- 然后,我们使用这些输出创建一个新的输入给接收方,这里已经被引用的输入就相当于被花掉了;注意,输出是不可再分的;
- 最后,将多余的钱(找零)创建一个新的输出返回给发送方。
好啦!一个最基本的交易原型就这样完成了,现在来看看代码;
```rs
impl Transaction {
/// NewUTXOTransaction creates a new transaction
pub fn new_UTXO(from: &str, to: &str, amount: i32, bc: &Blockchain) -> Result<Transaction> {
info!("new UTXO Transaction from: {} to: {}", from, to);
let mut vin = Vec::new();
let acc_v = bc.find_spendable_outputs(from, amount);
if acc_v.0 < amount {
error!("Not Enough balance");
return Err(format_err!(
"Not Enough balance: current balance {}",
acc_v.0
));
}
for tx in acc_v.1 {
for out in tx.1 {
let input = TXInput {
txid: tx.0.clone(),
vout: out,
script_sig: String::from(from),
};
vin.push(input);
}
}
let mut vout = vec![TXOutput {
value: amount,
script_pub_key: String::from(to),
}];
if acc_v.0 > amount {
vout.push(TXOutput {
value: acc_v.0 - amount,
script_pub_key: String::from(from),
})
}
let mut tx = Transaction {
id: String::new(),
vin,
vout,
};
tx.set_id()?;
Ok(tx)
}
```
来看看相关的辅助函数,首先是在区块链中寻找未花费的输出 find_spendable_outputs,该方法返回一个包含累积未花费输出和相关输出结构体集合的元组:
- 首先,使用 `find_unspent_transactions` 找到包含发送方的所有未花掉的输出;
- 然后,在所有未花掉的输出上面迭代,将能够被使用者解锁的输出的 id 插入到用交易 id 作为索引的集合中;增加累计数值;
- 当累计数值超过需要数值的时候返回。
```rs
impl Blockchain {
pub fn find_spendable_outputs(
&self,
address: &str,
amount: i32,
) -> (i32, HashMap<String, Vec<i32>>) {
let mut unspent_outputs: HashMap<String, Vec<i32>> = HashMap::new();
let mut accumulated = 0;
let unspend_TXs = self.find_unspent_transactions(address);
for tx in unspend_TXs {
for index in 0..tx.vout.len() {
if tx.vout[index].can_be_unlock_with(address) && accumulated < amount {
match unspent_outputs.get_mut(&tx.id) {
Some(v) => v.push(index as i32),
None => {
unspent_outputs.insert(tx.id.clone(), vec![index as i32]);
}
}
accumulated += tx.vout[index].value;
if accumulated >= amount {
return (accumulated, unspent_outputs);
}
}
}
}
(accumulated, unspent_outputs)
}
```
下一步是找到区块链中对应地址能解锁的包含未花费输出的交易,即 `find_unspent_transactions`:
- 如果一个输出可以被发送方的地址解锁,并且该输出没有被包含在一个交易的输入中,它就是可以使用的;
- 由于我们对区块链是从尾部往头部迭代,因此如果我们见到的输出没有被包含在我们见到的任何一笔输入中,它就是未使用的;
- 我们将见到的输入加入一个集合,然后在这个集合中查找对应的输出,如果一个输出可以被解锁并且没有在集合中找到的话,它就是可以被花费的。
```rs
impl Blockchain {
fn find_unspent_transactions(&self, address: &str) -> Vec<Transaction> {
let mut spent_TXOs: HashMap<String, Vec<i32>> = HashMap::new();
let mut unspend_TXs: Vec<Transaction> = Vec::new();
for block in self.iter() {
for tx in block.get_transaction() {
for index in 0..tx.vout.len() {
if let Some(ids) = spent_TXOs.get(&tx.id) {
if ids.contains(&(index as i32)) {
continue;
}
}
if tx.vout[index].can_be_unlock_with(address) {
unspend_TXs.push(tx.to_owned())
}
}
if !tx.is_coinbase() {
for i in &tx.vin {
if i.can_unlock_output_with(address) {
match spent_TXOs.get_mut(&i.txid) {
Some(v) => {
v.push(i.vout);
}
None => {
spent_TXOs.insert(i.txid.clone(), vec![i.vout]);
}
}
}
}
}
}
}
unspend_TXs
}
```
对于一个普通的交易,可以用以上方法完成;但我们还需要一种 `coinbase` 交易,它“凭空”产生了币,这是矿工获得挖出新块的奖励;
```rs
impl Transaction {
pub fn new_coinbase(to: String, mut data: String) -> Result<Transaction> {
info!("new coinbase Transaction to: {}", to);
if data == String::from("") {
data += &format!("Reward to '{}'", to);
}
let mut tx = Transaction {
id: String::new(),
vin: vec![TXInput {
txid: String::new(),
vout: -1,
script_sig: data,
}],
vout: vec![TXOutput {
value: SUBSIDY,
script_pub_key: to,
}],
};
tx.set_id()?;
Ok(tx)
}
```
我们还可以创建一个简单的辅助函数,让我们可以比较简单地获取余额:这个函数返回了一个交易列表,里面包含了未花费输出;
```rs
impl Blockchain {
/// FindUTXO finds and returns all unspent transaction outputs
pub fn find_UTXO(&self, address: &str) -> Vec<TXOutput> {
let mut utxos = Vec::<TXOutput>::new();
let unspend_TXs = self.find_unspent_transactions(address);
for tx in unspend_TXs {
for out in &tx.vout {
if out.can_be_unlock_with(&address) {
utxos.push(out.clone());
}
}
}
utxos
}
```
交易的部分差不多就这些啦!我们已经完成了准备工作,现在可以更改一下之前留下来的接口:
我们首先需要在区块中添加一下包含的交易,是这样的:
```rs
#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Block {
timestamp: u128,
transactions: Vec<Transaction>,
prev_block_hash: String,
hash: String,
nonce: i32,
}
```
然后也要更改一下添加区块的接口:
```rs
impl Block {
pub fn new_block(transactions: Vec<Transaction>, prev_block_hash: String) -> Result<Block> {
....
}
pub fn new_genesis_block(coinbase: Transaction) -> Block {
Block::new_block(vec![coinbase], String::new()).unwrap()
}
```
在创建区块链的时候,我们也需要创建一笔 `coinbase` 交易:
```rs
impl Blockchain {
pub fn create_blockchain(address: String) -> Result<Blockchain> {
...
let cbtx = Transaction::new_coinbase(address, String::from(GENESIS_COINBASE_DATA))?;
let genesis: Block = Block::new_genesis_block(cbtx);
...
}
```
基本上大功告成!我们看看具体的命令实现:
send 命令:
```rs
...
let mut bc = Blockchain::new()?;
let tx = Transaction::new_UTXO(from, to, amount, &bc)?;
bc.mine_block(vec![tx])?;
...
```
getbalance 命令:
```rs
...
let bc = Blockchain::new()?;
let utxos = bc.find_UTXO(&address);
let mut balance = 0;
for out in utxos {
balance += out.value;
}
println!("Balance of '{}': {}\n", address, balance);
...
```
这样就好啦!如果想要进一步观察交易的相关知识,可以参考:[https://en.bitcoin.it/wiki/Transaction](https://en.bitcoin.it/wiki/Transaction)
|
Markdown
|
UTF-8
| 2,291
| 2.75
| 3
|
[] |
no_license
|
# Parte do Back-end
Como proposto no desafio, foi utilzado o php
para fazer o backend, porém eu tomei a liberdade
de utilizar um dos frameworks php que mais gosto e utilizo
na atualidade, o Laravel.
O processo foi o seguinte: uma rota do tipo get foi criada (/api/v1/planos),
nela chamando um controller, que chamara a model e que por sua vez fara a busca
no banco de dados pois as informações estão no banco de dados (mysql),com isso a
model devolve para o controller que transformara o conteudo em json e devolvera
uma resposta.
Foi feito o deploy da aplicação no heroku, logo tanto a api quanto a parte do front
pode ser vistas.
>O resultado final da api está disposto aqui
[api-fit](https://api-fit.herokuapp.com/api/v1/planos).
# Parte do Front-end
Na parte do front-end foi utilizado o vue-js,
fazendo uma separação basica em paginas e components, logo dentro da
pasta pages contem o component Home que representa a pagina e é o primeiro componente a ser chamado.
Ao ser montado a primeira coisa que fará é buscar os dados
da api, utlizando a função getAllPlanos() que está dentro de uma
pasta chamada service e retorna uma promise. Ela tem como objetivo
fazer uma requisição do tipo get para nossa
api, utilizano a fetch api e arrow function
para ficar mais enxuto e sussinto, com o resultado é adquirido
e transformado em json. E como é utilizado
uma Promise, logo o acesso dela ficará disponivel
no component Home, que por sua vez mandara esse objeto
para um state usando this.setPlanos, para ser manipulado depois.
Um detalhe que pode ser notado é que estou usando vuex
para uma separação mais limpa.
Com isso a Pagina principal Home é composta
por outros componentes, sendo o Header, CampoBusca e Card,
que pode ser encontrados dentro da pasta components,
cada um tendo apenas uma função, como por exemplo card, que
monta a imagem e o nome conforme o loop de dados vindo da api, e busca, que apenas tem a responsabilidade de efetuar uma busca.
A parte do css foi utlizado flex box para organização, com o arquivo
dentro de css/style.css, e um reset.css para resetar as configurações
iniciais.
Como o projeto foi upado no heroku,
> O Projeto final pode ser visto aqui, [projeto-fit](https://projeto-fit.herokuapp.com/).
|
C#
|
UTF-8
| 5,857
| 2.78125
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using WebStore.Entities;
using WebStore.Models;
namespace WebStore.Data
{
public class TestData
{
private static readonly List<Employee> _employees = new()
{
new()
{
Id = 1,
LastName = "Иванов",
FirstName = "Иван",
Patronymic = "Иванович",
Birthday = new DateTime(1971, 11, 23),
EmploymentStart = new DateTime(2010, 12, 1)
},
new()
{
Id = 2,
LastName = "Петров",
FirstName = "Пётр",
Patronymic = "Петрович",
Birthday = new DateTime(1981, 9, 3),
EmploymentStart = new DateTime(2014, 2, 16)
},
new()
{
Id = 3,
LastName = "Сидоров",
FirstName = "Сидор",
Patronymic = "Сидорович",
Birthday = new DateTime(1991, 7, 30),
EmploymentStart = new DateTime(2016, 9, 26)
},
};
public static List<Employee> Employees => _employees;
private static readonly List<Brand> _brands = new()
{
new() { Id = 1, Name = "Acne", OrderNumber = 1 },
new() { Id = 2, Name = "Grüne Erde", OrderNumber = 2 },
new() { Id = 3, Name = "Albiro", OrderNumber = 3 },
new() { Id = 4, Name = "Ronhill", OrderNumber = 4 },
new() { Id = 5, Name = "Oddmolly", OrderNumber = 5 },
new() { Id = 6, Name = "Boudestijn", OrderNumber = 6 },
new() { Id = 7, Name = "Rösch creative culture", OrderNumber = 7 }
};
public static List<Brand> Brands => _brands;
private static readonly List<Category> _categories = new()
{
new() { Id = 1, Name = "Sportswear", OrderNumber = 1 },
new() { Id = 2, Name = "Nike", OrderNumber = 1, ParentId = 1 },
new() { Id = 3, Name = "Under Armour", OrderNumber = 2, ParentId = 1 },
new() { Id = 4, Name = "Adidas", OrderNumber = 3, ParentId = 1 },
new() { Id = 5, Name = "Puma", OrderNumber = 4, ParentId = 1 },
new() { Id = 6, Name = "ASICS", OrderNumber = 5, ParentId = 1 },
new() { Id = 7, Name = "Mens", OrderNumber = 2 },
new() { Id = 8, Name = "Fendi", OrderNumber = 1, ParentId = 7 },
new() { Id = 9, Name = "Guess", OrderNumber = 2, ParentId = 7 },
new() { Id = 10, Name = "Valentino", OrderNumber = 3, ParentId = 7 },
new() { Id = 11, Name = "Dior", OrderNumber = 4, ParentId = 7 },
new() { Id = 12, Name = "Versace", OrderNumber = 5, ParentId = 7 },
new() { Id = 13, Name = "Armani", OrderNumber = 6, ParentId = 7 },
new() { Id = 14, Name = "Prada", OrderNumber = 7, ParentId = 7 },
new() { Id = 15, Name = "Dolce and Gabbana", OrderNumber = 8, ParentId = 7 },
new() { Id = 16, Name = "Chanel", OrderNumber = 9, ParentId = 7 },
new() { Id = 17, Name = "Gucci", OrderNumber = 10, ParentId = 7 },
new() { Id = 18, Name = "Womens", OrderNumber = 3 },
new() { Id = 19, Name = "Fendi", OrderNumber = 1, ParentId = 18 },
new() { Id = 20, Name = "Guess", OrderNumber = 2, ParentId = 18 },
new() { Id = 21, Name = "Valentino", OrderNumber = 3, ParentId = 18 },
new() { Id = 22, Name = "Dior", OrderNumber = 4, ParentId = 18 },
new() { Id = 23, Name = "Versace", OrderNumber = 5, ParentId = 18 },
new() { Id = 24, Name = "Kids", OrderNumber = 4 },
new() { Id = 25, Name = "Fashion", OrderNumber = 5 },
new() { Id = 26, Name = "Households", OrderNumber = 6 },
new() { Id = 27, Name = "Interiors", OrderNumber = 7 },
new() { Id = 28, Name = "Clothing", OrderNumber = 8 },
new() { Id = 29, Name = "Bags", OrderNumber = 9 },
new() { Id = 30, Name = "Shoes", OrderNumber = 10 }
};
public static List<Category> Categories => _categories;
private static List<Product> _products = new()
{
new() { Id = 1, Name = "Product 1", ImageUrl = "product1.jpg", Price = 101, CategoryId = 2, BrandId = 1 },
new() { Id = 2, Name = "Product 2", ImageUrl = "product2.jpg", Price = 102, CategoryId = 8, BrandId = 1 },
new() { Id = 2, Name = "Product 3", ImageUrl = "product3.jpg", Price = 103, CategoryId = 19, BrandId = 2 },
new() { Id = 2, Name = "Product 4", ImageUrl = "product4.jpg", Price = 104, CategoryId = 24, BrandId = 2 },
new() { Id = 2, Name = "Product 5", ImageUrl = "product5.jpg", Price = 105, CategoryId = 25, BrandId = 3 },
new() { Id = 2, Name = "Product 6", ImageUrl = "product6.jpg", Price = 106, CategoryId = 26, BrandId = 3 },
new() { Id = 2, Name = "Product 7", ImageUrl = "product7.jpg", Price = 107, CategoryId = 27, BrandId = 4 },
new() { Id = 2, Name = "Product 8", ImageUrl = "product8.jpg", Price = 108, CategoryId = 28, BrandId = 5 },
new() { Id = 2, Name = "Product 9", ImageUrl = "product9.jpg", Price = 109, CategoryId = 29, BrandId = 5 },
new() { Id = 2, Name = "Product 10", ImageUrl = "product10.jpg", Price = 110, CategoryId = 30, BrandId = 6 },
new() { Id = 2, Name = "Product 11", ImageUrl = "product11.jpg", Price = 111, CategoryId = 1, BrandId = 7 },
new() { Id = 2, Name = "Product 12", ImageUrl = "product12.jpg", Price = 112, CategoryId = 1, BrandId = 7 }
};
public static List<Product> Products => _products;
}
}
|
C++
|
UTF-8
| 647
| 2.9375
| 3
|
[] |
no_license
|
#include <iostream>
#include <iomanip>
using namespace std;
int main(int argc, char const *argv[])
{
int t,n;
cin >> t;
while(t-- > 0){
cin >> n;
int A[n];
for (int i = 0; i < n; ++i)
{
cin >> A[i];
}
int max_sum = 0, ctr = 0;
for(int i=0; i<n ;i++){
for(int j = i+1; j < n;j++){
if(A[i]+A[j] > max_sum){
max_sum = A[i] + A[j];
ctr = 1;
}
else if(A[i]+A[j] == max_sum)
ctr++;
}
}
int tot = n*(n-1)/2;
double prob = (double)ctr/tot;
if(prob == 1)
cout << setprecision(9) << showpoint << prob << "\n";
else
cout << setprecision(8) << showpoint << prob << "\n";
}
return 0;
}
|
Java
|
UTF-8
| 1,594
| 2.984375
| 3
|
[
"Apache-2.0"
] |
permissive
|
package tests.java.awt;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import java.awt.AWTException;
import java.awt.Dimension;
import java.awt.GraphicsDevice;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
public class ScreenshotTest {
@Test
public void test() {
BufferedImage img = createDesktopScreenshot(null, 0, 0, 3, 2);
assertEquals(2, img.getHeight());
assertEquals(3, img.getWidth());
assertEquals(img.getType(), BufferedImage.TYPE_INT_RGB);
}
public static BufferedImage createDesktopScreenshot() {
Dimension size = Toolkit.getDefaultToolkit().getScreenSize();
return createDesktopScreenshot(null, 0, 0, (int) size.getWidth(), (int) size.getHeight());
}
public static BufferedImage createDesktopScreenshot(GraphicsDevice screen, Rectangle region) {
return createDesktopScreenshot(screen, region.x, region.y, region.width, region.height);
}
public static BufferedImage createDesktopScreenshot(GraphicsDevice screen,
int x, int y, int w, int h) {
try {
final Robot objRobot;
if (screen != null) {
objRobot = new Robot(screen);
} else {
objRobot = new Robot();
}
return objRobot.createScreenCapture(new Rectangle(x, y, w, h));
} catch (AWTException ex) {
throw new RuntimeException(ex);
}
}
}
|
JavaScript
|
UTF-8
| 803
| 2.515625
| 3
|
[] |
no_license
|
import React , {Component} from 'react';
import Fevent from './functionalEvent';
class Event extends Component{
state={
details: [
{name : 'jeevan', age: 22},
{name : 'rakesh', age: 30},
{name : 'chadarla', age: 42},
],
title: 'Hello React list students'
}
render(){
return(
<>
<h1>{this.state.title}</h1>
<Fevent age={this.state.details[0].age}> {this.state.details[0].name} </Fevent>
<Fevent age={this.state.details[1].age}> {this.state.details[1].name} </Fevent>
<Fevent age={this.state.details[2].age}> {this.state.details[2].name} </Fevent>
</>
)
}
}
export default Event;
|
JavaScript
|
UTF-8
| 14,644
| 2.703125
| 3
|
[
"ISC"
] |
permissive
|
'use strict';
var util = require('./../common/util.js');
var geometry = require('./../common/geometry.js');
var Pathfinder = require('./../actors/pathfinder.js');
var Slab = require('./slab.js');
var Tile = require('./tile.js');
var TileSheet = require('./sheet2.js');
module.exports = World;
var Canvas = require('./../common/bettercanvas.js');
var testCanvas = new Canvas(200,100);
var unoccupiedGrids; // For faster actor placement on init
//document.body.appendChild(testCanvas.canvas);
function World(game,worldSize) {
this.game = game;
this.game.world = this;
this.worldSize = Math.max(24,Math.floor(worldSize/2)*2); // Must be an even number >= 24
//this.worldSize = Math.max(12,Math.floor(worldSize/2)*2); // Must be an even number >= 24
this.worldRadius = Math.floor(this.worldSize/2);
this.objects = {};
this.map = {}; // Grid-based map to hold world tiles
this.walkable = {}; // Grid-based map to hold walkable surfaces
// TODO: Move world generation into a new module
geometry.generateClosestGrids(this.worldSize);
testCanvas.clear();
var noiseBig = geometry.buildNoiseMap(this.worldRadius/3 + 1, this.worldRadius/3 + 1);
var noiseSmall = geometry.buildNoiseMap(this.worldRadius/1.5 + 1,this.worldRadius/1.5 + 1);
var bigBlur = (noiseBig.length - 1) / this.worldSize;
var smallBlur = (noiseSmall.length - 1) / this.worldSize;
this.mapBounds = { xl: 0, yl: 0, xh: 0, yh: 0 }; // TODO: Center canvas using this
for(var tx = 0; tx < this.worldSize; tx++) for(var ty = 0; ty < this.worldSize; ty++) {
var bigNoiseValue = geometry.getNoiseMapPoint(noiseBig, tx * bigBlur, ty * bigBlur);
var smallNoiseValue = geometry.getNoiseMapPoint(noiseSmall, tx * smallBlur, ty * smallBlur);
var noiseValue = (bigNoiseValue + smallNoiseValue*2) / 3;
//var color = 'rgba(255,255,255,'+noiseValue+')'; // Draw debug noise map
//testCanvas.fillRect(color, tx, ty, 1, 1);
var grid;
var x = (tx-this.worldRadius), y = (ty-this.worldRadius);
var farness = (this.worldRadius - (Math.abs(x)+Math.abs(y))/2)/this.worldRadius;
if(noiseValue/1.1 < farness) {
this.mapBounds.xl = Math.min(x,this.mapBounds.xl);
this.mapBounds.yl = Math.min(y,this.mapBounds.yl);
this.mapBounds.xh = Math.max(x,this.mapBounds.xh);
this.mapBounds.yh = Math.max(y,this.mapBounds.yh);
grid = new Slab('grass', x, y, -0.5);
grid.grid = x+':'+y;
this.map[x+':'+y] = grid;
grid.addToGame(game);
}
}
this.staticMap = [];
this.crawlMap(); // Examine map to determine islands, borders, etc
this.createTiles(); // Create map tiles from grid intersections
var lowestScreenX = 0, lowestScreenY = 0, highestScreenX = 0, highestScreenY = 0;
for(var i = 0; i < this.staticMap.length; i++) {
var preTile = this.staticMap[i];
var preScreen = { x: preTile.screen.x, y: preTile.screen.y };
preScreen.x += preTile.sprite.metrics.ox || 0;
preScreen.y += preTile.sprite.metrics.oy || 0;
lowestScreenX = lowestScreenX < preScreen.x ? lowestScreenX : preScreen.x;
lowestScreenY = lowestScreenY < preScreen.y ? lowestScreenY : preScreen.y;
highestScreenX = highestScreenX > preScreen.x ? highestScreenX : preScreen.x;
highestScreenY = highestScreenY > preScreen.y ? highestScreenY : preScreen.y;
}
var bgCanvas = new Canvas(
(highestScreenX - lowestScreenX) + 32 + 1, (highestScreenY - lowestScreenY) + 32 + 9
);
for(var j = 0; j < this.staticMap.length; j++) {
var tile = this.staticMap[j];
var screen = { x: tile.screen.x, y: tile.screen.y };
screen.x += tile.sprite.metrics.ox || 0;
screen.y += tile.sprite.metrics.oy || 0;
screen.x -= lowestScreenX;
screen.y -= lowestScreenY;
bgCanvas.drawImage(
this.game.renderer.images[tile.sprite.image], tile.sprite.metrics.x, tile.sprite.metrics.y,
tile.sprite.metrics.w, tile.sprite.metrics.h,
Math.round(screen.x), Math.round(screen.y), tile.sprite.metrics.w, tile.sprite.metrics.h
);
}
//bgCanvas.context.globalCompositeOperation = 'color';
//bgCanvas.fill('rgba(30,30,50,0.7)');
this.game.renderer.bgCanvas = {
x: lowestScreenX, y: lowestScreenY, image: bgCanvas.canvas
};
Pathfinder.loadMap(this.walkable);
unoccupiedGrids = Object.keys(this.map);
unoccupiedGrids.splice(unoccupiedGrids.indexOf('0:0'), 1); // 0,0 is taken by beacon
console.log('Created world with',Object.keys(this.map).length,'tiles');
// TODO: Retry if tile count is too high/low
}
World.prototype.crawlMap = function() {
this.islands = [];
var crawled = {};
var thisIsland = 0;
for(var x = this.mapBounds.xl; x <= this.mapBounds.xh; x++) {
for(var y = this.mapBounds.yl; y <= this.mapBounds.yh; y++) {
var currentTile = this.map[x+':'+y]; if(!currentTile) continue;
if(crawled[currentTile.grid]) continue; // Skip already-crawled tiles
var neighborsToCrawl = [];
while(true) { // Keep crawling outward until no neighbors are left
crawled[currentTile.grid] = currentTile;
if(this.islands[thisIsland]) this.islands[thisIsland].push(currentTile);
else this.islands.push([currentTile]);
var currentNeighbors = geometry.getNeighbors(currentTile.grid);
currentNeighbors = geometry.getNeighbors(currentTile.grid);
for(var iKey in currentNeighbors) { if (!currentNeighbors.hasOwnProperty(iKey)) continue;
var neighbor = this.map[currentNeighbors[iKey]];
if(!neighbor) { currentTile.border = true; continue; }
if(!crawled[neighbor.grid]) neighborsToCrawl.push(neighbor);
}
if(neighborsToCrawl.length > 0) {
currentTile = neighborsToCrawl.pop();
} else { thisIsland++; break; } // No more neighbors, this island is done
}
}
}
this.mainIsland = 0;
for(var i = 1; i < this.islands.length; i++) {
this.mainIsland = this.islands[i].length > this.islands[this.mainIsland].length ?
i : this.mainIsland;
}
for(var i2 = 0; i2 < this.islands.length; i2++) { if(i2 == this.mainIsland) continue;
for(var it = 0; it < this.islands[i2].length; it++) {
delete this.map[this.islands[i2][it].grid];
this.islands[i2][it].remove();
}
}
// Set border tiles to slab
for(var gKey in this.map) { if(!this.map.hasOwnProperty(gKey)) continue;
var finalTile = this.map[gKey];
if(finalTile.border) {
finalTile.style = 'plain';
} else {
var finalNeighbors = geometry.get8Neighbors(finalTile.grid);
for(var nKey in finalNeighbors) { if (!finalNeighbors.hasOwnProperty(nKey)) continue;
if(!this.map[finalNeighbors[nKey]]) {
finalTile.style = 'plain';
break;
}
}
}
}
this.map['0:0'].style = 'plain'; // Slab around beacon
this.map['1:0'].style = 'plain';
this.map['-1:0'].style = 'plain';
this.map['0:1'].style = 'plain';
this.map['0:-1'].style = 'plain';
// Create flower patches
for(var fp = 0; fp < Math.ceil(Math.pow(this.worldRadius,2) / 20); fp++) {
var safety = 0;
do {
var valid = true;
var grid = this.map[util.pickInObject(this.map)];
var flowerNeighbors = geometry.get8Neighbors(grid.grid);
for(var fKey in flowerNeighbors) { if (!flowerNeighbors.hasOwnProperty(fKey)) continue;
var fNeighbor = this.map[flowerNeighbors[fKey]];
if(!fNeighbor || fNeighbor.style != 'grass') {
valid = false;
break;
}
}
safety++;
} while(safety < 1000 && (grid.style != 'grass' || !valid));
if(safety == 1000) continue;
grid.style = 'flowers';
var spread = util.randomIntRange(1,4);
for(var s = 0; s < spread; s++) {
var canSpread = false;
var spreadX = grid.position.x+util.randomIntRange(-1,1),
spreadY = grid.position.y+util.randomIntRange(-1,1);
var spreadGrid = this.map[spreadX+':'+spreadY];
var spreadNeighbors = geometry.get8Neighbors(spreadGrid.grid);
for(var sKey in spreadNeighbors) { if (!spreadNeighbors.hasOwnProperty(sKey)) continue;
var sNeighbor = this.map[spreadNeighbors[sKey]];
if(!sNeighbor || (sNeighbor.style != 'grass' && sNeighbor.style != 'flowers')) {
canSpread = false;
break;
}
}
if(canSpread) spreadGrid.style = 'flowers';
}
}
};
World.prototype.createTiles = function() {
// Tile types:
// Grass G
// Slab S
// Flowers F
// Empty E
// Tile code constructed as NW-NE-SE-SW (eg. "S-X-X-B")
this.tileMap = {};
var self = this;
function tileType(grid) { return self.map[grid].style[0].replace(/p/,'s').toUpperCase(); }
function getTileCode(oGrid, nGrid) {
if(oGrid == nGrid) return tileType(oGrid);
var neighbor = self.map[nGrid];
if(!neighbor) return 'E';
return tileType(nGrid);
}
function generateTile(oGrid, tile, grid, game) {
var nGrids = tile.grids;
var tileCode = getTileCode(oGrid,nGrids[0])+'-'+getTileCode(oGrid,nGrids[1])
+'-'+getTileCode(oGrid,nGrids[2])+'-'+getTileCode(oGrid,nGrids[3]);
var tileSprite = (new TileSheet('tile')).map[tileCode];
if(!tileSprite) console.error('unknown tile code',tileCode,nGrids);
return {
tileCode: tileCode, position: tile, grid: grid, game: game
};
}
for(var key in this.map) { if(!this.map.hasOwnProperty(key)) continue;
var x = +key.split(':')[0], y = +key.split(':')[1], z = this.map[key].position.z;
var neighbors = geometry.get8Neighbors(key);
var nw = { x: x-0.5, y: y-0.5, z: z, grids: [neighbors.nw, neighbors.n, key, neighbors.w] },
ne = { x: x+0.5, y: y-0.5, z: z, grids: [neighbors.n, neighbors.ne, neighbors.e, key] },
se = { x: x+0.5, y: y+0.5, z: z, grids: [key, neighbors.e, neighbors.se, neighbors.s] },
sw = { x: x-0.5, y: y+0.5, z: z, grids: [neighbors.w, key, neighbors.s, neighbors.sw] };
var tiles = [nw,ne,se,sw];
for(var i = 0; i < tiles.length; i++) {
var tileGrid = z+':'+tiles[i].x+':'+tiles[i].y;
if(this.tileMap[tileGrid]) continue;
this.tileMap[tileGrid] = new Tile(generateTile(key, tiles[i], tileGrid, this.game));
this.staticMap.push(this.tileMap[tileGrid]);
}
}
this.staticMap.sort(function(a,b) { return a.zDepth - b.zDepth; });
};
World.prototype.addToWorld = function(obj) {
//console.log('world: adding object at',obj.position.x,obj.position.y,obj.position.z);
if(this.objects[obj.position.x]) {
if(this.objects[obj.position.x][obj.position.y]) {
if(this.objects[obj.position.x][obj.position.y][obj.position.z]) {
console.error('occupado!',obj.position.x,obj.position.y,obj.position.z,
obj,this.objects[obj.position.x][obj.position.y][obj.position.z]);
return false;
}
} else {
this.objects[obj.position.x][obj.position.y] = {};
}
} else {
this.objects[obj.position.x] = {};
this.objects[obj.position.x][obj.position.y] = {};
}
this.objects[obj.position.x][obj.position.y][obj.position.z] = obj;
this.updateWalkable(obj.position.x, obj.position.y);
};
World.prototype.removeFromWorld = function(obj) {
//console.log('world: removing object at',obj.position.x,obj.position.y,obj.position.z);
delete this.objects[obj.position.x][obj.position.y][obj.position.z];
this.updateWalkable(obj.position.x, obj.position.y);
};
World.prototype.moveObject = function(obj,x,y,z) {
//console.log('world: moving object from',obj.position.x,obj.position.y,obj.position.z,'to',x,y,z);
this.removeFromWorld(obj);
obj.position.x = x; obj.position.y = y; obj.position.z = z;
this.addToWorld(obj)
};
World.prototype.updateWalkable = function(x, y) {
//console.log('world: updating walkable at',x,y);
var objects = this.objects[x][y];
if(!objects || Object.keys(objects).length == 0) {
delete this.walkable[x+':'+y];
//console.log('world: ',x,y,'is now unwalkable');
return;
}
var zKeys = Object.keys(objects).sort(function(a, b) { return a - b; });
var topObject = objects[zKeys[zKeys.length-1]];
if(topObject.unWalkable) {
delete this.walkable[x+':'+y];
//console.log('world: ',x,y,'is now unwalkable');
} else {
this.walkable[x+':'+y] = topObject.position.z + topObject.height;
//console.log('world: ',x,y,'is now walkable',this.walkable[x+':'+y]);
}
};
World.prototype.randomEmptyGrid = function() {
return unoccupiedGrids.splice(util.randomIntRange(0, unoccupiedGrids.length - 1), 1)[0];
};
World.prototype.objectAtXYZ = function(x,y,z) {
if(!this.objects[x]) return false;
if(!this.objects[x][y]) return false;
return this.objects[x][y][z];
};
World.prototype.objectUnderXYZ = function(x,y,z) {
if(!this.objects[x]) return false;
if(!this.objects[x][y]) return false;
var highest = -1000;
for(var zKey in this.objects[x][y]) { if(!this.objects[x][y].hasOwnProperty(zKey)) continue;
if(+zKey > z) continue;
highest = +zKey > highest ? +zKey : highest;
}
return this.objects[x][y][highest];
};
World.prototype.findObject = function(obj) { // For debugging
for(var xKey in this.objects) { if (!this.objects.hasOwnProperty(xKey)) continue;
var xObjects = this.objects[xKey];
for(var yKey in xObjects) { if (!xObjects.hasOwnProperty(yKey)) continue;
var yObjects = xObjects[yKey];
for(var zKey in yObjects) { if (!yObjects.hasOwnProperty(zKey)) continue;
if(obj === yObjects[zKey]) return [xKey,yKey,zKey];
}
}
}
};
|
Python
|
UTF-8
| 836
| 3.328125
| 3
|
[] |
no_license
|
#
# https://app.codility.com/programmers/lessons/12-euclidean_algorithm/common_prime_divisors/
# https://app.codility.com/demo/results/trainingKEBYGS-74H/
#
def UniquePrimeDivisors(x):
result = set()
divisor = 2
while divisor < x:
if x % divisor == 0:
result.add(divisor)
x = x / divisor
else:
divisor += 1
result.add(int(x))
return result
def solution(a, b):
if a == None:
raise ValueError()
if b == None:
raise ValueError()
if len(a) != len(b):
raise ValueError()
counter = 0
for ix, xa in enumerate(a):
xb = b[ix]
s1 = UniquePrimeDivisors(xa)
s2 = UniquePrimeDivisors(xb)
if s1 == s2:
counter += 1
return counter
|
JavaScript
|
UTF-8
| 1,375
| 2.578125
| 3
|
[] |
no_license
|
import { database } from '../firebase'
const EditNote = ({
editId,
editTitle,
setEditTitle,
editText,
setEditText,
setShowEditForm,
setMessage1
}) => {
const handleDoneButton = async () => {
setShowEditForm(false)
setMessage1('Loading...')
function editNote(id, title, description) {
const editNote = {}
editNote['/notes/' + id] = { id, title, description }
database.ref().update(editNote)
}
editNote(editId, editTitle, editText)
setMessage1('')
}
const handleDeleteButton = async () => {
setShowEditForm(false)
setMessage1('Loading...')
function deleteNote() {
database.ref('notes/' + editId).remove()
}
deleteNote()
setMessage1('')
}
return (
<form className='edit-note'>
<input
className='note-title'
type='text'
placeholder='Title'
value={editTitle}
onChange={(e) => setEditTitle(e.target.value)}
/>
<textarea
className='note-area'
value={editText}
onChange={(e) => setEditText(e.target.value)}
placeholder='Description'
></textarea>
<button className='delete-btn' type='button'>
<img
src='/svgs/delete-icon.svg'
alt='delete-icon'
onClick={() => handleDeleteButton()}
/>
</button>
<input
className='done-btn'
type='button'
value='Done'
onClick={() => handleDoneButton()}
/>
</form>
)
}
export default EditNote
|
Markdown
|
UTF-8
| 848
| 2.859375
| 3
|
[] |
no_license
|
---
title: "About me"
date: 2019-09-01T09:05:18-05:00
---
I am a digital strategist who blogs about leadership and digital technology. I help organizations transform by using technology to make smarter decisions that improve performance. I am a former Economics Reporter at **The Wall Street Journal** and **two-time Google scholarship winner** for web development. I have a keen knowledge of leadership, digital communication, strategic planning, software development, the Internet, economics and international markets. I am a **public speaker** who has discussed business trends on **network television** and **national radio**. Contact me via LinkedIn if you are looking for a leader to **modernize and transform your organization** for digital success.
## LinkedIn
[Click Here to find me on LinkedIn](https://www.linkedin.com/in/rafaelgerena)
|
Java
|
UTF-8
| 315
| 2.484375
| 2
|
[] |
no_license
|
package lite.ast;
public class DivisionNode extends BinaryOperatorNode
{
public DivisionNode(ExpressionNode e1, ExpressionNode e2, int line, int col)
{
super(e1, e2, line, col);
}
public String unparse(int indent)
{
return this.unparseBinaryOperator("/", indent);
}
} // class DivisionNode
|
Python
|
UTF-8
| 967
| 3.109375
| 3
|
[] |
no_license
|
import os
from tkinter import filedialog, Text
from Ponto import *
# funcao para ler pontos de um arquivo através de uma interface gráfica
def lerPontos():
raiz = os.getcwd()
fileName = filedialog.askopenfilename(initialdir="${raiz}", title="Selecione um arquivo",
filetypes=(("text", "*.txt"),))
#os.chdir(raiz + "/TeseAlgoritmos/corretos/") #Muda a pasta raiz para esta (comentar/modificar essa linha caso o código não pegue)
pontos = []
with open(fileName, "r") as f:
for l in f:
row = l.split()
p = Ponto(float(row[0]),float(row[1]), float(row[2]))
pontos.append(p)
return pontos
# funcao para ler pontos de um arquivo através de seu diretório
def readPontos(fileName):
pontos = []
with open(fileName, "r") as f:
for l in f:
row = l.split()
p = Ponto(float(row[0]),float(row[1]), float(row[2]))
pontos.append(p)
return pontos
|
Java
|
UTF-8
| 1,315
| 2.8125
| 3
|
[] |
no_license
|
package com.hackaton.visualrecognition.data;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Created by fatih.erol on 19.10.2017.
*/
public class Class implements Parcelable {
private String className;
private float score;
public String getClassName(){
return this.className;
}
public void setClassName(String className){
this.className = className;
}
public float getScore(){
return this.score;
}
public void setScore(float score){
this.score = score;
}
public Class(String className, float score){
this.className = className;
this.score = score;
}
protected Class(Parcel in) {
this.className = in.readString();
this.score = in.readFloat();
}
@Override
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(className);
dest.writeFloat(score);
}
@Override
public int describeContents() {
return 0;
}
public static final Creator<Class> CREATOR = new Creator<Class>() {
@Override
public Class createFromParcel(Parcel in) {
return new Class(in);
}
@Override
public Class[] newArray(int size) {
return new Class[size];
}
};
}
|
PHP
|
UTF-8
| 2,128
| 2.8125
| 3
|
[] |
no_license
|
<?php
/**
* @author Carlos Alberto Suarez Garrido <suarezcarlos@unbosque.edu.co>
* @copyright Universidad el Bosque - Dirección de Tecnología
* @package entidades
*/
class ModalidadSIC{
/**
* @type int
* @access private
*/
private $codigoModalidadAcademicaSic;
/**
* @type String
* @access private
*/
private $nombreModalidadAcademicaSic;
/**
* @type int
* @access private
*/
private $estadoModalidadAcademicaSic;
/**
* @type Singleton
* @access private
*/
private $persistencia;
/**
* Constructor
* @param $persistencia
*/
public function ModalidadSIC( $persistencia ){
$this->persistencia = $persistencia;
}
/**
* Modifica el codigo de la modalidad academica
* @param int $codigoModalidadAcademica
* @access public
* @return void
*/
public function setCodigoModalidadAcademicaSic( $codigoModalidadAcademicaSic ){
$this->codigoModalidadAcademicaSic = $codigoModalidadAcademicaSic;
}
/**
* Retorna el codigo de la modalidad academica
* @access public
* @return int
*/
public function getCodigoModalidadAcademicaSic( ){
return $this->codigoModalidadAcademicaSic;
}
/**
* Modifica el nombre de la modalidad academica
* @param String $nombreModalidadAcademica
* @access public
* @return void
*/
public function setNombreModalidadAcademicaSic( $nombreModalidadAcademicaSic ){
$this->nombreModalidadAcademicaSic = $nombreModalidadAcademicaSic;
}
/**
* Retorna el nombre de la modalidad academica
* @access public
* @return String
*/
public function getNombreModalidadAcademicaSic( ){
return $this->nombreModalidadAcademicaSic;
}
/**
* Modifica el estado de la modalidad academica
* @param String $estadoModalidadAcademica
* @access public
* @return void
*/
public function setEstadoModalidadAcademicaSic( $estadoModalidadAcademicaSic ){
$this->estadoModalidadAcademicaSic = $estadoModalidadAcademicaSic;
}
/**
* Retorna el estado de la modalidad academica
* @access public
* @return int
*/
public function getEstadoModalidadAcademicaSic( ){
return $this->estadoModalidadAcademicaSic;
}
}
?>
|
C
|
ISO-8859-1
| 3,720
| 2.796875
| 3
|
[] |
no_license
|
#pragma once
#ifndef JEU_H
#define JEU_H
#define DEBUG 1
#ifdef DEBUG
// Module utile la detection de fuites memoires.
#include "vld.h"
#endif
#define NB_CASES 78
#define MOTIF "[]"
#define BAS 0
#define HAUT 1
#define LIGNES 0
#define COLONNES 1
#define ROULEUR 0
#define SPRINTEUR 1
#define print1D(i, tab, tag, taille) for(i = 0; i < taille; i++) printf(tag, tab[i]);
#define print2D(i, j, tab, tag, taille) for(i = 0; i < taille; i++) printf(tag, tab[j][i]);
#define CLS system("cls")
#define PAUSE system("pause")
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// Structure associe aux cyclistes : position sur le plateau, paquet de cartes associ, paquet de cartes dfausses.
typedef struct cycliste {
int m_indexesPlateau[2]; // Position [0, 1][0, 81].
int m_paquet[15]; // Paquet de 15 cartes associ chaque cycliste.
int m_defausse[15]; // Paquets de 15 cartes qu'on completera 3 cartes par 3 cartes.
}cycliste;
// Structure associe au jeu : Plateau de jeu, cyclistes et nombre de joueur.
typedef struct jeu {
char m_plateau[2][NB_CASES][3]; // Tableau 2 lignes, NB_CASES colonnes, de chaines de 3 caractres ("Ri\0").
cycliste *m_cyclistes; // Tableau de cyclistes R1 S1 R2 S2 [...] RN SN.
int m_nbJoueurs; // m_nbJoueurs * 2 -> Taille du tableau de cyclistes.
}jeu;
// 1 Fonction qui initialise une partie pour 'p_nbJoueur' joueurs.
jeu* Initialisation(int p_nbJoueur);
// 2 Fonction qui demande le nombre de joueur et le stocke dans 'p_nbJoueur'.
void Nb_joueur(int *p_nbJoueur);
// 3 Fonction qui rempli le tableau de cartes en fonction de 'mode' (0 : Rouleur, 1 : Sprinteur).
void Init_paquet(int p_cartes[15], char p_mode);
// 4 Fonction de test des indices des joueurs et des cartes associes avec le jeu '*p_terrain'.
void Test_init(jeu *p_terrain);
// 5 Fonction d'affichage du plateau et des personnages dessus.
void Affiche_jeu(jeu *p_terrain);
// 6 Fonction de libration de la mmoire associe tout '*p_terrain'.
void Liberer_jeu(jeu *p_terrain);
// 7 Fonction ralisant un tour de jeu sur le terrain.
void Tour(jeu *p_terrain);
// 8 Fonction qui dit s'il faut Transferer la defausse dans la pioche.
int Retirer(int p_cartes[15]);
// 9 Fonction qui indique si il y a un vainqueur.
int Fini(jeu *p_terrain);
// 10 Fonction qui change la valeur de deux pointeurs.
void Echange(int *p_a, int *p_b);
// 11 Fonction qui mlange le paquet de cartes.
void Melange(int p_paquet[15]);
// 12 Fonction qui Transfere les cartes de la defausse, les met la suite des cartes de la pioche et mlange le tout.
void Transfere(jeu *p_terrain, int p_joueur);
// 13 Fonction qui applique les dplacements aux cyclistes.
void Mouvements(jeu *p_terrain, int *p_cartes);
// 14 Fonction qui applique l'effet d'Aspiration aux cyclistes.
void Aspiration(jeu *p_terrain);
// 15 Fonction permettant de retrouver l'indice du joueur dans le tableau partir de sa chaine.
int Indice_j(char p_chaine[3]);
// 16 Fonction qui diffrencie un Rouleur d'un Sprinter.
int Difference_j(char p_chaine[3]);
// 17 Fonction qui ralise les dcallages adquats aux cyclistes.
void Decallages(jeu *p_terrain);
// 18 Fonction qui applique les cartes Fatigue aux cyclistes concerns.
void Fatigue(jeu *p_terrain);
// 19 Fonction qui affiche la dfausse du joueur courant.
void Affiche_defausse(jeu *p_terrain, int p_joueur);
// 20 Fonction qui affiche le ou les gagnants.
void Gagnant(jeu *p_terrain);
// 21 Fonction qui renvoie la chaine associe l'indexe du tableau.
char* Chaine_j(int p_indexe);
// 22 Fonction qui vrifie si 'p_test' est bien compris dans les bornes [p_min;p_max].
int Valide(int p_test, int p_min, int p_max);
#endif // !JEU_H
|
Shell
|
UTF-8
| 179
| 2.875
| 3
|
[] |
no_license
|
#!/bin/bash
echo "Menu:"
echo "1. open nano"
echo "2. open vi"
echo "3. open links"
echo "4. exit"
opt=0
read opt
case $opt in
1) nano ;;
2) vi ;;
3) links ;;
*) exit 0 ;;
esac
|
Markdown
|
UTF-8
| 6,559
| 2.640625
| 3
|
[
"MIT"
] |
permissive
|
# tol-api-php
[](https://travis-ci.org/traderinteractive/tol-api-php)
[](https://scrutinizer-ci.com/g/traderinteractive/tol-api-php/?branch=master)
[](https://coveralls.io/github/traderinteractive/tol-api-php?branch=master)
[](https://packagist.org/packages/traderinteractive/tol-api)
[](https://packagist.org/packages/traderinteractive/tol-api)
[](https://packagist.org/packages/traderinteractive/tol-api)
[](https://packagist.org/packages/traderinteractive/tol-api)
[](https://packagist.org/packages/traderinteractive/tol-api)
[](https://packagist.org/packages/traderinteractive/tol-api)
This is a PHP client for [REST](http://en.wikipedia.org/wiki/Representational_state_transfer) APIs like the TraderOnline APIs.
## Requirements
This api client requires PHP 7.3 or newer and uses composer to install further PHP dependencies. See the [composer specification](composer.json) for more details.
When contributing, access to a working mongo database for testing is needed. See the [Contribution Guidelines](.github/CONTRIBUTING.md) for more details.
## Installation
tol-api-php can be installed for use in your project using [composer](http://getcomposer.org).
The recommended way of using this library in your project is to add a `composer.json` file to your project. The following contents would add tol-api-php as a dependency:
```sh
composer require traderinteractive/tol-api
```
## Basic Usage
The basic guzzle client, without caching or automated pagination handling is mostly easy to work with.
To instantiate a client, you need the guzzle adapter, client id, client secret, and API url. This client should work with apis like the TOL APIs.
```php
use TraderInteractive\Api;
$apiAdapter = new Api\GuzzleAdapter();
$auth = Api\Authentication::createClientCredentials(
'clientId',
'clientSecret'
)
$apiClient = new Api\Client(
$apiAdapter,
$auth,
'https://baseApiUrl/v1'
);
```
Then you can make index requests like below, although it is recommended to take a look at the [Collection](#collection) section below so that you can take advantage of automatic pagination handling. Here's an example of how to fetch a single page of items.
```php
<li>
<?php
$response = $apiClient->index(
'resourceName',
array('aFilter' => '5')
);
if ($response->getStatusCode() !== 200) {
throw new Exception('Non successful index call');
}
$body = json_decode($response->getBody(), true);
$total = $body['pagination']['total'];
// Loop over the first page of items
foreach ($body['result'] as $item) {
echo "<li>{$item['foo']}</li>\n";
}
?>
</ul>
```
For getting just a single item back from the api, you can use the `get` method:
```php
// Get item 1234
$response = $apiClient->get('resourceName', '1234');
if ($response->getStatusCode() !== 200) {
throw new Exception('Failed to fetch item 1234');
}
$item = json_decode($response->getBody(), true);
echo "Fetched item {$item['foo']}\n";
```
For creating a new item, you can use the `post` method:
```php
$response = $apiClient->post(
'resourceName',
array(
'foo' => array(
'bar' => 'boo',
'bing' => '5',
),
)
);
if ($response->getStatusCode() !== 201) {
throw new Exception('Failed to create item foo');
}
$item = json_decode($response->getBody(), true);
echo $item['result']['foo'];
```
For updating an item, you can use the `put` method:
```php
// Set item 1234's foo to bar.
$response = $apiClient->put(
'resourceName',
'1234',
array('bing' => array('foo' => 'bar'))
);
if ($response->getStatusCode() !== 200) {
throw new Exception('Failed to update item 1234');
}
```
For deleting an item, you can use the `delete` method:
```php
// Delete item 1234.
$response = $apiClient->delete('resourceName', '1234');
if ($response->getStatusCode() !== 204) {
throw new Exception('Failed to delete item 1234');
}
```
For making asynchronous requests use the `start*()` and `end()` methods:
```php
$handleOne = $apiClient->startGet('resourceName', '1234');
$handleTwo = $apiClient->startGet('resourceName', '5678');
$responseOne = $apiClient->end($handleOne);
$responseTwo = $apiClient->end($handleTwo);
if ($responseOne->getStatusCode() !== 200) {
throw new Exception('Failed to fetch item 1234');
}
if ($responseTwo->getStatusCode() !== 200) {
throw new Exception('Failed to fetch item 5678');
}
$itemOne = json_decode($responseOne->getBody(), true);
$itemTwo = json_decode($responseTwo->getBody(), true);
echo "Fetched item {$itemOne['foo']}\n";
echo "Fetched item {$itemTwo['foo']}\n";
```
### Cache
The library allows for a [PSR-16 SimpleCache](https://www.php-fig.org/psr/psr-16/) implementation.
### Collection
This is the preferred way to make index requests so that you don't have to handle (or forget to handle!) pagination yourself. Using this iterator is simple with the API Client. As an example, here is a snippet of code that will create a dropdown list of items.
**WARNING** Updates should not be performed to the items in the collection while interating as this may change the pagination.
```php
<ul>
<?php
$items = new \TraderInteractive\Api\Collection(
$apiClient,
'resourceName',
array('aFilter' => '5')
);
foreach ($items as $item) {
echo "<li>{$item['foo']}</li>\n";
}
?>
</ul>
```
## Contributing
If you would like to contribute, please use our build process for any changes and after the build passes, send us a pull request on github!
There is also a [docker](http://www.docker.com/)-based [fig](http://www.fig.sh/) configuration that will standup docker containers for the databases, execute the build inside a docker container, and then terminate everything. This is an easy way to build the application:
```sh
fig run build
```
|
JavaScript
|
UTF-8
| 19,754
| 2.703125
| 3
|
[
"Apache-2.0"
] |
permissive
|
import polygonBoolean from 'poly-bool';
export default function makePolygonGroups(rects, pathOffset) {
const polygons = unionRects(offsetRects(rects, pathOffset), pathOffset);
const cleanedPolygons = polygons.map(poly => cleanPolygon(poly));
return cleanedPolygons;
}
function offsetRects(rects, offset) {
// offsets all the points in a rect
for (let i = 0; i < rects.length; i++) {
rects[i].x1 = rects[i].x1 - offset;
rects[i].y1 = rects[i].y1 - offset;
rects[i].x2 = rects[i].x2 + offset;
rects[i].y2 = rects[i].y2 + offset;
}
return rects;
}
function unionRects(rects, pathOffset) {
//console.log('unionRects: ', rects);
let initialPoly = polygonPointArr(rects[0]);
let polygons = [initialPoly];// todo - don't init?
//console.log(' - polygon:', polygon);
rects.forEach((rect, i) => {
//console.log(' - rect:', rect);
let pointArr = [polygonPointArr(rect)];
//console.log(' - pointArr:', pointArr);
polygons = polygonBoolean(pointArr, polygons, 'or');
//console.log(' - polygon:', polygon);
});
//console.log(' - unionRects returning: ', polygons);
if(polygons.length > 1){
// connect polygon islands
polygons = joinPolygons(polygons, pathOffset, 'elastic');
//console.log(' - joinPolygons returning: ', polygons);
}
return polygons;
}
function polygonPointArr(rect) {
const { x1, y1, x2, y2 } = rect;
return [ [x1, y1], [x2, y1], [x2, y2], [x1, y2] ];
}
function joinPolygons(polygonsArr, minBridgeThickness, style){
//console.log('joinPolygons start data ', JSON.stringify(polygonsArr));
// join the polygons until there is only 1 polygon
// limit prevents infinite loops on unsolvable problem (probably indicating a bug)
let i = 0;
let limit = polygonsArr.length +2;
while(polygonsArr.length > 1 && i <= limit){
i++;
let bridgeData = findNearestPointsInAll(polygonsArr);
//console.log('join', polygonsArr);
let bridgeRect;
let startLine = bridgeData.lineA;
let endLine = bridgeData.lineB;
let startPoint = bridgeData.pointA;
let endPoint = bridgeData.pointB;
if(bridgeData.pointA[0] > bridgeData.pointB[0]){
startLine = bridgeData.lineB;
endLine = bridgeData.lineA;
startPoint = bridgeData.pointB;
endPoint = bridgeData.pointA;
}
if(bridgeData.overlap == true){
if (startLine[0][1] == startLine[1][1]){
//console.log('horizontal parallel lines - make vertical bridge')
// find the overlapping x pixels - make a vertical bridge
let rectX1 = startLine[0][0] > endLine[0][0] ? startLine[0][0] : endLine[0][0];
let rectX2 = startLine[1][0] < endLine[1][0] ? startLine[1][0] : endLine[1][0];
let rectY1 = startLine[0][1];
let rectY2 = endLine[0][1];
rectX2 = rectX2 - rectX1 < minBridgeThickness ? rectX1 + minBridgeThickness : rectX2;
let deltaX = Math.abs(rectX2 - rectX1);
let deltaY = Math.abs(rectY2 - rectY1);
let thickness = minBridgeThickness;
if(style == 'elastic'){
thickness = deltaX * ((1/(deltaY*deltaY))*deltaX);
thickness = thickness < minBridgeThickness ? minBridgeThickness : thickness;
thickness = thickness > deltaX ? deltaX : thickness;
}
let bridgeX1 = ((rectX2 - rectX1)/2) - (thickness/2) + rectX1;
let bridgeX2 = ((rectX2 - rectX1)/2) + (thickness/2) + rectX1;
// bridgeX1 = bridgeX1 < rectX1 ? rectX1 : bridgeX1;
// bridgeX2 = bridgeX2 > rectX2 ? rectX2 : bridgeX2;
bridgeRect = [[bridgeX1, rectY1], [bridgeX2, rectY1], [bridgeX2, rectY2], [bridgeX1, rectY2]];
//console.log('bridgeRect ', bridgeRect);
polygonsArr = polygonBoolean(polygonsArr, bridgeRect, 'or');
} else {
// lineDirection == 'v' - build horizontal bridge
//console.log('vertical parallel lines - make horizontal bridge');
// - find the overlapping Y pixels
let rectX1 = startLine[0][0];
let rectX2 = endLine[0][0];
let rectY1 = startLine[0][1] > endLine[0][1] ? startLine[0][1] : endLine[0][1];
let rectY2 = startLine[1][1] < endLine[1][1] ? startLine[1][1] : endLine[1][1];
rectY2 = rectY2 - rectY1 < minBridgeThickness ? rectY1 + minBridgeThickness : rectY2;
let deltaX = Math.abs(rectX2 - rectX1);
let deltaY = Math.abs(rectY2 - rectY1);
let thickness = minBridgeThickness;
if(style == 'elastic'){
thickness = deltaY * ((1/(deltaX*deltaX))*deltaY);
thickness = thickness < minBridgeThickness ? minBridgeThickness : thickness;
thickness = thickness > deltaY ? deltaY : thickness;
}
let bridgeY1 = ((rectY2 - rectY1)/2) - (thickness/2) + rectY1;
let bridgeY2 = ((rectY2 - rectY1)/2) + (thickness/2) + rectY1;
bridgeRect = [[rectX1, bridgeY1], [rectX2, bridgeY1], [rectX2, bridgeY2], [rectX1, bridgeY2]];
//console.log('bridgeRect ', bridgeRect);
polygonsArr = polygonBoolean(polygonsArr, bridgeRect, 'or');
}
} else {
// points are orthoganol to each other
//console.log('adjascent');
if(startLine[0][0] == startLine[1][0]){
//start line is vertical - build horizontal bridge segment
//console.log('- h then v');
let startX = startPoint[0];
let endX = endPoint[0] + minBridgeThickness;
//let startY = startPoint[1] - minBridgeThickness;
//let endY = startPoint[1];
// if(startPoint[1] == startLine[0][1] && startPoint[1] < startLine[1][1]){
// startY = startPoint[1];
// endY = startPoint[1] + minBridgeThickness;
// }
let startY = startPoint[1] < startLine[1][1] ? startPoint[1] : startPoint[1] - minBridgeThickness;
let endY = startPoint[1] < startLine[1][1] ? startPoint[1] + minBridgeThickness : startPoint[1];
let rectX1 = startX;
let rectX2 = endX;
let rectY1 = startY;
let rectY2 = endY;
bridgeRect = [[rectX1, rectY1], [rectX2, rectY1], [rectX2, rectY2], [rectX1, rectY2]];
//console.log('bridgeRect ', bridgeRect);
polygonsArr = polygonBoolean(polygonsArr, bridgeRect, 'or');
// build vertical bridge segment
startY = rectY1;
endY = endPoint[1];
startX = rectX2 - minBridgeThickness;
endX = rectX2;
if(startPoint[0] == startLine[0][0] && startPoint[0] < startLine[1][0]){
startX = startPoint[0];
endX = startPoint[0] + minBridgeThickness;
}
rectX1 = startX;
rectX2 = endX;
rectY1 = startY;
rectY2 = endY;
bridgeRect = [[rectX1, rectY1], [rectX2, rectY1], [rectX2, rectY2], [rectX1, rectY2]];
//console.log('bridgeRect ', bridgeRect);
polygonsArr = polygonBoolean(polygonsArr, bridgeRect, 'or');
} else {
// line A is Horizontal - build vertical bridge segment
//console.log('- v then h');
let startY = startPoint[1];
let endY = endPoint[1];
// let startX = startPoint[0] < endPoint[0] ? startPoint[0] - minBridgeThickness : startPoint[0];
// let endX = startPoint[0] < endPoint[0] ? startPoint[0]: startPoint[0] - minBridgeThickness;
let startX = startPoint[0] < startLine[1][0] ? startPoint[0] : startPoint[0] - minBridgeThickness;
let endX = startPoint[0] < startLine[1][0] ? startPoint[0] + minBridgeThickness : startPoint[0] ;
let rectX1 = startX;
let rectX2 = endX;
let rectY1 = startY;
let rectY2 = endY;
bridgeRect = [[rectX1, rectY1], [rectX2, rectY1], [rectX2, rectY2], [rectX1, rectY2]];
//console.log('bridgeRect ', bridgeRect);
polygonsArr = polygonBoolean(polygonsArr, bridgeRect, 'or');
// build horizontal line segment
//console.log('startLine: ', startLine);
//console.log('endLine: ', endLine);
startY = endPoint[1] < endLine[1][1] ? endPoint[1] : endPoint[1] - minBridgeThickness;
endY = endPoint[1] < endLine[1][1] ? endPoint[1] + minBridgeThickness : endPoint[1];
startX = rectX1;
endX = endPoint[0] + minBridgeThickness;
if(startPoint[0] == startLine[0][0] && startPoint[0] < startLine[1][0]){
startX = startPoint[0];
endX = startPoint[0] + minBridgeThickness;
}
rectX1 = startX;
rectX2 = endX;
rectY1 = startY;
rectY2 = endY;
bridgeRect = [[rectX1, rectY1], [rectX2, rectY1], [rectX2, rectY2], [rectX1, rectY2]];
//console.log('bridgeRect ', bridgeRect);
polygonsArr = polygonBoolean(polygonsArr, bridgeRect, 'or');
}
}
// console.log('bridgePoints result data', bridgeRect);
//console.log('joinPolygons result data', JSON.stringify(polygonsArr));
}
return(polygonsArr);
}
// a function to find the closest points between all of the polygons
function findNearestPointsInAll(polygonArr){
let shortestDelta = Number.POSITIVE_INFINITY;
let shortestResult;
for (let i = 0; i < polygonArr.length; i++) {
for (let j = i+1; j < polygonArr.length; j++) {
let result = findNearestPoints(polygonArr[i], polygonArr[j]);
if(result.delta < shortestDelta){
shortestDelta = result.delta;
shortestResult = result;
}
}
}
return shortestResult;
}
function findNearestPoints(polygonA, polygonB) {
let closestDelta = Number.POSITIVE_INFINITY;
let closestPoint = polygonA[0];
let closestPointIndex = 0;
let closestLine = [polygonB[0], polygonB[1]];
// compare every point in PolygonA to every line in PolygonB and find closest distance
polygonA.forEach( (pointA, indexA, arrA) => {
let thisClosestPoint;
let thisClosestLine;
let thisClosestPointIndex;
let thisClosestDelta = polygonB.reduce( (prev, curr, i, arr) => {
let minDistance = 0;
if (i < arr.length -1) {
minDistance = pDistance(pointA[0], pointA[1], arr[i][0], arr[i][1], arr[i+1][0], arr[i+1][1]);
} else {
minDistance = pDistance(pointA[0], pointA[1], arr[i][0], arr[i][1], arr[0][0], arr[0][1]);
}
//console.log('minDistance ', minDistance);
if (minDistance < prev) {
thisClosestPoint = pointA;
thisClosestPointIndex = indexA;
let thisNextPointI = i+1 < arr.length ? i+1 : 0;
let thisPrevPointI = i-1 >= 0 ? i-1 : arr.length-1;
thisClosestLine = [arr[i], arr[thisNextPointI]];
//console.log('compare: ', thisClosestPoint[1], arr[i][1], arr[thisNextPointI][1]);
if((thisClosestPoint[0] == arr[i][0]) && (thisClosestPoint[0] == arr[thisNextPointI][0])){
// all x's are same- aligned on Y axis
thisClosestLine = [arr[i], arr[thisPrevPointI]];
//console.log('swapping vertical line');
} else if ((thisClosestPoint[1] == arr[i][1]) && (thisClosestPoint[1] == arr[thisNextPointI][1])){
// all Y's are same- aligned on X axis
thisClosestLine = [arr[i], arr[thisPrevPointI]];
//console.log('swapping H line');
}
return minDistance;
} else {
return prev;
}
}, Number.POSITIVE_INFINITY);
//console.log('thisClosestDelta ', thisClosestDelta);
if (thisClosestDelta < closestDelta){
closestDelta = thisClosestDelta;
closestPoint = thisClosestPoint;
closestLine = thisClosestLine;
closestPointIndex = thisClosestPointIndex;
}
});
//console.log('closestDelta: ', closestDelta);
let lineDirection = 'p';
let closestPointB = closestLine[0][0];
let overlap = false;
let lineA = [[0,0],[0,10]];
// find if points are alligned
//if(closestPoint[0] == closestLine[0][0]){
// x coordinate is alligned
//overlap = true;
//console.log("x align");
//} else if (closestPoint[1] == closestLine[0][1]){
// y coordinate is alligned
//overlap = true;
//console.log("y align");
// }
let prevPointIndex = closestPointIndex-1;
let nextPointIndex = closestPointIndex+1;
if (prevPointIndex < 0) prevPointIndex = polygonA.length - 1;
if (nextPointIndex > polygonA.length-1) nextPointIndex = 0;
if(closestLine[0][0] == closestLine[1][0]){
// Manage Vertical Lines
lineDirection = 'v'
// reorder points on line
if(closestLine[0][1] > closestLine[1][1]){
closestLine = [closestLine[1], closestLine[0]]
}
if(Math.abs(closestPoint[1] - closestLine[0][1]) < Math.abs(closestPoint[1] - closestLine[1][1]) ){
closestPointB = closestLine[0];
} else {
closestPointB = closestLine[1];
}
if(closestPoint[1] >= closestLine[0][1] && closestPoint[1] <= closestLine[1][1]){
overlap = true;
if (polygonA[prevPointIndex][0] == closestPoint[0]){
// prev point on PolygonA is vertically offset
lineA = [polygonA[prevPointIndex], polygonA[closestPointIndex]];
} else if (polygonA[nextPointIndex][0] == closestPoint[0]) {
// next point is vertically offset
lineA = [polygonA[nextPointIndex], polygonA[closestPointIndex]];
}
if(lineA[0][1] > lineA[1][1]){
lineA = [lineA[1], lineA[0]]
}
} else {
// nearest line is orthoganol (non overlaping) so select a perpendicular lineA
if (polygonA[prevPointIndex][1] == closestPoint[1]){
// prev point on PolygonA is horizontally offset
lineA = [polygonA[nextPointIndex], polygonA[closestPointIndex]];
} else if (polygonA[nextPointIndex][1] == closestPoint[1]) {
// next point is horizontally offset
lineA = [polygonA[prevPointIndex], polygonA[closestPointIndex]];
}
if(lineA[0][1] > lineA[1][1]){
lineA = [lineA[1], lineA[0]];
}
}
} else if(closestLine[0][1] == closestLine[1][1]){
// closestLine is Horizontal
lineDirection = 'h';
// reorder points in line
if(closestLine[0][0] > closestLine[1][0]){
closestLine = [closestLine[1], closestLine[0]]
}
// find closest point on line
if(Math.abs(closestPoint[0] - closestLine[0][0]) < Math.abs(closestPoint[0] - closestLine[1][0]) ){
closestPointB = closestLine[0];
} else {
closestPointB = closestLine[1];
}
// find if lines overlap in X pixels
if(closestPoint[0] >= closestLine[0][0] && closestPoint[0] <= closestLine[1][0]){
overlap = true;
// find the parallel line on polygonA
if (polygonA[prevPointIndex][1] == closestPoint[1]){
// prev point on PolygonA is horizontally offset
lineA = [polygonA[prevPointIndex], polygonA[closestPointIndex]];
} else if (polygonA[nextPointIndex][1] == closestPoint[1]) {
// next point is horizontally offset
lineA = [polygonA[nextPointIndex], polygonA[closestPointIndex]];
}
if(lineA[0][0] > lineA[1][0]){
lineA = [lineA[1], lineA[0]];
}
} else {
// nearest line is orthoganol (non overlaping) so select a perpendicular lineA
if (polygonA[prevPointIndex][1] == closestPoint[1]){
// prev point on PolygonA is horizontally offset
lineA = [polygonA[nextPointIndex], polygonA[closestPointIndex]];
} else if (polygonA[nextPointIndex][1] == closestPoint[1]) {
// next point is horizontally offset
lineA = [polygonA[prevPointIndex], polygonA[closestPointIndex]];
}
if(lineA[0][1] > lineA[1][1]){
lineA = [lineA[1], lineA[0]];
}
}
}
return ({ delta: closestDelta,
pointA: closestPoint,
pointB: closestPointB,
lineA: lineA,
lineB: closestLine,
overlap: overlap});
}
// finds shortest distance between point and line
function pDistance(x, y, x1, y1, x2, y2) {
var A = x - x1;
var B = y - y1;
var C = x2 - x1;
var D = y2 - y1;
var dot = A * C + B * D;
var len_sq = C * C + D * D;
var param = -1;
if (len_sq != 0) //in case of 0 length line
param = dot / len_sq;
var xx, yy;
if (param < 0) {
xx = x1;
yy = y1;
}
else if (param > 1) {
xx = x2;
yy = y2;
}
else {
xx = x1 + param * C;
yy = y1 + param * D;
}
var dx = x - xx;
var dy = y - yy;
return Math.sqrt(dx * dx + dy * dy);
}
function cleanPolygon(polygon) {
// clean up redundant points on a line
let polygonLength = 0;
while(polygon.length != polygonLength && polygon.length > 2) {
polygonLength = polygon.length;
for (let i=0; i<polygon.length; i++) {
var x2i = i+1;
if (x2i > polygon.length-1) x2i = (x2i - polygon.length);
var x3i = i+2;
if (x3i > polygon.length-1) x3i = (x3i - polygon.length);
//console.log('is ', hull.length, i, x2i, x3i );
if (polygon[i][0] == polygon[x2i][0] && polygon[i][0] == polygon[x3i][0]) {
//console.log('remove: ', hull[i-2].x, hull[i-1].x, hull[i].x );
polygon.splice(x2i, 1);
}
}
for (let i=0; i < polygon.length; i++) {
var y2i = i+1;
if (y2i > polygon.length-1) y2i = (y2i - polygon.length);
var y3i = i+2;
if (y3i > polygon.length-1) y3i = (y3i - polygon.length);
if (polygon[i][1] == polygon[y2i][1] && polygon[i][1] == polygon[y3i][1]) {
//console.log('remove: ', hull[i-2].x, hull[i-1].x, hull[i].x );
polygon.splice(y2i, 1);
}
}
}
return polygon;
}
function findNearestRect(rectA, rects) {
let neighbors = rects.forEach((rectB) => {
// make sure rects are not intersecting
if (rectA !== rectB && !isIntersecting(rectA, rectB)) {
// find closest faces
let minDist = Number.POSITIVE_INFINITY;
}
});
}
// determine if two rects intersect
function isIntersecting(rectA, rectB) {
let overlappingX = false;
let overlappingY = false;
if (rectA.x1 == rectB.x1 && rectA.x2 == rectB.x2 &&
rectA.y1 == rectB.y1 && rectA.y2 == rectB.y2) {
//same
return true;
}
if (rectA.x1 >= rectB.x1 && rectA.x1 <= rectB.x2) {
overlappingX = true;
} else if (rectA.x2 >= rectB.x1 && rectA.x2 <= rectB.x2) {
overlappingX = true;
}
if (rectA.y1 >= rectB.y1 && rectA.y1 <= rectB.y2) {
overlappingY = true;
} else if (rectA.y2 >= rectB.y1 && rectA.y2 <= rectB.y2) {
overlappingY = true;
}
//console.log(' - result x y: ' , overlappingX, overlappingY);
if (overlappingY && overlappingX) {
//console.log('overlapping: ', JSON.stringify(rectA), JSON.stringify(rectB));
return true;
} else {
return false;
}
}
function findIntersecting(rects) {
let overlappingX = false;
let overlappingY = false;
let overlappingRects = rects.filter((rectA, i, rects) =>
{
//console.log('rectPoints ', JSON.stringify(rectPoints));
for (let rectB of rects) {
overlappingX = false;
overlappingY = false;
// debugger;
//console.log('checking: ' , JSON.stringify(rectA), JSON.stringify(rectB));
if (!(rectA.x1 === rectB.x1 && rectA.x2 === rectB.x2 &&
rectA.y1 === rectB.y1 && rectA.y2 === rectB.y2)) {
if (rectA.x1 >= rectB.x1 && rectA.x1 <= rectB.x2) {
overlappingX = true;
} else if (rectA.x2 >= rectB.x1 && rectA.x2 <= rectB.x2) {
overlappingX = true;
}
if (rectA.y1 >= rectB.y1 && rectA.y1 <= rectB.y2) {
overlappingY = true;
} else if (rectA.y2 >= rectB.y1 && rectA.y2 <= rectB.y2) {
overlappingY = true;
}
//console.log(' - result x y: ' , overlappingX, overlappingY);
if (overlappingY && overlappingX) {
//console.log('overlapping: ', JSON.stringify(rectA), JSON.stringify(rectB));
return true;
}
}
}
return false;
});
return(overlappingRects);
}
|
Go
|
UTF-8
| 3,357
| 2.515625
| 3
|
[
"MIT"
] |
permissive
|
package radarr
import (
"bytes"
"context"
"encoding/json"
"fmt"
"golift.io/starr"
)
const bpMovieEditor = bpMovie + "/editor"
// BulkEdit is the input for the bulk movie editor endpoint.
// You may use starr.True(), starr.False(), starr.Int64(), and starr.String() to add data to the struct members.
// Use Availability.Ptr() to add a value to minimum availability, and starr.ApplyTags.Ptr() for apply tags.
type BulkEdit struct {
MovieIDs []int64 `json:"movieIds"`
Monitored *bool `json:"monitored,omitempty"`
QualityProfileID *int64 `json:"qualityProfileId,omitempty"`
MinimumAvailability *Availability `json:"minimumAvailability,omitempty"` // tba
RootFolderPath *string `json:"rootFolderPath,omitempty"` // path
Tags []int `json:"tags,omitempty"` // [0]
ApplyTags *starr.ApplyTags `json:"applyTags,omitempty"` // add
MoveFiles *bool `json:"moveFiles,omitempty"`
DeleteFiles *bool `json:"deleteFiles,omitempty"` // delete only
AddImportExclusion *bool `json:"addImportExclusion,omitempty"` // delete only
}
// Availability is an enum used as MinimumAvailability in a few places throughout Radarr.
type Availability string
// Availability / MinimumAvailability constants.
// https://radarr.video/docs/api/#/MovieEditor/put_api_v3_movie_editor
const (
AvailabilityToBeAnnounced Availability = "tba"
AvailabilityAnnounced Availability = "announced"
AvailabilityInCinemas Availability = "inCinemas"
AvailabilityReleased Availability = "released"
AvailabilityDeleted Availability = "deleted"
)
// Ptr returns a pointer to a minimum availability. Useful for a BulkEdit struct.
func (a Availability) Ptr() *Availability {
return &a
}
// EditMovies allows bulk diting many movies at once.
func (r *Radarr) EditMovies(editMovies *BulkEdit) ([]*Movie, error) {
return r.EditMoviesContext(context.Background(), editMovies)
}
// EditMoviesContext allows bulk diting many movies at once.
func (r *Radarr) EditMoviesContext(ctx context.Context, editMovies *BulkEdit) ([]*Movie, error) {
var body bytes.Buffer
if err := json.NewEncoder(&body).Encode(editMovies); err != nil {
return nil, fmt.Errorf("json.Marshal(%s): %w", bpMovieEditor, err)
}
var output []*Movie
req := starr.Request{URI: bpMovieEditor, Body: &body}
if err := r.PutInto(ctx, req, &output); err != nil {
return nil, fmt.Errorf("api.Put(%s): %w", &req, err)
}
return output, nil
}
// DeleteMovies bulk deletes movies. Can also mark them as excluded, and delete their files.
func (r *Radarr) DeleteMovies(deleteMovies *BulkEdit) error {
return r.DeleteMoviesContext(context.Background(), deleteMovies)
}
// DeleteDeleteMoviesContextMovies bulk deletes movies. Can also mark them as excluded, and delete their files.
func (r *Radarr) DeleteMoviesContext(ctx context.Context, deleteMovies *BulkEdit) error {
var body bytes.Buffer
if err := json.NewEncoder(&body).Encode(deleteMovies); err != nil {
return fmt.Errorf("json.Marshal(%s): %w", bpMovieEditor, err)
}
req := starr.Request{URI: bpMovieEditor, Body: &body}
if err := r.DeleteAny(ctx, req); err != nil {
return fmt.Errorf("api.Delete(%s): %w", &req, err)
}
return nil
}
|
Ruby
|
UTF-8
| 784
| 2.734375
| 3
|
[
"Apache-2.0"
] |
permissive
|
#create_db
require "sequel"
begin
DB = Sequel.sqlite('sinatra_shop.db')
DB.create_table :products do
primary_key :id
String :name
Float :price
String :buy_link
end
rescue
end
begin
DB = Sequel.sqlite('sinatra_shop.db')
DB.create_table :carts do
primary_key :id
String :username
Float :session_id
String :content
end
rescue
end
# create a dataset from the items table
# products = DB[:products]
# # populate the table
# items.insert(:name => 'abc', :price => rand * 100)
# items.insert(:name => 'def', :price => rand * 100)
# items.insert(:name => 'ghi', :price => rand * 100)
# # print out the number of records
# puts "Item count: #{items.count}"
# # print out the average price
# puts "The average price is: #{items.avg(:price)}"
|
Java
|
UTF-8
| 13,236
| 1.960938
| 2
|
[] |
no_license
|
/*!*****************************************************************************
*
* Selenium Tests For CTools
*
* Copyright (C) 2002-2016 by Pentaho : http://www.pentaho.com
*
*******************************************************************************
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************/
package com.pentaho.ctools.cdf;
import static org.testng.Assert.assertEquals;
import static org.testng.Assert.assertNotEquals;
import static org.testng.Assert.assertNotNull;
import static org.testng.Assert.assertTrue;
import java.util.Iterator;
import java.util.Set;
import org.apache.http.HttpStatus;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.interactions.Actions;
import org.testng.annotations.Test;
import com.pentaho.ctools.utils.ActionsHelper;
import com.pentaho.ctools.utils.ElementHelper;
import com.pentaho.ctools.utils.HttpUtils;
import com.pentaho.ctools.utils.PageUrl;
import com.pentaho.selenium.BaseTest;
/**
* Testing the functionalities related with jFree Chart Component.
*
* Naming convention for test: 'tcN_StateUnderTest_ExpectedBehavior'
*
*/
public class JFreeChartComponent extends BaseTest {
// Access to wrapper for webdriver
private final ElementHelper elemHelper = new ElementHelper();
// Log instance
private final Logger log = LogManager.getLogger( JFreeChartComponent.class );
/**
* ############################### Test Case 0 ###############################
*
* Test Case Name: Open Sample Page
*/
@Test
public void tc0_OpenSamplePage_Display() {
this.log.info( "tc0_OpenSamplePage_Display" );
// The URL for the JFreeChartComponent under CDF samples
// This sample is in: Public/plugin-samples/CDF/Documentation/Component Reference/Core Components/jFreeChartComponent
this.elemHelper.Get( driver, PageUrl.JFREE_CHART_COMPONENT );
// NOTE - we have to wait for loading disappear
this.elemHelper.WaitForElementInvisibility( driver, By.cssSelector( "div.blockUI.blockOverlay" ) );
}
/**
* ############################### Test Case 1 ###############################
*
* Test Case Name:
* Validate Page Contents
*
* Description:
* Here we want to validate the page contents.
*
* Steps:
* 1. Check the widget's title.
*/
@Test
public void tc1_PageContent_DisplayTitle() {
this.log.info( "tc1_PageContent_DisplayTitle" );
// Wait for title become visible and with value 'Community Dashboard Framework'
String expectedPageTitle = "Community Dashboard Framework";
String actualPageTitle = this.elemHelper.WaitForTitle( driver, expectedPageTitle );
// Wait for visibility of 'jFreeChartComponent'
String expectedSampleTitle = "jFreeChartComponent";
String actualSampleTitle = this.elemHelper.WaitForTextDifferentEmpty( driver, By.xpath( "//div[@id='dashboardContent']/div/div/div/h2/span[2]" ) );
// Validate the sample that we are testing is the one
assertEquals( actualPageTitle, expectedPageTitle );
assertEquals( actualSampleTitle, expectedSampleTitle );
}
/**
* ############################### Test Case 2 ###############################
*
* Test Case Name:
* Reload Sample
*
* Description:
* Reload the sample (not refresh page).
* Steps:
* 1. Click in Code and then click in button 'Try me'.
*/
@Test
public void tc2_ReloadSample_SampleReadyToUse() {
this.log.info( "tc2_ReloadSample_SampleReadyToUse" );
// ## Step 1
// Render again the sample
this.elemHelper.ClickJS( driver, By.xpath( "//div[@id='example']/ul/li[2]/a" ) );
this.elemHelper.ClickJS( driver, By.xpath( "//div[@id='code']/button" ) );
// NOTE - we have to wait for loading disappear
this.elemHelper.WaitForElementInvisibility( driver, By.cssSelector( "div.blockUI.blockOverlay" ) );
// Now sample element must be displayed
assertTrue( this.elemHelper.FindElement( driver, By.id( "sample" ) ).isDisplayed() );
// Check the number of divs with id 'SampleObject'
// Hence, we guarantee when click Try Me the previous div is replaced
int nSampleObject = this.elemHelper.FindElements( driver, By.id( "sampleObject" ) ).size();
assertEquals( 1, nSampleObject );
}
/**
* ############################### Test Case 3 ###############################
*
* Test Case Name:
* Select Month
*
* Description:
* The test case pretends to validate an alert is displayed after select a
* month and the alert displayed the selected month.
*
* Steps:
* 1. Open Pie Chart
* 2. Click on chart
* 3. Open Bar Chart
* 4. Click on chart
*/
@Test
public void tc3_ClickOnChart_AlertDisplayed() {
this.log.info( "tc3_ClickOnChart_AlertDisplayed" );
String title = "";
String confirmationMsg = "";
String firstChart = this.elemHelper.GetAttribute( driver, By.xpath( "//img[@id='sampleObjectimage']" ), "src" );
ActionsHelper actsHelper = new ActionsHelper( driver );
actsHelper.MouseOver( By.xpath( "//div[contains(text(),'Details')]" ) );
title = this.elemHelper.WaitForElementPresentGetText( driver, By.id( "sampleObjectcaptiontitle" ) );
assertTrue( title.equals( "Top 10 Customers" ) );
this.elemHelper.Click( driver, By.xpath( "//div[@id='sampleObjectcaptionchartType']" ) );
// NOTE - we have to wait for loading disappear
this.elemHelper.WaitForElementInvisibility( driver, By.cssSelector( "div.blockUI.blockOverlay" ) );
// Check if the generated image is different from previews, is not something static
assertNotNull( this.elemHelper.FindElement( driver, By.xpath( "//img[@id='sampleObjectimage']" ) ) );
String secondChart = this.elemHelper.GetAttribute( driver, By.xpath( "//img[@id='sampleObjectimage']" ), "src" );
assertNotEquals( firstChart, secondChart );
// ## Step 2
// Click in 'Dragon Souveniers, Ltd.'
this.elemHelper.Click( driver, By.xpath( "//map[@id='sampleObjectimageMap']/area[4]" ) );
confirmationMsg = this.elemHelper.WaitForAlertReturnConfirmationMsg( driver );
assertEquals( confirmationMsg, "You clicked Dragon Souveniers, Ltd." );
// Click in 'Mini Gifts Distributors Ltd'
this.elemHelper.FindElement( driver, By.xpath( "//map[@id='sampleObjectimageMap']/area[9]" ) ).click();
confirmationMsg = this.elemHelper.WaitForAlertReturnConfirmationMsg( driver );
assertEquals( confirmationMsg, "You clicked Mini Gifts Distributors Ltd." );
// ## Step 3
Actions acts2 = new Actions( driver );
acts2.moveToElement( this.elemHelper.FindElement( driver, By.xpath( "//div[contains(text(),'Details')]" ) ) );
acts2.perform();
// Open the Pie Chart
title = this.elemHelper.WaitForElementPresentGetText( driver, By.id( "sampleObjectcaptiontitle" ) );
assertTrue( title.equals( "Top 10 Customers" ) );
this.elemHelper.Click( driver, By.xpath( "//div[@id='sampleObjectcaptionchartType']" ) );
// NOTE - we have to wait for loading disappear
this.elemHelper.WaitForElementInvisibility( driver, By.cssSelector( "div.blockUI.blockOverlay" ) );
// Check if the generated image is different from previews, is not something static
assertNotNull( this.elemHelper.FindElement( driver, By.xpath( "//img[@id='sampleObjectimage']" ) ) );
String thirdChart = this.elemHelper.GetAttribute( driver, By.xpath( "//img[@id='sampleObjectimage']" ), "src" );
assertNotEquals( firstChart, thirdChart );
assertNotEquals( secondChart, thirdChart );
// ## Step 3
// Click in 'Australian Collectors, Co.'
this.elemHelper.FindElement( driver, By.xpath( "//map[@id='sampleObjectimageMap']/area[8]" ) ).click();
confirmationMsg = this.elemHelper.WaitForAlertReturnConfirmationMsg( driver );
assertEquals( confirmationMsg, "You clicked Australian Collectors, Co." );
// Click in 'Down Under Souveniers, Inc'
this.elemHelper.FindElement( driver, By.xpath( "//map[@id='sampleObjectimageMap']/area[5]" ) ).click();
confirmationMsg = this.elemHelper.WaitForAlertReturnConfirmationMsg( driver );
assertEquals( confirmationMsg, "You clicked Down Under Souveniers, Inc" );
}
/**
* ############################### Test Case 4 ###############################
*
* Test Case Name:
* Preview Chart
*
* Description:
* The test case pretends to validate when user press on Zoom a new window
* is displayed.
*
* Steps:
* 1. Zoom on Bar Chart
* 2. Zoom on Pie Chart
*/
@Test
public void tc4_PreviewChart_NewWindowDisplayed() {
this.log.info( "tc4_PreviewChart_NewWindowDisplayed" );
String title = "";
// ## Step 1
// Check bar title
this.elemHelper.MouseOverElementAndClick( driver, By.cssSelector( "div.caption-details" ) );
title = this.elemHelper.WaitForElementPresentGetText( driver, By.id( "sampleObjectcaptiontitle" ) );
assertTrue( title.equals( "Top 10 Customers" ) );
this.elemHelper.WaitForAttributeValue( driver, By.xpath( "//div[@class='caption-bottom']" ), "style", "margin: 0px", 10 );
// Click in Zoom
this.elemHelper.MouseOverElementAndClick( driver, By.cssSelector( "div.caption-details" ) );
this.elemHelper.Click( driver, By.xpath( "//div[@id='sampleObjectcaptionzoom']" ) );
this.elemHelper.WaitForAttributeValue( driver, By.xpath( "//div[@class='caption-bottom']" ), "style", "margin: 0px", 10 );
// NOTE - we have to wait for loading disappear
this.elemHelper.WaitForElementInvisibility( driver, By.cssSelector( "div.blockUI.blockOverlay" ) );
WebDriver popup = null;
String parentWindowHandle = driver.getWindowHandle(); // save the current window handle.
Set<String> setWindows = driver.getWindowHandles();
// wait for popup render
this.elemHelper.WaitForNewWindow( driver );
setWindows = driver.getWindowHandles();
// Get popup id
Iterator<String> windowIterator = setWindows.iterator();
while ( windowIterator.hasNext() ) {
String windowHandle = windowIterator.next();
popup = driver.switchTo().window( windowHandle );
if ( popup.getTitle().isEmpty() ) {
break;
}
}
if ( popup != null ) {
String attrSrcPopup = this.elemHelper.GetAttribute( popup, By.cssSelector( "img" ), "src" );
assertEquals( HttpStatus.SC_OK, HttpUtils.GetHttpStatus( attrSrcPopup ) );
popup.close();
driver = driver.switchTo().window( parentWindowHandle );
assertTrue( driver.getWindowHandles().size() == 1 );
this.elemHelper.SwitchToDefault( driver );
// ## Step 2
// Change to pie chart
this.elemHelper.MouseOverElementAndClick( driver, By.cssSelector( "div.caption-details" ) );
this.elemHelper.Click( driver, By.xpath( "//div[@id='sampleObjectcaptionchartType']" ) );
this.elemHelper.WaitForAttributeValue( driver, By.xpath( "//div[@class='caption-bottom']" ), "style", "margin: 0px", 3 );
// NOTE - we have to wait for loading disappear
this.elemHelper.WaitForElementInvisibility( driver, By.cssSelector( "div.blockUI.blockOverlay" ) );
// Zoom
this.elemHelper.MouseOverElementAndClick( driver, By.xpath( "//div[@class='caption-details']" ) );
this.elemHelper.Click( driver, By.xpath( "//div[@id='sampleObjectcaptionzoom']" ) );
this.elemHelper.WaitForAttributeValue( driver, By.xpath( "//div[@class='caption-bottom']" ), "style", "margin: 0px", 3 );
// NOTE - we have to wait for loading disappear
this.elemHelper.WaitForElementInvisibility( driver, By.cssSelector( "div.blockUI.blockOverlay" ) );
parentWindowHandle = driver.getWindowHandle(); // save the current window handle.
setWindows = driver.getWindowHandles();
// wait for popup render
this.elemHelper.WaitForNewWindow( driver );
setWindows = driver.getWindowHandles();
// Get popup id
windowIterator = setWindows.iterator();
while ( windowIterator.hasNext() ) {
String windowHandle = windowIterator.next();
popup = driver.switchTo().window( windowHandle );
if ( popup.getTitle().isEmpty() ) {
break;
}
}
attrSrcPopup = this.elemHelper.GetAttribute( popup, By.cssSelector( "img" ), "src" );
assertEquals( HttpStatus.SC_OK, HttpUtils.GetHttpStatus( attrSrcPopup ) );
popup.close();
driver.switchTo().window( parentWindowHandle );
assertTrue( driver.getWindowHandles().size() == 1 );
} else {
assertNotNull( popup );
}
}
}
|
Java
|
UTF-8
| 264
| 2.109375
| 2
|
[] |
no_license
|
package com.example.simple;
import akka.actor.*;
public class FirstActor extends UntypedAbstractActor {
@Override
public void onReceive(Object message) throws Throwable {
System.out.println("FirstActor收到的消息为:"+message);
}
}
|
Swift
|
UTF-8
| 1,506
| 2.921875
| 3
|
[] |
no_license
|
//
// NamesTableViewController.swift
// foo
//
// Created by Arthur Sabintsev on 6/29/15.
// Copyright (c) 2015 GA. All rights reserved.
//
import UIKit
class NamesTableViewController: UITableViewController {
var names = ["Thomas", "Arthur", "Devin", "Luke", "Foo"]
override func viewDidLoad() {
super.viewDidLoad()
println("loaded")
}
// MARK: - Table view data source
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return names.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("nameCell", forIndexPath: indexPath) as! UITableViewCell
/*
NSIndexPath
- Section
- Row
0, 0
0, 1
0, 2
0, 3
*/
// Configure the cell...
println("Cell with row number = \(indexPath.row)")
cell.textLabel?.text = names[indexPath.row]
cell.backgroundColor = randomColor()
return cell
}
func randomColor() -> UIColor{
var randomRed:CGFloat = CGFloat(drand48())
var randomGreen:CGFloat = CGFloat(drand48())
var randomBlue:CGFloat = CGFloat(drand48())
return UIColor(red: randomRed, green: randomGreen, blue: randomBlue, alpha: 1.0)
}
}
|
Java
|
UTF-8
| 477
| 1.828125
| 2
|
[] |
no_license
|
package com.autogeneral.techtest.angservice.model.json;
import com.fasterxml.jackson.annotation.JsonProperty;
/** JSON object used as during the Patch (i.e. update) ToDoItem request */
public class ToDoItemUpdateRequest extends ToDoItemRequest {
private Boolean completed;
@JsonProperty("isCompleted")
public Boolean getCompleted() {
return completed;
}
public void setCompleted(Boolean completed) {
this.completed = completed;
}
}
|
Rust
|
UTF-8
| 2,888
| 2.546875
| 3
|
[
"MIT",
"LicenseRef-scancode-other-permissive",
"Apache-2.0",
"BSD-3-Clause",
"BSD-2-Clause",
"NCSA"
] |
permissive
|
// run-pass
// ignore-cloudabi no processes
// ignore-emscripten no processes
use std::process::{Command, Stdio};
use std::env;
use std::sync::{Mutex, RwLock};
use std::time::Duration;
use std::thread;
fn test_mutex() {
let m = Mutex::new(0);
let _g = m.lock().unwrap();
let _g2 = m.lock().unwrap();
}
fn test_try_mutex() {
let m = Mutex::new(0);
let _g = m.lock().unwrap();
let _g2 = m.try_lock().unwrap();
}
fn test_rwlock_ww() {
let m = RwLock::new(0);
let _g = m.write().unwrap();
let _g2 = m.write().unwrap();
}
fn test_try_rwlock_ww() {
let m = RwLock::new(0);
let _g = m.write().unwrap();
let _g2 = m.try_write().unwrap();
}
fn test_rwlock_rw() {
let m = RwLock::new(0);
let _g = m.read().unwrap();
let _g2 = m.write().unwrap();
}
fn test_try_rwlock_rw() {
let m = RwLock::new(0);
let _g = m.read().unwrap();
let _g2 = m.try_write().unwrap();
}
fn test_rwlock_wr() {
let m = RwLock::new(0);
let _g = m.write().unwrap();
let _g2 = m.read().unwrap();
}
fn test_try_rwlock_wr() {
let m = RwLock::new(0);
let _g = m.write().unwrap();
let _g2 = m.try_read().unwrap();
}
fn main() {
let args: Vec<String> = env::args().collect();
if args.len() > 1 {
match &*args[1] {
"mutex" => test_mutex(),
"try_mutex" => test_try_mutex(),
"rwlock_ww" => test_rwlock_ww(),
"try_rwlock_ww" => test_try_rwlock_ww(),
"rwlock_rw" => test_rwlock_rw(),
"try_rwlock_rw" => test_try_rwlock_rw(),
"rwlock_wr" => test_rwlock_wr(),
"try_rwlock_wr" => test_try_rwlock_wr(),
_ => unreachable!(),
}
// If we reach this point then the test failed
println!("TEST FAILED: {}", args[1]);
} else {
let mut v = vec![];
v.push(Command::new(&args[0]).arg("mutex").stderr(Stdio::null()).spawn().unwrap());
v.push(Command::new(&args[0]).arg("try_mutex").stderr(Stdio::null()).spawn().unwrap());
v.push(Command::new(&args[0]).arg("rwlock_ww").stderr(Stdio::null()).spawn().unwrap());
v.push(Command::new(&args[0]).arg("try_rwlock_ww").stderr(Stdio::null()).spawn().unwrap());
v.push(Command::new(&args[0]).arg("rwlock_rw").stderr(Stdio::null()).spawn().unwrap());
v.push(Command::new(&args[0]).arg("try_rwlock_rw").stderr(Stdio::null()).spawn().unwrap());
v.push(Command::new(&args[0]).arg("rwlock_wr").stderr(Stdio::null()).spawn().unwrap());
v.push(Command::new(&args[0]).arg("try_rwlock_wr").stderr(Stdio::null()).spawn().unwrap());
thread::sleep(Duration::new(1, 0));
// Make sure all subprocesses either panicked or were killed because they deadlocked
for mut c in v {
c.kill().ok();
assert!(!c.wait().unwrap().success());
}
}
}
|
Python
|
UTF-8
| 888
| 3.515625
| 4
|
[] |
no_license
|
import math
from euler_21 import ESieve, sumOfFactorsPrime
# find all abundant numbers
# create and mark all numbers which can be created as the sum
# of two abundant numbers
# sum up all non-marked numbers
limit = 28123
abundant = []
primeList = ESieve(int(math.sqrt(limit)))
sum = 0
# find all abundant numbers
for i in range(2, limit+1):
if sumOfFactorsPrime(i, primeList) > i:
abundant.append(i)
# create all sums of numbers
canBeWrittenAsAbundant = [False] * (limit+1)
for i in range(len(abundant)):
for j in range(i, len(abundant)):
if abundant[i] + abundant[j] <= limit:
canBeWrittenAsAbundant[abundant[i] + abundant[j]] = True
else:
break
# sum numbers which are not sums of two abundant
for i in range(1, limit+1):
if not canBeWrittenAsAbundant[i]:
sum += i
print(sum)
|
Ruby
|
UTF-8
| 3,340
| 2.71875
| 3
|
[
"MIT"
] |
permissive
|
module Rdm
module Handlers
class DependenciesHandler
ALREADY_MENTIONED_DEPS = '...'
class << self
def show_names(package_name:, project_path:)
new(package_name, project_path).show_names
end
def show_packages(package_name:, project_path:)
new(package_name, project_path).show_packages
end
def draw(package_name:, project_path:)
new(package_name, project_path).draw
end
end
def initialize(package_name, project_path)
@package_name = package_name
@project_path = project_path
end
def show_names
if @package_name.nil? || @package_name.empty?
raise Rdm::Errors::InvalidParams, "Package name should be specified"
end
if @project_path.nil? || @project_path.empty?
raise Rdm::Errors::InvalidParams, "Project directory should be specified"
end
recursive_find_dependencies([@package_name])
end
def show_packages
names = show_names
source.packages.values.select do |p|
names.include?(p.name)
end
end
def draw(pkg_name = @package_name, uniq_packages = [], self_predicate = '', child_predicate = '')
raise Rdm::Errors::InvalidParams, "Type package name, ex: rdm gen.deps repository" if pkg_name.to_s.empty?
raise Rdm::Errors::PackageHasNoDependencies, @package_name if source.packages[@package_name].local_dependencies.empty?
node = [format(pkg_name, self_predicate)]
return node if pkg_name == ALREADY_MENTIONED_DEPS
local_dependencies = source.packages[pkg_name].local_dependencies.dup
if uniq_packages.include?(pkg_name)
local_dependencies = local_dependencies.count == 0 ? [] : [ALREADY_MENTIONED_DEPS]
else
uniq_packages.push(pkg_name)
end
local_dependencies.count.times do
dependency = local_dependencies.pop
if local_dependencies.empty?
tmp_self_predicate = child_predicate + '2'
tmp_child_predicate = child_predicate + '0'
else
tmp_self_predicate = child_predicate + '1'
tmp_child_predicate = child_predicate + '3'
end
node.push(*draw(dependency, uniq_packages, tmp_self_predicate, tmp_child_predicate))
end
node
end
private
def source
@source ||= Rdm::SourceParser.read_and_init_source(Rdm::SourceLocator.locate(@project_path))
end
def format(pkg_name, predicate)
predicate
.concat(pkg_name)
.gsub(/0/, ' ')
.gsub(/1/, '├── ')
.gsub(/2/, '└── ')
.gsub(/3/, '| ')
end
def recursive_find_dependencies(package_names)
all_packages = source.packages.values
deps_package_names = all_packages
.select {|pkg| package_names.include?(pkg.name)}
.map(&:local_dependencies)
.flatten
.uniq
extended_package_names = deps_package_names | package_names
return package_names if package_names == extended_package_names
recursive_find_dependencies(extended_package_names)
end
end
end
end
|
Java
|
UTF-8
| 1,562
| 2.265625
| 2
|
[] |
no_license
|
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package imac.dp.dao;
import imac.dp.model.Parcela;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* @author @andre_ments
*/
public class ParcelaDao {
//LISTA TODOS AS PARCELAS CADASTRADOS NO BANCO
public List<Parcela> readParcela() throws ClassNotFoundException {
java.sql.Connection con = ConnectionFactory.getConnection();
PreparedStatement stmt = null;
ResultSet rs = null;
List<Parcela> Parcela = new ArrayList<>();
try {
stmt = con.prepareStatement("SELECT codParcela, DATEDIFF(NOW(), dataVencParcela) as diasVencPar FROM tbparcela WHERE statusParcela = 1");
rs = stmt.executeQuery();
while (rs.next()) {
Parcela par = new Parcela();
par.setCodParcela(rs.getInt("codParcela"));
par.setDiasAtrasoPar(rs.getInt("diasVencPar"));
Parcela.add(par);
}
} catch (SQLException ex) {
Logger.getLogger(ParcelaDao.class.getName()).log(Level.SEVERE, null, ex);
} finally {
ConnectionFactory.closeConnection(con, stmt, rs);
}
return Parcela;
}
}
|
C#
|
UTF-8
| 2,704
| 2.875
| 3
|
[
"MIT"
] |
permissive
|
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace TouhouStock
{
public partial class BuySellForm : Form
{
public GameData gameData;
public DataGridView dataGridView1;
public int buyOrSell = 1;
public int stockIndex = 0;
public BuySellForm()
{
InitializeComponent();
}
private void trackBar1_Scroll(object sender, EventArgs e)
{
numOfBuySellLabel.Text = numOfBuySellTrackBar.Value + "";
}
internal void setPrice(double currentPrice)
{
priceLabel.Text = currentPrice + "";
}
public void SetBuyChecked()
{
radioButton1.Checked = true;
radioButton2.Checked = false;
}
public void SetSellChecked()
{
radioButton2.Checked = true;
radioButton1.Checked = false;
}
private void cancelButton_Click(object sender, EventArgs e)
{
this.Hide();
}
private void okButton_Click(object sender, EventArgs e)
{
//Console.WriteLine("index=" + index);
int value = numOfBuySellTrackBar.Value;
//double price = GameData.companyArray[index].ClosingPrice;
double price = Double.Parse(priceLabel.Text);
if (radioButton1.Checked)
{
//Console.WriteLine(price * (1 + GameData.TransactionFees));
//錢夠才能買
if (GameData.money >= price * (1 + GameData.TransactionFees))
gameData.buyStock(stockIndex, value, price);
else
MessageBox.Show("錢不夠");
}
else
{
//有這張股票並且張數夠才可以賣
if (GameData.holdStockMap.ContainsKey(stockIndex))
{
HoldStock holdStock = (HoldStock)GameData.holdStockMap[stockIndex];
if (holdStock.numOfHold >= value)
gameData.sellStock(stockIndex, value, price);
else
MessageBox.Show("張數不夠");
}
}
Hide();
}
private void radioButton1_VisibleChanged(object sender, EventArgs e)
{
if (buyOrSell == 1)
SetBuyChecked();
else
SetSellChecked();
}
}
}
|
Markdown
|
UTF-8
| 8,792
| 2.703125
| 3
|
[] |
no_license
|
<center><h1>Axel 快速下载</h1></center>
## 1. 介绍
[Axel](https://axel.alioth.debian.org/) 是一个轻量级下载程序,它和其他加速器一样,对同一个文件建立多个连接,每个连接下载单独的文件片段以更快地完成下载。
Axel 支持 HTTP、HTTPS、FTP 和 FTPS 协议。它也可以使用多个镜像站点下载单个文件,所以,Axel 可以加速下载高达 40%(大约,我个人认为)。它非常轻量级,因为它没有依赖并且使用非常少的 CPU 和内存。
Axel 一步到位地将所有数据直接下载到目标文件(LCTT 译注:而不是像其它的下载软件那样下载成多个文件块,然后拼接)。
注意:不支持在单条命令中下载两个文件。
你还可以尝试其他命令行下载管理器/加速器。
- [aria2 - 超快速下载程序](http://www.2daygeek.com/aria2-command-line-download-utility-tool/)
- [wget - 标准命令行下载程序](http://www.2daygeek.com/wget-command-line-download-utility-tool/)
- [curl - 命令行下载程序](http://www.2daygeek.com/aria2-command-line-download-utility-tool/)
- [Linux 下的最好的 4 个命令行下载管理器/加速器](https://linux.cn/article-8124-1.html)
大多数发行版(Debian、Ubuntu、Mint、Fedora、suse、openSUSE、Arch Linux、Manjaro、Mageia 等)都有 axel 包,所以我们可以从发行版官方仓库轻松安装。对于 CentOS/RHEL,我们需要启用 [EPEL Repository](https://linux.cn/article-2324-1.html)。
### 1.1 Debian/Ubuntu/LinuxMint 上安装 Axel
```linux
sudo apt-get install axel
```
### 1.2 RHEL/CentOS 上安装 Axel
```
sudo yum install axel
```
### 1.3 Fedora 上安装 Axel
```
dnf install axel
```
### 1.4 openSUSE 上安装 Axel
```
sudo zypper install axel
```
## 2. 下载单个文件
以下命令将从给定的 URL 下载文件并存储在当前目录中,下载文件时,我们可以看到文件的信息(建立的连接数、下载速度、下载进度、完成下载所花费的时间以及连接完成的时间)。
```
root@leco:/tmp/cmz# axel https://download.owncloud.org/community/owncloud-9.0.0.tar.bz2
初始化下载: https://download.owncloud.org/community/owncloud-9.0.0.tar.bz2
文件大小: 22678208 字节
打开输出文件 owncloud-9.0.0.tar.bz2
开始下载
[ 0%] .......... .......... .......... .......... .......... [ 8.6KB/s]
[ 0%] .......... .......... .......... .......... .......... [ 8.6KB/s]
[ 0%] .......... .......... .......... .......... .......... [ 8.1KB/s]
[ 0%] .......... .......... .......... .......... .......... [ 8.7KB/s]
[ 0%] .......... .......... .......... .......... .......... [ 9.8KB/s]
[ 1%] .......... .......... .......... .......... .......... [ 10.5KB/s]
[ 1%] .......... .......... .......... .......... .......... [ 11.1KB/s]
[ 1%] .......... .......... .......... .......... .......... [ 10.6KB/s]
[ 1%] .......... .......... .......... .......... .......... [ 8.4KB/s]
[ 2%] .......... .....
连接超时 0
,,,,,,,,,, ,,,,,..... .......... .......... .......... [ 8.8KB/s]
[ 2%] .......... .......... .......... .......... .......... [ 9.5KB/s]
[ 2%] .......... .......... .......... .......... .......... [ 10.3KB/s]
[ 2%] .......... .......... .......... .......... .......... [ 11.0KB/s]
[ 2%] .......... .......... .......... .......... .......... [ 11.6KB/s]
[ 3%] .......... .......... .......... .......... .......... [ 12.2KB/s]
[ 3%] .......... .......... .......... .......... .......... [ 12.7KB/s]
[ 3%] .......... .......... .......... .......... .......... [ 12.8KB/s]
[ 3%] .......... .......... .......... .......... .......... [ 12.6KB/s]
[ 4%] .......... .......... .......... .......... .......... [ 12.5KB/s]
[ 4%] .......... .......... .......... .......... .......... [ 12.6KB/s]
[ 4%] .......... .......... .......... .......... .......... [ 12.7KB/s]
```
## 3. 用不同的名称保存文件
```
root@leco:/tmp/cmz# axel -o cloud.tar.bz2 https://download.owncloud.org/community/owncloud-9.0.0.tar.bz2
初始化下载: https://download.owncloud.org/community/owncloud-9.0.0.tar.bz2
文件大小: 22678208 字节
打开输出文件 cloud.tar.bz2
开始下载
[ 0%] .......... .......... .......... .......... .......... [ 2.9KB/s]
[ 0%] .......... .......... .......^C
77.7 千字节 已下载,用时 19 秒。(3.96 千字节/秒)
root@leco:/tmp/cmz# ls owncloud-9.0.0.tar.bz2
owncloud-9.0.0.tar.bz2
```
## 4. 限制下载速度
默认情况下 axel 以字节/秒为单位设置下载文件的最大速度。当我们的网络连接速度较慢时,可以使用此选项。只需添加 `-s` 选项,后面跟字节值。这里我们要限速 `512 KB/s` 下载一个文件。
```
root@leco:/tmp/cmz# axel -s 512000 https://download.owncloud.org/community/owncloud-9.0.0.tar.bz2
初始化下载: https://download.owncloud.org/community/owncloud-9.0.0.tar.bz2
文件大小: 22678208 字节
打开输出文件 owncloud-9.0.0.tar.bz2
找到状态文件: 2151071 字节已下载,继续下载 20527137 字节。
开始下载
,,,,,,,,,, ,,,,,,,,,, ,,,,,,,,,, ,,,,,,,,,, ,,,,,,,,,, [ 3.3KB/s]
[ 9%] .......... .......... ...
```
## 5. 限制连接数
axel 默认建立 4 个连接以从不同的镜像获取文件。此外,我们可以通过使用 `-n` 选项添加更多的连接,后跟连接数 `10` 来提高下载速度。保险起见,我们添加了十个连接,但不幸的是,它花了更多时间来下载文件。
```
root@leco:/tmp/cmz# axel -n 10 https://download.owncloud.org/community/owncloud-9.0.0.tar.bz2
初始化下载: https://download.owncloud.org/community/owncloud-9.0.0.tar.bz2
文件大小: 22678208 字节
打开输出文件 owncloud-9.0.0.tar.bz2
找到状态文件: 2217319 字节已下载,继续下载 20460889 字节。
开始下载
,,,,,,,,,, ,,,,,..... .......... .......... .......... [ 28.7KB/s]
[ 9%] .......... .......... .......... .......... .......... [ 40.2KB/s]
[ 10%] .......... .......... .......... .......... .......... [ 38.9KB/s]
[ 10%] ........
```
## 6. 恢复未完成的下载
axel 默认具有恢复未完成的下载的行为。Axel 在下载文件时定期更新状态文件(扩展名为 `.st`)。由于某些原因,下载中途停止了?不用担心,只要使用相同的 axel 命令,它将会检查 `file` 和 `file.st`,如果找到,它会从停止处恢复下载。
```
root@leco:/tmp/cmz# ll
总用量 2496
drwxr-xr-x 2 root root 4096 3月 25 14:36 ./
drwxrwxrwt 31 root root 12288 3月 25 14:41 ../
-rw-r--r-- 1 root root 17028450 3月 25 14:36 cloud.tar.bz2
-rw-r--r-- 1 root root 44 3月 25 14:36 cloud.tar.bz2.st
-rw-r--r-- 1 root root 17651050 3月 25 14:41 owncloud-9.0.0.tar.bz2
-rw-r--r-- 1 root root 44 3月 25 14:41 owncloud-9.0.0.tar.bz2.st
root@leco:/tmp/cmz# axel -n 10 https://download.owncloud.org/community/owncloud-9.0.0.tar.bz2
初始化下载: https://download.owncloud.org/community/owncloud-9.0.0.tar.bz2
文件大小: 22678208 字节
打开输出文件 owncloud-9.0.0.tar.bz2
找到状态文件: 2424295 字节已下载,继续下载 20253913 字节。
开始下载
,,,,,,,,,, ,,,,,,,... .......... .......... .......... [ 42.8KB/s]
[ 10%] .......... .......... .......... .......... .......... [ 45.9KB/s]
[ 11%] .......... .......... .......... .......... .......... [ 64.8KB/s]
[ 11%] .......... .......... .......... .......... .......... [ 82.4KB/s]
[ 11%] .......... ..^C
195.1 千字节 已下载,用时 2 秒。(77.54 千字节/秒)
```
上面的输出清晰地显示了在下载断开时有两个文件 `owncloud-9.0.0.tar.bz2` 和 `owncloud-9.0.0.tar.bz2.st`。当重新开始下载时,它会从停止处开始下载。
## 7. 不显示文件下载进度
如果你不想要看到文件的下载进度,只要在 axel 命令中加入 `-q` 选项。
```
root@leco:/tmp/cmz# axel -q https://download.owncloud.org/community/owncloud-9.0.0.tar.bz2
```
## 8. 替换进度条
如果你不喜欢默认的进度条,你可以使用 `-a` 选项来替换进度条。
```
root@leco:/tmp/cmz# axel -q https://download.owncloud.org/community/owncloud-9.0.0.tar.bz2
^Croot@leco:/tmp/cmz# axel -a https://download.owncloud.org/community/owncloud-9.0.0.tar.bz2
初始化下载: https://download.owncloud.org/community/owncloud-9.0.0.tar.bz2
文件大小: 22678208 字节
打开输出文件 owncloud-9.0.0.tar.bz2
找到状态文件: 3204427 字节已下载,继续下载 19473781 字节。
开始下载
[ 14%] [.0 .1 .2 .3 ] [ 16.2KB/s] [19:33]
```
|
TypeScript
|
UTF-8
| 2,376
| 2.578125
| 3
|
[
"MIT"
] |
permissive
|
// tslint:disable:no-var-requires no-implicit-dependencies
const test = require("tape");
import { Test } from "tape";
import { getProduct, getVendor } from "./usbinfo";
test("Test Get Product - existing vendor and device - 1", async (t: Test) => {
// tslint:disable-next-line:no-debugger
const expected = {
product: "Counterfeit flash drive [Kingston]",
productId: "7778",
vendor: "Fry's Electronics",
vendorId: "0001",
};
const device = await getProduct("0001", "7778").catch((err) => t.fail(err));
t.deepEqual(device, expected);
t.end();
});
test("Test Get Product - existing vendor and device - 2", async (t: Test) => {
const expected = {
product: "LUFA CDC Demo Application",
productId: "2044",
vendor: "Atmel Corp.",
vendorId: "03eb",
};
const device = await getProduct("03eb", "2044").catch((err) => t.fail(err));
t.deepEqual(device, expected);
t.end();
});
test("Test Get Product - existing vendor and device - no padded id", async (t: Test) => {
const expected = {
product: "Counterfeit flash drive [Kingston]",
productId: "7778",
vendor: "Fry's Electronics",
vendorId: "0001",
};
const device = await getProduct("1", "7778").catch((err) => t.fail(err));
t.deepEqual(device, expected);
t.end();
});
test("Test Get Product - NOT existing vendor and device", async (t: Test) => {
const device = await getProduct("lolo", "haha").catch((err) => t.pass());
if (device) {
return t.end("Fake device was found");
} else {
t.end();
}
});
test("Test Get Product - existing vendor but not device", async (t: Test) => {
const expected = {
product: undefined,
productId: "yyyy",
vendor: "Fry's Electronics",
vendorId: "0001",
};
const device = await getProduct("0001", "yyyy").catch((err) => t.fail(err));
t.deepEqual(device, expected);
t.end();
});
test("Test Get Vendor - existing vendor with no devices", async (t: Test) => {
const expected = {
vendor: "Iwatsu America, Inc.",
vendorId: "03ec",
};
const vendor = await getVendor("3ec").catch((err) => t.fail(err));
t.deepEqual(vendor, expected);
t.end();
});
test("Test Get Vendor - NON existing vendor", async (t: Test) => {
const device = await getVendor("xxxxx").catch((err) => t.pass());
if (device) {
t.fail("Fake vendor found");
} else {
t.end();
}
});
|
Java
|
UTF-8
| 472
| 2.078125
| 2
|
[] |
no_license
|
package com.example.lysuytry.itemprice;
import android.content.Context;
import com.readystatesoftware.sqliteasset.SQLiteAssetHelper;
/**
* Created by Ly Suytry on 8/5/2016.
*/
public class MyAssetsDatabase extends SQLiteAssetHelper{
private static final String DATABASE_NAME = "ItemDatabase.db";
private static final int DATABASE_VERSION = 1;
public MyAssetsDatabase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
}
|
JavaScript
|
UTF-8
| 3,342
| 3.765625
| 4
|
[] |
no_license
|
// window.alert("1"); // window опускается тк глобальная функция
// window.prompt("как тебя зовут?");
// window.confirm("как тебя зовут?");
// const heading = document.getElementById("hello"); //возрощает ссылку на элемент
// console.log(heading);
// console.dir(heading); //раскрывает*
// console.dir(heading.id); //получаем свойство id
// console.dir(heading.textContent); // получаем контент
// heading.textContent = "Changed from JavaScript!";
// heading.style.color = "red";
// heading.style.textAlign = "center";
// heading.style.backgroundColor = "green";
// heading.style.padding = "2rem";
// setTimeout(() => {
// heading.textContent = "Changed from JavaScript!";
// heading.style.color = "red";
// heading.style.textAlign = "center";
// heading.style.backgroundColor = "green";
// heading.style.padding = "2rem";
// }, 1000);
// const heading = document.getElementById("hello");
// const heading2 = document.getElementsByTagName("h2")[0];
// const heading2 = document.getElementsByClassName("h2-class")[0]; //получаем по классу, получаем псевдо массив, [0] получаем первый элемент массива, метод устаревший
// const heading2 = document.querySelector(".h2-class"); // через class, querySelector() всегда возращает один элемент
// const heading2 = document.querySelector("#sub-hello"); // через id
// const heading3 = heading2.nextElementSibling; // получаем следующий элемент
// console.log(heading2);
// console.log(heading3);
const h2List = document.querySelectorAll("h2"); //принемает множество значений, получаем псевдомассив
console.log(h2List);
const heading2 = h2List[0];
const heading3 = h2List[1]; //или
const heading4 = h2List[h2List.length - 1];
console.log(heading3);
console.log(heading4);
const heading = document.getElementById("hello");
setTimeout(() => {
addStylesTo(heading, (text = "JavaScript"));
}, 1000);
setTimeout(() => {
addStylesTo(heading2, (text = "Тренеруйся"), (color = "yellow")), "0";
}, 1500);
setTimeout(() => {
addStylesTo(heading3, (text = "И все получится"), (color = "blue"), "3rem");
}, 2000);
function addStylesTo(node, text, color = "red", fontSize) {
node.textContent = text;
node.style.color = color;
node.style.textAlign = "center";
node.style.backgroundColor = "green";
node.style.padding = "2rem";
// falsy: '', undefined, null, 0, false
if (fontSize) {
node.style.fontSize = fontSize;
}
}
heading.onclick = () => {
// Меняем цвет background и color по клику
console.log("click");
if (heading.style.color === "red") {
heading.style.color = "#000";
heading.style.backgroundColor = "#fff";
} else {
heading.style.color = "red";
heading.style.backgroundColor = "green";
}
};
heading2.addEventListener("dblclick", () => {
console.log("click");
if (heading2.style.color === "yellow") {
heading2.style.color = "#000";
heading2.style.backgroundColor = "#fff";
} else {
heading2.style.color = "yellow";
heading2.style.backgroundColor = "green";
}
});
|
Shell
|
UTF-8
| 1,369
| 3.703125
| 4
|
[] |
no_license
|
#!/usr/bin/env bash
sketchget() {
curl --create-dirs -f -k -L -o ${2} -S -s https://sketchmaster2001.github.io/RC24_Patcher/${1}
}
title() {
clear
printf "Wiimmfi WiiWare Patcher\tBy: Noah Pistilli\n" | fold -s -w "$(tput cols)"
printf -- "=%.0s" $(seq "$(tput cols)") && printf "\n\n"
}
case $(uname -m),$(uname) in
x86_64,Darwin)
sys="(macOS)"
;;
x86_64,*)
sys="(linux-x64)"
;;
*,*)
sys="(linux-arm)"
;;
esac
title
sketchget "Wiimmfi-stuff/lzx${sys}" "lzx"
chmod +x lzx
sketchget "Wiimmfi-stuff/wiiwarepatcher${sys}" "wiiwarepatcher"
chmod +x wiiwarepatcher
if [ ! -f *.wad ]
then
printf "There are no wads to patch. Put some in the same directory as the script.\n\n"
read -n 1 -r -p "Press any key to exit: "
exit
fi
mkdir -p "wiimmfi-images"
mkdir -p "backup-wads"
for f in *.wad
do
echo "Processing $f..."
echo "Making backup..."
cp "$f" "backup-wads"
echo "Patching... This might take a second."
./sharpii WAD -u "$f" "temp"
mv temp/00000001.app 00000001.app
./wiiwarepatcher
mv 00000001.app temp/00000001.app
rm "$f"
./sharpii WAD -p "temp" "./wiimmfi-images/${f}-Wiimmfi"
rm -rf "temp"
title
printf "Patching has completed! You will find the patched game in the folder \"wiimmfi-images\".\n\n" | fold -s -w "$(tput cols)"
read -n 1 -r -p "Press any key to return to the patcher: "
done
|
JavaScript
|
UTF-8
| 1,610
| 2.515625
| 3
|
[] |
no_license
|
$(function(){
$("#new_item").validate({
rules: {
"item[name]":{
required: true,
},
"item[description]":{
required: true,
},
"item[category_id]":{
required: true,
},
"item[state]":{
required: true,
},
"item[delivery]":{
required: true,
},
"item[shipping_method]":{
required: true,
},
"item[region]":{
required: true,
},
"item[shipping_time]":{
required: true,
},
"item[price]":{
required: true,
},
},
messages: {
"item[name]":{
required: "入力してください",
},
"item[description]":{
required: "選択してください",
},
"item[category_id]":{
required: "選択してください",
},
"item[state]":{
required: "選択してください",
},
"item[delivery]":{
required: "選択してください",
},
"item[shipping_method]":{
required: "選択してください",
},
"item[region]":{
required: "選択してください",
},
"item[shipping_time]":{
required: "選択してください",
},
"item[price]":{
required: "300以上9999999以下で入力してください",
},
},
errorPlacement: function(error, element) {
switch(element.attr('name')) {
case "item[price]":
error.insertAfter($('#price'));
break;
default:
error.insertAfter(element);
}
}
});
});
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.