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
|
|---|---|---|---|---|---|---|---|
C#
|
UTF-8
| 2,825
| 3.5
| 4
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Blackjack
{
public class Hand
{
public Card[] hand { get; private set; }
public string playerAndDealer { get; private set; }
public int score { get; private set; }
public Hand(string p)
{
score = 0;
playerAndDealer = p;
}
public void TakeCard(Card dealtCard)
{
if (hand == null)
{
hand = new Card[1];
hand[0] = dealtCard;
}
else
{
Card[] temporaryHand = hand;
hand = new Card[temporaryHand.Length + 1];
temporaryHand.CopyTo(hand, 0);
hand[hand.GetUpperBound(0)] = dealtCard;
}
Score();
}
private void Score()
{
score = 0;
bool ace = false;
foreach (Card cardHand in hand)
{
switch (cardHand.cardRank)
{
case Card.Rank.Ace:
score += 1;
ace = true;
if (ace == true && score + 10 <= 21)
{
score += 10;
}
break;
case Card.Rank.Two:
score += 2;
break;
case Card.Rank.Three:
score += 3;
break;
case Card.Rank.Four:
score += 4;
break;
case Card.Rank.Five:
score += 5;
break;
case Card.Rank.Six:
score += 6;
break;
case Card.Rank.Seven:
score += 7;
break;
case Card.Rank.Eight:
score += 8;
break;
case Card.Rank.Nine:
score += 9;
break;
case Card.Rank.Ten:
score += 10;
break;
case Card.Rank.Jack:
score += 10;
break;
case Card.Rank.Queen:
score += 10;
break;
case Card.Rank.King:
score += 10;
break;
default:
break;
}
}
}
}
}
|
Java
|
UTF-8
| 8,006
| 2.5625
| 3
|
[] |
no_license
|
package cst338.p1.tests;
import static org.junit.Assert.*;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import cst338.p1.CourseDuplicateException;
import cst338.p1.CourseFullException;
import cst338.p1.CourseMissingException;
import cst338.p1.CourseNotEmptyException;
import cst338.p1.EnrollmentDuplicateException;
import cst338.p1.EnrollmentMissingException;
import cst338.p1.StudentDuplicateException;
import cst338.p1.StudentMissingException;
import cst338.p1.data.Database;
import cst338.p1.data.EnrollmentRecord;
import cst338.p1.data.StudentRecord;
public class DatabaseStudentCourseLinkageTests {
@Rule
public ExpectedException thrown = ExpectedException.none();
@Test
public void ensureEnrolledOnLinked()
throws CourseDuplicateException, StudentDuplicateException, EnrollmentDuplicateException,
CourseMissingException, StudentMissingException, CourseFullException {
Database db = new Database();
db.createStudent(100, "StudeXtnt");
db.createCourse(100, "100 - Course", 10, "ROOM 1");
db.linkStudentCourse(100, 100);
assertTrue(db.doesEnrollmentExist(100, 100));
}
@Test
public void ensureExceptionOnEnrolledIfAlreadyEnrolled()
throws StudentDuplicateException, CourseDuplicateException, EnrollmentDuplicateException,
CourseMissingException, StudentMissingException, CourseFullException {
Database db = new Database();
db.createStudent(100, "Student");
db.createCourse(100, "100 - Course", 10, "ROOM 1");
db.linkStudentCourse(100, 100);
thrown.expect(EnrollmentDuplicateException.class);
db.linkStudentCourse(100, 100);
fail("Should have thrown exception.");
}
@Test
public void ensureExceptionOnEnrolledIfMissingStudent()
throws CourseDuplicateException, EnrollmentDuplicateException, CourseMissingException,
StudentMissingException, CourseFullException {
Database db = new Database();
db.createCourse(100, "100 - Course", 10, "ROOM 1");
thrown.expect(StudentMissingException.class);
db.linkStudentCourse(100, 100);
fail("Should have thrown exception.");
}
@Test
public void ensureExceptionOnEnrolledIfMissingCourse()
throws EnrollmentDuplicateException, CourseMissingException, StudentMissingException,
CourseFullException, StudentDuplicateException {
Database db = new Database();
db.createStudent(100, "Student");
thrown.expect(CourseMissingException.class);
db.linkStudentCourse(100, 100);
fail("Should have thrown exception.");
}
@Test
public void ensureExceptionOnEnrolledIfCourseFull()
throws StudentDuplicateException, EnrollmentDuplicateException, CourseMissingException,
StudentMissingException, CourseFullException, CourseDuplicateException {
Database db = new Database();
db.createCourse(100, "100 - Course", 10, "ROOM 1");
for (int i = 0; i < 10; i++) {
db.createStudent(i, "Student");
db.linkStudentCourse(i, 100);
}
db.createStudent(11, "Bob");
thrown.expect(CourseFullException.class);
db.linkStudentCourse(11, 100);
fail("Should have thrown exception.");
}
@Test public void ensureUnenrolledOnUnenroll() throws StudentDuplicateException, CourseDuplicateException, EnrollmentDuplicateException, CourseMissingException, StudentMissingException, CourseFullException, EnrollmentMissingException{
Database db = new Database();
db.createStudent(100, "Studetnt");
db.createCourse(100, "100 - Course", 10, "ROOM 1");
db.linkStudentCourse(100, 100);
db.unlinkStudentCourse(100,100);
assertFalse(db.doesEnrollmentExist(100, 100));
}
@Test public void ensureExceptionOnUnenrollIfMissingStudent() throws CourseDuplicateException, EnrollmentDuplicateException, CourseMissingException, StudentMissingException, CourseFullException, EnrollmentMissingException, StudentDuplicateException{
Database db = new Database();
db.createCourse(100, "100 - Course", 10, "ROOM 1");
db.createStudent(100, "Student");
db.linkStudentCourse(100, 100);
db.deleteStudent(100);
thrown.expect(StudentMissingException.class);
db.unlinkStudentCourse(100,100);
fail("Should have thrown exception.");
}
@Test public void ensureExceptionOnUnenrollIfMissingCourse() throws CourseMissingException, CourseNotEmptyException, EnrollmentDuplicateException, StudentMissingException, CourseFullException, StudentDuplicateException, CourseDuplicateException, EnrollmentMissingException{
Database db = new Database();
db.createStudent(100, "Student");
thrown.expect(CourseMissingException.class);
db.unlinkStudentCourse(100,101);
fail("Should have thrown exception.");
}
@Test public void ensureExceptionOnUnenrollIfNotEnrolled() throws EnrollmentMissingException, CourseMissingException, StudentMissingException, StudentDuplicateException, CourseDuplicateException{
Database db = new Database();
db.createCourse(100, "100 - Course", 10, "ROOM 1");
db.createStudent(100, "Student");
thrown.expect(EnrollmentMissingException.class);
db.unlinkStudentCourse(100,100);
fail("Should have thrown exception.");
}
@Test public void ensureCorrectOnCoursesForStudentQuery() throws CourseDuplicateException, StudentDuplicateException, EnrollmentDuplicateException, CourseMissingException, StudentMissingException, CourseFullException, EnrollmentMissingException{
Database db=new Database();
db.createStudent(100,"Seth");
db.createCourse(2000, "A", 1,"Room 1");
db.createCourse(2001, "B", 1,"Room 1");
db.createCourse(2002, "C", 1,"Room 1");
db.createCourse(2003, "D", 1,"Room 1");
db.linkStudentCourse(100,2000);
db.linkStudentCourse(100,2001);
db.linkStudentCourse(100,2002);
db.linkStudentCourse(100,2003);
db.unlinkStudentCourse(100,2000);
db.unlinkStudentCourse(100,2001);
db.linkStudentCourse(100,2000);
List<EnrollmentRecord> enrollments=db.selectStudentCourses(100);
Map<Integer,Boolean> expectedRecords=new HashMap<>();
expectedRecords.put(2000,false);
expectedRecords.put(2002,false);
expectedRecords.put(2003,false);
for(EnrollmentRecord enrollment:enrollments){
if(expectedRecords.containsKey(enrollment.getCourseId())){
expectedRecords.put(enrollment.getCourseId(),true);
}else{
fail("Unexpected enrollment detected.");
}
}
for(Entry<Integer,Boolean> entry:expectedRecords.entrySet()){
if(!entry.getValue()){
fail("Missing enrollment for class "+entry.getKey());
}
}
}
@Test public void ensureCorrectOnStudentsForCourseQuery() throws CourseMissingException, EnrollmentDuplicateException, StudentMissingException, CourseFullException, EnrollmentMissingException, CourseDuplicateException, StudentDuplicateException{
Database db=new Database();
db.createStudent(100,"Seth");
db.createStudent(101,"Champ");
db.createStudent(102,"Glah");
db.createCourse(2000, "A", 3,"Room 1");
db.linkStudentCourse(100,2000);
db.linkStudentCourse(101,2000);
db.linkStudentCourse(102,2000);
db.unlinkStudentCourse(102,2000);
db.unlinkStudentCourse(101, 2000);
db.linkStudentCourse(101, 2000);
db.selectCourseStudents(2000);
List<StudentRecord> students=db.selectCourseStudents(2000);
Map<Integer,Boolean> expectedRecords=new HashMap<>();
expectedRecords.put(100,false);
expectedRecords.put(101,false);
for(StudentRecord student:students){
if(expectedRecords.containsKey(student.getId())){
expectedRecords.put(student.getId(),true);
}
else{
fail("Unexpected enrollment.");
}
}
for(Entry<Integer,Boolean> entry:expectedRecords.entrySet()){
if(!entry.getValue()){
fail("Missing class for student "+entry.getKey());
}
}
}
}
|
JavaScript
|
UTF-8
| 253
| 2.8125
| 3
|
[] |
no_license
|
class App extends React.Component {
constructor(props) {
super(props); // calls the constructor of the extended class
// which is React.Component
}
render() {
return <h2>Hello, this is the App component</h2>;
}
}
|
Python
|
UTF-8
| 2,154
| 2.875
| 3
|
[
"MIT"
] |
permissive
|
import batma
from models import *
class Lose(batma.Scene):
def load_content(self):
self.label = batma.Text('Loser...', batma.display.center)
def update(self, tick):
if batma.mouse.is_any_pressed():
batma.game.new_game()
def draw(self):
self.label.draw()
class Win(batma.Scene):
def load_content(self):
self.label = batma.Text('Winner!', batma.display.center)
def update(self, tick):
if batma.mouse.is_any_pressed():
batma.game.new_game()
def draw(self):
self.label.draw()
class LevelScene(batma.Scene):
def initialize(self):
self.level = batma.game.level
self.player = batma.game.player
self.n_foes = batma.game.n_foes
self.n_goals = batma.game.n_goals
batma.display.show_fps = True
# batma.display.show_colliders = True
batma.display.show_cursor = False
batma.display.background_color = batma.game.colors[self.level]
def reset(self):
self.foes.clear()
self.goals.clear()
for i in xrange(self.n_foes):
self.foes.add(Foe(batma.Vector2(200, 200)))
for i in xrange(self.n_goals):
self.goals.append(Goal())
def load_content(self):
self.foes = batma.Group()
self.goals = batma.Group()
self.reset()
def unload_content(self):
pass
def update(self, tick):
self.player.update(tick)
self.foes.update(tick)
# Foe Collision
if self.foes.any_colliding(self.player):
self.player.life -= 1
self.reset()
# Goal Collision
for obj in self.goals.objs_colliding(self.player):
self.goals.remove(obj)
self.n_goals -= 1
# Win Verification
if self.n_goals == 0:
batma.game.next_level()
# Lose Verification
if self.player.life == 0:
batma.game.lose()
if batma.keyboard.is_pressed('jump'):
print self.n_goals
def draw(self):
self.goals.draw()
self.foes.draw()
self.player.draw()
|
Python
|
UTF-8
| 2,114
| 2.578125
| 3
|
[] |
no_license
|
from matplotlib import pyplot as plt
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Conv2D, MaxPooling2D, Dropout, Flatten, Dense
from tensorflow.keras.optimizers import Adam
from dataprocessor import data_process
import os
def build_model(model):
model.add(Conv2D(32, (5, 5), padding='SAME', activation='relu', input_shape=(150, 150, 3)))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.5))
model.add(Conv2D(64, (5, 5), padding='SAME', activation='relu'))
model.add(MaxPooling2D(pool_size=(2, 2)))
model.add(Dropout(0.5))
model.add(Flatten())
model.add(Dense(256, activation='relu'))
model.add(Dropout(0.5))
model.add(Dense(1, activation='sigmoid'))
model.summary()
return model
def run(model):
model.compile(Adam(learning_rate=0.001),
loss='binary_crossentropy',
metrics=['accuracy'])
def evaluator(model):
(train_generator, validation_generator, test_generator) = data_process()
history = model.fit(train_generator,
batch_size=32,
epochs=30,
validation_data=validation_generator,
verbose=1)
print(history.history.keys())
model.save('D:\\Program Files\\pythonProject\\covid.h5')
plt.plot(history.history['loss'])
plt.plot(history.history['val_loss'])
plt.legend(['Training', 'Validation'])
plt.title('Training and Validation losses')
plt.xlabel('epoch')
plt.plot(history.history['accuracy'])
plt.plot(history.history['val_accuracy'])
plt.legend(['Training', 'Validation'])
plt.title('Training and Validation accuracy')
plt.xlabel('epoch')
test_loss, test_acc = model.evaluate(test_generator)
print('test loss: {} test acc: {}'.format(test_loss, test_acc))
if __name__ == '__main__':
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
model = Sequential()
model = build_model(model)
run(model)
evaluator(model)
# data_process()
|
C
|
UTF-8
| 1,742
| 3.9375
| 4
|
[] |
no_license
|
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/**********
Crie uma struct palavra para armazenar um texto de no máximo 100 bytes,
quantidade de vogais e quantidade de consoantes. Crie um programa com uma
função leArquivo para ler palavras de um arquivo e preencher o vetor, alocado
dinamicamente, com entradas da estrutura Palavra, e também com uma função para exibir
as contagens de vogais e consoantes.
struct palavra * leArquivo(const char * arquivo);
void imprimePalavras(const struct palavra * palavras, int tamanho);
**********/
struct Palavra {
char texto[100];
int quantidade_vogais;
int quantidade_consoantes;
};
struct Palavra * lerArquivo(const char * arquivo){
struct Palavra *p = malloc(sizeof(struct Palavra));
p->quantidade_vogais = 0;
p->quantidade_consoantes = 0;
int i;
FILE * fp = fopen(arquivo, "r");
fgets(p->texto, sizeof(p->texto), fp);
//fscanf(fp,"%s",palavra)
int tamanho = strlen(p->texto);
for (i = 0; i < tamanho; i++){
if (p->texto[i] == 'a' || p->texto[i] == 'e' || p->texto[i] == 'i' || p->texto[i] == 'o' || p->texto[i] == 'u')
{
//printf("%d\n", p->quantidade_vogais);
p->quantidade_vogais = p->quantidade_vogais + 1;
}else{
// printf("%d\n", p->quantidade_consoantes);
p->quantidade_consoantes = p->quantidade_consoantes + 1;
}
}
fclose(fp);
return p;
}
void imprimePalavras(const struct Palavra * palavras, int tamanho){
printf("%s\n", palavras);
printf("%d\n", tamanho);
}
int main()
{
struct Palavra *a;
a = lerArquivo("arquivo.txt");
printf("Vogais: %d\n",a->quantidade_vogais);
printf("Consoantes: %d\n",a->quantidade_consoantes);
imprimePalavras(a->texto,strlen(a->texto));
return 0;
}
|
Java
|
UTF-8
| 4,854
| 2.03125
| 2
|
[] |
no_license
|
package psd.stats;
import org.apache.flink.api.java.tuple.Tuple2;
import psd.alerts.*;
import java.util.ArrayList;
import java.util.List;
public class StatsChecker {
/**
* // For testing (first 100 samples):
* private static final double[] MEAN_THRESHOLD = {-0.006894507, 0.004927153, 0.00134661, -0.001135192, 0.003586044, -0.01379235};
* private static final double[] MEDIAN_THRESHOLD = {-0.002762632, 0.01151195, -0.002524657, -0.003271306, 0.006812286, -0.02584299};
* private static final double[] QUANTILE_THRESHOLD = {-0.07934302, -0.07264282, -0.07145597, -0.07667505, -0.07903422, -0.08632244};
* private static final double[] MEAN_FROM_MIN_RATES_THRESHOLD = {-0.08980066, -0.08159521, -0.086443, -0.09122514, -0.08923056, -0.09611306};
* private static final double[] SAFETY_RATE_AVG_DEV_THRESHOLD = {0.02552551, 0.0251733, 0.02181392, 0.02429839, 0.02354965, 0.02586854};
* private static final double[] SAFETY_RATE_GINI_THRESHOLD = {0.06781909, 0.06622779, 0.06090565, 0.06642242, 0.06432812, 0.06894819};
**/
private static final double[] MEAN_THRESHOLD = {2.741122e-05, 9.557385e-06, -7.064e-06, 8.467337e-05, 7.915884e-05, 3.187289e-05};
private static final double[] MEDIAN_THRESHOLD = {8.58e-05, 1.625e-05, 4.005e-06, 0.000182586, 4.775e-05, 2.05e-05};
private static final double[] QUANTILE_THRESHOLD = {-0.07981682, -0.08011171, -0.0797318, -0.08006085, -0.07988979, -0.07994182};
private static final double[] MEAN_FROM_MIN_RATES_THRESHOLD = {-0.08989526, -0.09005075, -0.08987406, -0.09004942, -0.08990006, -0.08999679};
private static final double[] SAFETY_RATE_AVG_DEV_THRESHOLD = {0.02492365, 0.02500448, 0.0249166, 0.02502468, 0.02497435, 0.02498649};
private static final double[] SAFETY_RATE_GINI_THRESHOLD = {0.06651252, 0.06668754, 0.06647875, 0.06671993, 0.06659843, 0.06664281};
private StatsChecker() {
}
// Produces alerts on events that values are 10% lower than constant threshold
public static List<StatsAlert> produceAlertsFor(Tuple2<Integer, StatsAggregationResult> tuple) {
final List<StatsAlert> alertsProduced = new ArrayList<>();
final int assetId = tuple.f0;
final int index = assetId - 1;
final StatsAggregationResult result = tuple.f1;
final int windowId = result.getWindowId();
if (result.getMean() < MEAN_THRESHOLD[index]) {
double value = result.getMean();
double threshold = MEAN_THRESHOLD[index];
double percentage = StatsHelper.calculatePercentage(value, threshold);
if (StatsHelper.higherThanMaxTolerance(percentage)) {
alertsProduced.add(new MeanAlert(windowId, assetId, percentage, threshold, value));
}
}
if (result.getMedian() < MEDIAN_THRESHOLD[index]) {
double value = result.getMedian();
double threshold = MEDIAN_THRESHOLD[index];
double percentage = StatsHelper.calculatePercentage(value, threshold);
if (StatsHelper.higherThanMaxTolerance(percentage)) {
alertsProduced.add(new MedianAlert(windowId, assetId, percentage, threshold, value));
}
}
if (result.getQuantile() < QUANTILE_THRESHOLD[index]) {
double value = result.getQuantile();
double threshold = QUANTILE_THRESHOLD[index];
double percentage = StatsHelper.calculatePercentage(value, threshold);
if (StatsHelper.higherThanMaxTolerance(percentage)) {
alertsProduced.add(new QuanitleAlert(windowId, assetId, percentage, threshold, value));
}
}
if (result.getMeanFromMinRates() < MEAN_FROM_MIN_RATES_THRESHOLD[index]) {
double value = result.getMeanFromMinRates();
double threshold = MEAN_FROM_MIN_RATES_THRESHOLD[index];
double percentage = StatsHelper.calculatePercentage(value, threshold);
if (StatsHelper.higherThanMaxTolerance(percentage)) {
alertsProduced.add(new MeanFromMinRates(windowId, assetId, percentage, threshold, value));
}
}
if (result.getSafetyRateAverageDeviation() < SAFETY_RATE_AVG_DEV_THRESHOLD[index]) {
double value = result.getSafetyRateAverageDeviation();
double threshold = SAFETY_RATE_AVG_DEV_THRESHOLD[index];
double percentage = StatsHelper.calculatePercentage(value, threshold);
if (StatsHelper.higherThanMaxTolerance(percentage)) {
alertsProduced.add(new SafetyRateAlert(windowId, assetId, percentage, threshold, value));
}
}
if (result.getSafetyRateGini() < SAFETY_RATE_GINI_THRESHOLD[index]) {
double value = result.getSafetyRateGini();
double threshold = SAFETY_RATE_GINI_THRESHOLD[index];
double percentage = StatsHelper.calculatePercentage(value, threshold);
if (StatsHelper.higherThanMaxTolerance(percentage)) {
alertsProduced.add(new SafetyRateGiniAlert(windowId, assetId, percentage, threshold, value));
}
}
return alertsProduced;
}
}
|
Go
|
UTF-8
| 2,380
| 3.171875
| 3
|
[] |
no_license
|
package main
import (
"context"
"fmt"
"genLink/proto/api"
"google.golang.org/grpc"
"log"
"os"
)
func Сhoice(cli api.GenLinkClient) {
file, err := os.OpenFile("log.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
if err != nil {
log.Fatal(err)
}
log.SetOutput(file)
var start string
const Create = "1"
const Get = "2"
const Exit = "3"
fmt.Print("\nЧто будем делать?\n" +
"1. Генерировать сокращенную ссылку\n" +
"2. Использовать короткую ссылку для получения первичной ссылки\n" +
"3. Выйти\n" +
"Выбери пункт:")
fmt.Scan(&start)
var link string
switch start {
case Create:
fmt.Print("Вставь ссылку:")
fmt.Scan(&link)
result, err := cli.Create(context.Background(), &api.URL{URL: link})
if err != nil {
log.Println(err)
log.Fatalf("Error in grpcserver, method Create: %s", err)
}
fmt.Printf("Короткая ссылка: %s\n", result.ShortURL)
Сhoice(cli)
case Get:
fmt.Print("Вставь короткую ссылку:")
fmt.Scan(&link)
result, err := cli.Get(context.Background(), &api.ShortURL{ShortURL: link})
if err != nil {
log.Println(err)
log.Fatalf("Error in grpcserver, method Get: %s", err)
}
if result.URL != "empty" {
fmt.Printf("Найдена длинная ссылка: %s\n", result.URL)
} else {
fmt.Print("Этой ссылке ничего не соответствует :(\n")
}
Сhoice(cli)
case Exit:
fmt.Print("\nПрощай!")
os.Exit(0)
default:
fmt.Print("\nТакой команды нет. Попробуй еще!\n")
Сhoice(cli)
}
}
func main() {
file, err := os.OpenFile("log.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0666)
if err != nil {
log.Fatal(err)
}
log.SetOutput(file)
fmt.Print("Привет, это сокращатель ссылок!\n")
//создаем соединение с grpc сервером
conn, err := grpc.Dial("127.0.0.1:9080", grpc.WithInsecure())
if err != nil {
log.Println(err)
panic(err)
}
//создаем клиента с помощью сгенерированного кода
cli := api.NewGenLinkClient(conn)
//вызываем функцию, которая общается с нами и вызывает удаленные функции
Сhoice(cli)
}
|
Markdown
|
UTF-8
| 8,616
| 3.328125
| 3
|
[] |
no_license
|
# Motivation
## Why bipedal walking?
* Robots should be able to navigate in environments made for humans:
* Little space
* Obstacles (e.g. stairs)
$\Rightarrow$ Wheeled base not flexible enough.
* **Problem:** How do you guarantee stability during walking?
## The Human Gait
* Of primary interest for stability: Number of feet that are in contact with ground
* Dual support phase: Shift weight from last support leg to next one
* Single support phase: Move swing leg to next foot position
\begin{figure}[b]
\includegraphics[width=\textwidth,resolution=300]{images/human_gait.png}
\center{
\tiny{Source: Dynamics of Human Gait}
}
\end{figure}
## Application to robots?
1. Adapt recorded human motions to robot:
* Kinematic structure and dynamic properties are different: Mapping needs to be found.
* Mapping is computationally expensive (offline), but trajectory looks very natural
2. Derive stable trajectories from dynamic models of the robot:
* Most popular: 3D-Linear Inverted Pendulum Model and ZMP
* Simplification: Height of the CoM is constant with respect to ground (only approximately true for humans see Orendurff et al. \cite{orendurff2004effect})
* Can be computed online, but looks less natural
This work is build on the second approach.
## 3D Linear Inverted Pendulum Model
\begin{columns}
\begin{column}{0.55\textwidth}
\begin{itemize}
\item Simplified dynamic description of robot
\item Reduce robot to pendulum with massless rod and point contact
\item \textit{Linear actuator} in rod of pendulum
\item Mass of robot gets reduced to the \textit{CoM} $c = (c_x, c_y)^T$ (the head of the pendulum)
\item To make the dynamics \textit{linear} we constrain the head of the pendulum
to a constant height
\end{itemize}
\end{column}
\begin{column}{0.45\textwidth}
\begin{figure}
\begin{center}
\includegraphics[width=\textwidth]{images/3dlimp.png}
\end{center}
\end{figure}
\vspace{-1.5em}
Resulting Equation:
\begin{equation*}
\ddot{c}_x = \frac{g}{z_c} c_x
\end{equation*}
\end{column}
\end{columns}
## Contact forces
We can reduce all contact forces acting on the foot to a single force at the *Center of Pressure* which is computed as:
\begin{columns}
\begin{column}{0.5\textwidth}
\begin{equation*} \label{eq:zmp-definition}
p := \left(\begin{array}{c}
p_x \\ p_y \\ p_z
\end{array}\right)
= \frac{\sum^N_{i=1}p_i f_{iz}}{\sum^N_{i=1} f_{iz}}
\end{equation*}
\end{column}
\begin{column}{0.5\textwidth}
\begin{figure}[b]
\includegraphics[width=\textwidth,resolution=300]{images/contact_forces.png}
\end{figure}
\end{column}
\end{columns}
* If all contact forces are in the same plane: Torque around $x$ and $y$ axis at this point is zero
* Thus we can call this point the *Zero Moment Point* (ZMP).
## Why is the ZMP interesting?
1. Describes the *foot-floor contact dynamics* in case of flat ground contact
2. Can be used to derive a *condition to ensure dynamically stable pose*:
If the ZMP is **strictly inside the support polygon**, the foot-floor contact will be preserved.
Use 2. to derive dynamically stable trajectory by constraining ZMP to support polygones:
\begin{figure}[b]
\includegraphics[width=0.5\textwidth,resolution=300]{images/zmp_steps.png}
\end{figure}
## Cart-Table-Model
\begin{columns}
\begin{column}{0.5\textwidth}
\begin{itemize}
\item Simple model to compute the ZMP
\item Does not require knowledge about contact forces
\item For each dimension: Cart on massless table
\item Cart represents the CoM of the robot
\item Foot of the table corresponds to the support polygon
\end{itemize}
Resulting ZMP:
\begin{equation*} \label{eq:zmp-x}
p_x = c_x - \frac{z_c}{g} \ddot{c_x}
\end{equation*}
\end{column}
\begin{column}{0.5\textwidth}
\begin{figure}
\begin{center}
\includegraphics[width=\textwidth]{images/carttable.png}
\end{center}
\end{figure}
\end{column}
\end{columns}
# Walking Pattern Generation
## Pattern generation as control problem
* **Idea:** Formulate dynamic walking as a control problem
* **Goal:** Realize given reference ZMP position
* **Result:** Array of system states (position, velocity, acceleration of the CoM and realized ZMP position)
* **Implementation**: Uses a Preview Controller (Kajita et al. 2003 \cite{kajita2003biped}) that utilizes knowledge about the future trajectory
\begin{figure}
\begin{center}
\includegraphics[width=\textwidth]{images/pattern_generator_architechture.png}
\end{center}
\end{figure}
## Video of pattern based walking
\begin{figure}
\begin{center}
\includemovie[poster]{6cm}{4cm}{../Videos/10_steps_unstabilized.mp4}
\end{center}
\end{figure}
# Walking Stabilization
## Stabilizer
* **Problem:** Disturbances cause instabilities (even though the pattern is dynamically stable!)
* **Solution:** Adapt pattern to disturbances $\rightarrow$ stabilizer
* **Implemented:** Stabilizer based on Kajita et al. 2010 \cite{kajita2010biped}. Adapts frames in Cartesian space (no torque control needed).
\begin{figure}
\begin{center}
\includegraphics[width=\textwidth]{images/stabilizer_architechture.png}
\end{center}
\end{figure}
## Ankle torques
**Problem:** Needs accurately measured torques. Bullet does not provide realistic torques.
\begin{figure}
\begin{center}
\includegraphics[width=\textwidth]{images/ankle_torques.png}
\end{center}
\end{figure}
## Heuristic Stabilizer
* Works very similar to stabilizer proposed by Kajita
* Instead of torque feedback, we use the pose of error of the frames
* **Problem**: Accurately measuring pose error for each frame not possible in reality
\begin{figure}
\begin{center}
\includegraphics[width=\textwidth]{images/heuristic_architechture.png}
\end{center}
\end{figure}
## Stabilized walking in a circle
\begin{figure}
\begin{center}
\includegraphics[width=\textwidth]{images/undisturbed_circle.png}
\end{center}
\end{figure}
\begin{figure}
\begin{center}
\includemovie[poster]{3cm}{2cm}{../Videos/circle.mp4}
\end{center}
\caption{Walking in a half-circle.}
\end{figure}
## Walking with disturbances
\begin{figure}
\begin{center}
\includegraphics[width=\textwidth]{images/disturbed_front_straight_x.png}
\end{center}
\end{figure}
\vspace{-2.5em}
\begin{columns}
\begin{column}{5cm}
\begin{figure}
\begin{center}
\includemovie[poster]{5cm}{1cm}{../Videos/push_front_unstabilized.mp4}
\end{center}
\caption{Push without stabilization}
\end{figure}
\end{column}
\begin{column}{5cm}
\begin{figure}
\begin{center}
\includemovie[poster]{5cm}{1cm}{../Videos/push_front.mp4}
\end{center}
\caption{Push with stabilization.}
\end{figure}
\end{column}
\end{columns}
# Push recovery
## Push recovery based on Capture Point
* The (immediate) Capture Point is defined as the point on the floor,
where by placing the base of the pendulum there, the CoM would come to a rest. \cite{koolen2012capturability}
* **Problem:** The base needs to be moved instantaneously to the Capture Point,
but foot would at least need $t_{min}$ seconds.
* **Solution:** Predict the future position of the immediate Capture Point in $t_{min}$
\begin{figure}
\begin{center}
\includegraphics[width=\textwidth]{images/recovery_architechture.png}
\end{center}
\end{figure}
## Capture Point Video
\begin{figure}
\begin{center}
\includemovie[poster]{5cm}{5cm}{../Videos/recovery.mp4}
\end{center}
\caption{Push recovery, standing on left leg.}
\end{figure}
# Conclusion & Future Work
## Implementation
* All algorithms implemented independent of the physical simulation (```libBipedal```):
```https://github.com/TheMarex/libbipedal```
* Simulator using Simox with SimDynamics:
```https://i61wiki.itec.uka.de/git/simdynamicsviewer.git```
* All C++11, needs Simox, MMMCore and Bullet 2.82 with double support
\begin{figure}
\begin{center}
\includegraphics[width=\textwidth]{images/architechture.png}
\end{center}
\end{figure}
## Conclusion
* Implemented a **dynamic simulator** that can test MMM trajectories
* **Verified** walking patterns in dynamic simulation
* Implemented multiple **stabilizers** and tested in simulation
* Implemented simple **push recovery** mechanism based on the Capture Point
## Future Work
* Implement different pattern generation schemes (simple 3D-LIPM based, CP based)
* Make walking more natural: Use toe joint.
$\rightarrow$ Kajita et al. \cite{kajita2012evaluation} proposed extension of the
methodes implemented here to include a toe support phase
* Better push recovery: General case, use extended LIP models proposed by Pratt
|
Java
|
UTF-8
| 361
| 2.453125
| 2
|
[] |
no_license
|
package com.m2d2apps.catviewer.models;
import java.util.ArrayList;
import java.util.List;
public class PhotosList {
ArrayList<Photo> data;
public PhotosList() {
data = new ArrayList<Photo>();
}
public ArrayList<Photo> getPhotos() {
return data;
}
public void addPhoto(Photo photo) {
data.add(photo);
}
}
|
JavaScript
|
UTF-8
| 2,597
| 3.03125
| 3
|
[] |
no_license
|
class MathFactsOutcome extends Phaser.Scene {
constructor() {
super({ key: 'MathFactsOutcome' });
}
init(data) {
this.numDone = data.completed;
this.playerTime = data.time;
this.correct = data.score;
this.operation = data.operator;
}
preload() {
this.load.audio('applause', 'audio/applause.mp3');
}
create() {
// set listener
this.input.keyboard.on('keyup_A', this.personalBest, this);
let seconds = 120 - this.playerTime;
let minutes = Phaser.Math.FloorTo(seconds / 60);
seconds = seconds % 60;
let zero = (seconds < 10) ? ":0" : ":";
this.gameTime = minutes + zero + seconds;
let fontStyle = '36px Arial';
this.add.text(70, 100, "Your time was " + this.gameTime + ".", { font: fontStyle, color: '#000000' })
this.add.text(70, 175, "You completed " + this.numDone + " math facts.", { font: fontStyle, color: '#000000' })
this.add.text(70, 250, "Your score was " + this.correct + " correct!", { font: fontStyle, color: '#000000' })
let outcome = "";
if (this.playerTime < 120 && this.correct >= 95) {
switch (this.operation) {
case "1":
outcome = "You have mastered Addition!"
break;
case "2":
outcome = "You have mastered Subtraction!"
break;
case "3":
outcome = "You have mastered Multiplication!"
break;
case "4":
outcome = "Congratulations! You are a Math Facts Master!"
break;
}
if (outcome != "") {
this.add.text(70, 350, outcome, { font: fontStyle, color: '#000000' })
this.applause();
}
} else {
this.add.text(70, 400, "If this score is a personal best, \npress the A key to give yourself a hand!", { font: fontStyle, color: '#000000' })
}
}
applause() {
// play appause!
let effect = this.sound.add('applause');
effect.play({
name: '',
start: 0,
duration: effect.duration,
config: {
mute: false,
volume: 0.1,
rate: 1,
loop: false,
delay: 0
}
});
}
personalBest() {
if (event.keyCode === Phaser.Input.Keyboard.KeyCodes.A) {
this.applause();
}
}
}
|
C++
|
UTF-8
| 190
| 2.6875
| 3
|
[] |
no_license
|
#include "stdio.h"
int main(){
int round = 0;
printf("Enter 2D = ");
scanf("%d",&round);
for(int i=0;i<round;i+=1){
for(int j=0;j<=i;j+=1){
printf("*");
}
printf("\n\n");
}
}
|
Java
|
UTF-8
| 1,239
| 3.640625
| 4
|
[] |
no_license
|
package com.carrysk.Demo06IOAndProperties;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
/**
* public abstract write(byte[] b) 将byte[] b 写入文件
* public abstrack write(byte[] b, int begin, int len); begin 就是开始下标 len 是写的长度
*
* 注意 字节在0~128之间是ascall 之外是系统默认的码表 一个负数加一个数 组成中文
*/
public class Demo02OutputStream {
public static void main(String[] args) throws IOException {
// 创建一个文件输出流对象
FileOutputStream fos = new FileOutputStream(new File("./a.txt"));
// public abstract void write(int num) 写入字节
// fos.write(123);
byte[] bytes1 = {67, 62, 63, 64};
fos.write(bytes1); // C>?@
byte[] bytes2 = {32,33,34,35,36};
fos.write(bytes2, 1, 3); // !"#
// 使用String 转化为字节
byte[] bytes = "你好啊,我是天才昆".getBytes();
System.out.println(Arrays.toString(bytes));
fos.write(bytes);
// 释放资源(流使用会占用一定的内存,使用完毕要把内存清空,提供程序的效率)
fos.close();
}
}
|
Java
|
UTF-8
| 339
| 2.9375
| 3
|
[] |
no_license
|
package strategy;
public class RubberDuck extends Duck {
public RubberDuck() {
this.flyingBehaviour = new FlyWithNoWings();
}
@Override
public void display() {
System.out.println("I am yellow and rubbery");
}
public void quack() {
System.out.println("Squeek Squeek");
}
}
|
Java
|
UHC
| 6,974
| 2.828125
| 3
|
[] |
no_license
|
package cproject;
import java.util.*;
import java.util.regex.Pattern;
public class AdminHandler {
Scanner s;
User userList[] = new User[5];
//Admin adminList[] = new Admin[1];
Admin admin = new Admin();
int userCnt;
int AdminCheck;
int adminLoginCnt = 0;
int userLoginCnt = 0;
String adminID = "admin";
String adminPW = "admin";
public AdminHandler() {
s = new Scanner(System.in);
}
int CheckAD() {
//System.out.print("ڶ 1 Էϰ ڶ 0 Էϼ :");
AdminCheck = Integer.parseInt(s.nextLine());
return AdminCheck;
}
int adminLogin() {
while(true)
{
System.out.print(" ID Էּ : ");
String ID = s.nextLine();
System.out.print(" PW Էּ : ");
String PW = s.nextLine();
if(ID.equals(adminID)&&PW.equals(adminPW)) {
System.out.println(" α ");break;
}else
System.out.println("ԷϽ ID PW ġ ʽϴ.");
}
adminLoginCnt = 1;
return adminLoginCnt;
}
void adminLogout() {
System.out.println("αƿ Ǿϴ.");
adminLoginCnt = 0;
}
int userLogin() {
System.out.print(" ID Էּ : ");
String ID = s.nextLine();
System.out.print(" PW Էּ : ");
String PW = s.nextLine();
for(int i = 0; i<userList.length;i++)
{
if(userList[i]!=null) {
if(ID.equals(userList[i].ID)&&PW.equals(userList[i].PW)) {
System.out.println("α ");break;
}//else
//System.out.println("ԷϽ ID PW ġ ʽϴ.");
}else
{
System.out.println("ϵ Դϴ. ȸ մϴ.");
registerUser();break;
}
}
userLoginCnt = 1;
return userLoginCnt;
}
void userLogout() {
System.out.println("αƿ Ǿϴ.");
userLoginCnt = 0;
}
void registerUser() {
if(userCnt == userList.length)
{
System.out.println(" ʱȭմϴ. ٽ Էϼ");
for(int i = 0; i<userList.length;i++)
{
userCnt = 0;
userList[i] = null;
}
}
String sPattern = "^[a-zA-Z0-9-R\\s]*$";
int retry = 0;
boolean regex;
do {
System.out.print("̸ Էϼ : ");
String Name = s.nextLine();
regex = Pattern.matches(sPattern, Name);
if(regex != true) {
System.out.println("ڸ ڿ Էϼ ");
break;
}
System.out.print("ȭȣ Էϼ : ");
String Tel = s.nextLine();
regex = Pattern.matches(sPattern, Tel);
if(regex != true) {
System.out.println("ڸ ڿ Էϼ ");
break;
}
System.out.print("ID Էϼ : ");
String ID = s.nextLine();
regex = Pattern.matches(sPattern, ID);
if(regex != true) {
System.out.println("ڸ ڿ Էϼ ");
break;
}
System.out.print("PW Էϼ : ");
String PW = s.nextLine();
regex = Pattern.matches(sPattern, PW);
if(regex != true) {
System.out.println("ڸ ڿ Էϼ ");
break;
}
AdminCheck = 1;
User user = new User(Name, Tel, ID, PW);
userList[userCnt] = user;
userCnt++;
System.out.println("ȸ ϷǾϴ.");
System.out.println(" ԷϽðھ? yes..1 no..0");
retry = s.nextInt();
s.nextLine();
}while(retry!=0);
}
void showUser() {
for(int i = 0; i<userList.length;i++)
{
if(userList[i]!=null )
{
userList[i].showUser();
}
//else
//System.out.println("Էµ ϴ. ڸ ּ߰.");
}
}
void findID() {
System.out.print(" ̸ Էּ : ");
String Name = s.nextLine();
for(int i = 0; i<userList.length;i++)
{
if(userList[i]!=null) {
if(Name.equals(userList[i].Name)) {
System.out.println(userList[i].Name+" ID "+userList[i].ID+"Դϴ.");
}
}
}
}
void findPW() {
System.out.print(" ID Էּ : ");
String ID = s.nextLine();
for(int i = 0; i<userList.length;i++)
{
if(userList[i]!=null) {
if(ID.equals(userList[i].ID)) {
System.out.println(userList[i].ID+" PW "+userList[i].PW+"Դϴ.");
}
}
}
}
void removeUser(){
System.out.println(" ŻϽðڽϱ? : Ż ̵ Է");
String ID = s.nextLine();
for(int i = 0; i<userList.length;i++)
{
if(userList[i]==null) {
//System.out.println("nullԴϴ.");
}
else if(ID.equals(userList[i].ID)) {
userList[i]= null;
System.out.println(ID+" Ǿϴ.");
userCnt--;
userLoginCnt = 0;
}//else
//System.out.println("ġ ");
}
}
void searchUser(){
System.out.print("˻ ID Էּ");
String ID = s.nextLine();
for(int i = 0; i<userList.length;i++)
{
if(userList[i]!=null) {
if(ID.equals(userList[i].ID)) {
System.out.println("ãô ");
userList[i].showUser();
System.out.print(" Դϴ. ");
}
// else
// System.out.println("Ǥ̤");
}
}
}
void deleteUser() {
System.out.print(" ID Էּ :");
String ID = s.nextLine();
for(int i = 0; i<userList.length;i++)
{
if(userList[i]==null) {
//System.out.println("nullԴϴ.");
}
else if(ID.equals(userList[i].ID)) {
userList[i]= null;
System.out.println(ID+" Ǿϴ.");
userCnt--;
}//else
//System.out.println("ġ ");
}
}
void sortUser() {
System.out.println(" մϴ.");
for(int i = 0; i<userList.length;i++)
{
if(userList[i]==null )
{
userList[i] = new User("a"+i,"010"+i,"user"+(i+1),"user"+(i+1));
System.out.println("ڸ ߰Ͽϴ.");
userCnt++;
}
}
Arrays.sort(userList);
for(int i = 0; i < userList.length;i++)
{
userList[i].showUser();
}
}
}
|
C#
|
UTF-8
| 2,865
| 2.6875
| 3
|
[] |
no_license
|
using NUnit.Framework;
using RMays.Aoc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RMays.Aoc2020.Tests
{
[TestFixture]
public class Day4Tests
{
// Official final times:
// part 1: 12m25.54s
// part 1+2: 76m52.15s (would've been about 20m shorter if I had re-read the year ranges in the specs!)
private string inputData = InputData.Day4;
private string knownOutputA = "256";
private string knownOutputB = "198";
private IDay<long> GetDayObject()
{
return new Day4();
}
[Test]
[TestCase(@"ecl:gry pid:860033327 eyr:2020 hcl:#fffffd
byr:1937 iyr:2017 cid:147 hgt:183cm
iyr:2013 ecl:amb cid:350 eyr:2023 pid:028048884
hcl:#cfa07d byr:1929
hcl:#ae17e1 iyr:2013
eyr:2024
ecl:brn pid:760753108 byr:1931
hgt:179cm
hcl:#cfa07d eyr:2025 pid:166559648
iyr:2011 ecl:brn hgt:59in", 2)]
public void PartATests(string input, long expectedOutput)
{
var day = GetDayObject();
var result = day.Solve(input);
Assert.AreEqual(expectedOutput, result);
}
[Test]
[TestCase(@"eyr:1972 cid:100
hcl:#18171d ecl:amb hgt:170 pid:186cm iyr:2018 byr:1926
iyr:2019
hcl:#602927 eyr:1967 hgt:170cm
ecl:grn pid:012533040 byr:1946
hcl:dab227 iyr:2012
ecl:brn hgt:182cm pid:021572410 eyr:2020 byr:1992 cid:277
hgt:59cm ecl:zzz
eyr:2038 hcl:74454a iyr:2023
pid:3556412378 byr:2007", 0)]
[TestCase(@"pid:087499704 hgt:74in ecl:grn iyr:2012 eyr:2030 byr:1980
hcl:#623a2f
eyr:2029 ecl:blu cid:129 byr:1989
iyr:2014 pid:896056539 hcl:#a97842 hgt:165cm
hcl:#888785
hgt:164cm byr:2001 iyr:2015 cid:88
pid:545766238 ecl:hzl
eyr:2022
iyr:2010 hgt:158cm hcl:#b6652a ecl:blu byr:1944 eyr:2021 pid:093154719", 4)]
public void PartBTests(string input, long expectedOutput)
{
var day = GetDayObject();
var result = day.Solve(input, true);
Assert.AreEqual(expectedOutput, result);
}
[Test]
public void DoItA() // ?
{
var day = GetDayObject();
Console.WriteLine(day.Solve(inputData));
}
[Test]
public void DoItB() // ?
{
var day = GetDayObject();
Console.WriteLine(day.Solve(inputData, true));
}
[Test]
public void DoItA_Answer()
{
var day = GetDayObject();
var result = day.Solve(inputData);
Assert.AreEqual(knownOutputA, result.ToString());
}
[Test]
public void DoItB_Answer()
{
var day = GetDayObject();
var result = day.Solve(inputData, true);
Assert.AreEqual(knownOutputB, result.ToString());
}
}
}
|
Markdown
|
UTF-8
| 1,597
| 2.734375
| 3
|
[
"Apache-2.0"
] |
permissive
|
# IntersightClient::HyperflexServerFirmwareVersionEntryAllOf
## Properties
| Name | Type | Description | Notes |
| ---- | ---- | ----------- | ----- |
| **class_id** | **String** | The fully-qualified name of the instantiated, concrete type. This property is used as a discriminator to identify the type of the payload when marshaling and unmarshaling data. | [default to 'hyperflex.ServerFirmwareVersionEntry'] |
| **object_type** | **String** | The fully-qualified name of the instantiated, concrete type. The value should be the same as the 'ClassId' property. | [default to 'hyperflex.ServerFirmwareVersionEntry'] |
| **constraint** | [**HyperflexAppSettingConstraint**](HyperflexAppSettingConstraint.md) | | [optional] |
| **server_platform** | **String** | The server platform type that is applicable for the server firmware bundle version. * `M5` - M5 generation of UCS server. * `M3` - M3 generation of UCS server. * `M4` - M4 generation of UCS server. * `M6` - M6 generation of UCS server. | [optional][default to 'M5'] |
| **version** | **String** | The server firmware bundle version. | [optional] |
| **server_firmware_version** | [**HyperflexServerFirmwareVersionRelationship**](HyperflexServerFirmwareVersionRelationship.md) | | [optional] |
## Example
```ruby
require 'intersight_client'
instance = IntersightClient::HyperflexServerFirmwareVersionEntryAllOf.new(
class_id: null,
object_type: null,
constraint: null,
server_platform: null,
version: null,
server_firmware_version: null
)
```
|
JavaScript
|
UTF-8
| 172
| 3.296875
| 3
|
[] |
no_license
|
function printStars() {
let toPrint = "";
for (let i = 1; i < 6; i++) {
toPrint = toPrint.concat("*");
console.log(toPrint);
}
}
console.log(printStars());
|
JavaScript
|
UTF-8
| 5,479
| 3.84375
| 4
|
[] |
no_license
|
//**** variables & strings ****
//var firstName = "jack";
//var lastName = "jacob";
//var age = 23;
//
//
//var message = " hi, my name is " + firstName + " and I am " + age + " years old ";
//
//console.log(message);
//******** NUMBERS********
//var sum = 10 + 15;
//var sub = 15 - 10;
//var mul = 10 * 3;
//var div = 10 / 3;
//var mod = 10 % 3;
//
//var msg="10/3 with a remaider of " + mod;
//console.log(msg);
//var result = 10 * ((5+3)-4);
//
//console.log(result);
//********Comparation operators********
//var myAccountBalance = 300;
//var nikeSBShoes = 799.23;
//var coupon = 500;
//== equal to
// === ??
// <= less than or equal to
// >= greater than or equal to
// != not equal to
//var val1 = 23;
//var val2 = "23";
//
//if (val1 === val2){
// console.log("these are the same !");
//
//}
//else {
// console.log("are not the same type! ")
//}
//if (nikeSBShoes <= myAccountBalance) {
//// myAccountBalance = myAccountBalance - nikeSBShoes;
// myAccountBalance -= nikeSBShoes;
//
// console.log("we just bought some shoes!")
//
// console.log("Account Balance:" + myAccountBalance);
//
//} else if (nikeSBShoes-coupon<= myAccountBalance){
// console.log("we just bought some shoes with a coupon!")
// myAccountBalance-=nikeSBShoes -coupon;
// console.log("Account Balance:" +myAccountBalance);
//}
//else
//{ console.log("you too broke fo shoes bra!")
//
//}
//
////********Logical Operators********
//var cat1 = 5;
//var cat2 = 10;
//var cat3 = 1;
//var cat3DisabledHandicap =true;
//
//
//if ((cat1 > cat2 && cat1 > cat3) && !cat3DisabledHandicap ){
// console.log("cat1 is the cutest");
//}else if ((cat2 > cat1 && cat2 > cat3) && !cat3DisabledHandicap ){
// console.log("cat2 is the cutest");
//}else if ((cat3 > cat1 && cat3 > cat2) || cat3DisabledHandicap ){
// console.log("cat3 is the cutest");
//}
////******** Arrays ********
//var students = ["Timmy","Janess","Arun"]; //crear el array
//
//var naughtlyList = []; //crear array chicos malos
//
//naughtlyList.push(students[0]);//put student in here
//
//var index = naughtlyList.indexOf("Timmy");//find index location
//console.log(naughtlyList);
//
//if (index > -1){
// naughtlyList.splice(index,1);// remove from the array
//}
//
//console.log(naughtlyList);
////******** Loops ********
//var total = 10;
//for (var x = 0; x <total; x++){
// console.log(x);
//}
//var students = ["Timmy","Janess","Arun"]; //crear array
//for (var index = 0; index < students.length; index++){
// console.log(students[index]);
//}
////******** funtions ********
//var bankBalance = 500;
//
//function makeTransaction(priceOfSale){
// //cremos una funcion que llamamos maketranssaction donde metemos los priceOfSale
// if (priceOfSale <= bankBalance){
// //si el priceOfSale es menor o igual al bankBalance rpocedercon lo de abajo
// bankBalance -= priceOfSale;
// //al ser verdadero lo de arriba se resta el priceOfSale al bankbalance lo que es igual a bankBalance = bankbalance - priceOfSale;
//
// console.log("Purchase Succesful");
// }else {
// console.log("Insufficent Funds");
// }
//}
//
//console.log(bankBalance);//nos da el bankbalance antes de la operacion
//makeTransaction(79.00);
//
//console.log(bankBalance);
//makeTransaction(2.32);
//
//console.log(bankBalance);
//makeTransaction(10.45);
//
//console.log(bankBalance);
//makeTransaction(450.00);
//
//
//var transaction = function(priceOfSale){
// if (priceOfSale <= bankBalance){
// bankBalance -= priceOfSale;
// console.log("Purchase Succesful");
// } else {
// console.log("Insufficent Funds");
// }
// }
//
//var printCustomerName = function (first,last){
// console.log("First Name:" + first + "Last Name:" + last );
//}
//var applyForCreditCard = function (creditScore,soul){
// //call some funtions to process application
//}
//
//var bankOperations = [];
//bankOperations.push(transaction);
//bankOperations.push(printCustomerName);
//bankOperations.push(applyForCreditCard);
//
///******** objects ********
//var student0 = {
// firstName: "Jayne",
// lastName: "Looo",
// age: 8
//};
//
//console.log(student0.greeting());
//*******
//Creates a new empty object
//var student1 = new Object();
//student1.firstName = "John";
//student1.lastName = "Parker";
//student1.age = 7;
//
//var student2 = {};
//student2.firstName = "Zack";
//student2.lastName = "Bobo";
//student2.age = 5;
//}
//console.log(student.firstName);
//console.log(student.lastName);
//console.log(student["firstName"]);
//console.log(student["lastName"]);
//
//var s1 = new Student("Jenny","Laga",5);
//console.log(s1);
//console.log(s1.greeting());
//
//students.push(student0);
//students.push(student1);
//students.push(student2);
//
//for (var index = 0; index < students.length; index++) {
// var student = students[index];
// console.log(student.greeting());
//}
var students = [];
function Student(first, last, age) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.greeting = function() {
return "Hi, I'm " + this.firstName + " and I'm " + this.age + " years old.";
};
}
students.push(new Student("Jenny","Laga",5));
students.push(new Student("Timmy","Turner",8));
students.push(new Student("Carl","Jr",4));
var student = students[0];
//for in
for (var key in student) {
console.log(student[key]);
}
|
Go
|
UTF-8
| 18,772
| 2.734375
| 3
|
[
"Apache-2.0"
] |
permissive
|
package main
import (
"bytes"
"encoding/binary"
"math/rand"
"net"
"time"
)
// Start time for this instance, used to compute sysUptime
var StartTime = time.Now().UnixNano()
// current sysUptime in msec - recalculated in CreateNFlowHeader()
var sysUptime uint32 = 0
// Counter of flow packets that have been sent
var flowSequence uint32 = 0
const (
FTP_PORT = 21
SSH_PORT = 22
DNS_PORT = 53
HTTP_PORT = 80
HTTPS_PORT = 443
NTP_PORT = 123
SNMP_PORT = 161
IMAPS_PORT = 993
MYSQL_PORT = 3306
HTTPS_ALT_PORT = 8080
P2P_PORT = 6681
BITTORRENT_PORT = 6682
UINT16_MAX = 65535
PAYLOAD_AVG_MD = 1024
PAYLOAD_AVG_SM = 256
)
// struct data from fach
type NetflowHeader struct {
Version uint16
FlowCount uint16
SysUptime uint32
UnixSec uint32
UnixMsec uint32
FlowSequence uint32
EngineType uint8
EngineId uint8
SampleInterval uint16
}
type NetflowPayload struct {
SrcIP uint32
DstIP uint32
NextHopIP uint32
SnmpInIndex uint16
SnmpOutIndex uint16
NumPackets uint32
NumOctets uint32
SysUptimeStart uint32
SysUptimeEnd uint32
SrcPort uint16
DstPort uint16
Padding1 uint8
TcpFlags uint8
IpProtocol uint8
IpTos uint8
SrcAsNumber uint16
DstAsNumber uint16
SrcPrefixMask uint8
DstPrefixMask uint8
Padding2 uint16
}
//Complete netflow records
type Netflow struct {
Header NetflowHeader
Records []NetflowPayload
}
//Marshall NetflowData into a buffer
func BuildNFlowPayload(data Netflow) bytes.Buffer {
buffer := new(bytes.Buffer)
err := binary.Write(buffer, binary.BigEndian, &data.Header)
if err != nil {
log.Println("Writing netflow header failed:", err)
}
for _, record := range data.Records {
err := binary.Write(buffer, binary.BigEndian, &record)
if err != nil {
log.Println("Writing netflow record failed:", err)
}
}
return *buffer
}
//Generate a netflow packet w/ user-defined record count
func GenerateNetflow(recordCount int) Netflow {
data := new(Netflow)
header := CreateNFlowHeader(recordCount)
records := []NetflowPayload{}
if recordCount == 8 {
// overwrite payload to add some variations for traffic spikes.
records = CreateVariablePayload(recordCount)
} else {
records = CreateNFlowPayload(recordCount)
}
data.Header = header
data.Records = records
return *data
}
//Generate and initialize netflow header
func CreateNFlowHeader(recordCount int) NetflowHeader {
t := time.Now().UnixNano()
sec := t / int64(time.Second)
nsec := t - sec*int64(time.Second)
sysUptime = uint32((t-StartTime) / int64(time.Millisecond))+1000
flowSequence++
// log.Infof("Time: %d; Seconds: %d; Nanoseconds: %d\n", t, sec, nsec)
// log.Infof("StartTime: %d; sysUptime: %d", StartTime, sysUptime)
// log.Infof("FlowSequence %d", flowSequence)
h := new(NetflowHeader)
h.Version = 5
h.FlowCount = uint16(recordCount)
h.SysUptime = sysUptime
h.UnixSec = uint32(sec)
h.UnixMsec = uint32(nsec)
h.FlowSequence = flowSequence
h.EngineType = 1
h.EngineId = 0
h.SampleInterval = 0
return *h
}
func CreateVariablePayload(recordCount int) []NetflowPayload {
payload := make([]NetflowPayload, recordCount)
for i := 0; i < recordCount; i++ {
payload[0] = CreateHttpFlow()
payload[1] = CreateHttpsFlow()
payload[2] = CreateHttpAltFlow()
payload[3] = CreateDnsFlow()
payload[5] = CreateNtpFlow()
payload[6] = CreateImapsFlow()
payload[7] = CreateMySqlFlow()
}
return payload
}
func CreateNFlowPayload(recordCount int) []NetflowPayload {
payload := make([]NetflowPayload, recordCount)
for i := 0; i < recordCount; i++ {
payload[0] = CreateHttpFlow()
payload[1] = CreateHttpsFlow()
payload[2] = CreateHttpAltFlow()
payload[3] = CreateDnsFlow()
payload[4] = CreateIcmpFlow()
payload[5] = CreateNtpFlow()
payload[6] = CreateImapsFlow()
payload[7] = CreateMySqlFlow()
payload[8] = CreateRandomFlow()
payload[9] = CreateSshFlow()
payload[10] = CreateP2pFlow()
payload[11] = CreateBitorrentFlow()
payload[12] = CreateFTPFlow()
payload[13] = CreateSnmpFlow()
payload[14] = CreateIcmpFlow()
payload[15] = CreateRandomFlow()
}
return payload
}
//Initialize netflow record with random data
func CreateIcmpFlow() NetflowPayload {
payload := new(NetflowPayload)
payload.SrcIP = IPtoUint32("172.16.50.10")
payload.DstIP = IPtoUint32("132.12.130.10")
payload.NextHopIP = IPtoUint32("132.12.130.1")
payload.SrcPort = 0
payload.DstPort = 0
// payload.SnmpInIndex = genRandUint16(UINT16_MAX)
// payload.SnmpOutIndex = genRandUint16(UINT16_MAX)
// payload.NumPackets = genRandUint32(PAYLOAD_AVG_SM)
// payload.NumOctets = genRandUint32(PAYLOAD_AVG_SM)
// payload.SysUptimeStart = rand.Uint32()
// payload.SysUptimeEnd = rand.Uint32()
// payload.Padding1 = 0
// payload.IpProtocol = 1
// payload.IpTos = 0
// payload.SrcPrefixMask = uint8(rand.Intn(32))
// payload.DstPrefixMask = uint8(rand.Intn(32))
// payload.Padding2 = 0
FillCommonFields(payload, PAYLOAD_AVG_SM, 1, rand.Intn(32))
return *payload
}
//Initialize netflow record with random data
func CreateHttpFlow() NetflowPayload {
payload := new(NetflowPayload)
payload.SrcIP = IPtoUint32("112.10.20.10")
payload.DstIP = IPtoUint32("172.30.190.10")
payload.NextHopIP = IPtoUint32("172.199.15.1")
payload.SrcPort = uint16(40)
payload.DstPort = uint16(HTTP_PORT)
// payload.SnmpInIndex = genRandUint16(UINT16_MAX)
// payload.SnmpOutIndex = genRandUint16(UINT16_MAX)
// payload.NumPackets = genRandUint32(PAYLOAD_AVG_MD)
// payload.NumOctets = genRandUint32(PAYLOAD_AVG_MD)
// payload.SysUptimeStart = rand.Uint32()
// payload.SysUptimeEnd = rand.Uint32()
// payload.Padding1 = 0
// payload.IpProtocol = 6
// payload.IpTos = 0
// payload.SrcPrefixMask = uint8(rand.Intn(32))
// payload.DstPrefixMask = uint8(rand.Intn(32))
// payload.Padding2 = 0
FillCommonFields(payload, PAYLOAD_AVG_MD, 6, rand.Intn(32))
return *payload
}
//Initialize netflow record with random data
func CreateSnmpFlow() NetflowPayload {
payload := new(NetflowPayload)
payload.SrcIP = IPtoUint32("112.10.20.10")
payload.DstIP = IPtoUint32("172.30.190.10")
payload.NextHopIP = IPtoUint32("172.199.15.1")
payload.SrcPort = uint16(40)
payload.DstPort = uint16(SNMP_PORT)
// payload.SnmpInIndex = genRandUint16(UINT16_MAX)
// payload.SnmpOutIndex = genRandUint16(UINT16_MAX)
// payload.NumPackets = genRandUint32(PAYLOAD_AVG_MD)
// payload.NumOctets = genRandUint32(PAYLOAD_AVG_MD)
// payload.SysUptimeStart = rand.Uint32()
// payload.SysUptimeEnd = rand.Uint32()
// payload.Padding1 = 0
// payload.IpProtocol = 17
// payload.IpTos = 0
// payload.SrcPrefixMask = uint8(rand.Intn(32))
// payload.DstPrefixMask = uint8(rand.Intn(32))
// payload.Padding2 = 0
FillCommonFields(payload, PAYLOAD_AVG_MD, 17, rand.Intn(32))
return *payload
}
func CreateFTPFlow() NetflowPayload {
payload := new(NetflowPayload)
payload.SrcIP = IPtoUint32("112.10.100.10")
payload.DstIP = IPtoUint32("192.168.120.10")
payload.NextHopIP = IPtoUint32("172.199.15.1")
payload.SrcPort = uint16(40)
payload.DstPort = uint16(FTP_PORT)
// payload.SnmpInIndex = genRandUint16(UINT16_MAX)
// payload.SnmpOutIndex = genRandUint16(UINT16_MAX)
// payload.NumPackets = genRandUint32(PAYLOAD_AVG_MD)
// payload.NumOctets = genRandUint32(PAYLOAD_AVG_MD)
// payload.SysUptimeStart = rand.Uint32()
// payload.SysUptimeEnd = rand.Uint32()
// payload.Padding1 = 0
// payload.IpProtocol = 6
// payload.IpTos = 0
// payload.SrcPrefixMask = uint8(rand.Intn(32))
// payload.DstPrefixMask = uint8(rand.Intn(32))
// payload.Padding2 = 0
FillCommonFields(payload, PAYLOAD_AVG_MD, 6, rand.Intn(32))
return *payload
}
func CreateNtpFlow() NetflowPayload {
payload := new(NetflowPayload)
payload.SrcIP = IPtoUint32("247.104.20.202")
payload.DstIP = IPtoUint32("10.12.190.10")
payload.NextHopIP = IPtoUint32("192.199.15.1")
payload.SrcPort = uint16(40)
payload.DstPort = uint16(NTP_PORT)
// payload.SnmpInIndex = genRandUint16(UINT16_MAX)
// payload.SnmpOutIndex = genRandUint16(UINT16_MAX)
// payload.NumPackets = genRandUint32(PAYLOAD_AVG_MD)
// payload.NumOctets = genRandUint32(PAYLOAD_AVG_MD)
// payload.SysUptimeStart = rand.Uint32()
// payload.SysUptimeEnd = rand.Uint32()
// payload.Padding1 = 0
// payload.IpProtocol = 17
// payload.IpTos = 0
// payload.SrcAsNumber = genRandUint16(UINT16_MAX)
// payload.SrcPrefixMask = uint8(32)
// payload.DstPrefixMask = uint8(rand.Intn(32))
// payload.Padding2 = 0
FillCommonFields(payload, PAYLOAD_AVG_MD, 17, 32)
return *payload
}
func CreateP2pFlow() NetflowPayload {
payload := new(NetflowPayload)
payload.SrcIP = IPtoUint32("247.104.20.202")
payload.DstIP = IPtoUint32("10.12.190.10")
payload.NextHopIP = IPtoUint32("192.199.15.1")
payload.SrcPort = uint16(40)
payload.DstPort = uint16(P2P_PORT)
// payload.SnmpInIndex = genRandUint16(UINT16_MAX)
// payload.SnmpOutIndex = genRandUint16(UINT16_MAX)
// payload.NumPackets = genRandUint32(PAYLOAD_AVG_MD)
// payload.NumOctets = genRandUint32(PAYLOAD_AVG_MD)
// payload.SysUptimeStart = rand.Uint32()
// payload.SysUptimeEnd = rand.Uint32()
// payload.Padding1 = 0
// payload.IpProtocol = 17
// payload.IpTos = 0
// payload.SrcAsNumber = genRandUint16(UINT16_MAX)
// payload.SrcPrefixMask = uint8(32)
// payload.DstPrefixMask = uint8(rand.Intn(32))
// payload.Padding2 = 0
FillCommonFields(payload, PAYLOAD_AVG_MD, 17, 32)
return *payload
}
func CreateBitorrentFlow() NetflowPayload {
payload := new(NetflowPayload)
payload.SrcIP = IPtoUint32("192.168.20.202")
payload.DstIP = IPtoUint32("42.12.190.10")
payload.NextHopIP = IPtoUint32("192.199.15.1")
payload.SrcPort = uint16(40)
payload.DstPort = uint16(BITTORRENT_PORT)
// payload.SnmpInIndex = genRandUint16(UINT16_MAX)
// payload.SnmpOutIndex = genRandUint16(UINT16_MAX)
// payload.NumPackets = genRandUint32(PAYLOAD_AVG_MD)
// payload.NumOctets = genRandUint32(PAYLOAD_AVG_MD)
// payload.SysUptimeStart = rand.Uint32()
// payload.SysUptimeEnd = rand.Uint32()
// payload.Padding1 = 0
// payload.IpProtocol = 17
// payload.IpTos = 0
// payload.SrcAsNumber = genRandUint16(UINT16_MAX)
// payload.SrcPrefixMask = uint8(32)
// payload.DstPrefixMask = uint8(rand.Intn(32))
// payload.Padding2 = 0
FillCommonFields(payload, PAYLOAD_AVG_MD, 17, 32)
return *payload
}
func CreateSshFlow() NetflowPayload {
payload := new(NetflowPayload)
payload.SrcIP = IPtoUint32("172.30.20.102")
payload.DstIP = IPtoUint32("222.12.190.10")
payload.NextHopIP = IPtoUint32("192.199.15.1")
payload.SrcPort = uint16(40)
payload.DstPort = uint16(SSH_PORT)
// payload.SnmpInIndex = genRandUint16(UINT16_MAX)
// payload.SnmpOutIndex = genRandUint16(UINT16_MAX)
// payload.NumPackets = genRandUint32(PAYLOAD_AVG_MD)
// payload.NumOctets = genRandUint32(PAYLOAD_AVG_MD)
// payload.SysUptimeStart = rand.Uint32()
// payload.SysUptimeEnd = rand.Uint32()
// payload.Padding1 = 0
// payload.IpProtocol = 6
// payload.IpTos = 0
// payload.SrcAsNumber = genRandUint16(UINT16_MAX)
// payload.SrcPrefixMask = uint8(rand.Intn(32))
// payload.DstPrefixMask = uint8(rand.Intn(32))
// payload.Padding2 = 0
FillCommonFields(payload, PAYLOAD_AVG_MD, 6, rand.Intn(32))
return *payload
}
func CreateHttpsFlow() NetflowPayload {
payload := new(NetflowPayload)
payload.SrcIP = IPtoUint32("192.168.20.10")
payload.DstIP = IPtoUint32("202.12.190.10")
payload.NextHopIP = IPtoUint32("172.199.15.1")
payload.SrcPort = uint16(40)
payload.DstPort = uint16(HTTPS_PORT)
// payload.SnmpInIndex = genRandUint16(UINT16_MAX)
// payload.SnmpOutIndex = genRandUint16(UINT16_MAX)
// payload.NumPackets = genRandUint32(PAYLOAD_AVG_MD)
// payload.NumOctets = genRandUint32(PAYLOAD_AVG_MD)
// payload.SysUptimeStart = rand.Uint32()
// payload.SysUptimeEnd = rand.Uint32()
// payload.Padding1 = 0
// payload.IpProtocol = 6
// payload.IpTos = 0
// payload.SrcAsNumber = genRandUint16(UINT16_MAX)
// payload.SrcPrefixMask = uint8(rand.Intn(32))
// payload.DstPrefixMask = uint8(rand.Intn(32))
// payload.Padding2 = 0
FillCommonFields(payload, PAYLOAD_AVG_MD, 6, rand.Intn(32))
return *payload
}
func CreateHttpAltFlow() NetflowPayload {
payload := new(NetflowPayload)
payload.SrcIP = IPtoUint32("10.10.20.122")
payload.DstIP = IPtoUint32("84.12.190.210")
payload.NextHopIP = IPtoUint32("192.199.15.1")
payload.SrcPort = uint16(12001)
payload.DstPort = uint16(HTTPS_ALT_PORT)
// payload.SnmpInIndex = genRandUint16(UINT16_MAX)
// payload.SnmpOutIndex = genRandUint16(UINT16_MAX)
// payload.NumPackets = genRandUint32(PAYLOAD_AVG_MD)
// payload.NumOctets = genRandUint32(PAYLOAD_AVG_MD)
// payload.SysUptimeStart = rand.Uint32()
// payload.SysUptimeEnd = rand.Uint32()
// payload.Padding1 = 0
// payload.IpProtocol = 6
// payload.IpTos = 0
// payload.SrcAsNumber = genRandUint16(UINT16_MAX)
// payload.SrcPrefixMask = uint8(rand.Intn(32))
// payload.DstPrefixMask = uint8(rand.Intn(32))
// payload.Padding2 = 0
FillCommonFields(payload, PAYLOAD_AVG_MD, 6, rand.Intn(32))
return *payload
}
func CreateDnsFlow() NetflowPayload {
payload := new(NetflowPayload)
payload.SrcIP = IPtoUint32("59.220.158.122")
payload.DstIP = IPtoUint32("10.12.233.210")
payload.NextHopIP = IPtoUint32("39.199.15.1")
payload.SrcPort = uint16(9221)
payload.DstPort = uint16(DNS_PORT)
// payload.SnmpInIndex = genRandUint16(UINT16_MAX)
// payload.SnmpOutIndex = genRandUint16(UINT16_MAX)
// payload.NumPackets = genRandUint32(PAYLOAD_AVG_MD)
// payload.NumOctets = genRandUint32(PAYLOAD_AVG_MD)
// payload.SysUptimeStart = rand.Uint32()
// payload.SysUptimeEnd = rand.Uint32()
// payload.Padding1 = 0
// payload.IpProtocol = 17
// payload.IpTos = 0
// payload.SrcAsNumber = genRandUint16(UINT16_MAX)
// payload.SrcPrefixMask = uint8(rand.Intn(32))
// payload.DstPrefixMask = uint8(rand.Intn(32))
// payload.Padding2 = 0
FillCommonFields(payload, PAYLOAD_AVG_MD, 17, rand.Intn(32))
return *payload
}
func CreateImapsFlow() NetflowPayload {
payload := new(NetflowPayload)
payload.SrcIP = IPtoUint32("172.30.20.102")
payload.DstIP = IPtoUint32("62.12.190.10")
payload.NextHopIP = IPtoUint32("131.199.15.1")
payload.SrcPort = uint16(9010)
payload.DstPort = uint16(IMAPS_PORT)
// payload.SnmpInIndex = genRandUint16(UINT16_MAX)
// payload.SnmpOutIndex = genRandUint16(UINT16_MAX)
// payload.NumPackets = genRandUint32(PAYLOAD_AVG_MD)
// payload.NumOctets = genRandUint32(PAYLOAD_AVG_MD)
// payload.SysUptimeStart = rand.Uint32()
// payload.SysUptimeEnd = rand.Uint32()
// payload.Padding1 = 0
// payload.IpProtocol = 6
// payload.IpTos = 0
// payload.SrcAsNumber = genRandUint16(UINT16_MAX)
// payload.SrcPrefixMask = uint8(rand.Intn(32))
// payload.DstPrefixMask = uint8(rand.Intn(32))
// payload.Padding2 = 0
FillCommonFields(payload, PAYLOAD_AVG_MD, 6, rand.Intn(32))
return *payload
}
func CreateMySqlFlow() NetflowPayload {
payload := new(NetflowPayload)
payload.SrcIP = IPtoUint32("10.154.20.12")
payload.DstIP = IPtoUint32("77.12.190.94")
payload.NextHopIP = IPtoUint32("150.20.145.1")
payload.SrcPort = uint16(9010)
payload.DstPort = uint16(MYSQL_PORT)
// payload.SnmpInIndex = genRandUint16(UINT16_MAX)
// payload.SnmpOutIndex = genRandUint16(UINT16_MAX)
// payload.NumPackets = genRandUint32(PAYLOAD_AVG_MD)
// payload.NumOctets = genRandUint32(PAYLOAD_AVG_MD)
// payload.SysUptimeStart = rand.Uint32()
// payload.SysUptimeEnd = rand.Uint32()
// payload.Padding1 = 0
// payload.IpProtocol = 6
// payload.IpTos = 0
// payload.SrcAsNumber = genRandUint16(UINT16_MAX)
// payload.SrcPrefixMask = uint8(rand.Intn(32))
// payload.DstPrefixMask = uint8(rand.Intn(32))
// payload.Padding2 = 0
FillCommonFields(payload, PAYLOAD_AVG_MD, 6, rand.Intn(32))
return *payload
}
func CreateRandomFlow() NetflowPayload {
payload := new(NetflowPayload)
payload.SrcIP = rand.Uint32()
payload.DstIP = rand.Uint32()
payload.NextHopIP = rand.Uint32()
payload.SrcPort = genRandUint16(UINT16_MAX)
payload.DstPort = genRandUint16(UINT16_MAX)
// payload.SnmpInIndex = genRandUint16(UINT16_MAX)
// payload.SnmpOutIndex = genRandUint16(UINT16_MAX)
// payload.NumPackets = genRandUint32(PAYLOAD_AVG_MD)
// payload.NumOctets = genRandUint32(PAYLOAD_AVG_MD)
// payload.SysUptimeStart = rand.Uint32()
// payload.SysUptimeEnd = rand.Uint32()
// payload.Padding1 = 0
// payload.IpProtocol = 6
// payload.IpTos = 0
// payload.SrcAsNumber = genRandUint16(UINT16_MAX)
// payload.SrcPrefixMask = uint8(rand.Intn(32))
// payload.DstPrefixMask = uint8(rand.Intn(32))
// payload.Padding2 = 0
FillCommonFields(payload, PAYLOAD_AVG_MD, 6, rand.Intn(32))
return *payload
}
// patch up the common fields of the packets
func FillCommonFields (
payload *NetflowPayload,
numPktOct int,
ipProtocol int,
srcPrefixMask int) NetflowPayload {
// Fill template with values not filled by caller
// payload.SrcIP = IPtoUint32("10.154.20.12")
// payload.DstIP = IPtoUint32("77.12.190.94")
// payload.NextHopIP = IPtoUint32("150.20.145.1")
// payload.SrcPort = uint16(9010)
// payload.DstPort = uint16(MYSQL_PORT)
// payload.SnmpInIndex = genRandUint16(UINT16_MAX)
// payload.SnmpOutIndex = genRandUint16(UINT16_MAX)
payload.NumPackets = genRandUint32(numPktOct)
payload.NumOctets = genRandUint32(numPktOct)
// payload.SysUptimeStart = rand.Uint32()
// payload.SysUptimeEnd = rand.Uint32()
payload.Padding1 = 0
payload.IpProtocol = uint8(ipProtocol)
payload.IpTos = 0
payload.SrcAsNumber = genRandUint16(UINT16_MAX)
payload.DstAsNumber = genRandUint16(UINT16_MAX)
payload.SrcPrefixMask = uint8(srcPrefixMask)
payload.DstPrefixMask = uint8(rand.Intn(32))
payload.Padding2 = 0
// now handle computed values
if !opts.FalseIndex { // default interfaces are zero
payload.SnmpInIndex = 0
payload.SnmpOutIndex = 0
} else if payload.SrcIP > payload.DstIP { // false-index
payload.SnmpInIndex = 1
payload.SnmpOutIndex = 2
} else {
payload.SnmpInIndex = 2
payload.SnmpOutIndex = 1
}
uptime := int(sysUptime)
payload.SysUptimeEnd = uint32(uptime - randomNum(10,500))
payload.SysUptimeStart = payload.SysUptimeEnd - uint32(randomNum(10,500))
// log.Infof("S&D : %x %x %d, %d", payload.SrcIP, payload.DstIP, payload.DstPort, payload.SnmpInIndex)
// log.Infof("Time: %d %d %d", sysUptime, payload.SysUptimeStart, payload.SysUptimeEnd)
return *payload
}
func genRandUint16(max int) uint16 {
return uint16(rand.Intn(max))
}
func IPtoUint32(s string) uint32 {
ip := net.ParseIP(s)
return binary.BigEndian.Uint32(ip.To4())
}
func genRandUint32(max int) uint32 {
return uint32(rand.Intn(max))
}
|
C++
|
UTF-8
| 1,282
| 3.296875
| 3
|
[] |
no_license
|
#pragma once
#include <string>
#include <iostream>
using namespace std;
class Item
{
public:
// Constructors and destructors
Item();
Item(string id, string title, string rentType, string loanType, int stock, double rentFee); // Constructor for new games
Item(string id, string title, string rentType, string loanType, int stock, double rentFee, string genre); // Constructor for new others
Item(const Item& item);
~Item();
// Overloads
friend ostream& operator<<(ostream& os, Item& item);
// Getters
string getId();
string getTitle();
string getRentType();
string getLoanType();
int getStock();
double getRentFee();
string getRentStatus();
string getGenre();
// Setters
void setId(string id);
void setTitle(string title);
void setRentType(string rentType);
void setLoanType(string loanType);
void setStock(int stock);
void setRentFee(double rentFee);
void setRentStatus(string rentStatus);
void setGenre(string genre);
void setAll(string id, string title, string rentType, string loanType, int stock, double rentFee, string genre);
// Methods
bool renting(); // Never used
bool returning(); // Never used
private:
string id;
string title;
string rentType;
string loanType;
int stock;
double rentFee;
string rentStatus;
string genre;
};
|
PHP
|
UTF-8
| 3,439
| 2.671875
| 3
|
[] |
no_license
|
<?php
require_once('dbinit.php');
require_once('customer.php');
require_once('order.php');
require_once('orderDetail.php');
function comboBoxHtml($label, $map, $selectedRowId) {
$html = "<select id='$label' name='$label'>";
foreach ($map as $id => $name) {
$selected = $id === intval($selectedRowId) ? 'selected' : '';
$html .= "<option value='$id' $selected>$name</option>\n";
}
$html .= "</select>\n</p>";
return $html;
}
// Get a map for all customers.
$customerMap = Customer::listAll();
// The currently selected customer is just the first customer in the first list
$customerIds = array_keys($customerMap);
$customerId = $customerIds[0];
$customer = Customer::read($customerId);
// Get a map for all orders which related to the selected customer.
$orderMap = Order::listAll($customerId);
// The currently selected order is just the first order in the first list
$orderIds = array_keys($orderMap);
$orderId = $orderIds[0];
$order = Order::read($orderId);
$orderDetailMap = OrderDetail::listAll($orderId);
$orderDetailIds = array_keys($orderDetailMap);
$orderDetailId = $orderDetailIds[0];
$orderDetail = OrderDetail::read($orderDetailId);
// =========== THE MAIN FORM =================
?>
<link rel="stylesheet" type="text/css" href="orders.css">
<div id="container">
<div id="content">
<h1>Order Details</h1>
<p><?php echo 'Customer Name:'.comboBoxHtml('CustomerName', $customerMap, $customerId); ?></p>
<p><?php echo 'Order Number:'.comboBoxHtml('OrderNumber', $orderMap, $orderId); ?></p>
<p><?php echo 'Ordered Product:'.comboBoxHtml('OrderedProduct', $orderDetailMap, $orderDetailId); ?></p>
<table id='CustomerDetails'>
<!-- Customers -->
<tr>
<td>Customer Name</td>
<td><?php echo $customer->customerName; ?></td>
</tr>
<!-- Orders -->
<tr>
<td>Order Number</td>
<td><?php echo $order->orderNumber; ?></td>
</tr>
<tr>
<td>Order Date</td>
<td><?php echo $order->orderDate; ?></td>
</tr>
<tr>
<td>Shipped Date</td>
<td><?php echo $order->shippedDate; ?></td>
</tr>
<tr>
<td>Status</td>
<td><?php echo $order->status; ?></td>
</tr>
<tr>
<td>Product Id</td>
<td><?php echo $orderDetail->productId; ?></td>
</tr>
<tr>
<td>Quantity Ordered</td>
<td><?php echo $orderDetail->quantityOrdered; ?></td>
</tr>
<tr>
<td>Price Each</td>
<td><?php echo $orderDetail->priceEach; ?></td>
</tr>
</table>
<script type='text/javascript' src="orders.js" ></script>
</div>
|
Python
|
UTF-8
| 2,929
| 2.75
| 3
|
[] |
no_license
|
import PlanNode as pn
import Parser as ps
def RelationTest():
test_schema = ["a", "b", "c"]
test_tuple_1 = [1, 2, 3]
test_tuple_2 = [4, 5, 6]
test_tuple_3 = [7, 8, 9]
test_tuples_1 = [test_tuple_1, test_tuple_2, test_tuple_3]
test_relation_1 = pn.Relation(test_schema, test_tuples_1, "test1")
test_parser = ps.Parser({"test1": test_relation_1})
test_parser.parse("test1").printOut()
def SelectTest():
test_query = "SELECT [a < c] (test1)"
print test_query
print "input table:"
test_schema_1 = ["a", "b", "c"]
test_tuple_1 = [1, 2, 1]
test_tuple_2 = [1, 2, 3]
test_tuple_3 = [2, 2, 3]
test_relation_1 = pn.Relation(test_schema_1, [test_tuple_1, test_tuple_2, test_tuple_3], "test1")
test_relation_1.printOut()
test_parser = ps.Parser({"test1": test_relation_1})
print "output table:"
test_parser.parse(test_query).execute().printOut()
def ProjectTest():
test_query = "PROJECT [a + 2 AS a, b] (test1)"
print test_query
print "input table:"
test_schema_1 = ["a", "b", "c"]
test_tuple_1 = [1, 2, 1]
test_tuple_2 = [1, 2, 3]
test_tuple_3 = [2, 2, 3]
test_relation_1 = pn.Relation(test_schema_1, [test_tuple_1, test_tuple_2, test_tuple_3], "test1")
test_relation_1.printOut()
test_parser = ps.Parser({"test1": test_relation_1})
print "output table:"
test_parser.parse(test_query).execute().printOut()
def JoinTest():
test_query = "(PROJECT [a + 2 AS a,b] (test1)) CROSSJOIN test2"
test_schema_1 = ["a", "b", "c"]
test_tuple_1 = [1, 2, 1]
test_tuple_2 = [1, 2, 3]
test_tuple_3 = [2, 2, 3]
test_relation_1 = pn.Relation(test_schema_1, [test_tuple_1, test_tuple_2, test_tuple_3], "test1")
test_relation_2 = pn.Relation(test_schema_1, [test_tuple_1, test_tuple_2, test_tuple_3], "test2")
test_parser = ps.Parser({"test1": test_relation_1, "test2": test_relation_2})
test_parser.parse(test_query).execute().printOut()
def SimpleAggregationTest():
test_query = "AGGREGATE [sum(b) AS total_b] (test1)"
test_schema_1 = ["a", "b", "c"]
test_tuple_1 = [1, 2, 1]
test_tuple_2 = [1, 2, 3]
test_tuple_3 = [2, 2, 3]
test_relation_1 = pn.Relation(test_schema_1, [test_tuple_1, test_tuple_2, test_tuple_3], "test1")
test_parser = ps.Parser({"test1": test_relation_1})
test_parser.parse(test_query).execute().printOut()
def GroupingTest():
test_query = "GROUPBY [c] AGGREGATE [sum(a) AS total_a] (test1)"
test_schema_1 = ["a", "b", "c"]
test_tuple_1 = [1, 2, 1]
test_tuple_2 = [1, 2, 3]
test_tuple_3 = [2, 2, 3]
test_relation_1 = pn.Relation(test_schema_1, [test_tuple_1, test_tuple_2, test_tuple_3], "test1")
test_parser = ps.Parser({"test1": test_relation_1})
test_parser.parse(test_query).execute().printOut()
RelationTest()
SelectTest()
ProjectTest()
JoinTest()
SimpleAggregationTest()
GroupingTest()
|
Markdown
|
UTF-8
| 768
| 3
| 3
|
[
"MIT"
] |
permissive
|
# archive
Utils for archiving files.
## archive.extract
```python
extract(path, to_path='', ext='')
```
Unpack the tar or zip file at the specified path or file to the directory
specified by ``to_path``. It supports many extensions, like ``.tar``,
``.tar.bz2``, ``.tar.gz``, ``.tgz``, ``.tz2``, ``.zip``. If the file name of
given ``path`` doesn't contain file extension, the ``ext`` parameter can be
specified one of supported extensions to indicate file type.
```python
>>> from pydu.archive import extract
>>> extract('foobar.tgz', '/tmp')
>>> extract('foobar', '/tmp', ext='.tgz')
>>> extract('foobar', '/tmp')
Traceback (most recent call last):
... AttributeError: pydu.archive.UnrecognizedArchiveFormat: Path not a recognized archive format: foobar
```
|
Java
|
UTF-8
| 3,988
| 3.0625
| 3
|
[] |
no_license
|
package com.smithforge.realty;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotSame;
import static org.junit.Assert.assertTrue;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import org.junit.Test;
import com.smithforge.realty.BookingDate.BookingDateUnit;
public class BookingDateTest {
@Test
public void testGetTimeReturnsTimePassedInCtr() {
BookingDate bookingDate = new BookingDate(2010, 1);
Calendar c = createDefaultCalendar(2010, 1);
assertEquals(c.getTime(), bookingDate.getTime());
}
@Test
public void testGetTimeInMillisReturnsTimePassedInCtr() {
BookingDate bookingDate = new BookingDate(2010, 1);
Calendar c = createDefaultCalendar(2010, 1);
assertEquals(c.getTimeInMillis(), bookingDate.getTimeInMillis());
}
private Calendar createDefaultCalendar(int year, int dayOfYear) {
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, year);
c.set(Calendar.DAY_OF_YEAR, dayOfYear);
c.set(Calendar.HOUR, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
c.set(Calendar.AM_PM, Calendar.AM);
return c;
}
@Test
public void testEqualsReturnsTrueWhenEqual() {
BookingDate first = new BookingDate(2010, 1);
BookingDate second = new BookingDate(2010, 1);
assertEquals(first, second);
}
@Test
public void testEqualsReturnsFalseWhenNotEqual() {
BookingDate first = new BookingDate(2010, 1);
BookingDate second = new BookingDate(2010, 2);
assertFalse(first.equals(second));
}
@Test
public void testAfterReturnsTrueWhenAfter() {
BookingDate first = new BookingDate(2010, 1);
BookingDate second = new BookingDate(2010, 2);
assertTrue(second.after(first));
}
@Test
public void testAfterReturnsFalseWhenNotAfter() {
BookingDate first = new BookingDate(2010, 1);
BookingDate second = new BookingDate(2010, 2);
assertFalse(first.after(second));
}
@Test
public void testAfterReturnsFalseWhenEquals() {
BookingDate first = new BookingDate(2010, 1);
assertFalse(first.after(first));
}
@Test
public void testAddAddsOneYearWhenGivenOneYear() {
BookingDate date = new BookingDate(2010, 1);
date.add(BookingDate.BookingDateUnit.YEAR, 1);
Calendar c = createDefaultCalendar(2011, 1);
assertEquals(c.getTime(), date.getTime());
}
@Test
public void testAddAddsOneDayWhenGivenOneDay() {
BookingDate date = new BookingDate(2010, 1);
date.add(BookingDate.BookingDateUnit.DAY_OF_YEAR, 1);
Calendar c = createDefaultCalendar(2010, 2);
assertEquals(c.getTime(), date.getTime());
}
@Test
public void testAddRollsOverToNextYearWhen365DaysAdded() {
BookingDate date = new BookingDate(2010, 1);
date.add(BookingDate.BookingDateUnit.DAY_OF_YEAR, 365);
Calendar c = createDefaultCalendar(2011, 1);
assertEquals(c.getTime(), date.getTime());
}
@Test
public void testCopyReturnsIdenticalBookingDate() {
BookingDate date = new BookingDate(2010, 1);
BookingDate copy = date.copy();
assertEquals(date, copy);
}
@Test
public void testCopyReturnsCopyThatIsNotSame() {
BookingDate date = new BookingDate(2010, 1);
BookingDate copy = date.copy();
assertNotSame(date, copy);
}
@Test
public void testGetReturnsCorrectAmount() {
BookingDate b = new BookingDate(2010, 1);
assertEquals(2010, b.get(BookingDateUnit.YEAR));
assertEquals(1, b.get(BookingDateUnit.DAY_OF_YEAR));
}
@Test
public void testToStringReturnsDateFormattedDDDMMYYY() {
BookingDate b = new BookingDate(2010, 1);
Date date = createDefaultCalendar(2010, 1).getTime();
DateFormat format = new SimpleDateFormat("EEEE, MMMM DD yyyy");
String expected = format.format(date);
assertEquals(expected, b.toString());
b = new BookingDate(2010, 276);
date = createDefaultCalendar(2010, 276).getTime();
expected = format.format(date);
assertEquals(expected, b.toString());
}
}
|
JavaScript
|
UTF-8
| 2,841
| 4.15625
| 4
|
[] |
no_license
|
let userScore = 0;
let computerScore = 0;
// DOM elements:
const userScoreEl = document.getElementById("user-score");
const computerScoreEl = document.getElementById("computer-score");
const scoreBoardEl = document.querySelector(".score-board");
//getting the results p tag so that the styling does not go away
const resultEl = document.querySelector(".result p");
const rockEl = document.getElementById("rock");
const paperEl = document.getElementById("paper");
const scissorsEl = document.getElementById("scissors");
const getComputerChoice = function () {
const choices = ["rock", "paper", "scissors"];
const index = Math.floor(Math.random() * 3);
const choice = choices[index];
console.log(`Computer has selected ${choice}`);
return choice;
};
const userWin = function (userChoice, computerChoice) {
console.log("User Wins!");
userScore++;
userScoreEl.textContent = userScore;
resultEl.textContent = `User chose ${userChoice}. Computer chose ${computerChoice}. User Wins!`;
document.getElementById(userChoice).classList.add("user-win");
setTimeout(function () {
document.getElementById(userChoice).classList.remove("user-win");
}, 1000);
};
const userLoss = function (userChoice, computerChoice) {
console.log("Computer Wins!");
computerScore++;
computerScoreEl.textContent = computerScore;
resultEl.textContent = `User chose ${userChoice}. Computer chose ${computerChoice}. Computer Wins!`;
document.getElementById(userChoice).classList.add("user-loss");
setTimeout(function () {
document.getElementById(userChoice).classList.remove("user-loss");
}, 1000);
};
const draw = function (userChoice) {
console.log("It was a draw!");
resultEl.textContent = `User and Computer both chose ${userChoice}. It's a draw!`;
document.getElementById(userChoice).classList.add("draw");
setTimeout(function () {
document.getElementById(userChoice).classList.remove("draw");
}, 1000);
};
const game = function (choice) {
console.log(`User has selected ${choice}`);
const computerChoice = getComputerChoice();
switch (choice + computerChoice) {
//when user wins:
case "rockscissors":
case "paperrock":
case "scissorspaper":
userWin(choice, computerChoice);
break;
//when computer wins
case "rockpaper":
case "paperscissors":
case "scissorsrock":
userLoss(choice, computerChoice);
break;
//when there is a draw
case "rockrock":
case "paperpaper":
case "scissorsscissors":
draw(choice);
break;
}
};
rockEl.addEventListener("click", function () {
game("rock");
});
paperEl.addEventListener("click", function () {
game("paper");
});
scissorsEl.addEventListener("click", function () {
game("scissors");
});
|
Shell
|
UTF-8
| 3,195
| 3.34375
| 3
|
[] |
no_license
|
#!/bin/bash
SQLITE_DBPATH=${SQLITE_DBPATH:-/data/pdns.sqlite}
API_KEY=${API_KEY:-genericapikey}
MASTER=${MASTER:-no}
SLAVE=${SLAVE:-yes}
SLAVE_RENOTIFY=${SLAVE_RENOTIFY:-no}
SLAVE_CYCLE_INTERVAL=${SLAVE_CYCLE_INTERVAL:-10}
DEFAULT_TTL=${DEFAULT_TTL:-3600}
DEFAULT_SOA_NAME=${DEFAULT_SOA_NAME:-$(hostname -f)}
DEFAULT_SOA_MAIL=${DEFAULT_SOA_MAIL}
ALLOW_AXFR_IPS=${ALLOW_AXFR_IPS:-127.0.0.0/8}
ALSO_NOTIFY=${ALSO_NOTIFY}
ALLOW_NOTIFY_FROM=${ALLOW_NOTIFY_FROM}
GSQLITE3_PRAGMA_SYNCHRONOUS=${GSQLITE3_PRAGMA_SYNCHRONOUS:-0}
DNSSEC=${DNSSEC:-no}
#TSIG_SUPERMASTER=
#TSIG_NOTIFY=
#DEBUG=
OPTIONS=()
OPTIONS+="--setuid=pdns "
OPTIONS+="--setgid=pdns "
OPTIONS+="--api=yes "
OPTIONS+="--api-key=${API_KEY} "
OPTIONS+="--webserver=yes "
OPTIONS+="--webserver-address=0.0.0.0 "
OPTIONS+="--launch=gsqlite3 "
OPTIONS+="--gsqlite3-database=${SQLITE_DBPATH} "
OPTIONS+="--gsqlite3-pragma-foreign-keys "
OPTIONS+="--gsqlite3-dnssec=${DNSSEC} "
OPTIONS+="--gsqlite3-pragma-synchronous=${GSQLITE3_PRAGMA_SYNCHRONOUS} "
OPTIONS+="--default-ttl=${DEFAULT_TTL} "
OPTIONS+="--default-soa-name=${DEFAULT_SOA_NAME} "
OPTIONS+="--allow-axfr-ips=${ALLOW_AXFR_IPS} "
OPTIONS+="--slave-renotify=${SLAVE_RENOTIFY} "
OPTIONS+="--slave-cycle-interval=${SLAVE_CYCLE_INTERVAL} "
OPTIONS+="--webserver-port=8083 "
OPTIONS+="--daemon=no --no-config "
# Use TSIGs if provided
if [[ -n ${TSIG_SUPERMASTER} ]]; then
OPTIONS+="--allow-unsigned-supermaster=no "
fi
if [[ -n ${TSIG_NOTIFY} ]]; then
OPTIONS+="--allow-unsigned-notify=no "
fi
# Enable showing of dns queries if debugging enabled
if [[ ${DEBUG} == "true" ]]; then
OPTIONS+="--log-dns-queries=yes "
OPTIONS+="--loglevel=5 "
fi
# Master/Slave management
if [[ ${SLAVE} == "yes" ]]
then
OPTIONS+="--slave=${SLAVE} "
# ALLOW_NOTIFY_FROM must be set
if [[ -z ${ALLOW_NOTIFY_FROM} ]]; then
echo "ALLOW_NOTIFY_FROM is not set, please configure this when to turn slave mode on."
exit 1
fi
OPTIONS+="--allow-notify-from=${ALLOW_NOTIFY_FROM} "
elif [[ ${MASTER} == "yes" ]]
then
OPTIONS+="--master=${MASTER} "
else
echo "Error, PowerDNS must be configured in either master or slave mode"
exit 1
fi
# also-notify
if [[ -n ${ALSO_NOTIFY} ]]
then
OPTIONS+="--also-notify=$ALSO_NOTIFY "
fi
# default-soa-email
if [[ -n ${DEFAULT_SOA_MAIL} ]]; then
OPTIONS+="--default-soa-mail=${DEFAULT_SOA_MAIL} "
fi
# Init the sqlite db if it does not exist
if [[ ! -e ${SQLITE_DBPATH} ]]
then
cat /pdns/init.sql | sqlite3 ${SQLITE_DBPATH}
else
echo "Database exist and some tables were found."
echo "Assuming this is not the first launch"
fi
# Set correct permissions
chown -Rv pdns:pdns /data
chown -Rv pdns:pdns ${SQLITE_DBPATH}
# Recreate list of Supermasters.
if [[ -n $PDNS_SUPERMASTERS ]]; then
echo "PDNS_SUPERMASTERS SET! TO: $PDNS_SUPERMASTERS"
for i in $PDNS_SUPERMASTERS; do
IFS=: read -r ipaddr ipname <<< "$i"
echo "sqlite3 ${SQLITE_DBPATH} insert into supermasters values ('$ipaddr','$ipname', 'admin');"
sqlite3 ${SQLITE_DBPATH} "insert into supermasters values ('$ipaddr','$ipname', 'admin');"
done
fi
# Start PowerDNS
echo "/usr/sbin/pdns_server ${OPTIONS}"
echo "hello"
/usr/sbin/pdns_server ${OPTIONS}
|
C#
|
UTF-8
| 1,016
| 2.546875
| 3
|
[] |
no_license
|
using UnityEngine;
using System.Collections;
public struct heart_beat {
public static ushort ID = 65500;
enum state_t
{
INTERACTIVE,
HEART_BEAT,
};
public void interactive()
{
m_mode = (long)state_t.INTERACTIVE;
m_future_time = System.DateTime.UtcNow.Ticks + max_interactive_interval * 10000000;
}
public void heartbeat()
{
m_mode = (long)state_t.HEART_BEAT;
m_future_time = System.DateTime.UtcNow.Ticks + max_heart_beat_interval * 10000000;
}
public bool die()
{
return (System.DateTime.UtcNow.Ticks >= m_future_time);
}
public bool is_interactive()
{
return ((long)state_t.INTERACTIVE == m_mode);
}
public bool is_heartbeat()
{
return ((long)state_t.HEART_BEAT == m_mode);
}
long m_mode;
long m_future_time;
static int max_interactive_interval = 15;
static int max_heart_beat_interval = 15;
}
|
Java
|
UTF-8
| 1,987
| 2.75
| 3
|
[
"Apache-2.0"
] |
permissive
|
package org.siouan.frontendgradleplugin.core;
import java.io.File;
import org.gradle.api.Task;
/**
* This abstract class provides the reusable logic to run a NPM/Yarn script.
*/
public class RunScriptJob extends AbstractTaskJob {
/**
* Executor use to run the script.
*/
private final Executor executor;
/**
* Directory where the Node distribution is installed.
*/
private final File nodeInstallDirectory;
/**
* Directory where the Yarn distribution is installed.
*/
private final File yarnInstallDirectory;
/**
* The script run by the job with NPM or Yarn.
*/
private final String script;
/**
* O/S name.
*/
private final String osName;
/**
* Builds a job to run a script.
*
* @param task Parent task.
* @param executor Executor to use to run the script.
* @param nodeInstallDirectory Node install directory.
* @param yarnInstallDirectory Yarn install directory.
* @param script The script run by the job.
* @param osName O/S name.
*/
public RunScriptJob(final Task task, final Executor executor, final File nodeInstallDirectory,
final File yarnInstallDirectory, final String script, final String osName) {
super(task);
this.executor = executor;
this.nodeInstallDirectory = nodeInstallDirectory;
this.yarnInstallDirectory = yarnInstallDirectory;
this.script = script;
this.osName = osName;
}
public void run() throws ExecutableNotFoundException {
task.getProject()
.exec(new ExecSpecAction(executor, nodeInstallDirectory, yarnInstallDirectory, osName, script, execSpec -> {
logDebug(execSpec.getEnvironment().toString());
logLifecycle(
"Running '" + execSpec.getExecutable() + ' ' + String.join(" ", execSpec.getArgs()) + '\'');
})).rethrowFailure().assertNormalExitValue();
}
}
|
Shell
|
UTF-8
| 464
| 3.421875
| 3
|
[] |
no_license
|
# Source: http://stackoverflow.com/a/14106707 by Keith Thompson
# ============
# Example:
# fileName="$(cond "$useDefault" "$defaultName" "$customName").txt"
# ============
# Instead of
# ============
# if [ $useDefault ]; then
# tmpname="$defaultName"
# else
# tmpname="$customName"
# fi
# fileName="$dirName/$tmpname.txt"
#
# Or the ugly alternate
# a=$([[ $b = 5 ]] && echo "$c" || echo "$d"])
cond(){
if [ "$1" ]; then
echo "$2"
else
echo "$3"
fi
}
|
C#
|
UTF-8
| 2,594
| 3.015625
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using WHMS.Commands.Contracts;
using WHMS.Services.Contracts;
namespace WHMS.Commands.Modifying
{
public class AddProductToOrderCommand : ICommand
{
private IOrderService orderService;
private IProductService productService;
private IProductWarehouseService productWarehouseService;
private IWarehouseService warehouseService;
public AddProductToOrderCommand(
IOrderService orderService,
IProductService productService,
IProductWarehouseService productWarehouseService,
IWarehouseService warehouseService)
{
this.orderService = orderService;
this.productService = productService;
this.productWarehouseService = productWarehouseService;
this.warehouseService = warehouseService;
}
//orderId,product,quantity,warehouse
public string Execute(IReadOnlyList<string> parameters)
{
if (parameters.Count!=4)
{
throw new ArgumentException(@"Please provide parameters: OrderId;Product;Quantity;Warehouse");
}
int orderId;
if (!int.TryParse(parameters[0], out orderId))
{
throw new ArgumentException($"{parameters[0]} is not a valid order ID.");
}
var order = orderService.GetOrderById(orderId);
var product = this.productService.FindByName(parameters[1]);
int quantity;
if (!int.TryParse(parameters[2], out quantity))
{
throw new ArgumentException($"{parameters[2]} is not a valid quantity.");
}
var warehouse = this.warehouseService.GetByName(parameters[3]);
var inStock = this.productWarehouseService.GetQuantity(product.Id, warehouse.Id);
if (order.Type.Equals("sell"))
{
if (inStock < quantity)
{
throw new ArgumentException($"The wanted quantity of {product.Name} is not available in {warehouse.Name}");
}
this.productWarehouseService.SubstractQuantity(product.Id, warehouse.Id, quantity);
}
else
{
this.productWarehouseService.AddQuantity(product.Id, warehouse.Id, quantity);
}
orderService.AddProductToOrder(orderId, product, quantity);
return $"Product: {product.Name} was added to Order with ID: {order.Id}.";
}
}
}
|
Swift
|
UTF-8
| 1,464
| 2.796875
| 3
|
[
"MIT"
] |
permissive
|
//
// BoundlessContext.swift
// BoundlessKit
//
// Created by Akash Desai on 3/8/18.
//
import Foundation
internal class BoundlessContext : NSObject {
static var locationEnabled = false
static var bluetoothEnabled = false
static let queue = DispatchQueue(label: NSStringFromClass(BoundlessContext.self), attributes: .concurrent)
class func getContext(completion:@escaping([String:Any]) -> Void) {
queue.async {
var context = [String:Any]()
let group = DispatchGroup()
if bluetoothEnabled {
group.enter()
BoundlessBluetooth.shared.getBluetooth { bluetoothInfo in
// BKLog.debug("Bluetoothinfo:\(bluetoothInfo as AnyObject)")
if let bluetoothInfo = bluetoothInfo {
context["bluetoothInfo"] = bluetoothInfo
}
group.leave()
}
}
if locationEnabled {
group.enter()
BoundlessLocation.shared.getLocation { locationInfo in
if let locationInfo = locationInfo {
context["locationInfo"] = locationInfo
}
group.leave()
}
}
group.notify(queue: DispatchQueue.global()) {
completion(context)
}
}
}
}
|
Java
|
UTF-8
| 753
| 3.046875
| 3
|
[] |
no_license
|
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Mathematics.Algorithm;
/**
* Interface for an
* <a href="http://en.wikipedia.org/wiki/Iterative">iterative</a>
* {@see Algorithm algorithm}.
* @author Rune Dahl Iversen
* @param <TypeOfValue> Type of value.
*/
public interface Iterative<TypeOfValue> extends Algorithm<TypeOfValue> {
/**
* Gets the maximum number of iterations allowed.
* @return The maximum number of iterations allowed.
*/
public int getMaximumIterations();
/**
* Sets the maximum number of iterations allowed.
* @param iterations The maximum number of iterations allowed.
*/
public void setMaximumIterations(final int iterations);
}
|
C++
|
UTF-8
| 7,463
| 2.515625
| 3
|
[] |
no_license
|
#include "test_runner.h"
#include "manager.h"
#include "utils.h"
#include "requests.h"
using namespace std;
const unordered_map<string, Request::ERequestType> ModifyRequestTypeByString = {
{"Stop", Request::ERequestType::ADD_STOP},
{"Bus", Request::ERequestType::ADD_BUS}
};
const unordered_map<string, Request::ERequestType> ReadRequestTypeByString = {
{"Bus", Request::ERequestType::QUERY_BUS},
{"Stop", Request::ERequestType::QUERY_STOP},
{"Route", Request::ERequestType::QUERY_ROUTE},
{"Map", Request::ERequestType::QUERY_MAP}
};
RequestHolder CreateRequestHolder(Request::ERequestType type) {
switch (type) {
case Request::ERequestType::ADD_BUS:
return make_unique<AddBusRequest>();
case Request::ERequestType::ADD_STOP:
return make_unique<AddStopRequest>();
case Request::ERequestType::QUERY_BUS:
return make_unique<ReadBusInfoRequest>();
case Request::ERequestType::QUERY_STOP:
return make_unique<ReadStopInfoRequest>();
case Request::ERequestType::QUERY_ROUTE:
return make_unique<ReadRouteInfoRequest>();
case Request::ERequestType::QUERY_MAP:
return make_unique<ReadMapInfoRequest>();
default:
throw "undefined type";
}
}
void ReadRequestsJson(vector<RequestHolder>& requests, const Node& node,
const unordered_map<string, Request::ERequestType>& RequestTypeByString) {
for (const auto& query_node : node.AsArray()) {
auto type = RequestTypeByString.at(query_node.AsMap().at("type").AsString());
requests.push_back(CreateRequestHolder(type));
requests.back()->ReadInfo(query_node);
}
}
struct InputData {
BusManagerSettings bus_manager_settings;
RenderSettings render_settings;
vector<RequestHolder> requests;
};
InputData ReadAllRequestsJson() {
auto document = Load(cin);
vector<RequestHolder> requests;
const auto& modify_requests = document.GetRoot().AsMap().at("base_requests");
ReadRequestsJson(requests, modify_requests, ModifyRequestTypeByString);
const auto& read_requests = document.GetRoot().AsMap().at("stat_requests");
ReadRequestsJson(requests, read_requests, ReadRequestTypeByString);
const auto& settings_info = document.GetRoot().AsMap().at("routing_settings").AsMap();
auto settings = BusManagerSettings(
static_cast<int>(settings_info.at("bus_wait_time").AsDouble()),
static_cast<int>(settings_info.at("bus_velocity").AsDouble())
);
auto render_settings = RenderSettings(document.GetRoot().AsMap().at("render_settings").AsMap());
return { settings, render_settings, move(requests) };
}
vector<unique_ptr<Response>> GetResponses(const InputData& input) {
BusManager manager(input.bus_manager_settings, input.render_settings);
vector<unique_ptr<Response>> responses;
for (auto& request_holder : input.requests) {
if (request_holder->Type == Request::ERequestType::ADD_STOP) {
const auto& request = static_cast<const ModifyRequest&>(*request_holder);
request.Process(manager);
}
}
for (auto& request_holder : input.requests) {
if (request_holder->Type == Request::ERequestType::ADD_BUS) {
const auto& request = static_cast<const ModifyRequest&>(*request_holder);
request.Process(manager);
}
}
manager.BuildRoutes();
for (auto& request_holder : input.requests) {
if (request_holder->Type == Request::ERequestType::QUERY_BUS) {
const auto& request = static_cast<const ReadBusInfoRequest&>(*request_holder);
responses.push_back(make_unique<BusInfoResponse>(request.Process(manager)));
}
else if (request_holder->Type == Request::ERequestType::QUERY_STOP) {
const auto& request = static_cast<const ReadStopInfoRequest&>(*request_holder);
responses.push_back(make_unique<StopInfoResponse>(request.Process(manager)));
}
else if (request_holder->Type == Request::ERequestType::QUERY_ROUTE) {
const auto& request = static_cast<const ReadRouteInfoRequest&>(*request_holder);
responses.push_back(make_unique<RouteInfoResponse>(request.Process(manager)));
}
else if (request_holder->Type == Request::ERequestType::QUERY_MAP) {
const auto& request = static_cast<const ReadMapInfoRequest&>(*request_holder);
responses.push_back(make_unique<MapInfoResponse>(request.Process(manager)));
}
}
return responses;
}
void PrintResponsesJson(const vector<unique_ptr<Response>>& responses) {
auto result_vec = vector<Node>();
for (const auto& response_ptr: responses) {
Node response_node;
if (response_ptr->Type == Response::EResponseType::BUS_INFO) {
auto cur_node = map<string, Node>{};
const auto& response = static_cast<const BusInfoResponse&>(*response_ptr);
cur_node["request_id"] = Node(static_cast<double>(response.Request_id));
if (response.Info) {
cur_node["stop_count"] = Node(static_cast<double>(response.Info.value().CntStops));
cur_node["unique_stop_count"] = Node(static_cast<double>(response.Info.value().UniqueStops));
cur_node["curvature"] = Node(response.Info.value().Curvature);
cur_node["route_length"] = Node(response.Info.value().PathLength);
}
else {
cur_node["error_message"] = Node("not found"s);
}
response_node = Node(cur_node);
}
else if (response_ptr->Type == Response::EResponseType::STOP_INFO) {
auto cur_node = map<string, Node>{};
const auto& response = static_cast<const StopInfoResponse&>(*response_ptr);
cur_node["request_id"] = Node(static_cast<double>(response.Request_id));
if (response.Info) {
auto buses_vector = vector<Node>();
for (const auto& bus_name : response.Info.value().Buses) {
buses_vector.push_back(Node(bus_name));
}
cur_node["buses"] = buses_vector;
}
else {
cur_node["error_message"] = Node("not found"s);
}
response_node = Node(cur_node);
}
else if (response_ptr->Type == Response::EResponseType::ROUTE_INFO) {
const auto& response = static_cast<const RouteInfoResponse&>(*response_ptr);
response_node = response.Info;
}
else if (response_ptr->Type == Response::EResponseType::MAP_INFO) {
const auto& response = static_cast<const MapInfoResponse&>(*response_ptr);
response_node = response.Info;
}
else {
throw runtime_error("Not implemented Response to print");
}
result_vec.push_back(response_node);
}
auto result_node = Node(result_vec);
result_node.Print(cout);
}
int main() {
//FILE* file;
//freopen_s(&file, "C:\\Users\\Admin\\source\\repos\\BlackBelt\\Solutions\\BusManager\\a.in", "r", stdin);
//FILE* file2;
//freopen_s(&file2, "C:\\Users\\Admin\\source\\repos\\BlackBelt\\Solutions\\BusManager\\map.svg", "w", stdout);
auto requests = ReadAllRequestsJson();
const auto responses = GetResponses(move(requests));
PrintResponsesJson(responses);
}
|
C#
|
UTF-8
| 1,673
| 2.84375
| 3
|
[] |
no_license
|
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System;
using Cygni.DataTypes;
using Cygni.AST;
namespace Cygni.Extensions
{
/// <summary>
/// Description of Extension.
/// </summary>
public static class Extension
{
public static string OperatorToString(this NodeType type)
{
switch (type)
{
case NodeType.Add:
return "+";
case NodeType.Subtract:
return "-";
case NodeType.Multiply:
return "*";
case NodeType.Divide:
return "/";
case NodeType.IntDiv:
return "//";
case NodeType.Modulo:
return "%";
case NodeType.Power:
return "^";
case NodeType.Concatenate:
return "&";
case NodeType.LessThan:
return "<";
case NodeType.GreaterThan:
return ">";
case NodeType.LessThanOrEqual:
return "<=";
case NodeType.GreaterThanOrEqual:
return ">=";
case NodeType.Equal:
return "==";
case NodeType.NotEqual:
return "!=";
case NodeType.Plus:
return "+";
case NodeType.Minus:
return "-";
default:
return type.ToString();
}
}
}
}
|
Markdown
|
UTF-8
| 1,593
| 3.078125
| 3
|
[] |
no_license
|
# C'est quoi un navigateur ?
## [Le fonctionnement de base du navigateur:](https://www.ntu.edu.sg/home/ehchua/programming/webprogramming/HTTP_Basics.html)
Le navigateur ne fait pas de magie : tout se passe sur le réseau. le navigateur interroge le serveur distant sur une socket, récupère la réponse, l'interprète, et l'affiche.

source : https://www.ntu.edu.sg/home/ehchua/programming/webprogramming/images/HTTP_Steps.png
## Exemple de requête web:

La requête contient, par ordre d'apparition :
* **un Verbe (GET)**, **un chemin (/doc/test.html)**, un protocole (HTTP/1.1)
* l'hôte auquel s'adresse la requete (www.test101.com)
* les headers
* une ligne vide pour marquer la fin de la requête
* un corps de message qui suit (optionnel)
Plus de détails : https://tools.ietf.org/html/rfc2616
## Exemple de réponse:

On retrouve dans la réponse :
* le protocole (HTTP/1.1), **le statut** (200 OK)
* des headers
* une ligne blanche
* le contenu de la page (optionnel, mais très fréquemment rempli)
plus de détails : https://tools.ietf.org/html/rfc7231
Dans l'exemple ci dessus, la partie qui nous intéresse et qui fera l'objet du travail est
```<h1> My Home page</h1>```
suite : [anatomie d'une page web](./02-anatomie-page-web.md)
|
Java
|
UTF-8
| 539
| 3.046875
| 3
|
[] |
no_license
|
package IXL;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
/**
* Created by yuegu on 12/1/18.
*/
public class _518_CoinChange2 {
public int change(int amount, int[] coins) {
Map<Integer, Integer> map = new HashMap<>();
for(int i = 0; i < coins.length; i++) {
map.put(coins[i], 1);
}
Arrays.sort(coins);
for(int i = coins.length - 1; i >=0; i--) {
if(amount < coins[i])
continue;
else {
return 1 + change(amount - coins[i], coins);
}
}
}
}
|
C#
|
UTF-8
| 2,474
| 2.6875
| 3
|
[] |
no_license
|
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ClassLibraryData;
namespace ClassLibraryMethods
{
public class ServiceMethods
{
public List<FilmDTO> GetFilms()
{
List<FilmDTO> Films = new List<FilmDTO>();
var dataset = new DB_dotNetDataSet();
var FilmsAdapter = new ClassLibraryData.DB_dotNetDataSetTableAdapters.FilmTableAdapter();
FilmsAdapter.Fill(dataset.Film);
var ProducersAdapter = new ClassLibraryData.DB_dotNetDataSetTableAdapters.ProducerTableAdapter();
ProducersAdapter.Fill(dataset.Producer);
Films = (from item in dataset.Film
select new FilmDTO()
{
Title = item.Title,
year = item.year,
producer = item.producer
}).ToList();
return Films;
}
public List<ProducerDTO> GetProducers()
{
List<ProducerDTO> Producers = new List<ProducerDTO>();
var dataset = new DB_dotNetDataSet();
var ProducersAdapter = new ClassLibraryData.DB_dotNetDataSetTableAdapters.ProducerTableAdapter();
ProducersAdapter.Fill(dataset.Producer);
Producers = (from item in dataset.Producer
select new ProducerDTO()
{
id = item.id,
FirstName = item.FirstName,
LastName = item.LastName,
FullName = item.FullName
}).ToList();
return Producers;
}
public void AddProducer(string firstName,string lastName)
{
var dataset = new DB_dotNetDataSet();
var ProducersAdapter = new ClassLibraryData.DB_dotNetDataSetTableAdapters.ProducerTableAdapter();
ProducersAdapter.Fill(dataset.Producer);
ProducersAdapter.Insert(firstName, lastName);
}
public void DeleteProducer(int id)
{
var dataset = new DB_dotNetDataSet();
var ProducersAdapter = new ClassLibraryData.DB_dotNetDataSetTableAdapters.ProducerTableAdapter();
ProducersAdapter.Fill(dataset.Producer);
ProducersAdapter.DeleteQuery(id);
}
}
}
|
Java
|
UTF-8
| 1,715
| 2.40625
| 2
|
[] |
no_license
|
/**
* 26-feb-2015 - MyGochisDAO.java
* © Instituto Tecnológico de Informática, All Rights Reserved
*/
package es.iti.formacion.tecnogochi.persistence.dao;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;
import es.iti.formacion.tecnogochi.model.MyGochis;
import es.iti.formacion.tecnogochi.model.MyGochis_;
import es.iti.formacion.tecnogochi.persistence.dao.base.MyGochisJpaController;
import es.iti.formacion.tecnogochi.persistence.enums.ConfigurationEnum;
/**
* @author Francisco Javier Barrena (twitter: @DogDeveloper)
*/
public class MyGochisDAO extends MyGochisJpaController {
private static final org.slf4j.Logger LOGGER = org.slf4j.LoggerFactory.getLogger(MyGochisDAO.class);
public MyGochisDAO() {
super(Persistence.createEntityManagerFactory(ConfigurationEnum.PERSISTENCE_UNIT_NAME.getValue()));
}
public MyGochis findByName(String name) {
EntityManager em = null;
try {
em = this.getEntityManager();
String query = String.format(
"SELECT t FROM %s t WHERE t.%s = :nameParam",
MyGochis.class.getSimpleName(),
MyGochis_.name.getName());
TypedQuery<MyGochis> typedQuery = em.createQuery(query, MyGochis.class);
typedQuery.setParameter("nameParam", name);
return typedQuery.getSingleResult();
}
catch(Exception ex) {
LOGGER.error("Error buscando MyGochis por nombre", ex);
return null;
}
finally {
if(em != null) {
em.close();
}
}
}
}
|
C++
|
UTF-8
| 9,565
| 2.53125
| 3
|
[
"MIT"
] |
permissive
|
#include "CryptoUtil.h"
static const unsigned int _IV[5] = { 0x67452301, 0xefcdab89, 0x98badcfe,
0x10325476, 0xc3d2e1f0 };
static const unsigned int _K0 = 0x5a827999;
static const unsigned int _K1 = 0x6ed9eba1;
static const unsigned int _K2 = 0x8f1bbcdc;
static const unsigned int _K3 = 0xa953fd4e;
static const unsigned int _K4 = 0x7a6d76e9;
static const unsigned int _K5 = 0x6d703ef3;
static const unsigned int _K6 = 0x5c4dd124;
static const unsigned int _K7 = 0x50a28be6;
static unsigned int rotl(unsigned int x, unsigned int n) {
return (x << n) | (x >> (32 - n));
}
static unsigned int F(unsigned int x, unsigned int y, unsigned int z) {
return x ^ y ^ z;
}
static unsigned int G(unsigned int x, unsigned int y, unsigned int z) {
return (((x) & (y)) | (~(x) & (z)));
}
static unsigned int H(unsigned int x, unsigned int y, unsigned int z) {
return (((x) | ~(y)) ^ (z));
}
static unsigned int I(unsigned int x, unsigned int y, unsigned int z) {
return (((x) & (z)) | ((y) & ~(z)));
}
static unsigned int J(unsigned int x, unsigned int y, unsigned int z) {
return ((x) ^ ((y) | ~(z)));
}
static void FF(unsigned int &a, unsigned int &b, unsigned int &c,
unsigned int &d, unsigned int &e, unsigned int x, unsigned int s) {
a += F(b, c, d) + x;
a = rotl(a, s) + e;
c = rotl(c, 10);
}
static void GG(unsigned int &a, unsigned int &b, unsigned int &c,
unsigned int &d, unsigned int &e, unsigned int x, unsigned int s) {
a += G(b, c, d) + x + _K0;
a = rotl(a, s) + e;
c = rotl(c, 10);
}
static void HH(unsigned int &a, unsigned int &b, unsigned int &c,
unsigned int &d, unsigned int &e, unsigned int x, unsigned int s) {
a += H(b, c, d) + x + _K1;
a = rotl(a, s) + e;
c = rotl(c, 10);
}
static void II(unsigned int &a, unsigned int &b, unsigned int &c,
unsigned int &d, unsigned int &e, unsigned int x, unsigned int s) {
a += I(b, c, d) + x + _K2;
a = rotl(a, s) + e;
c = rotl(c, 10);
}
static void JJ(unsigned int &a, unsigned int &b, unsigned int &c,
unsigned int &d, unsigned int &e, unsigned int x, unsigned int s) {
a += J(b, c, d) + x + _K3;
a = rotl(a, s) + e;
c = rotl(c, 10);
}
static void FFF(unsigned int &a, unsigned int &b, unsigned int &c,
unsigned int &d, unsigned int &e, unsigned int x, unsigned int s) {
a += F(b, c, d) + x;
a = rotl(a, s) + e;
c = rotl(c, 10);
}
static void GGG(unsigned int &a, unsigned int &b, unsigned int &c,
unsigned int &d, unsigned int &e, unsigned int x, unsigned int s) {
a += G(b, c, d) + x + _K4;
a = rotl(a, s) + e;
c = rotl(c, 10);
}
static void HHH(unsigned int &a, unsigned int &b, unsigned int &c,
unsigned int &d, unsigned int &e, unsigned int x, unsigned int s) {
a += H(b, c, d) + x + _K5;
a = rotl(a, s) + e;
c = rotl(c, 10);
}
static void III(unsigned int &a, unsigned int &b, unsigned int &c,
unsigned int &d, unsigned int &e, unsigned int x, unsigned int s) {
a += I(b, c, d) + x + _K6;
a = rotl(a, s) + e;
c = rotl(c, 10);
}
static void JJJ(unsigned int &a, unsigned int &b, unsigned int &c,
unsigned int &d, unsigned int &e, unsigned int x, unsigned int s) {
a += J(b, c, d) + x + _K7;
a = rotl(a, s) + e;
c = rotl(c, 10);
}
void crypto::ripemd160(unsigned int *x, unsigned int *digest) {
unsigned int a1 = _IV[0];
unsigned int b1 = _IV[1];
unsigned int c1 = _IV[2];
unsigned int d1 = _IV[3];
unsigned int e1 = _IV[4];
unsigned int a2 = _IV[0];
unsigned int b2 = _IV[1];
unsigned int c2 = _IV[2];
unsigned int d2 = _IV[3];
unsigned int e2 = _IV[4];
/* round 1 */
FF(a1, b1, c1, d1, e1, x[0], 11);
FF(e1, a1, b1, c1, d1, x[1], 14);
FF(d1, e1, a1, b1, c1, x[2], 15);
FF(c1, d1, e1, a1, b1, x[3], 12);
FF(b1, c1, d1, e1, a1, x[4], 5);
FF(a1, b1, c1, d1, e1, x[5], 8);
FF(e1, a1, b1, c1, d1, x[6], 7);
FF(d1, e1, a1, b1, c1, x[7], 9);
FF(c1, d1, e1, a1, b1, x[8], 11);
FF(b1, c1, d1, e1, a1, x[9], 13);
FF(a1, b1, c1, d1, e1, x[10], 14);
FF(e1, a1, b1, c1, d1, x[11], 15);
FF(d1, e1, a1, b1, c1, x[12], 6);
FF(c1, d1, e1, a1, b1, x[13], 7);
FF(b1, c1, d1, e1, a1, x[14], 9);
FF(a1, b1, c1, d1, e1, x[15], 8);
/* round 2 */
GG(e1, a1, b1, c1, d1, x[7], 7);
GG(d1, e1, a1, b1, c1, x[4], 6);
GG(c1, d1, e1, a1, b1, x[13], 8);
GG(b1, c1, d1, e1, a1, x[1], 13);
GG(a1, b1, c1, d1, e1, x[10], 11);
GG(e1, a1, b1, c1, d1, x[6], 9);
GG(d1, e1, a1, b1, c1, x[15], 7);
GG(c1, d1, e1, a1, b1, x[3], 15);
GG(b1, c1, d1, e1, a1, x[12], 7);
GG(a1, b1, c1, d1, e1, x[0], 12);
GG(e1, a1, b1, c1, d1, x[9], 15);
GG(d1, e1, a1, b1, c1, x[5], 9);
GG(c1, d1, e1, a1, b1, x[2], 11);
GG(b1, c1, d1, e1, a1, x[14], 7);
GG(a1, b1, c1, d1, e1, x[11], 13);
GG(e1, a1, b1, c1, d1, x[8], 12);
/* round 3 */
HH(d1, e1, a1, b1, c1, x[3], 11);
HH(c1, d1, e1, a1, b1, x[10], 13);
HH(b1, c1, d1, e1, a1, x[14], 6);
HH(a1, b1, c1, d1, e1, x[4], 7);
HH(e1, a1, b1, c1, d1, x[9], 14);
HH(d1, e1, a1, b1, c1, x[15], 9);
HH(c1, d1, e1, a1, b1, x[8], 13);
HH(b1, c1, d1, e1, a1, x[1], 15);
HH(a1, b1, c1, d1, e1, x[2], 14);
HH(e1, a1, b1, c1, d1, x[7], 8);
HH(d1, e1, a1, b1, c1, x[0], 13);
HH(c1, d1, e1, a1, b1, x[6], 6);
HH(b1, c1, d1, e1, a1, x[13], 5);
HH(a1, b1, c1, d1, e1, x[11], 12);
HH(e1, a1, b1, c1, d1, x[5], 7);
HH(d1, e1, a1, b1, c1, x[12], 5);
/* round 4 */
II(c1, d1, e1, a1, b1, x[1], 11);
II(b1, c1, d1, e1, a1, x[9], 12);
II(a1, b1, c1, d1, e1, x[11], 14);
II(e1, a1, b1, c1, d1, x[10], 15);
II(d1, e1, a1, b1, c1, x[0], 14);
II(c1, d1, e1, a1, b1, x[8], 15);
II(b1, c1, d1, e1, a1, x[12], 9);
II(a1, b1, c1, d1, e1, x[4], 8);
II(e1, a1, b1, c1, d1, x[13], 9);
II(d1, e1, a1, b1, c1, x[3], 14);
II(c1, d1, e1, a1, b1, x[7], 5);
II(b1, c1, d1, e1, a1, x[15], 6);
II(a1, b1, c1, d1, e1, x[14], 8);
II(e1, a1, b1, c1, d1, x[5], 6);
II(d1, e1, a1, b1, c1, x[6], 5);
II(c1, d1, e1, a1, b1, x[2], 12);
/* round 5 */
JJ(b1, c1, d1, e1, a1, x[4], 9);
JJ(a1, b1, c1, d1, e1, x[0], 15);
JJ(e1, a1, b1, c1, d1, x[5], 5);
JJ(d1, e1, a1, b1, c1, x[9], 11);
JJ(c1, d1, e1, a1, b1, x[7], 6);
JJ(b1, c1, d1, e1, a1, x[12], 8);
JJ(a1, b1, c1, d1, e1, x[2], 13);
JJ(e1, a1, b1, c1, d1, x[10], 12);
JJ(d1, e1, a1, b1, c1, x[14], 5);
JJ(c1, d1, e1, a1, b1, x[1], 12);
JJ(b1, c1, d1, e1, a1, x[3], 13);
JJ(a1, b1, c1, d1, e1, x[8], 14);
JJ(e1, a1, b1, c1, d1, x[11], 11);
JJ(d1, e1, a1, b1, c1, x[6], 8);
JJ(c1, d1, e1, a1, b1, x[15], 5);
JJ(b1, c1, d1, e1, a1, x[13], 6);
/* parallel round 1 */
JJJ(a2, b2, c2, d2, e2, x[5], 8);
JJJ(e2, a2, b2, c2, d2, x[14], 9);
JJJ(d2, e2, a2, b2, c2, x[7], 9);
JJJ(c2, d2, e2, a2, b2, x[0], 11);
JJJ(b2, c2, d2, e2, a2, x[9], 13);
JJJ(a2, b2, c2, d2, e2, x[2], 15);
JJJ(e2, a2, b2, c2, d2, x[11], 15);
JJJ(d2, e2, a2, b2, c2, x[4], 5);
JJJ(c2, d2, e2, a2, b2, x[13], 7);
JJJ(b2, c2, d2, e2, a2, x[6], 7);
JJJ(a2, b2, c2, d2, e2, x[15], 8);
JJJ(e2, a2, b2, c2, d2, x[8], 11);
JJJ(d2, e2, a2, b2, c2, x[1], 14);
JJJ(c2, d2, e2, a2, b2, x[10], 14);
JJJ(b2, c2, d2, e2, a2, x[3], 12);
JJJ(a2, b2, c2, d2, e2, x[12], 6);
/* parallel round 2 */
III(e2, a2, b2, c2, d2, x[6], 9);
III(d2, e2, a2, b2, c2, x[11], 13);
III(c2, d2, e2, a2, b2, x[3], 15);
III(b2, c2, d2, e2, a2, x[7], 7);
III(a2, b2, c2, d2, e2, x[0], 12);
III(e2, a2, b2, c2, d2, x[13], 8);
III(d2, e2, a2, b2, c2, x[5], 9);
III(c2, d2, e2, a2, b2, x[10], 11);
III(b2, c2, d2, e2, a2, x[14], 7);
III(a2, b2, c2, d2, e2, x[15], 7);
III(e2, a2, b2, c2, d2, x[8], 12);
III(d2, e2, a2, b2, c2, x[12], 7);
III(c2, d2, e2, a2, b2, x[4], 6);
III(b2, c2, d2, e2, a2, x[9], 15);
III(a2, b2, c2, d2, e2, x[1], 13);
III(e2, a2, b2, c2, d2, x[2], 11);
/* parallel round 3 */
HHH(d2, e2, a2, b2, c2, x[15], 9);
HHH(c2, d2, e2, a2, b2, x[5], 7);
HHH(b2, c2, d2, e2, a2, x[1], 15);
HHH(a2, b2, c2, d2, e2, x[3], 11);
HHH(e2, a2, b2, c2, d2, x[7], 8);
HHH(d2, e2, a2, b2, c2, x[14], 6);
HHH(c2, d2, e2, a2, b2, x[6], 6);
HHH(b2, c2, d2, e2, a2, x[9], 14);
HHH(a2, b2, c2, d2, e2, x[11], 12);
HHH(e2, a2, b2, c2, d2, x[8], 13);
HHH(d2, e2, a2, b2, c2, x[12], 5);
HHH(c2, d2, e2, a2, b2, x[2], 14);
HHH(b2, c2, d2, e2, a2, x[10], 13);
HHH(a2, b2, c2, d2, e2, x[0], 13);
HHH(e2, a2, b2, c2, d2, x[4], 7);
HHH(d2, e2, a2, b2, c2, x[13], 5);
/* parallel round 4 */
GGG(c2, d2, e2, a2, b2, x[8], 15);
GGG(b2, c2, d2, e2, a2, x[6], 5);
GGG(a2, b2, c2, d2, e2, x[4], 8);
GGG(e2, a2, b2, c2, d2, x[1], 11);
GGG(d2, e2, a2, b2, c2, x[3], 14);
GGG(c2, d2, e2, a2, b2, x[11], 14);
GGG(b2, c2, d2, e2, a2, x[15], 6);
GGG(a2, b2, c2, d2, e2, x[0], 14);
GGG(e2, a2, b2, c2, d2, x[5], 6);
GGG(d2, e2, a2, b2, c2, x[12], 9);
GGG(c2, d2, e2, a2, b2, x[2], 12);
GGG(b2, c2, d2, e2, a2, x[13], 9);
GGG(a2, b2, c2, d2, e2, x[9], 12);
GGG(e2, a2, b2, c2, d2, x[7], 5);
GGG(d2, e2, a2, b2, c2, x[10], 15);
GGG(c2, d2, e2, a2, b2, x[14], 8);
/* parallel round 5 */
FFF(b2, c2, d2, e2, a2, x[12], 8);
FFF(a2, b2, c2, d2, e2, x[15], 5);
FFF(e2, a2, b2, c2, d2, x[10], 12);
FFF(d2, e2, a2, b2, c2, x[4], 9);
FFF(c2, d2, e2, a2, b2, x[1], 12);
FFF(b2, c2, d2, e2, a2, x[5], 5);
FFF(a2, b2, c2, d2, e2, x[8], 14);
FFF(e2, a2, b2, c2, d2, x[7], 6);
FFF(d2, e2, a2, b2, c2, x[6], 8);
FFF(c2, d2, e2, a2, b2, x[2], 13);
FFF(b2, c2, d2, e2, a2, x[13], 6);
FFF(a2, b2, c2, d2, e2, x[14], 5);
FFF(e2, a2, b2, c2, d2, x[0], 15);
FFF(d2, e2, a2, b2, c2, x[3], 13);
FFF(c2, d2, e2, a2, b2, x[9], 11);
FFF(b2, c2, d2, e2, a2, x[11], 11);
digest[0] = be32toh(_IV[1] + c1 + d2);
digest[1] = be32toh(_IV[2] + d1 + e2);
digest[2] = be32toh(_IV[3] + e1 + a2);
digest[3] = be32toh(_IV[4] + a1 + b2);
digest[4] = be32toh(_IV[0] + b1 + c2);
}
|
Java
|
UTF-8
| 1,722
| 2.921875
| 3
|
[] |
no_license
|
package nullpointerexception.flexichess;
public class FitGirls {
public static String boardAsString(int[][] board) {
int radky = board.length;
int sloupce = board[0].length;
StringBuffer buffer = new StringBuffer();
buffer.append(" ");
for (int i = 0; i < sloupce; i++) {
buffer.append(i);
if (i == (sloupce - 1)) {
buffer.append(" \n");
} else {
buffer.append(" ");
}
}
buffer.append(" ┌");
for (int i = 0; i < sloupce - 1; i++) {
buffer.append("───┬");
}
buffer.append("───┐\n");
for (int i = 0; i < (radky * 2) - 1; i++) {
if (i % 2 == 0) {
buffer.append(i / 2);
buffer.append(" │");
for (int j = 0; j < sloupce; j++) {
buffer.append(" ");
if (board[i / 2][j] != 0) {
buffer.append(board[i / 2][j]);
} else {
buffer.append(" ");
}
buffer.append(" │");
}
buffer.append("\n");
} else {
buffer.append(" ├");
for (int j = 0; j < sloupce - 1; j++) {
buffer.append("───┼");
}
buffer.append("───┤\n");
}
}
buffer.append(" └");
for (int i = 0; i < sloupce - 1; i++) {
buffer.append("───┴");
}
buffer.append("───┘");
return buffer.toString();
}
}
|
Java
|
UTF-8
| 13,618
| 2.390625
| 2
|
[] |
no_license
|
package org.zywx.wbpalmstar.base.zip;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;
import java.util.zip.CRC32;
import java.util.zip.Deflater;
import java.util.zip.ZipException;
public class CnZipOutputStream extends DeflaterOutputStream implements
ZipConstants {
private ZipEntry entry;
@SuppressWarnings("rawtypes")
private Vector entries = new Vector();
@SuppressWarnings("rawtypes")
private Hashtable names = new Hashtable();
private CRC32 crc = new CRC32();
private long written;
private long locoff = 0L;
private String comment;
private int method = 8;
private boolean finished;
private boolean closed = false;
private String encoding = "UTF-8";
public static final int STORED = 0;
public static final int DEFLATED = 8;
private void ensureOpen() throws IOException {
if (this.closed)
throw new IOException("Stream closed");
}
public CnZipOutputStream(OutputStream out) {
super(out, new Deflater(-1, true));
this.usesDefaultDeflater = true;
}
public CnZipOutputStream(OutputStream out, String encoding) {
this(out);
this.encoding = encoding;
}
public void setComment(String comment) {
if ((comment != null) && (comment.length() > 21845)
&& (getUTF8Length(comment) > 65535)) {
throw new IllegalArgumentException("ZIP file comment too long.");
}
this.comment = comment;
}
public void setMethod(int method) {
if ((method != 8) && (method != 0)) {
throw new IllegalArgumentException("invalid compression method");
}
this.method = method;
}
public void setLevel(int level) {
this.def.setLevel(level);
}
@SuppressWarnings("unchecked")
public void putNextEntry(ZipEntry e) throws IOException {
ensureOpen();
if (this.entry != null) {
closeEntry();
}
if (e.time == -1L) {
e.setTime(System.currentTimeMillis());
}
if (e.method == -1) {
e.method = this.method;
}
switch (e.method) {
case 8:
if ((e.size == -1L) || (e.csize == -1L) || (e.crc == -1L)) {
e.flag = 8;
} else if ((e.size != -1L) && (e.csize != -1L) && (e.crc != -1L)) {
e.flag = 0;
} else
throw new ZipException(
"DEFLATED entry missing size, compressed size, or crc-32");
e.version = 20;
break;
case 0:
if (e.size == -1L)
e.size = e.csize;
else if (e.csize == -1L)
e.csize = e.size;
else if (e.size != e.csize) {
throw new ZipException(
"STORED entry where compressed != uncompressed size");
}
if ((e.size == -1L) || (e.crc == -1L)) {
throw new ZipException(
"STORED entry missing size, compressed size, or crc-32");
}
e.version = 10;
e.flag = 0;
break;
default:
throw new ZipException("unsupported compression method");
}
e.offset = this.written;
if (this.names.put(e.name, e) != null) {
throw new ZipException("duplicate entry: " + e.name);
}
writeLOC(e);
this.entries.addElement(e);
this.entry = e;
}
public void closeEntry() throws IOException {
ensureOpen();
ZipEntry e = this.entry;
if (e != null) {
switch (e.method) {
case 8:
this.def.finish();
while (!this.def.finished()) {
deflate();
}
if ((e.flag & 0x8) == 0) {
if (e.size != this.def.getTotalIn()) {
throw new ZipException("invalid entry size (expected "
+ e.size + " but got " + this.def.getTotalIn()
+ " bytes)");
}
if (e.csize != this.def.getTotalOut()) {
throw new ZipException(
"invalid entry compressed size (expected "
+ e.csize + " but got "
+ this.def.getTotalOut() + " bytes)");
}
if (e.crc != this.crc.getValue())
throw new ZipException(
"invalid entry CRC-32 (expected 0x"
+ Long.toHexString(e.crc)
+ " but got 0x"
+ Long.toHexString(this.crc.getValue())
+ ")");
} else {
e.size = this.def.getTotalIn();
e.csize = this.def.getTotalOut();
e.crc = this.crc.getValue();
writeEXT(e);
}
this.def.reset();
this.written += e.csize;
break;
case 0:
if (e.size != this.written - this.locoff) {
throw new ZipException("invalid entry size (expected "
+ e.size + " but got "
+ (this.written - this.locoff) + " bytes)");
}
if (e.crc == this.crc.getValue())
break;
throw new ZipException("invalid entry crc-32 (expected 0x"
+ Long.toHexString(e.crc) + " but got 0x"
+ Long.toHexString(this.crc.getValue()) + ")");
default:
throw new InternalError("invalid compression method");
}
this.crc.reset();
this.entry = null;
}
}
public synchronized void write(byte[] b, int off, int len)
throws IOException {
ensureOpen();
if ((off < 0) || (len < 0) || (off > b.length - len))
throw new IndexOutOfBoundsException();
if (len == 0) {
return;
}
if (this.entry == null) {
throw new ZipException("no current ZIP entry");
}
switch (this.entry.method) {
case 8:
super.write(b, off, len);
break;
case 0:
this.written += len;
if (this.written - this.locoff > this.entry.size) {
throw new ZipException(
"attempt to write past end of STORED entry");
}
this.out.write(b, off, len);
break;
default:
throw new InternalError("invalid compression method");
}
this.crc.update(b, off, len);
}
@SuppressWarnings("rawtypes")
public void finish() throws IOException {
ensureOpen();
if (this.finished) {
return;
}
if (this.entry != null) {
closeEntry();
}
if (this.entries.size() < 1) {
throw new ZipException("ZIP file must have at least one entry");
}
long off = this.written;
Enumeration e = this.entries.elements();
while (e.hasMoreElements()) {
writeCEN((ZipEntry) e.nextElement());
}
writeEND(off, this.written - off);
this.finished = true;
}
public void close() throws IOException {
if (!this.closed) {
super.close();
this.closed = true;
}
}
private void writeLOC(ZipEntry e) throws IOException {
writeInt(67324752L);
writeShort(e.version);
writeShort(e.flag);
writeShort(e.method);
writeInt(e.time);
if ((e.flag & 0x8) == 8) {
writeInt(0L);
writeInt(0L);
writeInt(0L);
} else {
writeInt(e.crc);
writeInt(e.csize);
writeInt(e.size);
}
byte[] nameBytes = (byte[]) null;
try {
if (this.encoding.toUpperCase().equals("UTF-8")) {
nameBytes = getUTF8Bytes(e.name);
} else
nameBytes = e.name.getBytes(this.encoding);
} catch (Exception byteE) {
nameBytes = getUTF8Bytes(e.name);
}
writeShort(nameBytes.length);
writeShort(e.extra != null ? e.extra.length : 0);
writeBytes(nameBytes, 0, nameBytes.length);
if (e.extra != null) {
writeBytes(e.extra, 0, e.extra.length);
}
this.locoff = this.written;
}
private void writeEXT(ZipEntry e) throws IOException {
writeInt(134695760L);
writeInt(e.crc);
writeInt(e.csize);
writeInt(e.size);
}
private void writeCEN(ZipEntry e) throws IOException {
writeInt(33639248L);
writeShort(e.version);
writeShort(e.version);
writeShort(e.flag);
writeShort(e.method);
writeInt(e.time);
writeInt(e.crc);
writeInt(e.csize);
writeInt(e.size);
byte[] nameBytes = (byte[]) null;
try {
if (this.encoding.toUpperCase().equals("UTF-8")) {
nameBytes = getUTF8Bytes(e.name);
} else
nameBytes = e.name.getBytes(this.encoding);
} catch (Exception byteE) {
nameBytes = getUTF8Bytes(e.name);
}
writeShort(nameBytes.length);
writeShort(e.extra != null ? e.extra.length : 0);
byte[] commentBytes;
if (e.comment != null) {
commentBytes = getUTF8Bytes(e.comment);
writeShort(commentBytes.length);
} else {
commentBytes = (byte[]) null;
writeShort(0);
}
writeShort(0);
writeShort(0);
writeInt(0L);
writeInt(e.offset);
writeBytes(nameBytes, 0, nameBytes.length);
if (e.extra != null) {
writeBytes(e.extra, 0, e.extra.length);
}
if (commentBytes != null)
writeBytes(commentBytes, 0, commentBytes.length);
}
private void writeEND(long off, long len) throws IOException {
writeInt(101010256L);
writeShort(0);
writeShort(0);
writeShort(this.entries.size());
writeShort(this.entries.size());
writeInt(len);
writeInt(off);
if (this.comment != null) {
byte[] b = getUTF8Bytes(this.comment);
writeShort(b.length);
writeBytes(b, 0, b.length);
} else {
writeShort(0);
}
}
private void writeShort(int v) throws IOException {
OutputStream out = this.out;
out.write(v >>> 0 & 0xFF);
out.write(v >>> 8 & 0xFF);
this.written += 2L;
}
private void writeInt(long v) throws IOException {
OutputStream out = this.out;
out.write((int) (v >>> 0 & 0xFF));
out.write((int) (v >>> 8 & 0xFF));
out.write((int) (v >>> 16 & 0xFF));
out.write((int) (v >>> 24 & 0xFF));
this.written += 4L;
}
private void writeBytes(byte[] b, int off, int len) throws IOException {
this.out.write(b, off, len);
this.written += len;
}
static int getUTF8Length(String s) {
int count = 0;
for (int i = 0; i < s.length(); i++) {
char ch = s.charAt(i);
if (ch <= '')
count++;
else if (ch <= '߿')
count += 2;
else {
count += 3;
}
}
return count;
}
private static byte[] getUTF8Bytes(String s) {
char[] c = s.toCharArray();
int len = c.length;
int count = 0;
for (int i = 0; i < len; i++) {
int ch = c[i];
if (ch <= 127)
count++;
else if (ch <= 2047)
count += 2;
else {
count += 3;
}
}
byte[] b = new byte[count];
int off = 0;
for (int i = 0; i < len; i++) {
int ch = c[i];
if (ch <= 127) {
b[(off++)] = (byte) ch;
} else if (ch <= 2047) {
b[(off++)] = (byte) (ch >> 6 | 0xC0);
b[(off++)] = (byte) (ch & 0x3F | 0x80);
} else {
b[(off++)] = (byte) (ch >> 12 | 0xE0);
b[(off++)] = (byte) (ch >> 6 & 0x3F | 0x80);
b[(off++)] = (byte) (ch & 0x3F | 0x80);
}
}
return b;
}
}
|
Python
|
UTF-8
| 608
| 5.15625
| 5
|
[] |
no_license
|
# Chapter-3: Arrays
# Array-Swap-Pairs
# Swap positions of successive pairs of values of given array. If length is odd, do not change the final element. e.g, for [1,2,3,4] return [2,1,4,3]. for ["Brendan", true, 42] return [true, "Brendan", 42]. Do this without using built-in methods
# Assume the array passed is a non-empty array
def swapPairs(arr):
for i in range(0, len(arr), 2):
if (i + 1) < len(arr):
arr[i], arr[i + 1] = arr[i + 1], arr[i]
myArr = [1,2,3,5,'',4]
print("The original array is {}").format(myArr)
swapPairs(myArr)
print("The swapped array is {}").format(myArr)
|
Java
|
UTF-8
| 606
| 2.09375
| 2
|
[] |
no_license
|
package com.neirx.stopwatchtimer.fragments;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.neirx.stopwatchtimer.R;
public class QueueFragment extends Fragment {
public static QueueFragment newInstance() {
return new QueueFragment();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_queue, container, false);
return rootView;
}
}
|
Java
|
UTF-8
| 1,707
| 3.171875
| 3
|
[] |
no_license
|
package com.zcc.thread_practise.Thread_example1;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* @author zcc
* @ClassName PhoneSearchMethon
* @description
* @date 2021/5/31 19:49
* @Version 1.0
*/
public class PhoneSearchMethon {
Connection connection = null;
public void search(int num) throws SQLException, ClassNotFoundException {
connection = DbUtil.getConnection();
PhoneBook phoneBook = new PhoneBook();
List<PhoneBook> list = new ArrayList<>();
String sql = "select * from phonebook where name =?;";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
for (int i = 0; i < num; i++) {
preparedStatement.setString(1,"同学" + String.valueOf(i));
ResultSet set = preparedStatement.executeQuery();
while (set.next()) {
phoneBook.setName(set.getString("name"));
phoneBook.setPhone(set.getString("phone"));
phoneBook.setAddress(set.getString("address"));
}
if (phoneBook != null) {
list.add(phoneBook);
}
}
list.forEach((item) ->{
System.out.println("姓名:"+item.getName()+",电话:"+item.getPhone() +",地址:"+item.getAddress());
});
}
public static void main(String[] args) throws SQLException, ClassNotFoundException {
PhoneSearchMethon p = new PhoneSearchMethon();
p.search(50);
}
}
|
Markdown
|
UTF-8
| 7,663
| 2.8125
| 3
|
[] |
no_license
|
# Mirage Demo
This demo shows how [Mirage](https://github.com/SpectoLabs/mirage) can "record" responses from a third-party service, and then mimic the third-party service by "playing back" the recorded responses.
Please refer to the [Mirage documentation](https://github.com/SpectoLabs/mirage/wiki) for more information. The [introduction](https://github.com/SpectoLabs/mirage/wiki/Introduction) is a good place to start.
## Demo Structure
This demo is comprised of 3 main parts (4 if you count the dependency, in this case api.twitter.com):
- The Mirage server, on [http://localhost:8001](http://localhost:8001)
- The Twitter App, on [http://localhost:8080](http://localhost:8080)
- The Twitter Proxy, on [http://localhost:8300/admin](http://localhost:8300/admin)

It's actually more complicated if you count in Redis, Mongo etc. let us not forget it's all wrapped inside docker too. But for now these are the parts we shall be working with.
## Installation
> These instructions are for OSX and Linux only at the moment as Docker Compose is not yet available for Windows. There is an [open issue](https://github.com/SpectoLabs/mirage_demo/issues/3) to add a Vagrantfile which will allow Windows users to run the demo applications.
You need Docker, Docker Compose and a Twitter API key pair. OSX users can download the [Docker Toolbox](https://www.docker.com/toolbox).
Set environment variables:
```bash
export TwitterKey=<twitter key>
export TwitterSecret=<twitter secret>
```
Clone the repository:
```bash
git clone https://github.com/SpectoLabs/mirage_demo.git && cd mirage_demo
```
Get the applications:
```bash
git submodule update --init
```
Launch:
```bash
./up.sh
```
Mirage application: http://{docker-host-ip}:8001
Twitter Search (demo application): http://{docker-host-ip}:8080
Proxy application: http://{docker-host-ip}:8300/admin
To update the applications from their upstream repositories:
```bash
git submodule update --init --remote
```
## Usage
> **Note:** After running the up.sh script, you will see the logging output of each application in your terminal window. This will allow you to see what's going on behind the scenes. For a more user-friendly output, you can use [Kitematic](https://kitematic.com/) from Docker which allows you to see the logging output from each individual application in its own window.
In this demo, we will test a simple application called "Twitter Search". This application allows you to submit a search term to the Twitter search API and view the results in JSON format.
You can find more information on the [Mirage testing workflow in the Mirage docs](https://github.com/SpectoLabs/mirage/wiki/Testing-Workflow).
The Twitter Search application has a drop-down (**External API URI**) which allows you to choose whether API calls are routed straight to Twitter or via Mirage.
There is an input field where you can set the name of the Mirage [scenario and session](https://github.com/SpectoLabs/mirage/wiki/Glossary).
Normally these two options would be set in a configuration file, but we've put them in the application UI for the purposes of this demo.

With the External API URI drop-down set to **Twitter**, you can submit a search query and view the response.

The Twitter Search application is calling the real Twitter search API which returns a real-time response.
Next you need to configure Mirage to record the Twitter search API responses.
In the Mirage management UI, navigate to **Management > Scenarios** and click the **Add a new scenario** button.
Enter "mirage_app:demo" under **Scenario name** and "test" under **Session name**.
You can find more information on [sessions and scenarios in the Mirage docs](https://github.com/SpectoLabs/mirage/wiki/Glossary).
Check the **Start session in record mode...** box so that when you click the "Submit" button, Mirage is ready to record.


Mirage uses proxies to handle the routing of requests and responses. You can find out more about this in the Mirage docs.
In this demo a simple proxy sits between the Twitter Search application and Mirage.
The proxy can be set to either record or playback. By default, it is in record mode. You can see that in record mode the proxy gets responses from the real Twitter API at https://api.twitter.com.

Return to Twitter Search application and select **Mirage Proxy** in the **External API URI** drop-down. Enter "demo:test" in the **scenario:session** field and submit a search term. The response is still coming from the real Twitter search API, but it is being routed through the proxy.

If you go back to the Mirage management UI and navigate to the **Tracker Collection** page, you can see that the Twitter search API response has been recorded.

Now you have recorded a response, you need to switch Mirage into playback mode. In the Mirage application, navigate to **Management > Scenarios** and click the **Stop** button next to the scenario. The recording session stops, and you can click the "play" button to start playback.

You also need to switch the proxy into playback mode. Go to the Proxy application and click the **Recording** button to switch the proxy into playback mode. You can see that the Proxy is now getting responses from the Mirage Application at http://mirage_app:8001.

Return to the Twitter Search application and submit the search term again. The Twitter Search application is calling Mirage, which is returning the recorded response.

Go back to the Mirage application and navigate to the Tracker Collection page. You can see that Mirage is now mimicking the Twitter search API.

If you click the "Details" button next to one of the responses, you can see more information about the request that Mirage received and the response that it returned.

During the recording session, you only entered one search term, so Mirage only recorded one response. If you return to the Twitter Search application and submit a different search term, you can see that Mirage cannot find the correct response for the request.

However, Mirage can use partial matching - meaning that one request can have multiple possible responses. More on this later.
|
C++
|
UTF-8
| 731
| 2.75
| 3
|
[] |
no_license
|
#include "mbed.h"
#define BAUDRATE 115200
#define PC_BUFFER_SIZE 256
Serial pc( USBTX, USBRX, BAUDRATE );
char pc_buff[PC_BUFFER_SIZE];
volatile bool pc_msg = false; // valid message recieved from PC
// ISR to read Serial message from the PC bus
void echo(void)
{
// echo whatever you get
int i = 0;
char p;
do
{
p = pc.getc();
pc_buff[i++] = p;
}
while ( p != '\n' && i < PC_BUFFER_SIZE );
pc_msg = true;
}
int main()
{
pc.attach( &echo ); // setup RX interrupt handler
while (1)
{
if (msg)
{
pc.printf("%s\r\n", pc_buff);
msg = false;
memset(pc_buff, 0, sizeof(pc_buffer)); // clear the buffer
}
}
}
|
Java
|
UTF-8
| 3,755
| 2.578125
| 3
|
[
"MIT"
] |
permissive
|
/*
* Copyright (c) 2021 Dinusha Jayawardena. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*/
package service;
import model.Batch;
import model.Course;
import service.exception.NotFoundException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class BatchService {
private static final List<Course> courseDB = new ArrayList<>();
static {
}
private final Set<String> coursesList = new HashSet<>();
public BatchService() {
}
public void initialize() {
}
public void saveCourse(Course course) {
}
private boolean exitsCourse(String courseID) {
for (Course course : courseDB) {
if (course.getCourseID().equals(courseID)) {
return true;
}
}
return false;
}
private void findDuplicatedRecord(Course course) {
System.out.println(course.getCourseID() + " , " + course.getSelectedBatch().getId());
for (Course course1 : courseDB) {
}
}
public void updateCourse(Course course) throws NotFoundException {
Course c = findCourse(course.getCourseID());
courseDB.set(courseDB.indexOf(c), course);
}
public void deleteCourse(String courseId) throws NotFoundException {
Course course = findCourse(courseId);
courseDB.remove(course);
}
public List<Course> findAllCourses() {
return courseDB;
}
public Course findCourse(String courseId) throws NotFoundException {
for (Course course : courseDB) {
if (course.getCourseID().equals(courseId)) {
return course;
}
}
throw new NotFoundException();
}
public Boolean isCourseExists(String inputCourseID, String inputBatchId) {
for (Course course : courseDB) {
//String[] rawCourseId = course.getCourseID().split("-");
if (course.getCourseID().equals(inputCourseID.trim()) && course.getSelectedBatch().getId().equals(inputBatchId.trim())) {
return true;
}
}
return false;
}
public List<Course> findCourses(String query) {
List<Course> result = new ArrayList<>();
for (Course course : courseDB) {
if (course.getCourseName().contains(query) ||
course.getCourseID().contains(query)) {
for (Course course1 : result) {
}
result.add(course);
}
}
return result;
}
public Set<Course> findDuplicates(List<Course> listContainingDuplicates) {
final Set<Course> duplicateCourseIds = new HashSet<>();
final Set<Course> notDuplicates = new HashSet<>();
final Set<Course> set1 = new HashSet<>();
for (Course courseList : listContainingDuplicates) {
if (!set1.add(courseList)) {
duplicateCourseIds.add(courseList);
} else {
notDuplicates.add(courseList);
}
}
// System.out.println(notDuplicates);
return notDuplicates;
}
public Set<String> getAllCourses() {
Set<String> courseSet = new HashSet<String>();
for (Course course : courseDB) {
courseSet.add(course.getCourseID());
}
//System.out.println(courseSet);
return courseSet;
}
public String getCourseNameUsingId(String id) {
for (Course course : courseDB) {
if (course.getCourseID().equals(id)) {
return course.getCourseName();
}
}
return null;
}
}
|
Python
|
UTF-8
| 15,996
| 4.1875
| 4
|
[] |
no_license
|
"""
Implements a binary search tree in python
"""
class BinaryNode(object):
def __init__(self, left=None, right=None, value=None, parent=None):
self.left = left
self.right = right
self.value = value
self.parent = parent
def __eq__(self, other):
return self.value == other.value
def __ne__(self, other):
return self.value != other.value
def has_sibling(self):
"""
Returns true if the node has a sibling
:return:
"""
return self.get_sibling() is not None
def get_sibling(self):
"""
Returns the sibling of the node if it has a sibling
:return:
"""
if self.parent.left == self:
return self.parent.right
elif self.parent.right == self:
return self.parent.left
else:
return None
def is_leaf(self):
"""
Returns true if no children
:return:
"""
return self.left is None and self.right is None
class BinarySearchTree(object):
def __init__(self):
"""
Init will instantiate an empty tree without even a root node
"""
self.root = None
self.num_nodes = 0
self.height = 0
def add_root(self, root):
"""
Adds a root to the tree
:param root:
:return:
"""
if self.root is not None:
raise AttributeError("Tree already has a root!")
self.root = root
self.num_nodes += 1
def insert(self, item):
"""
Inserts a value into the correct place in the tree
:param item:
:return:
"""
if self.root is None:
self.add_root(BinaryNode(value=item))
return
def __insert(new_node, node):
"""
A recursive helper for insertion
:param item:
:param node:
:return:
"""
# Base case, item already exists (here our tree just stores distinct items)
if node == new_node:
raise ValueError("Cannot insert a duplicate item into the tree")
# Base case, perform the insertion here!
elif node.is_leaf() or (node.left is None or node.right is None):
new_node.parent = node
if item < node.value and node.left is None:
node.left = new_node
elif item > node.value and node.right is None:
node.right = new_node
else:
raise Exception("Attempted to insert value at a non-leaf node.")
# Need to recurse
else:
if item < node.value:
__insert(new_node, node.left)
elif item > node.value:
__insert(new_node, node.right)
else:
raise Exception("We should never get to this part!")
node = self.root
new_node = BinaryNode(value=item)
__insert(new_node, node)
# Update our tree metrics
self.num_nodes += 1
self.height = self.get_height(self.root)
def search(self, item, start_node=None, mode="val"):
"""
Search to see if the item is within the tree
:param item:
:return:
"""
node = self.root if start_node is None else start_node
# Easiest base case - we found it
if node.value == item:
if mode == "val":
return node.value
else:
return node
# Other base case - we exhausted the search
elif node.is_leaf() or node is None:
return None
# Now the recursive case
else:
if item < node.value:
return self.search(item, node.left, mode=mode)
elif item > node.value:
return self.search(item, node.right, mode=mode)
return self.search(item, node, mode)
def get_num_nodes(self):
return self.num_nodes
def compute_num_nodes(self):
"""
Count the number of nodes in the tree
:return:
"""
counter = 0
for _ in self:
counter += 1
return counter
def __str__(self):
"""
Prints values from min to max
:return:
"""
out = ""
def get_gridsize(height, x_pad=4, y_pad=1):
"""
Helper function which returns width, height of the print grid
:param x_space:
:param y_space:
:param height:
:return:
"""
w = (2 ** self.height) * (x_pad + 1)
h = (height + 1) * (y_pad + 1)
return w, h
def get_print_xy(level, node_idx, w, h, y_pad=1):
"""
Helper function which returns the co-ordinate to print given a level and the node on that level
:param level:
:param node:
:return:
"""
x = w // ((2 ** level) + 1) * (1 + node_idx)
y = lvl * (y_pad + 1)
return int(x), int(y)
# Size up our grid
w, h = get_gridsize(self.height)
# Figure out where we need to plot numbers
queue = [self.root]
lvl = 0
plt = []
while len(queue) > 0:
new_queue = []
for idx, node in enumerate(queue):
if node is not None:
x, y = get_print_xy(lvl, idx, w, h)
plt.append(((x, y), node.value))
new_queue.extend([node.left, node.right])
lvl += 1
queue = new_queue
# Now print out the tree
to_plot = plt.pop(0)
for j in range(h):
for i in range(w):
if to_plot[0][0] == i and to_plot[0][1] == j:
out += str(to_plot[1])
if len(plt) > 0:
to_plot = plt.pop(0)
else:
out += " "
out += "\n"
return out
def __iter__(self):
"""
Returns an inorder iteration through the tree
:return:
"""
def inorder(node):
"""
Recursive helper function for inorder traversal
:param node:
:return:
"""
if node.left is not None:
yield from inorder(node.left)
yield node.value
if node.right is not None:
yield from inorder(node.right)
return inorder(self.root) if self.root is not None else iter([])
def delete_tree(self):
"""
De-allocates all the nodes and sets the root to None
:return:
"""
def __dealloc(node):
"""
Deallocates a node
:param node:
:return:
"""
if node is None:
return
__dealloc(node.left)
__dealloc(node.right)
del node
__dealloc(self.root)
# Finally reset everything
self.root = None
self.num_nodes = 0
self.height = 0
def delete_node(self, item, start_node=None):
"""
Deletes the node corresponding to the value
:param item:
:return:
"""
sn = self.root if start_node is None else start_node
node = self.search(item, start_node=sn, mode="node")
if node is None:
raise Exception("Trying to delete a value that does not exist within the tree.")
# Now we have 3 possibilities for deletion
# 1. Node is a leaf, which means we can just delete it
# 2. Node has one child, in which case we replace the node's value with the child value and delete the child
# 3. Node has two children, in which case we replace the node's value with the inorder successor
# and delete the inorder successor node
if node.is_leaf():
if node.parent.left == node:
node.parent.left = None
elif node.parent.right == node:
node.parent.right = None
self.num_nodes -= 1
self.height = self.get_height(self.root)
# Node has 1 child with left child being empty
elif node.left is None:
node.value = node.right.value
node.right = None
self.num_nodes -= 1
self.height = self.get_height(self.root)
# Node has 1 child with right child being empty
elif node.right is None:
node.value = node.left.value
node.left = None
self.num_nodes -= 1
self.height = self.get_height(self.root)
# Node is a full node
# Inorder successor is the min value of the right tree
else:
succ_node = self.get_min(node=node.right, mode="node")
node.value = succ_node.value
self.delete_node(succ_node.value, start_node=succ_node)
def get_min(self, node=None, mode="val"):
"""
Return minimum value, traverse down the left child until we hit the dead end
:return:
"""
cur_node = self.root if node is None else node
while (cur_node.left is not None):
cur_node = cur_node.left
if mode == "val":
return cur_node.value
elif mode == "node":
return cur_node
else:
raise ValueError("Mode must be one of { val | node }")
def get_max(self, node=None, mode="val"):
"""
Return maximum value, traverse down the right child until we hit the dead end
:return:
"""
cur_node = self.root if node is None else node
while (cur_node.right is not None):
cur_node = cur_node.right
if mode == "val":
return cur_node.value
elif mode == "node":
return cur_node
else:
raise ValueError("Mode must be one of { val | node }")
def verify_bst(self):
"""
Check if our binary tree is a valid binary search tree
i.e.
1. left subtree is < node & is valid bst
2. right subtree is > node & is valid bst
:return:
"""
def verify_bst_helper(node):
"""
Recursive helper for verifying the bst
:param node:
:return:
"""
if node.is_leaf():
return True
elif node.right is None:
return node.left.value < node.value and verify_bst_helper(node.left)
elif node.left is None:
return node.right.value > node.value and verify_bst_helper(node.right)
else:
return node.left.value < node.value and verify_bst_helper(node.left) \
and node.right.value > node.value and verify_bst_helper(node.right)
return verify_bst_helper(self.root) if self.root is not None else False
def get_before(self, item, mode="val"):
"""
Returns next highest value in tree before given value, None if None
:return:
"""
# The next highest value should be the max of the left branch of the node
node = self.search(item, start_node=self.root, mode="node")
if node is None or node.left is None:
return None
return self.get_max(node=node.left, mode=mode)
def get_after(self, item, mode="val"):
"""
Returns next lowest value in tree after given value. None if None
:param item:
:return:
"""
# The next lowest value in the tree is the min of the right branch
node = self.search(item, start_node=self.root, mode="node")
if node is None or node.right is None:
return None
return self.get_min(node=node.right, mode=mode)
def iter_preorder(self):
"""
Returns a preorder iteration through the tree
:return:
"""
def preorder(node):
"""
Recursive helper for pre-order
:param node:
:return:
"""
yield node.value
for child in (node.left, node.right):
if child is not None:
yield from preorder(child)
return preorder(self.root) if self.root is not None else iter([])
def iter_postorder(self):
"""
Returns a postorder iteration through the tree
:return:
"""
def postorder(node):
"""
Recursive helper for post-order
:param node:
:return:
"""
for child in (node.left, node.right):
if child is not None:
yield from postorder(child)
yield node.value
return postorder(self.root) if self.root is not None else iter([])
def iter_bfs(self):
"""
Return the breadth first traversal of the tree
:return:
"""
if self.root is None:
return iter([])
queue = [self.root] # This is not an efficient queue structure but it'll do
while len(queue) > 0:
node = queue.pop(0)
if node is not None:
yield node.value
queue.extend((node.left, node.right))
def get_height(self, node=None):
"""
Returns the height of tree if node = None, else return the height of the tree from that Node
:param node:
:return:
"""
def __get_height(node):
if node is None or node.is_leaf():
return 0
else:
return 1 + max(__get_height(node.left), __get_height(node.right))
if node is None:
return self.height
else:
return __get_height(node)
def balance(self):
"""
Balances the tree
:return:
"""
# To balance the tree we first perform an inorder traversal which should leave us with a sorted array
arr = list(self.__iter__())
self.delete_tree()
self.from_array(arr)
def from_array(self, arr):
"""
Build a balanced binary search tree from an array
:param arr:
:return:
"""
def __from_array(arr, parent, child):
"""
Recursive helper
:param arr:
:param parent:
:return:
"""
# Check the length of the array to see if we need to do anything as the base case
if len(arr) < 1:
return
else:
m = len(arr) // 2
v = arr[m]
# Assign the correct reference at the parent node
new_node = BinaryNode(value=v, parent=parent)
if child == 'left':
parent.left = new_node
elif child == 'right':
parent.right = new_node
# Now recurse
__from_array(arr[:m], new_node, 'left')
__from_array(arr[m + 1:], new_node, 'right')
if self.root is not None:
raise ValueError("Cannot build a tree as one already exists")
if len(arr) < 1:
raise ValueError("Must take an array of at least 1 element")
# Sort the array
s_arr = sorted(arr)
# Extract the middle value of the array
m = len(s_arr) // 2
v = s_arr[m]
self.root = BinaryNode(value=v)
# Now recurse
__from_array(s_arr[:m], self.root, 'left')
__from_array(s_arr[m + 1:], self.root, 'right')
# Now set the other parameters
self.num_nodes = len(arr)
self.height = self.get_height(self.root)
|
Python
|
UTF-8
| 1,031
| 2.71875
| 3
|
[] |
no_license
|
#!/usr/bin/env python
# coding: utf-8
# In[ ]:
import numpy as np
import pdb
def Time_of_flight(xpmin,xpmax,ZPmin,ZPmax,N,pitch,c2):
resolution=0.0001 # 0.0002 m, grid resolution
sarray=(N-1)*pitch #size of array
Gx,Gz,Xt=np.mgrid[xpmin:xpmax+resolution:resolution,ZPmin:ZPmax+resolution:resolution,-sarray/2:sarray/2+pitch:pitch]
Zt=np.zeros((Xt.shape))
sgx=Gx.shape[0]
sgz=Gx.shape[1]
#transducer --> focal point
# Di1=np.sqrt((Xt-xat)**2+(Zt-za)**2)
# Di2=np.sqrt((Gx-xat)**2+(Gz-za)**2)
Di1 = np.sqrt((Gx - Xt) ** 2 + (Gz - Zt) ** 2)
# focal point --> transducer
Dv1 = Di1
# Dv2=Di2
# time of flight calculation
# tempi=Di1/c1+Di2/c2
# tempv=Dv1/c1+Dv2/c2
tempi = Di1 / c2
tempv = tempi
tempia=np.tile(tempi,(1,1,N))
tempia2=np.reshape(tempia,(sgx,sgz,N,N))
tempva=np.tile(tempv,(1,1,N))
tempva2=np.reshape(tempva,(sgx,sgz,N,N))
tempva3=tempva2.swapaxes(3,2)
temp=tempia2+tempva3
return(temp)
|
Java
|
UTF-8
| 3,795
| 2.484375
| 2
|
[] |
no_license
|
package net.huawei.wisdomstudy.dao.impl;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate5.HibernateCallback;
import org.springframework.orm.hibernate5.support.HibernateDaoSupport;
import org.springframework.stereotype.Repository;
import net.huawei.wisdomstudy.dao.inter.IKnowledgePointDao;
import net.huawei.wisdomstudy.domain.Chapter;
import net.huawei.wisdomstudy.domain.KnowledgePoint;
@Repository
public class KnowledgePointDaoImpl extends HibernateDaoSupport implements IKnowledgePointDao {
@Resource
public void setSessionFacotry(SessionFactory sessionFacotry) {
super.setSessionFactory(sessionFacotry);
}
/**
* 添加知识点
* @author cexo addedy on 2017-12-9
* @param kpDescribe
* @param chapterId
* @return
*/
@Override
public void addKnowledgePoint(String kpDescribe, int chapterId) {
KnowledgePoint kp = new KnowledgePoint();
kp.setKpDescribe(kpDescribe);
Chapter c = getHibernateTemplate().load(Chapter.class, chapterId);
kp.setChapter(c);
getHibernateTemplate().save(kp);
}
/**
* 到KnowledgePoint表中查找并分页查询知识点 added on 2017-11-14
* @param chapterId 章节OID
* @param firstResult 起始位置
* @param maxResults 获取的数量
* @author cexo
* @return Map<String,Object>
*/
@Override
public Map<String, Object> getKnowledgePointList(int chapterId, int firstResult, int maxResults) {
String hql = "select count(*) from KnowledgePoint k where k.chapter.id = ?";
Long totalInteger = (Long)getHibernateTemplate().find(hql, chapterId).listIterator().next();
int total = totalInteger.intValue();
final int f = firstResult;
final int m = maxResults;
final int c = chapterId;
@SuppressWarnings("unchecked")
List<KnowledgePoint> list = (List<KnowledgePoint>) getHibernateTemplate().execute(
new HibernateCallback<List<KnowledgePoint>>() {
public List<KnowledgePoint> doInHibernate(Session session)throws HibernateException {
List<KnowledgePoint> list2 = session.createQuery("from KnowledgePoint k where k.chapter.id = "+c)
.setFirstResult(f).setMaxResults(m).list();
return list2;
}
});
Map<String, Object> map = new HashMap<String, Object>();
map.put("total", total);
map.put("rows", list);
return map;
}
/**
* 添加知识点
* @author cexo addedy on 2017-12-9
* @param kpDescribe
* @param chapterId
* @param effectTag
* @return
*/
@Override
public void addKnowledgePoint(String kpDescribe, int chapterId, boolean effectTag) {
KnowledgePoint kp = new KnowledgePoint();
kp.setKpDescribe(kpDescribe);
Chapter c = getHibernateTemplate().load(Chapter.class, chapterId);
kp.setChapter(c);
kp.setEffectTag(effectTag);
getHibernateTemplate().save(kp);
}
/**
* 按章节id获取知识点
* @param chapterId 章节OID
* @author cexo addey on 2017-12-9
* @return List<KnowledgePoint>
*/
@Override
public List<KnowledgePoint> getKnowledgePointList(int chapterId) {
String hql = "from KnowledgePoint k where k.chapter.id = ?";
@SuppressWarnings("unchecked")
List<KnowledgePoint> kpList = (List<KnowledgePoint>) getHibernateTemplate().find(hql, chapterId);
return kpList;
}
/**
* 按章节OID查找所含知识点的数量
* @author cexo addey on 2017-12-14
* @param chapterId 章节OID
* @return int 知识点数量
*/
@Override
public int knowledgePointCount(int chapterId) {
String hql = "select count(*) from KnowledgePoint k where k.chapter.id = ?";
Long l = (Long)getHibernateTemplate().find(hql, chapterId).iterator().next();
return l.intValue();
}
}
|
Python
|
UTF-8
| 66
| 2.65625
| 3
|
[] |
no_license
|
import numpy
# identity matrix array
arr=numpy.eye(3)
print(arr)
|
Python
|
UTF-8
| 6,047
| 3.59375
| 4
|
[] |
no_license
|
from pprint import pprint as pp
from random import randint, randrange, random, uniform
# Estructuras por extensión
numeros = [1,5,3,4,8,2,5,7]
edades = {'Juan': 30, 'Camila': 28}
# Estructuras por compresión
# numeros pares del 2 al 100
numerosPares = []
for num in range(2,101):
if num % 2 == 0:
numerosPares.append(num)
#print(numerosPares)
numerosPares = []
for num in range(2,101,2):
numerosPares.append(num)
#print(numerosPares)
# listaComprension = [definicionElementoAgregar for varible in otraLista]
listaCompresion = [num*2 for num in [2,3,4,5,6,7,8,9,10]]
#print(listaCompresion)
# numeros pares del 2 al 100, por comprension
numerosPares = [num for num in range(2,101) if num % 2 == 0]
#print(numerosPares)
# numeros entre 0 y 100, divisibles por 3
divisible3 = []
for num in range(101):
#print(f'{num} % 3 = {num % 3}')
if num % 3 == 0:
divisible3.append(num)
#print(divisible3)
divisible3 = [num for num in range(101) if num % 3 == 0]
#print(divisible3)
# numeros pares entre 0 y 100, divisibles por 3
paresDivisibles3 = [num for num in range(101) if num % 3 == 0 and num in range(0,101,2)]
#print(paresDivisibles3)
# Compresion usando funciones
# Numeros pares
def esPar(num:int)->int:
if num % 2 == 0:
return num
numerosPares = [num for num in range(0,101) if esPar(num) != None]
#print(numerosPares)
# Area de un cuadrado
ladoCuadrados = [2,4,6,8,10,12,14,16]
areaCuadrados = [l*l for l in ladoCuadrados]
#print(areaCuadrados)
# Construir una funcion que retorne una lista con las llaves de un diccionario (no usar keys)
diccionario = {1:'a', 2:'b', 3:'c'}
#print(list(diccionario.keys()))
keys = []
def myKeys(diccionario:dict)->list:
for key in diccionario:
keys.append(key)
return keys
#print(myKeys(diccionario))
keys = [key for key in diccionario]
#print(keys)
# Construir una funcion que retorne una lista con los valores de un diccionario (no usar values)
diccionario = {1:'a', 2:'b', 3:'c'}
#print(list(diccionario.values()))
values = []
def myValues(diccionario:dict)->list:
for key in diccionario:
values.append(diccionario[key])
return values
#print(myValues(diccionario))
values = [diccionario[key] for key in diccionario]
#print(values)
# Encontrar elementos repetidos en una lista
a = ['Andres', 'Julian', 'Edison', 'Edwin', 'Felipe']
b = ['Francisco', 'Juan', 'Andres', 'Julian', 'Felipe']
repetidos = []
def repetido(a:list,b:list)->list:
for x in a:
if x in b:
repetidos.append(x)
return repetidos
#print(repetido(a,b))
repetidos = [x for x in a if x in b]
#print(repetidos)
repetidos = []
def repetido(a:list,b:list)->list:
for x in a:
for y in b:
if x == y:
repetidos.append(x)
return repetidos
#print(repetido(a,b))
repetidos = [x for x in a for y in b if x == y]
#print(repetidos)
# Tablas de multiplicar
# tablasDict = {2: [4,6,8,10,12,14,16,18], 3: []}
tablasDict = {}
def tablas(num:int)->dict:
for n in range(2,num+1):
auxLista = []
for z in range(2,10):
auxLista.append(n*z)
tablasDict[f'Tabla del {n}'] = auxLista
return tablasDict
#print(tablas(10))
tablasDict = {f'Tabla del {n}': [n*z for z in range(2,10)] for n in range(2,11)}
#print(tablasDict)
#pp(tablasDict)
'''
# Generar numeros aleatorios
# Genera un numero entero de forma aleatoria entre los limites dados
for num in range(10):
print(randint(10,100), end=' ')
print()
aleatorioRandint = [randint(10,100) for num in range(10)]
print(aleatorioRandint)
# Genera un numero entero de forma aleatoria entre los limites dados
# Opcionalmente se puede indicar un step
for num in range(10):
print(randrange(10,100,20), end=' ')
print()
aleatorioRandrange = [randrange(10,100,20) for num in range(10)]
print(aleatorioRandrange)
# Genera decimales entre 0 y 1 (no se incluye)
for num in range(10):
print(random(), end=' ')
print()
aleatorioRandom = [random() for num in range(10)]
print(aleatorioRandom)
# Genera un numero decimal de forma aleatoria entre un punto inicial y uno final
for num in range(10):
print(uniform(10,100), end=' ')
aleatorioUniform= [uniform(10,100) for num in range(10)]
print(aleatorioUniform)
'''
# ciudadesDict = {(a,b): 85, (a,c): 71, ...}
listaCiudades = ['a','b','c','d','e','f','g']
# Generar todos los arcos para la lista
arcos = {}
for i in listaCiudades:
auxLista = []
for j in listaCiudades:
if j != i:
auxLista.append((i,j))
arcos[i] = auxLista
#pp(arcos)
arcos = {i: [(i, j) for j in listaCiudades if j != i] for i in listaCiudades}
#pp(arcos)
# Obtener una lista con todos los arcos por ciudades
arcos = list(arcos.values())
#print(arcos)
# Obtener los arcos "unicos"
auxArcos = []
i = 0
def seleccionarArcos(i:int,auxArcos:list)->list:
for fila in arcos:
aux = fila[i:len(fila)]
if aux != []:
auxArcos.append(aux)
i += 1
return auxArcos
arcos = seleccionarArcos(i,auxArcos)
# Cuantas distancias se deben generar?
numDistancias = 0
for lista in arcos:
numDistancias += len(lista)
#print(numDistancias)
# Lista con los arcos
auxArcos = []
for lista in arcos:
for par in lista:
auxArcos.append(par)
#print(len(auxArcos))
auxArcos = [par for lista in arcos for par in lista]
#print(auxArcos)
# {(a,b):40, (b,a):40}
auxArcos2 = [(tupla[1], tupla[0]) for tupla in auxArcos]
#print(auxArcos2)
# Generar las distancias
numDistancias = len(auxArcos)
distancias = []
for km in range(numDistancias):
distancias.append(randrange(60,800,40))
#print(distancias)
# Añadir a los arcos sus distancias
ciudadesDic = {}
for posicion in range(numDistancias):
ciudadesDic[auxArcos[posicion]] = distancias[posicion]
ciudadesDic[auxArcos2[posicion]] = distancias[posicion]
#pp(ciudadesDic)
# Segunda opción
ciudadesDic = {}
for arco in auxArcos:
dis = distancias[auxArcos.index(arco)]
ciudadesDic[arco] = dis
ciudadesDic[arco[::-1]] = dis
pp(ciudadesDic)
|
C++
|
UTF-8
| 4,147
| 2.90625
| 3
|
[] |
no_license
|
#include <iostream>
#include <fstream>
#include <cstdio>
#include <vector>
#include <map>
#include "Ngram.h"
using namespace std;
void input_td(const char *, vector<string> &);
void input_mp(const char *, map< string, vector<string> > &);
double getBigramProb(const char*, const char*, Vocab &, Ngram &);
vector<string> viterbi(string &, map< string, vector<string> > &, Vocab &, Ngram & );
int main(int argc, char * argv[])
{
int ngram_order = 2;
Vocab voc;
Ngram lm( voc, ngram_order );
vector<string> testdata;
map<string, vector<string> > map;
File lmFile( argv[6], "r" );
lm.read( lmFile );
lmFile.close();
input_td( argv[2] , testdata);
input_mp( argv[4] , map);
for(int i=0;i<testdata.size();i++)
{
cout<<"<s> ";
vector<string> answer=viterbi(testdata[i],map,voc,lm);
for(int j=0; j<answer.size();j++)
{
if (j<answer.size()-1)
cout << answer[j] << " ";
else
cout << answer[j] << endl;
}
}
}
void input_td(const char * filename, vector<string> & td) //input testdata
{
fstream fp;
string ip_line;
fp.open(filename, ios::in|ios::binary);
while(getline(fp,ip_line))
{
string line;
for(int i=0;i<ip_line.length();i++)
{
if(ip_line[i]!=' ')
line=line+ip_line[i];
}
td.push_back(line);
}
fp.close();
}
void input_mp(const char * filename, map<string,vector<string> > & mapping) //input mapping
{
fstream fp;
string ip_line;
fp.open(filename, ios::in|ios::binary);
while(getline(fp,ip_line))
{
string charac=ip_line.substr(0,2);
string line;
for(int i=3;i<ip_line.size();i++)
{
if(ip_line[i]!=' ')
line=line+ip_line[i];
}
for(int j=0;j<(line.size()-1);j=j+2)
mapping[charac].push_back(line.substr(j,2));
string end_tag="</s>";
mapping[end_tag].push_back(end_tag);
}
}
// Get P(W2 | W1) -- bigram
double getBigramProb(const char *w1, const char *w2, Vocab & voc, Ngram & lm)
{
VocabIndex wid1 = voc.getIndex(w1);
VocabIndex wid2 = voc.getIndex(w2);
if(wid1 == Vocab_None) //OOV
wid1 = voc.getIndex(Vocab_Unknown);
if(wid2 == Vocab_None) //OOV
wid2 = voc.getIndex(Vocab_Unknown);
VocabIndex context[] = { wid1, Vocab_None };
return lm.wordProb( wid2, context);
}
vector<string> viterbi(string & input, map<string, vector<string> > & mapping, Vocab & voc, Ngram & lm)
{
int size1=input.size()/2+1;
vector<vector<string> > chars(size1);
vector<vector<double> >log_prob(size1);
vector<vector<int> > prev_index(size1);
for(int i=0;i<size1;i++)
{
string charac;
if(i==size1-1)
charac="</s>";
else
charac=input.substr(i*2,2);
int size2=mapping[charac].size();
chars[i].resize(size2);
log_prob[i].resize(size2);
prev_index[i].resize(size2);
vector<string>::iterator iter=mapping[charac].begin();
for(int j=0;j<chars[i].size();j++)
{
chars[i][j]= *iter;
++iter;
}
}
//initialization
for(int i=0;i<chars[0].size();i++)
{
prev_index[0][i] = 0;
log_prob[0][i] = getBigramProb("<s>", chars[0][i].c_str(), voc, lm);
}
//recursion
for(int i=1;i<log_prob.size();i++)
{
for(int j=0;j<log_prob[i].size();j++)
{
log_prob[i][j]=-1e9;
for(int q=0;q<log_prob[i-1].size();q++)
{
double tmp_prob;
tmp_prob=getBigramProb(chars[i-1][q].c_str(), chars[i][j].c_str(), voc, lm);
tmp_prob=tmp_prob+log_prob[i-1][q];
if(log_prob[i][j]<tmp_prob)
{
log_prob[i][j]=tmp_prob;
prev_index[i][j]=q;
}
}
}
}
//backtracking
double max_p=-1e9;
int max_index;
for(int j=0;j<log_prob.back().size();j++)
{
if(max_p<log_prob.back()[j])
{
max_p=log_prob.back()[j];
max_index=j;
}
}
vector<string> out(size1);
for(int i=size1-1;i>=0;i--)
{
out[i]=chars[i][max_index];
max_index=prev_index[i][max_index];
}
return out;
}
|
JavaScript
|
UTF-8
| 3,839
| 2.515625
| 3
|
[] |
no_license
|
var wxApiJs = {
bannerAd : null, // banner 对象
showBannerTime : 0,//banner显示时间
//获取微信
getWx(){
if (cc.sys.platform != cc.sys.WECHAT_GAME) {
return null;
}
return wx;
},
/**
* 发送信息打开微信排行榜
* @param {类型} _type
*/
postMessage:function(_type){
console.log("==pai=hb2")
const openDataContext = wx.getOpenDataContext()
openDataContext.postMessage({
type: _type,
})
},
/**
* 上传分数
* @param {Key} name
* @param {分数} score
*/
updataScore:function(name,score){
wx.setUserCloudStorage({
KVDataList: [{key: name, value: "" + score}],
success: function (res) {
console.log('setUserCloudStorage', 'success', res)
},
fail: function (res) {
// self.submitScore(name,score)
console.log('setUserCloudStorage', 'fail')
},
complete: function (res) {
console.log('setUserCloudStorage', 'ok')
}
});
},
/**
* 吊起微信分享
* @param {显示的内容} _title
* @param {分享的图片} _image
* @param {数据} _queryData
*/
shareAppMessage:function(_title,_image,_queryData){
wx.shareAppMessage({
title: _title,
imageUrl: _image,
query: _queryData,
success(res) {},
fail() {}
})
},
/**
* 小游戏回到前台
* @param {回调函数} callBack
*/
onShow:function(callBack){
wx.onShow((res) => {
console.log('小游戏回到前台');
callBack(res)
})
},
/**
* 小游戏回到后台
* @param {回调函数} callBack
*/
onHide:function(callBack){
wx.onHide((res) => {
console.log('小游戏回到后台');
callBack(res)
});
},
/**
* 创建视频
* @param {视频的id} videoId
*/
createVideo:function(videoId){
let videoAdv = wx.createRewardedVideoAd({adUnitId: videoId});
return videoAdv;
},
/**
* 创建视频
* @param {bannerId} _adUnitId
* @param {*} _left
* @param {*} _top
* @param {*} _width
* @param {*} _height
*/
createBannerAd:function(_adUnitId,_left,_top,_width,_height){
let bannerAd = wx.createBannerAd({
adUnitId: _adUnitId,
style: {
left: _left,
top: _top,
width: _width,
height: _height,
}
})
return bannerAd;
},
/**
* 显示banner
* @param isShow 是否显示
* @param _adUnitId id
*/
wxShowBanner(isShow,_adUnitId){
// if (isShow) {
// if (this.bannerAd && (Date.now() - this.showBannerTime) > GameDataManager.getInstance().kaiGuan.bannerRefreshTime) {//5分钟刷新一下
// console.log("destory banner")
// this.bannerAd.destroy();
// this.bannerAd = null;
// }
// }
if (!this.bannerAd) {
var screenWidth = wx.getSystemInfoSync().screenWidth
this.showBannerTime = Date.now();
let bannerAd = wx.createBannerAd({
adUnitId: _adUnitId,
style: {
left: 0,
top: 0,
width: screenWidth,
height: 200,
}
})
bannerAd.onError(err => {
console.log(err)
})
bannerAd.onResize(res => {
console.log(res.width, res.height)
console.log(bannerAd.style.realWidth, bannerAd.style.realHeight)
var screenHeight = wx.getSystemInfoSync().screenHeight
bannerAd.style.top = screenHeight - bannerAd.style.realHeight
})
this.bannerAd = bannerAd;
console.log("create banner")
}
if (isShow) {
this.bannerAd.show()
} else {
this.bannerAd.hide()
}
},
navigateToMiniProgram:function(_appid, name, _path,_type){
},
}
module.exports = wxApiJs;
|
Markdown
|
UTF-8
| 1,837
| 3.15625
| 3
|
[
"MIT"
] |
permissive
|
# Progress 进度条
### 介绍
用于展示操作的当前进度。
### 引入
在`app.json`或`index.json`中引入组件,详细介绍见[快速上手](#/quickstart#yin-ru-zu-jian)。
```json
"usingComponents": {
"van-progress": "@vant/weapp/progress/index"
}
```
## 代码演示
### 基础用法
进度条默认为蓝色,使用`percentage`属性来设置当前进度。
```html
<van-progress percentage="50" />
```
### 线条粗细
通过`stroke-width`可以设置进度条的粗细。
```html
<van-progress :percentage="50" stroke-width="8" />
```
### 置灰
设置`inactive`属性后进度条将置灰。
```html
<van-progress inactive percentage="50" />
```
### 样式定制
可以使用`pivot-text`属性自定义文字,`color`属性自定义进度条颜色。
```html
<van-progress pivot-text="橙色" color="#f2826a" percentage="25" />
<van-progress pivot-text="红色" color="#ee0a24" percentage="50" />
<van-progress
percentage="75"
pivot-text="紫色"
pivot-color="#7232dd"
color="linear-gradient(to right, #be99ff, #7232dd)"
/>
```
## API
### Props
| 参数 | 说明 | 类型 | 默认值 |
| --- | --- | --- | --- |
| inactive | 是否置灰 | _boolean_ | `false` |
| percentage | 进度百分比 | _number_ | `0` |
| stroke-width | 进度条粗细,默认单位为`px` | _string \| number_ | `4px` |
| show-pivot | 是否显示进度文字 | _boolean_ | `true` |
| color | 进度条颜色 | _string_ | `#1989fa` |
| text-color | 进度文字颜色 | _string_ | `#fff` |
| track-color | 轨道颜色 | _string_ | `#e5e5e5` |
| pivot-text | 文字显示 | _string_ | 百分比文字 |
| pivot-color | 文字背景色 | _string_ | 与进度条颜色一致 |
### 外部样式类
| 类名 | 说明 |
| ------------ | ------------ |
| custom-class | 根节点样式类 |
|
Python
|
UTF-8
| 496
| 3.796875
| 4
|
[] |
no_license
|
import math
a=input("enter length")
b=input("enter base")
c=input("enter hypotenuse")
a=float(a)
b=float(b)
c=float(c)
if a==0 or b==0 or c==0:
print("invalid input")
elif a+b>c and b+c>a and a+c>b:
perimeter=a+b+c
s=perimeter/2
area=math.sqrt(s*(s-a)*(s-b)*(s-c))
# print("the area and perimeter of your triangle is {} and {}".format(area,perimeter))
print("the area and perimeter of your triangle is %f and %f" %(area,perimeter))
else:
print("invalid triangle")
|
Markdown
|
UTF-8
| 2,565
| 2.609375
| 3
|
[] |
no_license
|
<h1 align="center">Hi 👋, I'm Manon</h1>
<h3 align="center">A junior web developer from France</h3>
- 🔭 I’m currently working on **finding a job!**
- 🌱 I’m currently learning **React**
- 📫 How to reach me **manon.garnier.lehy@gmail.com**
<h3 align="left">Connect with me:</h3>
<p align="left">
<a href="https://linkedin.com/in/manongarnier1" target="blank"><img align="center" src="https://cdn.jsdelivr.net/npm/simple-icons@3.0.1/icons/linkedin.svg" alt="manongarnier1" height="30" width="40" /></a>
</p>
<h3 align="left">Languages and Tools:</h3>
<p align="left"> <a href="https://getbootstrap.com" target="_blank"> <img src="https://raw.githubusercontent.com/devicons/devicon/master/icons/bootstrap/bootstrap-plain-wordmark.svg" alt="bootstrap" width="40" height="40"/> </a> <a href="https://www.w3schools.com/css/" target="_blank"> <img src="https://raw.githubusercontent.com/devicons/devicon/master/icons/css3/css3-original-wordmark.svg" alt="css3" width="40" height="40"/> </a> <a href="https://git-scm.com/" target="_blank"> <img src="https://www.vectorlogo.zone/logos/git-scm/git-scm-icon.svg" alt="git" width="40" height="40"/> </a> <a href="https://heroku.com" target="_blank"> <img src="https://www.vectorlogo.zone/logos/heroku/heroku-icon.svg" alt="heroku" width="40" height="40"/> </a> <a href="https://www.w3.org/html/" target="_blank"> <img src="https://raw.githubusercontent.com/devicons/devicon/master/icons/html5/html5-original-wordmark.svg" alt="html5" width="40" height="40"/> </a> <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript" target="_blank"> <img src="https://raw.githubusercontent.com/devicons/devicon/master/icons/javascript/javascript-original.svg" alt="javascript" width="40" height="40"/> </a> <a href="https://www.mysql.com/" target="_blank"> <img src="https://raw.githubusercontent.com/devicons/devicon/master/icons/mysql/mysql-original-wordmark.svg" alt="mysql" width="40" height="40"/> </a> <a href="https://www.postgresql.org" target="_blank"> <img src="https://raw.githubusercontent.com/devicons/devicon/master/icons/postgresql/postgresql-original-wordmark.svg" alt="postgresql" width="40" height="40"/> </a> <a href="https://rubyonrails.org" target="_blank"> <img src="https://raw.githubusercontent.com/devicons/devicon/master/icons/rails/rails-original-wordmark.svg" alt="rails" width="40" height="40"/> </a> <a href="https://www.ruby-lang.org/en/" target="_blank"> <img src="https://raw.githubusercontent.com/devicons/devicon/master/icons/ruby/ruby-original.svg" alt="ruby" width="40" height="40"/> </a> </p>
|
Markdown
|
UTF-8
| 4,612
| 2.640625
| 3
|
[
"MIT"
] |
permissive
|
#include <QTRSensors.h> // QTR Sensörü tanımlandı.
#define CW 0 // Motorların hangi durumda ne tarafa hareket
#define CCW 1 // edeceği belirlendi.
#define MOTOR_A 0
#define MOTOR_B 1
const byte PWMA = 3; // 1. motor hız pini
const byte PWMB = 11; // 2. motor hız pini
const byte DIRA = 12; // 1. motor yön pini
const byte DIRB = 13; // 2. motor yön pini
#define Kp 0.0009 // Oransal Kazanç 0.0009 --> süper
#define Ki 0 // İntegral Kazancı
#define Kd 0 // Türev Kazancı
#define M1_minumum_hiz 55 // M1 Motorunun minimum hızı belirlendi.
#define M2_minumum_hiz 55 // M2 Motorunun minimum hızı belirlendi.
#define M1_maksimum_hiz 65 // M1 Motorunun maksimum hızı belirlendi.
#define M2_maksimum_hiz 65 // M2 Motorunun maksimum hızı belirlendi.
#define NUM_SENSORS 6 // 6 Sensör kullanılacak.
#define NUM_SAMPLES_PER_SENSOR 4 // Ölçümler içinden 4 değer alındı.
#define EMITTER_PIN QTR_NO_EMITTER_PIN // Emiter pin kullanılmadı.
// Pinler sırası ile A0 A1 A2 A3 A4 A5 pinlerine bağlı olduğu tanımlandı.
QTRSensorsAnalog qtra((unsigned char[]) {0, 1, 2, 3, 4, 5},
NUM_SENSORS, NUM_SAMPLES_PER_SENSOR, EMITTER_PIN);
unsigned int sensorValues[NUM_SENSORS];
unsigned int error = 0; // Hata değerini tutan değişken.
unsigned int lastError = 0; // İlk hatadan sonra ölçülen hata.
int motorSpeed = 0; // Hataya göre motor hızının ayarlanmasında kullanılır.
int leftMotorSpeed = 0; // Sol motor hızı.
int rightMotorSpeed = 0; // Sağ motor hızı.
unsigned int integral=0;
void setup()
{
setupArdumoto(); // Ardumoto (Motor sürücü) ayarları.
QTR8A_kalibrasyon (); //Sensör kalibrasyonu yapılıyor.
}
void loop()
{
unsigned int sensors[6];
int position = qtra.readLine(sensors); // Konum bilgisi pozisyon değerine gönderildi.
error = 2500 - position ; // Hataya göre aracın çizginin sağında mı yoksa solunda mı olduğu belirlendi.
integral = integral + error;
motorSpeed = Kp*error + Kd*(error - lastError) + Ki*integral;
lastError = error;
leftMotorSpeed = M1_minumum_hiz + motorSpeed; // Hataya göre sol motor hızı ayarlandı.
rightMotorSpeed = M2_minumum_hiz - motorSpeed; // Hataya göre sağ motor hızı ayarlandı.
set_motors(leftMotorSpeed, rightMotorSpeed); //Motor hızları.
}
void set_motors(int motor1speed, int motor2speed)
{
if (motor1speed > M1_maksimum_hiz ) motor1speed = M1_maksimum_hiz; //MAKSİMUM MOTOR 1 HIZ LİMİTİ
if (motor2speed > M2_maksimum_hiz ) motor2speed = M2_maksimum_hiz; // MAKSİMUM MOTOR 2 HIZ LİMİTİ
if (motor1speed < 0) motor1speed = 0; // MİNIMUM MOTOR 1 HIZ LİMİTİ
if (motor2speed < 0) motor2speed = 0; // MİNİMUM MOTOR 2 HIZ LİMİTİ
driveArdumoto(MOTOR_A, CW, motor1speed ); //1.MOTOR HIZI
driveArdumoto(MOTOR_B, CW, motor2speed ); // 2.MOTOR HIZI
}
void driveArdumoto(byte motor, byte yon, byte hiz)
{
if (motor == MOTOR_A)
{
digitalWrite(DIRA, yon); // Motor 1 yön
analogWrite(PWMA, hiz); // Motor 1 hız
}
else if (motor == MOTOR_B)
{
digitalWrite(DIRB, yon); // Motor 2 yön
analogWrite(PWMB, hiz); // Motor 2 hız
}
}
void stopArdumoto(byte motor) // Motorları durdurur.
{
driveArdumoto(motor, 0, 0);
}
void setupArdumoto()
{
pinMode(PWMA, OUTPUT); // pin giriş çıkışları belirlendi.
pinMode(PWMB, OUTPUT);
pinMode(DIRA, OUTPUT);
pinMode(DIRB, OUTPUT);
digitalWrite(PWMA, LOW); // Başlangıçta motor hızları sıfırlandı.
digitalWrite(PWMB, LOW);
digitalWrite(DIRA, LOW);
digitalWrite(DIRB, LOW);
}
void QTR8A_kalibrasyon () //QTR-8A sensörünün kalibrasyon ayarları.
{
delay(500);
pinMode(13, OUTPUT);
digitalWrite(13, HIGH); // Kalibrasyon modunda olduğumuzu göstermek için Arduino'nun LED'ini açtık.
for (int i = 0; i < 400; i++) // Kalibrasyon yaklaşık 10 saniye sürüyor.
{
qtra.calibrate(); // Kişi başına kalibrasyon, ortalama 2.5 msn'dir.
}
digitalWrite(13, LOW); // Kalibrasyona devam ettiğimizi göstermek için led söndürüldü.
Serial.begin(9600);
for (int i = 0; i < NUM_SENSORS; i++)
{
Serial.print(qtra.calibratedMinimumOn[i]); // Ölçülen minimum değerler yazdırıldı.
Serial.print(' ');
}
Serial.println();
for (int i = 0; i < NUM_SENSORS; i++)
{
Serial.print(qtra.calibratedMaximumOn[i]); // Ölçülen maksimum değerler yazdırıldı.
Serial.print(' ');
}
Serial.println();
Serial.println();
delay(1000);
}
|
Python
|
UTF-8
| 3,666
| 2.640625
| 3
|
[] |
no_license
|
from google.cloud import documentai_v1beta2 as documentai
def parse_table(project_id='document-ai-project-291706',
input_uri='gs://analysis_report_samples/sample_ocr_1.pdf'):
client = documentai.DocumentUnderstandingServiceClient()
gcs_source = documentai.types.GcsSource(uri=input_uri)
# mime_type can be application/pdf, image/tiff,
# and image/gif, or application/json
input_config = documentai.types.InputConfig(
gcs_source=gcs_source, mime_type='application/pdf')
# Improve table parsing results by providing bounding boxes
# specifying where the box appears in the document (optional)
table_bound_hints = [
documentai.types.TableBoundHint(
page_number=1,
bounding_box=documentai.types.BoundingPoly(
# Define a polygon around tables to detect
# Each vertice coordinate must be a number between 0 and 1
normalized_vertices=[
# Top left
documentai.types.geometry.NormalizedVertex(
x=0,
y=0
),
# Top right
documentai.types.geometry.NormalizedVertex(
x=1,
y=0
),
# Bottom right
documentai.types.geometry.NormalizedVertex(
x=1,
y=1
),
# Bottom left
documentai.types.geometry.NormalizedVertex(
x=0,
y=1
)
]
)
)
]
# Setting enabled=True enables form extraction
table_extraction_params = documentai.types.TableExtractionParams(
enabled=True, table_bound_hints=table_bound_hints)
# Location can be 'us' or 'eu'
parent = 'projects/{}/locations/us'.format(project_id)
request = documentai.types.ProcessDocumentRequest(
parent=parent,
input_config=input_config,
table_extraction_params=table_extraction_params)
document = client.process_document(request=request)
def _get_text(el):
"""Convert text offset indexes into text snippets.
"""
response = ''
# If a text segment spans several lines, it will
# be stored in different text segments.
for segment in el.text_anchor.text_segments:
start_index = segment.start_index
end_index = segment.end_index
response += document.text[start_index:end_index]
return response
file_= open('output_table_sample_1.text','w')
for page in document.pages:
print('Page number: {}'.format(page.page_number))
file_.write('Page number: {}'.format(page.page_number))
for table_num, table in enumerate(page.tables):
print('Table {}: '.format(table_num))
file_.write('Table {}: '.format(table_num))
for row_num, row in enumerate(table.header_rows):
cells = '\t'.join(
[_get_text(cell.layout) for cell in row.cells])
print('Header Row {}: {}'.format(row_num, cells))
file_.write('Header Row {}: {}'.format(row_num, cells))
for row_num, row in enumerate(table.body_rows):
cells = '\t'.join(
[_get_text(cell.layout) for cell in row.cells])
print('Row {}: {}'.format(row_num, cells))
file_.write('Row {}: {}'.format(row_num, cells))
file_.close()
parse_table()
|
JavaScript
|
UTF-8
| 1,349
| 3.5625
| 4
|
[] |
no_license
|
import $ from 'jquery';
function postWords(word){
let cleanedWord = word.replace(/[^a-zA-Z ]/g, "");
console.log(cleanedWord);
let addWordsUrl = "https://wordwatch-api.herokuapp.com/api/v1/words"
let addWordsData = {
word: { value: cleanedWord }
}
$.post(addWordsUrl, addWordsData, function(data, status){
console.log(data);
});
}
$(document).ready(() => {
// have fun!
fetch(`https://wordwatch-api.herokuapp.com/api/v1/top_word`)
.then(response => response.json())
.then(data => {
let topWord = data.word;
let word = Object.keys(topWord);
let count = Object.values(topWord);
let wordCount = document.querySelector('.word-count');
let topWordField = document.querySelector('#word');
topWordField.innerHTML += word;
wordCount.innerHTML = `<p>${count}</p>`;
})
.catch(error => console.error(error))
let breakDown = document.getElementById('break-down');
breakDown.addEventListener('click', function (e) {
let textArea = document.querySelector('textarea');
let noNewLine = textArea.value.replace(/\n/g, " ");
let words = noNewLine.split(" ");
for (var i= 0; i< words.length; i++){
postWords(words[i]);
}
alert("Your string has been added to database!");
//prevent the normal submission of the form
e.preventDefault();
});
})
|
Python
|
UTF-8
| 652
| 2.625
| 3
|
[] |
no_license
|
import csv
from pyspark import SparkContext
from pyspark.sql import SQLContext
sc = SparkContext()
sqlContext = SQLContext(sc)
csvfile = sc.textFile('cleanedData.csv')
data = csvfile.mapPartitions(lambda line: csv.reader(line, delimiter='*'))
header = data.first()
datatail = data.filter(lambda x: x!=header)
schema = sqlContext.createDataFrame(datatail, schema=header)
schema.registerTempTable("ta")
def toCSVLine(line):
return ','.join(str(d) for d in line)
odata = sqlContext.sql("SELECT KY_CD, OFNS_DESC FROM ta GROUP BY KY_CD, OFNS_DESC ORDER BY KY_CD, OFNS_DESC")
lines = odata.map(toCSVLine)
lines.saveAsTextFile('keyCode2desc.csv')
|
C++
|
UTF-8
| 662
| 2.96875
| 3
|
[] |
no_license
|
#include<stdio.h>
void swap(int &a,int &b)
{
int tm = a;
a = b;
b = tm;
}
int main()
{
freopen("in.txt","r",stdin);
freopen("out.txt","w",stdout);
int T;
scanf("%d",&T);
for(int t = 0; t<T; t++)
{
int x,r,c;
scanf("%d%d%d",&x,&r,&c);
if(r>c) swap(r,c);
int win ;
if((r*c)%x !=0) win = 1;
else if(x>(r*c)) win = 1;
else if(r==1&&x>=3) win = 1;
else if(x>c) win = 1;
else if(x==4&&r==2&&c==4) win = 1;
else win = 2;
printf("Case #%d: %s\n",t+1,(win==1)?"RICHARD":"GABRIEL");
}
return 0;
}
|
Java
|
UTF-8
| 174
| 2.953125
| 3
|
[] |
no_license
|
public class Nombre{
private String nombre;
public Nombre(String n){
this.nombre=n;
}
@Override
public String toString(){
return "La persona se llama "+nombre;
}
}
|
C
|
UTF-8
| 140
| 3.21875
| 3
|
[] |
no_license
|
#include <stdio.h>
void soma1(int *x)
{
*x = *x + 1;
}
void main()
{
int x = 0;
soma1(&x);
soma1(&x);
soma1(&x);
printf("%d", x);
}
|
Python
|
UTF-8
| 2,471
| 3.5
| 4
|
[] |
no_license
|
from simpleai.search import SearchProblem, astar, breadth_first
class Connection:
def __init__(self, src, dest, cost):
self.src = src
self.dest = dest
self.cost = cost
class Graph:
def __init__(self):
self.connections = []
def add_connection(self, node1, node2, cost):
self.connections.append(Connection(node1, node2, cost))
self.connections.append(Connection(node2, node1, cost))
def print(self):
for connection in self.connections:
print(connection.src + ' -> ' + connection.dest + ' (' + str(connection.cost) + ')')
# print(connection.node2 + ' -> ' + connection.node1 + ' (' + str(connection.cost) + ')')
g = Graph()
g.add_connection('Kraków', 'Warszawa', 293)
g.add_connection('Kraków', 'Wrocław', 272)
g.add_connection('Warszawa', 'Wrocław', 348)
g.add_connection('Warszawa', 'Gdańsk', 339)
g.add_connection('Gdańsk', 'Szczecin', 370)
g.add_connection('Wrocław', 'Szczecin', 415)
g.print()
class DistanceProblem(SearchProblem):
def __init__(self, init_state, goal, graph):
self.initial_state = init_state
self.goal = goal
self.graph = graph
def actions(self, state):
if self.goal not in state:
possible_cities = [c.dest for c in self.graph.connections if c.src == state.split(',')[-1]]
# print('Possible cities:', possible_cities)
return possible_cities
else:
return []
def result(self, state, action):
return state + ',' + action
def is_goal(self, state):
# print('State:', state)
return self.goal in state
def cost(self, state, action, state2):
src = state.split(',')[-1]
dest = action
cost = [c.cost for c in self.graph.connections if c.src == src and c.dest == dest][0]
return cost
def heuristic(self, state):
#print(state)
# how far are we from the goal?
# wrong = sum([1 if state[i] != self.goal[i] else 0
# for i in range(len(state))])
# missing = len(self.goal) - len(state)
# return wrong + missing
return 1
# Znajdz najkrotsza drogę z Krakowa do Szczecina
initial_state = 'Kraków'
goal = 'Szczecin'
problem = DistanceProblem(initial_state, goal, g)
result = astar(problem, graph_search=True)
print('Final state:', result.state)
print('Path:', result.path())
print('Cost:', result.cost)
|
C++
|
UTF-8
| 947
| 3.375
| 3
|
[] |
no_license
|
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
stack<int> st1; // store l1
stack<int> st2; // store l2
ListNode* prev = NULL;
ListNode* head;
int sum = 0;
// push l1's elements into stack
while(l1) {
st1.push(l1->val);
l1 = l1->next;
}
// push l2's element into stack
while(l2) {
st2.push(l2->val);
l2 = l2->next;
}
// calculate
while(!st1.empty() || !st2.empty() || sum >= 10) {
sum /= 10;
if(!st1.empty()) {
sum += st1.top();
st1.pop();
}
if(!st2.empty()) {
sum += st2.top();
st2.pop();
}
head = new ListNode(sum % 10);
head->next = prev;
prev = head;
}
return head;
}
};
|
JavaScript
|
UTF-8
| 1,192
| 2.8125
| 3
|
[] |
no_license
|
const todo = (state = [], action) => {
switch (action.type) {
case 'ADD_TODO': {
return [
...state,
{
id: action.id,
text: action.text,
completed: false
},
]
}
case 'EDIT_TODO': {
return state.map((todo, id) => {
if(id === action.id) {
return {
...todo,
text: todo.text,
id: todo.id
}
} else {
return todo
}
})
}
case 'REMOVE_TODO':
return[
...state.slice(0, action.id),
...state.slice(action.id + 1)
];
case 'TOGGLE_TODO':
return[
...state.slice(0, action.id),
{
text: state[action.id].text,
completed: !state[action.id].completed
},
...state.slice(action.id + 1)
];
default: {
return state
}
}
}
const filterReducer = (state = 'ALL', action) => {
switch(action.type){
case 'SHOW_ALL':
return 'ALL';
case 'SHOW_COMPLETED':
return 'COMPLETED';
case 'SHOW_ACTIVE':
return 'ACTIVE';
default:
return state;
}
}
export { todo, filterReducer }
|
C++
|
UTF-8
| 823
| 2.6875
| 3
|
[] |
no_license
|
#include "timeitem.h"
timeItem::timeItem()
{
timeSting = QDateTime::currentDateTime().toString("yyyy/MM/dd dddd hh:mm:ss");
timeWidth = 300;
timeHeight = 100;
}
void timeItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *, QWidget *)
{
QFont font;
font.setPixelSize(18);
font.setBold(true);
painter->setPen(Qt::yellow);
painter->setFont(font);
timeSting = QDateTime::currentDateTime().toString("yyyy/MM/dd\ndddd\nhh:mm:ss");
painter->drawText(boundingRect(), Qt::AlignRight | Qt::AlignVCenter, timeSting);
}
QRectF timeItem::boundingRect() const
{
qreal adjust = 2;
return QRectF(-(timeWidth-adjust)/2, -(timeHeight-adjust)/2, (timeWidth+adjust), (timeHeight+adjust));
}
void timeItem::advance(int step)
{
if (!step)
return;
update();
}
|
Python
|
UTF-8
| 1,153
| 2.90625
| 3
|
[] |
no_license
|
import noise_modeling as nm
import stabilizer as st
# Initial parameters
ps = 0.000
pm = 0.000
pg = 0.1
system_size = 4
parity = "Z"
# Initialize objects
stab = st.Stabilizer(ps, pm, pg)
model = nm.NoiseModel(system_size, parity)
# Define function and apply superoperator
superoperator_function = stab.local_stabilizer
model.apply_superoperator(superoperator_function)
# Separate basis using the parity symmetry
# model.separate_basis_parity()
# Calculate chi matrix
model.make_chi_matrix()
print("Total sum: ", model.check_total_sum())
# Lenght must be 38
print("len: ", len(model.chi))
# class TestNoiseModeling(unittest.TestCase):
#
# def test_choi_state_ket(self):
# print("----------Test choi_state_ket-----------")
# choi = model.choi_state_ket(2)
# print(choi)
# # self.assertTrue(assert_Equivalent(op, op_ref))
#
# def test_symbol_product(self):
# print("----------Test symbol_product-----------")
# symA = "IXYZ"
# symB = "XYXZ"
#
# res = pb.symbol_product(symA, symB)
# self.assertEqual(res, "XZZI")
#
#
# if __name__ == '__main__':
# unittest.main()
|
Python
|
UTF-8
| 3,232
| 2.640625
| 3
|
[] |
no_license
|
#Standard Packages
from rest_framework.views import APIView
from rest_framework.response import Response
#Models
from dashboard.models.users import Users
from dashboard.models.ratings import Ratings
from dashboard.models.movies import Movies
from dashboard.models.genres_movies import GenresMovies
from dashboard.models.genres import Genres
#Serializers
from dashboard.serializers.movies_serializer import MoviesSerializer
#Additional Packages
from collections import Counter
#MainClass
class PersonalisedPicks(APIView):
def get(self, request, id):
user_tuple = Users.objects.get(id=id)
user_set = Users.objects.filter(occupation_id=user_tuple.occupation_id)|Users.objects.filter(age=22)
id_set = []
for tuple in user_set:
id_set.append(tuple.id)
good_ratings_set = Ratings.objects.filter(user_id__in=id_set, rating__range=[4,6])
bad_ratings_set = Ratings.objects.filter(user_id__in=id_set, rating__range=[-1,2])
high_rating_set = []
for tuple in good_ratings_set:
high_rating_set.append(tuple.movie_id)
low_rating_set = []
for tuple in bad_ratings_set:
low_rating_set.append(tuple.movie_id)
unique_high_set = set(high_rating_set)
unique_low_set = set(low_rating_set)
counted_high_set = Counter(high_rating_set)
counted_low_set = Counter(low_rating_set)
recommended_list = []
recommended_dict = {}
for item in unique_high_set:
if item in unique_low_set:
if(counted_high_set[item]-(1.5*counted_low_set[item])>0):
recommended_dict[item] = counted_high_set[item]/counted_low_set[item]
elif counted_high_set[item]>=20:
recommended_dict[item] = counted_high_set[item]
sorted_by_value = sorted(recommended_dict.items(), key=lambda kv: kv[1], reverse=True)
dataset = {}
ratings_arr = []
rating_arr_movie = []
genres = [[],[],[]]
iterator = -1
for item in sorted_by_value[:3]:
iterator = iterator+1
recommended_list.append(item[0])
try:
user_rating = Ratings.objects.get(user_id=id, movie_id = item[0])
ratings_arr.append(user_rating.rating)
rating_arr_movie.append(item[0])
except Ratings.DoesNotExist:
ratings_arr.append(0)
rating_arr_movie.append(item[0])
genre_tuples = GenresMovies.objects.filter(movie_id=item[0])
genre_list = []
for item in genre_tuples:
genre_list.append(Genres.objects.get(id=item.genre_id).name)
genres[iterator] = genre_list
movie_list = Movies.objects.filter(id__in=recommended_list)
seriailized = MoviesSerializer(movie_list, many=True)
rating_array = [x for _,x in sorted(zip(rating_arr_movie,ratings_arr))]
genres_array = [x for _,x in sorted(zip(rating_arr_movie,genres))]
dataset['data'] = seriailized.data
dataset['ratings'] = rating_array
dataset['genres'] = genres_array
print(dataset)
return Response(dataset)
|
Java
|
UTF-8
| 245
| 1.835938
| 2
|
[] |
no_license
|
package edu.uta.sis.calendars.data.repository;
import edu.uta.sis.calendars.data.entities.LocationEntity;
/**
* Created by Hannu Lohtander on 10.5.2016.
*/
public interface LocationRepository {
public void save(LocationEntity locationEntity);
}
|
Java
|
UTF-8
| 1,009
| 2.625
| 3
|
[] |
no_license
|
public class Restaurant {
// import takeout.utils.PrintUtils;
//import static takeout.utils.PrintUtils.*;
public static void main(String[] args) {
Menu menu = new Menu();
menu.printMenu();
Order firstOrder = new Order("John Smith");
firstOrder.setOrderNumber(firstOrder.createOrderId());
println();
System.out.println(firstOrder.getOrderNumber() + " " + firstOrder.getClientName());
Order secondOrder = new Order("Jane White");
secondOrder.setOrderNumber(secondOrder.createOrderId());
println();
System.out.println(secondOrder.getOrderNumber() + " " + secondOrder.getClientName());
Order thirdOrder = new Order("Paul Black");
thirdOrder.setOrderNumber(thirdOrder.createOrderId());
println();
System.out.println(thirdOrder.getOrderNumber() + " " + thirdOrder.getClientName());
}
}
|
Shell
|
UTF-8
| 2,116
| 3.671875
| 4
|
[] |
no_license
|
#!/bin/bash
if [ $# -ne 1 ];then
echo "[*] Usage: $0 <github url>"
exit;
fi
if [[ $1 == "https://github.com/*" ]]; then
echo "[X] Can't extract data for non-github website"
exit;
fi
issue_data() {
issue_resp=$(echo "$1")
for issue in $(echo $issue_resp | jq -r '.[] | @base64'); do
title=$(echo "$issue" | base64 -d | jq -r '.title' | sed 's/,//g' )
state=$(echo "$issue" | base64 -d | jq -r '.state')
id=$(echo "$issue" | base64 -d | jq -r '.number')
created_time=$(echo "$issue" | base64 -d | jq -r '.created_at')
updated_time=$(echo "$issue" | base64 -d | jq -r '.updated_at')
closed_time=$(echo "$issue" | base64 -d | jq -r '.closed_at')
body=$(python ../data_preparation/extract_natural_text.py <(echo "$issue" | base64 -d | jq -r '.body' | perl -p -e 's/\r/<\\r>/' | perl -p -e 's/\n/<\\n>/' | sed 's/,/<c>/g'))
user_name=$(echo "$issue" | base64 -d | jq -r '.user.login')
user_id=$(echo "$issue" | base64 -d | jq -r '.user.id')
author_assoc=$(echo "$issue" | base64 -d | jq -r '.author_association')
if [[ $is_pull == "" ]]; then
is_pull="0";
else
is_pull="1";
fi
echo "$id,$state,$created_time,$updated_time,$closed_time,$user_name,$user_id,$author_assoc,$title,$body"
done
}
check_github_api=$(curl -s https://api.github.com/users/ShefWuzi | jq 'select (.message != null) | .message' | grep "API rate limit")
while true;
do
if [[ $check_github_api != "" ]]; then
sleep 5m;
check_github_api=$(curl -s https://api.github.com/users/ShefWuzi | jq 'select (.message != null) | .message')
else
break
fi
done
echo "ID,State,Time Created,Time Updated,Time Closed,Username,User ID,Author Association,Title,Body"
user=$(echo $1 | rev | cut -d / -f 2 | rev)
repo=$(echo $1 | rev | cut -d / -f 1 | rev)
issue_resp=$(curl -s https://api.github.com/repos/$user/$repo/issues?state=closed&filter=all&direction=asc)
if [[ $issue_resp == "" ]]; then
exit;
fi
issue_data "$issue_resp"
pull_resp=$(curl -s https://api.github.com/repos/$user/$repo/pulls?state=closed&filter=all&direction=asc)
if [[ $issue_resp == "" ]]; then
exit;
fi
issue_data "$pull_resp"
|
Python
|
UTF-8
| 392
| 2.9375
| 3
|
[] |
no_license
|
def findprimes(b):
A=[]
for i in range(0,b+1):
A.append(i)
for j in range(2,(b//2)+1):
n=2
if A[j]==0:
pass
else:
while n <= b/j:
A[j*n]=0
n=n+1
k=0
L=len(A)
while k<L:
if A[k]==0:
del A[k]
L=len(A)
else:
k=k+1
return A[1:]
|
JavaScript
|
UTF-8
| 339
| 3.640625
| 4
|
[] |
no_license
|
function maxNumber(input) {
let index = 0
let maxNum = Number(input[0])
while (input[index] !== 'Stop') {
let currentNum = Number(input[index]);
if (currentNum > maxNum) {
maxNum = currentNum;
}
index++;
}
console.log(maxNum);
}
maxNumber(['100', '101', '80', '70', 'Stop'])
|
JavaScript
|
UTF-8
| 436
| 3.25
| 3
|
[] |
no_license
|
var number=110;
switch(number){
case 1:
console.log("it is okay");
break;
case 10:
console.log('searching correct number');
break;
case 12:
console.log("evething is okay");
break;
case 100:
console.log('are you okay with your new friends');
default:
console.log('it is work for default person');
}
|
Java
|
UTF-8
| 1,953
| 2.28125
| 2
|
[] |
no_license
|
/******************************************************************************
* Copyright (C) 2017 ShenZhen Powerdata Information Technology Co.,Ltd
* All Rights Reserved.
* 本软件为深圳博安达开发研制。未经本公司正式书面同意,其他任何个人、团体不得使用、
* 复制、修改或发布本软件.
*****************************************************************************/
package com.szboanda.epsm.workbench.contactmanager.exception;
import com.szboanda.platform.common.base.BaseException;
/**
* @title: 联系人管理
* @fileName: ContactManagerException.java
* @copyright: PowerData Software Co.,Ltd. Rights Reserved.
* @company: 深圳市博安达信息技术股份有限公司
* @author: 王观发
* @date: 2017年10月17日
* @version: V1.0
*/
public class ContactManagerException extends BaseException {
/**
* 序列化号
*/
private static final long serialVersionUID = -2347627245944564650L;
/**
* 构造一个不带参数的异常实例
*
*/
public ContactManagerException() {
super();
}
/**
* 使用指定异常构造一个异常实例
*
* @param message
*/
public ContactManagerException(Exception ex) {
super(ex);
}
/**
* 使用指定消息构造一个异常实例
*
* @param message
*/
public ContactManagerException(String message) {
super(message);
}
/**
* 使用指定消息和异常码构造一个异常实例
*
* @param message
* @param cause
*/
public ContactManagerException(String message, String code) {
super(message, code);
}
/**
* 使用指定消息和cause构造一个异常实例
*
* @param message
* @param cause
*/
public ContactManagerException(String message, Throwable cause) {
super(message, cause);
}
}
|
C
|
UTF-8
| 1,511
| 2.515625
| 3
|
[] |
no_license
|
#ifndef SIMPLE_TCP_H
#define SIMPLE_TCP_H
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <netinet/in.h>
#include <arpa/inet.h>
typedef struct simple_tcp simple_tcp;
typedef struct simple_tcp_msg simple_tcp_msg;
enum simple_tcp_errno {
ERROR_CREATE_SOCKET = 1,
ERROR_BIND,
ERROR_CONNECT,
ERROR_LISTEN,
ERROR_ACCEPT,
ERROR_READ,
ERROR_WRITE,
ERROR_CLOSE,
COMPLETED_SEND,
COMPLETED_RECV
};
struct simple_tcp_msg {
size_t len;
char data[];
};
struct simple_tcp {
int fd;
struct sockaddr_in src_addr;
struct sockaddr_in dest_addr;
};
extern simple_tcp * simple_tcp_new();
extern void simple_tcp_free(simple_tcp * tcp);
extern int simple_tcp_connect(simple_tcp * tcp, const char * addr, int port);
extern int simple_tcp_bind(simple_tcp * tcp, const char * addr, int port);
extern int simple_tcp_listen(simple_tcp * tcp, int backlog);
extern int simple_tcp_accept(simple_tcp * listen_tcp, simple_tcp * child_tcp);
extern int simple_tcp_send(const simple_tcp * tcp, void * msg, size_t len);
extern int simple_tcp_send_nonblock(const simple_tcp * tcp, void * msg, size_t len, size_t * sended);
extern int simple_tcp_recv(const simple_tcp * tcp, simple_tcp_msg ** msg);
extern int simple_tcp_recv_nonblock(const simple_tcp * tcp, simple_tcp_msg ** msg, size_t * recved);
extern int simple_tcp_close(simple_tcp * tcp);
#endif /* end of include guard: SIMPLE_TCP_H */
|
JavaScript
|
UTF-8
| 3,176
| 3.21875
| 3
|
[] |
no_license
|
var $container = document.getElementById("container"),
$city = document.getElementById("city"),
$numberDegree = document.getElementById("numberDegree"),
$iconTemp= document.getElementById("iconTemp"),
$descriptionTemp = document.getElementById("descriptionTemp"),
$city_actual = document.getElementById("city_actual")
$min = document.getElementById("min"),
$max = document.getElementById("max"),
$cityInput = document.getElementById("cityInput");
//Funciones accesorias
const changeBackground = (obj) => {
if (obj.weather[0].main == "Clouds" && obj.weather[0].icon == '03d'|| obj.weather[0].icon =='02d'|| obj.weather[0].icon =='04d') {
$container.classList.remove($container.classList)
$container.classList.add("container-dia-nublado")
};
if (obj.weather[0].main == "Clouds" && obj.weather[0].icon == '03n'|| obj.weather[0].icon =='02n'||obj.weather[0].icon =='04n') {
$container.classList.remove($container.classList)
$container.classList.add("container-noche-nublada")
};
if (obj.weather[0].main == "Rain") {
$container.classList.remove($container.classList)
$container.classList.add("container-rainy")};
if (obj.weather[0].main == "Snow") {
$container.classList.remove($container.classList)
$container.classList.add("container-snow")};
if (obj.weather[0].main == "Mist") {
$container.classList.remove($container.classList)
$container.classList.add("container-mist")}
if (obj.weather[0].main == "Clear" && obj.weather[0].icon == '01d') {
$container.classList.remove($container.classList)
$container.classList.add("container-dia-despejado")};
if (obj.weather[0].main == "Clear" && obj.weather[0].icon == '01n') {
$container.classList.remove($container.classList)
$container.classList.add("container-noche-despejada")
}
};
const mostrarDatos= (obj) => {
$numberDegree.textContent = Math.floor(obj.main.temp);
$descriptionTemp.textContent = obj.weather[0].description;
$city_actual.textContent = obj.name;
const icons = obj.weather[0].icon;
$iconTemp.innerHTML = `<img src="images/${icons}.svg"></img>`;
$min.textContent = Math.floor(obj.main.temp_min);
$max.textContent = Math.floor(obj.main.temp_max);
}
//Función principal
const getWeatherData = async(city) => {
const respuesta = await fetch(`https://community-open-weather-map.p.rapidapi.com/weather?q=${city}&lang=sp&units=metric`, {
"headers": {
"x-rapidapi-host": "community-open-weather-map.p.rapidapi.com",
"x-rapidapi-key": "9e2f26159cmshf87ccc480471b8fp10a24ejsn17c7d7cf4ec2"
},
});
const obj = await respuesta.json();
console.log(obj)
changeBackground(obj)
mostrarDatos(obj)
}
window.onload= () => {
getWeatherData("Buenos Aires");
}
$city.addEventListener("submit", e=>{
e.preventDefault();
getWeatherData($cityInput.value)
});
|
PHP
|
UTF-8
| 3,979
| 2.734375
| 3
|
[] |
no_license
|
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDaycare";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Create database
$sql = "CREATE DATABASE myDaycare";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully";
} else {
echo "Error creating database: " . $conn->error . "<br>";
}
$parent = "CREATE TABLE MyParent (
parent_id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
firstname VARCHAR(30) NOT NULL,
lastname VARCHAR(30) NOT NULL,
email VARCHAR(50) NOT NULL,
phone_number VARCHAR(15) NOT NULL,
address VARCHAR(50) NOT NULL,
city VARCHAR(50) NOT NULL,
zip VARCHAR(10) NOT NULL,
child_fname VARCHAR(50) NOT NULL,
child_lname VARCHAR(50) NOT NULL
)";
$child = "CREATE TABLE MyChild (
child_id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
child_fname VARCHAR(30) NOT NULL,
child_lname VARCHAR(30) NOT NULL,
phone_number VARCHAR(15) NOT NULL,
address VARCHAR(50) NOT NULL,
city VARCHAR(50) NOT NULL,
zip VARCHAR(10) NOT NULL,
parent_fname VARCHAR(50) NOT NULL,
parent_lname VARCHAR(50) NOT NULL,
info VARCHAR(200),
allergies VARCHAR(50),
child_dob DATE NOT NULL
)";
if ($conn->query($parent) === TRUE) {
echo "Table MyParent created successfully";
} else {
echo "Error creating table: " . $conn->error . "<br>";
}
if ($conn->query($child) === TRUE) {
echo "Table MyChild created successfully";
} else {
echo "Error creating table: " . $conn->error . "<br>";
}
//Insert into Table MyChild
$id = mysqli_real_escape_string($conn, $_POST['id from html form']);
$firstname = mysqli_real_escape_string($conn, $_POST['firstName']);
$lastname = mysqli_real_escape_string($conn, $_POST['']);
$phone_number = mysqli_real_escape_string($conn, $_POST['']);
$address = mysqli_real_escape_string($conn, $_POST['']);
$city = mysqli_real_escape_string($conn, $_POST['']);
$zip = mysqli_real_escape_string($conn, $_POST['']);
$parent_fname = mysqli_real_escape_string($conn, $_POST['']);
$parent_lname = mysqli_real_escape_string($conn, $_POST['']);
$info = mysqli_real_escape_string($conn, $_POST['']);
$allergies = mysqli_real_escape_string($conn, $_POST['']);
$child_dob = mysqli_real_escape_string($conn, $_POST['']);
$sql = "INSERT INTO MyChild (child_id, child_fname, child_lname, phone_number, address, city, zip, parent_fname, parent_lname, info, allergies, child_dob)
VALUES ('$id', '$firstname', '$lastname', '$phone_number', '$address', '$city', '$zip','$parent_fname', '$parent_lname', '$info', '$allergies', '$child_dob')";
//Insert MyParent Table
$id = mysqli_real_escape_string($conn, $_POST['']);
$firstname = mysqli_real_escape_string($conn, $_POST['']);
$lastname = mysqli_real_escape_string($conn, $_POST['']);
$email = mysqli_real_escape_string($conn, $_POST['']);
$phone_number = mysqli_real_escape_string($conn, $_POST['']);
$address = mysqli_real_escape_string($conn, $_POST['']);
$city = mysqli_real_escape_string($conn, $_POST['']);
$zip = mysqli_real_escape_string($conn, $_POST['']);
$child_fname = mysqli_real_escape_string($conn, $_POST['']);
$child_lname = mysqli_real_escape_string($conn, $_POST['']);
$sql = "INSERT INTO MyParent (parent_id, firstname, lastname, email, phone_number, address, city, zip, child_fname, child_lname)
VALUES ('$id', '$firstname', '$lastname', '$email', '$phone_number', '$address', '$city', '$zip', '$child_fname', '$child_lname')";
//Delete MyChild
$sql = "DELETE FROM MyChild WHERE child_id = $id";
//Delete MyParent
$sql = "DELETE FROM MyParent WHERE parent_id = $id";
//Update MyChild
$sql = "UPDATE MyChild SET child_fname = '$firstname' WHERE child_id = '$id'";
//Update MyParent
$sql = "UPDATE MyParent SET firstname = '$firstname' WHERE parent_id = '$id'";
$conn->close();
?>
|
Markdown
|
UTF-8
| 1,016
| 2.59375
| 3
|
[
"Apache-2.0"
] |
permissive
|
# Search Commons
Search Commons maintains custom search engines.
The engines are powered by [Google Custom Search][1] and available at [SearchCommons.org][4].
## Contributing
Search engines are specified in folder [`websites`](websites). A search engine specification contains the following files:
* `include.txt`: The URL patterns included in search
* `exclude.txt`: The URL patterns excluded from search
* `README.md`: Instructions for reproducing and maintaining the engine
### Create New Search Engine
Create a folder with specifications and send us a pull request.
### Edit Search Engine
Edit specifications in a folder and send us a pull request.
## Contacts
Anton Tarasenko, [antontarasenko@gmail.com][3]
## Acknowledgements
* [Wikidata](https://www.wikidata.org/) provided data for search engine specifications.
## License
[Apache License 2.0](LICENSE.txt)
[1]: https://programmablesearchengine.google.com/
[2]: https://www.customsearch.ai/
[3]: mailto:antontarasenko@gmail.com
[4]: https://searchcommons.org/engines.html
|
Java
|
UTF-8
| 16,181
| 1.5625
| 2
|
[] |
no_license
|
package com.cjm.spf.controllers;
import java.io.FileNotFoundException;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.Date;
import java.util.List;
import javax.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import com.cjm.spf.domain.*;
import com.cjm.spf.dao.DatosAgresorDao;
import com.cjm.spf.dao.ExpedienteDao;
import com.cjm.spf.dao.FolioDao;
import com.cjm.spf.dao.DomicilioAgresorDao;
import com.cjm.spf.pojo.conteoTS;
import com.cjm.spf.servicio.NuevoUsuarioService;
import com.cjm.spf.servicio.RegistroService;
import com.cjm.spf.servicio.eViolenciaService;
import com.cjm.spf.servicio.ExpedienteService;
import com.cjm.spf.servicio.NarracionService;
import com.cjm.spf.servicio.RFamiliaresService;
import com.cjm.spf.servicio.RedApoyoService;
import com.cjm.spf.servicio.SaludService;
import com.cjm.spf.servicio.AgresorService;
import com.cjm.spf.servicio.FijacionAService;
import com.cjm.spf.servicio.DomAgresorService;
import com.cjm.spf.servicio.PerfilAgresorService;
import com.cjm.spf.servicio.FactorRiesgoService;
import com.cjm.spf.servicio.ServiciosBrindadosService;
import com.cjm.spf.servicio.ExpPsicService;
import com.cjm.spf.servicio.SegPsicService;
import com.cjm.spf.servicio.RegEmpService;
import com.cjm.spf.servicio.SegEmpoService;
import com.cjm.spf.servicio.FolioService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
@Controller
@Slf4j
public class ControladorInicio {
@Autowired
private FolioService folioService;
@Autowired
DomicilioAgresorDao domADao;
@Autowired
ExpedienteDao expedienteDao;
@Autowired
DatosAgresorDao agresorDao;
@Autowired
FolioDao folioDao;
@Autowired
private RegEmpService regEmpService;
@Autowired
private SegEmpoService segEmpService;
@Autowired
private SegPsicService seguimientoPsicService;
@Autowired
private ExpPsicService expPsicService;
@Autowired
private FactorRiesgoService fRiesgoService;
@Autowired
private RegistroService registroService;
@Autowired
private ExpedienteService expedienteService;
@Autowired
private NarracionService narracionService;
@Autowired
private RFamiliaresService familiaresService;
@Autowired
private RedApoyoService apoyoService;
@Autowired
private eViolenciaService violenciaService;
@Autowired
private SaludService saludService;
@Autowired
private FijacionAService fijacionService;
@Autowired
private AgresorService agresorService;
@Autowired
private DomAgresorService domService;
@Autowired
private PerfilAgresorService perfilAService;
@Autowired
private ServiciosBrindadosService serviciosService;
@GetMapping("/prueba")
public String prueba(Model model, Expediente expediente) {
expediente.setUsuaria((long) 1);
return "index_prueba";
}
@GetMapping("/")
public String inicio(Model model, @AuthenticationPrincipal User user) {
return "index";
}
@GetMapping("/crear")
public String crear(NuevoUsuario usuario) {
return "crear";
}
@GetMapping("/registrar")
public String registro(Registro registro) {
return "preRegistro";
}
///////////////////////////////////////////////
// @GetMapping("/preRegistro")
// public String preRegistro(Registro registro) {
// return "preRegistro";
// }
// @GetMapping("/expediente")
// public String expediente(Expediente expediente, Model model) {
// expediente.setUsuaria((long) 1);
// return "expediente";
// }
/////////////////////////////////////////////
@GetMapping("/verRegistros")
public String visualizar(Model model) {
List<Registro> registros = registroService.listarRegistros();
model.addAttribute("registros", registros);
System.out.println(registros);
return "verUsuarias";
}
@GetMapping("/formato")
public String ejemplo(Registro registro) {
return "ejemplo";
}
// @GetMapping("/ver/{id}")
// public String editar(Registro registro, Model model) {
// registro = registroService.encontrarRegistro(registro);
// model.addAttribute("registros", registro);
// return "infoUsuaria";
// }
@GetMapping("/perfil_usuaria/{id}")
public String perfilusuaria(Registro registro, Model model) {
registro = registroService.encontrarRegistro(registro); //Registro de primera vez de la usuaria
Expediente exp = expedienteService.encontrarPorId(registro.getId()); //Se busca el exp de la usuaria
model.addAttribute("registro", registro); //Enviamos los datos grales de la usuaria
if(exp != null) { //Si existe un expediente..
model.addAttribute("expedienteTS", exp); //Envio del expediente
RegEmpoderamiento regEmp = regEmpService.findByUsuaria(registro.getId());
SeguimientoEmp segEmp = new SeguimientoEmp();
segEmp.setId(registro.getId());
List <SeguimientoEmp> seguimientoEmp = segEmpService.findSeguimientoS(segEmp.getId());
if(seguimientoEmp.isEmpty()) { //Si no hay seguimientos en empoderamiento
model.addAttribute("psicseguimientos", null);
model.addAttribute("registroemp", regEmp);
}else { //Cuando si hay seguimientos
int segemp = seguimientoEmp.size();
model.addAttribute("psicseguimientos", segemp);
model.addAttribute("registroemp", regEmp);
}
model.addAttribute("expedienteTS", exp);
ExpPsic expPsic = expPsicService.encontrarExpPsic(registro.getId());
List<SeguimientoPsic> registros = seguimientoPsicService.encontrarSeguimientosDeUsuaria(registro.getId());
if(registros.isEmpty()) { //Si no hay seguimientos psicologicos
model.addAttribute("pseguimientos", null);
model.addAttribute("pexpediente", expPsic);
}else { //Cuando si los hay
int segpsic = registros.size();
model.addAttribute("pseguimientos", segpsic);
model.addAttribute("pexpediente", expPsic);
}
}else { //Si no existe un expediente
model.addAttribute("pseguimientos", null);
model.addAttribute("pexpediente", null);
model.addAttribute("expedienteTS", null);
model.addAttribute("psicseguimientos", null);
model.addAttribute("registroemp", null);
}
return "PerfilTs";
}
@GetMapping("/abrirExpediente/{id}")
public String expediente(Registro registro, Model model) {
registro = registroService.encontrarRegistro(registro);
model.addAttribute("registros", registro);
return "index_prueba";
}
@GetMapping("/conteoMensual")
public String conteo(Model model) {
Date date = new Date();
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
int mes = localDate.getMonthValue();
int anio = localDate.getYear();
Long expedientes = folioService.hacerConteo("expediente",anio, mes);
Long info = folioService.hacerConteo("informacion", anio, mes);
Long asesoria = folioService.hacerConteo("asesoria", anio, mes);
model.addAttribute("expedientes", expedientes);
model.addAttribute("info", info);
model.addAttribute("asesoria", asesoria);
return "infMenTS";
}
@GetMapping("/registro_expediente/{id}")
public String abrir_expediente(@PathVariable("id") Long id, Model model) {
Folio folio = new Folio();
Folio num = folioDao.findTopByServicioOrderByIdDesc("expediente");
Date date = new Date();
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
folio.setDia(localDate.getDayOfMonth());
folio.setMes(localDate.getMonthValue());
folio.setAnio(localDate.getYear());
if(num == null){
folio.setUsuaria(id);
folio.setId_status_folio(1);
folio.setId_tipo_folio((long)1);
folio.setServicio("expediente");
folio.setAtencion("cjm");
}else{
long variable = num.getId_tipo_folio() + 1;
folio.setUsuaria(id);
folio.setId_status_folio(1);
folio.setId_tipo_folio(variable);
folio.setServicio("expediente");
folio.setAtencion("cjm");
}
folioDao.save(folio);
Expediente expediente = new Expediente();
model.addAttribute("expediente", expediente);
return "expediente";
}
////////////////////////////////////////////////////// POST ///////////////////////////////////////////////
@PostMapping("/guardar") //Guardar registro de nueva usuaria
public String guardar(@Valid Registro registro, Errors errores, Expediente expediente, Model model) {
if (errores.hasErrors()) {
return "preRegistro";
} else {
String servicio = registro.getMotivo_visita();
if ("expediente".equals(servicio)) {
registroService.guardar(registro);
return "expediente";
} else {
registroService.guardar(registro);
model.addAttribute("registrado", true);
return "redirect:/";
}
}
}
@PostMapping("/buscar") //Buscar usuaria existente por nombre
public String buscarPorNombre(String nombre, Model model) throws FileNotFoundException{
List<Registro> datos = registroService.encontrarUsuaria(nombre);
if(datos.isEmpty()) {
model.addAttribute("registros", null);
}else {
model.addAttribute("registros", datos);
}
return "index";
}
@PostMapping("/guardarUsuario") //guardar nuevo admin
public String guardar(@Valid NuevoUsuario usuario, Errors errores) {
if (errores.hasErrors()) {
return "crear";
}
return "redirect:/";
}
@PostMapping("/crearExpediente") //Crear nuevo expediente
public String guardar(@Valid Expediente expediente, Errors errores, Model model, RFamiliares familiares) {
if (errores.hasErrors()) {
return "expediente";
}
model.addAttribute("familiares", familiares);
expedienteService.guardar(expediente);
return "familiares";
}
@PostMapping("/crear_relaciones_familiares") //Crear relaciones familiares
public String guardar(@Valid RFamiliares familiares, Errors errores, Model model, RedApoyo apoyo) {
if (errores.hasErrors()) {
return "familiares";
}
model.addAttribute("apoyo", apoyo);
familiaresService.guardar(familiares);
return "red_apoyo";
}
@PostMapping("/crear_red_apoyo") //Crear red de apoyo
public String guardar(@Valid RedApoyo apoyo, Errors errores, Narracion narracion) {
if (errores.hasErrors()) {
return "red_apoyo";
}
apoyoService.guardar(apoyo);
return "narracionHechos";
}
@PostMapping("/crearNarracion") //Crear nueva narracion
public String guardar(@Valid Narracion narracion, Errors errores, EfectosViolencia violencia, Model model) {
if (errores.hasErrors()) {
return "narracionHechos";
}
model.addAttribute("violencia", violencia);
narracionService.guardar(narracion);
return "efectos_violencia";
}
@PostMapping("/crearEfectos") //Crear efectos de violencia
public String guardar(@Valid EfectosViolencia violencia, Errors errores, SaludFisica salud, Model model) {
if (errores.hasErrors()) {
return "efectos_violencia";
}
model.addAttribute("salud", salud);
violenciaService.guardar(violencia);
return "Salud";
}
@PostMapping("/nueva_salud") //Crear nuevo estado de salud
public String guardar(@Valid SaludFisica salud, Errors errores, Filiacion filiacion, Model model ) {
if (errores.hasErrors()) {
return "Salud";
}
saludService.guardar(salud);
model.addAttribute("filiacion", filiacion);
return "Filiacion";
}
@PostMapping("/crear_filiacion") //Crear nueva filiacion
public String guardar(@Valid Filiacion filiacion, Errors errores, Agresor agresor, Model model, Expediente expediente) {
if (errores.hasErrors()) {
return "Filiacion";
}
expediente = expedienteDao.findTopByOrderByIdDesc();
filiacion.setId_perfil(expediente.getId());
model.addAttribute("agresor", agresor);
fijacionService.guardar(filiacion);
return "DatosAgresor";
}
@PostMapping("/datos_agresor") //Crear nuevo expediente de agresor
public String guardar(@Valid Agresor agresor, Errors errores, DomicilioAgresor domAgresor, Model model ) {
if (errores.hasErrors()) {
return "DatosAgresor";
}
model.addAttribute("domAgresor", domAgresor);
agresorService.guardar(agresor);
return "DomicilioAgresor";
}
@PostMapping("/domicilio_agresor") //Crear nuevo dom agresor
public String guardar(@Valid DomicilioAgresor domAgresor, Errors errores, PerfilAgresor pAgresor, Model model ) {
if (errores.hasErrors()) {
return "DomicilioAgresor";
}
domService.guardar(domAgresor);
model.addAttribute("pAgresor", pAgresor);
return "PerfilAgresor";
}
@PostMapping("/perfil_agresor") //Crear perfil agresor
public String guardar(@Valid PerfilAgresor pAgresor, Errors errores, Filiacion filiacion) {
if (errores.hasErrors()) {
return "PerfilAgresor";
}
perfilAService.guardar(pAgresor);
return "FiliacionAgresor";
}
@PostMapping("/filiacion_agresor") //Crear filiacion del agresor
public String guardar(@Valid Filiacion filiacion, Errors errores, Agresor agresor, Model model, FactorRiesgo fRiesgo) {
if (errores.hasErrors()) {
return "FiliacionAgresor";
}
agresor = agresorDao.findTopByOrderByIdDesc();
filiacion.setId_perfil(agresor.getId());
fijacionService.guardar(filiacion);
model.addAttribute("fRiesgo", fRiesgo);
return "factor_riesgo";
}
@PostMapping("/factor_riesgo") //Crear factores de riesgo
public String guardar(@Valid FactorRiesgo fRiesgo, Errors errores, ServiciosBrindados servicios) {
if (errores.hasErrors()) {
return "factor_riesgo";
}
fRiesgoService.guardar(fRiesgo);
return "serviciosBrindados";
}
@PostMapping("/servicios_brindados") //Registrar servicios brindados
public String guardar(@Valid ServiciosBrindados servicios, Errors errores) {
if (errores.hasErrors()) {
return "serviciosBrindados";
}
serviciosService.guardar(servicios);
return "redirect:/";
}
}
|
Java
|
UTF-8
| 1,309
| 1.992188
| 2
|
[] |
no_license
|
package cn.bc.identity.service;
import cn.bc.identity.domain.Duty;
import cn.bc.test.AbstractEntityCrudTest;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;
@RunWith(SpringJUnit4ClassRunner.class)
@Transactional
@ContextConfiguration("classpath:spring-test.xml")
public class DutyServiceImplTest extends AbstractEntityCrudTest<Long, Duty> {
DutyService dutyService;
IdGeneratorService idGeneratorService;
@Autowired
public void setDutyService(DutyService dutyService) {
this.dutyService = dutyService;
this.crudOperations = dutyService;//赋值基类的crud操作对象
}
@Autowired
public void setIdGeneratorService(IdGeneratorService idGeneratorService) {
this.idGeneratorService = idGeneratorService;
}
@Override
protected Duty createInstance(String config) {
Duty entity = super.createInstance(config);
//System.out.println("----"+entity.getStatus());
//补充一些额外的设置
entity.setCode(this.idGeneratorService.next("duty.code"));
entity.setName(entity.getCode());
return entity;
}
}
|
Python
|
UTF-8
| 1,237
| 2.6875
| 3
|
[] |
no_license
|
import numpy as np
import math
import random
import seaborn as sns
from scipy import stats
import pandas as pd
from jury import *
from matplotlib import pyplot as plt
SIMULATIONS = 100000
# SIMULATIONS = 10000
BANDWIDTH = .5
# BANDWIDTH = 'silverman'
# CUMULATIVE = False
CUMULATIVE = True
jury = JuryList()
def no_duplicates():
counts = []
for i in range(SIMULATIONS):
jury_list = jury.create_jury()
makeup = jury.race_count(jury_list)['White']
counts.append(makeup)
counts = pd.Series(counts, name="KDE w/o Duplicates")
sns.kdeplot(counts, shade=True, color="b", bw=BANDWIDTH, cumulative=CUMULATIVE)
def w_duplicates():
counts = []
for i in range(SIMULATIONS):
jury_list = jury.create_jury(True)
makeup = jury.race_count(jury_list)['White']
counts.append(makeup)
counts = pd.Series(counts, name="KDE w/ Duplicates")
sns.kdeplot(counts, shade=True, color="r", bw=BANDWIDTH, cumulative=CUMULATIVE)
no_duplicates()
w_duplicates()
plt.grid(which='both')
plt.title("Likelihood of # of White people on a Jury with " + str(SIMULATIONS) + " simulations")
if CUMULATIVE:
plt.savefig('cumulative.png')
else:
plt.savefig('non_cumulative.png')
|
JavaScript
|
UTF-8
| 4,818
| 2.6875
| 3
|
[] |
no_license
|
const targetsOrder = [
STRUCTURE_SPAWN,
STRUCTURE_TOWER,
STRUCTURE_ROAD,
STRUCTURE_CONTAINER,
STRUCTURE_STORAGE,
STRUCTURE_EXTENSION,
// STRUCTURE_WALL,
];
const roleUtil = require('./role.util');
const tools = require('./tools');
var roleRepairer = module.exports = {
levels: [
{work: 1, carry: 1, move: 1},
{work: 1, carry: 1, move: 2},
{work: 1, carry: 1, move: 3},
{work: 2, carry: 1, move: 3},
{work: 2, carry: 2, move: 3},
{work: 2, carry: 3, move: 4},
{work: 2, carry: 3, move: 5}
],
/** @param {Creep} creep **/
run: function(creep) {
// Gathering
if( roleUtil.getResources(creep) ) {
creep.memory.repairerTargetId = null;
return;
}
let target = null,
targets = tools.getStructures(creep.room, struct => struct.hits < struct.hitsMax);
// Derp
if( !targets.length ) {
creep.memory.repairerTargetId = null;
return false;
}
// Only one target - pretty simple
if( targets.length === 1 ) {
target = targets[0];
creep.memory.repairerTargetId = target.id;
}
else if( creep.memory.repairerTargetId ) {
// tools.dump('Repairing from target', {creep_id: creep.name, target_id: creep.memory.repairerTargetId});
target = _.find(targets, _target => _target.id === creep.memory.repairerTargetId);
// done building - move on
if ( !target ) {
creep.memory.repairerTargetId = null;
}
}
if (!target) {
_.find(targetsOrder, function(targetType) {
if( target ) return true;
let typeTargets = _.filter(targets, {structureType: targetType});
// None for thistype
if( typeTargets.length === 0 ) {
return false;
}
// First sort by hits needed to repair, then by how many creeps are targeting it
// Sort by the number of creeps currently repairing this, then by number of hit
return target = _.sortBy(_.sortBy(typeTargets, t => t.hitsMax - t.hits),
t => roleUtil.targetCreeps(t, 'repairer'), 'hits')[0];
/*
let creepCounts = _.map(typeTargets, t => roleUtil.targetCreeps(t, 'repairer'));
// If all the same, sort by hits
if( creepCounts[0] === creepCounts.slice(-1) ) {
target = _.sortBy(typeTargets, 'hits')[0];
}
else {
target =
}
// For walls, find the wall with the fewest hits
if( targetType === STRUCTURE_WALL ) {
target = _.sortBy(_.filter(targets, (_target) => _target.structureType === targetType), 'hits');
if( target.length ) {
target = target[0];
}
else {
target = null;
}
}
else {
// Find targets that aren't currently being targeted by another repairer
target = _.sortBy(typeTargets, t => roleUtil.targetCreeps(t, 'repairer'))[0];
// target = target || _.find(targets, (_target) => _target.structureType === targetType);
}
*/
});
}
// Could not find one in our list of priorities - use whatever else we can find
target = target || targets[0];
// New target
if (creep.memory.repairerTargetId !== target.id) {
creep.memory.repairerTargetId = this.lastTargetId = target.id;
console.log('Repairing ' + target);
creep.say('Repairing.' + target.name);
}
let res = creep.repair(target);
if (res === ERR_NOT_IN_RANGE) {
creep.moveTo(target);
}
// Out of energy
else if(res === ERR_NOT_ENOUGH_RESOURCES) {
creep.memory.repairerTargetId = null;
return this.run(creep);
}
// Done or out of energy, run again
else if( !creep.carry.energy || target.hits >= target.hitsMax ) {
creep.memory.repairerTargetId = null;
return this.run(creep);
}
},
/**
* Only if we have roads or containers to maintain
* @param spawn
*/
spawn: function(spawn) {
return tools.getStructures(spawn.room, struct =>
struct.structureType === STRUCTURE_ROAD || struct.structureType === STRUCTURE_CONTAINER)
.length > 0;
}
};
|
Java
|
UTF-8
| 186
| 1.632813
| 2
|
[] |
no_license
|
package pacman;
public class NativeActivityAbortContext {
public NativeActivityAbortContext(ActivityInstance instance, ActivityExecutor executor, Exception terminationReason) {
}
}
|
Python
|
UTF-8
| 699
| 3.90625
| 4
|
[] |
no_license
|
# -*- coding:utf-8 -*-
print "Mary had a little lamb."#输出此句
print "Its fleece was white as %s."%'snow'#%s被‘snow’替代
print "And everywhere that Mary went."#输出此句
print "."*10 #what'd that do?#输出这句十倍,即输出十次
end1="C"#赋值
end2="h"#赋值
end3="e"#赋值
end4="e"#赋值
end5="s"#赋值
end6="e"#赋值
end7="B"#赋值
end8="u"#赋值
end9="r"#赋值
end10="g"#赋值
end11="e"#赋值
end12="r"#赋值
#watch that comma at the end. try removing it to see what happens
print end1+end2+end3+end4+end5+end6,#逗号(comma)作用是将两段连在一起,用空格隔开
print end7+end8+end9+end10+end11+end12#在上一个输出的同一行继续输出
|
Python
|
UTF-8
| 463
| 3.734375
| 4
|
[] |
no_license
|
import random
print("Welcome to the Lottery numbers generator.")
number = input("Please enter how many random numbers would you like to have: ")
def loto(n):
new = []
for x in range(0, n):
ran = random.randint(1, 40)
if ran not in new:
new.append(ran)
else:
ran = random.randint(1, 40)
new.append(ran)
return new
for i in range(1, 100):
print loto(number)
|
Java
|
UTF-8
| 6,004
| 1.757813
| 2
|
[] |
no_license
|
//
// Decompiled by Procyon v0.5.30
//
package com.google.android.gms.internal;
import android.content.Context;
public class zzuy
{
private zzuz Uv;
private boolean zzaom;
public zzuy() {
this.zzaom = false;
this.Uv = null;
}
public void initialize(final Context p0) {
//
// This method could not be decompiled.
//
// Original Bytecode:
//
// 0: aload_0
// 1: monitorenter
// 2: aload_0
// 3: getfield com/google/android/gms/internal/zzuy.zzaom:Z
// 6: ifeq 12
// 9: aload_0
// 10: monitorexit
// 11: return
// 12: aload_0
// 13: aload_1
// 14: getstatic com/google/android/gms/internal/zzsu.Oy:Lcom/google/android/gms/internal/zzsu$zzb;
// 17: ldc "com.google.android.gms.flags"
// 19: invokestatic com/google/android/gms/internal/zzsu.zza:(Landroid/content/Context;Lcom/google/android/gms/internal/zzsu$zzb;Ljava/lang/String;)Lcom/google/android/gms/internal/zzsu;
// 22: ldc "com.google.android.gms.flags.impl.FlagProviderImpl"
// 24: invokevirtual com/google/android/gms/internal/zzsu.zzjd:(Ljava/lang/String;)Landroid/os/IBinder;
// 27: invokestatic com/google/android/gms/internal/zzuz$zza.asInterface:(Landroid/os/IBinder;)Lcom/google/android/gms/internal/zzuz;
// 30: putfield com/google/android/gms/internal/zzuy.Uv:Lcom/google/android/gms/internal/zzuz;
// 33: aload_0
// 34: getfield com/google/android/gms/internal/zzuy.Uv:Lcom/google/android/gms/internal/zzuz;
// 37: aload_1
// 38: invokestatic com/google/android/gms/dynamic/zze.zzac:(Ljava/lang/Object;)Lcom/google/android/gms/dynamic/zzd;
// 41: invokeinterface com/google/android/gms/internal/zzuz.init:(Lcom/google/android/gms/dynamic/zzd;)V
// 46: aload_0
// 47: iconst_1
// 48: putfield com/google/android/gms/internal/zzuy.zzaom:Z
// 51: aload_0
// 52: monitorexit
// 53: goto 11
// 56: astore_2
// 57: aload_0
// 58: monitorexit
// 59: aload_2
// 60: athrow
// 61: astore_3
// 62: ldc "FlagValueProvider"
// 64: ldc "Failed to initialize flags module."
// 66: aload_3
// 67: invokestatic android/util/Log.w:(Ljava/lang/String;Ljava/lang/String;Ljava/lang/Throwable;)I
// 70: pop
// 71: goto 51
// 74: astore_3
// 75: goto 62
// Exceptions:
// Try Handler
// Start End Start End Type
// ----- ----- ----- ----- ------------------------------------------
// 2 11 56 61 Any
// 12 51 74 78 Lcom/google/android/gms/internal/zzsu$zza;
// 12 51 61 62 Landroid/os/RemoteException;
// 12 51 56 61 Any
// 51 59 56 61 Any
// 62 71 56 61 Any
//
// The error that occurred was:
//
// java.lang.IllegalStateException: Expression is linked from several locations: Label_0012:
// at com.strobel.decompiler.ast.Error.expressionLinkedFromMultipleLocations(Error.java:27)
// at com.strobel.decompiler.ast.AstOptimizer.mergeDisparateObjectInitializations(AstOptimizer.java:2592)
// at com.strobel.decompiler.ast.AstOptimizer.optimize(AstOptimizer.java:235)
// at com.strobel.decompiler.ast.AstOptimizer.optimize(AstOptimizer.java:42)
// at com.strobel.decompiler.languages.java.ast.AstMethodBodyBuilder.createMethodBody(AstMethodBodyBuilder.java:214)
// at com.strobel.decompiler.languages.java.ast.AstMethodBodyBuilder.createMethodBody(AstMethodBodyBuilder.java:99)
// at com.strobel.decompiler.languages.java.ast.AstBuilder.createMethodBody(AstBuilder.java:757)
// at com.strobel.decompiler.languages.java.ast.AstBuilder.createMethod(AstBuilder.java:655)
// at com.strobel.decompiler.languages.java.ast.AstBuilder.addTypeMembers(AstBuilder.java:532)
// at com.strobel.decompiler.languages.java.ast.AstBuilder.createTypeCore(AstBuilder.java:499)
// at com.strobel.decompiler.languages.java.ast.AstBuilder.createTypeNoCache(AstBuilder.java:141)
// at com.strobel.decompiler.languages.java.ast.AstBuilder.createType(AstBuilder.java:130)
// at com.strobel.decompiler.languages.java.ast.AstBuilder.addType(AstBuilder.java:105)
// at com.strobel.decompiler.languages.java.JavaLanguage.buildAst(JavaLanguage.java:71)
// at com.strobel.decompiler.languages.java.JavaLanguage.decompileType(JavaLanguage.java:59)
// at com.strobel.decompiler.DecompilerDriver.decompileType(DecompilerDriver.java:317)
// at com.strobel.decompiler.DecompilerDriver.decompileJar(DecompilerDriver.java:238)
// at com.strobel.decompiler.DecompilerDriver.main(DecompilerDriver.java:138)
//
throw new IllegalStateException("An error occurred while decompiling this method.");
}
public <T> T zzb(final zzuw<T> zzuw) {
T t;
synchronized (this) {
if (!this.zzaom) {
t = zzuw.zzkq();
}
else {
// monitorexit(this)
t = zzuw.zza(this.Uv);
}
}
return t;
}
}
|
Python
|
UTF-8
| 1,843
| 4.09375
| 4
|
[] |
no_license
|
import numpy as np
# ==========数组计算
a_array = np.array([10, 20, 30, 40])
b_array = np.arange(4)
# print(a_array, b_array) # [10 20 30 40] [0 1 2 3]
# 相加
result = a_array + b_array
# print(result) # [10 21 32 43]
# 幂运算
result = b_array ** 2
# print(result) # [0 1 4 9]
# 三角函数
result = 10 * np.sin(a_array)
# print(result) # [-5.44021111 9.12945251 -9.88031624 7.4511316 ]
# 元素值比较
# print(b_array < 2) # [ True True False False]
# ==========矩阵计算
a_dim2 = np.array([[1, 1],
[0, 1]])
b_dim2 = np.arange(4).reshape((2, 2))
# print(a_dim2)
# print(b_dim2)
"""
[[1 1]
[0 1]]
[[0 1]
[2 3]]
"""
# 按元素位置逐个相乘
result = a_dim2 * b_dim2
# print(result)
"""
[[0 1]
[0 3]]
"""
# 矩阵相乘
result = np.dot(a_dim2, b_dim2)
# print(result)
"""
[[2 4]
[2 3]]
"""
# or
result = a_dim2.dot(b_dim2)
# print(result) # 与上面结果一致
# =========矢量和标量运算
c_array = np.array([[1, 2], [3, 4]])
# print(1. / c_array)
"""
[[1. 0.5 ]
[0.33333333 0.25 ]]
"""
# print(2. * c_array)
"""
[[2. 4.]
[6. 8.]]
"""
# =========随机矩阵
random_a = np.random.random((2, 4)) # 元素值为0-1的随机array
# print(random_a)
"""
[[0.72452698 0.13651464 0.44600111 0.41655378]
[0.89009035 0.7912297 0.78067892 0.95713937]]
"""
random_b = np.random.rand(2, 4)
# print(random_b)
"""
[[0.21914195 0.51772941 0.66419856 0.96328403]
[0.45329901 0.29727969 0.80851175 0.50195666]]
"""
# =========聚合方法
# print(np.sum(random_a))
# 3.1339300057726764
# print(np.sum(random_a, axis=1)) # axis=1 每行聚合
# [2.1656187 0.9683113]
# print(np.sum(random_a, axis=0)) # axis=0 每列聚合
# [0.86301568 0.62897626 0.92527623 0.71666183]
# print(np.min(random_a))
# 0.11829881364496164
# print(np.max(random_a))
# 0.8069774128223589
|
PHP
|
UTF-8
| 5,841
| 2.53125
| 3
|
[] |
no_license
|
<?php
/**
* This Program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3, or (at your option)
* any later version.
*
* This Program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with TsunAMP; see the file COPYING. If not, see
* <http://www.gnu.org/licenses/>.
*
* PlayerUI Copyright (C) 2013 Andrea Coiutti & Simone De Gregori
* Tsunamp Team
* http://www.tsunamp.com
*
* Rewrite by Tim Curtis and Andreas Goetz
*/
require_once dirname(__FILE__) . '/../inc/connection.php';
function mpdTouchFiles() {
return sysCmd("find '" . MPD_LIB . 'WEBRADIO' . "' -name \"" . "*.pls" . "\"" . " -exec touch {} \+");
}
// Get options- cmd line or GET
$options = getopt('c:p:', array('cmd:', 'path:'));
$cmd = isset($options['c']) ? $options['c'] : (isset($options['cmd']) ? $options['cmd'] : null);
$path = isset($options['p']) ? $options['p'] : (isset($options['path']) ? $options['path'] : null);
if (empty($cmd)) {
if (!isset($_GET['cmd'])) {
die('Error: missing or invalid command');
}
$cmd = $_GET['cmd'];
$path = isset($_POST['path']) ? $_POST['path'] : null;
}
if (!$mpd) {
die('Error: connection to MPD failed');
}
// Commands
switch ($cmd) {
case 'filepath':
$res = (null !== $path)
? searchDB($mpd, 'filepath', $path)
: searchDB($mpd, 'filepath');
break;
// - delete radio station file
case 'deleteradiostn':
if (null !== $path) {
$res = array('syscmd' => array());
$res['syscmd'][] = sysCmd("rm '" . MPD_LIB . $path . "'");
// update time stamp on files so MPD picks up the change and commits the update
$res['syscmd'][] = mpdTouchFiles();
}
break;
// - add radio station file, also used for update
case 'addradiostn':
if (null !== $path) {
$res = array('syscmd' => array());
// create new file if none exists, or open existing file for overwrite
$_file = MPD_LIB . 'WEBRADIO/' . $path . '.pls';
if (false === ($handle = fopen($_file, 'w'))) {
die('db/index.php: file create failed on '.$_file);
}
// format .pls lines
$data = '[playlist]' . "\n";
$data .= 'numberofentries=1' . "\n";
$data .= 'File1='.$_POST['url'] . "\n";
$data .= 'Title1=' . $path . "\n";
$data .= 'Length1=-1' . "\n";
$data .= 'version=2' . "\n";
// write data, close file
fwrite($handle, $data);
fclose($handle);
// reset file permissions
$res['syscmd'][] = sysCmd("chmod 777 \"" .$_file . "\"");
// update time stamp on files so MPD picks up the change and commits the update
$res['syscmd'][] = mpdTouchFiles();
}
break;
// - list contents of saved playlist
case 'listsavedpl':
if (null !== $path) {
$res = mpdListPlayList($mpd, $path);
}
break;
// - delete saved playlist
case 'deletesavedpl':
if (null !== $path) {
$res = mpdRemovePlayList($mpd, $path);
}
break;
case 'add':
if (null !== $path) {
$res = mpdQueueAdd($mpd, $path);
}
break;
case 'addplay':
if (null !== $path) {
$status = _parseStatusResponse(mpdStatus($mpd));
$pos = $status['playlistlength'] ;
mpdQueueAdd($mpd, $path);
$res = execMpdCommand($mpd, 'play '.$pos);
}
break;
case 'addreplaceplay':
if (null !== $path) {
$res = execMpdCommand($mpd, 'clear');
mpdQueueAdd($mpd, $path);
$res = execMpdCommand($mpd, 'play');
}
break;
case 'update':
if (null !== $path) {
$res = execMpdCommand($mpd, 'update "' . html_entity_decode($path) . '"');
}
break;
case 'trackremove':
if (isset($_GET['songid']) && $_GET['songid'] != '') {
$res = mpdQueueRemoveTrack($mpd,$_GET['songid']);
}
break;
// - move playlist tracks
case 'trackmove':
if (isset($_GET['songid']) && $_GET['songid'] != '') {
$_args = $_GET['songid'].' '.$_GET['newpos'];
execMpdCommand($mpd, 'move '.$_args);
$res = 'track move args= '.$_args;
}
break;
case 'savepl':
if (isset($_GET['plname']) && $_GET['plname'] != '') {
$res = execMpdCommand($mpd, 'rm "' . html_entity_decode($_GET['plname']) . '"');
$res = execMpdCommand($mpd, 'save "' . html_entity_decode($_GET['plname']) . '"');
}
break;
case 'search':
if (isset($_POST['query']) && $_POST['query'] != '' &&
isset($_GET['querytype']) && $_GET['querytype'] != '')
{
$res = searchDB($mpd,$_GET['querytype'],$_POST['query']);
}
break;
case 'loadlib':
$res = loadAllLib($mpd);
break;
case 'addall':
if (null !== $path) {
$res = mpdQueueAddMultiple($mpd, array_column($path, 'file')); // nested array
}
break;
// - added code to set the playlist song pos for play
case 'playall':
if (null !== $path) {
$status = _parseStatusResponse(mpdStatus($mpd));
$pos = $status['playlistlength'] ;
$res = mpdQueueAddMultiple($mpd, array_column($path, 'file')); // nested array
execMpdCommand($mpd, 'play ' . $pos);
}
break;
// - library panel Add/replace/playall btn
case 'addallreplaceplay':
if (null !== $path) {
execMpdCommand($mpd, 'clear');
$res = mpdQueueAddMultiple($mpd, array_column($path, 'file')); // nested array
execMpdCommand($mpd, 'play');
}
break;
case 'currentsong':
$res = _parseMpdCurrentSong(execMpdCommand($mpd, 'currentsong'));
mpdEnrichItemInfo($res);
break;
case 'playlist':
$res = mpdQueueInfo($mpd);
foreach ($res as &$song) {
mpdEnrichItemInfo($song);
}
break;
default:
// execute any mpd command
$res = execMpdCommand($mpd, $cmd);
}
closeMpdSocket($mpd);
header('Content-type: application/json');
echo json_encode($res, JSON_PRETTY_PRINT);
|
JavaScript
|
UTF-8
| 1,406
| 2.78125
| 3
|
[] |
no_license
|
const files = require("./../../utils/files");
let movies = files.loadMovies(moviesData => movies = moviesData);
function getMovies(req, res) {
res.json(movies);
}
function getMovie(id) {
return movies.find(movie => movie.id === id);
}
function getLike(req, res) {
const likeMovies = movies.filter(movie => movie.like === true);
res.json(likeMovies);
}
function postMovie(req, res) {
const movie = req.body;
movie.id = `${movies.length + 1}`;
movies.push(movie);
saveMovies(res);
}
function updateMovie(req, res) {
const movieId = req.body.id;
let moviePosition = movies.findIndex(movie => movie.id === movieId);
if (moviePosition >= 0) {
movies[moviePosition] = req.body;
}
saveMovies(res);
}
function deleteMovie(req, res) {
const movieId = req.params.id;
const moviePosition = movies.findIndex(movie => movie.id === movieId);
if (moviePosition >= 0) {
movies.splice(moviePosition, 1);
}
saveMovies(res);
}
function deleteLike(req, res) {
const movieId = req.params.id;
const movie = movies.find(movie => movie.id === movieId);
if (movie) {
movie.like = false;
}
saveMovies(res);
}
function saveMovies(res) {
files.saveMovies(movies, err => {
if (err) {
res.error(err);
} else {
res.json(movies);
}
});
}
module.exports = {getMovie, getMovies, getLike, postMovie, updateMovie, deleteMovie, deleteLike};
|
Markdown
|
UTF-8
| 3,099
| 2.6875
| 3
|
[] |
no_license
|
# hadoop hdfs missing blocks & 安全模式 - 数据之美的博客 - CSDN博客
2018年11月19日 11:31:28[看穿数据之美](https://me.csdn.net/oppo62258801)阅读数:523
近期在做磁盘有关的一些测试时,最先是发现habse出现了RIT而且还是meta表的RIT,查看hadoop,出现了hdfs missing blocks的问题,hadoop master上一上来就能看见报该问题。
```
There are 88 missing blocks. The following files may be corrupted:
blk_1076662996 /**/default/usertable/c31c955d868aa590ee08776c4e47f648/cf/e04822ace0e348e38d09b55e5124cfdc
blk_1076663064 /**/default/usertable/c31c955d868aa590ee08776c4e47f648/cf/e04822ace0e348e38d09b55e5124cfdc
blk_1076743273 /**/default/********1029_201810/bdfb0c7d8651f9ba99eaec22dc42cb13/f/afc59021d518457b9152e4a1c057fce4
blk_1076663044 /**/default/usertable/c31c955d868aa590ee08776c4e47f648/cf/e04822ace0e348e38d09b55e5124cfdc
blk_1076743287 /**/default/*****1029_201810/bdfb0c7d8651f9ba99eaec22dc42cb13/f/afc59021d518457b9152e4a1c057fce4
blk_1076663096 /**/default/usertable/c31c955d868aa590ee08776c4e47f648/cf/e04822ace0e348e38d09b55e5124cfdc
blk_1076743312 /**/default/******1029_201810/bdfb0c7d8651f9ba99eaec22dc42cb13/f/afc59021d518457b9152e4a1c057fce4
blk_1073743276
```
在网上查看了一些博客,missing block的意思是hdfs上的块不存在了,并不是少于3份,很难恢复。但是, the "blocks missing" it means that those blocks are not available in the live data nodes of the cluster, please verify any data node is down/unhealthy and bring it back - might rectify the missing blocks.
解决方案:
1. 参考 [https://stackoverflow.com/questions/19205057/how-to-fix-corrupt-hdfs-files](https://stackoverflow.com/questions/19205057/how-to-fix-corrupt-hdfs-files)
2. 参考博客的一些做法 先用 hdfs fsck / 检查missing block,再用 hdfs fsck -delete + block 可以移除 missing block
这里要注意,如果datanode丢失的数据块过多,达到一定的比例,会使得hadoop进入安全模式,也就是除了读不能进行其他任何操作,从而hbaseRS也处于有问题的状态。如果进入安全模式要先解决安全模式的问题才能使用 hdfs fsck delete。
安全模式的问题可以参考下文第三个博客链接。有两种办法:
1. hadoop dfsadmin -safemode leave命令,强制离开
2. 修改dfs.safemode.threshold.pct,缺省是0.999,修改为一个比较小的值。
此外分享给小可爱们一个我自己写的蹩脚脚本用来删除MISSING BLOCK:
```
for (( i=0; i<100; i++ ))
do
hdfs fsck / | grep 'MISSING' | head -n 1 | cut -d : -f 1 | xargs hdfs fsck -delete
done
```
效率不高,我自己用着够用了。可能有不对的地方,小可爱们水平高的发现问题自助修改哈。
参考博客:
[http://julyme.com/20180202/99.html](http://julyme.com/20180202/99.html)
[https://blog.csdn.net/slx_2011/article/details/19634473](https://blog.csdn.net/slx_2011/article/details/19634473)
[https://blog.csdn.net/hongweigg/article/details/7185328](https://blog.csdn.net/hongweigg/article/details/7185328)
|
C++
|
UTF-8
| 2,593
| 3.015625
| 3
|
[
"BSD-3-Clause"
] |
permissive
|
#ifndef __RING_H__
#define __RING_H__
namespace CTF {
/**
* \addtogroup algstrct
* @{
*/
/**
* \brief Ring class defined by a datatype and addition and multiplicaton functions
* addition must have an identity, inverse, and be associative, does not need to be commutative
* multiplications must have an identity and be distributive
*/
template <typename dtype=double, bool is_ord=CTF_int::get_default_is_ord<dtype>()>
class Ring : public Semiring<dtype, is_ord> {
public:
Ring(Ring const & other) : Semiring<dtype, is_ord>(other) { }
/**
* \brief default constructor valid for only certain types:
* bool, int, unsigned int, int64_t, uint64_t,
* float, double, std::complex<float>, std::complex<double>
*/
Ring() : Semiring<dtype, is_ord>() {
this->abs = &CTF_int::char_abs< dtype, CTF_int::default_abs<dtype, is_ord> >;
}
virtual CTF_int::algstrct * clone() const {
return new Ring<dtype, is_ord>(*this);
}
/**
* \brief constructor for algstrct equipped with * and +
* \param[in] addid_ additive identity
* \param[in] fadd_ binary addition function
* \param[in] addmop_ MPI_Op operation for addition
* \param[in] mulid_ multiplicative identity
* \param[in] fmul_ binary multiplication function
* \param[in] gemm_ block matrix multiplication function
* \param[in] axpy_ vector sum function
* \param[in] scal_ vector scale function
*/
Ring(dtype addid_,
dtype (*fadd_)(dtype a, dtype b),
MPI_Op addmop_,
dtype mulid_,
dtype (*fmul_)(dtype a, dtype b),
void (*gemm_)(char,char,int,int,int,dtype,dtype const*,dtype const*,dtype,dtype*)=NULL,
void (*axpy_)(int,dtype,dtype const*,int,dtype*,int)=NULL,
void (*scal_)(int,dtype,dtype*,int)=NULL)
: Semiring<dtype,is_ord>(addid_, fadd_, mulid_, addmop_, fmul_, gemm_, axpy_, scal_) {
abs = &CTF_int::char_abs< dtype, CTF_int::default_abs<dtype, is_ord> >;
}
//treat NULL as mulid
void safeaddinv(char const * a, char *& b) const {
if (b==NULL) b = (char*)malloc(this->el_size);
if (a == NULL){
((dtype*)b)[0] = -this->tmulid;
} else {
((dtype*)b)[0] = -((dtype*)a)[0];
}
}
void addinv(char const * a, char * b) const {
((dtype*)b)[0] = -((dtype*)a)[0];
}
};
/**
* @}
*/
}
#endif
|
Java
|
UTF-8
| 1,733
| 2.15625
| 2
|
[] |
no_license
|
package com.tech387.arch.main;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.tech387.arch.R;
import com.tech387.arch.ViewModelFactory;
import com.tech387.arch.data.Movie;
import com.tech387.arch.databinding.MainFragBinding;
public class MainFragment extends Fragment implements MainClickListener {
public static MainFragment newInstance() {
return new MainFragment();
}
private MainFragBinding mBinding;
private MainViewModel mViewModel;
private MainAdapter mAdapter;
@Nullable
@Override
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
mBinding = MainFragBinding.inflate(inflater, container, false);
mViewModel = ViewModelFactory.obtainViewModel(getActivity(), MainViewModel.class);
mViewModel.start();
mBinding.setViewModel(mViewModel);
return mBinding.getRoot();
}
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
setupAdapter();
}
private void setupAdapter() {
mAdapter = new MainAdapter(getContext(), this);
mBinding.list.setLayoutManager(new LinearLayoutManager(getContext()));
mBinding.list.setAdapter(mAdapter);
}
@Override
public void onMovieClick(View view, Movie movie) {
mViewModel.getOpenMovieEvent().setValue(movie);
}
}
|
Python
|
UTF-8
| 1,847
| 4.3125
| 4
|
[] |
no_license
|
class Node:
def __init__(self, value=None, next_node=None):
# the value at this linked list node
self.value = value
# reference to the next node in the list
self.next_node = next_node
def get_value(self):
return self.value
def get_next(self):
return self.next_node
def set_next(self, new_next):
# set this node's next_node reference to the passed in node
self.next_node = new_next
class LinkedList:
def __init__(self):
# reference to the head of the list
self.head = None
def add_to_head(self, value):
node = Node(value)
if self.head is not None:
node.set_next(self.head)
self.head = node
def contains(self, value):
if not self.head:
return False
# get a reference to the node we're currently at; update this as we traverse the list
current = self.head
# check to see if we're at a valid node
while current:
# return True if the current value we're looking at matches our target value
if current.get_value() == value:
return True
# update our current node to the current node's next node
current = current.get_next()
# if we've gotten here, then the target node isn't in our list
return False
def reverse_list(self):
"""
take last item insert to head, make next as current -----> Recursively.
"""
if not self.head:
return
current = self.head
while current:
value = current.value
current = current.get_next()
self.add_to_head(value)
# current = self.head
# value = self.tail
# self.add_to_head()
# then take the last item insert to next of head, naow make head at current
# node = Node(value).get_next()
# value = node.value
# node.add_to_head(value)
# LinkedList().add_to_head(2)
# print(Node().get_value())
|
JavaScript
|
UTF-8
| 2,578
| 2.734375
| 3
|
[] |
no_license
|
var fs = require('fs');
var exec = require('child_process').exec;
var path = require('path');
//////////////////////////////////
// ROUTES
//////////////////////////////////
module.exports = [
// Serve up index.html
{ method: 'GET',
path: '/',
config: { handler: serveIndex }
},
// Serve up png's
{ method: 'GET',
path: '/thumbs/{filename}',
handler: { directory: { path: 'thumbs'} }
},
// Provide urls for converted png's
{ method: 'POST',
path: '/upload',
config: {
payload: {
output: 'stream',
parse: true,
allow: 'multipart/form-data'
},
handler: savePdfConvertToPngsAndSendBackToClient
}
}
]
/////////////////////////////////////////
// UTILITY FUNCTIONS
////////////////////////////////////////
// Does what the name says
function savePdfConvertToPngsAndSendBackToClient(request, reply) {
var data = request.payload;
var filename = data.uploadedfile.hapi.filename
// Only accept pdf's
if(path.extname(filename) !== ".pdf") {
reply('Please submit pdf only');
return;
}
// Write pdf to '/uploads'
var fileStream = data['uploadedfile'].pipe(fs.createWriteStream('./uploads/'+filename));
fileStream.on('close', function () {
console.log('file uploaded')
var name = getFileName(filename)
// Convert pdf to png's using ImageMagick, and write the thumbnails to '/thumbs'
exec('convert '+'./uploads/'+filename+' ./thumbs/'+name+'_thumb_page.png', function (err, stdout) {
if(err){ console.log('error ',err) }
// Search thumbnail archive and respond with only the png's that have
// the same filename as the given pdf
getThumbnails('./thumbs/', filename, function (urls) {
reply(urls)
})
})
})
}
// Searches archive for thumbnails with given filename
function getThumbnails (directory,filename, callback) {
fs.readdir(directory, function (err, files) {
var urls = [];
for(var i=0; i<files.length; i++) {
if(getFileName2(files[i]) === getFileName(filename)) {
urls.push({
name: getFileName(filename),
url: 'http://localhost:8000/thumbs/'+files[i]
})
}
}
// reply(urls)
callback(urls);
})
}
// Extracts title characters from pdf filename
function getFileName (string) {
var arr = string.split('');
var i = 0;
var name = [];
while(arr[i] != ".") {
name.push(arr[i]);
i++;
}
return name.join("");
}
// Extracts title characters from thumbnail file names
function getFileName2 (string) {
var arr = string.split('_thumb');
return arr[0]
}
// Serves index.html
function serveIndex (request, reply) {
reply.file('./index.html')
}
|
Java
|
UTF-8
| 859
| 2.15625
| 2
|
[] |
no_license
|
package com.virtusa.myapp.teamg.vhelper;
import com.virtusa.myapp.teamg.model.CartLineItem;
import com.virtusa.myapp.teamg.vo.CartLineItemVO;
public class CartLineItemvHelper {
private static CartLineItemvHelper cvHelper;
private CartLineItemvHelper() {
// nothing
}
public static CartLineItemvHelper getInstance() {
if (cvHelper == null) {
cvHelper = new CartLineItemvHelper();
}
return cvHelper;
}
public CartLineItem parseCartLineItemtoCartLineEnty(CartLineItemVO cvo){
CartLineItem cart = new CartLineItem();
cart.setId(cvo.getId());
cart.setItemprice(cvo.getItemprice());
cart.setMycart(cvo.getMycart());
cart.setProduct(cvo.getProduct());
cart.setQuantitysold(cvo.getQuantitysold());
return cart;
}
}
|
Python
|
UTF-8
| 8,755
| 2.53125
| 3
|
[] |
no_license
|
from setuptools import setup
setup(name='9dt',
version='0.1',
description='players, games',
url='http://github.com/jayljohnson/9dt', ## 'http://github.com/.../...'
author='Jay L. Johnson',
author_email='jljohn00@gmail.com',
license='...',
packages=['...'],
zip_safe=False)
#Database Scripts
copy_games_date_to_s3 =
"""
# This was done manually using pdf link https://s3-us-west-2.amazonaws.com/98point6homework-assets/game_data.csv. Saved to s3://9dt-jayljohnson/games
# Unable to read the data directly from Athena DDL.
# TODO: see if the data can be read directly.
"""
athena_create_schema = """
create database dev9dt_athena;
"""
athena_create_table_players = """
CREATE EXTERNAL TABLE dev9dt_athena.players (
id int,
data struct<gender:string, name:string, `location`:string, email:string, login:string, dob:string, registered:string, phone:string, cell:string, id:string, picture:string, nat:string>
)
ROW FORMAT SERDE 'org.openx.data.jsonserde.JsonSerDe'
LOCATION 's3://9dt-jayljohnson/players/';
"""
/
athena_create_table_games = """
CREATE EXTERNAL TABLE dev9dt_athena.games (
game_id string,
player_id int,
move_number int,
`column` int,
result string)
ROW FORMAT DELIMITED
FIELDS TERMINATED BY ','
ESCAPED BY '\\'
LINES TERMINATED BY '\n'
LOCATION 's3://9dt-jayljohnson/games'
TBLPROPERTIES ("skip.header.line.count"="1");
"""
redshift_create_external_schema = """
create external schema athena_schema if not exists from data catalog
database 'dev9dt_athena'
iam_role 'arn:aws:iam::967095003863:role/dev-9dt-redshift'
region 'us-west-1'
"""
redshift_setup_and_load_initial_tables = """
create schema if not exists dev_9dt;
/*
* Limiting the data to only the attributes needed for analysis, currently 'nat' and 'email'
* Need to understand PII requirements in the data warehouse before including other attributes.
* Assumption: athena_schema.players and the S3 data store are secured to PII standards
*/
create table dev_9dt.player_d as (
select
id as player_id
, data.nat as nationality
, data.email as email
from athena_schema.players
);
/*
* Fact table with game metrics
* Assumption: Game data does not change. If new metrics are needed in the future, decide on backfill requirements at that time.
*/
create table dev_9dt.games_f as (
with
/*
* Get the player id's for players 1 & 2 on a single row for each game_id
* Get the column played by player 1 in their first move
*
* Also tried using NTH_VALUE approach below but the execution plan was much better with rownum based approach. Keeping here for reference.
* Rownum approach is more verbose, but seems easier to understand and maintain than the ROWS clause in the window function.
*
select
distinct game_id
, NTH_VALUE(player_id, 1) over (partition by game_id order by move_number ROWS BETWEEN UNBOUNDED PRECEDING AND 0 FOLLOWING) as player_1
, NTH_VALUE(player_id, 2) over (partition by game_id order by move_number ROWS BETWEEN UNBOUNDED PRECEDING AND 1 FOLLOWING) as player_2
, NTH_VALUE("column", 1) over (partition by game_id order by move_number ROWS BETWEEN UNBOUNDED PRECEDING AND 0 FOLLOWING) as first_move_column
from athena_schema.games
*/
game_players as (
with
/*
* Get the first and second player from the first two moves of each game.
*/
game_players_ordered as (
select *
from (
select
game_id
, player_id
, row_number() over (partition by game_id order by game_id, move_number) rownum
from athena_schema.games)
where rownum <= 2
)
select
gp1.game_id
, gp1.player_id as player_1
, gp2.player_id as player_2
from game_players_ordered gp1
join game_players_ordered gp2 on gp1.game_id = gp2.game_id
where gp1.rownum = 1
and gp2.rownum = 2
),
/*
* Aggregate the moves values into an ordered list for each game_id to preserve the moves data for analysis
* Get the result value of either win or draw for the game using max(). Because other values are null except for the last move, the final game status is returned.
*/
game_moves as (
select
gp.game_id
, gp.player_1
, gp.player_2
, listagg(g."column", ',') within group (order by move_number) as moves
, max("result") as game_result
from athena_schema.games g
join game_players gp on g.game_id = gp.game_id
group by
gp.game_id
, gp.player_1
, gp.player_2
),
/*
* Get the player who made the last move in the game
* If the result is 'win' the same player won the game and the other player lost the game.
* The mod 2 (% 2) function on the moves list is faster than another window function scan to get the last move for each game.
* If the number of moves in a game is an even number, player 2 had the last move. Else player 1 had the last move.
* Uses mod 2 where remainder of 0 is an even number, 1 is an odd number
*/
game_move_metrics as (
select
gm.game_id
, regexp_count(gm.moves, ',') + 1 as number_of_moves_in_game
, SPLIT_PART(gm.moves, ',',1) as first_move_column
, case (regexp_count(gm.moves, ',') + 1) % 2
when 1
then 1
else 2
end as last_move_in_game_by_player
from game_moves gm
)
select
gm.game_id
, gm.player_1
, gm.player_2
, gm.moves
, gmm.first_move_column
, gm.game_result
, gmm.number_of_moves_in_game
, case when gm.game_result = 'draw'
then -1 --If game is a draw, there is no player_id that won. Default to dummy value -1.
when gm.game_result = 'win' and gmm.last_move_in_game_by_player = 1
then player_1
else player_2
end as player_id_win
, case when gm.game_result = 'draw'
then -1 --If game is a draw, there is no player_id that lost. Default to dummy value -1.
when gm.game_result = 'win' and gmm.last_move_in_game_by_player = 1
then player_2
else player_1
end as player_id_lose
, case when gm.game_result = 'draw' and gmm.number_of_moves_in_game = 16
then true
else false
end as game_is_draw --Only games that filled the board with 16 moves should be draws. Including extra validation for this. TODO: Edge case for abandoned games?
from game_moves gm
join game_move_metrics gmm on gm.game_id = gmm.game_id
);
/*
* percentile rank metrics
*/
create or replace view dev_9dt.games_metric_first_move_percentile_rank_v as (
with win_count as (
select
first_move_column
, count(1) as win_count
from dev_9dt.games_f
where player_id_win = player_1
group by 1
)
select
first_move_column
, win_count
, percent_rank()
over (order by win_count)
from win_count
);
/*
* Games by nationality metrics
* TODO: If two people of the same nationality play in the same game, count once or twice?
* Validation: Since each game has 2 players, the number of games played by person or dimension of person is 2x the number of games in f_games
*/
create table dev_9dt.player_metric_games_played as (
/*
* Get the list of players per game from the table games_f.
* Driving this from the games_f table instead of the base table for data consistency.
* For example, reads from the base table while games_f is being loaded could give inconsistent results.
*/
with unique_players as (
select
player_1 as player_id
, game_id
from dev_9dt.games_f g
union
select player_2 as player_id
, game_id
from dev_9dt.games_f g
)
/*
* Get the count of games per player
*/
select
player_id
, count(game_id) games_played
from unique_players
group by 1);
create or replace view dev_9dt.games_metric_played_by_nationality_v as (
select
p.nationality
, sum(pgp.games_played) as games_played
from dev_9dt.player_d p
join dev_9dt.player_metric_games_played pgp on p.player_id = pgp.player_id
group by 1);
/*
* Email campaign metrics for single game players
*/
create or replace view dev_9dt.player_metric_played_single_game_v as (
select
pgp.player_id
, case when g.game_is_draw
then 'drew'
when pgp.player_id = g.player_id_win
then 'won'
when pgp.player_id = g.player_id_lose
then 'lost'
else null
end as game_status
, p.email
, p.nationality
, pgp.games_played
from dev_9dt.player_metric_games_played pgp
join dev_9dt.games_f g on (pgp.player_id = g.player_1 or pgp.player_id = g.player_2)
join dev_9dt.player_d p on pgp.player_id = p.player_id
where pgp.games_played = 1
);
"""
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.