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
|
---|---|---|---|---|---|---|---|
TypeScript
|
UTF-8
| 3,897 | 2.515625 | 3 |
[] |
no_license
|
import { BattleConst } from "../battle/BattleConst";
import Game from "./Game";
import Tile from "./Tile";
import GameStyle from "./GameStyle";
const {ccclass, property} = cc._decorator;
@ccclass
export default class Card extends cc.Component{
@property(cc.Node)
private board: cc.Node = null;
@property(cc.Node)
private cardNode: cc.Node = null;
@property(cc.Node)
private lockNode: cc.Node = null;
@property(cc.Node)
private touchNode: cc.Node = null;
@property(cc.Prefab)
private TilePre: cc.Prefab = null;
@property
private scale: number = 0.8;
private style: number = 0;
private game: Game = null;
private tileArray: cc.Node[] = [];
private color: cc.Color;
private lastEventPos: cc.Vec2 = null;
private gameStyle:GameStyle = null;
private bLock = false;
init(game: Game, gameStyle:GameStyle) {
this.game = game;
this.gameStyle = gameStyle;
for (let i = 0; i < BattleConst.StyleBlockMax; i++) {
this.tileArray[i] = cc.instantiate(this.TilePre);
let tile = this.tileArray[i].getComponent(Tile);
tile.init(gameStyle, cc.v2(), this.game.tileScale);
}
this.updateScale(this.scale);
this.addEvent();
}
changeStyle(style:number) {
this.style = style;
this.color = this.gameStyle.randColor();
this.board.removeAllChildren();
let list = BattleConst.getBlocks(this.style);
for (let index = 0; index < list.length; ++index) {
let tile = this.tileArray[index].getComponent(Tile);
tile.changePos(list[index]);
tile.on(this.color);
this.board.addChild(this.tileArray[index]);
}
}
updateLock(bLock) {
this.bLock = bLock;
this.lockNode.active = bLock;
}
isLock() {
return this.bLock;
}
getStyle(): number {
return this.style;
}
getColor(): cc.Color {
return this.color;
}
onDestroy() {
this.removeEvent();
}
//-----------------------------------------------------------------------------
private addEvent() {
this.touchNode.on(cc.Node.EventType.TOUCH_START, this.onTouchBegin, this);
this.touchNode.on(cc.Node.EventType.TOUCH_MOVE, this.onTouchMove, this);
this.touchNode.on(cc.Node.EventType.TOUCH_END, this.onTouchEnd, this);
}
private removeEvent() {
this.touchNode.off(cc.Node.EventType.TOUCH_START, this.onTouchBegin);
this.touchNode.off(cc.Node.EventType.TOUCH_MOVE, this.onTouchMove);
this.touchNode.off(cc.Node.EventType.TOUCH_END, this.onTouchEnd);
}
private onTouchBegin(event: cc.Event.EventTouch) {
this.updateScale(0.9);
this.lastEventPos = event.getLocation();
}
private onTouchMove(event: cc.Event.EventTouch) {
this.cardNode.setPosition(this.cardNode.position.x + event.getLocation().x - this.lastEventPos.x, this.cardNode.position.y + event.getLocation().y - this.lastEventPos.y);
this.lastEventPos = event.getLocation();
this.game.preShow(this.board.convertToWorldSpace(cc.v2(0,0)), this.getStyle(), this.getColor());
}
private onTouchEnd(event: cc.Event.EventTouch) {
this.game.preShowClear();
let addOk = this.game.verifySet(this.board.convertToWorldSpace(cc.v2(0,0)), this.getStyle(), this.getColor());
this.cardNode.setPosition(0,0);
this.updateScale(this.scale);
if (addOk) {
this.refreshStyle();
}
}
private refreshStyle() {
this.game.resetCard(this);
this.game.verifyGameOver();
}
//-----------------------------------------------------------------------------
updateScale(scale) {
this.board.scaleX = scale;
this.board.scaleY = scale;
}
}
|
Java
|
UTF-8
| 2,033 | 2.453125 | 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 org.itsoftsolutions.controller.Services;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressBar;
import javafx.scene.layout.VBox;
import javax.mail.Folder;
import javax.mail.Message;
import org.itsoftsolutions.model.folder.EmailFolderBean;
/**
*
* @author Inzimam
*/
public class FetchMessagesService extends Service<Void> {
private EmailFolderBean<String> mailFolder;
private Folder folder;
private VBox progPanel;
private Label downProgLbl;
private ProgressBar pb;
public FetchMessagesService(EmailFolderBean<String> mailFolder, Folder folder
, VBox progPanel, Label downProgLbl, ProgressBar pb) {
this.mailFolder = mailFolder;
this.folder = folder;
this.progPanel = progPanel;
this.pb = pb;
this.downProgLbl = downProgLbl;
this.setOnRunning(e -> {
downProgLbl.setText("Loading Emails Data");
showProgressBar(true);
});
this.setOnSucceeded(e -> {
showProgressBar(false);
});
}
@Override
protected Task<Void> createTask() {
return new Task<Void>() {
@Override
protected Void call() throws Exception {
if (folder.getType() != Folder.HOLDS_FOLDERS) {
folder.open(Folder.READ_WRITE);
}
int folderSize = folder.getMessageCount();
for (int i = folderSize; i > 0; i--) {
Message currentMsg = folder.getMessage(i);
mailFolder.addEmail(-1, currentMsg);
}
return null;
}
};
}
private void showProgressBar(boolean show) {
progPanel.setVisible(show);
}
}
|
Java
|
UTF-8
| 2,220 | 3.890625 | 4 |
[] |
no_license
|
import java.util.Arrays;
public class ArraySort {
public static void main(String[] args){
int[] array = { 14, 9, 28, 3, 7, 63, 89, 5};
sort(array);
System.out.print(Arrays.toString(array));
}
public static void sort(
int[] Array) {
//This calls the quicksort method to sort the given array list
quickSort(Array, 0, Array.length-1);
}
private static int median(int Array[], int first, int last){
//the center will hold the position of the median of the three (left, right and middle)
int middle = (first + last) / 2;
// The if statements will postition all the values in order
if (Array[first] > Array[middle]){
swap(Array, first, middle);}
if (Array[first] > Array[last]){
swap(Array, first, last);}
if (Array[middle] > Array[last]){
swap(Array, middle, last);}
return middle;
}
public static void swap(int[] Array, int i, int j) {
//swaps the i and j value
int temp = Array[i];
Array[i] = Array[j];
Array[j] = temp;
}
private static void quickSort(int Array[], int first, int last){
int i = first;
int j = last - 1;
int pivot;
if (first < last){
int middle = median(Array, first, last);
//if there are less than or equal to 3 values, there are just ordered
if ((last - first) >= 3){
//the pivot is set as the median
pivot = Array[middle];
swap(Array, middle, last);
do {
while (Array[i] <= pivot && i < last) i++;
while (Array[j] >= pivot && j > first) j--;
//the values are swapped
if (i < j) swap(Array, i, j);
} while (i < j);
//it set the position of the pivot
swap(Array, i, last);
quickSort(Array, first, i-1);
quickSort(Array, i+1, last);
}
}
}
}
|
Java
|
UTF-8
| 2,773 | 2.53125 | 3 |
[] |
no_license
|
package util;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.util.Properties;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.firefox.FirefoxOptions;
import org.openqa.selenium.ie.InternetExplorerDriver;
import org.openqa.selenium.ie.InternetExplorerOptions;
import org.openqa.selenium.remote.CapabilityType;
import org.openqa.selenium.remote.DesiredCapabilities;
import org.openqa.selenium.remote.RemoteWebDriver;
public class DriverUtils {
private static Properties props;
private static final String DRIVER_PROP_FILE = "src/main/resources/driver.properties";
public static WebDriver getDriver(WebDriver driver, String browser, String baseUrl) throws IOException,
FileNotFoundException, Exception {
props = new Properties();
props.load(new FileInputStream(DRIVER_PROP_FILE));
if (isWindows()) {
if (browser.equalsIgnoreCase("firefox")) {
FirefoxOptions options = new FirefoxOptions();
options.setCapability(CapabilityType.BROWSER_VERSION, 48);
System.setProperty("webdriver.gecko.driver", props.getProperty(Constants.FIREFOX_DRIVER_WIN));
driver = new FirefoxDriver();
}
if (browser.equalsIgnoreCase("chrome")) {
System.setProperty("webdriver.chrome.driver", props.getProperty(Constants.CHROME_DRIVER_WIN));
driver = new ChromeDriver();
}
if (browser.equalsIgnoreCase("iexplore")) {
InternetExplorerOptions options = new InternetExplorerOptions();
options.introduceFlakinessByIgnoringSecurityDomains();
options.ignoreZoomSettings();
System.setProperty("webdriver.ie.driver", props.getProperty(Constants.IE_DRIVER_WIN));
driver = new InternetExplorerDriver(options);
}
}else if (isMac()){
if (browser.equalsIgnoreCase("firefox")) {
FirefoxOptions options = new FirefoxOptions();
options.setCapability(CapabilityType.BROWSER_VERSION, 48);
System.setProperty("webdriver.gecko.driver", props.getProperty(Constants.FIREFOX_DRIVER_MAC));
driver = new FirefoxDriver();
}
if (browser.equalsIgnoreCase("chrome")) {
System.setProperty("webdriver.chrome.driver", props.getProperty(Constants.CHROME_DRIVER_MAC));
driver = new ChromeDriver();
}
}
driver.get(baseUrl);
//driver.manage().window().maximize();
return driver;
}
private static boolean isWindows() {
String os = System.getProperty("os.name");
return os.startsWith("Windows");
}
private static boolean isMac() {
String os = System.getProperty("os.name");
return os.startsWith("Mac");
}
}
|
C
|
UTF-8
| 2,087 | 3.390625 | 3 |
[
"WTFPL"
] |
permissive
|
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#define PORT 1234 //定义端口号
#define MAXDATASIZE 100 //定义接收缓冲区大小
main()
{
int sockfd;
struct sockaddr_in server;
struct sockaddr_in client;
socklen_t len;
int num;
char buf[MAXDATASIZE];
/*creating UDP socket*/
if ((sockfd = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
{//调用socket函数,产生UDP套接字。如果出错打印错误信息。
perror("Creating socket failed.");
exit(1);
}
bzero(&server, sizeof(server));//初始化server套接字地址结构,并对地址结构中的成员赋值
server.sin_family = AF_INET;
server.sin_port = htons(PORT);
server.sin_addr.s_addr = htonl(INADDR_ANY);
if (bind(sockfd, (struct sockaddr *)&server, sizeof(server)) == -1)
{//将套接字和指定的协议地址绑定
perror("Bind() error.");
exit(1);
}
len = sizeof(client);
while(1)
{
num = recvfrom(sockfd, buf, MAXDATASIZE, 0, (struct sockaddr *)&client, &len);
//接收客户端的信息,并存放在buf中,客户端的地址信息存放在client地址结构中。如果成功num返回接收的字符串的长度。
if (num < 0)
{
perror("recvfrom() error\n");
exit(1);
}
buf[num]='\0';
printf("You got a message <%s> from client.\nIt's ip is %s, port is %d.\n", buf, inet_ntoa(client.sin_addr), htons(client.sin_port));
//显示接收到的客户信息、客户的IP地址和端口号。通过inet_ntoa()函数将IP地址转换成可显示的ASCII串,通过htons()函数将端口号转换成网络字节序
sendto(sockfd, "Welcome\n", 8, 0, (struct sockaddr *)&client, len);//发送Welcome字符串给客户端
if (!strcmp(buf, "bye")) //如果客户端发来的字符串是"bye",则退出循环
{
break;
}
}
close(sockfd);
}
|
Shell
|
WINDOWS-1252
| 921 | 3.359375 | 3 |
[
"Apache-2.0"
] |
permissive
|
#!/bin/sh
#####################################################################
# Project:Easy Web Framework
#
# Description: This project is based on much more open source projects than ever before,
# and can be applied to mostly web development environment.
# Author:ľ 110476592@qq.com
#
#
#
# ===================================================================================================
#
#
#####################################################################
# location of java executable
if [ -f "$JAVA_HOME/bin/java" ]; then
JAVA="$JAVA_HOME/bin/java"
else
JAVA=java
fi
top="$(cd "$(dirname "$0")"; echo "$PWD")"
find_jar() {
set -- "$top"/core/base/lib/ant-launcher-*.jar
if [ $# = 1 ] && [ -e "$1" ]; then
echo "$1"
else
echo "Couldn't find ant-launcher.jar" 1>&2
exit 1
fi
}
"$JAVA" -jar "$(find_jar)" -lib "$top/core/base/lib/ant" "$@"
|
Java
|
UTF-8
| 1,388 | 2.90625 | 3 |
[] |
no_license
|
package aufgabe.Personen;
import aufgabe.Termine.Veranstaltung;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Arrays;
public class Dozent extends Angestellter{
ArrayList<Veranstaltung> veranstaltung = new ArrayList<>();
Mitarbeiter mitarbeiter;
public Dozent(String name, String surname, LocalDate date, String rolle) {
super(name, surname, date, rolle);
}
public Dozent(String name, String surname, LocalDate date, String rolle, Mitarbeiter mitarbeiter) {
super(name, surname, date, rolle);
this.mitarbeiter=mitarbeiter;
}
public void setMitarbeiter(Mitarbeiter mitarbeiter) {
this.mitarbeiter = mitarbeiter;
}
public String[] getNamen(){
return super.getNamen();
}
public Mitarbeiter getMitarbeiter() {
return mitarbeiter;
}
public void fügeVeranstaltungHinzu(Veranstaltung veranstaltung) {
this.veranstaltung.add(veranstaltung);
}
public ArrayList<Veranstaltung> getVeranstaltung() {
return veranstaltung;
}
@Override
public String toString() {
return "Dozent{" +
"veranstaltung=" + veranstaltung +
", mitarbeiter=" + mitarbeiter +
", einstiegsdatum=" + einstiegsdatum +
", namen=" + Arrays.toString(namen) +
'}';
}
}
|
Markdown
|
UTF-8
| 9,064 | 3.765625 | 4 |
[] |
no_license
|
% Complexidade de Algoritmos
% Paulino Ng
% 2020-04-03
## Plano da aula
Esta aula apresenta a análise assintótica de alguns algoritmos simples.
1. Análise do algoritmo de impressão recursiva dos valores de uma lista encadeada.
2. Busca em um vetor aleatório
3. Busca em um vetor ordenado
4. Divisão e conquista: soluções recursivas. Equações de recorrência
5. Teorema Mestre para funções recursivas
## Exercício discursivo ENADE-2017
Listas lineares armazenam uma coleção de elementos. A seguir, é apresentada a declaração de uma lista simplesmente encadeada.
```C
struct ListaEncadeada {
int dado;
struct ListaEncadeada *proximo;
};
```
<!-- -* -->
Para imprimir os seus elementos da cauda para a cabeça \(do final para o início\) de forma eficiente, um algoritmo pode ser escrito da seguinte forma:
```C
void mostrar(struct ListaEncadeada *lista) {
if (lista != NULL) {
mostrar(lista->proximo);
printf("%d ", lista->dado);
}
}
```
##
Com base no algoritmo apresentado, faça o que se pede nos itens a seguir:
a) Apresente a classe de complexidade do algoritmo, usando a notação $\Theta$.
b) Considerando que já existe implementada uma estrutura de dados do tipo pilha de inteiros - com as operações de empilhar, desempilhar e verificar pilha vazia - reescreva o algoritmo de forma não recursiva, mantendo a mesma complexidade. Seu algoritmo pode ser escrito em português estruturado ou em alguma linguagem de programação, como C, Java ou Pascal.
## Solução
a) O algoritmo percorre a lista recursivamente, passando por cada nó uma única vez, logo, o algoritmo é: $\Theta(n)$
b) O "programa" para fazer o que é solicitado, faz um laço onde se desempilha um item, imprime, empilha numa pilha auxiliar. Estas operações são realizadas enquanto a pilha não estiver vazia. Após esvaziar a pilha original, deve-se fazer um novo laço para reempilhar os itens na pilha original.
## Busca linear de um valor num vetor
Seja o código:
```C
int busca(int *vi, int n, int val) {
int i;
for (i = 0; i < n; i++)
if (vi[i] == val) return i;
return -1;
}
```
Se o valor `val` fizer parte do vetor, a função retorna o índice do vetor onde está o valor, se não, a função retorna -1.
> No melhor caso, o valor está na primeira posição: $f(n) = 1$
> No pior caso, o valor está no fim do vetor ou não está no vetor: $f(n) = n$
> No caso médio: $f(n) = \frac{n}{2}$
> Ou seja, a complexidade do algoritmo é $\mathcal{O}(n)$
## Busca de um valor num vetor ordenado \(busca binária\)
```C
int busca2(int *vi, int n, int val) {
int sup = n-1, inf = 0, meio;
while (sup >= inf) {
meio = (sup + inf)/2;
if (vi[meio] == val) return meio;
if (val > vi[meio]) inf = meio + 1;
else sup = meio - 1;
}
return -1;
}
```
A cada passagem no laço, o espaço de busca diminui pela metade. O espaço fica reduzido a 1 elemento em $\log_2n$ iterações. Logo:
> No melhor caso, $f(n) = 1$
> No pior caso, $f(n) = lg\ n$
> O caso médio é próximo do pior caso, $f(n)=lg\ n$. A complexidade é $\mathcal{O}(lg\ n)$.
## Divisão e conquista
Uma técnica comum para a resolução de problemas computacionais é chamada de *divisão e conquista*.
O problema é dividido em problemas menores recursivamente até que sejam tão pequenos que possamos calcular a solução.
Exemplo: cálculo do fatorial recursivo e cálculo do n-ésimo número da sequência de Fibonacci.
Problema do fatorial:
- Entrada: inteiro não negativo $n$
- Saída: $1$ se $n=0$ e $n.(n-1).\ldots .2.1 = n!$ se $n>0$
Observando que: $n! = n.(n-1)!$ para n>0, podemos calcular o fatorial de forma recursiva.
## Cálculo do fatorial
```C
int fatorial(int n) {
if (n == 0) return 1;
return n * fatorial(n-1);
}
```
* O cálculo do fatorial acima usa a recursão. Podemos transformar a recursão num laço com:
```C
int fato(int n) {
int acc = 1, i;
for (i = 2; i <= n; i++) acc *= i;
return acc;
}
```
<!-- =* -->
* A solução não recursiva, em geral, é mais rápida. Apesar de ambas terem a mesma ordem de complexidade, $\Theta(n)$, a recursão custa mais tempo de execução, o que aumenta as constantes no cálculo do tempo.
## Algoritmos recursivos
* Muitos algoritmos úteis são recursivos na própria estrutura, por exemplo nos algoritmos para dados em árvore. Este algoritmos seguem a formulação *dividir-e-conquistar*: quebra-se o problema em subproblemas semelhantes ao problema original com tamanho menor e a composição das soluções resolvem o problema maior. Esta divisão dos problemas é feita recursivamente até se ter problemas básicos cuja solução possa ser facilmente calculada \(sem novas quebras\). A solução do problema original é obtida da composição das soluções básicas.
* O paradigma *dividir-e-conquistar* leva aos seguintes 3 passos:
- **Dividir** o problema em vários (ou um) problemas menores do mesmo tipo;
- **Conquistar** os subproblemas resolvendo-os recursivamente. Se o subproblema for pequeno o suficiente, resolvê-lo diretamente; e
- **Combinar** as soluções dos subproblemas até resolver o problema original.
## Teorema mestre para funções recursivas
Soluções recursivas frequentemente resultam na equação de recorrência a seguir no cálculo da complexidade do algoritmo.
Onde $a\geq 1$ e $b>1$ são constantes e $f(n)$ é uma função assintoticamente positiva, $T(n)$ é uma medida de complexidade definida sobre os inteiros. A solução da equação de recorrência:
$T(n)=aT(\frac{n}{b})+f(n)$,
É:
1. $T(n)= \Theta(n^{\log_ba})$, se $f(n)=\mathcal{O}(n^{\log_ba-\epsilon})$ para alguma constante $\epsilon>0$;
2. $T(n)= \Theta(n^{\log_ba}\,\log n)$, se $f(n)=\Theta(n^{\log_ba})$; e
3. $T(n)= \Theta(f(n))$, se $f(n)=\Omega(n^{\log_ba+\epsilon})$para alguma constante $\epsilon>0$, e se $a\,f(\frac{b}{b})\leq cf(n)$ para alguma constante $c<1$ e todo $n$ a partir de um valor suficientemente grande.
##
- A equação de recorrência diz que o problema foi dividido em $a$ subproblemas de tamanho $\frac{n}{b}$ cada um.
- Os problemas são resolvidos recursivamente em tempo $T(\frac{n}{b})$ cada um.
- A função $f(n)$ descreve o custo de dividir o problema em subproblemas e combinar os resultados de cada subproblema.
## Busca binária recursiva
* Problema:
- Entradas: vetor vi, índice inicial, índice final, valor buscado
- Saída: índice do elemento que casa com o valor buscado, ou -1 se o valor não estiver no vetor.
```C
int busca2_rec(int *vi, int ini, int fim, int val) {
if (ini > fim) return -1;
int meio = (ini + fim)/2;
if (vi[meio] == val) return meio;
if (val > vi[meio]) return busca2_rec(vi, meio + 1, fim, val);
return busca2_rec(vi, ini, meio - 1, val);
}
```
Use o teorema mestre para mostrar que a complexidade da busca binária recursiva é $\Theta(\log n)$.
Sem usar o teorema mestre, refaça a análise.
## Recursividade vs. Iteratividade
* Na recursividade, a função se chama para resolver os problemas menores. Cada chamada de função cria um contexto na memória para calcular a função. Estes contextos só são recolhidos no final do cálculo. A quantidade de contextos cresce com a complexidade do algoritmo, na maioria das vezes. Isto faz com que, em geral, uma implementação recursiva seja mais lenta do que sua implementação iterativa. Além disso, muitas vezes ao transformar um algoritmo recursivo em iterativo, é possível modificá-lo em mudar sua complexidade.
* O caso mais típico é o cálculo do enésimo elemento da sequência de Fibonacci. O algoritmo recursivo:
```C
int fibo_rec(int n) {
if (n < 2) return n;
return fibo_rec(n-1) + fibo_rec(n-2);
}
```
- Curto, elegante e que segue exatamente a definição matemática tem complexidade $\Theta(2^n)$.
## Árvore de chamadas do fibo_rec()

## (cont.)
- É fácil reescrever de maneira iterativa este cálculo com:
```C
int fibo_iter(int n) {
if (n < 2) return n;
int val1 = 1, val2 = 0, val;
for ( ; n > 1; n--) {
val = val1 + val2;
val2 = val1;
val1 = val;
}
return val;
}
```
- Este algoritmo iterativo tem complexidade $\Theta(n)$.
## (cont.)
Para os alunos de programação funcional que possam achar que devido a isto, algoritmos iterativos são sempre melhores. Observe que é possível escrever um `fibo_rec()` com complexidade $\Theta(n)$.
```C
int fibo_aux(int n, int val1, int val2) {
if (n == 0) return 0;
if (n == 1) return val1;
return fibo_aux(n-1, val1+val2, val1);
}
int fibo_rec2(int n) {
return fibo_aux(n, 1, 0);
}
```
> Obs.: A função recursiva fibo_aux() tem a vantagem de ter recursividade terminal. Recursividade terminal ocorre quando a última instrução da função recursiva, a que faz o retorno, só faz a única chamada recursiva. Neste caso o compilador não precisa gerar código para uma chamada de função, ele pode fazer simplesmente um ´GOTO´ para a função. Evita-se deste modo a criação dos contextos da recursão.
|
C++
|
UTF-8
| 1,065 | 3.015625 | 3 |
[] |
no_license
|
#ifndef MATH_CONSTANTS_H
#define MATH_CONSTANTS_H
#include "gltypes.h"
//#include "vec3.h"
namespace gsl
{
// Mathematical constants
constexpr double PI_D = 3.141592653589793238462643383279502884;
constexpr float PI = 3.14159265358979323846264338f;
constexpr float E = 2.71828182845904523536f;
constexpr float GRAVITY = 9.80665f; // Differs depending on where you are on the earth, ~9.81
// Functions
inline GLdouble rad2deg(GLdouble rad)
{return rad * (180.0 / PI_D);}
inline GLdouble deg2rad(GLdouble deg)
{return deg * (PI_D / 180.0);}
inline GLfloat rad2degf(GLfloat rad)
{return rad * (180.0f / PI);}
inline GLfloat deg2radf(GLfloat deg)
{return deg * (PI / 180.0f);}
//World axis constants
//For some reason the FORWARD vector gets converted to Z = 1.f when used....
// static const vec3 UP{0.f, 1.f, 0.f}; //Y-axis
// static const vec3 FORWARD{0.f, 0.f, -1.f}; //- Z-axis
// static const vec3 RIGHT{1.f, 0.f, 0.f}; //X-axis
}
#endif // MATH_CONSTANTS_H
|
PHP
|
UTF-8
| 925 | 2.859375 | 3 |
[] |
no_license
|
<?php
namespace Stgen\Source;
use Stgen\Source\Item\ISourceItem;
class BlacklistSourceDecorator extends \FilterIterator implements ISource
{
/**
* @var array
*/
private $blacklist;
/**
* @var ISource
*/
private $decorated;
/**
* BlacklistSourceDecorator constructor.
* @param ISource $decorated
* @param array $blacklist
*/
public function __construct(ISource $decorated, array $blacklist)
{
parent::__construct($decorated);
$this->blacklist = $blacklist;
$this->decorated = $decorated;
}
/**
* @inheritDoc
*/
public function accept()
{
$accept = !in_array(realpath($this->currentItem()->getFile()), $this->blacklist, true);
return $accept;
}
/**
* @inheritdoc
*/
function currentItem(): ISourceItem
{
return $this->decorated->currentItem();
}
}
|
Markdown
|
UTF-8
| 444 | 3.15625 | 3 |
[] |
no_license
|
# 题目地址
<https://leetcode-cn.com/problems/number-of-good-pairs/>
# 解答
题目很简单,主要是关注 Rust 的用法。
```Rust
impl Solution {
pub fn num_identical_pairs(nums: Vec<i32>) -> i32 {
let mut count = 0;
for i in 1..nums.len() {
for j in 0..i {
if nums[i] == nums[j] {
count = count + 1;
}
}
}
count
}
}
```
|
Java
|
UTF-8
| 1,416 | 3.671875 | 4 |
[] |
no_license
|
//Пользователь вводит размер массива и данные с клавиатуры в массив типа double.
//Посчитайте среднее арифметическое элементов массива.
//После этого произведите вывод массива на экран,
//где каждый элемент массива умножается на среднее арифметическое
import java.text.DecimalFormat;
import java.util.Arrays;
import java.util.Scanner;
public class TaskWork09 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
DecimalFormat decimalFormat = new DecimalFormat("#.###");
double sum = 0;
double average = 0;
System.out.println("Введите размер массива: ");
int lenght = input.nextInt();
double array[] = new double[lenght];
System.out.println("Введите элементы массива: ");
for (int i = 0; i < lenght; i++) {
array[i] = input.nextDouble();
sum+=array[i];
}
average = sum / array.length;
int i=0;
System.out.print("Результат работы программы: ");
do {
System.out.printf(decimalFormat.format(array[i]*=average) + "\t");
} while (++i<array.length);
}
}
|
C++
|
UTF-8
| 5,972 | 3.28125 | 3 |
[] |
no_license
|
/*!
\file
\brief String Array description
\author Yaroslav Pozndyak
File with a description of the class StringArray
*/
#include "StringArray.h"
/*!
\param [in] file pointer to used file
\return size of the file in bites
*/
long long get_file_size(FILE* *file) {
assert(file != NULL);
fpos_t cur_pos;
fgetpos(*file, &cur_pos);
fseek(*file, 0, SEEK_END);
long long size = ftell(*file);
fseek(*file, 0, cur_pos);
return size;
}
/*!
\brief Input
\param [in] path pointer to path to input file
\param [out] buf_size pointer to size of file
\param [out] buf pointer to data
\return sucsess
\note Delete buf and buf_size. Scan file to buf.
*/
bool scan_str_with_delete_and_new(const char* path, size_t *buf_size, char* *buf) {
assert(path != NULL);
assert(buf_size != NULL);
assert(buf != NULL);
FILE* input = fopen(path, "rb");
assert(input != NULL);
int size = get_file_size(&input) + 1;
int length = size / sizeof(char);
*buf_size = 0;
delete *buf;
*buf_size = length;
*buf = new char[length];
int result = fread(*buf, sizeof(char), size, input);
*(*buf + length - 1) = EOF;
if(result != size - 1) {
printf("[ERROR] reading from %s\n", path);
return false;
}
fclose(input);
return true;
}
/*!
\brief Print string
\param [in] str_size size of string
\param [in] str string to printing
\return sucsess
\note print string
*/
bool print_str(int str_size, char *str) {
assert(str != NULL);
for(int i = 0; i < str_size; i ++) {
printf("%c", *(str + i));
}
return true;
}
/*!
\brief Print string to file
\param [in] str_size size of string
\param [in] str string to printing
\param [in] file pointer to file for printing
\return sucsess
\note print string to file
*/
bool fprint_str(M_str str, FILE* *file) {
assert(str.str != NULL);
fprintf(*file, "%s", str.str);
return true;
}
/*!
\brief Standrad constructor
*/
StringArray :: StringArray()
:data(NULL)
,data_size(0)
,strings(NULL)
,n_strings(0)
,is_marked(false)
,is_data_loaded(false){
}
StringArray :: StringArray(StringArray *copy)
:data(NULL)
,data_size(0)
,strings(NULL)
,n_strings(0)
,is_marked(false)
,is_data_loaded(false){
memcopy(copy);
}
bool StringArray :: memcopy(StringArray *copy) {
delete_marking();
delete_data();
assert(copy);
data_size = copy->data_size;
n_strings = copy->n_strings;
is_marked = copy->is_marked;
is_data_loaded = copy->is_data_loaded;
data = new char[data_size];
strings = new M_str[n_strings];
for(int i = 0; i < (int)data_size; i ++) {
*(data + i) = *(copy->data + i);
}
for(int i = 0; i < (int)n_strings; i ++) {
(*(strings + i)).str = ((*(copy->strings + i)).str - copy->data) + data;
(*(strings + i)).len = ( *(copy->strings + i)).len;
}
}
/*!
\brief Standard destructor
*/
StringArray :: ~StringArray() {
delete_marking();
delete_data();
}
/*!
\brief Memory cleaner
\note delete info about strings
*/
bool StringArray :: delete_marking() {
if(!is_marked)
return false;
for(int i = 0; i < n_strings; i ++) {
strings[i].str = NULL;
}
if(strings)
delete[] strings;
strings = NULL;
is_marked = false;
return true;
}
/*!
\brief Memory cleaner
\note delete data
*/
bool StringArray :: delete_data() {
if(!is_data_loaded)
return false;
assert(!is_marked);
if(data)
delete[] data;
data = NULL;
is_data_loaded = false;
return true;
}
/*!
\brief Memory cleaner
*/
bool StringArray :: clean_mem() {
delete_marking();
delete_data();
}
/*!
\brief Scan data
\param [in] path path to file
\return sucsess
*/
bool StringArray :: scan(const char* path) {
assert(path != NULL);
is_data_loaded = scan_str_with_delete_and_new(path, &data_size, &data);
data[data_size - 1] = EOF;
return is_data_loaded;
}
/*!
\brief Print data
\param [in] path path to file
\return sucsess
*/
bool StringArray :: print(const char *path) {
assert(path != NULL);
FILE *output = fopen(path, "wt");
assert(output != NULL);
for(int i = 0; i < n_strings; i ++) {
fprint_str(strings[i], &output);
fprintf(output, "\n");
}
fclose(output);
return true;
}
/*!
\brief Mark data
\return sucsess
\note This function divides data to strings and changing '\n' and EOF to '\0', makes array of pointers to begins of strings and array of size of strings
*/
bool StringArray :: mark_text() {
delete_marking();
n_strings = 1;
for(int i = 0; i < data_size; i ++) {
if(data[i] == '\r' || data[i] == EOF) {
data[i] = '\0';
}
if(data[i] == '\n') {
data[i] = '\0';
}
}
for(int i = 1; i < data_size; i ++) {
if(data[i] == '\0' && !(i + 1 < data_size && data[i + 1] == '\0') || i + 1 == data_size){
n_strings ++;
}
}
strings = new M_str[n_strings];
int str_counter = 1;
int str_length = 1;
strings[0].str = data;
for(int i = 1; i < data_size && str_counter <= n_strings; i ++) {
if(data[i] == '\0' && !(i + 1 < data_size && data[i + 1] == '\0') || i + 1 == data_size) {
strings[str_counter].str = data + i + 1;
strings[str_counter - 1].len = str_length;
str_length = 0;
str_counter ++;
} else {
str_length ++;
}
}
is_marked = true;
return true;
}
|
Markdown
|
UTF-8
| 10,867 | 2.953125 | 3 |
[
"LicenseRef-scancode-unknown-license-reference",
"LicenseRef-scancode-public-domain"
] |
permissive
|
# Predicting NCAAM 2017-2019 First Round Matchups
(technical presentation can be found in index.ipynb file in project_files folder)
## Goal
In this notebook, we construct a classifier to attempt to forecast the outcomes of 2017-2019 NCAAM March Madness first round matchups. Although our goal is overall preditions of the first round, we will keep special attention to predicting the upsets that occur.
#### Define Upsets:
An upset is considered a lower seed beating a higher seed team (i.e. 15 beats 2, 10 beats 7, and even 9 beats 8)
## Data
#### EDA:
<p align="center">
<img src = "project_files/averages.png"/>
</p>
If you are to compare the average points scored by the winning team and the average points scored by the losing team, you can see a 10 point difference in every season. The highest average points scored by the losing team doesn't even reach the lowest average scored by the winning team, showing you that most of these games were not just won but dominated by the winning team.
<p align="center">
<img src = "project_files/upsetsovertime.png"/>
</p>
Since 2003, there has always been 4 or more upsets per year. 2016 had the largest number of upsets, at 13, and 2004 had the lowest at 4. Thre three seasons we are looking to predict, 2017-2019, had an increasing number of upsets with 2019 having the most at 12.
2019 was full of upsets but not that many were suprises if you were to look at the teams closely. Many of the lower seeded teams that won were coming off a hot streak, one of them on a 17-game win streak heading into the tournament. Others had top-talented players who chose to go to smaller schools and showed up big time in the tournament. On the flip-side, some of the higher seeded teams had a lack of completeness to their game and roster, showing holes that could have been taken advantadge of.
#### Raw Data Description:
Each season there are thousands of NCAA basketball games played between Division I men's teams, culminating in March Madness, the 68-team national championship that starts in the middle of March. From Google's Kaggle NCAAM March Madness competition, I have gathered various csv datasets containing a large amount of historical data about college basketball games and individual teams from 1985. I have various datasets containing raw data all follwing different structures, but most consisting of a winnign team, a losing team, and their corresponding information. Some datasets are team specific and some are season specific. Below, you may visualize some of the raw data used in computing the features used in our model:
| Season | DayNum | WTeamID | WScore | LTeamID | LScore | WLoc | NumOT | WFGM | WFGA | ... | LStl | LBlk | LPF |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| 2003 | 10 | 1104 | 68 | 1328 | 62 | N | 0 | 27 | 58 | ... | 9 | 2 | 20 |
| 2003 | 10 | 1272 | 70 | 1393 | 63 | N | 0 | 26 | 62 | ... | 8 | 6 | 16 |
| 2003 | 11 | 1266 | 73 | 1437 | 61 | N | 0 | 24 | 58 | ... | 2 | 5 | 23 |
| EventID | Season | DayNum | WTeamID | LTeamID | WFinalScore | LFinalScore | WCurrentScore | LCurrentScore | ElapsedSeconds | EventTeamID | EventPlayerID | EventType | EventSubType | X | Y | Area |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| 5216688 | 2017 | 11 | 1104 | 1157 | 70 | 53 | 0 | 0 | 0 | 1104 | 6977 | sub | in | 0 | 0 | 0 |
| 5216689 | 2017 | 11 | 1104 | 1157 | 70 | 53 | 0 | 0 | 15 | 1157 | 1899 | foul | unk | 0 | 0 | 0 |
| 5216690 | 2017 | 11 | 1104 | 1157 | 70 | 53 | 0 | 0 | 15 | 1157 | 1899 | turnover | unk | 0 | 0 | 0 |
| Season | TeamID | FirstDayNum | LastDayNum | CoachName |
| --- | --- | --- | --- | --- |
| 1985 | 1102 | 0 | 154 | reggie_minton |
| 1985 | 1103 | 0 | 154 | bob_huggins |
| 1985 | 1104 | 0 | 154 | wimp_sanderson |
| TeamID | TeamName | FirstD1Season | LastD1Season |
| --- | --- | --- | --- |
|1101 | Abilene Chr | 2014 | 2020 |
|1102 | Air Force | 1985 | 2020 |
|1103 | Akron | 1985 | 2020 |
| Season | RankingDayNum | SystemName | TeamID | OrdinalRank |
| --- | --- | --- | --- | --- |
| 2003 | 35 | SEL | 1102 | 159 |
| 2003 | 35 | SEL | 1103 | 229 |
| 2003 | 35 | SEL | 1104 | 12 |
| 2003 | 35 | SEL | 1105 | 314 |
#### Desired Train and Test Dataset Construction:
The desired structure of our target variable going into our model fitting and forecasting is to predict whether the team with the lower Team ID wins the game. Therefore, our features will be labelled by Team1 (lower Team ID) and Team2 (higher Team ID). Each row will specify a specific game and the target will be the end result of that game. Our features will be rolling averages of difference in per game and advanced statistics for each team up to the date of that game. This means, the difference in scoring, field goal percentage in first 5 minutes of game, etc. for each team will be averages of the games played previously. There are also columns corresponding to current season statistics, like difference in how long that program has been in Division I basketball, difference in average ranking by rating systems on that date and more. There are also columns referring to the dates specific importance, like difference in coach tenure up to that game and location of game. Lastly, there are the same per game and advanced statistics total season averages for both teams but for the prior three seasons as well, as college players can play up to four years in NCAA.
The train data will consist of regular season matchups (Days 1-132), and our test data will consist of first round tournament games (Days 136-137) whose games have values for all of the features available.
In this notebook, train and test data is for season 2017-2019.
Below, you can see a rough idea of the structure of our train and test data:
| Team1ScoreDiff | Team2ScoreDiff | ... | Team1ORTG | Team2ORTG | ... | CoachDiff | ... | Team1ScoreDiff-1 | Team2ScoreDiff-1 | ... | Team1H | Team2H | ... | Team1fhf52 | Team2fhf52 | ... | Target |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| 10.823 | 9.424 | ... | 1.007 | 1.040 | ... | 608 | ... | 6.456 | 5.345 | ... | 1 | 0 | ... | 0.416 | 0.200 | ... | 1 |
| 7.903 | 2.548 | ... | 1.101 | 0.975 | ... | 0 | ... | 8.623 | -1.456 | ... | 0 | 1 | ... | 0.750 | 1.000 | ... | 0 |
| 10.187 | 12.333 | ... | 1.044 | 1.024 | ... | -123 | ... | 0.235 | -2.349 | ... | 0 | 0 | ... | 0.500 | 0.333 | ... | 1 |
## Hypertuning Parameters and Modeling
Although inputing train values for future seasons to predict past seasons may influence results (in this case using 2018 and 2019 train data for 2017 test, and 2019 train data for 2018 test), I aim to find model that can be used to predict first round matchups for the NCAA tournament every year, not individual years. So we run our pipeline on our whole train dataset and later use the best classifier we find on seperate years train data.
We first use standardize our data and then we convert our features into a set of values of linearly uncorrelated variables using a Standard Scalar and Principal Component Analysis. I then test for classifiers XGBoost, RandomForest and Logistic Regression using a gridsearch to hypertune a set of parameters to find the best.
Logistic regression leads to simple understanding of our explanatory features and if speed is a factor, Logistic regression is the answer. Random Forest may be a better choice for unbalanced data as it builds each tree independently and combines results at the end of the process through averaging. XGBoost is an additive model that combines results as it trains. Instead of training independently like Random Forest, it trains models in succession and corrects the errors made by the previous models. However, XGBoost is the hardest to tune.
The resulting model is XGBoost, with 74 components and 50 estimators.
## Interpreting Results
Before going into results, know that 65.2% of our upsets had a higher team ID.
When training over combined regular season data, we get an accuracy score of 75.3%, having a true positive rate of 73.2% and true negative rate of 77.3%. Therefore, we were more successful in predicting that the team with the higher team ID wins. In 2017, we predicted 60% of our upsets correctly and 86.2% of our overall matchups. In 2018, we predicted 57.1% of our upsets correctly and 71.4% of our overall matchups. In 2019 however, we only predicted 45.5% of our upsets correctly and 67.9% of our overall matchups.
The 8 most important features (in order) for if the predicting lower ID team wins are:
-- The average 2-point field goal percentage difference for lower ID team
-- The average free throw percentage difference for lower ID team
-- The average score difference for higher ID team
-- The average steal difference for lower ID team
-- If the location is neutral for lower ID team
-- The average net rating of higher ID team
-- The average true shooting of higher ID team
-- The average 2 point field goal percentage of first 5 minutes of the first half for the higher ID team
When training over each season independently, we get an accuracy score of 76.5% for all three years, having a true positive rate of 73.2% and true negative rate of 79.5%. Therefore, we were even more successful in predicting that the team with the higher team ID wins. In 2017, we predicted 60% of our upsets correctly and 86.2% of our overall matchups. In 2018, we predicted 42.9% of our upsets correctly instead but still 71.4% of our overall matchups. In 2019 however, we have now predicted 54.5% of our upsets correctly and also 71.4% of our overall matchups.
There are various factors that influence a basketball game, not only in the statistics but also external factors like elevation of performance and momentum heading into a game. How to value importance of those factors for each game is another issues as one variable may be more important than another depending on the opponent and day. It is important to note that we were successful in predicting just over 76% of first round matchups using solely regular season results. With more in depth understanding of feature engineering for this topic, feature importance and gathering of data outside of regular season, we may construct a more accurate model.
## Future Work
- Include individual player significance (injuries, player talent)
- Include secondary tournament results
- Include past tournament results
- A better understanding of incorrectly predicted matches
- Find better parameters for classifiers (test for better model parameters in gridsearch)
- Arrange target to show upset winning rather than lower Team ID (this should force the coefficents to value upsets in predictions)
- Make functions more efficient (slow down runtime for computing features)
|
Java
|
UTF-8
| 701 | 2.640625 | 3 |
[
"Apache-2.0"
] |
permissive
|
package deskplaner.commands;
import java.io.File;
import deskplaner.handler.CommandHandler;
import deskplaner.main.DeskPlaner;
import deskplaner.util.Command;
public class VersionCommand implements Command {
@Override
public boolean onCommand(String label, String args[], File directory) {
String string = DeskPlaner.getName() + " " + DeskPlaner.getVersion() + "\n";
string += "By " + DeskPlaner.getAuthorsAsString() + "\n";
string += "Running DeskPlaner on " + System.getProperty("os.name");
CommandHandler.sendConsoleOutput(string);
return true;
}
@Override
public String getCommandHelp() {
return "Display the current version of the DeskPlaner.";
}
}
|
PHP
|
UTF-8
| 4,137 | 3.140625 | 3 |
[] |
no_license
|
<?php
/**
* Manage queries for a mysql db
*
*/
class database {
private $_host = "localhost";
private $_user = "LinkBiz";
private $_pass = "fzg60n82hc";
private $_base = "proj_LinkBiz_7isoybau";
private $_cursor = null;
private $_ressource = null;
private $_errorNum = 0;
private $_errorMsg = '';
/**
* Shared instance
*/
private static $_instance;
/**
* Constructor
*
* <p>Create the static instance of the singleton</p>
*
* @name database::__construct()
* @return void
*/
private function __construct () {
$this->_ressource = mysql_connect($this->_host, $this->_user, $this->_pass);
mysql_select_db( $this->_base );
//set utf-8
$this->query("SET CHARACTER SET utf8;");
$this->query("SET NAMES utf8;");
}
/**
* Clone
*
* <p>Avoid extern copy of instance</p>
*
* @return void
*/
private function __clone () {}
/**
* getInstance
*
* <p>Get the shared db instance</p>
*
* @return database instance
*/
public static function getInstance () {
if (!(self::$_instance instanceof self))
self::$_instance = new self();
return self::$_instance;
}
/**
* getObject
*
* <p>Get one tuple from database (SELECT requests)</p>
*
* @param selection query $sqlquery
* @return dbrow
*/
function getObject ( $sql_query ) {
$this->_cursor = mysql_query ( $sql_query, $this->_ressource );
if ( $this->_cursor != null ) {
$object = mysql_fetch_object ( $this->_cursor );
mysql_free_result ( $this->_cursor );
return $object;
}
return false;
}
/**
* getObjects
*
* <p>Get a collection from database (SELECT requests)</p>
*
* @param selection query $sqlquery
* @return array
*/
function getObjects ( $sql_query ) {
$this->_cursor = mysql_query ( $sql_query, $this->_ressource );
$objects = array();
if ( $this->_cursor ) {
while ( $object = mysql_fetch_object ( $this->_cursor ) )
array_push ( $objects, $object );
mysql_free_result ( $this->_cursor );
}
return $objects;
}
/**
* Execute a query (INSERT, DELETE, UPDATE,... requests)
*
* @param sql query to execute $sql_query
* @return mysql_query result
*/
function query ( $sql_query ) {
$this->_errorNum = 0;
$this->_errorMsg = '';
$this->_cursor = mysql_query( $sql_query, $this->_ressource );
if (!$this->_cursor) {
$this->_errorNum = mysql_errno( $this->_ressource );
$this->_errorMsg = mysql_error( $this->_ressource ) ." SQL=".$sql_query ;
echo $this->_errorMsg;
return false;
}
return $this->_cursor;
}
/**
* Get the latest id
*
* @return lastest id
*/
function getInsertId () {
if ( $this->_ressource != null )
return mysql_insert_id( $this->_ressource ) ;
return false;
}
/**
* Check if $table exist
*
* @param table $table
* @return boolean
*/
function isTableExist($table){
$query = "SHOW TABLES FROM ".$this->_base;
$runQuery = mysql_query($query);
$tables = array();
while($row = mysql_fetch_row($runQuery)){
$tables[] = $row[0];
}
if(in_array($table, $tables)){
return true;
}
return false;
}
/**
* List all tables of the database
*
* @return array which contains all tables names
*/
function listTables(){
$query = "SHOW TABLES FROM ".$this->_base;
$runQuery = mysql_query($query);
$tables = array();
while($row = mysql_fetch_row($runQuery)){
$tables[] = $row[0];
}
return $tables;
}
/**
* List all columns of $table
*
* @param $table
* @return array which contains all tables names
*/
function listColumnsOfTable($table){
$query = "SHOW COLUMNS FROM ".$table;
$columns = array();
if (!$result) {
return $columns;
}
if (mysql_num_rows($result) > 0) {
while ($row = mysql_fetch_assoc($result)) {
$columns[] = $row;
}
}
return $columns;
}
}
$_db = database::getInstance();
?>
|
Go
|
UTF-8
| 766 | 3.09375 | 3 |
[] |
no_license
|
/**
@author ZhengHao Lou
Date 2022/06/08
*/
package main
import "fmt"
/**
https://leetcode.cn/problems/valid-boomerang/
*/
func isBoomerang(points [][]int) bool {
if (points[0][0] == points[1][0] && points[0][1] == points[1][1]) ||
(points[0][0] == points[2][0] && points[0][1] == points[2][1]) {
return false
}
if points[0][0] == points[1][0] && points[0][0] == points[2][0] {
return false
}
a1, b1 := points[0][1]-points[1][1], points[0][0]-points[1][0]
g1 := gcd(a1, b1)
a1, b1 = a1/g1, b1/g1
a2, b2 := points[0][1]-points[2][1], points[0][0]-points[2][0]
g2 := gcd(a2, b2)
a2, b2 = a2/g2, b2/g2
return fmt.Sprintf("%v/%v", a1, b1) != fmt.Sprintf("%v/%v", a2, b2)
}
func gcd(a, b int) int {
if a == 0 {
return b
}
return gcd(b%a, a)
}
|
Swift
|
UTF-8
| 4,302 | 3.015625 | 3 |
[] |
no_license
|
//
// Currency.swift
// CurrencyCalculator
//
// Created by Jacob Aronoff on 7/17/15.
// Copyright (c) 2015 Jacob Aronoff. All rights reserved.
//
import Foundation
class Currency: Printable {
var symbol: String?
var name: String!
var code: String!
var formatter: NSNumberFormatter?
var myUSCurrency: Currency?
var myTurkishCurrency: Currency?
var myBritishCurrency: Currency?
var myIsraeliCurrency: Currency?
var myEuroCurrency: Currency?
var mySwissFranc: Currency?
var myCanadaDollar: Currency?
var myJapaneseYen: Currency?
init(){
name=""
code=""
}
init(symbol aSymbol: String, name aName: String, code aCode: String){
symbol=aSymbol
name=aName
code=aCode
}
var description: String{
return name!
}
func sharedUSDollar()->Currency{
if myUSCurrency==nil{
myUSCurrency = Currency(symbol: "$", name: "US Dollars", code: "USD")
var myFormatter: NSNumberFormatter? = NSNumberFormatter();
myFormatter!.maximumFractionDigits=2;
myFormatter!.minimumFractionDigits=2;
myUSCurrency!.formatter=myFormatter
println("MADE A NEW CURRENCY")
}
return myUSCurrency!;
}
func sharedTurkishLira()->Currency{
if myTurkishCurrency==nil{
myTurkishCurrency = Currency(symbol: "₺", name: "Turkish Lira", code: "TRY")
var myFormatter: NSNumberFormatter? = NSNumberFormatter();
myFormatter!.maximumFractionDigits=2;
myFormatter!.minimumFractionDigits=2;
myTurkishCurrency!.formatter=myFormatter
}
return myTurkishCurrency!;
}
func sharedBritishPound()->Currency{
if myBritishCurrency==nil{
myBritishCurrency = Currency(symbol: "₤", name: "Great British Pound", code: "GBP")
var myFormatter: NSNumberFormatter? = NSNumberFormatter();
myFormatter!.maximumFractionDigits=2;
myFormatter!.minimumFractionDigits=2;
myBritishCurrency!.formatter=myFormatter
}
return myBritishCurrency!;
}
func sharedIsraeliShekel()->Currency{
if myIsraeliCurrency==nil{
myIsraeliCurrency = Currency(symbol: "₪", name: "Israeli Shekel", code: "ILS")
var myFormatter: NSNumberFormatter? = NSNumberFormatter();
myFormatter!.maximumFractionDigits=2;
myFormatter!.minimumFractionDigits=2;
myIsraeliCurrency!.formatter=myFormatter
}
return myIsraeliCurrency!;
}
func sharedEuro()->Currency{
if myEuroCurrency==nil{
myEuroCurrency = Currency(symbol: "€", name: "Euro", code: "EUR")
var myFormatter: NSNumberFormatter? = NSNumberFormatter();
myFormatter!.maximumFractionDigits=2;
myFormatter!.minimumFractionDigits=2;
myEuroCurrency!.formatter=myFormatter
}
return myEuroCurrency!;
}
func sharedSwissFranc()->Currency{
if mySwissFranc==nil{
mySwissFranc = Currency(symbol: "Fr", name: "Swiss Franc", code: "CHF")
var myFormatter: NSNumberFormatter? = NSNumberFormatter();
myFormatter!.maximumFractionDigits=2;
myFormatter!.minimumFractionDigits=2;
mySwissFranc!.formatter=myFormatter
}
return mySwissFranc!;
}
func sharedCanadaDollar()->Currency{
if myCanadaDollar==nil{
myCanadaDollar = Currency(symbol: "$", name: "Canadian Dollar", code: "CAD")
var myFormatter: NSNumberFormatter? = NSNumberFormatter();
myFormatter!.maximumFractionDigits=2;
myFormatter!.minimumFractionDigits=2;
myCanadaDollar!.formatter=myFormatter
}
return myCanadaDollar!;
}
func sharedJapaneseYen()->Currency{
if myJapaneseYen==nil{
myJapaneseYen = Currency(symbol: "¥", name: "Japanese Yen", code: "JPY")
var myFormatter: NSNumberFormatter? = NSNumberFormatter();
myFormatter!.maximumFractionDigits=2;
myFormatter!.minimumFractionDigits=2;
myJapaneseYen!.formatter=myFormatter
}
return myJapaneseYen!;
}
}
|
Java
|
UTF-8
| 629 | 2.890625 | 3 |
[] |
no_license
|
package com.example.spacetraders.data.entity;
public enum Weapons {
SONICRAY("Sonic Ray", 250, 5),
PLASMARAY("Plasma Ray", 500, 15),
MESONPHASER("Meson Phaser", 750, 25);
private final String name;
private final int cost;
private final int damage;
Weapons(String weaponName, int weaponCost, int damageCount) {
name = weaponName;
cost = weaponCost;
damage = damageCount;
}
public String getWeaponName() {
return name;
}
public int getWeaponCost() {
return cost;
}
public int getDamageCount() {
return damage;
}
}
|
Python
|
UTF-8
| 2,775 | 2.796875 | 3 |
[] |
no_license
|
# -*- coding:utf-8 -*-
import sys
if sys.version_info[:2] > (3, 5):
import asyncio
import aiohttp
PY3 = True
else:
import grequests
PY3 = False
class RequestLeveFunError(Exception):
def __init__(self, result=None):
super(TimeOutError, self).__init__()
self.result = result
class Leverfun:
stock_api = 'https://app.leverfun.com/timelyInfo/timelyOrderForm'
def __init__(self):
self.stocks_dict = dict()
def stocks(self, stock_codes):
self.stocks_dict = dict()
if type(stock_codes) is not list:
stock_codes = [stock_codes]
if PY3:
threads = []
for stock in stock_codes:
threads.append(self.get_stock_detail(stock))
try:
loop = asyncio.get_event_loop()
except RuntimeError:
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(asyncio.wait(threads))
else:
for stock_code in stock_codes:
try:
req = grequests.get(Leverfun.stock_api,
params=dict(stockCode=stock_code))
rep = grequests.map([req, ])[0]
r_json = rep.json()
except Exception as ex:
raise RequestLeveFunError(ex.message)
else:
self.stocks_dict[
stock_code] = Leverfun.format_response_data(r_json)
return self.stocks_dict
"""async def get_stock_detail(self, stock_code):
params = dict(stockCode=stock_code)
async with aiohttp.get(Leverfun.stock_api, params=params) as r:
r_json = await r.json()
self.stocks_dict[
stock_code] = Leverfun.format_response_data(r_json)
"""
@classmethod
def format_response_data(cls, response_data):
data = response_data['data']
buys = data['buyPankou']
sells = data['sellPankou']
stock_dict = dict(
close=round(data['preClose'], 3),
now=data['match'],
buy=buys[0]['price'],
sell=sells[0]['price'],
)
for trade_info_li, name in zip([sells, buys], ['ask', 'bid']):
for i, trade_info in enumerate(trade_info_li):
stock_dict['{name}{index}'.format(
name=name, index=i + 1)] = trade_info['price']
stock_dict['{name}{index}_volume'.format(
name=name, index=i + 1)] = trade_info['volume'] * 100
return stock_dict
if __name__ == '__main__':
q = Leverfun()
print(q.stocks(['000001', '162411']))
print(q.stocks('162411'))
|
C
|
UTF-8
| 4,541 | 3.640625 | 4 |
[] |
no_license
|
/**
* \file gagne.c
* \brief C'est la fonction avec laquelle on vérifie si un joueur à gagné ou pas
*/
#include <stdio.h>
#include<stdlib.h>
#include"../Include/P4.h"
/**
* \fn int gagne(joueur_t * joueur, case_t mat[L][C])
* \brief fonction qui vérifie si 4 pièces sont alignées
* \param * joueur : un pointeur sur une structure joueur qui représente le joueur qui joue
* \param mat[L][C] : la matrice dans laquelle on vérifie si les 4 pièces sont alignées
*/
int gagne(joueur_t * joueur, case_t mat[L][C]){
int i,j; /* i et j étant les lignes et les colonnes de notre matrice */
for(i=L-1;i>(L/2);i--){ /* on regarde verticalement */
for(j=0;j<C;j++){
if(mat[i][j].piece1->couleur == joueur->couleur || mat[i][j].piece2->couleur == joueur->couleur){
if(mat[i-1][j].piece1->couleur == joueur->couleur || mat[i-1][j].piece2->couleur == joueur->couleur){
if(mat[i-2][j].piece1->couleur == joueur->couleur || mat[i-2][j].piece2->couleur == joueur->couleur){
if(mat[i-3][j].piece1->couleur == joueur->couleur || mat[i-3][j].piece2->couleur == joueur->couleur){
return 1;
}
}
}
}
}
}
for(i=L-1;i>0;i--){ /* on regarde horizontalement */
for(j=0;j<=((C/2));j++){
if(mat[i][j].piece1->couleur == joueur->couleur || mat[i][j].piece2->couleur == joueur->couleur){
if(mat[i][j+1].piece1->couleur == joueur->couleur || mat[i][j+1].piece2->couleur == joueur->couleur){
if(mat[i][j+2].piece1->couleur == joueur->couleur || mat[i][j+2].piece2->couleur == joueur->couleur){
if(mat[i][j+3].piece1->couleur == joueur->couleur || mat[i][j+3].piece2->couleur == joueur->couleur){
return 1;
}
}
}
}
}
}
for(i=L-1;i>(L/2);i--){ /* on teste en diagonale de gauche a droite du bas vers le haut */
for(j=0;j<=(C/2);j++){
if(mat[i][j].piece1->couleur == joueur->couleur || mat[i][j].piece2->couleur == joueur->couleur){
if(mat[i-1][j+1].piece1->couleur == joueur->couleur || mat[i-1][j+1].piece2->couleur == joueur->couleur){
if(mat[i-2][j+2].piece1->couleur == joueur->couleur || mat[i-2][j+2].piece2->couleur == joueur->couleur){
if(mat[i-3][j+3].piece1->couleur == joueur->couleur || mat[i-3][j+3].piece2->couleur == joueur->couleur){
return 1;
}
}
}
}
}
}
for(i=L-1;i>(L/2);i--){ /* on teste en diagonale de droite a gauche du bas vers le haut */
for(j=C-1;j>=(C/2);j--){
if(mat[i][j].piece1->couleur == joueur->couleur || mat[i][j].piece2->couleur == joueur->couleur){
if(mat[i-1][j-1].piece1->couleur == joueur->couleur || mat[i-1][j-1].piece2->couleur == joueur->couleur){
if(mat[i-2][j-2].piece1->couleur == joueur->couleur || mat[i-2][j-2].piece2->couleur == joueur->couleur){
if(mat[i-3][j-3].piece1->couleur == joueur->couleur || mat[i-3][j-3].piece2->couleur == joueur->couleur){
return 1;
}
}
}
}
}
}
return 0;
}
|
JavaScript
|
UTF-8
| 3,200 | 2.640625 | 3 |
[] |
no_license
|
/**
* Sample React Native App
* https://github.com/facebook/react-native
*/
/*
用户体验优化,数据加载完全前显示loading,加载完全后展示出来
1. 添加renderLoadingView方法,用于数据loading时,控件的外观
2. 给Status中添加loaded布尔型变量用来表示是否加载完成
3. 在render方法中首先判断loaded是否完成,已完成:填充ListView数据并渲染输出;未完成:执行renderLoadingView方法,提示用户loading中状态
*/
'use strict';
var React = require('react-native');
var {
AppRegistry,
StyleSheet,
Text,
View,
Image,
ListView,
} = React;
var REQUEST_URL = 'http://10.168.0.151/caichao/qinglist.js';
// multiRowWithFetchUE:添加loadingreadner方法
// 初始化一个loaded变量
var reactdemo = React.createClass({
// multiRowWithFetchUE:初始化一个loaded变量为false,标明loading中状态
getInitialState: function() {
return {
dataSource: new ListView.DataSource({
rowHasChanged: (row1, row2) => row1 !== row2,
}),
loaded: false,
};
},
// multiRowWithFetchUE:控件加载完成,再获取数据
componentDidMount: function() {
this.fetchData();
},
// multiRowWithFetchUE:再获取数据设置完成,loaded变量为true
fetchData: function() {
fetch(REQUEST_URL)
.then((response) => response.json())
.then((responseData) => {
this.setState({
dataSource: this.state.dataSource.cloneWithRows(responseData),
loaded: true,
});
})
.done();
},
// multiRowWithFetchUE:主render方法,判断loaded变量
// false调用loading render,true调用listview方法
render: function() {
if (!this.state.loaded) {
return this.renderLoadingView();
}
return (
<ListView
dataSource={this.state.dataSource}
renderRow={this.renderQing}
style={styles.listView}
/>
);
},
// multiRowWithFetchUE: loaded为false时调用的方法
renderLoadingView: function() {
return (
<View style={styles.row}>
<Text>
加载轻互动列表中...
</Text>
</View>
);
},
// multiRowWithArray:单行渲染方法改了个名字,接受一个叫item的obj,显示
renderQing: function(item) {
return (
<View style={styles.row}>
<Image
style={styles.img}
source={{uri:item.imgsrc}} />
<View style={styles.intro}>
<Text style={styles.title}>{item.title}</Text>
<Text style={styles.desc}>{item.desc}</Text>
</View>
</View>
)
}
});
// multiRowWithArray:为ListView加入新追加的ListView样式styles.listView
var styles = StyleSheet.create({
row: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
flexDirection: 'row',
},
img: {
width: 50,
height: 50,
marginRight: 10
},
intro: {
flex: 1,
},
title: {
fontSize: 24,
},
listView: {
paddingTop: 20, // 给系统上面信息条留出空间
backgroundColor: '#F5FCFF',
},
});
AppRegistry.registerComponent('reactdemo', () => reactdemo);
|
Python
|
UTF-8
| 484 | 3.046875 | 3 |
[] |
no_license
|
from PIL import Image
img = Image.open('problem.png')
width, height = img.size
img_pixels = []
for y in range(height):
for x in range(width):
img_pixels.append(img.getpixel((x, y)))
num_list = []
for i in range(len(img_pixels)):
num = img_pixels[i][0]
num_list.append(num)
print(num_list)
gen_html = ""
for i in range(len(num_list)):
char = chr(num_list[i])
gen_html += char
print(gen_html)
with open('output.html', 'w') as f:
f.write(gen_html)
|
C#
|
UTF-8
| 1,340 | 2.765625 | 3 |
[
"Apache-2.0"
] |
permissive
|
using System.Threading;
using System.Threading.Tasks;
using AutoMapper;
using Database.Entities.Nodes;
using MediatR;
using Neo4j.Driver;
namespace MediatorRequests.CreateIngredient
{
public class CreateIngredientHandler : IRequestHandler<CreateIngredientCommand, Ingredient>
{
private readonly IDriver _driver;
private readonly IMapper _mapper;
public CreateIngredientHandler(IDriver driver, IMapper mapper)
{
_driver = driver;
_mapper = mapper;
}
public async Task<Ingredient> Handle(CreateIngredientCommand request, CancellationToken cancellationToken)
{
var session = _driver.AsyncSession();
var ingredient = await session.WriteTransactionAsync(async transaction =>
{
const string cypher = @"
CREATE (i:Ingredient {name: $name, weight: $weight})
RETURN id(i) AS id, i.name AS name, i.weight as weight";
var result = await transaction.RunAsync(cypher,
new { name = request.Name, weight = request.Weight });
var record = await result.PeekAsync();
await transaction.CommitAsync();
return _mapper.Map<Ingredient>(record);
});
return ingredient;
}
}
}
|
C#
|
UTF-8
| 9,251 | 2.640625 | 3 |
[] |
no_license
|
using SUP_G6.DataTypes;
using SUP_G6.Interface;
using SUP_G6.Models;
using SUP_G6.Other;
using SUP_G6.ViewModels;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Media;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Threading;
using System.IO;
using System.Windows.Resources;
namespace SUP_G6.Views
{
/// <summary>
/// Interaction for view specific logic in GamePlayPage.xaml
/// </summary>
public partial class GamePlayPage : Page
{
private GamePlayViewModel viewModel;
#region Fields
List<Panel> Panels = new List<Panel>();
List<Panel> currentGuessRow = new List<Panel>();
List<Panel> nextGuessRow = new List<Panel>();
#endregion
#region Constructor
public GamePlayPage(IPlayer player, Level level)
{
InitializeComponent();
viewModel = new GamePlayViewModel(player, level);
DataContext = viewModel;
AddPanelsToList();
}
#endregion
#region Helper functions
public void AddPanelsToList()
{
/* Checks all childrenitems in Main Grid a.k.a "MasterGrid".
If the type is Grid, it's casted to a Panel and check the x:name.
If it starts with "p" it gets added to the Panels-list. */
foreach (UIElement p in MasterGrid.Children)
{
if (p.GetType() == typeof(Grid))
{
var panel = (Panel)p;
if (panel.Name.StartsWith('p'))
{
Panels.Add(panel);
}
}
}
}
public int[] ExtractGuessFromCurrentGuessRow()
{
List<UIElement> guessedPegs = new List<UIElement>();
/* New list to get the current row's guesses.
* Returns array with what ID the peg has, and in which panel the peg is placed */
guessedPegs.Add(currentGuessRow[0].Children[0]);
guessedPegs.Add(currentGuessRow[1].Children[0]);
guessedPegs.Add(currentGuessRow[2].Children[0]);
guessedPegs.Add(currentGuessRow[3].Children[0]);
int[] guess = new int[4];
foreach (IPeg peg in guessedPegs)
{
int pegId = peg.PegId;
int position = guessedPegs.IndexOf((UIElement)peg);
guess.SetValue(pegId, position);
}
return guess;
}
public void DetermineActivePanel()
{
currentGuessRow.Clear();
/* NumberOfTries is set in ViewModel, and is multiplied by 4 to check which row that should be active. */
//Adds the last 4 Panels that the player has manipulated to currentGuessRow
currentGuessRow.Add(Panels[viewModel.NumberOfTries * 4]);
currentGuessRow.Add(Panels[viewModel.NumberOfTries * 4 + 1]);
currentGuessRow.Add(Panels[viewModel.NumberOfTries * 4 + 2]);
currentGuessRow.Add(Panels[viewModel.NumberOfTries * 4 + 3]);
nextGuessRow.Clear();
//If the player has any tries left, the next 4 Panels that the player may manipulate gets added to nextGuessRow
if (viewModel.NumberOfTries < 9)
{
nextGuessRow.Add(Panels[viewModel.NumberOfTries * 4 + 4]);
nextGuessRow.Add(Panels[viewModel.NumberOfTries * 4 + 5]);
nextGuessRow.Add(Panels[viewModel.NumberOfTries * 4 + 6]);
nextGuessRow.Add(Panels[viewModel.NumberOfTries * 4 + 7]);
}
}
#endregion
#region Handle Guesses
private bool IsGuessDone(List<Panel> currentPanel)
{
/* Checks if there are one children in each panel in the currentPanel. If so, the guess is submitted and the pabel is disabled for additional pegplacements.*/
for (int i = 0; i < currentPanel.Count; i++)
{
if (currentPanel[0].Children.Count > 0 && currentPanel[1].Children.Count > 0 && currentPanel[2].Children.Count > 0 && currentPanel[3].Children.Count > 0)
{
currentPanel[i].AllowDrop = false;
currentPanel[i].Background = Brushes.LightGray;
foreach (IPeg peg in currentPanel[i].Children)
{
peg.IsEnabled = false;
}
}
else
{
return false;
}
}
return true;
}
private void MakeNextGuessAvailable(List<Panel> nextGuessRow)
{
// Is called when "IsGuessDown()" returns true and enables the next row for drag N drop.
for (int i = 0; i < nextGuessRow.Count; i++)
{
nextGuessRow[i].AllowDrop = true;
nextGuessRow[i].Background = Brushes.LightYellow;
}
}
#endregion
#region Drag and Drop
private void panel_DragOver(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent("Object"))
{
// These Effects values are used in the drag source's
// GiveFeedback event handler to determine which cursor to display.
if (e.KeyStates == DragDropKeyStates.ControlKey)
{
e.Effects = DragDropEffects.Copy;
}
else
{
e.Effects = DragDropEffects.Move;
}
}
}
private void panel_Drop(object sender, DragEventArgs e)
{
//If an element in the panel has already handled the drop, the panel should not also handle it.
if (e.Handled == false)
{
Panel _panel = (Panel)sender;
UIElement _element = (UIElement)e.Data.GetData("Object");
if (_panel != null && _element != null)
{
//Get the panel that the element currently belongs to and add the children on the panel that its been dropped on.
Panel _parent = (Panel)VisualTreeHelper.GetParent(_element);
if (_parent != null)
{
if (e.AllowedEffects.HasFlag(DragDropEffects.Copy))
{
if (_element is IPeg)
{
var pegId = ((IPeg)_element).PegId;
IPeg peg;
switch (pegId)
{
case 1:
peg = (IPeg)new Peg1();
break;
case 2:
peg = (IPeg)new Peg2();
break;
case 3:
peg = (IPeg)new Peg3();
break;
case 4:
peg = (IPeg)new Peg4();
break;
case 5:
peg = (IPeg)new Peg5();
break;
case 6:
peg = (IPeg)new Peg6();
break;
case 7:
peg = (IPeg)new Peg7();
break;
case 8:
peg = (IPeg)new Peg8();
break;
default:
peg = (IPeg)new Peg6();
break;
}
_panel.Children.Clear();
_panel.Children.Add((UIElement)peg);
}
}
}
}
}
}
#endregion
#region Event Handler for Guess Button
private void GuessButton_Click(object sender, RoutedEventArgs e)
{
DetermineActivePanel();
if (IsGuessDone(currentGuessRow))
{
viewModel.Guess = ExtractGuessFromCurrentGuessRow();
MakeNextGuessAvailable(nextGuessRow);
}
else
{
MessageBox.Show($"{viewModel.ToMessageBox}");
}
}
#endregion
}
}
|
C++
|
UTF-8
| 9,640 | 2.890625 | 3 |
[] |
no_license
|
#include <gtest/gtest.h>
#include <memory>
#include "sic/Base/Tolerances.hh"
#include "sic/Model/ModelPortfolio.hh"
#include "sic/Portfolio/MockAsset.hh"
namespace {
class ModelPortfolioTest : public testing::Test {};
TEST_F(ModelPortfolioTest, CreateValid) {
auto assetWeightsMap =
std::make_unique<sic::AbstractAsset::AssetWeightMap>();
auto assetWeightsMapRawPtr = assetWeightsMap.get();
constexpr int expAssetCount = 19;
assetWeightsMap->reserve(expAssetCount);
std::vector<sic::WeightRange> assetWeights;
assetWeights.reserve(expAssetCount);
// First set of Asset get 10% weighting, min/max -1/+1.
constexpr int largePercentAssetCount = 9;
constexpr sic::Weight largePercentTargetWeight = 0.1;
constexpr sic::Weight largePercentMinWeight =
largePercentTargetWeight - 0.01;
constexpr sic::Weight largePercentMaxWeight =
largePercentTargetWeight + 0.01;
const sic::WeightRange largeWeightRange(
largePercentMinWeight, largePercentTargetWeight, largePercentMaxWeight);
for (int i = 0; i < largePercentAssetCount; i++) {
assetWeights.push_back(largeWeightRange);
}
// Remaining Assets split the remainder of the weight.
constexpr int remainingAssetCount = expAssetCount - largePercentAssetCount;
constexpr sic::Weight remainingWeight =
1.0 - static_cast<sic::Weight>(largePercentAssetCount) *
largePercentTargetWeight;
constexpr sic::Weight remainingPercentTargetWeight =
remainingWeight / static_cast<sic::Weight>(remainingAssetCount);
constexpr sic::Weight remainingPercentMinWeight =
remainingPercentTargetWeight - 0.01;
constexpr sic::Weight remainingPercentMaxWeight =
remainingPercentTargetWeight + 0.01;
const sic::WeightRange remainingWeightRange(remainingPercentMinWeight,
remainingPercentTargetWeight,
remainingPercentMaxWeight);
for (int i = 0; i < remainingAssetCount; i++) {
assetWeights.push_back(remainingWeightRange);
}
std::vector<std::unique_ptr<const sic::MockAsset>> assets;
assets.reserve(expAssetCount);
for (int i = 0; i < expAssetCount; i++) {
const auto assetID = static_cast<sic::External::ID>(i);
assets.emplace_back(std::make_unique<const sic::MockAsset>(assetID));
assetWeightsMap->insert({assets.at(i).get(), assetWeights.at(i)});
}
constexpr sic::External::ID expExternalID = 43534l;
sic::ModelPortfolio validMPF(std::move(assetWeightsMap), expExternalID);
ASSERT_EQ(expExternalID, validMPF.getExternalID());
ASSERT_EQ(expAssetCount, validMPF.getAssetCount());
// Check we can iterate through the items correctly.
auto assetWeightIterators = validMPF.getAssetWeightIterators();
ASSERT_EQ(assetWeightsMapRawPtr->begin()->first,
assetWeightIterators.current()->first);
ASSERT_TRUE(assetWeightIterators.remaining());
}
TEST_F(ModelPortfolioTest, CreateInvalidEmptyAssetsList) {
auto assetWeightsMap =
std::make_unique<sic::AbstractAsset::AssetWeightMap>();
constexpr sic::External::ID expExternalID = 43534l;
const std::string expError =
"assetWeightMap must contain at least one entry.";
try {
const sic::ModelPortfolio invalidMPF(std::move(assetWeightsMap),
expExternalID);
FAIL() << "Able to create MPF with empty assets map.";
} catch (std::invalid_argument &e) {
ASSERT_EQ(expError, e.what());
} catch (...) {
FAIL() << "Unexpected exception.";
}
}
TEST_F(ModelPortfolioTest, CreateInvalidDuplicateAssets) {
auto assetWeightsMap =
std::make_unique<sic::AbstractAsset::AssetWeightMap>();
constexpr int expAssetCount = 20;
constexpr int expDuplicateAssetCount = 2;
constexpr sic::External::ID expExternalID = 43534;
constexpr sic::Weight perAssetTargetWeight =
1.0 / static_cast<sic::Weight>(expAssetCount);
constexpr sic::Weight perAssetMinWeight = perAssetTargetWeight - 0.01;
constexpr sic::Weight perAssetMaxWeight = perAssetTargetWeight + 0.01;
const sic::WeightRange perAssetWeightRange(
perAssetMinWeight, perAssetTargetWeight, perAssetMaxWeight);
constexpr sic::External::ID duplicateID = 432344;
std::vector<std::unique_ptr<const sic::MockAsset>> assets;
assets.reserve(expAssetCount);
for (int i = 0; i < expAssetCount; i++) {
const sic::External::ID assetID =
(i < expDuplicateAssetCount) ? duplicateID
: static_cast<sic::External::ID>(i);
assets.emplace_back(std::make_unique<const sic::MockAsset>(assetID));
assetWeightsMap->insert({assets.at(i).get(), perAssetWeightRange});
}
const std::string expError =
"assetWeightMap must not contain duplicate Assets.";
try {
const sic::ModelPortfolio invalidMPF(std::move(assetWeightsMap),
expExternalID);
FAIL() << "Able to create MPF with duplicate Assets.";
} catch (std::invalid_argument &e) {
ASSERT_EQ(expError, e.what());
} catch (...) {
FAIL() << "Unexpected exception.";
}
}
TEST_F(ModelPortfolioTest, CreateValidAssetsSum100Percent) {
constexpr int expAssetCount = 5;
constexpr sic::Weight perAssetTargetWeight =
1.0 / static_cast<sic::Weight>(expAssetCount);
constexpr sic::Weight perAssetMinWeight = perAssetTargetWeight - 0.01;
constexpr sic::Weight perAssetMaxWeight = perAssetTargetWeight + 0.01;
constexpr sic::External::ID expExternalID = 435354;
// Overweight, still valid.
auto validOverAssetList =
std::make_unique<sic::AbstractAsset::AssetWeightMap>();
std::vector<std::unique_ptr<const sic::MockAsset>> overAssets;
overAssets.reserve(expAssetCount);
for (int i = 0; i < expAssetCount; i++) {
const auto assetID = static_cast<sic::External::ID>(i);
// Offset one Asset weight by the maximum tolerance allowed.
const sic::Weight assetWeight =
(i == 0)
? perAssetTargetWeight + 0.99 * sic::Tolerance<sic::Weight>()
: perAssetTargetWeight;
const sic::WeightRange adjustedWeightRange(
perAssetMinWeight, assetWeight, perAssetMaxWeight);
overAssets.emplace_back(
std::make_unique<const sic::MockAsset>(assetID));
validOverAssetList->insert(
{overAssets.at(i).get(), adjustedWeightRange});
}
const sic::ModelPortfolio validOverMPF(std::move(validOverAssetList),
expExternalID);
// Overweight, still valid.
auto validUnderAssetList =
std::make_unique<sic::AbstractAsset::AssetWeightMap>();
std::vector<std::unique_ptr<const sic::MockAsset>> underAssets;
underAssets.reserve(expAssetCount);
for (int i = 0; i < expAssetCount; i++) {
const auto assetID = static_cast<sic::External::ID>(i);
// Offset one Asset weight by the maximum tolerance allowed.
const sic::Weight assetWeight =
(i == 0)
? perAssetTargetWeight - 0.99 * sic::Tolerance<sic::Weight>()
: perAssetTargetWeight;
const sic::WeightRange adjustedWeightRange(
perAssetMinWeight, assetWeight, perAssetMaxWeight);
underAssets.emplace_back(
std::make_unique<const sic::MockAsset>(assetID));
validUnderAssetList->insert(
{underAssets.at(i).get(), adjustedWeightRange});
}
const sic::ModelPortfolio validUnderMPF(std::move(validUnderAssetList),
expExternalID);
}
TEST_F(ModelPortfolioTest, CreateInvalidAssetsSum100Percent) {
constexpr int expAssetCount = 5;
constexpr sic::Weight perAssetTargetWeight =
1.0 / static_cast<sic::Weight>(expAssetCount);
constexpr sic::Weight perAssetMinWeight = perAssetTargetWeight - 0.01;
constexpr sic::Weight perAssetMaxWeight = perAssetTargetWeight + 0.01;
constexpr sic::External::ID expExternalID = 435354;
const std::string expError =
"ModelPortfolio Asset weights must sum to 1.0.";
// Overweight, invalid.
auto invalidOverAssetList =
std::make_unique<sic::AbstractAsset::AssetWeightMap>();
std::vector<std::unique_ptr<const sic::MockAsset>> overAssets;
overAssets.reserve(expAssetCount);
for (int i = 0; i < expAssetCount; i++) {
const auto assetID = static_cast<sic::External::ID>(i);
// Offset one Asset weight by just over the maximum tolerance.
const sic::Weight assetWeight =
(i == 0)
? perAssetTargetWeight + 1.01 * sic::Tolerance<sic::Weight>()
: perAssetTargetWeight;
const sic::WeightRange adjustedWeightRange(
perAssetMinWeight, assetWeight, perAssetMaxWeight);
overAssets.emplace_back(
std::make_unique<const sic::MockAsset>(assetID));
invalidOverAssetList->insert(
{overAssets.at(i).get(), adjustedWeightRange});
}
try {
const sic::ModelPortfolio invalidOverMPF(
std::move(invalidOverAssetList), expExternalID);
FAIL() << "Able to create a ModelPortfolio with weight sum greater "
"than tolerance.";
} catch (std::invalid_argument &e) {
ASSERT_EQ(expError, e.what());
}
// Underweight, invalid.
auto invalidUnderAssetList =
std::make_unique<sic::AbstractAsset::AssetWeightMap>();
std::vector<std::unique_ptr<const sic::MockAsset>> underAssets;
underAssets.reserve(expAssetCount);
sic::Weight sum = 0.0;
for (int i = 0; i < expAssetCount; i++) {
const auto assetID = static_cast<sic::External::ID>(i);
// Offset one Asset weight by just over the maximum tolerance.
const sic::Weight assetWeight =
(i == 0)
? perAssetTargetWeight - 1.01 * sic::Tolerance<sic::Weight>()
: perAssetTargetWeight;
const sic::WeightRange adjustedWeightRange(
perAssetMinWeight, assetWeight, perAssetMaxWeight);
underAssets.emplace_back(
std::make_unique<const sic::MockAsset>(assetID));
invalidUnderAssetList->insert(
{underAssets.at(i).get(), adjustedWeightRange});
sum += assetWeight;
}
try {
const sic::ModelPortfolio invalidUnderMPF(
std::move(invalidUnderAssetList), expExternalID);
FAIL() << "Able to create a ModelPortfolio with weight sum less "
"than tolerance.";
} catch (std::invalid_argument &e) {
ASSERT_EQ(expError, e.what());
}
}
} // namespace
|
C++
|
UTF-8
| 1,110 | 3.328125 | 3 |
[] |
no_license
|
/*
#include "..\heap.h"
void Heap::_push(int i_key)
{
m_heap.push_back(i_key);
int index = static_cast<int>(m_heap.size() - 1);
int tmp_key = m_heap[index];
int index_parent = (index - 1) / 2;
while (index > 0 && tmp_key >= m_heap[index_parent])
{
m_heap[index] = m_heap[index_parent];
index = index_parent;
index_parent = (index_parent - 1) / 2;
}
m_heap[index] = tmp_key;
}
void Heap::_pop()
{
int index = 0;
m_heap[index] = m_heap[static_cast<int>(m_heap.size() - 1)];
int tmp_key = m_heap[index];
m_heap.pop_back();
int index_current = 0;
int index_L = 0;
int index_R = 0;
while (index < static_cast<int>(m_heap.size() / 2))
{
index_L = 2 * index + 1;
index_R = index_L + 1;
if (index_R < static_cast<int>(m_heap.size()) && m_heap[index_L] < m_heap[index_R])
{
index_current = index_R;
}
else
{
index_current = index_L;
}
if (tmp_key >= m_heap[index_current])
{
break;
}
m_heap[index] = m_heap[index_current];
index = index_current;
}
if (!m_heap.empty())
{
m_heap[index] = tmp_key;
}
}
int Heap::_peek()
{
return m_heap[0];
}
*/
|
C++
|
UTF-8
| 564 | 3.296875 | 3 |
[] |
no_license
|
#include <iostream>
usando el espacio de nombres estándar ;
int main () {
int cantNumeros = 0 ;
int promedio = 0 ;
int suma = 0 ;
cout << " Ingrese la cantidad de numeros: " ;
cin >> cantNumeros;
int numeros [cantNumeros];
para ( int i = 0 ; i <cantNumeros; i ++) {
cout << " Ingrese el dato " << (i + 1 ) << endl;
cin >> numeros [i];
suma = suma + numeros [i];
}
promedio = suma / cantNumeros;
cout << " El promedio de los números es: " << promedio << endl;
devuelve 0 ;
}
|
PHP
|
UTF-8
| 1,057 | 2.75 | 3 |
[
"MIT"
] |
permissive
|
<?php
Class _netspeed {
public static function lookup($ip) {
$ch = curl_init();
// Notice: the request back to the Symphony services API includes your domain name
// and the version of Symphony that you're using
$version = Frontend::instance()->Configuration->get('version', 'symphony');
$domain = $_SERVER[SERVER_NAME];
curl_setopt($ch, CURLOPT_URL, "http://symphony-cms.net/_netspeed/1.0/?symphony=".$version."&domain=".$domain."&ip=".$ip);
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$speedinfo = curl_exec($ch);
$info = curl_getinfo($ch);
curl_close($ch);
if ($speedinfo === false || $info['http_code'] != 200) {
return;
}
else {
$speedinfo = explode(',', $speedinfo);
}
$result = new XMLElement("netspeed");
$included = array(
'id',
'connection',
'error'
);
$i = 0;
foreach($included as $netspeed) {
$result->appendChild(new XMLElement($netspeed, $speedinfo[$i]));
$i++;
}
return $result;
}
}
|
Ruby
|
UTF-8
| 382 | 3.78125 | 4 |
[] |
no_license
|
# The guess API is already defined for you.
# @param num, your guess
# @return -1 if my number is lower, 1 if my number is higher, otherwise return 0
# def guess(num)
def guessNumber(n)
left, right = 0, n
loop {
mid = left + (right - left) / 2
case guess(mid)
when 0 then return mid
when -1 then right = mid - 1
when 1 then left = mid + 1
end
}
end
|
Java
|
UTF-8
| 2,822 | 2.25 | 2 |
[] |
no_license
|
package com.leonardo.doctorsoffice.service;
import com.leonardo.doctorsoffice.DTO.MedicalConsultationDTO;
import com.leonardo.doctorsoffice.entity.MedicalConsultation;
import com.leonardo.doctorsoffice.entity.Patient;
import com.leonardo.doctorsoffice.repository.DoctorRepository;
import com.leonardo.doctorsoffice.repository.MedicalConsultationRepository;
import com.leonardo.doctorsoffice.repository.PatientRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class MedicalConsultationService {
@Autowired
private MedicalConsultationRepository medicalConsultationRepository;
@Autowired
private PatientRepository patientRepository;
@Autowired
private DoctorRepository doctorRepository;
public MedicalConsultation saveMedicalConsultation(MedicalConsultationDTO medicalConsultationDTO) {
MedicalConsultation medicalConsultation = new MedicalConsultation();
medicalConsultation.setDescription(medicalConsultationDTO.getDescription());
medicalConsultation.setPrescription(medicalConsultationDTO.getPrescription());
medicalConsultation.setDate(medicalConsultationDTO.getDate());
medicalConsultation.setPatient(patientRepository.findById(medicalConsultationDTO.getPatientId()).orElse(null));
medicalConsultation.setDoctor(doctorRepository.findById(medicalConsultationDTO.getDoctorId()).orElse(null));
return medicalConsultationRepository.save(medicalConsultation);
}
public List<MedicalConsultation> getMedicalConsultations() {
return medicalConsultationRepository.findAll();
}
public MedicalConsultation getMedicalConsultationById(Long id) {
return medicalConsultationRepository.findById(id).get();
}
public List<MedicalConsultation> getMedicalConsultationByDoctorId(Long id) {
return medicalConsultationRepository.findAllByDoctor_Id(id);
}
public List<MedicalConsultation> getMedicalConsultationByPatientId(Long id) {
return medicalConsultationRepository.findAllByPatient_Id(id);
}
public MedicalConsultation updateMedicalConsultation(MedicalConsultation medicalConsultation) {
MedicalConsultation currentMedicalConsultation = medicalConsultationRepository.
findById(medicalConsultation.getId()).orElse(null);
currentMedicalConsultation.setDescription(medicalConsultation.getDescription());
currentMedicalConsultation.setPrescription(medicalConsultation.getPrescription());
return medicalConsultationRepository.save(currentMedicalConsultation);
}
public MedicalConsultation deleteMedicalConsultation(Long id) {
medicalConsultationRepository.deleteById(id);
return null;
}
}
|
Java
|
UTF-8
| 2,044 | 1.671875 | 2 |
[
"Apache-2.0"
] |
permissive
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.netbeans.modules.maven.model.pom;
import java.util.List;
/**
*
* @author mkleint
*/
public interface Resource extends POMComponent {
// <!--xs:complexType name="Resource">
// <xs:all>
// <xs:element name="targetPath" minOccurs="0" type="xs:string">
// <xs:element name="filtering" minOccurs="0" type="xs:boolean" default="false">
// <xs:element name="directory" minOccurs="0" type="xs:string">
// <xs:element name="includes" minOccurs="0">
// <xs:element name="include" minOccurs="0" maxOccurs="unbounded" type="xs:string"/>
// <xs:element name="excludes" minOccurs="0">
// <xs:element name="exclude" minOccurs="0" maxOccurs="unbounded" type="xs:string"/>
// </xs:all>
// </xs:complexType-->
String getDirectory();
void setDirectory(String directory);
String getTargetPath();
void setTargetPath(String path);
Boolean isFiltering();
void setFiltering(Boolean filtering);
public List<String> getIncludes();
public void addInclude(String include);
public void removeInclude(String include);
public List<String> getExcludes();
public void addExclude(String exclude);
public void removeExclude(String exclude);
}
|
C++
|
UTF-8
| 5,447 | 3.109375 | 3 |
[] |
no_license
|
#include<iostream>
#include<fstream>
#include<windows.h>
using namespace std;
void menu();
void name();
int Problem1(int a);//return value w arg
int Problem2(int a);
int Problem3(int a);
int Problem4(int a);
int Problem5(int a);//up to here
void Problem6();
void Problem7();
void Problem8();
void Problem9();
void Problem10();
main (){
int choice,n;
do{
name();
menu();
cout<<"Enter your Choice:\n";
cin>>choice;
if(choice<=5&&choice>=1){
cout<<"Enter n:\n";
cin>>n;
cout<<"Writing to file ";
Sleep(400);
cout<<". ";
Sleep(400);
cout<<". ";
Sleep(400);
cout<<". ";
Sleep(400);
cout<<". \n";
system("pause");
}
switch(choice){
case 1:{
Problem1(n);
break;
}
case 2:{
Problem2(n);
break;
}
case 3:{
Problem3(n);
break;
}
case 4:{
Problem4(n);
break;
}
case 5:{
Problem5(n);
break;
}
case 6:{
Problem6();
break;
}
case 7:{
Problem7();
break;
}
case 8:{
Problem8();
break;
}
case 9:{
Problem9();
break;
}
case 10:{
Problem10();
break;
}case 11:{
exit(1);
break;
}
default:{
cout<<"Invalid Input\n";
system("pause");
break;
}
}
system ("cls");
}while(choice!=11)
;}
void name(){
cout<<"Name: Paul Andrei R. Caoile\nSection: E21\nFinal Hands-On Quiz 1\nDate: 10.19.2016\n\n";
}
void menu(){
cout<<"Menu"<<endl;
cout<<"Write to file\n";
cout<<"[1] Problem 1\n";
cout<<"[2] Problem 2\n";
cout<<"[3] Problem 3\n";
cout<<"[4] Problem 4\n";
cout<<"[5] Problem 5\n";
cout<<"Write to file\n";
cout<<"[6] Problem 1\n";
cout<<"[7] Problem 2\n";
cout<<"[8] Problem 3\n";
cout<<"[9] Problem 4\n";
cout<<"[10] Problem 5\n";
cout<<"[11] Exit\n";
}
int Problem1(int a){
int counter(1);
FILE *fp;
fp=fopen("CAOILE_PAUL ANDREI1.txt","w");
if(!fp)
{
cout << "Cannot open file.\n";
system("pause");
}
cout<<
fputs("Name: Paul Andrei R. Caoile\nSection: E21\n Final Hands-On\nDate: 10.19.2016\n\n\n",fp);
do{
fprintf(fp,"%5d",counter);
counter+=1;
if(counter<a)
fprintf(fp,"%5d",counter);
counter+=2;
if(counter<a)
fprintf(fp,"%5d",counter);
counter+=4;
if(counter<a)
fprintf(fp,"%5d",counter);
counter+=3;
}while (counter<a);
fclose(fp);
}
int Problem2(int a){
int counter(1);
FILE *fp;
fp=fopen("CAOILE_PAUL ANDREI2.txt","w");
if(!fp)
{
cout << "Cannot open file.\n";
system("pause");
}
fputs("Name: Paul Andrei R. Caoile\nSection: E21\n Final Hands-On\nDate: 10.19.2016\n\n\n",fp);
do{
fprintf(fp,"%5d",counter);
counter+=1;
if(counter<a)
fprintf(fp,"%5d",counter);
counter+=2;
if(counter<a)
fprintf(fp,"%5d",counter);
counter+=4;
}while (counter<a);
fclose(fp);
}
int Problem3(int a){
int counter(1);
FILE *fp;
fp=fopen("CAOILE_PAUL ANDREI3.txt","w");
if(!fp)
{
cout << "Cannot open file.\n";
system("pause");
}
fputs("Name: Paul Andrei R. Caoile\nSection: E21\n Final Hands-On\nDate: 10.19.2016\n\n\n",fp);
do{
fprintf(fp,"%5d",counter);
counter+=2;
if(counter<a)
fprintf(fp,"%5d",counter);
counter+=6;
if(counter<a)
fprintf(fp,"%5d",counter);
counter+=7;
if(counter<a)
fprintf(fp,"%5d",counter);
counter+=5;
}while (counter<a);
fclose(fp);
}
int Problem4(int a){
int counter(1),secounter(2);
FILE *fp;
fp=fopen("CAOILE_PAUL ANDREI4.txt","w");
if(!fp)
{
cout << "Cannot open file.\n";
system("pause");
}
fputs("Name: Paul Andrei R. Caoile\nSection: E21\n Final Hands-On\nDate: 10.19.2016\n\n\n",fp);
do{
fprintf(fp,"%5d",secounter);
fprintf(fp,"%5d",counter);
secounter=secounter+counter;
counter++;
counter++;
}while (counter<a);
fclose(fp);
}
int Problem5(int a){
int counter(100);
FILE *fp;
fp=fopen("CAOILE_PAUL ANDREI5.txt","w");
if(!fp)
{
cout << "Cannot open file.\n";
system("pause");
}
fputs("Name: Paul Andrei R. Caoile\nSection: E21\n Final Hands-On\nDate: 10.19.2016\n\n\n",fp);
do{
fprintf(fp,"%7d",counter);
counter+=11;
}while (counter<a);
fclose(fp);
}
void Problem6(){
FILE *fp;
char buff[10000];
fp=fopen("CAOILE_PAUL ANDREI1.txt","r");
if(!fp){
cout << "Cannot open file.\n";
system("pause");
}
while(fgets(buff,10000,fp)!=NULL)
cout << buff;
fclose(fp);
system("pause>0");
}
void Problem7(){
FILE *fp;
char buff[10000];
fp=fopen("CAOILE_PAUL ANDREI2.txt","r");
if(!fp){
cout << "Cannot open file.\n";
system("pause");
}
while(fgets(buff,10000,fp)!=NULL)
cout << buff;
fclose(fp);
system("pause>0");
}
void Problem8(){
FILE *fp;
char buff[10000];
fp=fopen("CAOILE_PAUL ANDREI3.txt","r");
if(!fp){
cout << "Cannot open file.\n";
system("pause");
}
while(fgets(buff,10000,fp)!=NULL)
cout << buff;
fclose(fp);
system("pause>0");
}
void Problem9(){
FILE *fp;
char buff[10000];
fp=fopen("CAOILE_PAUL ANDREI4.txt","r");
if(!fp){
cout << "Cannot open file.\n";
system("pause");
}
while(fgets(buff,10000,fp)!=NULL)
cout << buff;
fclose(fp);
system("pause>0");
}
void Problem10(){
FILE *fp;
char buff[10000];
fp=fopen("CAOILE_PAUL ANDREI5.txt","r");
if(!fp){
cout << "Cannot open file.\n";
system("pause");
}
while(fgets(buff,10000,fp)!=NULL)
cout << buff;
fclose(fp);
system("pause>0");
}
|
Markdown
|
UTF-8
| 618 | 2.890625 | 3 |
[] |
no_license
|
# `cores`
## Purpose
Summarizes output from the Linux `lscpu` command. I must confess that I don't often think of using this one but I probably need to get more into the habit of using it. I'm not crazy about the name `cores` - I wonder if `cpus` would be easier for me to remember, etc.
## Syntax
```
Syntax: cores
```
### Options and arguments
There are no options or arguments
## Example
```
$ cores
CPU(s): 4
Core(s) per socket: 2
8
$
```
## Notes
- It likely won't work well from Windoze - perhaps it would work if you use [cygwin](https://www.cygwin.com). Personally, cygwin is a requirement on Windoze!
|
Java
|
UTF-8
| 371 | 1.804688 | 2 |
[] |
no_license
|
package com.murglin.consulting.roomoccupationservice.service;
import com.murglin.consulting.roomoccupationservice.model.BookingPlan;
import com.murglin.consulting.roomoccupationservice.model.dto.request.BookingPlanRequest;
public interface BookingPlanServiceI {
//TODO probably ACID transcation needed
BookingPlan plan(BookingPlanRequest bookingPlanRequest);
}
|
Java
|
UTF-8
| 330 | 1.84375 | 2 |
[] |
no_license
|
package br.com.fiap.ddd.ead.aula06.daoImpl;
import javax.persistence.EntityManager;
import br.com.fiap.ddd.ead.aula06.dao.AlunoDAO;
import br.com.fiap.ddd.ead.aula06.entity.Aluno;
public class AlunoDAOImpl extends GenericDAOImpl<Aluno, String> implements AlunoDAO {
public AlunoDAOImpl(EntityManager em) {
super(em);
}
}
|
Shell
|
UTF-8
| 405 | 3.1875 | 3 |
[
"Apache-2.0"
] |
permissive
|
#!/bin/bash
prog="testOnDemandR"
#try to gracefully terminate the server first
pid1=$(ps aux | grep ${prog} | grep -v "color" | awk '{print $2}')
kill -SIGUSR1 $pid1 > /dev/null 2>&1
sleep 1
#if it is still alive because of some unknown reason, force to stop it
pid2=$(ps aux | grep ${prog} | grep -v "color" | awk '{print $2}')
if [ "$pid1" == "$pid2" ]; then
kill -SIGTERM $pid2 > /dev/null 2>&1
fi
|
Java
|
UTF-8
| 1,562 | 2.421875 | 2 |
[] |
no_license
|
package com.example.menufy.fragments;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.example.menufy.R;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
public class InformationFragment extends Fragment implements View.OnClickListener{
private FloatingActionButton fabInformation;
public InformationFragment() {
// Required empty public constructor
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_information, container, false);
fabInformation = view.findViewById(R.id.fabInformation);
fabInformation.setOnClickListener(this::onClick);
return view;
}
@Override
public void onClick(View v) {
showAlertForShowingMoreInfo("Show more info", "there is more info about my app");
}
private void showAlertForShowingMoreInfo(String title, String message){
AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
if(title != null) builder.setTitle(title);
if(message != null) builder.setMessage(message);
builder.setNeutralButton("Ok", null);
AlertDialog dialog = builder.create();
dialog.show();
}
}
|
C++
|
UTF-8
| 1,853 | 3.28125 | 3 |
[
"LicenseRef-scancode-public-domain"
] |
permissive
|
#pragma once
#include <SFML/Graphics.hpp>
#include <string>
#include <map>
#include "Config.hpp"
class TextureManager
{
private:
/* Array of textures used */
std::map<std::string, sf::Texture> textures;
public:
void load(std::string name, int w, int h)
{
if (this->textures.count(name) == 0) {
sf::Texture tex;
tex.create(w, h);
this->textures[name] = tex;
}
return;
}
void load(std::string name, const std::string& filename)
{
if (this->textures.count(name) == 0) {
#ifdef MANAGER_DEBUG
std::cout << "TextureManager: load " << name << " from file " << filename << std::endl;
#endif
/* Load the texture */
sf::Texture tex;
tex.loadFromFile(filename);
/* Add it to the list of textures */
this->textures[name] = tex;
}
#ifdef MANAGER_DEBUG
else {
std::cout << "TextureManager: " << name << " already loaded" << std::endl;
}
#endif
return;
}
void load(std::string name, sf::Image img, const sf::IntRect &area) {
if (this->textures.count(name) == 0) {
#ifdef MANAGER_DEBUG
std::cout << "TextureManager: load " << name << " from image " << std::endl;
#endif
/* Load the texture */
sf::Texture tex;
tex.loadFromImage(img, area);
/* Add it to the list of textures */
this->textures[name] = tex;
}
#ifdef MANAGER_DEBUG
else {
std::cout << "TextureManager: " << name << " already loaded" << std::endl;
}
#endif
return;
}
sf::Texture& getRef(std::string name)
{
return this->textures.at(name);
}
bool hasRef(std::string name) {
return this->textures.count(name) > 0;
}
};
|
Swift
|
UTF-8
| 1,257 | 2.796875 | 3 |
[
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] |
permissive
|
//
// WikipediaAPI.swift
// Brunel
//
// Created by Aaron McTavish on 29/01/2016.
// Copyright © 2016 ustwo Fampany Ltd. All rights reserved.
//
import Foundation
import Moya
enum WikipediaAPI {
case queryTitle(title: String)
}
extension WikipediaAPI: TargetType {
var baseURL: URL { return URL(string: "https://en.wikipedia.org/w/api.php")! }
var path: String {
switch self {
case .queryTitle:
return ""
}
}
var method: Moya.Method {
switch self {
case .queryTitle:
return .get
}
}
var multipartBody: [MultipartFormData]? {
return nil
}
var parameterEncoding: ParameterEncoding {
return URLEncoding.default
}
var parameters: [String: Any]? {
switch self {
case let .queryTitle(title):
return ["action": "query",
"prop": "extracts",
"exintro": "",
"explaintext": "",
"titles": title]
}
}
var sampleData: Data {
let emptyStringData = "".data(using: String.Encoding.utf8)!
return emptyStringData
}
var task: Task {
return .request
}
}
|
Python
|
UTF-8
| 489 | 2.59375 | 3 |
[
"Apache-2.0"
] |
permissive
|
import matplotlib.pyplot as plt
def plot_augmentations(images, titles, sup_title):
fig, axes = plt.subplots(figsize=(20, 16), nrows=3, ncols=4, squeeze=False)
for indx, (img, title) in enumerate(zip(images, titles)):
axes[indx // 4][indx % 4].imshow(img)
axes[indx // 4][indx % 4].set_title(title, fontsize=15)
plt.tight_layout()
fig.suptitle(sup_title, fontsize = 20)
fig.subplots_adjust(wspace=0.2, hspace=0.2, top=0.93)
plt.show()
|
Java
|
UTF-8
| 3,929 | 4.0625 | 4 |
[] |
no_license
|
package zhh.algorithm.lucifer.basic.day1.array;
import org.junit.Assert;
/**
* @author zhanghao
* @date 2021-05-03 09:00
* @desc 双指针
*/
public class DoublePointer {
/**
* 42. 接雨水
* https://leetcode-cn.com/problems/trapping-rain-water/
* 输入:height = [0,1,0,2,1,0,1,3,2,1,2,1]
* 输出:6
*
* 输入:height = [4,2,0,3,2,5]
* 输出:9
*
* 只关心左右两侧较小的那一个,并不需要两者都计算出来。具体来说:
* 如果 l[i + 1] < r[i] 那么 最终积水的高度由 i 的左侧最大值决定。
* 如果 l[i + 1] >= r[i] 那么 最终积水的高度由 i 的右侧最大值决定。
* 因此我们不必维护完整的两个数组,而是可以只进行一次遍历,同时维护左侧最大值和右侧最大值,使用常数变量完成即可
*
* 时间复杂度:O(n)
* 空间复杂度:O(1)
*
* @param height
* @return
*/
public int trapRainWater(int[] height) {
int leftIndex = 0, rightIndex = height.length - 1;
int leftMaxHeight = 0, rightMaxHeight = 0;
int ans = 0;
while (leftIndex < rightIndex) {
if (height[leftIndex] < height[rightIndex]) {
leftMaxHeight = Math.max(leftMaxHeight, height[leftIndex]);
ans += (leftMaxHeight - height[leftIndex]);
leftIndex++;
} else {
rightMaxHeight = Math.max(rightMaxHeight, height[rightIndex]);
ans += (rightMaxHeight - height[rightIndex]);
rightIndex--;
}
}
return ans;
}
/**
* 11. 盛最多水的容器
* 给你 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0) 。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
* 说明:你不能倾斜容器。
*
* 示例 1:
*
* 输入:[1,8,6,2,5,4,8,3,7]
* 输出:49
* 解释:图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49。
*
* 示例 2:
* 输入:height = [1,1]
* 输出:1
*
* 示例 3:
* 输入:height = [4,3,2,1,4]
* 输出:16
*
* 示例 4:
* 输入:height = [1,2,1]
* 输出:2
*
* 提示:
* n = height.length
* 2 <= n <= 3 * 104
* 0 <= height[i] <= 3 * 104
*
* 链接:https://leetcode-cn.com/problems/container-with-most-water
*
* 时间复杂度:O(n)
* 空间复杂度:O(1)
* @param height
* @return
*/
public int maxArea(int[] height) {
int left = 0, right = height.length-1;
int maxArea = 0;
while (right > left) {
maxArea = Math.max(maxArea, (right - left) * Math.min(height[left], height[right]));
if (height[left] > height[right]) {
--right;
} else {
++left;
}
}
return maxArea;
}
public static void main(String[] args) {
DoublePointer doublePointer = new DoublePointer();
int[] trapInput = {0,1,0,2,1,0,1,3,2,1,2,1};
Assert.assertEquals(6,doublePointer.trapRainWater(trapInput));
int[] maxAreaInput1 = {1,8,6,2,5,4,8,3,7};
Assert.assertEquals(49, doublePointer.maxArea(maxAreaInput1));
int[] maxAreaInput2 = {1,1};
Assert.assertEquals(1, doublePointer.maxArea(maxAreaInput2));
int[] maxAreaInput3 = {4,3,2,1,4};
Assert.assertEquals(16, doublePointer.maxArea(maxAreaInput3));
int[] maxAreaInput4 = {1,2,1};
Assert.assertEquals(2, doublePointer.maxArea(maxAreaInput4));
}
}
|
Shell
|
UTF-8
| 610 | 2.75 | 3 |
[] |
no_license
|
#!/bin/bash
counts=`zcat query.uniprot20.hhr.gz | $PSSH/src/util/countHHblitsHits.pl`
stamp=`stat -c%Y query.uniprot20.hhr.gz`
md5=`fasta_to_md5 query.fasta`
DB.pssh2_local "insert into hhblits_family_counts set md5=\"$md5\" , $counts hh_stamp=$stamp ON DUPLICATE KEY UPDATE $counts hh_stamp=$stamp"
# to do this for many md5 sums, you can do this on the shell:
# foreach md5 ( ` tail -n +2 swissprot.20150610.uniq.md5 | head` )
# foreach? echo $md5
# foreach? cd `$PSSH/src/util/find_cache_path -m $md5`
# foreach? pwd
# foreach? $PSSH/src/util/DB_insert_countHHblitsHits.sh
# foreach? cd -
# foreach? end
|
Markdown
|
UTF-8
| 591 | 2.859375 | 3 |
[] |
no_license
|
# personal-profile-page
Description:
Creation of a personal profile page to showcase my personal and professional history
Structure:
This will include a main landing page with an introduction and contact information. It will also include a page for Work History (previous jobs, work acheivements, etc.) and Personal information (personal life, education, volunteer groups, etc.).
Purpose:
To fulfill the project requirements for Code Louisville course completion. Additionally, this will be uploaded (through GitHub) as a resource for potential employers during my ongoing job search.
|
SQL
|
UTF-8
| 255 | 2.5625 | 3 |
[] |
no_license
|
create or replace view `fishtown-interview-292223`.`dbt_atambay`.`my_second_dbt_model`
OPTIONS()
as -- Use the `ref` function to select from other models
select *
from `fishtown-interview-292223`.`dbt_atambay`.`my_first_dbt_model`
where id = 1;
|
PHP
|
UTF-8
| 859 | 3 | 3 |
[
"MIT"
] |
permissive
|
<?php
namespace Pinq\Iterators\Common;
use Pinq\Iterators\Standard\IIterator;
/**
* Common functionality for the adapter iterator
*
* @author Elliot Levin <elliotlevin@hotmail.com>
*/
trait AdapterIterator
{
/**
* @var \Traversable
*/
protected $source;
/**
* @var \Iterator
*/
protected $iterator;
public function __constructIterator(\Traversable $iterator)
{
$this->source = $iterator;
$this->iterator = $iterator instanceof \Iterator ? $iterator : new \IteratorIterator($iterator);
}
/**
* {@inheritDoc}
*/
final public function getSourceIterator()
{
return $this->source;
}
/**
* @return bool
*/
final public function isArrayCompatible()
{
return $this->source instanceof IIterator ? $this->source->isArrayCompatible() : false;
}
}
|
Java
|
UTF-8
| 2,911 | 2.5625 | 3 |
[
"Apache-2.0"
] |
permissive
|
package com.secuconnect.client.model;
import com.google.gson.annotations.SerializedName;
import java.util.Objects;
/**
* Bank details for withdrawals
*/
public class PaymentInformation {
@SerializedName("iban")
protected String iban = null;
@SerializedName("bic")
protected String bic = null;
@SerializedName("owner")
protected String owner = null;
@SerializedName("bankname")
protected String bankname = null;
public PaymentInformation iban(String iban) {
this.iban = iban;
return this;
}
/**
* International Bank Account Number (IBAN)
* @return iban
**/
public String getIban() {
return iban;
}
public void setIban(String iban) {
this.iban = iban;
}
public PaymentInformation bic(String bic) {
this.bic = bic;
return this;
}
/**
* Bank Identifier Code (BIC), or formerly SWIFT code
* @return bic
**/
public String getBic() {
return bic;
}
public void setBic(String bic) {
this.bic = bic;
}
public PaymentInformation owner(String owner) {
this.owner = owner;
return this;
}
/**
* Account owner name
* @return owner
**/
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public PaymentInformation bankname(String bankname) {
this.bankname = bankname;
return this;
}
/**
* Bank name
* @return bankname
**/
public String getBankname() {
return bankname;
}
public void setBankname(String bankname) {
this.bankname = bankname;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PaymentInformation paymentInformation = (PaymentInformation) o;
return Objects.equals(this.iban, paymentInformation.iban) &&
Objects.equals(this.bic, paymentInformation.bic) &&
Objects.equals(this.owner, paymentInformation.owner) &&
Objects.equals(this.bankname, paymentInformation.bankname);
}
@Override
public int hashCode() {
return Objects.hash(iban, bic, owner, bankname);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class PaymentInformation {\n");
sb.append(" iban: ").append(toIndentedString(iban)).append("\n");
sb.append(" bic: ").append(toIndentedString(bic)).append("\n");
sb.append(" owner: ").append(toIndentedString(owner)).append("\n");
sb.append(" bankname: ").append(toIndentedString(bankname)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
C++
|
UTF-8
| 2,520 | 3.3125 | 3 |
[] |
no_license
|
//============= Copyright Connor McLaughlan, All rights reserved. =============
//
// Purpose: Linear algebra classes.
//
// Notes:
// - [https://www.cprogramming.com/tutorial/3d/quaternions.html]
//
//=============================================================================
#pragma once
#include <cmath>
#include "vec.h"
/* Quaternion class */
class Quat {
public:
Quat() : w(1.0f), v(0.0f) {}
Quat(float _w, float _x, float _y, float _z) : w(_w), v(_x,_y,_z) {}
Quat(float _w, const Vec3 &_v) : w(_w), v(_v) {}
Quat(const Quat& other) :
w(other.w),
v(other.v)
{ }
Quat& operator=(const Quat& other) {
if (this == &other) return *this;
w = other.w;
v = other.v;
return *this;
}
inline void set(float _w, float _x, float _y, float _z) {
this->w = _w;
this->v = Vec3(_x,_y,_z);
return;
}
inline void set(float _w, const Vec3 &_v) {
this->w = _w;
this->v = _v;
return;
}
inline void zero() {
this->w = 0.0f;
this->v = Vec3(0.0f);
return;
}
inline void identity() {
this->w = 1.0f;
this->v = Vec3(0.0f);
return;
}
inline float length() {
return sqrt(w*w + v*v);
}
Quat normalize() {
float length = this->length();
this->w /= length;
this->v = this->v * (1/length);
return *this;
}
Mat4 getMatrix() {
const float &x = this->v.x;
const float &y = this->v.y;
const float &z = this->v.z;
Mat4 rMatrix = Mat4(
(w*w + x*x - y*y - z*z), (2*x*y - 2*w*z), (2*x*z + 2*w*y), 0,
(2*x*y + 2*w*z), (w*w - x*x + y*y - z*z), (2*y*z + 2*w*x), 0,
(2*x*z - 2*w*y), (2*y*z - 2*w*x), (w*w - x*x - y*y + z*z), 0,
0, 0, 0, 1
);
return rMatrix;
}
Quat operator*(Quat &q) {
Quat tQ = Quat();
const float &wo = q.w;
const Vec3 &vo = q.v;
float tW = w*wo - v.x*vo.x - v.y*vo.y - v.z*vo.z;
float tX = w*vo.x + v.x*wo + v.y*vo.z - v.z*vo.y;
float tY = w*vo.y + v.x*vo.y - v.y*vo.x + v.z*wo;
float tZ = w*vo.z + v.x*vo.y - v.y*vo.x + v.z*wo;
tQ.w = tW;
tQ.v = Vec3(tX,tY,tZ);
return tQ;
}
friend Quat operator*( float a, const Quat& vo) {
return Quat(a * vo.w, a * vo.v.x, a * vo.v.y, a * vo.v.z);
}
float w;
Vec3 v;
};
|
Python
|
UTF-8
| 202 | 2.703125 | 3 |
[] |
no_license
|
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# author:艾强云
# Email:1154282938@qq.com
# datetime:2019/4/5 01:56
# software: PyCharm
import numpy as np
x = np.random.rand(10)
print(x)
b = x[x > 0.5]
print(b)
|
C++
|
UTF-8
| 433 | 3.0625 | 3 |
[] |
no_license
|
#include<iostream>
using namespace std;
void last_index(int arr[],int n,int m,int i,int k)
{
//base case
if(n==0)
{
cout<<k<<endl;
return;
}
//recursive case
if(arr[i]==m)
{
k=i;
last_index(arr,n-1,m,i+1,k);
//cout<<k<<endl;
}
last_index(arr,n-1,m,i+1,k);
}
int main() {
int n,*arr;
int m;
cin>>n;
arr=new int[n];
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
cin>>m;
last_index(arr,n,m,0,-1);
return 0;
}
|
Java
|
UTF-8
| 3,163 | 2.15625 | 2 |
[] |
no_license
|
package com.mockuai.data.check.canal;
import com.alibaba.otter.canal.protocol.CanalEntry;
import com.alibaba.otter.canal.protocol.FlatMessage;
import com.google.common.collect.Lists;
import com.mockuai.data.check.dto.DataEventType;
import com.mockuai.data.check.dto.DataStoreMappingUtils;
import com.mockuai.data.check.dto.EventData;
import com.mockuai.data.check.dto.PropertyValue;
import com.mockuai.data.check.dto.RowValue;
import com.mockuai.data.check.strategy.DataCheckStrategy;
import com.mockuai.data.check.strategy.DataCheckStrategyHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.Map;
/**
* @author : yangqi
* @email : lukewei@mockuai.com
* @description :
* @since : 2020-08-23 17:56
*/
@Slf4j
@Component
public class HandleCanalMessage {
/**
* 需要处理的event类型
*/
private static final List<String> HANDLE_EVENT_TYPES = Lists.newArrayList(CanalEntry.EventType.INSERT.toString(), CanalEntry.EventType.UPDATE.toString());
public void consumer(FlatMessage flatMessage) {
String eventType = flatMessage.getType();
String dataStore = this.getDataStoreName(flatMessage);
log.info("================> dataStore {} eventType : {}", dataStore, eventType);
if (!DataStoreMappingUtils.containDataStore(dataStore)) {
log.info("表不在监听处理范围内 dataStore {}", dataStore);
return;
}
if (!HANDLE_EVENT_TYPES.contains(eventType)) {
log.info("eventType 不处理 eventType {}", eventType);
return;
}
List<EventData> list = buildEventData(flatMessage, dataStore);
for (EventData eventData : list) {
List<DataCheckStrategy> strategyList = DataCheckStrategyHolder.getStrategyList();
for (DataCheckStrategy dataCheckStrategy : strategyList) {
dataCheckStrategy.comparison(eventData);
}
}
}
public List<EventData> buildEventData(FlatMessage flatMessage, String dataStore) {
DataEventType dataEventType = DataEventType.getEventType(flatMessage.getType());
List<Map<String, String>> afterColumnsList = flatMessage.getData();
List<EventData> list = Lists.newArrayListWithExpectedSize(afterColumnsList.size());
for (Map<String, String> columnMap : afterColumnsList) {
EventData eventData = new EventData();
List<PropertyValue> afterList = Lists.newArrayList();
columnMap.forEach((key, value) -> afterList.add(PropertyValue.build(key, value)));
RowValue afterValue = RowValue.build(afterList, dataStore);
afterValue.setOccourTime(flatMessage.getEs());
eventData.setEventType(dataEventType)
.setOccourTime(afterValue.getOccourTime())
.setDataStore(dataStore)
.setRowValue(afterValue);
list.add(eventData);
}
return list;
}
private String getDataStoreName(FlatMessage flatMessage) {
return flatMessage.getDatabase() + "." + flatMessage.getTable();
}
}
|
Shell
|
UTF-8
| 2,855 | 2.796875 | 3 |
[
"MIT"
] |
permissive
|
#!/usr/bin/env bash
set -e
if [[ -n "${DEBUG}" ]]; then
set -x
fi
varnish() {
docker-compose exec -T varnish "${@}"
}
docker-compose up -d
echo -n "Running check-ready action... "
varnish make check-ready max_try=10 -f /usr/local/bin/actions.mk
echo "OK"
echo -n "Running flush action... "
varnish make flush -f /usr/local/bin/actions.mk
echo "OK"
us_ip="185.229.59.42"
echo -n "Checking healthz endpoint... "
varnish curl -s -o /dev/null -w '%{http_code}' "localhost:6081/.vchealthz" | grep -q 204
echo "OK"
echo -n "Checking varnish backend response containing a country code header detected via geoip module... "
docker-compose exec -T php sh -c 'echo "<?php var_dump(\$_SERVER[\"HTTP_X_COUNTRY_CODE\"]);" > /var/www/html/index.php'
varnish curl --header "X-Real-IP: ${us_ip}" -s "localhost:6081" | grep -q "US"
varnish make flush -f /usr/local/bin/actions.mk
echo "OK"
echo -n "Checking varnish backend response containing the currency... "
docker-compose exec -T php sh -c 'echo "<?php var_dump(\$_SERVER[\"HTTP_X_CURRENCY\"]);" > /var/www/html/index.php'
varnish curl --header "X-Real-IP: ${us_ip}" -s "localhost:6081" | grep -q "USD"
varnish make flush -f /usr/local/bin/actions.mk
echo "OK"
echo -n "Checking varnish backend response containing the currency (from Cloudflare \"CF-IPCountry\" header)... "
docker-compose exec -T php sh -c 'echo "<?php var_dump(\$_SERVER[\"HTTP_X_CURRENCY\"]);" > /var/www/html/index.php'
varnish curl --header "CF-IPCountry: US" -s "localhost:6081" | grep -q "USD"
varnish make flush -f /usr/local/bin/actions.mk
echo "OK"
echo -n "Checking varnish VCKEY cookies... "
docker-compose exec -T php sh -c 'echo "<?php echo(\"Hello World\");" > /var/www/html/index.php'
varnish sh -c 'curl -sI -b "VCKEYinvalid=123" localhost:6081 | grep -q "X-VC-Cache: MISS"'
varnish sh -c 'curl -sI -b "VCKEYinvalid=123" localhost:6081 | grep -q "X-VC-Cache: MISS"'
varnish sh -c 'curl -sI -b "VCKEY-.invalid=123" localhost:6081 | grep -q "X-VC-Cache: MISS"'
varnish sh -c 'curl -sI -b "VCKEY-.invalid=123" localhost:6081 | grep -q "X-VC-Cache: MISS"'
varnish sh -c 'curl -sI -b "vckey-invalid=123" localhost:6081 | grep -q "X-VC-Cache: MISS"'
varnish sh -c 'curl -sI -b "vckey-invalid=123" localhost:6081 | grep -q "X-VC-Cache: MISS"'
varnish sh -c 'curl -sI -b "VCKEY-valid=123" localhost:6081 | grep -q "X-VC-Cache: MISS"'
varnish sh -c 'curl -sI -b "VCKEY-valid=123" localhost:6081 | grep -q "X-VC-Cache: HIT"'
varnish sh -c 'curl -sI -b "VCKEY-valid=123; VCKEY-multiple-cookies_1=123;" localhost:6081 | grep -q "X-VC-Cache: MISS"'
varnish sh -c 'curl -sI -b "VCKEY-valid=123; VCKEY-multiple-cookies_1=123;" localhost:6081 | grep -q "X-VC-Cache: HIT"'
varnish sh -c 'curl -sI -b "VCKEY-valid=123; VCKEY-multiple-cookies_1=321;" localhost:6081 | grep -q "X-VC-Cache: MISS"'
echo "OK"
docker-compose down
|
Python
|
UTF-8
| 163 | 3.46875 | 3 |
[] |
no_license
|
num = int(input())
while num != 0:
quadrados = 0
for i in range(1, num+1):
quadrados += i * i
print(quadrados)
num = int(input())
|
C#
|
UTF-8
| 1,920 | 2.859375 | 3 |
[] |
no_license
|
using Datos;
using Entity;
using System;
using System.Collections.Generic;
namespace Logica
{
public class DatosService
{
private readonly ConnectionManager _conexion;
private readonly DatosRepository _repositorio;
public DatosService(string connectionString)
{
_conexion = new ConnectionManager(connectionString);
_repositorio = new DatosRepository(_conexion);
}
public GuardarDatosResponse Guardar(DatosCopago datos)
{
try
{
if(datos.ValorServicio < 0 || datos.SalarioTrabajador < 0){
return new GuardarDatosResponse("Error. Ni el valor del servicio ni el salario pueden ser menores de cero");
}else{
datos.CalcularCopago();
_conexion.Open();
_repositorio.Guardar(datos);
_conexion.Close();
return new GuardarDatosResponse(datos);
}
}
catch (Exception e)
{
return new GuardarDatosResponse($"Error de la Aplicacion: {e.Message}");
}
finally { _conexion.Close(); }
}
public List<DatosCopago> ConsultarTodos()
{
_conexion.Open();
List<DatosCopago> listadatos = _repositorio.ConsultarTodos();
_conexion.Close();
return listadatos;
}
}
public class GuardarDatosResponse
{
public GuardarDatosResponse(DatosCopago datos)
{
Error = false;
DatosCopago = datos;
}
public GuardarDatosResponse(string mensaje)
{
Error = true;
Mensaje = mensaje;
}
public bool Error { get; set; }
public string Mensaje { get; set; }
public DatosCopago DatosCopago { get; set; }
}
}
|
Python
|
UTF-8
| 339 | 3.703125 | 4 |
[
"MIT"
] |
permissive
|
#!/usr/bin/python3
def is_kind_of_class(obj, a_class):
"""checks if an object is sort of a class
-> through inheritance
"""
if not isinstance(a_class, type):
raise TypeError("a_class type must be 'type'")
if isinstance(obj, a_class) or issubclass(type(obj), a_class):
return True
return False
|
C++
|
UTF-8
| 424 | 3 | 3 |
[] |
no_license
|
#include <iostream>
#include <fstream>
using namespace std;
int main(int argc, char const *argv[])
{
//1. taking input from a text file
// freopen("input.txt", "r", stdin);
//2. printing output to text file
// freopen("output.txt", "w", stdout);
std::ios::sync_with_stdio(false);
int number;
while (true)
{
cin >> number;
if (number == 42)
{
break;
}
cout << number << "\n";
}
return 0;
}
|
Python
|
UTF-8
| 2,909 | 2.65625 | 3 |
[] |
no_license
|
import report_queries as rq
import codecs
import pdfkit
file_path = "output/kvalitet/"
index_path = file_path+"izvestaj_kvalitet.html"
def faculty_reports():
index.write("<h3>Opšta pitanja</h3>")
pitanja = rq.get_faculty_questions_reports()
for tekst_pitanja, ocene in pitanja.items():
index.write(tekst_pitanja + "<br><br>")
index.write("Prosečna ocena: " + str(round(ocene['prosecna_ocena'], 2)) + "<br>")
index.write("Ukupno glasalo: " + str(ocene['ukupno']) + "<br>")
for ocena in range(1, 6):
index.write("\t" + str(ocena) + ": ")
index.write(str(ocene[ocena]['broj_glasova']) + " glasova ")
index.write("(" + str(ocene[ocena]['procenat']) + "%)<br>")
index.write("<br><br>")
primedbe = rq.get_faculty_primedbe()
index.write("<br><h3>Primedbe/zamerke:</h3>")
for p in primedbe:
if (p):
index.write(p)
index.write("<br>-----------------------------------------------------------------<br>")
def subject_reports_for_teachers():
predmeti = rq.get_all_subjects()
for p in predmeti.keys():
index.write("<h3>Predmet: "+p+"</h3>")
if rq.get_has_answers_subject(predmeti[p]):
index.write("Prosečna ocene za predmet: ")
avg = rq.get_subject_avg(predmeti[p])
index.write(avg[0] + " ("+avg[1]+")")
index.write("<br>")
else:
index.write("Nema odgovora")
teachers = rq.get_teachers_for_subject(predmeti[p])
for t in teachers:
if rq.get_has_answers_teacher(predmeti[p],t[4]):
index.write(t[0]+" " +t[1]+ " (" + t[3] + ")" + ": ")
avg_prof = rq.get_teacher_avg(t[4],predmeti[p])
index.write(avg_prof[0] + " ("+avg_prof[1]+")")
index.write("<br>")
with codecs.open(index_path, "w+", "utf-8") as index:
index.write("<html>")
index.write("<head><meta charset='UTF-8'></meta></head>")
index.write("<body style='letter-spacing:1px';'font-family:Arial'>")
index.write("<h2>Računarski fakultet</h2><h2>Rezultati studentske ankete za parni semestar školske 2017/2018. godine</h2><br>")
faculty_reports()
index.write("<br><h2>Prosečne ocene za predmete i nastavnike</h2><br>")
subject_reports_for_teachers()
index.write("</body>")
index.write("</html>")
options = {
'page-size': 'A4',
'margin-top': '0.75in',
'margin-right': '0.75in',
'margin-bottom': '0.75in',
'margin-left': '0.75in',
'encoding': "UTF-8"
}
pdfkit.from_file(index_path, file_path+"izvestaj-ankete-parni201718.pdf", options)
|
C#
|
UTF-8
| 5,700 | 2.5625 | 3 |
[] |
no_license
|
using System;
using IMDBService;
using TechTalk.SpecFlow;
using IMDBRepository;
using System.Linq;
using TechTalk.SpecFlow.Assist;
using IMDBDomain;
namespace IMDBTests
{
[Binding]
public class application
{
private readonly ScenarioContext _scenarioContext;
public application(ScenarioContext scenarioContext)
{
_scenarioContext = scenarioContext;
}
private string mname, aname, pname, adob, pdob, plot,actors;
private int year, aid, pid;
private ApplicationService _applicationService = new ApplicationService();
private ProducerRepository _producerRepo = new ProducerRepository();
private ActorRepository _actorRepo = new ActorRepository();
private MovieRepository _movieRepo = new MovieRepository();
[Given(@"I have a movie with name ""(.*)""")]
public void GivenIHaveAMovieWithName(string p0)
{
mname = p0;
}
[Given(@"Year of Release is (.*)")]
public void GivenYearOfReleaseIs(int p0)
{
year = p0;
}
[Given(@"plot is ""(.*)""")]
public void GivenPlotIs(string p0)
{
plot = p0;
}
[Given(@"ID of the producer is (.*)")]
public void GivenIDOfTheProducerIs(int p0)
{
pid = p0;
}
[Given(@"Id of the actor is ""(.*)""")]
public void GivenIdOfTheActorIs(string p0)
{
actors = p0;
}
[When(@"I add the movie to movielist")]
public void WhenIAddTheMovieToMovielist()
{
_applicationService.AddActor("Brad Pitt", "12/18/1963");
_applicationService.AddActor("Leon", "11/18/1966");
_applicationService.AddProducer("James Mangold", "12/16/1963");
_applicationService.AddMovie(mname,plot,year,pid,actors);
}
[Then(@"my movielist should look like this")]
public void ThenMyMovielistShouldLookLikeThis(Table table)
{
var movie = _applicationService.GetAllMovies();
table.CompareToSet(movie.Select(movie=>new Movie { ID=movie.ID , Name = movie.Name, Plot = movie.Plot, Year = movie.Year, Producer = movie.Producer}));
}
[Then(@"My Actorr List Should Look Like This")]
public void ThenMyActorrListShouldLookLikeThis(Table table)
{
var actors = _applicationService.GetAllActors();
table.CompareToSet(actors.Select(actors => new Actor { ID = actors.ID, Name = actors.Name, DOB = actors.DOB }));
}
//addActor
[Given(@"I have an actor with name ""(.*)""")]
public void GivenIHaveAnActorWithName(string p0)
{
aname = p0;
}
[Given(@"Date of Birth of Actor is ""(.*)""")]
public void GivenDateOfBirthOfActorIs(string p0)
{
adob = p0;
}
[When(@"I add the actor")]
public void WhenIAddTheActor()
{
_applicationService.AddActor(aname,adob);
}
[Then(@"my actorlist should look like this")]
public void ThenMyActorlistShouldLookLikeThis(Table table)
{
var actors = _applicationService.GetAllActors();
table.CompareToSet(actors.Select(actors => new Actor { ID = actors.ID, Name = actors.Name, DOB = actors.DOB }));
}
//addProducer
[Given(@"I have a producer with name ""(.*)""")]
public void GivenIHaveAProducerWithName(string p0)
{
pname = p0;
}
[Given(@"Date of Birth of producer is ""(.*)""")]
public void GivenDateOfBirthOfProducerIs(string p0)
{
pdob = p0;
}
[When(@"I add the producer")]
public void WhenIAddTheProducer()
{
_applicationService.AddProducer(pname,pdob);
}
[Then(@"my producerlist should look like this")]
public void ThenMyProducerlistShouldLookLikeThis(Table table)
{
var pro = _applicationService.GetAllProducers();
table.CompareToSet(pro.Select(pro => new Actor { ID = pro.ID, Name = pro.Name, DOB = pro.DOB }));
}
//listMovies
[Given(@"I have a list of movies")]
public void GivenIHaveAListOfMovies()
{
_applicationService.AddActor("Brad Pitt", "12/18/1963");
_applicationService.AddActor("Leon", "11/18/1966");
_applicationService.AddProducer("James Mangold", "12/16/1963");
}
[When(@"I fetch my movielist")]
public void WhenIFetchMyMovielist()
{
_applicationService.AddMovie("Ford v Ferrari", "Car Movie",2019,1,"1 2");
}
[Then(@"I should have the following movies")]
public void ThenIShouldHaveTheFollowingMovies(Table table)
{
var movie = _applicationService.GetAllMovies();
table.CompareToSet(movie.Select(movie => new Movie { ID = movie.ID, Name = movie.Name, Plot = movie.Plot, Year = movie.Year, Producer = movie.Producer }));
}
[Then(@"My Actor List Should Look Like This")]
public void ThenMyActorListShouldLookLikeThis(Table table)
{
var actors = _applicationService.GetAllActors();
table.CompareToSet(actors.Select(actors => new Actor { ID = actors.ID, Name = actors.Name, DOB = actors.DOB }));
}
[Then(@"Producer Looks Like This")]
public void ThenProducerLooksLikeThis(Table table)
{
var producer = _applicationService.GetAllProducers();
table.CompareToSet(producer);
}
}
}
|
Java
|
UTF-8
| 248 | 1.515625 | 2 |
[] |
no_license
|
package br.com.l0k0s.portal.interfaces.repositorio;
import br.com.l0k0s.portal.interfaces.InterfaceGenericRepositorio;
import br.com.l0k0s.portal.model.Titulo;
public interface TituloRepositorio extends InterfaceGenericRepositorio<Titulo> {
}
|
Java
|
UTF-8
| 1,298 | 2.3125 | 2 |
[] |
no_license
|
package com.fancypants.websocket.app.controller;
import java.security.Principal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.messaging.simp.annotation.SubscribeMapping;
import org.springframework.stereotype.Controller;
import com.fancypants.websocket.container.SessionContainer;
@Controller
public class DeviceController {
private static final Logger LOG = LoggerFactory.getLogger(DeviceController.class);
@Autowired
private SessionContainer sessionContainer;
@SubscribeMapping("/topic/device/notifications")
public void handleNotificationSubscription(Principal user, Message<?> message) {
LOG.trace("DeviceController.handleNotificationSubscription enter" + " user" + user + " message" + message);
// only allowed to subscribe if they are registered
if (false == sessionContainer.isRegistered()) {
throw new IllegalAccessError("must be registered to subscribe to notifications");
}
// map subscriptions to the actual device topic
// this.template.convertAndSend("/topic/device." + user.getName(),
// message.getPayload(), message.getHeaders());
LOG.trace("DeviceController.handleNotificationSubscription exit");
}
}
|
Ruby
|
UTF-8
| 9,799 | 4.40625 | 4 |
[] |
no_license
|
# Today we'll be creating a Task List for an individual who has a lot of errands and tasks to complete and multiple locations or stores to go to in order to complete them.
# Release 1
# Create a class for a Task List.
# All TaskList instances should have an owner and a due date passed in on creation. For instance, our owner could be "Tyler" and his due date would be "Sunday". The owner should not be changeable but you should be able to read it outside of the class. The due date should be readable and writeable outside of the class.
# class TaskList
# attr_reader :owner
# attr_accessor :due_date
# def initialize(owner, due_date)
# @owner = owner
# @due_date = due_date
# end
# end
# list = TaskList.new("Andrew", "Thursday")
# p list.owner # "Andrew"
# p list.due_date # "Thursday"
# list.due_date = "Friday"
# p list.due_date # "Friday"
# Release 2
# We may have multiple locations to go to in order to complete our tasks, for instance we may need to go to Target to pick up batteries. Create a list instance variable which can hold the location and tasks at each location. It should be empty on creation.
# When we think of a new location we need to go to, we'll need to save it in our list and set it up to hold multiple tasks. Create an instance method that will save the new location to the list with the ability to hold multiple tasks. If the location already exists in our list, notify the user that the location is already on the list.
# class TaskList
# attr_reader :owner
# attr_accessor :due_date
# def initialize(owner, due_date)
# @owner = owner
# @due_date = due_date
# @list = {} # keys: location, values: tasks at each location
# end
# def new_location(location)
# if @list[location].nil?
# @list[location] = []
# else
# puts "You already have the location #{location} on your list. Now add some tasks!"
# end
# end
# end
# list = TaskList.new("Andrew", "Thursday")
# p list.new_location("Target") # []
# p list.new_location("Target") # nil
# Release 3
# When we add a new task to the list, we'll need to also say which location the task should be completed. Create an instance method to save a task and its location to the list.
# If the location doesn't exist in the list yet, we'll need to create it, and then add the task. If the location already exists, then we'll need to check if that task already exists for the location. Check if that tasks is in our records for the location, if it's not, add it. If the task already exists, notify the user that the task is already on their list!
# class TaskList
# attr_reader :owner
# attr_accessor :due_date
# def initialize(owner, due_date)
# @owner = owner
# @due_date = due_date
# @list = {} # keys: location, values: tasks at each location
# end
# # { "Target" => ["pick up some batteries", "pick up a clothesline"] }
# def new_location(location)
# if @list[location].nil?
# @list[location] = []
# else
# puts "You already have the location #{location} on your list. Now add some tasks!"
# end
# end
# def add_task(task, location)
# new_location(location)
# if @list[location].include?(task)
# puts "You already have the task #{task} on your list! Try another one!"
# else
# @list[location] << task
# end
# end
# end
# list = TaskList.new("Andrew", "Thursday")
# list.new_location("Target")
# p list.add_task("pick up some batteries", "Target")
# Release 4
# Congrats, you completed a task - cross it off your list! Create an instance method to delete a task off its location records. If the specified location includes the task, delete it. If the specified location does not include the task, notify the user that they don't have that task on their list.
# class TaskList
# attr_reader :owner
# attr_accessor :due_date
# def initialize(owner, due_date)
# @owner = owner
# @due_date = due_date
# @list = {} # keys: location, values: tasks at each location
# end
# def new_location(location)
# if @list[location].nil?
# @list[location] = []
# else
# puts "You already have the location #{location} on your list. Now add some tasks!"
# end
# end
# def add_task(task, location)
# new_location(location)
# if @list[location].include?(task)
# puts "You already have the task #{task} on your list! Try another one!"
# else
# @list[location] << task
# end
# end
# def remove_task(task, location)
# if @list[location] && @list[location].include?(task)
# @list[location].delete(task)
# else
# puts "You don't have the task #{task} at #{location}. Maybe you had it somewhere else"
# end
# end
# end
# list = TaskList.new("Andrew", "Thursday")
# list.new_location("Target")
# p list.add_task("pick up some batteries", "Target")
# p list.add_task("pick up some milk", "Stan's donuts")
# p list.remove_task("pick up some batteries", "Target")
# Release 5
# Wow, you sure have a lot to do! Print out your list in a user friendly way, printing each location and then each of the tasks needed to be accomplished there below it. Like the following:
# At Target:
# - pick up batteries
# - get new toothpaste
# At pet store:
# - pick out new chew toy
# At post office:
# - mail Grandma's birthday present
# - buy new stamps
# class TaskList
# attr_reader :owner
# attr_accessor :due_date
# def initialize(owner, due_date)
# @owner = owner
# @due_date = due_date
# @list = {} # keys: location, values: tasks at each location
# end
# def new_location(location)
# if @list[location].nil?
# @list[location] = []
# else
# puts "You already have the location #{location} on your list. Now add some tasks!"
# end
# end
# def add_task(task, location)
# new_location(location)
# if @list[location].include?(task)
# puts "You already have the task #{task} on your list! Try another one!"
# else
# @list[location] << task
# end
# end
# def remove_task(task, location)
# if @list[location] && @list[location].include?(task)
# @list[location].delete(task)
# else
# puts "You don't have the task #{task} at #{location}. Maybe you had it somewhere else"
# end
# end
# def print_list
# puts "#{owner}'s Task List!"
# puts "Due #{due_date}."
# puts #line break
# # For each location
# @list.each do |location, tasks|
# if tasks.length > 0
# # print "At location"
# puts "At #{location}:"
# # For each task in the location's list
# tasks.each do |task|
# # print the task name
# puts "- #{task}"
# end
# end
# end
# end
# end
# list = TaskList.new("Andrew", "Thursday")
# list.new_location("Target")
# list.add_task("pick up batteries", "Target")
# list.add_task("pick up milkshakes", "Stan's donuts")
# list.add_task("pick up doge food", "Target")
# list.remove_task("pick up milkshakes", "Stan's donuts")
# list.new_location("Costco")
# list.print_list
# Release 6
# Uh oh, have you done everything on your task list by the due date? Create a predicate instance method #is_past_due? that uses the current day as an argument and checks to see if your task list is past due. You'll need to compare the days of the week to each other in some way. Don't forget that if you have no tasks on your list, then nothing is past due!
class TaskList
attr_reader :owner
attr_accessor :due_date
def initialize(owner, due_date)
@owner = owner
@due_date = due_date
@list = {} # keys: location, values: tasks at each location
end
def new_location(location)
if @list[location].nil?
@list[location] = []
# else
# puts "You already have the location #{location} on your list. Now add some tasks!"
end
end
def add_task(task, location)
new_location(location)
if @list[location].include?(task)
puts "You already have the task #{task} on your list! Try another one!"
else
@list[location] << task
end
end
def remove_task(task, location)
if @list[location] && @list[location].include?(task)
@list[location].delete(task)
else
puts "You don't have the task #{task} at #{location}. Maybe you had it somewhere else"
end
end
def print_list
puts "#{owner}'s Task List!"
puts "Due #{due_date}."
puts #line break
# For each location
@list.each do |location, tasks|
if tasks.length > 0
# print "At location"
puts "At #{location}:"
# For each task in the location's list
tasks.each do |task|
# print the task name
puts "- #{task}"
end
end
end
end
def is_past_due?(current_day)
days_of_week = [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
]
if @list.values.all? {|tasks| tasks.empty?}
puts "You have no more tasks. Great job!"
false
else
if days_of_week.index(current_day) < days_of_week.index(due_date)
puts "You still have time to complete these tasks! Hurry up!"
false
else
puts "Your list is overdue! Tsk tsk."
true
end
end
end
end
list = TaskList.new("Andrew", "Thursday")
# list.new_location("Target")
list.add_task("pick up batteries", "Target")
list.add_task("pick up milkshakes", "Stan's donuts")
list.add_task("pick up doge food", "Target")
list.remove_task("pick up milkshakes", "Stan's donuts")
# list.remove_task("pick up batteries", "Target")
# list.remove_task("pick up doge food", "Target")
list.new_location("Costco")
list.print_list
list.is_past_due?("Wednesday") # false
# p list.is_past_due?("Friday") # true
|
Markdown
|
UTF-8
| 1,125 | 3 | 3 |
[] |
no_license
|
# Article 77
Le président de la Polynésie française, au moment de son élection, le vice-président et les ministres, au moment de leur désignation, doivent, lorsqu'ils se trouvent dans l'un des cas d'incompatibilité prévus aux articles 75 et 76, déclarer leur option au haut-commissaire dans le délai d'un mois suivant leur entrée en fonction.
Si la cause de l'incompatibilité est postérieure, selon le cas, à l'élection ou à la désignation, le droit d'option prévu à l'alinéa précédent est ouvert pendant le mois suivant la survenance de la cause de l'incompatibilité.
A défaut d'avoir exercé son option dans les délais, le président de la Polynésie française, le vice-président ou le ministre est réputé avoir renoncé à ses fonctions de président ou de membre du gouvernement de la Polynésie française.
L'option exercée ou le défaut d'option est constaté par un arrêté du haut-commissaire. Cet arrêté est notifié au président de la Polynésie française, au président de l'assemblée de la Polynésie française et, le cas échéant, au membre du gouvernement intéressé.
|
Markdown
|
UTF-8
| 1,398 | 3.359375 | 3 |
[] |
no_license
|
# Verify Account
If deployed: https://thedanitor.github.io/verify_account/
This project is from the Day 41 code along video from Udemy's 50 projects in 50 days series focused on web development. I have added some comments to the CSS and JavaScript to make notes to myself why certain choices are being made and what particular lines of code do.
### Overall Impression
This project was to make the UI for an account verification code input box. We made an input box for each digit and shifted the cursor to the next box once a digit was entered. I've used this type of interface plenty of times, but hadn't really considered how it works (on the front end at least). It wasn't a lot of code, but I would not have thought to use the .focus() method to move to the next box as soon as a valid number was entered. I think the lesson here is not to take any part of the UI for granted, even if it isn't flashy.
### Things Learned
* There is a ```:valid``` pseudo-class that targets any input or form element whose contents validate successfully.
* There are "spinner" widgets in some input elements. They can be removed with ```-moz-appearance: textfield;``` in Firefox and
```.code::-webkit-outer-spin-button,```
```.code::-webkit-inner-spin-button {```
```-webkit-appearance: none;```
```margin: 0;```
```}```
in Chrome, Safari
* ```.focus()``` method moves the cursor to the element.
|
PHP
|
UTF-8
| 1,645 | 2.78125 | 3 |
[] |
no_license
|
<?php
/**
* Date: 05.06.19
* Time: 16:06
* @author Konstantin Maruhnich <nocturneumbra@gmail.com>
* Iterios core team
*/
namespace Decadal\LiftTest\Zend;
use PHPUnit\Framework\TestCase;
use Decadal\Lift\Common\Enum\EnumInterface;
use Decadal\Lift\Common\Enum\EnumTrait;
use Decadal\Lift\Common\Zend\Validator\EnumValidator;
class SampleEnum implements EnumInterface
{
use EnumTrait;
const VALUE1 = 'value1';
const VALUE2 = 'value2';
const VALUE3 = '3';
}
class EnumValidatorTest extends TestCase
{
/**
* @throws \Exception
*/
public function testEnumIsNotSetted()
{
$this->expectException(\Exception::class);
$enumValidator = new EnumValidator();
$enumValidator->isValid("1");
}
/**
* @throws \Exception
*/
public function testEnumIsInvalid()
{
$this->expectException(\TypeError::class);
new EnumValidator(['enum' => 1]);
}
/**
* @throws \Exception
*/
public function testEnumValidation()
{
$enumValidator = new EnumValidator(['enum' => new SampleEnum]);
$this->assertSame(true, $enumValidator->isValid("value1"));
$this->assertSame(true, empty($enumValidator->getMessages()));
$this->assertSame(false, $enumValidator->isValid("VALUE1"));
$this->assertSame(true, !empty($enumValidator->getMessages()));
$this->assertSame(false, $enumValidator->isValid("555555"));
$enumValidator = new EnumValidator(['enum' => new SampleEnum]);
$this->assertSame(true, $enumValidator->isValid("3"));
$this->assertSame(true, empty($enumValidator->getMessages()));
}
}
|
Markdown
|
UTF-8
| 662 | 2.828125 | 3 |
[] |
no_license
|
# todoapp-python-django
## This is the simple todo application in *Python* , *Django* , and *Bootstrap* with responsive UI.
#### It's a simple web app where you can add a bunch of task s, update or delete any tasks. All modifications are saved in the database.
### Home Page

### Update task

### Delete task

|
PHP
|
UTF-8
| 7,463 | 2.734375 | 3 |
[] |
no_license
|
<?php
/**
* Created by PhpStorm.
* User: eduardo
* Date: 06/03/2017
* Time: 15:56
*/
namespace Com\CodeFive\Framework\Core\Hooks;
use InvalidArgumentException;
class Panel implements HookContract
{
protected static $methods = [
'GET',
'POST',
'PUT',
'PATCH',
'DELETE'
];
/**
* @var array
*/
protected static $wpPanels = [
'index.php', 'edit.php', 'upload.php',
'link-manager.php', 'edit.php?post_type=*',
'edit-comments.php', 'themes.php',
'plugins.php', 'users.php', 'tools.php',
'options-general.php', 'settings.php'
];
protected $panel = [];
protected $context;
public function __construct()
{
if (!is_admin()) {
return;
}
add_action('admin_menu', [$this, 'boot']);
if ($_SERVER['REQUEST_METHOD'] !== 'GET') {
add_action('init', [$this, 'bootEarly']);
}
}
/**
* Boots the panels.
*
* @return void
*/
public function boot()
{
if (empty($this->panel)) return;
switch ($this->panel['type']) {
case 'panel':
$this->addPanel($this->panel);
break;
case 'wp-sub-panel':
case 'sub-panel':
$this->addSubPanel($this->panel);
break;
}
}
/**
* Boots early.
*
* @return void
*/
public function bootEarly()
{
$slug = null;
if (!empty($_GET['page'])) {
$slug = $_GET['page'];
}
if ($slug === null) {
return;
}
if (($panel = $this->isPanel($slug, true)) === null) {
return;
}
if (!$this->handler($panel, $this->context, true)) {
return;
}
die;
}
/**
* Adds a panel.
*
* @param array $data
* @param $context
*/
public static function create(array $data, $context)
{
foreach (['type', 'uses', 'title', 'slug'] as $key) {
if (isset($data[$key])) {
continue;
}
throw new InvalidArgumentException("Missing {$key} definition for panel");
}
if (!in_array($data['type'], ['panel', 'sub-panel', 'wp-sub-panel'])) {
throw new InvalidArgumentException("Unknown panel type '{$data['type']}'");
}
if (in_array($data['type'], ['sub-panel', 'wp-sub-panel']) && !isset($data['parent'])) {
throw new InvalidArgumentException("Missing parent definition for sub-panel");
}
if ($data['type'] === 'wp-sub-panel') {
$arr = array_filter(static::$wpPanels, function ($value) use ($data) {
return str_is($value, $data['parent']);
});
if (count($arr) === 0) {
throw new InvalidArgumentException("Unknown WP panel '{$data['parent']}'");
}
}
$p = new Panel();
$p->panel = $data;
$p->context = $context;
}
/**
* Adds a panel.
*
* @param $panel
* @return void
*/
protected function addPanel($panel)
{
add_menu_page(
$panel['title'],
$panel['title'],
isset($panel['capability']) && $panel['capability'] ? $panel['capability'] : 'manage_options',
$panel['slug'],
$this->makeCallable($panel),
isset($panel['icon']) ? $this->fetchIcon($panel['icon']) : '',
isset($panel['order']) ? $panel['order'] : null
);
if (isset($panel['rename']) && !empty($panel['rename'])) {
$this->addSubPanel([
'title' => $panel['rename'],
'rename' => true,
'slug' => $panel['slug'],
'parent' => $panel['slug']
]);
}
}
/**
* Adds a sub panel.
*
* @param $panel
* @return void
*/
protected function addSubPanel($panel)
{
/*foreach ($this->panels as $parent) {
if (array_get($parent, 'as') !== $panel['parent']) {
continue;
}
$panel['parent'] = $parent['slug'];
}*/
add_submenu_page(
$panel['parent-slug'],
$panel['title'],
$panel['title'],
isset($panel['capability']) && $panel['capability'] ? $panel['capability'] : 'manage_options',
$panel['slug'],
isset($panel['rename']) && $panel['rename'] ? null : $this->makeCallable($panel)
);
}
/**
* Fetches an icon for a panel.
*
* @param $icon
* @return string
*/
protected function fetchIcon($icon)
{
if (empty($icon)) {
return '';
}
if (substr($icon, 0, 9) === 'dashicons' || substr($icon, 0, 5) === 'data:'
|| substr($icon, 0, 2) === '//' || $icon == 'none'
) {
return $icon;
}
return $icon;
}
/**
* Makes a callable for the panel hook.
*
* @param $panel
* @return callable
*/
protected function makeCallable($panel)
{
$context = $this->context;
return function () use ($panel, $context) {
return $this->handler($panel, $context);
};
}
/**
* Gets a panel.
*
* @param string $name
* @param boolean $slug
* @return array
*/
protected function isPanel($name, $slug = false)
{
$slug = $slug ? 'slug' : 'as';
if (array_get($this->panel, $slug) !== $name) {
return null;
}
return $this->panel;
}
/**
* Gets the panels.
*
* @return array
*/
public function getPanels()
{
return array_values($this->panels);
}
/**
* Get the URL to a panel.
*
* @param string $name
* @return string
*/
public function url($name)
{
if (($panel = $this->isPanel($name)) === null) {
return null;
}
$slug = array_get($panel, 'slug');
if (array_get($panel, 'type') === 'wp-sub-panel') {
return admin_url(add_query_arg('page', $slug, array_get($panel, 'parent')));
}
return admin_url('admin.php?page=' . $slug);
}
/**
* Return the correct callable based on action
*
* @param array $panel
* @param $context
* @param boolean $strict
* @return bool
*/
protected function handler($panel, $context, $strict = false)
{
$callable = $uses = $panel['uses'];
$method = strtolower($_SERVER['REQUEST_METHOD']);
$action = strtolower(empty($_GET['action']) ? 'uses' : $_GET['action']);
$callable = array_get($panel, $method, false) ?: $callable;
if ($callable === $uses || is_array($callable)) {
$callable = array_get($panel, $action, false) ?: $callable;
}
if ($callable === $uses || is_array($callable)) {
$callable = array_get($panel, "{$method}.{$action}", false) ?: $callable;
}
if ($strict && $uses === $callable) {
return false;
}
try {
(new $callable[0]($context))->{$callable[1]}();
} catch (\Exception $e) {
var_dump($e);
}
return true;
}
}
|
JavaScript
|
UTF-8
| 4,434 | 2.75 | 3 |
[] |
no_license
|
let address = document.getElementById('address');
let contact = document.getElementById('contact');
let businessHour = document.getElementById('businessHour');
let contactTitle = contact.getElementsByClassName('title');
let addressTitle = address.getElementsByClassName('title');
let BHTitle = businessHour.getElementsByClassName('title');
let contactExpanded = true;
let addressExpanded = false;
let businessHourExpanded = false;
addressTitle[0].addEventListener('click', () => {
if(!addressExpanded){
address.style.height = '60%';
contact.style.height = '20%';
businessHour.style.height = '20%';
expandLayout(address);
if(contactExpanded){
collapseLayout(contact);
contactExpanded = false;
}
else if(businessHourExpanded){
collapseLayout(businessHour);
businessHourExpanded = false;
}
addressExpanded = true;
}
})
contactTitle[0].addEventListener('click', () => {
if(!contactExpanded){
contact.style.height = '60%';
address.style.height = '20%';
businessHour.style.height = '20%';
expandLayout(contact);
if(addressExpanded){
collapseLayout(address);
addressExpanded = false;
}
if(businessHourExpanded){
collapseLayout(businessHour);
businessHourExpanded = false
}
contactExpanded = true;
}
})
BHTitle[0].addEventListener('click', () =>{
if(!businessHourExpanded){
contact.style.height = '20%';
address.style.height = '20%';
businessHour.style.height = '60%';
expandLayout(businessHour);
if(addressExpanded){
collapseLayout(address);
addressExpanded = false;
}
if(contactExpanded){
collapseLayout(contact);
contactExpanded = false
}
businessHourExpanded = true;
}
})
let expandLayout = (component) => {
let backgroundRunning = component.getElementsByClassName('backgroundRunning');
let contentContainer = component.getElementsByClassName('contentContainer');
let titleDiv = component.getElementsByClassName('title');
let title = titleDiv[0].getElementsByTagName('p');
let icon = title[0].getElementsByTagName('i');
let titleDivWidth = window.getComputedStyle(titleDiv[0]).getPropertyValue('width');
let titleWidth = window.getComputedStyle(title[0]).getPropertyValue('width');
let distance = parseFloat(titleDivWidth)/2 - parseFloat(titleWidth)/2 - parseFloat(titleDivWidth)*0.02;
console.log(titleWidth);
console.log(titleDivWidth);
backgroundRunning[0].style.width = '100%'
title[0].style.color = 'white';
title[0].style.transform = 'translateX(-'+distance+'px)';
icon[0].style.color = 'white';
icon[0].style.transform = 'rotate(720deg)';
contentContainer[0].style.display = 'flex';
titleDiv[0].style.height = '20%';
let seperator = component.getElementsByClassName('seperator');
seperator[0].style.width = '30%';
}
let collapseLayout = (component) => {
let backgroundRunning = component.getElementsByClassName('backgroundRunning');
let titleDiv = component.getElementsByClassName('title');
let title = titleDiv[0].getElementsByTagName('p');
let icon = title[0].getElementsByTagName('i');
let titleDivWidth = window.getComputedStyle(titleDiv[0]).getPropertyValue('width');
let titleWidth = window.getComputedStyle(title[0]).getPropertyValue('width');
let distance = parseFloat(titleDivWidth)/2 - parseFloat(titleWidth)/2 - parseFloat(titleDivWidth)*0.02;
let contentContainer = component.getElementsByClassName('contentContainer');
backgroundRunning[0].style.width = '0%';
title[0].style.color = 'rgb(165,95,193)';
title[0].style.transform = 'translateX(0px)';
icon[0].style.color = 'rgb(165,95,193)';
icon[0].style.transform = 'rotate(0deg)';
contentContainer[0].style.display = 'none';
titleDiv[0].style.height = '100%';
let seperator = component.getElementsByClassName('seperator');
seperator[0].style.width = '0%';
}
let expandContact = () =>{
contact.style.height = '60%';
address.style.height = '20%';
businessHour.style.height = '20%';
expandLayout(contact);
}
setTimeout(expandContact,500);
|
JavaScript
|
UTF-8
| 613 | 2.671875 | 3 |
[] |
no_license
|
// import $ from "jquery";
// import Rx from "rxjs/Rx";
// import { interval } from "rxjs/observable/interval";
// import { throttle } from "rxjs/operators";
// console.log("RxJS Basdoiler Running...");
// THROTTLE
// const input = $("#input");
// const output = $("#output");
// const inputSource$ = Rx.Observable.fromEvent(input, "keyup");
// const result$ = inputSource$.throttle(val => interval(1000));
// result$.subscribe(
// e => {
// console.log(e.target.value);
// },
// err => {
// console.log(err);
// },
// complete => {
// console.log(`complete: ${complete}`);
// }
// );
|
Java
|
UTF-8
| 593 | 3.6875 | 4 |
[] |
no_license
|
package hello;
import java.util.ArrayList;
public class HelloWorld {
public static void main(String[] args) {
// System.out.println("Hello Bhushal Chushak !!!");
// ArrayList<Integer> arr =new ArrayList<>();
// arr.add(5);
// arr.add(55);
// arr.add(500);
// for (Integer i : arr) {
// System.out.println(i);
// }
// System.out.println(arr.contains(5.5));
// System.out.println(arr.get(2));
int []arr= {2,3,4,5};
for (int i : arr) {
System.out.print(i + " ");
}
System.out.println();
System.out.println("Length of the given array is "+arr.length);
}
}
|
Java
|
UTF-8
| 256 | 1.976563 | 2 |
[] |
no_license
|
package Annotation.AnnotationDemo03;
/**
* @Author: lxy
* @Date: 2020/12/21
* @Description: Annotation.AnnotationDemo03
* @Version: 1.0
*/
public class Ann03_Demo01 {
public void show(){
System.out.println("Ann03_Demo01 show..");
}
}
|
C#
|
UTF-8
| 508 | 2.65625 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Text;
namespace Vehicles
{
public class Truck : Vehicles
{
public override double Consumption
{
get { return base.Consumption + 1.6; }
}
public Truck(double quantity, double consumption):base(quantity, consumption)
{
}
public override void Refueling(double litters)
{
base.Refueling(litters * 0.95);
}
}
}
|
C++
|
UTF-8
| 373 | 2.859375 | 3 |
[] |
no_license
|
class Solution {
public:
void moveZeroes(vector<int>& nums) {
int pos = 0;
for(int i = 0;i<nums.size();i++)
{
if(nums[i]!=0)
{
nums[pos] = nums[i];
pos++;
}
}
for(;pos<nums.size();pos++)
{
nums[pos] = 0;
}
}
};
283. Move Zeroes
|
C
|
UTF-8
| 1,962 | 2.703125 | 3 |
[] |
no_license
|
/*
* file: display.c
*
* Copyright (c) 1990 by John J. Grefenstette
*
* purpose: manages the display for interactive use
*
* modified: 10 sep 90
*/
#include "extern.h"
Dtrace(s)
char *s;
{
/* write currently executing function name to display */
if (Displayflag)
{
move(1,46);
clrtoeol();
printw("%s", s);
refresh();
/* delay in order to make the action intelligible */
#if TURBOC
/* delay(250); */ /* delay 250 ms */
#else
/* sleep(1); */ /* delay 1 sec (too long!) */
#endif
}
}
Interactive() {
char cmd[40];
char opt[40];
register int i;
int ncycles;
int ok;
ncycles = 1;
while (1) {
ok = 1;
move(22,0);
clrtoeol();
move(22,35);
printw("q (clear & exit), x (exit), <n> (do n gens)");
move(22,0);
printw(" ");
refresh();
move(22,0);
printw("gens[%d]: ", ncycles);
refresh();
getstr(cmd);
if (strcmp(cmd, "q") == 0) {
clear();
die();
}
if (strcmp(cmd, "x") == 0) {
move(23,0);
die();
}
if (strcmp(cmd, "") != 0) {
if (sscanf(cmd, "%d", &ncycles) !=1)
{
move(23,0);
clrtoeol();
printw("unknown command: %s", cmd);
ok = 0;
refresh();
}
}
if (ok)
{
move(23,0);
clrtoeol();
move(1,0);
printw("run until Gens = %d", Gen + ncycles -1);
move(1,35);
printw("executing: ");
refresh();
for (i=0; i < ncycles; i++)
Generate();
}
}
}
die(sig)
int sig;
{
sig++;
signal(SIGINT, SIG_IGN);
if (Lastflag)
PCheckpoint(Ckptfile);
else
if (Savesize)
Printbest();
move(23,0);
clrtoeol();
refresh();
endwin();
exit(0);
}
#if TURBOC
/* Turbo C versions of curses functions */
move(row, col)
int row, col;
{
/* move to row, col coordinates of the screen */
/* (0,0) = upper left corner; (23,79) = lower right corner */
gotoxy(col+1, row+1);
}
clear()
{
/* clear the screen */
clrscr();
}
getstr(s)
char *s;
{
getw(s);
}
initscr() {}
endwin() {}
#endif
|
C++
|
UTF-8
| 1,290 | 2.734375 | 3 |
[] |
no_license
|
#ifndef POINTSWIDGET_H
#define POINTSWIDGET_H
#include <QWidget>
namespace Ui {
class PointsWidget;
}
class PointsCollection;
/**
* @brief Widget displays table with plot's points
* Uses simple pagination
*/
class PointsWidget : public QWidget
{
Q_OBJECT
public:
explicit PointsWidget(QWidget *parent, PointsCollection *points);
~PointsWidget();
public slots:
void previousPageClicked();
void nextPageClicked();
/**
* @brief Refresh currently dislayed page with data from points collection
*/
void updatePage();
protected:
/**
* @brief Event handler to update current page on widget's show
* @param event
*/
void showEvent(QShowEvent * event);
private:
Ui::PointsWidget *ui;
PointsCollection *_points;
int _perPage; // number of entries per page
int _pageNumber; // number of current page
/**
* @brief Update state (caption and 'enabled' state) of 'Previous Page' button
*/
void updatePreviousPageButton();
/**
* @brief Update state (caption and 'enabled' state) of 'Next Page' button
*/
void updateNextPageButton();
/**
* @brief Calculate available number of pages
* @return
*/
int getPagesNumber();
};
#endif // POINTSWIDGET_H
|
C#
|
UTF-8
| 2,172 | 2.6875 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using CentralAtivos.Domain.Entities;
using CentralAtivos.Domain.Interfaces;
namespace CentralAtivos.Repository.Repositories
{
public class PlacaRepository : IPlaca
{
public void Delete(int id)
{
using (var ctx = new Context.Context())
{
var placa = ctx.Placas.Find(id);
if (placa != null)
{
placa.DataExclusao = DateTime.Now;
}
ctx.Entry(placa).State = System.Data.Entity.EntityState.Modified;
ctx.SaveChanges();
}
}
public Placa GetByID(int id)
{
Placa placa = null;
using (var ctx = new Context.Context())
{
placa = ctx.Placas.Find(id);
}
return placa;
}
public List<Placa> GetByPlacaGrupoID(int placaGrupoID)
{
List<Placa> placas = null;
using (var ctx = new Context.Context())
{
placas = ctx.Placas.Where(x => x.PlacaGrupoID == placaGrupoID && x.DataExclusao == null).OrderBy(x => x.NumeroPlaca).ToList();
}
return placas;
}
public List<Placa> GetJumpsByPlacaGrupoID(int placaGrupoID)
{
List<Placa> placas = null;
using (var ctx = new Context.Context())
{
placas = ctx.Placas.Where(x => x.PlacaGrupoID == placaGrupoID && x.ItemID == null && x.DataExclusao == null).OrderBy(x => x.NumeroPlaca).ToList();
}
return placas;
}
public void Insert(Placa placa)
{
using(var ctx = new Context.Context())
{
ctx.Placas.Add(placa);
ctx.SaveChanges();
}
}
public void Update(Placa placa)
{
using (var ctx = new Context.Context())
{
ctx.Entry(placa).State = System.Data.Entity.EntityState.Modified;
ctx.SaveChanges();
}
}
}
}
|
Shell
|
UTF-8
| 1,872 | 3.65625 | 4 |
[
"Apache-2.0"
] |
permissive
|
#!/bin/bash
# This script parses in the command line parameters from runCust,
# maps them to the correct command line parameters for DispNet training script and launches that task
# The last line of runCust should be: bash $CONFIG_FILE --data-dir $DATA_DIR --log-dir $LOG_DIR
# Parse the command line parameters
# that runCust will give out
DATA_DIR=NONE
LOG_DIR=NONE
CONFIG_DIR=NONE
MODEL_DIR=NONE
# Parsing command line arguments:
while [[ $# > 0 ]]
do
key="$1"
case $key in
-h|--help)
echo "Usage: run_dispnet_training_philly.sh [run_options]"
echo "Options:"
echo " -d|--data-dir <path> - directory path to input data (default NONE)"
echo " -l|--log-dir <path> - directory path to save the log files (default NONE)"
echo " -p|--config-file-dir <path> - directory path to config file directory (default NONE)"
echo " -m|--model-dir <path> - directory path to output model file (default NONE)"
exit 1
;;
-d|--data-dir)
DATA_DIR="$2"
shift # pass argument
;;
-p|--config-file-dir)
CONFIG_DIR="$2"
shift # pass argument
;;
-m|--model-dir)
MODEL_DIR="$2"
shift # pass argument
;;
-l|--log-dir)
LOG_DIR="$2"
shift
;;
*)
echo Unkown option $key
;;
esac
shift # past argument or value
done
# Prints out the arguments that were passed into the script
echo "DATA_DIR=$DATA_DIR"
echo "LOG_DIR=$LOG_DIR"
echo "CONFIG_DIR=$CONFIG_DIR"
echo "MODEL_DIR=$MODEL_DIR"
# Run training on philly
# Add the root folder of the code to the PYTHONPATH
export PYTHONPATH=$PYTHONPATH:$CONFIG_DIR
# Run the actual job
python $CONFIG_DIR/anytime_models/examples/resnet-ann.py \
--data_dir=$DATA_DIR \
--log_dir=$LOG_DIR \
--model_dir=$MODEL_DIR \
--load=${MODEL_DIR}/checkpoint \
-n=17 -c=32 -s=1 --opt_at=44 --ds_name=cifar100 --batch_size=64 --nr_gpu=1 -f=2 --samloss=0
|
C#
|
UTF-8
| 1,319 | 2.984375 | 3 |
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
namespace L2L.WebApi.Utilities
{
public static class HelperUtil
{
public static int[] GetIntArrayFromString(string strArray)
{
int[] intArr = new int[0];
if (strArray != null & string.IsNullOrEmpty(strArray) == false)
{
var strArrayTmp = strArray.Substring(0, strArray.Length - 1);
intArr = strArrayTmp.Split(',').Select(s => Int32.Parse(s)).ToArray();
}
return intArr;
}
public static int[] GetIntArrayFromString(string strArray, int size)
{
var list = new List<int>();
for (int i = 0; i < size; i++)
list.Add(0);
var intArr = list.ToArray();
var intArrTmp = GetIntArrayFromString(strArray);
for (int i = 0; i < intArrTmp.Count(); i++)
intArr[i] = intArrTmp[i];
return intArr;
}
public static string GetStrFromIntArray(int[] intArray)
{
StringBuilder str = new StringBuilder();
foreach (var item in intArray)
str.Append(item.ToString() + ",");
return str.ToString();
}
}
}
|
Java
|
UTF-8
| 2,750 | 2.203125 | 2 |
[] |
no_license
|
package com.drew.metadata.exif.makernotes;
import androidx.exifinterface.media.ExifInterface;
import com.drew.lang.annotations.NotNull;
import com.drew.lang.annotations.Nullable;
import com.drew.metadata.TagDescriptor;
public class LeicaMakernoteDescriptor extends TagDescriptor<LeicaMakernoteDirectory> {
public LeicaMakernoteDescriptor(@NotNull LeicaMakernoteDirectory leicaMakernoteDirectory) {
super(leicaMakernoteDirectory);
}
@Nullable
public String getDescription(int i) {
if (i == 768) {
return getQualityDescription();
}
if (i == 770) {
return getUserProfileDescription();
}
if (i == 772) {
return getWhiteBalanceDescription();
}
if (i == 800) {
return getCameraTemperatureDescription();
}
switch (i) {
case 785:
return getExternalSensorBrightnessValueDescription();
case LeicaMakernoteDirectory.TAG_MEASURED_LV /*786*/:
return getMeasuredLvDescription();
case LeicaMakernoteDirectory.TAG_APPROXIMATE_F_NUMBER /*787*/:
return getApproximateFNumberDescription();
default:
switch (i) {
case LeicaMakernoteDirectory.TAG_WB_RED_LEVEL /*802*/:
case LeicaMakernoteDirectory.TAG_WB_GREEN_LEVEL /*803*/:
case LeicaMakernoteDirectory.TAG_WB_BLUE_LEVEL /*804*/:
return getSimpleRational(i);
default:
return super.getDescription(i);
}
}
}
@Nullable
private String getCameraTemperatureDescription() {
return getFormattedInt(800, "%d C");
}
@Nullable
private String getApproximateFNumberDescription() {
return getSimpleRational(LeicaMakernoteDirectory.TAG_APPROXIMATE_F_NUMBER);
}
@Nullable
private String getMeasuredLvDescription() {
return getSimpleRational(LeicaMakernoteDirectory.TAG_MEASURED_LV);
}
@Nullable
private String getExternalSensorBrightnessValueDescription() {
return getSimpleRational(785);
}
@Nullable
private String getWhiteBalanceDescription() {
return getIndexedDescription(772, "Auto or Manual", "Daylight", "Fluorescent", "Tungsten", ExifInterface.TAG_FLASH, "Cloudy", "Shadow");
}
@Nullable
private String getUserProfileDescription() {
return getIndexedDescription(768, 1, "User Profile 1", "User Profile 2", "User Profile 3", "User Profile 0 (Dynamic)");
}
@Nullable
private String getQualityDescription() {
return getIndexedDescription(768, 1, "Fine", "Basic");
}
}
|
Java
|
UTF-8
| 1,988 | 3.5 | 4 |
[] |
no_license
|
package util;
import java.util.ArrayList;
import java.util.regex.Pattern;
import model.Example;
/**
* 工具类
*/
public class AlgorithmUtil {
/**
* 清洗数据,去掉非字母的字符,和字节长度小于2的单词
* @param info 一条样本
* @return info 清洗后一条样本
*/
public static String cleanData(String info) {
// 去标点
Pattern p = Pattern.compile("\\W");
String[] tempInfo = p.split(info);
info = "";
// 去停用词
// 去除长度小于3的单词
for (int i = 0; i < tempInfo.length; i++) {
if (tempInfo[i].length() >= 3)
info += tempInfo[i] + " ";
}
// 去大写
info = info.toLowerCase();
if (info.equals("")) {// 经观察,处理后有25条数据为空
return null;
} else {
return info;
}
}
/**
* 按比例把数据集分为训练集和测试集
* @param dataSetList 数据集
* @param trainRate 训练集占数据集的比例
* @return trainTestSet 包含训练集和测试集的集合
*/
public static ArrayList<ArrayList<Example>> dataProcessing(ArrayList<Example> dataSetList, double trainRate) {
System.out.println(dataSetList.size());
ArrayList<ArrayList<Example>> trainTestSet = new ArrayList<ArrayList<Example>>();
ArrayList<Example> trainSet = new ArrayList<Example>();
ArrayList<Example> testSet = new ArrayList<Example>();
int dataSize = dataSetList.size();
int trainLength = (int) (dataSize * trainRate);
int[] sum = new int[dataSize];
for (int i = 0; i < dataSize; i++) {
sum[i] = i;
}
int num = dataSize;
for (int i = 0; i < trainLength; i++) {
int temp = (int) (Math.random() * (num--));
trainSet.add(dataSetList.get(sum[temp]));
sum[temp] = sum[num];
}
trainTestSet.add(trainSet);
System.out.println(trainSet.size());
for (int i = 0; i < dataSize - trainLength; i++) {
testSet.add(dataSetList.get(sum[i]));
}
trainTestSet.add(testSet);
System.out.println(testSet.size());
return trainTestSet;
}
}
|
C++
|
UTF-8
| 503 | 2.890625 | 3 |
[] |
no_license
|
#include <iostream>
using namespace std;
class List {
private:
class Node {
public:
int data;
Node* link;
};
bool access_valid(int count);
Node* head = NULL;
int numbers;
public:
int tracking(int data); // find index
void add(int data); // add tail
void add(int index, int data);
void del(int index);
void del_all(int data);
void print();
void clean();
List reverse();
List reverse(int index);
List extract(int index);
List concat(List after);
bool isnull();
int count();
};
|
Python
|
UTF-8
| 1,311 | 3.15625 | 3 |
[] |
no_license
|
from pathlib import Path
def find_context(sentence, path):
def _left_context(idx, sentence, text):
chunks = text[:idx].split(' ')
return ' '.join(chunks[-3:])
def _right_context(idx, sentence, text):
chunks = text[idx+len(sentence):].split(' ')
return ' '.join(chunks[:3])
contexts = []
fns = path.glob('*.txt')
for fn in fns:
text = fn.read_text()
idx = text.find(sentence)
if idx >= 0:
l_context = _left_context(idx, sentence, text)
r_context = _right_context(idx, sentence, text)
sentence_with_context = l_context + sentence + r_context
return sentence_with_context
return sentence
if __name__ == "__main__":
path = Path('../data/corpus/derge-kangyur')
sentence = "གསུམ་པོ་དེ་དག་གང་ཞེ་ན། ཕ་དང་མ་གཉིས་ཆགས་པར་གྱུར་ཅིང་འདུས་པ་དང་། མ་དུས་ལ་བབ་ཅིང་ཟླ་མཚན་དང་ལྡན་པ་དང་། དྲི་ཟ་ཉེ་བར་གནས་ཤིང་འཇུག་པར་འདོད་པ་སྟེ།"
sentence_with_context = find_context(sentence, path)
print(sentence_with_context)
|
Java
|
UTF-8
| 275 | 2.1875 | 2 |
[] |
no_license
|
package src.fizzBuzz;
public class Buzz implements Elements {
public Buzz() {
}
@Override
public boolean isaBoolean(int input) {
return input % 5 == 0;
}
@Override
public String getString(int input) {
return "Buzz";
}
}
|
Python
|
UTF-8
| 238 | 3.078125 | 3 |
[] |
no_license
|
'''
Question : You are given a complex z. Your task is to convert it to polar coordinates.
Link : https://www.hackerrank.com/challenges/polar-coordinates/problem
'''
import cmath
z = complex(input())
print(abs(z))
print(cmath.phase(z))
|
TypeScript
|
UTF-8
| 557 | 2.6875 | 3 |
[] |
no_license
|
import { Action } from '@ngrx/store';
export class ActionTypes {
static readonly LOADING_START = '[App] Loading start';
static readonly LOADING_END = '[App] Loading end';
}
export class StartAction implements Action {
readonly type = ActionTypes.LOADING_START;
public static of() {
return new StartAction();
}
constructor() {}
}
export class EndAction implements Action {
readonly type = ActionTypes.LOADING_END;
public static of() {
return new EndAction();
}
constructor() {}
}
export type Action = StartAction | EndAction;
|
Go
|
UTF-8
| 3,040 | 2.71875 | 3 |
[] |
no_license
|
package models
import (
"encoding/json"
"zonart/db"
"gopkg.in/go-playground/validator.v9"
)
// Opsi is class
type Opsi struct {
idOpsi int
namaGrup string
opsi string
harga int
berat int
perProduk bool
status bool
}
func (o *Opsi) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
IDOpsi int `json:"idOpsi"`
NamaGrup string `json:"namaGrup"`
Opsi string `json:"opsi"`
Harga int `json:"harga"`
Berat int `json:"berat"`
PerProduk bool `json:"perProduk"`
Status bool `json:"status"`
}{
IDOpsi: o.idOpsi,
NamaGrup: o.namaGrup,
Opsi: o.opsi,
Harga: o.harga,
Berat: o.berat,
PerProduk: o.perProduk,
Status: o.status,
})
}
func (o *Opsi) UnmarshalJSON(data []byte) error {
alias := struct {
IDOpsi int `json:"idOpsi"`
NamaGrup string `json:"namaGrup"`
Opsi string `json:"opsi" validate:"required"`
Harga int `json:"harga"`
Berat int `json:"berat"`
PerProduk bool `json:"perProduk"`
Status bool `json:"status"`
}{}
err := json.Unmarshal(data, &alias)
if err != nil {
return err
}
o.idOpsi = alias.IDOpsi
o.namaGrup = alias.NamaGrup
o.opsi = alias.Opsi
o.harga = alias.Harga
o.berat = alias.Berat
o.perProduk = alias.PerProduk
o.status = alias.Status
if err = validator.New().Struct(alias); err != nil {
return err
}
return nil
}
// GetOpsi is func
func (opsi Opsi) GetOpsi(idGrupOpsi, idOpsi string) (Opsi, error) {
con := db.Connect()
query := "SELECT idOpsi, opsi, harga, berat, perProduk, status FROM opsi WHERE idGrupOpsi = ? AND idOpsi = ?"
err := con.QueryRow(query, idGrupOpsi, idOpsi).Scan(
&opsi.idOpsi, &opsi.opsi, &opsi.harga, &opsi.berat, &opsi.perProduk, &opsi.status)
defer con.Close()
return opsi, err
}
// GetOpsis is func
func (opsi Opsi) GetOpsis(idGrupOpsi string) []Opsi {
con := db.Connect()
query := "SELECT idOpsi, opsi, harga, berat, perProduk, status FROM opsi WHERE idGrupOpsi = ?"
rows, _ := con.Query(query, idGrupOpsi)
var opsis []Opsi
for rows.Next() {
rows.Scan(
&opsi.idOpsi, &opsi.opsi, &opsi.harga, &opsi.berat, &opsi.perProduk, &opsi.status,
)
opsis = append(opsis, opsi)
}
defer con.Close()
return opsis
}
// CreateUpdateOpsi is func
func (opsi Opsi) CreateUpdateOpsi(idGrupOpsi string) error {
con := db.Connect()
query := "INSERT INTO opsi (idOpsi, idGrupOpsi, opsi, harga, berat, perProduk, status) VALUES (?,?,?,?,?,?,?) ON DUPLICATE KEY UPDATE opsi = ?, harga = ?, berat = ?, perProduk = ?, status = ?"
_, err := con.Exec(query, opsi.idOpsi, idGrupOpsi, opsi.opsi, opsi.harga, opsi.berat, opsi.perProduk, opsi.status, opsi.opsi, opsi.harga, opsi.berat, opsi.perProduk, opsi.status)
defer con.Close()
return err
}
// DeleteOpsi is func
func (opsi Opsi) DeleteOpsi(idGrupOpsi, idOpsi string) error {
con := db.Connect()
query := "DELETE FROM opsi WHERE idGrupOpsi = ? AND idOpsi = ?"
_, err := con.Exec(query, idGrupOpsi, idOpsi)
defer con.Close()
return err
}
|
Java
|
UTF-8
| 218 | 2.03125 | 2 |
[] |
no_license
|
package jlcAarray;
public class Lab483_2DArray_Length {
public static void main(String[] args) {
// TODO Auto-generated method stub
int []arr,arr1;
arr=new int[2];
System.out.println("hello raj");
}
}
|
C++
|
ISO-8859-1
| 4,009 | 2.625 | 3 |
[
"MIT"
] |
permissive
|
// lusolver.cpp
//#include "lusolver.h"
#include "utils.h"
namespace Izm
{
namespace Numerics
{
namespace Solvers
{
template <class LinearType, class DomainType, class RangeType>
void LUSolver<LinearType,DomainType,RangeType>::LU(LinearType& A)
{
const int m = A.xDim();
const int n = A.yDim();
_Error = 0;
_Swap.setSize(m);
for (int i = 1; i <= m; ++i) _Swap(i) = i;
_Swaps = 0;
for (int k = 1; k < n; ++k)
{
// Pivot-Suche
int piv = k;
for (int i = k+1; i <= m; ++i)
{
if (Numerics::abs(A(_Swap(i),k)) > Numerics::abs(A(_Swap(piv),k))) piv = i;
}
// Zeilentausch in swap
if (piv > k)
{
std::swap(_Swap(piv),_Swap(k));
_Swaps++;
}
// Berechnung der Gau-Faktoren
for (int i = k+1; i <= m; ++i)
{
if (Numerics::abs(A(_Swap(k),k)) > 10.0*eps)
{
A(_Swap(i),k) = A(_Swap(i),k)/A(_Swap(k),k);
}
else
{
_Error = -1;
return;
}
}
// Transformation der Zeilen i:=k+1,...,m
for (int i = k+1; i <= m; ++i)
{
for (int j = k+1; j <= n; ++j)
{
A(_Swap(i),j) = A(_Swap(i),j) - A(_Swap(i),k) * A(_Swap(k),j);
}
}
}
}
template <class LinearType, class DomainType, class RangeType>
void LUSolver<LinearType,DomainType,RangeType>::LU(LinearType& A, LinearType& L, LinearType& U)
{
const int m = A.xDim();
const int n = A.yDim();
LU(A);
if (_Error != 0) return;
// Aufbau von U
U.clear();
for (int i = 1; i <= m; ++i)
{
for (int j = i; j <= n; ++j)
{
U(i,j) = A(_Swap(i),j);
}
}
// Aufbau von L
L.clear();
for (int i = 1; i <= m; ++i)
{
for (int j = 1; j <= i-1; ++j)
{
L(i,j) = A(_Swap(i),j);
}
}
for (int i = 1; i <= m; ++i) L(i,i) = 1.0;
}
template <class LinearType, class DomainType, class RangeType>
void LUSolver<LinearType,DomainType,RangeType>::LU(LinearType& A, LinearType& L, LinearType& U, LinearType& P)
{
LU(A,L,U);
if (_Error != 0) return;
P.clear();
for (int i = 1; i <= _Swap.Size(); ++i)
{
P(i,_Swap(i)) = 1.0;
}
}
template <class LinearType, class DomainType, class RangeType>
void LUSolver<LinearType,DomainType,RangeType>::Solve(LinearType& A, const RangeType& b, DomainType& c, bool doLU)
{
const int m = A.xDim();
const int n = A.yDim();
RangeType y(m);
_Error = 0;
if (doLU) LU(A);
if (_Error != 0) return;
// Initialisierung von y mit b entsprechend den vongenommenen Zeilenvertauschungen
for (int i = 1; i <= m; ++i) y(i) = b(_Swap(i));
// Berechnung der Lsung von L * y = b
for (int k = 1; k <= n; ++k)
{
for (int j = 1; j <= k-1; ++j)
{
y(k) -= A(_Swap(k),j) * y(j);
}
}
for (int k = 1; k <= n; ++k) c(k) = y(k);
// Lsung von U * c := y
for (int k = n; k >= 1; --k)
{
for (int j = k+1; j <= n; ++j) c(k) -= A(_Swap(k),j) * c(j);
if (Numerics::abs(A(_Swap(k),k)) < 10.0*eps)
{
_Error = -1;
return;
}
else
{
c(k) /= A(_Swap(k),k);
}
}
}
template <class LinearType, class DomainType, class RangeType>
void LUSolver<LinearType,DomainType,RangeType>::Solve(LinearType& A, const LinearType& B, LinearType& C, bool doLU)
{
const int n = A.yDim();
const int m = B.yDim();
DomainType b(n), x(n);
_Error = 0;
if (doLU) LU(A);
if (_Error != 0) return;
for (int i = 1; i <= m; ++i)
{
for (int k = 1; k <= n; ++k) b(k) = B(k,i);
Solve(A,b,x,false);
if (_Error != 0) return;
for (int k = 1; k <= n; ++k) C(k,i) = x(k);
}
}
template <class LinearType, class DomainType, class RangeType>
void LUSolver<LinearType,DomainType,RangeType>::Invert(LinearType& A, LinearType& B, bool doLU)
{
LinearType E(A.xDim(),A.yDim());
for (int i = 1; i <= A.xDim(); ++i) E(i,i) = 1.0;
Solve(A,E,B,doLU);
}
template <class LinearType, class DomainType, class RangeType>
double LUSolver<LinearType,DomainType,RangeType>::Det(LinearType& A, bool doLU)
{
double result = 1.0;
_Error = 0;
if (doLU) LU(A);
if (_Error != 0) return 0.0;
for (int i = 1; i <= A.xDim(); ++i) result *= A(_Swap(i),i);
if ((_Swaps % 2)!=0) return -result; else return result;
}
}
}
}
// lusolver.cpp
|
Java
|
GB18030
| 19,271 | 2.484375 | 2 |
[] |
no_license
|
package com.jdd.powermanager.model.MeterSurvey;
import java.util.ArrayList;
import java.util.HashMap;
import com.jdd.powermanager.model.MeterSurvey.BoxSurveyForm.BoxSurvey;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class BoxSurveyDBHelper extends SQLiteOpenHelper
{
public static final int DATABASE_VERSION = 1;
public static final String DATABASE_NAME = "Survey.db";
private static final String TEXT_TYPE = " TEXT";
private static final String COMMA_SEP = ",";
private static String SQL_CREATE_ENTRIES = null;
private static final String SQL_DELETE_ENTRIES =
"DROP TABLE IF EXISTS " + BoxSurvey.TABLE_NAME;
private static final String TAG = "BoxSurveyDBHelper";
public BoxSurveyDBHelper(Context context)
{
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db)
{
SQL_CREATE_ENTRIES = "CREATE TABLE " + BoxSurvey.TABLE_NAME + " (";
int DBToXLSColumnIndexAllLength = BoxSurvey.DBToXLSColumnIndexAll.length;
for (int i = 0; i < DBToXLSColumnIndexAllLength - 1; i ++)
{
SQL_CREATE_ENTRIES += BoxSurvey.DBToXLSColumnIndexAll[i] + TEXT_TYPE + COMMA_SEP;
}
SQL_CREATE_ENTRIES += BoxSurvey.DBToXLSColumnIndexAll[DBToXLSColumnIndexAllLength - 1]
+ TEXT_TYPE + " )";
db.execSQL(SQL_CREATE_ENTRIES);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
db.execSQL(SQL_DELETE_ENTRIES);
onCreate(db);
}
/**
* ִݼصsql
*/
private void executeNoDataSetSQL(String SQL)
{
SQLiteDatabase db = getWritableDatabase();
try
{
db.execSQL(SQL);
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
db.close();
}
}
/**
* ɾղ
*/
public void cleanBoxSurveyTable()
{
SQLiteDatabase db = getWritableDatabase();
try
{
db.execSQL(SQL_DELETE_ENTRIES);
onCreate(db);
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
db.close();
}
}
/**
* ݲ뵽̨ղݿ
* @param allContentValues ݶ
*/
public void insertBoxSurveyTable(ContentValues[] allContentValues)
{
SQLiteDatabase db = getWritableDatabase();
try
{
for (int i = 0; i < allContentValues.length; i ++)
{
db.insert(
BoxSurvey.TABLE_NAME,
null,
allContentValues[i]);
}
}
catch(Exception e)
{
e.printStackTrace();
}
finally
{
db.close();
}
}
/**
* ȡݿϢ
* @return ȡݿϢ,hashmapʾϢж
*/
public ArrayList<HashMap<String, String>> getAllDatas()
{
String SQL = "SELECT ";
int allColumnLength = BoxSurvey.DBToXLSColumnIndexAll.length;
for (int i = 0 ; i < allColumnLength - 1 ; i ++)
{
SQL += BoxSurvey.DBToXLSColumnIndexAll[i] + COMMA_SEP;
}
SQL += BoxSurvey.DBToXLSColumnIndexAll[allColumnLength - 1] +
" FROM " + BoxSurvey.TABLE_NAME;
SQLiteDatabase db = getWritableDatabase();
ArrayList<HashMap<String, String>> boxList = new ArrayList<HashMap<String, String>>();
Cursor c = null;
try
{
c = db.rawQuery(SQL, null);
while (c.moveToNext())
{
HashMap<String, String> boxColumnMap = new HashMap<String, String>();
for (int i = 0; i < allColumnLength; i ++)
{
boxColumnMap.put(BoxSurvey.DBToXLSColumnIndexAll[i], c.getString(i));
}
boxList.add(boxColumnMap);
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (c != null)
{
c.close();
}
db.close();
}
return boxList;
}
/**
* ȡ̨
* @return ȡ̨
*/
public ArrayList<HashMap<String, String>> getAllDistrict()
{
String SQL = "SELECT DISTINCT ";
int districtColumnLength = BoxSurvey.DBToXLSColumnIndexDistrict.length;
for (int i = 0; i < districtColumnLength - 1; i ++)
{
SQL += BoxSurvey.DBToXLSColumnIndexDistrict[i] + COMMA_SEP;
}
SQL += BoxSurvey.DBToXLSColumnIndexDistrict[districtColumnLength - 1];
SQL += " FROM " + BoxSurvey.TABLE_NAME;
SQLiteDatabase db = getWritableDatabase();
ArrayList<HashMap<String, String>> districtList = new ArrayList<HashMap<String, String>>();
Cursor c = null;
try
{
c = db.rawQuery(SQL, null);
while (c.moveToNext())
{
HashMap<String, String> districtColumnMap = new HashMap<String, String>();
for (int i = 0; i < districtColumnLength; i ++)
{
districtColumnMap.put(BoxSurvey.DBToXLSColumnIndexDistrict[i], c.getString(i));
}
districtList.add(districtColumnMap);
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (c != null)
{
c.close();
}
db.close();
}
return districtList;
}
/**
* ȡij̨ղļб
* @param districtID ̨id
* @param commitStatus ύ״̬ 0еı 1ύ 2δύ
* @return ij̨ղб,hashmapʾ
*/
public ArrayList<HashMap<String, String>> getAllSurveyedBoxesInDistrict(String districtID, int commitStatus)
{
String SQL = "SELECT DISTINCT ";
int boxColumnLength = BoxSurvey.DBToXLSColumnIndexBox.length;
for (int i = 0 ; i < boxColumnLength - 1 ; i ++)
{
SQL += BoxSurvey.DBToXLSColumnIndexBox[i] + COMMA_SEP;
}
SQL += BoxSurvey.DBToXLSColumnIndexBox[boxColumnLength - 1] +
" FROM " + BoxSurvey.TABLE_NAME +
" where " + BoxSurvey.DISTRICT_ID + " = \"" + districtID +"\""
+ " and " + SurveyForm.SURVEY_STATUS + " = \"" + SurveyForm.SURVEY_STATUS_SURVEYED + "\"";
//Ƿύ
String commitStatusCondition = "";
switch (commitStatus)
{
case 0:
commitStatusCondition = "";
break;
case 1:
commitStatusCondition = " and " + SurveyForm.COMMIT_STATUS +
" = \"" + SurveyForm.COMMIT_STATUS_COMMITED + "\"";
break;
case 2:
commitStatusCondition = " and " + SurveyForm.COMMIT_STATUS +
" = \"" + SurveyForm.COMMIT_STATUS_UNCOMMITED + "\"";
break;
default:
commitStatusCondition = "";
break;
}
SQL += commitStatusCondition;
SQLiteDatabase db = getWritableDatabase();
ArrayList<HashMap<String, String>> boxList = new ArrayList<HashMap<String, String>>();
Cursor c = null;
try
{
c = db.rawQuery(SQL, null);
while (c.moveToNext())
{
HashMap<String, String> boxColumnMap = new HashMap<String, String>();
for (int i = 0; i < boxColumnLength; i ++)
{
boxColumnMap.put(BoxSurvey.DBToXLSColumnIndexBox[i], c.getString(i));
}
boxList.add(boxColumnMap);
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (c != null)
{
c.close();
}
db.close();
}
return boxList;
}
/**
* ݴļб("id,id,id...")ַ
* @param boxList б
* @return ("id,id,id...")ַ
*/
private String createBoxIdsListString(ArrayList<HashMap<String, String>> boxList)
{
int boxListSize = boxList.size();
String boxIdsString = "(";
for (int i = 0; i < boxListSize - 1; i ++)
{
boxIdsString += "\"" + boxList.get(i).get(BoxSurvey.ASSET_NO) + "\"" + COMMA_SEP;
}
boxIdsString += "\"" + boxList.get(boxListSize - 1).get(BoxSurvey.ASSET_NO) + "\")";
return boxIdsString;
}
/**
* ݴidַupdate䡣
* ԭݿеļ䣺ղ顢ǡδύ
* @param district ̨Ϣ
* @param boxIdsString ("id,id,id...")ַ
* @return update
*/
private String createUpdateBoxInIdSetSQL(HashMap<String, String> district,
String boxIdsString)
{
String updateSql = "UPDATE " + BoxSurvey.TABLE_NAME + " SET ";
int districtColumnLength = BoxSurvey.DBToXLSColumnIndexDistrict.length;
String districtColumnValue = null;
for (int i = 0 ; i < districtColumnLength ; i ++)
{
districtColumnValue = district.get(BoxSurvey.DBToXLSColumnIndexDistrict[i]);
if (null == districtColumnValue)
{
districtColumnValue = "";
}
updateSql += BoxSurvey.DBToXLSColumnIndexDistrict[i] + " = \"" +
districtColumnValue + "\"" + COMMA_SEP;
}
updateSql += SurveyForm.COMMIT_STATUS + " = \"" + SurveyForm.COMMIT_STATUS_UNCOMMITED + "\"" + COMMA_SEP;
updateSql += SurveyForm.SURVEY_STATUS + " = \"" + SurveyForm.SURVEY_STATUS_SURVEYED + "\"" + COMMA_SEP;
updateSql += SurveyForm.SURVEY_RELATION + " = \"" + SurveyForm.SURVEY_RELATION_YES + "\"";
updateSql += " WHERE " + BoxSurvey.ASSET_NO + " IN " + boxIdsString;
Log.d(TAG, "updateSql is: " + updateSql);
return updateSql;
}
/**
* ݴidַselect
* @param boxIdsString ("id,id,id...")ַ
* @return select
*/
private String createSelectBoxInIdSet(String boxIdsString)
{
String selectSql = "SELECT " + BoxSurvey.ASSET_NO +
" FROM " + BoxSurvey.TABLE_NAME +
" WHERE " + BoxSurvey.ASSET_NO +
" IN " + boxIdsString;
return selectSql;
}
/**
* ȡݿеļб
* @param boxList б
* @param boxIdsString ("id,id,id...")ַ
* @return ȡݿеļб
*/
private ArrayList<HashMap<String, String>> getBoxesNotInDB(ArrayList<HashMap<String, String>> boxList
,String boxIdsString)
{
ArrayList<HashMap<String, String>> boxesNotInDBList = new ArrayList<HashMap<String, String>>();
//Ƚݼ
for (int i = 0; i < boxList.size(); i ++)
{
boxesNotInDBList.add(boxList.get(i));
}
String selectSql = createSelectBoxInIdSet(boxIdsString);
SQLiteDatabase db = getWritableDatabase();
Cursor c = null;
try
{
c = db.rawQuery(selectSql, null);
while (c.moveToNext())
{
//бƳݿѴڵ
for (int i = 0; i < boxesNotInDBList.size(); i ++)
{
if (c.getString(0).equals(boxesNotInDBList.get(i).get(BoxSurvey.ASSET_NO)))
{
boxesNotInDBList.remove(i);
break;
}
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (c != null)
{
c.close();
}
db.close();
}
return boxesNotInDBList;
}
/**
* ݴidַinsert䡣
* ԭݿеĵղ顢δύ
* еDBToXLSColumnIndexAllΪݴbox̨ȡ
* DBToXLSColumnIndexBoxDBToXLSColumnIndexDistrict
* @param district ̨Ϣ
* @param boxList ļб
* @return insert
*/
private String[] createInsertBoxInIdSetSQL(HashMap<String, String> district,
ArrayList<HashMap<String, String>> boxList)
{
int boxListSize = boxList.size();
String[] insertStrings = new String[boxListSize];
int allColumnLength = BoxSurvey.DBToXLSColumnIndexAll.length;
String columnName = null;
String columnValue = null;
HashMap<String, String> box = null;
for (int j = 0 ; j < boxListSize; j ++)
{
box = boxList.get(j);
insertStrings[j] = "INSERT INTO " + BoxSurvey.TABLE_NAME + " values(";
for (int i = 0 ; i < allColumnLength ; i ++)
{
columnName = BoxSurvey.DBToXLSColumnIndexAll[i];
//ղ顢δύ
if (SurveyForm.COMMIT_STATUS.equals(columnName))
{
columnValue = SurveyForm.COMMIT_STATUS_UNCOMMITED;
}
else if (SurveyForm.SURVEY_STATUS.equals(columnName))
{
columnValue = SurveyForm.SURVEY_STATUS_SURVEYED;
}
else if (SurveyForm.SURVEY_RELATION.equals(columnName))
{
columnValue = SurveyForm.SURVEY_RELATION_NEW;
}
else
{
//̨ܸboxظ̨ңҵΪȷֵ
columnValue = district.get(columnName);
if (null == columnValue)
{
columnValue = box.get(columnName);
if (null == columnValue)
{
columnValue = "";
}
}
}
insertStrings[j] += "\"" + columnValue + "\"" + COMMA_SEP;
}
//ȥһ
insertStrings[j] = insertStrings[j].substring(0, insertStrings[j].length() - 1) + ")";
}
return insertStrings;
}
/**
* ̨бӦ̨Ϣбԭݿвڵĵ뵽ݿ
* ԭݿеĵղ顢ǡδύ
* ԭݿвڵĵղ顢δύ
* @param box
* @param meterList
*/
private void updateAndInsertBoxesToDB(HashMap<String, String> district,
ArrayList<HashMap<String, String>> boxList)
{
String boxIdsString = createBoxIdsListString(boxList);
//ִupdateɰѺinsertļ¼ղϵҲɡǡ
String updateSql = createUpdateBoxInIdSetSQL(district, boxIdsString);
executeNoDataSetSQL(updateSql);
//µĵݲݿ
ArrayList<HashMap<String, String>> boxesNotInDB = getBoxesNotInDB(boxList, boxIdsString);
String insertSQLStrings[] = createInsertBoxInIdSetSQL(district, boxesNotInDB);
for (int i = 0; i < insertSQLStrings.length; i ++)
{
executeNoDataSetSQL(insertSQLStrings[i]);
}
}
/**
* 桱һݡ
* ݴµļбݿеļݣһ
* @param district ̨Ϣ
* @param boxList б
*/
public void saveBoxSurvey(HashMap<String, String> district,
ArrayList<HashMap<String, String>> boxList)
{
if (boxList.size() > 0)
{
updateAndInsertBoxesToDB(district, boxList);
}
}
/**
* ύһղ
* @param boxIds id
*/
public void commitBoxesSurvey(String[] boxIds)
{
String SQL = "update " + BoxSurvey.TABLE_NAME + " set ";
SQL += SurveyForm.COMMIT_STATUS + " = \"" + SurveyForm.COMMIT_STATUS_COMMITED + "\"";
SQL += " where " + BoxSurvey.ASSET_NO + " in " + SurveyForm.parseIdArray2SQLIds(boxIds);
executeNoDataSetSQL(SQL);
}
/**
* ɾδύı
* ϵΪ쳣ղ״̬ijδղ
* @param boxIds ɾļid
*/
public void deleteUncommitedBox(String[] boxIds)
{
String SQL = "update " + BoxSurvey.TABLE_NAME + " set ";
SQL += SurveyForm.SURVEY_STATUS + " = \"" + SurveyForm.SURVEY_STATUS_UNSURVEYED + "\"";
SQL += COMMA_SEP + SurveyForm.SURVEY_RELATION + " = \"" + SurveyForm.SURVEY_RELATION_ABNORMAL + "\"";
SQL += " where " + BoxSurvey.ASSET_NO + " in " + SurveyForm.parseIdArray2SQLIds(boxIds);
SQL += " and " + SurveyForm.COMMIT_STATUS + " = \"" + SurveyForm.COMMIT_STATUS_UNCOMMITED +"\"";
executeNoDataSetSQL(SQL);
}
/**
* ɾύı
* ύ״̬Ϊδύ
* @param boxIds ɾļid
*/
public void deleteCommitedBox(String[] boxIds)
{
String SQL = "update " + BoxSurvey.TABLE_NAME + " set ";
SQL += SurveyForm.COMMIT_STATUS + " = \"" + SurveyForm.COMMIT_STATUS_UNCOMMITED + "\"";
SQL += " where " + BoxSurvey.ASSET_NO + " in " + SurveyForm.parseIdArray2SQLIds(boxIds);
SQL += " and " + SurveyForm.COMMIT_STATUS + " = \"" + SurveyForm.COMMIT_STATUS_COMMITED +"\"";
executeNoDataSetSQL(SQL);
}
/**
* ύ̨δύղı
* @param districtId ̨id
*/
public void commitAllUncommitedBoxSurveyInDistrict(String districtId)
{
String SQL = "update " + BoxSurvey.TABLE_NAME + " set ";
SQL += SurveyForm.COMMIT_STATUS + " = \"" + SurveyForm.COMMIT_STATUS_COMMITED + "\"";
SQL += " where " + BoxSurvey.DISTRICT_ID + " = \"" + districtId +"\"";
SQL += " and " + SurveyForm.SURVEY_STATUS + " = \"" + SurveyForm.SURVEY_STATUS_SURVEYED +"\"";
SQL += " and " + SurveyForm.COMMIT_STATUS + " != \"" + SurveyForm.COMMIT_STATUS_COMMITED +"\"";
executeNoDataSetSQL(SQL);
}
/**
* ȡij̨мб
* @return ij̨мб,hashmapʾ
*/
public ArrayList<HashMap<String, String>> getAllBoxesInDistrict(String districtID)
{
String SQL = "SELECT ";
int boxColumnLength = BoxSurvey.DBToXLSColumnIndexBox.length;
for (int i = 0 ; i < boxColumnLength - 1 ; i ++)
{
SQL += BoxSurvey.DBToXLSColumnIndexBox[i] + COMMA_SEP;
}
SQL += BoxSurvey.DBToXLSColumnIndexBox[boxColumnLength - 1] +
" FROM " + BoxSurvey.TABLE_NAME +
" where " + BoxSurvey.DISTRICT_ID + " = \"" + districtID +"\"";
SQLiteDatabase db = getWritableDatabase();
ArrayList<HashMap<String, String>> boxList = new ArrayList<HashMap<String, String>>();
Cursor c = null;
try
{
c = db.rawQuery(SQL, null);
while (c.moveToNext())
{
HashMap<String, String> boxColumnMap = new HashMap<String, String>();
for (int i = 0; i < boxColumnLength; i ++)
{
boxColumnMap.put(BoxSurvey.DBToXLSColumnIndexBox[i], c.getString(i));
}
boxList.add(boxColumnMap);
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (c != null)
{
c.close();
}
db.close();
}
return boxList;
}
/**
* ȡijϢ
* @return ȡijϢ,hashmapʾ
*/
public HashMap<String, String> getBoxWithAssetNo(String assetNo)
{
String SQL = "SELECT ";
int boxColumnLength = BoxSurvey.DBToXLSColumnIndexBox.length;
for (int i = 0 ; i < boxColumnLength - 1 ; i ++)
{
SQL += BoxSurvey.DBToXLSColumnIndexBox[i] + COMMA_SEP;
}
SQL += BoxSurvey.DBToXLSColumnIndexBox[boxColumnLength - 1] +
" FROM " + BoxSurvey.TABLE_NAME +
" where " + BoxSurvey.ASSET_NO + " = \"" + assetNo +"\"";
SQLiteDatabase db = getWritableDatabase();
Cursor c = null;
HashMap<String, String> boxColumnMap = new HashMap<String, String>();
try
{
c = db.rawQuery(SQL, null);
while (c.moveToNext())
{
for (int i = 0; i < boxColumnLength; i ++)
{
boxColumnMap.put(BoxSurvey.DBToXLSColumnIndexBox[i], c.getString(i));
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
if (c != null)
{
c.close();
}
db.close();
}
return boxColumnMap;
}
}
|
Java
|
UTF-8
| 418 | 2.65625 | 3 |
[] |
no_license
|
package question021;
/*
* See analysis: https://blog.csdn.net/qq_41231926/article/details/82250787
*/
public class Solution2 {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1 == null) {
return l2;
}
if(l2 == null) {
return l1;
}
if(l1.val > l2.val) {
l2.next = mergeTwoLists(l1, l2.next);
return l2;
}else {
l1.next = mergeTwoLists(l1.next, l2);
return l1;
}
}
}
|
Python
|
UTF-8
| 808 | 3.234375 | 3 |
[] |
no_license
|
import time
from turtle import Screen
from player import Player
from car_manager import CarManager
from scoreboard import Scoreboard
screen = Screen()
screen.setup(width=600, height=600)
screen.tracer(0)
player = Player()
carManager = CarManager()
scoreboard = Scoreboard()
screen.listen()
screen.onkey(player.goUp, "Up")
game_is_on = True
while game_is_on:
time.sleep(0.1)
screen.update()
carManager.createCars()
carManager.moveCars()
#Case: Collision with car
for car in carManager.allCars:
if car.distance(player) < 20:
game_is_on = False
scoreboard.gameOver()
#Case: Succesful Crossing
if player.isAtFinishLine():
player.goToStart()
carManager.levelUp()
scoreboard.increaseLevel()
screen.exitonclick()
|
Python
|
UTF-8
| 1,718 | 2.515625 | 3 |
[] |
no_license
|
#!/usr/bin/python
from optparse import OptionParser
import os
import threading
import sys
from lib import CMDUtils
from lib import ADBUtils
# ------------------------------------------- ARG PARSE -----------------------------------------------------#
CMDUtils.clear()
parser = OptionParser()
parser.add_option("-f", "--file", type="string", dest="file", default="", help="Path-To-APK to extract the package from")
parser.add_option("-p", "--package-name", type="string", dest="package", default="", help="Package name")
(arguments, args) = parser.parse_args()
# ------------------------------------------- ARG VALIDATIONS -----------------------------------------------------#
if len(sys.argv) == 1:
parser.print_help()
exit(1)
if arguments.file and arguments.package:
CMDUtils.print_error("Can't define both arguments, you should use one or the other")
package = arguments.package
if arguments.file:
if not os.path.isfile(arguments.file):
CMDUtils.print_error("File does not exists: " + arguments.file)
else:
package = ADBUtils.get_package_from_apk(arguments.file)
devices = ADBUtils.get_connected_devices()
if len(devices) == 0:
CMDUtils.print_error("No devices connected")
# ------------------------------------------------------------------------------------------------------#
# ------------------------------------------- MAIN -----------------------------------------------------#
# ------------------------------------------------------------------------------------------------------#
# List devices
ADBUtils.pretty_print_devices()
# Start
for device in devices:
threading.Thread(target=ADBUtils.clear_user_data, args=(device, package,)).start()
|
C++
|
UTF-8
| 1,142 | 2.96875 | 3 |
[] |
no_license
|
#include <cstdio>
#include <vector>
#include <cstring>
#include <algorithm>
struct node {
node* ch[26];
int ret, size;
bool root;
bool mark;
node() {
memset(ch, 0, sizeof(ch));
ret = 0;
size = 0;
root = 0;
mark = 0;
}
};
void ins(node* o, char *s) {
node* p = o;
for (int i = 0; s[i]; ++i) {
int c = s[i] - 'A';
p->size++;
if (!p->ch[c]) p->ch[c] = new node();
p = p->ch[c];
}
p->size++;
p->mark = 1;
}
int solve(node *o) {
int sum = o->mark, leaf = 1;
for (int c = 0; c < 26; ++c) {
if (o->ch[c]) {
leaf = 0;
sum += solve(o->ch[c]);
o->ret += o->ch[c]->ret;
}
}
if (sum >= 2 && !o->root) o->ret += 2, sum -= 2;
if (leaf) return 1;
else return sum;
}
int main() {
int T;
scanf("%d", &T);
for (int cas = 1; cas <= T; ++cas) {
int n;
scanf("%d", &n);
node *rt = new node();
rt->root = true;
for (int i = 0; i < n; ++i) {
char s[100];
scanf("%s", s);
int l = strlen(s);
std::reverse(s, s + l);
ins(rt, s);
}
solve(rt);
printf("Case #%d: %d\n", cas, rt->ret);
}
return 0;
}
|
C
|
UTF-8
| 678 | 3.390625 | 3 |
[] |
no_license
|
#include <stdio.h>
#include <time.h>
int main ()
{
int importancia;
time_t atual;
atual = time (NULL);
struct tm str_time;
time_t time_of_day;
str_time.tm_year = 2019-1900;
str_time.tm_mon = 6;
str_time.tm_mday = 5;
str_time.tm_hour = 10;
str_time.tm_min = 3;
str_time.tm_sec = 5;
str_time.tm_isdst = 0;
time_of_day = mktime (&str_time);
printf(ctime(&time_of_day));
printf("seconds fake data is %ld \n",time_of_day);
printf(ctime(&atual));
printf ("Number of seconds since January 1, 1970 is %ld \n", atual);
importancia = (time_of_day)-(atual);
printf ("importancia relativa = %ld",importancia);
return 0;
}
|
JavaScript
|
UTF-8
| 1,441 | 2.65625 | 3 |
[
"Apache-2.0"
] |
permissive
|
/**
* Scans all the glyphs in the range and returns a list with those available
*
* @requires jQuery, PubSub
* @author Cristian Dobre
*/
( function( $, d, w, s, r ){
var e, glyphs = false, st = [], empty, iv, not = i = 0;
/**
* Uses pubsub to trigger event after the search is finished
*/
$.fn.iconGlyphs = function( c ){
if( ! glyphs ) $.subscribe( 'icon_font_glyphs', function( v, k ){ c( k ) } );
else c( glyphs );
}
/**
* Get empty glyph width only after the page is loaded
*/
$( w ).load( function(){
if( typeof e == 'undefined' ) return ;
empty = e.scrollWidth;
/**
* Set the first glyph
*/
e.innerHTML = String.fromCharCode( s );
/**
* Uses an async mode, allowing the page to redraw
*/
iv = w.setInterval( function(){
if( e.scrollWidth == empty ) not ++;
else{
not = 0;
st.push( s + i );
}
/**
* Increase index or finish the search
*/
if( i < r && not < 16 ) i++;
else {
w.clearInterval( iv );
glyphs = st;
$.publish( 'icon_font_glyphs', [ st ] );
}
e.innerHTML = String.fromCharCode( s + i );
}, 5 );
})
$( d ).ready( function(){
/**
* Set an empty glyph to the tester div
*/
e = $( '#glypher' ).html( String.fromCharCode( 61439 ) ).get( 0 );
});
})( jQuery, document, window, 61440, 512 );
|
Python
|
UTF-8
| 4,926 | 2.53125 | 3 |
[
"Unlicense"
] |
permissive
|
import math
from collections import OrderedDict
from dataclasses import dataclass
from pathlib import Path
from typing import Dict, List, Tuple
import click
import click_pathlib
import dash
import dash_core_components as dcc
import dash_html_components as html
from flask import Flask
from plotly.graph_objs import Figure, Heatmap, Layout
from .simulation_report import GrowthType, SimulationReport, create_simulation_reports
@dataclass
class SimulationTable:
growth_type: GrowthType
param_name: str
param: float
# TODO(lukas): Consider using pandas DataFrame here, this is actually a table.
errors: Dict[int, List[Tuple[int, float]]]
def group_data(simulation_reports: List[SimulationReport]) -> Dict[float, SimulationTable]:
"""Groups data in SimulationReport's by the value of alpha or gamma2"""
heat_maps: OrderedDict[float, SimulationTable] = OrderedDict()
for report in simulation_reports:
if report.param not in heat_maps:
param_name = "alpha" if report.growth_type == GrowthType.Polynomial else "gamma2"
simulation_table = heat_maps.setdefault(
report.param,
SimulationTable(report.growth_type, param_name, report.param, OrderedDict()),
)
else:
simulation_table = heat_maps[report.param]
errors_by_prefix = simulation_table.errors.setdefault(report.prefix_length, [])
errors_by_prefix.append((report.b0, report.error))
return heat_maps
def create_heat_map(simulation_table: SimulationTable):
data = []
for errors in simulation_table.errors.values():
errors.sort()
b0_set = [b0 for b0, _ in errors]
data.append([math.log(error) for _, error in errors])
layout = Layout(
title=f"Logarithm of average error for {simulation_table.param_name} = "
f"{simulation_table.param}",
xaxis=dict(title="$b_0$"),
yaxis=dict(title="prefix length"),
height=700,
font={"size": 20},
)
figure = Figure(layout=layout)
figure.add_trace(
Heatmap(
z=data,
x=b0_set,
y=list(simulation_table.errors.keys()),
reversescale=True,
colorscale="Viridis",
hovertemplate="b0: %{x}<br>prefix_len: %{y}<br>" "log(error): %{z}<extra></extra>",
)
)
return figure
def create_heat_map_dashboard(simulation_pb2_file: Path, growth_type: GrowthType, server: Flask):
app = dash.Dash(
name=f"COVID-19 {growth_type} heat map",
server=server,
url_base_pathname=f"/covid19/heatmap/{growth_type}/",
external_scripts=[
"https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.4/MathJax.js?config=TeX-MML-AM_CHTML"
],
)
try:
simulation_reports = create_simulation_reports(simulation_pb2_file)
except (ValueError, FileNotFoundError) as e:
print(e)
app.layout = html.Div(
dcc.Markdown(
f"""
# Error in parsing simulation proto file
The file `{simulation_pb2_file}` failed to parse.
Please contact the site administrator.
"""
),
style={"font-family": "sans-serif"},
)
return app
growth_type = next(iter(simulation_reports)).growth_type
app.title = "Heat map of a COVID-19 stochastic model, with {growth_type} growth"
simulation_tables = group_data(simulation_reports)
graphs = [
dcc.Graph(id=f"{simulation_table.param}", figure=create_heat_map(simulation_table))
for simulation_table in simulation_tables.values()
]
body = (
[
dcc.Markdown(
f"""
# Visualizations of a COVID-19 stochastic model, with {growth_type} growth
Model is by Radoslav Harman. You can read the
[description of the model](http://www.iam.fmph.uniba.sk/ospm/Harman/COR01.pdf).
* Squares correspond to a combination of b<sub>0</sub> and prefix length.
* Heat is the average error for these parameters, averaged over 200 simulations.
We show the logarithm of the error, since we want to emphasize differences
between small values.
""",
dangerously_allow_html=True,
)
]
+ graphs
)
app.layout = html.Div(body, style={"font-family": "sans-serif"})
return app
@click.command(help="COVID-19 simulation heat map for Slovakia")
@click.argument(
"simulation_protofile",
required=True,
type=click_pathlib.Path(exists=True),
)
def show_heat_map(simulation_protofile):
# TODO(lukas): This can be exponential growth, but if the file fails to parse there's no way of
# knowing it.
app = create_heat_map_dashboard(simulation_protofile, GrowthType.Polynomial, True)
app.run_server(host="0.0.0.0", port=8080)
|
Markdown
|
UTF-8
| 3,948 | 2.765625 | 3 |
[] |
no_license
|
#HSLIDE
##Writing Better Java Tests with Spock
[github.com/ssheftel/spock-demo](https://github.com/ssheftel/spock-demo)
#HSLIDE

#HSLIDE
Spock is a testing and specification framework for Java and Groovy apps
#HSLIDE
##History
- spock 2008 by Peter Niederwieser
- default test framework used by Grails
- increasingly popular for java testing
<img src="https://camo.githubusercontent.com/9d97ef423cdcfcef614c8527596b1e0d3e73cd25/687474703a2f2f636f646570697065732e636f6d2f626f6f6b2f6a6176612d74657374696e672d776974682d73706f636b2d626f6f6b2e6a7067" width="200" />
#HSLIDE
Compatibility
- All existing JUnit tools - it uses JUnit runner
- SonarQube
- Spring
#HSLIDE
> What makes it stand out from the crowd is its beautiful and highly expressive specification language.
#HSLIDE
##Syntax
#VSLIDE
```groovy
//HashMapSpec.groovy
import spock.lang.Specification
class HashMapSpec extends Specification {
def "HashMap accepts null key"() {
given: "a hashmap"
def map = [:]
when: "item is inserted with null as key"
map.put(null, "elem")
then: "NullPointerException isn't thrown"
notThrown NullPointerException
map[null] == "elem"
}
}
```
#HSLIDE
##Why use Spock?
#VSLIDE
##Test structure
spock enforces setup-trigger-assert paradigm
#VSLIDE
###Spock blocks → clearly marks phases
- `given`: Creates initial conditions
- `setup`: An alternative name for given:
- `when`: Triggers the action that will be tested
- `then`: Examines results of test
- `and`: Cleaner expression of other blocks
- `expect`: Simpler version of then:
- `where`: Parameterized tests
- `cleanup`: Releases resources
#VSLIDE
##Readability
- Spock tests read like sentences
- Unit tests are specifications
> Any fool can write code that a computer can understand. Good programmers write code that humans can understand. - Kent Beck
#VSLIDE
```groovy
def "Client should have a bonus if he spends more than 100 dollars"() {
when: "a client buys something with value at least 100"
def client = new Client()
def billing = new CreditCardBilling()
billing.charge(client,150)
then: "Client should have the bonus option active"
client.hasBonus() == true
}
```
#VSLIDE
##Better Error Messages

#VSLIDE
##Native Mocking Support
- JUnit needs Mockito
- Mockito does not support partial matchers
```java
when(mock.someMethod(any(), 10)).thenReturn(20);
```
<div style="text-align:center">VS</div>
```groovy
mock.someMethod(_, 10) >> 20
```
##Interactions Expressions
```java
restTemplate.postForEntity(url, msg1, msg2)
```
With Mockito
```java
verify(restTemplate, times(1)).postForEntity(eq("site-url"), anyObject(), anyObject())
```
With Spock
```groovy
1 * restTemplate.postForEntity("site-url", _, _)
```
#VSLIDE
##Less Boilerplate
Groovy is less verbose and more expressive
```groovy
[] // new ArrayList
[:] // new HashMap
obj.name // obj.getName()
new User(name: "spock") // construct and set values
{n -> x % 2 == 0} // closure
(0..9) // range operator
```
#VSLIDE
##Parameterized tests
```groovy
class ImageNameValidatorSpec extends Specification{
def "Valid images are PNG and JPEG files"() {
given: "an image extension checker"
ImageNameValidator validator = new ImageNameValidator()
expect: "that only valid filenames are accepted"
validator.isValidImageExtension(pictureFile) == validPicture
where: "sample image names are"
pictureFile || validPicture
"scenery.jpg" || true
"house.jpeg" || true
"car.png" || true
"sky.tiff" || false
"dance_bunny.gif" || false
}
}
```
#HSLIDE
Demo + Examples
|
Rust
|
UTF-8
| 4,226 | 3 | 3 |
[
"MIT"
] |
permissive
|
//! The vector table.
use core::intrinsics::{offset, transmute, volatile_store};
use core::failure;
use core::fmt;
use platform::io;
static VIC_INT_ENABLE: *mut u32 = (0x10140000 + 0x010) as *mut u32;
static UART0_IRQ: u8 = 12;
static VT: *mut u32 = 0 as *mut u32; // WARNING verify should be mutable.
#[repr(u8)]
pub enum Int {
Reset = 0,
/// In ARM mode, an undefined opcode is used as a breakpoint to break
/// execution[[7]].
Undef,
/// Software interrupt.
SWI,
PrefetchAbort,
DataAbort,
IRQ = 6,
FIQ
}
fn set_word(vector: u8, instruction: u32) {
unsafe {
volatile_store(offset(VT, vector as int) as *mut u32, instruction);
}
}
fn branch(rel: u32) -> u32 {
// b isr ; branch instruction [1]
0xea000000 | (((rel - 8) >> 2) & 0xffffff)
}
/// Exception handlers can be dynamically installed[[1]] into the vector table[[2]].
/// Interrupts must be unmasked with the `VIC_INT_ENABLE`[[3]] interrupt controller register[[4]].
///
/// Enabling interrupts[[5]].
///
/// In ARM mode, an undefined opcode is used as a breakpoint to break execution[[7]].
///
/// When the exception handler has completed execution, the processor restores the state so that the program can resume. The following instructions are used to leave an exception handler[[8]]:
///
/// | Exception | Return instruction |
/// |-----------|--------------------|
/// | UNDEF | `movs pc, lr` |
/// | IRQ, FIQ | `subs pc, lr, #4` |
///
/// [1]: http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0056d/Caccfahd.html
/// [2]: http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0203j/Cihdidh2.html
/// [3]: http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.ddi0273a/Cihiicbh.html
/// [4]: http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dui0225d/I1042232.html
/// [5]: http://balau82.wordpress.com/2012/04/15/arm926-interrupts-in-qemu/ "ARM926 interrupts in QEMU"
/// [7]: http://stackoverflow.com/questions/11345371/how-do-i-set-a-software-breakpoint-on-an-arm-processor "How do I set a software breakpoint on an ARM processor? - Stack Overflow"
/// [8]: http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.ddi0222b/I3108.html "2.9.1. Exception entry and exit summary"
/// [6]: https://github.com/torvalds/linux/blob/
pub struct Table;
impl Table {
pub fn new() -> Table {
Table
}
#[allow(visible_private_types)]
pub fn enable(&self, which: Int, isr: unsafe fn()) {
// Installing exception handlers into the vectors directly [1]
let vector: u8 = unsafe { transmute(which) };
set_word(vector, branch(isr as u32 - (vector as u32 * 4)));
}
pub fn load(&self) {
let mut i = 0;
while i < 10 {
// make every handler loop indefinitely
set_word(i, branch(0));
i += 1;
}
self.enable(Reset, unsafe { transmute(start) });
// breakpoints use an UND opcode to trigger UNDEF. [7]
self.enable(Undef, debug);
unsafe {
// Enable IRQs [5]
asm!("mov r2, sp
mrs r0, cpsr // get Program Status Register
bic r1, r0, #0x1F // go in IRQ mode
orr r1, r1, #0x12
msr cpsr, r1
mov sp, 0x19000 // set IRQ stack
bic r0, r0, #0x80 // Enable IRQs
msr cpsr, r0 // go back in Supervisor mode
mov sp, r2"
::: "r0", "r1", "r2", "cpsr");
// enable UART0 IRQ [4]
*VIC_INT_ENABLE = 1 << UART0_IRQ;
// enable RXIM interrupt
*io::UART0_IMSC = 1 << 4;
}
}
}
extern {
fn start();
}
#[no_mangle]
pub unsafe fn debug() {
asm!("movs pc, lr")
}
// TODO respect destructors
#[lang="begin_unwind"]
unsafe extern "C" fn begin_unwind(fmt: &fmt::Arguments, file: &str, line: uint) -> ! {
loop { };
}
/*
#[lang="fail_"]
#[fixed_stack_segment]
pub fn fail(expr: *u8, file: *u8, line: uint) -> ! {
unsafe { zero::abort(); }
}
#[lang="fail_bounds_check"]
#[fixed_stack_segment]
pub fn fail_bounds_check(file: *u8, line: uint, index: uint, len: uint) {
unsafe { zero::abort(); }
}
*/
|
Java
|
UTF-8
| 1,758 | 2.34375 | 2 |
[
"Apache-2.0"
] |
permissive
|
package com.github.timpeeters.boot.logger;
import org.junit.Test;
import org.springframework.boot.logging.LogLevel;
import org.springframework.mock.web.MockHttpServletRequest;
import java.util.AbstractMap.SimpleEntry;
import static org.assertj.core.api.Assertions.assertThat;
public class HeaderLogLevelSourceTest {
@Test
public void defaultHeaderAbsent() {
assertThat(new HeaderLogLevelSource().getLogLevels(new MockHttpServletRequest())).isEmpty();
}
@Test
public void defaultHeaderPresent() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader(HeaderLogLevelSource.DEFAULT_HEADER_NAME, "com.github.timpeeters=debug");
assertThat(new HeaderLogLevelSource().getLogLevels(request)).containsExactly(
new SimpleEntry<>("com.github.timpeeters", LogLevel.DEBUG));
}
@Test
public void defaultHeaderPresentWithMultipleLoggers() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader(HeaderLogLevelSource.DEFAULT_HEADER_NAME, "com=warn");
request.addHeader(HeaderLogLevelSource.DEFAULT_HEADER_NAME, "com.github=info");
assertThat(new HeaderLogLevelSource().getLogLevels(request)).contains(
new SimpleEntry<>("com", LogLevel.WARN),
new SimpleEntry<>("com.github", LogLevel.INFO));
}
@Test
public void defaultHeaderPresentRootLogger() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.addHeader(HeaderLogLevelSource.DEFAULT_HEADER_NAME, "root=warn");
assertThat(new HeaderLogLevelSource().getLogLevels(request)).containsExactly(
new SimpleEntry<>("root", LogLevel.WARN));
}
}
|
Java
|
UTF-8
| 455 | 2.859375 | 3 |
[] |
no_license
|
public class k
{
static void main()
{
boolean x=false;
do
{
System.out.println("Good Work!");
}
while(x);
for(int i=1;i<=3;i++)
{
if(i==2)
{
continue;
}
System.out.println(i);
}
int i,j;
for(i=1,j=10;i<=3;i++,j--)
{
System.out.println(j+"\t"+i+"+\n");
}
}
}
|
Ruby
|
UTF-8
| 1,464 | 2.515625 | 3 |
[] |
no_license
|
class User < ApplicationRecord
has_secure_password
has_many :reservations, foreign_key: "guest_id", dependent: :destroy
has_many :kitchens, foreign_key: "owner_id"
has_many :kitchen_pictures, through: :kitchens
has_many :reviewed_kitchens, class_name: "KitchenReview", foreign_key: "guest_id", dependent: :destroy
has_many :owners, through: :kitchens
has_many :sent_messages, class_name: "Message", foreign_key: "sender_id"
has_many :received_messages, class_name: "Message", foreign_key: "recipient_id"
def session_hash
response = {}
response[:user] = self
response[:reservations] = self.reservations
response[:kitchens] = self.kitchens
response[:kitchen_reviews] = self.reviewed_kitchens
response[:kitchen_pictures] = self.kitchens.map {|k| k.kitchen_pictures[0]}
response[:kitchen_reservations] = self.kitchens.map {|k| k.reservations}.flatten
response[:reviews_of_users_kitchens] = self.kitchens.map {|k| k.reviews}.flatten
response[:received_messages] = self.received_messages
response[:sent_messages] = self.sent_messages
response[:reservations_kitchens] = self.reservations.map{|r| r.kitchen}.uniq
response[:reservations_kitchens_pictures] = self.reservations.map{|r| r.kitchen}.uniq.map{|k| k.kitchen_pictures[0]}
response
end
def unread_messages
self.received_messages.select{|m| !m.read}
end
def read_messages
self.received_messages.select{|m| m.read}
end
end
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.