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 |
|---|---|---|---|---|---|---|---|
PHP | UTF-8 | 818 | 2.984375 | 3 | [] | no_license | <?php
declare(strict_types = 1);
namespace Service\Discount;
class PromoCode implements IDiscount
{
/**
* @var string
*/
private string $promoCode;
/**
* @param string $promoCode
*/
public function __construct(string $promoCode)
{
$this->promoCode = $promoCode;
}
/**
* @inheritdoc
*/
public function getDiscount(): float
{
// Получаем по промокоду размер скидки на заказ в процентах
// $discount = $this->find($this->promoCode)->discount();
// Запрос в систему хранения промокодов для пометки кода как использованный
// $this->find($this->promoCode)->deactivate();
return 5.50;
}
}
|
C++ | UTF-8 | 1,097 | 2.703125 | 3 | [] | no_license |
#include <iostream>
#include <iomanip>
// #include <memory>
// #include <algorithm>
// #include <vector>
// #include <list>
// #include <unordered_map>
#include <chrono> // for high_resolution_clock
#include <eigen3/Eigen/Core>
#include <eigen3/Eigen/Eigen>
using namespace std;
using namespace std::chrono;
using namespace Eigen;
constexpr int DIM_SIZE = 160'000'000;
//typedef Array<double,10000000,1> LongArray; // Won't work - will try to allocate on stack
int main()
{
// Holy crap, this is so Ugly, really no better Eagen way to do his?
ArrayXd x = (1.0 + ArrayXd::Random(DIM_SIZE)) * 0.5;
ArrayXd y = (1.0 + ArrayXd::Random(DIM_SIZE)) * 0.5;
auto start = high_resolution_clock::now();
double v = x.cwiseProduct(y).sum(); // Srsly? no dot product for Array, invent your own?
auto finish = high_resolution_clock::now();
cout << "===============\n" << std::fixed << std::setprecision(3) << v << endl;
std::cout << "Calculation took "
<< duration_cast<milliseconds>(finish - start).count()
<< "ms.\n";
return 0;
}
|
Python | UTF-8 | 554 | 3.609375 | 4 | [
"Apache-2.0"
] | permissive | """
ATM machines allow 4 or 6 digit PIN codes and PIN codes cannot contain anything
but exactly 4 digits or exactly 6 digits.
If the function is passed a valid PIN string, return true, else return false
"""
def pin_validate(pin):
if not isinstance(pin, int):
result = 'false'
print(result)
return result
elif len(str(pin)) > 6 or len(str(pin)) < 4:
result = 'false'
print(result)
return result
else:
result = 'true'
print(result)
return result
pin_validate(123452)
|
Java | UTF-8 | 16,105 | 3.046875 | 3 | [] | no_license | package uno;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.Collections;
import java.util.Scanner;
public class Game {
public static boolean flagrev = false;
public static boolean flagskip = false;
public static boolean flagdrawtwo = false;
public static boolean flagwilddrawfour = false;
public static void main(String[] args) {
//----------------------------ascii art drawing-----------------------------------------------
int width=220;
int height=25;
BufferedImage image = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
Graphics g = image.getGraphics();
g.setFont(new Font("SansSerif",Font.PLAIN,14));
Graphics2D g2 = (Graphics2D)g;
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g2.drawString("WELCOME TO JAVA UNO GAME!", 3, 18);
//----------------------------ascii art drawing-----------------------------------------------
Scanner sc = new Scanner(System.in);
int id = 1; //to declare id for each card
int playcard; //card choice to play
int playernum = 0; //number of players
int challengeChoice = 0;
String rubbish;
boolean validPlayernum = false;
boolean validPlayeraction = false; //to validate the action for each player
//----------------------------ascii art drawing-----------------------------------------------
for(int y=0;y<height;y++)
{
StringBuilder builder = new StringBuilder();
for(int x = 0; x<width;x++){
builder.append(image.getRGB(x, y)==-16777216 ? "@" : " ");
}
System.out.println(builder);
}
//----------------------------ascii art drawing-----------------------------------------------
System.out.println("\n");
// check valid player numbers
while (validPlayernum == false) {
System.out.println("Enter the number of players(Recommended 2-4 players): ");
while (!sc.hasNextInt()) { //check for invalid input (not integers)
System.out.println("That's not a number!");
sc.nextLine();
}
playernum = sc.nextInt();
rubbish = sc.nextLine();
if (playernum >= 2 && playernum <= 4)
validPlayernum = true;
}
// prompt players' names
ArrayList<Player> players = new ArrayList<Player>();
for (int i = 0; i < playernum; i++) {
System.out.println("Enter player" + (i + 1) + " name: ");
players.add(new Player(sc.nextLine()));
}
//intializing card deck, pile deck, and player array
ArrayList<Card> deck = new ArrayList<Card>();
ArrayList<Card> pile = new ArrayList<Card>(); // empty pile
String[] symbol = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" };
String[] color = { "Red", "Yellow", "Green", "Blue" };
// initializing card deck with id
for (int i = 0; i <= 3; i++) {
deck.add(new Card(color[i], "0", id));
id++;
deck.add(new Card(color[i], "1", id));
id++;
deck.add(new Card(color[i], "2", id));
id++;
deck.add(new Card(color[i], "3", id));
id++;
deck.add(new Card(color[i], "4", id));
id++;
deck.add(new Card(color[i], "5", id));
id++;
deck.add(new Card(color[i], "6", id));
id++;
deck.add(new Card(color[i], "7", id));
id++;
deck.add(new Card(color[i], "8", id));
id++;
deck.add(new Card(color[i], "9", id));
id++;
deck.add(new Skip(color[i], "Skip", id));
id++;
deck.add(new Reverse(color[i], "Reverse", id));
id++;
deck.add(new DrawTwo(color[i], "DrawTwo", id));
id++;
}
deck.add(new Wild("No Color", "Wild", id));
id++;
deck.add(new Wild("No Color", "Wild", id));
id++;
deck.add(new WildDrawFour("No Color", "WildDrawFour", id));
id++;
deck.add(new WildDrawFour("No Color", "WildDrawFour", id));
id++;
deck.add(new CopyCat("No Color", "CopyCat", id));//self implemented action cards, copies last played card
id++;
deck.add(new CopyCat("No Color", "CopyCat", id));//can only be played on normal cards to copy their property("color" and "symbol")
id++; //wild,wild draw four,reverse,skip are special cards(not normal cards)
deck.add(new CopyCat("No Color", "CopyCat", id));
id++;
deck.add(new CopyCat("No Color", "CopyCat", id));
Collections.shuffle(deck);
pile.add(deck.remove(0));
// distribute cards to players
for (int i = 0; i < playernum; i++) {
players.get(i).addCard(deck.remove(0));
players.get(i).addCard(deck.remove(0));
players.get(i).addCard(deck.remove(0));
players.get(i).addCard(deck.remove(0));
players.get(i).addCard(deck.remove(0));
}
// ------------------AFTER GAME INITIALIZATION------------------------
boolean checkWinningCondition = false;
boolean validcardFlag = false;
int i = 0;
int choice = 0;
// ------switch case for action cards for first card drawn from
// deck------
boolean firstpilecardflag = true;
while (firstpilecardflag) {
switch (pile.get(pile.size() - 1).getSymbol()) {
case "Reverse":
pile.get(pile.size() - 1).action();
firstpilecardflag = false;
break;
case "Skip":
pile.get(pile.size() - 1).action();
firstpilecardflag = false;
break;
case "DrawTwo":
pile.get(pile.size() - 1).action();
firstpilecardflag = false;
break;
case "Wild":
System.out.println("Replacing Wild Card on top");
pile.add(deck.remove(0));
System.out.println("\n\nTOP CARD IN PILE : " + pile.get(pile.size() - 1).toString());
break;
case "WildDrawFour":
System.out.println("Replacing Wild Draw Four Card on top");
pile.add(deck.remove(0));
System.out.println("\n\nTOP CARD IN PILE : " + pile.get(pile.size() - 1).toString());
break;
case "CopyCat":
System.out.println("Replacing Copy Cat Card on top");
pile.add(deck.remove(0));
System.out.println("\n\nTOP CARD IN PILE : " + pile.get(pile.size() - 1).toString());
break;
default:
firstpilecardflag = false;
}
}
// ------switch case for action cards for first card on pile------
// normal game direction
if (flagrev == false) {
// skip function
if (flagskip == true) {
i++;
System.out.print(i);
flagskip = false;
}
if (i >= playernum)
i = i - playernum;
if (flagdrawtwo == true) {
players.get(i).addCard(deck.remove(0));
players.get(i).addCard(deck.remove(0));
System.out.println("(Draw Two action)" + players.get(i).getName() + " is skipped ");
i++;
flagdrawtwo = false;
}
// reverse game direction
} else if (flagrev == true) {
// skip function
if (flagskip == true) {
i--;
flagskip = false;
}
if (i < 0)
i = i + playernum;
}
while (checkWinningCondition == false) {
validcardFlag = false;
System.out.println(new String(new char[50]).replace("\0", "\r\n"));
// game loop
// looping back to player1
if (i >= playernum)
i = i - playernum;
// looping back to player1 in reverse direction
if (i < 0)
i = i + playernum;
System.out.println("\n\nTOP CARD IN PILE : " + pile.get(pile.size() - 1).toString());
System.out.println(players.get(i).getName() + "'s turn: ");
Collections.sort(players.get(i).getHandcard());
System.out.println("Your hand card:\n" + players.get(i).toString()); // display
// player
// card
while (validPlayeraction == false) {
System.out.println("Choose your action: 1)Play a card ");
System.out.println(" 2)Draw a card ");
while (!sc.hasNextInt()) { //check for invalid inputs(not integers)
System.out.println("That's not a number!");
sc.nextLine();
System.out.println("Choose your action: 1)Play a card ");
System.out.println(" 2)Draw a card ");
}
choice = sc.nextInt();
rubbish = sc.nextLine();
if(choice==1){
if(players.get(i).handCheck(pile.get(pile.size()-1))) //checking player's hand to check for any valid cards matching top pile
validPlayeraction = true ;
else{
System.out.println("Unplayable handcards, you must draw a card");
}
}
else
validPlayeraction = true;
}
if (choice == 1) {
// ---------------Choose card from deck--------------------
while (validcardFlag == false) { // check valid card , if true,proceed || if false, loop
// until valid
System.out.println("Enter your card to play");
while (!sc.hasNextInt()) { //check for invalid input (not integers)
System.out.println("That's not a number!");
sc.nextLine();
System.out.println("Enter your card to play");
}
playcard = sc.nextInt();
rubbish = sc.nextLine();
// playing card out of hand
if (players.get(i).playCard(playcard, pile.get(pile.size() - 1))) { // check (color or symbol and valid card choice
pile.add(players.get(i).removeCard(playcard - 1));
validcardFlag = true;
// ------switch case for action cards------
switch (pile.get(pile.size() - 1).getSymbol()) {
case "Reverse":
pile.get(pile.size() - 1).action();
break;
case "Skip":
pile.get(pile.size() - 1).action();
break;
case "DrawTwo":
pile.get(pile.size() - 1).action();
break;
case "Wild":
pile.get(pile.size() - 1).action();
break;
case "WildDrawFour":
pile.get(pile.size() - 1).action();
break;
case "CopyCat":
pile.get(pile.size()-1).setColor(pile.get(pile.size() - 2).getColor());
pile.get(pile.size()-1).setSymbol(pile.get(pile.size() - 2).getSymbol());
break;
}
// ------switch case for action cards------
if (players.get(i).getCount() == 0)
checkWinningCondition = true;
// normal game direction
if (flagrev == false) {
// skip function
if (flagskip == true) {
i++;
flagskip = false;
}
// draw two function
if (flagdrawtwo == true) {
i++;
if (i >= playernum)
i = i - playernum;
players.get(i).addCard(deck.remove(0));
players.get(i).addCard(deck.remove(0));
System.out.println(players.get(i).toString());
flagdrawtwo = false;
}
// wild draw four
if (flagwilddrawfour == true) {
i++;
if (i >= playernum)
i = i - playernum;
System.out.println(players.get(i).getName()+"'s turn");
System.out.println("1)Challenge or 2)no:");
challengeChoice = sc.nextInt();
rubbish = sc.nextLine();
if (challengeChoice == 1) {
i--;
if (i < 0)
i = i + playernum;
if (players.get(i).challengeCheck(pile.get(pile.size() - 2))) {//challenge checking
players.get(i).addCard(deck.remove(0));
players.get(i).addCard(deck.remove(0));
players.get(i).addCard(deck.remove(0));
players.get(i).addCard(deck.remove(0));
}
else {
i++;
if (i >= playernum)
i = i - playernum;
players.get(i).addCard(deck.remove(0));
players.get(i).addCard(deck.remove(0));
players.get(i).addCard(deck.remove(0));
players.get(i).addCard(deck.remove(0));
players.get(i).addCard(deck.remove(0));
players.get(i).addCard(deck.remove(0));
}
} else if (challengeChoice == 2) {
players.get(i).addCard(deck.remove(0));
players.get(i).addCard(deck.remove(0));
players.get(i).addCard(deck.remove(0));
players.get(i).addCard(deck.remove(0));
}
Collections.sort(players.get(i).getHandcard());
System.out.println(players.get(i).toString());
flagwilddrawfour = false;
}
i++; // player turn counter
}
// reverse game direction
else if (flagrev == true) {
// skip function
if (flagskip == true) {
i--;
flagskip = false;
}
// draw two function
if (flagdrawtwo == true) {
i--;
if (i < 0)
i = i + playernum;
players.get(i).addCard(deck.remove(0));
players.get(i).addCard(deck.remove(0));
System.out.println(players.get(i).toString());
flagdrawtwo = false;
}
// draw four function
if (flagwilddrawfour == true) {
i--;
if (i < 0)
i = i + playernum;
System.out.println("1)Challenge or 2)no:");
challengeChoice = sc.nextInt();
rubbish = sc.nextLine();
if (challengeChoice == 1) {
i++;
if (i >= playernum)
i = i - playernum;
if (players.get(i).challengeCheck(pile.get(pile.size() - 2))) { //challenge checking
players.get(i).addCard(deck.remove(0));
players.get(i).addCard(deck.remove(0));
players.get(i).addCard(deck.remove(0));
players.get(i).addCard(deck.remove(0));
}
else {
i--;
if (i < 0)
i = i + playernum;
players.get(i).addCard(deck.remove(0));
players.get(i).addCard(deck.remove(0));
players.get(i).addCard(deck.remove(0));
players.get(i).addCard(deck.remove(0));
players.get(i).addCard(deck.remove(0));
players.get(i).addCard(deck.remove(0));
}
} else if (challengeChoice == 2) {
players.get(i).addCard(deck.remove(0));
players.get(i).addCard(deck.remove(0));
players.get(i).addCard(deck.remove(0));
players.get(i).addCard(deck.remove(0));
}
Collections.sort(players.get(i).getHandcard());
System.out.println(players.get(i).toString());
flagwilddrawfour = false;
}
i--;
}
}
// ---------------CHoose card from deck--------------------
}
}
// ---------------------------player draws a card---------------------
else if (choice == 2) {
if (deck.isEmpty()) { //check if deck is empty , refill from pile
System.out.println("The deck is empty, refilling deck with cards from pile");
while (pile.size() > 1) {
if(pile.get(0).getId()>=57 && pile.get(0).getId()<=60){
pile.get(0).setColor("");
pile.get(0).setSymbol("CopyCat");
}
deck.add(pile.remove(0));
}
Collections.shuffle(deck);
}
players.get(i).addCard(deck.remove(0));
// ---------------------------player draws a card---------------------
}
choice = 0;
validPlayeraction = false;
}
width=180;
height=25;
BufferedImage im = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
Graphics p = im.getGraphics();
p.setFont(new Font("SansSerif",Font.BOLD,24));
Graphics2D p2 = (Graphics2D)p;
p2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
p2.drawString("UNO GAME!", 25, 21);
//----------------------------ascii art drawing-----------------------------------------------
for(int y=0;y<height;y++)
{
StringBuilder builder = new StringBuilder();
for(int x = 0; x<width;x++){
builder.append(im.getRGB(x, y)==-16777216 ? "@" : " ");
}
System.out.println(builder);
}
//----------------------------ascii art drawing-----------------------------------------------
System.out.println("\n\n");
System.out.println("\n\n"+players.get(i).getName() + " won!");
}
}
|
Java | UTF-8 | 676 | 2.015625 | 2 | [] | no_license | package com.springclass.boot.domain;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.rest.core.annotation.RepositoryRestResource;
@RepositoryRestResource
public interface UserRepository extends CrudRepository<User, Long> {
// Select u from User u WHERE u.firstName == 'Mick'
User findUserByFirstName(String firstName);
User findUserByFirstNameAndLastName(String firstName, String lastName);
// User findUserByLastName(String lastName);
//
// User findUserByFirstNameAndLastName(String fName, String lName);
//
Boolean existsByFirstName(String firstName);
Boolean existsByLastName(String lastName);
} |
Markdown | UTF-8 | 767 | 2.90625 | 3 | [] | no_license | # API Documentation
## Create
`Post /classroom/create`
## Delete
`Post /classroom/:id/delete`
** Note: Should only archive classroom.
## Graduate Classroom
`Post /classroom/:id/graduate
Parameters (JSON):
* `grade: <int>` Where, grade can be `1-6`.
If `6` is specificed, the classroom is archived and removed from the class
list.
## Get Classroom Info
`Get /classroom/:id`
Returns (JSON Object):
{'specialist': [<Specialist Object>],
'teacher': [<Teacher Object>],
'student': [<Student Object>],
'grade': <int>}
## List Student(s)
`Get /classroom/:id/students
## List Teacher(s)
`Get /classroom/:id/instructors
## List Specialist(s)
`Get /classroom/:id/specialists
** Note For description on teacher/specialist/etc. objects, see root README
|
Python | UTF-8 | 7,144 | 2.953125 | 3 | [] | no_license |
import nltk
from nltk.corpus import brown
from nltk.corpus import gutenberg
import re
class PredictorModel:
def __init__(self):
'void constructor'
self.initialization()
def initialization(self):
'initialize the model'
corpusName = 'emma'
genre = 'news'
corpus = self.getCorpus(corpusName,genre)
tagged_corpus = self.getCorpus(corpusName,genre,tagged=True)
# n-gram frequency distributions
self.trigrams = nltk.trigrams(tagged_corpus)
self.tricfd = nltk.ConditionalFreqDist()
self.trifd = nltk.FreqDist()
self.postrifreq = nltk.ConditionalFreqDist()
for ((word2,tag2),(word1,tag1),(word0,tag0)) in self.trigrams:
self.tricfd[word2,word1][word0] += 1
self.trifd[(word2,word1,word0)] += 1
self.postrifreq[tag2,tag1][tag0] += 1
self.bicfd = nltk.ConditionalFreqDist(nltk.bigrams(corpus))
self.bifd = nltk.FreqDist(nltk.bigrams(corpus))
self.unifd = nltk.FreqDist(corpus)
self.taggedFreq= nltk.FreqDist(tagged_corpus)
# n-gram probability distributions
self.tricpd = nltk.ConditionalProbDist(self.tricfd,nltk.ELEProbDist)
self.tripd = nltk.ELEProbDist(self.trifd)
self.bicpd = nltk.ConditionalProbDist(self.bicfd,nltk.ELEProbDist)
self.bipd = nltk.ELEProbDist(self.bifd)
self.unipd = nltk.ELEProbDist(self.unifd)
# POS n-gram
self.postriprob = nltk.ConditionalProbDist(self.postrifreq,nltk.ELEProbDist)
def getCorpus(self,corpus,genre='',tagged=False):
if corpus=='brown':
if tagged:
return brown.tagged_words(categories=genre,tagset='universal')
else:
return brown.words(categories=genre)
if corpus=='emma':
words = gutenberg.words('shakespeare-all.txt')
if tagged:
return self.tokensFromFile(corpus+"_tag"+".dat")
else:
return words
def linearGuess(self,alpha=0.8,beta=0.15,gamma=0.05):
word = ''
best = 0
for x in self.unipd.samples():
if(x.startswith(self.chars)):
try:
tri = self.tricpd[self.word2,self.word1].prob(x)
except:
tri = self.tripd.prob((self.word2,self.word1,x))
try:
bi = self.bicpd[self.word1].prob(x)
except:
bi = self.bipd.prob((self.word2,x))
tmp = alpha*tri + beta*bi + gamma*self.unipd.prob(x)
if(tmp>best):
best = tmp
word = x
return word
def posGuess(self):
alpha = 0.5
beta = 0.5
best = 0
guess = ''
for (word,tag) in self.taggedFreq:
if(word.startswith(self.chars)):
try:
bi = self.bicpd[self.word1].prob(word)
except:
bi = self.bipd.prob((self.word1,word))
try:
tri = self.postriprob[self.tag2,self.tag1].prob(tag)
except:
tri = 0
tmp = alpha*bi + beta*tri
if(tmp>best):
best = tmp
guess = word
return guess
def getBackoffGuess(self):
guess = ''
try:
guess = self.getFreqGuess(self.tricfd[self.word2,self.word1])
print("Backoff Trigram")
except ValueError:
try:
guess = self.getFreqGuess(self.bicfd[self.word1])
print("Backoff Bigram")
except ValueError:
try:
guess = self.getFreqGuess()
print("Backoff Unigram")
except ValueError:
print("Backoff No matches")
return guess
def toFile(self,obj, fileName):
output = open(fileName,'w')
for x in obj:
output.write(str(x)+" ")
output.close()
def tokensFromFile(self,file):
inputm = open(file,'r')
reg1 = "'[A-Za-z,.]+', '[A-Za-z,.]+'"
reg2 = "[A-Za-z,.]+"
tups = re.findall(reg1,inputm.read())
listm =[]
for tup in tups:
x = re.findall(reg2,tup)
listm.append((x[0],x[2]))
return listm
def getFreqGuess(self,freqd):
guess = None
if(self.chars==""):
guess = freqd.max()
else:
for w in freqd.most_common(len(freqd)):
if w[0].startswith(self.chars):
guess = w[0];
if guess==None:
raise ValueError
return guess
def getPrediction(self,inputStr):
t = nltk.pos_tag(nltk.word_tokenize(inputStr),'universal')
l = len(t)
print(t)
if(inputStr.endswith(" ")):
self.word2 = t[l-2][0]
self.word1 = t[l-1][0]
self.tag2 = t[l-2][1]
self.tag1 = t[l-1][1]
self.chars = ""
else:
self.word2 = t[l-3][0]
self.word1 = t[l-2][0]
self.tag2 = t[l-3][1]
self.tag1 = t[l-2][1]
self.chars = t[l-1][0]
print(inputStr)
backoff=self.getBackoffGuess()
linear=self.linearGuess()
posguess=self.posGuess()
return (backoff,linear,posguess)
def testModel(self):
'test the accuracy of the model'
try:
fp = open('test.txt','r')
testStrng = fp.read()
fp.close()
tokens = nltk.word_tokenize(testStrng)
tlen = len(tokens)
alphas = 0.6
alphasp = 0.05
alphae = 0.9
alphan = (alphae-alphas)/alphasp
for ai in range(int(alphan)+1):
alpha = alphas+ai*alphasp
betas = 0.05
betasp = 0.05
betae = 0.95 - alpha
betan = (betae-betas)/betasp
for bi in range(int(betan+0.5)+1):
beta = betas+bi*betasp
gamma = 1-alpha-beta
sum = 0
for i in range(tlen-2):
self.word1 = tokens[i]
self.word2 = tokens[i+1]
self.chars = ""
predict = self.linearGuess()
if (predict == tokens[i+2]):
print(i,' ',self.word1,' ',self.word2,' ',predict)
sum += 1
print(alpha,'' ,beta,' ',gamma,' ',sum)
print(sum/(tlen-2))
except Exception:
print('ERROR')
|
PHP | UTF-8 | 1,695 | 2.765625 | 3 | [] | no_license | <?php
/**
* The declaration of MCL_TEMPLATE_IMAGE class.
*
*/
class MCL_TEMPLATE_IMAGE extends MCL_TEMPLATE {
/**
* Class data members.
*/
/**
* @see MCL_TEMPLATE::__construct()
*/
public function __construct($details = array()) {
$details['template_type'] = 'IMAGE';
parent::__construct($details);
}
/**
* @see MCL_TEMPLATE::byKey()
*/
public static function byKey($keys) {
$parent = parent::byKey($keys);
if ($parent) {
return new self($parent->getMemberArr());
}
}
/**
* @see MCL_TEMPLATE::defineDescription()
*/
public function defineDescription() {
$desc = 'The description for field book sheet';
return $desc;
}
/**
* @see MCL_TEMPLATE::defineHeaders()
*/
public function defineHeaders() {
$headers = array(
'file_name' => array('req' => TRUE,'width' => 10, 'desc' => "Name of the image file."),
'image_type' => array('req' => TRUE,'width' => 10, 'desc' => "The type of the image file."),
'file_legend' => array('req' => TRUE,'width' => 10, 'desc' => "Legend of the image file."),
'comments' => array('req' => TRUE,'width' => 10, 'desc' => "Any comments for the image file."),
);
return $headers;
}
/**
* @see MCL_TEMPLATE::defineCvterms()
*/
public function defineCvterms() {
$cvterms = array();
$cvterms['SITE_CV']['photo_provider'] = -1;
$cvterms['SITE_CV']['legend'] = -1;
return $cvterms;
}
/**
* @see MCL_TEMPLATE::runErrorCheckDataLine()
*/
public function runErrorCheckDataLine($line) {
}
/**
* @see MCL_TEMPLATE::uploadDataLine()
*/
public function uploadDataLine($line) {
}
} |
Java | UTF-8 | 7,705 | 2.265625 | 2 | [
"Apache-2.0"
] | permissive | /**
* $Id: MappedFileQueueTest.java 1831 2013-05-16 01:39:51Z shijia.wxr $
*/
package com.alibaba.rocketmq.store;
import org.junit.*;
import static org.junit.Assert.*;
public class MappedFileQueueTest {
// private static final String StoreMessage =
// "Once, there was a chance for me! but I did not treasure it. if";
@BeforeClass
public static void setUpBeforeClass() throws Exception {
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void test_getLastMappedFile() {
final String fixedMsg = "0123456789abcdef";
System.out.println("================================================================");
AllocateMappedFileService allocateMappedFileService = new AllocateMappedFileService();
allocateMappedFileService.start();
MappedFileQueue mappedFileQueue =
new MappedFileQueue("./unit_test_store/a/", 1024, allocateMappedFileService);
for (int i = 0; i < 1024; i++) {
MappedFile mappedFile = mappedFileQueue.getLastMappedFile();
assertTrue(mappedFile != null);
boolean result = mappedFile.appendMessage(fixedMsg.getBytes());
if (!result) {
System.out.println("appendMessage " + i);
}
assertTrue(result);
}
mappedFileQueue.shutdown(1000);
mappedFileQueue.destroy();
allocateMappedFileService.shutdown();
System.out.println("MappedFileQueue.getLastMappedFile() OK");
}
@Test
public void test_findMappedFileByOffset() {
final String fixedMsg = "abcd";
System.out.println("================================================================");
AllocateMappedFileService allocateMappedFileService = new AllocateMappedFileService();
allocateMappedFileService.start();
MappedFileQueue mappedFileQueue =
new MappedFileQueue("./unit_test_store/b/", 1024, allocateMappedFileService);
for (int i = 0; i < 1024; i++) {
MappedFile mappedFile = mappedFileQueue.getLastMappedFile();
assertTrue(mappedFile != null);
boolean result = mappedFile.appendMessage(fixedMsg.getBytes());
// System.out.println("appendMessage " + bytes);
assertTrue(result);
}
MappedFile mappedFile = mappedFileQueue.findMappedFileByOffset(0);
assertTrue(mappedFile != null);
assertEquals(mappedFile.getFileFromOffset(), 0);
System.out.println(mappedFile.getFileFromOffset());
mappedFile = mappedFileQueue.findMappedFileByOffset(100);
assertTrue(mappedFile != null);
assertEquals(mappedFile.getFileFromOffset(), 0);
System.out.println(mappedFile.getFileFromOffset());
mappedFile = mappedFileQueue.findMappedFileByOffset(1024);
assertTrue(mappedFile != null);
assertEquals(mappedFile.getFileFromOffset(), 1024);
System.out.println(mappedFile.getFileFromOffset());
mappedFile = mappedFileQueue.findMappedFileByOffset(1024 + 100);
assertTrue(mappedFile != null);
assertEquals(mappedFile.getFileFromOffset(), 1024);
System.out.println(mappedFile.getFileFromOffset());
mappedFile = mappedFileQueue.findMappedFileByOffset(1024 * 2);
assertTrue(mappedFile != null);
assertEquals(mappedFile.getFileFromOffset(), 1024 * 2);
System.out.println(mappedFile.getFileFromOffset());
mappedFile = mappedFileQueue.findMappedFileByOffset(1024 * 2 + 100);
assertTrue(mappedFile != null);
assertEquals(mappedFile.getFileFromOffset(), 1024 * 2);
System.out.println(mappedFile.getFileFromOffset());
mappedFile = mappedFileQueue.findMappedFileByOffset(1024 * 4);
assertTrue(mappedFile == null);
mappedFile = mappedFileQueue.findMappedFileByOffset(1024 * 4 + 100);
assertTrue(mappedFile == null);
mappedFileQueue.shutdown(1000);
mappedFileQueue.destroy();
allocateMappedFileService.shutdown();
System.out.println("MappedFileQueue.findMappedFileByOffset() OK");
}
@Test
public void test_commit() {
final String fixedMsg = "0123456789abcdef";
System.out.println("================================================================");
AllocateMappedFileService allocateMappedFileService = new AllocateMappedFileService();
allocateMappedFileService.start();
MappedFileQueue mappedFileQueue =
new MappedFileQueue("./unit_test_store/c/", 1024, allocateMappedFileService);
for (int i = 0; i < 1024; i++) {
MappedFile mappedFile = mappedFileQueue.getLastMappedFile();
assertTrue(mappedFile != null);
boolean result = mappedFile.appendMessage(fixedMsg.getBytes());
assertTrue(result);
}
// 不断尝试提交
boolean result = mappedFileQueue.commit(0);
assertFalse(result);
assertEquals(1024 * 1, mappedFileQueue.getCommittedWhere());
System.out.println("1 " + result + " " + mappedFileQueue.getCommittedWhere());
result = mappedFileQueue.commit(0);
assertFalse(result);
assertEquals(1024 * 2, mappedFileQueue.getCommittedWhere());
System.out.println("2 " + result + " " + mappedFileQueue.getCommittedWhere());
result = mappedFileQueue.commit(0);
assertFalse(result);
assertEquals(1024 * 3, mappedFileQueue.getCommittedWhere());
System.out.println("3 " + result + " " + mappedFileQueue.getCommittedWhere());
result = mappedFileQueue.commit(0);
assertFalse(result);
assertEquals(1024 * 4, mappedFileQueue.getCommittedWhere());
System.out.println("4 " + result + " " + mappedFileQueue.getCommittedWhere());
result = mappedFileQueue.commit(0);
assertFalse(result);
assertEquals(1024 * 5, mappedFileQueue.getCommittedWhere());
System.out.println("5 " + result + " " + mappedFileQueue.getCommittedWhere());
result = mappedFileQueue.commit(0);
assertFalse(result);
assertEquals(1024 * 6, mappedFileQueue.getCommittedWhere());
System.out.println("6 " + result + " " + mappedFileQueue.getCommittedWhere());
mappedFileQueue.shutdown(1000);
mappedFileQueue.destroy();
allocateMappedFileService.shutdown();
System.out.println("MappedFileQueue.commit() OK");
}
@Test
public void test_getMappedMemorySize() {
final String fixedMsg = "abcd";
System.out.println("================================================================");
AllocateMappedFileService allocateMappedFileService = new AllocateMappedFileService();
allocateMappedFileService.start();
MappedFileQueue mappedFileQueue =
new MappedFileQueue("./unit_test_store/d/", 1024, allocateMappedFileService);
for (int i = 0; i < 1024; i++) {
MappedFile mappedFile = mappedFileQueue.getLastMappedFile();
assertTrue(mappedFile != null);
boolean result = mappedFile.appendMessage(fixedMsg.getBytes());
assertTrue(result);
}
assertEquals(fixedMsg.length() * 1024, mappedFileQueue.getMappedMemorySize());
mappedFileQueue.shutdown(1000);
mappedFileQueue.destroy();
allocateMappedFileService.shutdown();
System.out.println("MappedFileQueue.getMappedMemorySize() OK");
}
}
|
C# | UTF-8 | 556 | 2.546875 | 3 | [] | no_license | using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Questionnaire : ScriptableObject
{
public List<AskItem> items;
public Dictionary<int, AskItem> dicItem = new Dictionary<int, AskItem>();
public Dictionary<int, AskItem> GetItems()
{
dicItem.Clear();
for (int i = 0; i < items.Count; i++)
{
dicItem.Add(i, items[i]);
}
return dicItem;
}
}
[System.Serializable]
public class AskItem
{
public string problem;
public string answer;
}
|
C++ | UTF-8 | 1,461 | 3.078125 | 3 | [] | no_license | // Copyright (c) 2017 Recluse Project. All rights reserved.
#pragma once
#include "Core/Types.hpp"
#include "Core/Exception.hpp"
namespace Recluse {
// Smart pointer, with the minimal needed features.
// TODO(): Will need to add additional alloc component later.
// Objects must have a defined move constructor for this APtr to
// work properly.
template<typename T>
class APtr {
public:
APtr()
: mObject(nullptr) { }
template<typename I>
APtr(I&& obj)
: mObject(new I(std::move(obj))) { }
APtr(APtr&& ptr)
: mObject(ptr.mObject)
{
ptr.mObject = nullptr;
}
~APtr()
{
cleanUp();
R_ASSERT(!mObject, "Object did not destroy prior to APtr destruction! Memory Leak!\n");
}
APtr& operator=(APtr&& ptr)
{
cleanUp();
mObject = ptr.mObject;
ptr.mObject = nullptr;
return (*this);
}
template<typename I>
APtr& operator=(I&& obj)
{
cleanUp();
mObject = new I(std::move(obj));
return (*this);
}
T* operator->()
{
return Ptr();
}
T& operator*()
{
return *mObject;
}
T* Ptr()
{
return mObject;
}
void cleanUp()
{
if (mObject)
{
delete mObject;
mObject = nullptr;
}
}
void Refresh(T&& obj)
{
cleanUp();
mObject = new T(obj);
}
void DeepCopy(const APtr& ptr) {
cleanUp();
mObject = new T(ptr.mObject);
}
private:
T* mObject;
};
} // Recluse |
Java | UTF-8 | 5,062 | 1.726563 | 2 | [] | no_license | package com.example.renewseviceqq;
import android.content.Context;
import android.content.Intent;
import android.text.format.DateFormat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;
import androidx.recyclerview.widget.RecyclerView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.firestore.FirebaseFirestore;
import java.util.Date;
import java.util.List;
import de.hdodenhof.circleimageview.CircleImageView;
public class SearchPostAdapter extends RecyclerView.Adapter<SearchPostAdapter.ViewHolder> {
public List<BlogPost> SearchPostList;
FragmentActivity activity;
public Context mContext;
private FirebaseFirestore firebaseFirestore;
private FirebaseAuth mAuth;
public SearchPostAdapter(FragmentActivity activity, List<BlogPost> SearchPostList){
this.SearchPostList = SearchPostList;
this.activity = activity;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_searchpost, parent, false);
mContext = parent.getContext();
firebaseFirestore = FirebaseFirestore.getInstance();
mAuth = FirebaseAuth.getInstance();
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
String image = SearchPostList.get(position).getImage();
holder.setSearchImageView(image);
String user_id = SearchPostList.get(position).getUser_id();
String topic = SearchPostList.get(position).getTopic();
holder.setSearchTopic(topic);
String spinner = SearchPostList.get(position).getAddress();
holder.setSearchProvide(spinner);
}
@Override
public int getItemCount() {
return SearchPostList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder {
private View mView;
private ImageView SearchImageView;
private TextView SearchTopic, SearchProvide;
public ViewHolder(@NonNull View itemView) {
super(itemView);
mView = itemView;
itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent postDetailActivity = new Intent(mContext, PostDetailActivity.class);
int position = getAdapterPosition();
postDetailActivity.putExtra("userId", SearchPostList.get(position).getUser_id());
postDetailActivity.putExtra("title", SearchPostList.get(position).getTopic());
postDetailActivity.putExtra("ToolbarTitle", SearchPostList.get(position).getTopic());
postDetailActivity.putExtra("postImage", SearchPostList.get(position).getImage());
postDetailActivity.putExtra("description", SearchPostList.get(position).getDesc());
postDetailActivity.putExtra("budget", SearchPostList.get(position).getBudget());
postDetailActivity.putExtra("address", SearchPostList.get(position).getAddress());
long timestamp = (long) SearchPostList.get(position).getTimestamp().getTime();
postDetailActivity.putExtra("postDate", timestamp);
postDetailActivity.putExtra("category", SearchPostList.get(position).getCategory());
postDetailActivity.putExtra("phone", SearchPostList.get(position).getPhone());
postDetailActivity.putExtra("postid", SearchPostList.get(position).getPostid());
postDetailActivity.putExtra("userPhoto", SearchPostList.get(position).getUserPhoto());
postDetailActivity.putExtra("userName", SearchPostList.get(position).getUserName());
mContext.startActivity(postDetailActivity);
}
});
}
public void setSearchImageView(String downloadUri){
SearchImageView = mView.findViewById(R.id.Post_Img);
RequestOptions requestOptions = new RequestOptions();
requestOptions.placeholder(R.mipmap.ic_launcher);
Glide.with(mContext).applyDefaultRequestOptions(requestOptions).load(downloadUri).thumbnail(
).into(SearchImageView);
}
public void setSearchTopic(String topicText){
SearchTopic = mView.findViewById(R.id.SearchPost_Title);
SearchTopic.setText(topicText);
}
public void setSearchProvide(String spinnerText){
SearchProvide = mView.findViewById(R.id.Post_provice);
SearchProvide.setText(spinnerText);
}
}
}
|
Java | UTF-8 | 282 | 1.789063 | 2 | [] | no_license | package org.oporaua.localelections.tvk;
import java.util.List;
import retrofit2.http.GET;
import retrofit2.http.Query;
import rx.Observable;
public interface TvkService {
@GET("/search/index.json")
Observable<List<TvkMember>> loadTvkMembers(@Query("q") String name);
}
|
Markdown | UTF-8 | 2,859 | 2.84375 | 3 | [] | no_license | ### 常用命令:
1.mkdir -p /test/one,递归创建目录
2.\cp 或者 /bin/cp,复制,且同名文件不提示覆盖
cp,mv,rm,这三个命令,~/.bashrc将其命名了别名:alias cp=cp -i,-i表示同名文件覆盖时,提示。
因此如果不想提示,则不要调用别名就行:、\屏蔽别名,/bin/cp全路径,不调用别名
3.alias:查看所有别名,alias mv = 'mv -i',设置别名,unalias mv:删除别名,
永久设置别名:全局修改/etc/bashrc,用户级修改:~/bashrc
4.环境变量:$LANG,可设置语言
5.tree,目录树结构
6.seq [选项] 首数 增量 尾数,显示序列
seq 首数字 尾数,
seq 尾数,
seq [选项] 首数 增量 尾数
7.文件共有100行,打印文件中20至30行
1.head 30 filename | tail 11
2.sed -n '20,30' p filename
3.awk 'NR>19&&NR<31' tow.txt
### 常用符号
1.;,用来分割命令
2.{},表示序列,
echo {1..10},会输出:1 2 3 4 5 6 7 8 9 10
mddir /test/{aaa,bbb}/123,会创建:/test/aaa/123和/test/bbb/123
3.!,调用执行过的命令:
!m,查找以前执行过的以m开头的命令、
!!,打印上一条执行的命令
!数字,打印执行的第N条命令
!,还可以取反,取交集,取并集
### 常用快捷键
1.ctrl+c
2.ctrl+l,清屏,=clear
3.ctrl+d,退出当前用户,=exit,=logout
### 查看命令的帮助
1.man [命令],适用一般的命令
2.[命令] --help,适用一般命令
3.help [命令],适用内置命令
### 常用命令25个
1.mkdir 1
2.touch:修改文件的访问,修改,等时间,如果文件不存在,则创建一个空文件
-a,只修改访问时间
-c,--no-create,不创建新文件
-d,--date=STRING,解析STRING并且将时间修改成它
-f,废弃了
-h --no-dereference 将符号链接的时间修改成它关联的文件的时间,(只在可以修改符号连接的时间戳的系统中有效)
-m,只修改改动时间
-r --reference=FILE,用FILE文件的时间值替换当前时间
-t STAMP,使用此格式:[[CC]YY]MMDDhhmm[.ss]的字符串替换当前时间
--time=WORD,修改指定的时间:当WORD为access,atime,use,等价于 -a
当WORD为modify,mtime,等价于-m
--help
--version
3.ls
4.cd
5.echo
6.cp
7.vi
8.head
9.rm
10.cat
11.rmdir
12.grep
13.find,阅读至第二页,35行开始
14.sed
15.alias
16.unalias
17.xargs
18.awk
19.seq
20.pwd
21.tree
22.tr
23.tail
24.vim
25.mv |
C# | UTF-8 | 447 | 2.65625 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Text;
namespace SudokuQuickSolver1_5
{
class Assignment
{
public Assignment(int inCellColumn, int inCellRow, int inValueToAssign)
{
CellColumn = inCellColumn;
CellRow = inCellRow;
ValueToAssign = inValueToAssign;
}
public int CellRow;
public int CellColumn;
public int ValueToAssign;
}
}
|
Python | UTF-8 | 275 | 3.046875 | 3 | [] | no_license | class Solution(object):
def isAnagram(self, s, t):
arr=[0]*256
for i in s:
arr[ord(i)]+=1
for j in t:
arr[ord(j)]-=1
for i in range(0,256):
if arr[i]!=0:
return False
return True |
Python | UTF-8 | 1,273 | 4.15625 | 4 | [] | no_license | # -*- coding: utf-8 -*-
# (if/elif/else)
# По номеру месяца вывести кол-во дней в нем (без указания названия месяца, в феврале 28 дней)
# Результат проверки вывести на консоль
# Если номер месяца некорректен - сообщить об этом
# Номер месяца получать от пользователя следующим образом
user_input = input('Введите, пожалуйста, номер месяца: ')
if user_input.isdigit():
month = int(user_input)
print('Вы ввели', month)
thirtyone_days = [1, 3, 5, 7, 8, 10, 12]
thirty_days = [4, 6, 9, 11]
if month in thirty_days:
print('В этом месяце 30 дней')
elif month in thirtyone_days:
print('В этом месяце 31 день')
elif month == 2:
print('В этом месяце 28 дней')
else:
print('Введен неверный номер месяца')
else:
print('Пожалуйста, введите целое число')
# в целом отличный подход! То, что и нужно по заданию!
# Спасибо! )
# зачёт! 🚀
|
Java | UTF-8 | 3,827 | 2.03125 | 2 | [
"MIT"
] | permissive | package com.qxcmp.message;
import com.aliyun.mns.client.CloudAccount;
import com.aliyun.mns.client.CloudTopic;
import com.aliyun.mns.common.ServiceException;
import com.aliyun.mns.model.BatchSmsAttributes;
import com.aliyun.mns.model.MessageAttributes;
import com.aliyun.mns.model.RawTopicMessage;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Maps;
import com.qxcmp.config.SystemConfigService;
import com.qxcmp.core.QxcmpSystemConfigConfiguration;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
@Service
public class SmsServiceImpl implements SmsService {
private SystemConfigService systemConfigService;
private String accessKey;
private String accessSecret;
private String endPoint;
private String topicRef;
private String sign;
private String captchaTemplateCode;
public SmsServiceImpl(SystemConfigService systemConfigService) {
this.systemConfigService = systemConfigService;
config();
}
@Override
public void send(List<String> phones, String templateCode, Consumer<Map<String, String>> consumer) throws ServiceException {
Map<String, String> parameters = Maps.newLinkedHashMap();
consumer.accept(parameters);
CloudAccount cloudAccount = new CloudAccount(accessKey, accessSecret, endPoint);
CloudTopic topic = cloudAccount.getMNSClient().getTopicRef(topicRef);
RawTopicMessage topicMessage = new RawTopicMessage();
topicMessage.setMessageBody("清醒内容管理平台");
MessageAttributes messageAttributes = new MessageAttributes();
BatchSmsAttributes batchSmsAttributes = new BatchSmsAttributes();
batchSmsAttributes.setFreeSignName(sign);
batchSmsAttributes.setTemplateCode(templateCode);
BatchSmsAttributes.SmsReceiverParams smsReceiverParams = new BatchSmsAttributes.SmsReceiverParams();
parameters.forEach(smsReceiverParams::setParam);
phones.forEach(phone -> batchSmsAttributes.addSmsReceiver(phone, smsReceiverParams));
messageAttributes.setBatchSmsAttributes(batchSmsAttributes);
topic.publishMessage(topicMessage, messageAttributes);
}
@Override
public void sendCaptcha(String phone, String captcha) throws ServiceException {
send(ImmutableList.of(phone), captchaTemplateCode, stringStringMap -> stringStringMap.put("captcha", captcha));
}
@Override
public void config() {
accessKey = systemConfigService.getString(QxcmpSystemConfigConfiguration.SYSTEM_CONFIG_MESSAGE_SMS_ACCESS_KEY).orElse(QxcmpSystemConfigConfiguration.SYSTEM_CONFIG_MESSAGE_SMS_ACCESS_KEY_DEFAULT_VALUE);
accessSecret = systemConfigService.getString(QxcmpSystemConfigConfiguration.SYSTEM_CONFIG_MESSAGE_SMS_ACCESS_SECRET).orElse(QxcmpSystemConfigConfiguration.SYSTEM_CONFIG_MESSAGE_SMS_ACCESS_SECRET_DEFAULT_VALUE);
endPoint = systemConfigService.getString(QxcmpSystemConfigConfiguration.SYSTEM_CONFIG_MESSAGE_SMS_END_POINT).orElse(QxcmpSystemConfigConfiguration.SYSTEM_CONFIG_MESSAGE_SMS_END_POINT_DEFAULT_VALUE);
topicRef = systemConfigService.getString(QxcmpSystemConfigConfiguration.SYSTEM_CONFIG_MESSAGE_SMS_TOPIC_REF).orElse(QxcmpSystemConfigConfiguration.SYSTEM_CONFIG_MESSAGE_SMS_TOPIC_REF_DEFAULT_VALUE);
sign = systemConfigService.getString(QxcmpSystemConfigConfiguration.SYSTEM_CONFIG_MESSAGE_SMS_SIGN).orElse(QxcmpSystemConfigConfiguration.SYSTEM_CONFIG_MESSAGE_SMS_SIGN_DEFAULT_VALUE);
captchaTemplateCode = systemConfigService.getString(QxcmpSystemConfigConfiguration.SYSTEM_CONFIG_MESSAGE_SMS_CAPTCHA_TEMPLATE_CODE).orElse(QxcmpSystemConfigConfiguration.SYSTEM_CONFIG_MESSAGE_SMS_CAPTCHA_TEMPLATE_CODE_DEFAULT_VALUE);
}
}
|
Python | UTF-8 | 1,862 | 4.78125 | 5 | [] | no_license | # - - - List comprehension - - -
# Väldigt ofta vill man ta en lista och göra något med alla element i listan
# Så som vi lärt oss hittils skulle detta se ut som
values = [1, 2, 3, 4, 5, 6, 7, 8, 9]
newValues = []
for value in values:
newValues.append(value * 2)
# Python erbjuder dock något som heter list comprehension,
# med detta blir ovanstående kod
values = [1, 2, 3, 4, 5, 6, 7, 8, 9]
newValues = [value**2 for value in values]
# När man skapar en lista med list comprehension kan man även filtrera listan
# genom att sätta en if-sats i slutet
values = [-3, -2, -1, 0, 1, 2, 3]
newValues = [1/value for value in values if value != 0]
# - - - Lambdas - - -
# Ni har sett att funktioner i python är precis som andra variable
# Man kan binda dem till namn
def square(x):
return x**2
newNameForSameFunction = square
print(newNameForSameFunction(2) == 4) # True
# Och man kan skicka dem som argument till andra funktioner
def doTwice(f, x):
return f(f(x))
print(doTwice(square, 2)) # 16 ty det är (2^2)^2
# Om vi vill skicka en mycket enkel funktion till en annan funktion är
# det omständigt att skriva def functionName(arg1, arg2): osv
# Istället kan vi använda lambda
# lambda x: x**2 är en funktion som tar ett argument
# och returnerar det till höger om :
print(doTwice(lambda x: x**2, 2)) # 16
print(doTwice(lambda x: x * 5, 2)) # 50
# Om vi sätter samman dessa (jag vet dock inte varför vi någonsin skulle vilja
# göra detta, men python gör det möjligt :) får vi detta
# listOfFunctions = [(lambda x: x**n) for n in range(3) if n % 2 == 0]
listOfFunctions = [(lambda x: x**n) for n in range(3)]
# En lista med funktioner som upphöjer en siffra till jämna tal.
# Låt oss använda denna för att hitta jämna potenser av 2
print([f(2) for f in listOfFunctions])
# Funkar inte???
|
C | UTF-8 | 327 | 3.171875 | 3 | [] | no_license | #include <stdio.h>
#include <stdlib.h>
/* for uintptr_t */
#include <inttypes.h>
int func(char c, int *i) {
printf("pointer: %p, value=%d\n", i, i ? *i : -1);
return (int)c;
}
int main(int argc, char **argv) {
uintptr_t v = func;
int c = ( (int (*)(char, int*)) v )('a', &argc);
printf("Ret: %d\n", c);
return 0;
}
|
C | UTF-8 | 200 | 2.5625 | 3 | [] | no_license | #include"my_string.h"
//#include<stdio.h>
int main()
{
char text [] = "Hello";
char copy_text [ sizeof(char) ];
Strcpy( copy_text, text );
printf("%s", copy_text);
return 0;
}
|
Python | UTF-8 | 1,218 | 2.765625 | 3 | [
"MIT"
] | permissive | import sys
import xml.etree.ElementTree as ET
from lxml import html
import requests
import spacy
if len(sys.argv) >2:
Genus = sys.argv[1]
Species = sys.argv[2]
else:
print("usage: "+sys.argv[0]+" <Genus_name> <Species_name>")
print("running with default options")
Genus = 'Phyllobates'
Species = 'bicolor'
page = requests.get('https://amphibiaweb.org/cgi/amphib_ws?where-genus='+Genus+'&where-species='+Species+'&src=eol')
root = ET.fromstring(page.content)
for species in root.findall('species'):
common_name = species.find('common_name')
genus = species.find('genus')
spec = species.find('species')
print(genus.text.strip()+' '+spec.text.strip()+', also known as: '+common_name.text.strip())
life_history = species.find('life_history')
as_string = str(life_history.text.strip())
print(as_string)
#load natural language processor
nlp = spacy.load(r'C:\Users\Tyler\Miniconda3\Lib\site-packages\en_core_web_sm\en_core_web_sm-2.3.1')
as_doc = nlp(as_string)
# print list of all individual tokens
for token in as_doc:
print(token.text, token.pos)
#parse paragraph into sentences
sentences = list(as_doc.sents)
for sentence in sentences:
print(sentence)
|
Java | UTF-8 | 662 | 2.09375 | 2 | [] | no_license | package com.example.android.notification.models;
/**
* Created by sakshi on 16/4/18.
*/
public class To_Items {
String to_item_name;
String to_name;
public To_Items()
{ }
public To_Items(String to_item_name, String to_name) {
this.to_item_name = to_item_name;
this.to_name = to_name;
}
public String getTo_item_name() {
return to_item_name;
}
public void setTo_item_name(String to_item_name) {
this.to_item_name = to_item_name;
}
public String getTo_name() {
return to_name;
}
public void setTo_name(String to_name) {
this.to_name = to_name;
}
}
|
Python | UTF-8 | 187 | 3 | 3 | [] | no_license | #!/usr/bin/python3
""" Sorts integers"""
def find_peak(list_of_integers):
"""Sorts integers"""
new = list_of_integers[:]
maximo = max(new, default=None)
return (maximo)
|
Java | UTF-8 | 1,704 | 2.21875 | 2 | [] | no_license | package br.com.iperonprev.controller.pericia;
import java.io.Serializable;
import java.util.List;
import javax.faces.bean.ManagedBean;
import org.primefaces.event.SelectEvent;
import br.com.iperonprev.dao.GenericPersistence;
import br.com.iperonprev.interfaces.GenericBean;
import br.com.iperonprev.models.Exames;
import br.com.iperonprev.util.jsf.DialogsPrime;
import br.com.iperonprev.util.jsf.Message;
@ManagedBean
public class ExamesBean implements GenericBean<Exames>,Serializable{
Exames exames = new Exames();
public Exames getExames() {
return exames;
}
public void setExames(Exames exames) {
this.exames = exames;
}
private static final long serialVersionUID = 1L;
@Override
public void salvarObjeto() {
try{
new GenericPersistence<Exames>(Exames.class).salvar(this.exames);
novoObjeto();
Message.addSuccessMessage("Exame salvo com sucesso");
}catch(Exception e){
Message.addErrorMessage("Erro ao salvar exame.");
}
}
@Override
public void novoObjeto() {
this.exames = new Exames();
}
@Override
public List<Exames> listaDeObjetos() {
// TODO Auto-generated method stub
return null;
}
@Override
public void exibeListaDeObjetos() {
new DialogsPrime().showDialog(true, true, true, false, "listaExames");
}
@Override
public void pegaInstanciaDialogo(Exames obj) {
new DialogsPrime().getInstanceObjectDialog(obj);
}
@Override
public void selecionaObjetoDialogo(SelectEvent event) {
this.exames = (Exames)event.getObject();
}
public List<Exames> getListaDeExames(){
return new GenericPersistence<Exames>(Exames.class).listarTodos("Exames");
}
}
|
Java | UTF-8 | 977 | 3.1875 | 3 | [] | no_license | package com.hcl;
import java.io.*;
public class Main {
public static void main(String[] args) throws IOException
{
// TODO Auto-generated method stub
String name;
double deposit,costPerDay;
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
itemType i=new itemType();
try
{
System.out.println("Enter the item type details:");
System.out.println("Enter the name:");
name=br.readLine();
System.out.println("Enter the deposit:");
deposit=Double.parseDouble(br.readLine());
System.out.println("Enter the cost per day:");
costPerDay=Double.parseDouble(br.readLine());
System.out.println("The item details are:");
i.setName(name);
i.setDeposit(deposit);
i.setCostPerDay(costPerDay);
System.out.println("Name:"+i.getName()+"\nDeposit:"+i.getDeposit()+"\nCost Per Day:"+i.getCostPerDay());
}
catch(NumberFormatException ne)
{
System.out.println(ne.toString());
}
}
}
|
Markdown | UTF-8 | 1,544 | 3.015625 | 3 | [
"CC-BY-4.0"
] | permissive | # 第一部分:数据系统的基石
本书前四章介绍了数据系统底层的基础概念,无论是在单台机器上运行的单点数据系统,还是分布在多台机器上的分布式数据系统都适用。
1. [第一章](ch1.md)将介绍本书使用的术语和方法。**可靠性,可扩展性和可维护性** ,这些词汇到底意味着什么?如何实现这些目标?
2. [第二章](ch2.md)将对几种不同的**数据模型和查询语言**进行比较。从程序员的角度看,这是数据库之间最明显的区别。不同的数据模型适用于不同的应用场景。
3. [第三章](ch3.md)将深入**存储引擎**内部,研究数据库如何在磁盘上摆放数据。不同的存储引擎针对不同的负载进行优化,选择合适的存储引擎对系统性能有巨大影响。
4. [第四章](https://github.com/tiandiyijian/ddia/tree/03cdebe14167136bb3811de33d5a5e603260003f/ch4/README.md)将对几种不同的 **数据编码**进行比较。特别研究了这些格式在应用需求经常变化、模式需要随时间演变的环境中表现如何。
第二部分将专门讨论在**分布式数据系统**中特有的问题。
## 目录
1. [可靠性、可扩展性、可维护性](ch1.md)
2. [数据模型与查询语言](ch2.md)
3. [存储与检索](ch3.md)
4. [编码与演化](ch4.md)
| 上一章 | 目录 | 下一章 |
| :--- | :--- | :--- |
| [序言](../preface.md) | [设计数据密集型应用](../) | [第一章:可靠性、可扩展性、可维护性](ch1.md) |
|
Markdown | UTF-8 | 551 | 2.703125 | 3 | [] | no_license | # Tutorial 2 - Inversion of an interval (I)
// date: 2020-11-24
// http://recherche.ircam.fr/equipes/repmus/OpenMusic/user-doc/DocFiles/Tutorial/tut002/Index.html
```csharp
var originalLine = new List<int>() { 6000, 7100 };
Console.WriteLine(string.Join(", ", originalLine)); // 6000, 7100
var invertedLine = Basic.InvertPitchSequence(originalLine, originalLine[0]);
Console.WriteLine(string.Join(", ", invertedLine)); // 6000, 4900
Console.WriteLine(string.Join(", ", Conversion.IntegersToPitchStrings(invertedLine))); // C4, C#3
```
|
C# | UTF-8 | 16,857 | 2.546875 | 3 | [
"MIT"
] | permissive | using System;
using System.IO;
using System.Text.RegularExpressions;
namespace FitsEdit
{
/// <summary>
/// Summary description for FitsFile.
/// </summary>
public class FitsFile
{
public string Simple;
public int BitPix;
public int Naxis;
public int XSize;
public int YSize;
public string Object;
public string Date;
public string DateObs;
public string Origin;
public string Instrument;
public string Telescope;
public string Observer;
public string Comment;
public double BZero;
public double BScale;
public int [,] Pixels;
public int iMax;
public uint iNumPixels;
public byte bT1, bT2;
public FitsFile(string sFilename)
{
int i, j;
string sTmp;
string [] aTmp;
FileStream oStream = new FileStream(sFilename, FileMode.Open, FileAccess.Read, FileShare.Read);
BinaryReader oReader = new BinaryReader(oStream);
Comment = "";
for(;;)
{
sTmp = new string(oReader.ReadChars(80));
if (sTmp.Substring(0,7).Trim().ToUpper() == "COMMENT")
{
Comment += sTmp;
}
else if(sTmp.Substring(0,3).Trim().ToUpper() == "END")
{
sTmp = new string(oReader.ReadChars(80));
break;
}
else
{
aTmp = sTmp.Split('=');
if (aTmp.Length < 2)
continue;
aTmp[0] = aTmp[0].Trim().ToUpper();
aTmp[1] = aTmp[1].Trim();
if (aTmp[0] == "SIMPLE")
{
Simple = aTmp[1];
}
else if (aTmp[0] == "BITPIX")
{
aTmp[1] = Regex.Match(aTmp[1], "[^\\D]+").ToString();
BitPix = Convert.ToInt32(aTmp[1]);
}
else if (aTmp[0] == "NAXIS")
{
aTmp[1] = Regex.Match(aTmp[1], "[^\\D]+").ToString();
Naxis = Convert.ToInt32(aTmp[1]);
}
else if (aTmp[0] == "NAXIS1")
{
aTmp[1] = Regex.Match(aTmp[1], "[^\\D]+").ToString();
XSize = Convert.ToInt32(aTmp[1]);
}
else if (aTmp[0] == "NAXIS2")
{
aTmp[1] = Regex.Match(aTmp[1], "[^\\D]+").ToString();
YSize = Convert.ToInt32(aTmp[1]);
}
else if (aTmp[0] == "OBJECT")
{
Object = aTmp[1];
}
else if (aTmp[0] == "DATE")
{
Date = aTmp[1];
}
else if (aTmp[0] == "DATE-OBS")
{
DateObs = aTmp[1];
}
else if (aTmp[0] == "ORIGIN")
{
Origin = aTmp[1];
}
else if (aTmp[0] == "INSTRUME")
{
Instrument = aTmp[1];
}
else if (aTmp[0] == "TELESCOP")
{
Telescope = aTmp[1];
}
else if (aTmp[0] == "OBSERVER")
{
Observer = aTmp[1];
}
else if (aTmp[0] == "BZERO")
{
aTmp[1] = Regex.Match(aTmp[1], "[^\\D]+").ToString();
BZero = Convert.ToDouble(aTmp[1]);
}
else if (aTmp[0] == "BSCALE")
{
aTmp[1] = Regex.Match(aTmp[1], "[^\\D]+").ToString();
BScale = Convert.ToDouble(aTmp[1]);
}
}
}
iNumPixels = (uint)(XSize * YSize);
iMax = 65535;
Pixels = new int[XSize, YSize];
for(j = YSize - 1; j >= 0; j--)
{
for(i = 0; i < XSize; i++)
{
bT2 = oReader.ReadByte();
bT1 = oReader.ReadByte();
Pixels[i, j] = ((int)bT2 * 255) + (int)bT1;
if (Pixels[i, j] >= (int)BZero)
{
Pixels[i, j] -= (int)BZero;
}
else
{
Pixels[i, j] = (int)BZero - Pixels[i, j];
}
}
}
oReader.Close();
oStream.Close();
}
public FitsFile()
{
}
//-----------------------------------------------------------
//Add
//Adds specified number to all pixels in specified area
//-----------------------------------------------------------
public void Add(int iNum, int iStartX, int iStartY, int iEndX, int iEndY)
{
int i, j;
for (i = iStartX; i <= iEndX; i++)
{
for (j = iStartY; j <= iEndY; j++)
{
if ((Pixels[i,j] + iNum) < Pixels[i,j])
{
Pixels[i,j] = iMax;
}
else
{
Pixels[i,j] += iNum;
}
}
}
}
//-----------------------------------------------------------
//Add
//Adds specified number to all pixels in image
//-----------------------------------------------------------
public void Add(int iNum)
{
Add(iNum, 0, 0, XSize - 1, YSize - 1);
}
//-----------------------------------------------------------
//AddCircle
//Adds specified number to all pixels in specified circle
//-----------------------------------------------------------
public void AddCircle(int iNum, int iCentreX, int iCentreY, int iRadius)
{
int i, j;
for (i = (iCentreX - iRadius); i <= (iCentreX + iRadius); i++)
{
for (j = (iCentreY - iRadius); j <= (iCentreY + iRadius); j++)
{
if (((i - iCentreX) * (i - iCentreX)) + ((j - iCentreY) * (j - iCentreY)) <= (iRadius * iRadius))
{
if ((Pixels[i,j] + iNum) < Pixels[i,j])
{
Pixels[i,j] = iMax;
}
else
{
Pixels[i,j] += iNum;
}
}
}
}
}
//-----------------------------------------------------------
//Subtract
//Subtracts specified number from all pixels in specified area
//-----------------------------------------------------------
public void Subtract(int iNum, int iStartX, int iStartY, int iEndX, int iEndY)
{
int i, j;
for (i = iStartX; i <= iEndX; i++)
{
for (j = iStartY; j <= iEndY; j++)
{
if ((Pixels[i,j] - iNum) > Pixels[i,j])
{
Pixels[i,j] = 0;
}
else
{
Pixels[i,j] -= iNum;
}
}
}
}
//-----------------------------------------------------------
//Subtract
//Subtracts specified number from all pixels in image
//-----------------------------------------------------------
public void Subtract(int iNum)
{
Subtract(iNum, 0, 0, XSize - 1, YSize - 1);
}
//-----------------------------------------------------------
//SubtractCircle
//Subtracts specified number to all pixels in specified circle
//-----------------------------------------------------------
public void SubtractCircle(int iNum, int iCentreX, int iCentreY, int iRadius)
{
int i, j;
for (i = (iCentreX - iRadius); i <= (iCentreX + iRadius); i++)
{
for (j = (iCentreY - iRadius); j <= (iCentreY + iRadius); j++)
{
if (((i - iCentreX) * (i - iCentreX)) + ((j - iCentreY) * (j - iCentreY)) <= (iRadius * iRadius))
{
if ((Pixels[i,j] - iNum) > Pixels[i,j])
{
Pixels[i,j] = 0;
}
else
{
Pixels[i,j] -= iNum;
}
}
}
}
}
//-----------------------------------------------------------
//Divides
//Divides all pixels in specified area by specified number
//-----------------------------------------------------------
public void Divide(int iNum, int iStartX, int iStartY, int iEndX, int iEndY)
{
int i, j;
if (iNum != 0)
{
for (i = iStartX; i <= iEndX; i++)
{
for (j = iStartX; j <= iEndY; j++)
{
Pixels[i,j] /= iNum;
}
}
}
}
//-----------------------------------------------------------
//Divides
//Divides all pixels in image by specified number
//-----------------------------------------------------------
public void Divide(int iNum)
{
Divide(iNum, 0, 0, XSize - 1, YSize - 1);
}
//-----------------------------------------------------------
//DivideCircle
//Divide all pixels by specified number in specified circle
//-----------------------------------------------------------
public void DivideCircle(int iNum, int iCentreX, int iCentreY, int iRadius)
{
int i, j;
for (i = (iCentreX - iRadius); i <= (iCentreX + iRadius); i++)
{
for (j = (iCentreY - iRadius); j <= (iCentreY + iRadius); j++)
{
if (((i - iCentreX) * (i - iCentreX)) + ((j - iCentreY) * (j - iCentreY)) <= (iRadius * iRadius))
{
Pixels[i,j] /= iNum;
}
}
}
}
//-----------------------------------------------------------
//Multiply
//Multiply all pixels in specified area by specified number
//-----------------------------------------------------------
public void Multiply(int iNum, int iStartX, int iStartY, int iEndX, int iEndY)
{
int i, j;
for (i = iStartX; i <= iEndX; i++)
{
for (j = iStartY; j <= iEndY; j++)
{
if ((Pixels[i,j] * iNum) < Pixels[i,j])
{
Pixels[i,j] = iMax;
}
else
{
Pixels[i,j] *= iNum;
}
}
}
}
//-----------------------------------------------------------
//Multiply
//Multiply all pixels in image by specified number
//-----------------------------------------------------------
public void Multiply(int iNum)
{
Multiply(iNum, 0, 0, XSize - 1, YSize - 1);
}
//-----------------------------------------------------------
//MultiplyCircle
//Multiply all pixels by specified number in specified circle
//-----------------------------------------------------------
public void MultiplyCircle(int iNum, int iCentreX, int iCentreY, int iRadius)
{
int i, j;
for (i = (iCentreX - iRadius); i <= (iCentreX + iRadius); i++)
{
for (j = (iCentreY - iRadius); j <= (iCentreY + iRadius); j++)
{
if (((i - iCentreX) * (i - iCentreX)) + ((j - iCentreY) * (j - iCentreY)) <= (iRadius * iRadius))
{
if ((Pixels[i,j] * iNum) < Pixels[i,j])
{
Pixels[i,j] = iMax;
}
else
{
Pixels[i,j] *= iNum;
}
}
}
}
}
//-----------------------------------------------------------
//GetSum
//Getsthe total of all pixels in specified area
//-----------------------------------------------------------
public double GetSum(int iStartX, int iStartY, int iEndX, int iEndY)
{
double fSum = 0.0;
int i, j;
for (i = iStartX; i <= iEndX; i++)
{
for (j = iStartY; j <= iEndY; j++)
{
fSum += (double)Pixels[i,j];
}
}
return fSum;
}
//-----------------------------------------------------------
//GetSumCircle
//Gets the total of all pixels in specified circle
//-----------------------------------------------------------
public double GetSumCircle(int iCentreX, int iCentreY, int iRadius)
{
double fSum = 0.0;
int i, j;
for (i = (iCentreX - iRadius); i <= (iCentreX + iRadius); i++)
{
for (j = (iCentreY - iRadius); j <= (iCentreY + iRadius); j++)
{
if (((i - iCentreX) * (i - iCentreX)) + ((j - iCentreY) * (j - iCentreY)) <= (iRadius * iRadius))
{
fSum += (double)Pixels[i,j];
}
}
}
return fSum;
}
//-----------------------------------------------------------
//GetSum
//Gets the total of all pixels in entire image
//-----------------------------------------------------------
public double GetSum()
{
return GetSum(0, 0, XSize - 1, YSize - 1);
}
//-----------------------------------------------------------
//GetMean
//Gets the mean of all pixels in specified area
//-----------------------------------------------------------
public double GetMean(int iStartX, int iStartY, int iEndX, int iEndY)
{
return GetSum(iStartX, iStartY, iEndX, iEndY) / (double)iNumPixels;
}
//-----------------------------------------------------------
//GetMean
//Gets the mean of all pixels in entire image
//-----------------------------------------------------------
public double GetMean()
{
return GetSum() / (double)iNumPixels;
}
//-----------------------------------------------------------
//GetMeanCircle
//Gets the mean of all pixels in specified circle
//-----------------------------------------------------------
public double GetMeanCircle(int iCentreX, int iCentreY, int iRadius)
{
double fSum = 0.0;
int i, j,iCount;
iCount = 0;
for (i = (iCentreX - iRadius); i <= (iCentreX + iRadius); i++)
{
for (j = (iCentreY - iRadius); j <= (iCentreY + iRadius); j++)
{
if (((i - iCentreX) * (i - iCentreX)) + ((j - iCentreY) * (j - iCentreY)) <= (iRadius * iRadius))
{
fSum += (double)Pixels[i,j];
iCount++;
}
}
}
return fSum / (double)iCount;
}
//-----------------------------------------------------------
//GetPeakLoc
//Gets the peak value and location in specified area
//-----------------------------------------------------------
public void GetPeakLoc(ref int iPeak, ref int iX, ref int iY, int iStartX, int iStartY, int iEndX, int iEndY)
{
int i, j;
iPeak = 0;
for (i = iStartX; i <= iEndX; i++)
{
for (j = iStartY; j <= iEndY; j++)
{
if (Pixels[i,j] >= iPeak)
{
iPeak = Pixels[i,j];
iX = i;
iY = j;
}
}
}
}
//-----------------------------------------------------------
//GetPeakLoc
//Gets the peak value and location in entire image
//-----------------------------------------------------------
public void GetPeakLoc(ref int iPeak, ref int iX, ref int iY)
{
GetPeakLoc(ref iPeak, ref iX, ref iY, 0, 0, XSize - 1, YSize - 1);
}
//-----------------------------------------------------------
//GetPeak
//Gets the peak value in specified area
//-----------------------------------------------------------
public int GetPeak(int iStartX, int iStartY, int iEndX, int iEndY)
{
int i, j;
int iPeak;
iPeak = 0;
for (i = iStartX; i <= iEndX; i++)
{
for (j = iStartY; j <= iEndY; j++)
{
if (Pixels[i,j] >= iPeak)
{
iPeak = Pixels[i,j];
}
}
}
return iPeak;
}
//-----------------------------------------------------------
//GetPeak
//Gets the peak value in entire image
//-----------------------------------------------------------
public int GetPeak()
{
return GetPeak(0, 0, XSize - 1, YSize - 1);
}
//-----------------------------------------------------------
//GetPeakCircle
//Gets the peak value in specified circle
//-----------------------------------------------------------
public int GetPeakCircle(int iCentreX, int iCentreY, int iRadius)
{
int iPeak;
int i, j;
iPeak = 0;
for (i = (iCentreX - iRadius); i <= (iCentreX + iRadius); i++)
{
for (j = (iCentreY - iRadius); j <= (iCentreY + iRadius); j++)
{
if (((i - iCentreX) * (i - iCentreX)) + ((j - iCentreY) * (j - iCentreY)) <= (iRadius * iRadius))
{
if (Pixels[i,j] >= iPeak)
{
iPeak = Pixels[i,j];
}
}
}
}
return iPeak;
}
//-----------------------------------------------------------
//GetMinLoc
//Gets the min value and location in specified area
//-----------------------------------------------------------
public void GetMinLoc(ref int iMin, ref int iX, ref int iY, int iStartX, int iStartY, int iEndX, int iEndY)
{
int i, j;
iMin = iMax;
for (i = iStartX; i <= iEndX; i++)
{
for (j = iStartY; j <= iEndY; j++)
{
if (Pixels[i,j] <= iMin)
{
iMin = Pixels[i,j];
iX = i;
iY = j;
}
}
}
}
//-----------------------------------------------------------
//GetMinLoc
//Gets the min value and location in entire image
//-----------------------------------------------------------
public void GetMinLoc(ref int iMin, ref int iX, ref int iY)
{
GetMinLoc(ref iMin, ref iX, ref iY, 0, 0, XSize - 1, YSize - 1);
}
//-----------------------------------------------------------
//GetMin
//Gets the min value in specified area
//-----------------------------------------------------------
public int GetMin(int iStartX, int iStartY, int iEndX, int iEndY)
{
int i, j;
int iMin;
iMin = iMax;
for (i = iStartX; i <= iEndY; i++)
{
for (j = iStartY; j <= iEndY; j++)
{
if (Pixels[i,j] <= iMin)
{
iMin = Pixels[i,j];
}
}
}
return iMin;
}
//-----------------------------------------------------------
//GetMin
//Gets the min value in entire image
//-----------------------------------------------------------
public int GetMin()
{
return GetMin(0, 0, XSize - 1, YSize - 1);
}
//-----------------------------------------------------------
//GetMinCircle
//Gets the min value in specified circle
//-----------------------------------------------------------
public int GetMinCircle(int iCentreX, int iCentreY, int iRadius)
{
int iMin;
int i, j;
iMin = iMax;
for (i = (iCentreX - iRadius); i <= (iCentreX + iRadius); i++)
{
for (j = (iCentreY - iRadius); j <= (iCentreY + iRadius); j++)
{
if (((i - iCentreX) * (i - iCentreX)) + ((j - iCentreY) * (j - iCentreY)) <= (iRadius * iRadius))
{
if (Pixels[i,j] <= iMin)
{
iMin = Pixels[i,j];
}
}
}
}
return iMin;
}
}
}
|
Python | UTF-8 | 142 | 3.453125 | 3 | [] | no_license | first = 'John'
last = 'Smith'
message = first +' [' + last + '] is a coder.'
msg = f'{first} [{last}] is a coder.'
print(message)
print(msg) |
Markdown | UTF-8 | 237 | 3.234375 | 3 | [
"MIT"
] | permissive | # Use custom money string (k, m, b)
Format money string value in thousands, millions or billions.
_Using Vega's method._
| Format | Value |
| - | - |
| 1k | 1.000 |
| 100kk | 100.000.000 |
| 100m | 100.000.000 |
| 1b | 1.000.000.000 |
|
PHP | UTF-8 | 2,915 | 2.734375 | 3 | [
"MIT"
] | permissive | <?php
namespace BlackScorp\ORM\Entity;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
/**
* Class User
* @package BlackScorp\ORM\Entity
* @ORM\Entity
*/
class User
{
use IdTrait;
/**
* @var string
* @ORM\Column(type="string",nullable=false)
*/
protected string $username;
/**
* @var string
* @ORM\Column(type="string",nullable=false)
*/
protected string $password;
/**
* @var string
* @ORM\Column(type="string", nullable=false,unique=true)
*/
protected string $email;
/**
* @var string|null
* @ORM\Column(type="string", nullable=true)
*/
protected ?string $activationKey = null;
/**
* @var string
* @ORM\Column(type="string",columnDefinition="ENUM('USER','ADMIN')", options={"default":"USER"})
*/
protected string $userRights;
/**
* @var Collection
* @ORM\OneToMany(targetEntity="CartProducts", mappedBy="user")
* @ORM\JoinTable(name="cart",
* joinColumns={@ORM\JoinColumn(name="user_id",referencedColumnName="id")}
* )
*/
protected Collection $cartProducts;
/**
* @return Collection
*/
public function getCartProducts(): Collection
{
return $this->cartProducts;
}
/**
* @param Collection $cartProducts
*/
public function setCartProducts(Collection $cartProducts): void
{
$this->cartProducts = $cartProducts;
}
/**
* @return string
*/
public function getUsername(): string
{
return $this->username;
}
/**
* @param string $username
*/
public function setUsername(string $username): void
{
$this->username = $username;
}
/**
* @return string
*/
public function getEmail(): string
{
return $this->email;
}
/**
* @param string $email
*/
public function setEmail(string $email): void
{
$this->email = $email;
}
/**
* @return string|null
*/
public function getActivationKey(): ?string
{
return $this->activationKey;
}
/**
* @param string|null $activationKey
*/
public function setActivationKey(?string $activationKey): void
{
$this->activationKey = $activationKey;
}
/**
* @return string
*/
public function getUserRights(): string
{
return $this->userRights;
}
/**
* @param string $userRights
*/
public function setUserRights(string $userRights): void
{
$this->userRights = $userRights;
}
/**
* @return string
*/
public function getPassword(): string
{
return $this->password;
}
/**
* @param string $password
*/
public function setPassword(string $password): void
{
$this->password = $password;
}
} |
Python | UTF-8 | 7,372 | 3.40625 | 3 | [] | no_license | # Projet : RedBallBot
# Auteur : Quentin Forestier
# Fichier : RedBallBot/api/image_analyser.py
__author__ = "Quentin Forestier"
__copyright__ = "Copyright 2019, RedBallBot2"
__version__ = "1.0.0"
from skimage import color
from skimage.transform import hough_circle, hough_circle_peaks, rescale
from skimage.feature import canny
from skimage.draw import circle
from skimage.util import img_as_ubyte
import numpy as np
class ImageAnalyser(object):
"""
Une classe utilisé pour l'analyse d'image
Attributes
----------
MAX_VALUE_RGB : int
Valeur maximal du RGB
Methods
-------
get_circle_center(image, min_radius, max_radius, step_radius, number_best_circle)
Détecte les cercles présents dans l'image
get_pixels_circles(center_x, center_y, radius)
Récupère tous les pixels du cercle demandé
is_red_circle(self, image, circx, circy)
Détecte si un rond contient du rouge
get_red_in_image(image)
Détecte le rouge de l'image et renvoi une nouvelle image modifié
is_red_circle_old(image, circx, circy)
Détecte si une balle est rouge
get_center_image(image)
Obtient la position x,y du centre de l'image
image_rescale(image, ratio)
Redimensionne l'image avec le ratio demandé
"""
MAX_VAlUE_RGB = 255
MIN_RED = 190
def __init__(self):
"""Constructeur de la classe
"""
pass
@staticmethod
def get_circle_center(image, min_radius, max_radius, step_radius, number_best_circle):
"""Détecte les cercles présents dans l'image
Parameters
----------
image: ndarray
Image à analyser
min_radius: int
Rayon minimum des cercles
max_radius : int
Rayon maximum des cercles
step_radius : int
Pas entre les rayons des cercles
number_best_circle : int
Nombre de cercles à retourner (Choisi les N meilleurs)
Returns
-------
tuple
Retourne les informations sur les cercles (centre X, centre Y, rayon)
"""
image = color.rgb2gray(image)
image = img_as_ubyte(image)
# Détecte les bords d'une forme grâce à un dérivé de la fonction gaussienne
# Possibilité de modifier la precision en modifiant le sigma
# Utilise des seuils d'hystère afin d'éviter le bruit
edges = canny(image, sigma=3, low_threshold=10, high_threshold=50)
hough_radii = np.arange(min_radius, max_radius, step_radius)
hough_res = hough_circle(edges, hough_radii)
# Sélectionne les N cercles les plus probables (N = numberBestCircle)
accums, cx, cy, radii = hough_circle_peaks(hough_res, hough_radii,
total_num_peaks=number_best_circle, min_xdistance=20,
min_ydistance=20)
return zip(cx, cy, radii)
@staticmethod
def get_pixels_circles(center_x, center_y, radius):
"""Récupère tous les pixels du cercle demandé
Parameters
----------
center_x : int
Centre en X du cercle
center_y : int
Centre en Y du cercle
radius : int
Rayon du cercle
Returns
-------
ndarray of int
Toutes les positions X,Y des pixels du cercle
"""
return circle(center_y, center_x, radius)
@staticmethod
def is_red_circle(image, circx, circy):
"""
Parameters
----------
image : ndarray
Image transformée par get_red_in_image
circx : liste position de pixels en X
Tous les pixels en X du rond
circy : liste position de pixels en Y
Tous les pixels en Y du rond
Returns
-------
bool
S'il y a plus de 50 pixels rouge dans l'image -> True
S'il y a moins de 50 pixels rouge dans l'image -> False
"""
counter = 0
for x, y in zip(circx, circy):
try:
r, g, b = image[y, x]
if r == 0 and g == 1 and b == 0:
counter += 1
except IndexError:
print('Erreur d\'index')
return counter > 50
@staticmethod
def get_red_in_image(image):
""" Transforme les pixels rouges en pixels verts pures
Parameters
----------
image : ndarray
Image sous forme d'array numpy
Returns
-------
ndarray
Image transformée
"""
image_slice_red = image[:, :, 0]
image_slice_green = image[:, :, 1]
image_slice_blue = image[:, :, 2]
mask = (image_slice_red * ImageAnalyser.MAX_VAlUE_RGB > ImageAnalyser.MIN_RED) & (
image_slice_red * ImageAnalyser.MAX_VAlUE_RGB > (
image_slice_green * ImageAnalyser.MAX_VAlUE_RGB + image_slice_blue * ImageAnalyser.MAX_VAlUE_RGB) * 5)
image[mask] = [0, 1, 0]
return image
@staticmethod
def is_red_circle_old(image, circx, circy):
"""Détecte si une balle est rouge
Parameters
----------
image : ndarray
Image à analyser
circx : list de int
Tous les pixels en X du rond
circy : list de int
Tous les pixels en Y du rond
Returns
-------
bool
Si le rond est rouge -> True
Si le rond n'est pas rouge -> False
"""
r_total = []
g_total = []
b_total = []
avg_r = 0
avg_g = 0
avg_b = 0
for x, y in zip(circx, circy):
try:
r, g, b = image[y, x]
r_total.append(r)
g_total.append(g)
b_total.append(b)
except IndexError:
print('Partie du rond en dehors de l\'image')
try:
avg_r = sum(r_total) / len(r_total) * ImageAnalyser.MAX_VAlUE_RGB
avg_g = sum(g_total) / len(g_total) * ImageAnalyser.MAX_VAlUE_RGB
avg_b = sum(b_total) / len(b_total) * ImageAnalyser.MAX_VAlUE_RGB
except ArithmeticError:
print('Tentative de division par 0')
# Conditions inventées "au hasard". Marche plutôt bien
return avg_r > avg_b + avg_g + 50 and avg_r > 200
@staticmethod
def get_center_image(image):
"""Obtient la position (x,y) du centre de l'image
Parameters
----------
image : ndarray
Image souhaité
Returns
-------
point
Position X,Y du centre de l'image
"""
image_center_x = round(len(image[0]) / 2)
image_center_y = round(len(image) / 2)
image_center = (image_center_x, image_center_y)
return image_center
@staticmethod
def image_rescale(image, ratio):
"""Redimensionne l'image avec le ration demandé
Parameters
----------
image : ndarray
Image a redimensionné
ratio : float
Ratio de redimensionnement
Returns
-------
ndarray
Image redimensionné
"""
return rescale(image, ratio, anti_aliasing=True)
|
Java | UTF-8 | 15,892 | 2.125 | 2 | [] | no_license | package nu.johanw123.squaremanboy;
import java.util.ArrayList;
import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.controllers.Controller;
import com.badlogic.gdx.controllers.PovDirection;
import com.badlogic.gdx.controllers.mappings.Ouya;
import com.badlogic.gdx.graphics.Color;
import com.badlogic.gdx.graphics.Pixmap;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.Pixmap.Format;
import com.badlogic.gdx.graphics.g2d.BitmapFont;
import com.badlogic.gdx.scenes.scene2d.EventListener;
import com.badlogic.gdx.scenes.scene2d.InputEvent;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.ui.Button;
import com.badlogic.gdx.scenes.scene2d.ui.ImageButton;
import com.badlogic.gdx.scenes.scene2d.ui.Skin;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton;
import com.badlogic.gdx.scenes.scene2d.ui.TextButton.TextButtonStyle;
import com.badlogic.gdx.scenes.scene2d.utils.ClickListener;
import com.badlogic.gdx.scenes.scene2d.utils.Drawable;
import com.badlogic.gdx.utils.TimeUtils;
public class ButtonHandler implements SKeyboardListener, SGamepadListener, STouchListener
{
private int selectedButton = -1;
private int menuBackButton = -1;
private ArrayList<Button> buttons;
private TextButtonStyle textButtonStyle;
private Skin skin;
private final int StandardButtonWidth = 600;
private final int StandardButtonHeight = 70;
private final int StandardSpacing = 90;
enum eButtonType
{
TextButton,
ImageButton
}
public ButtonHandler()
{
//buttons = new ArrayList<TextButton>();
buttons = new ArrayList<Button>();
skin = new Skin();
Pixmap pixmap = new Pixmap(32, 32, Format.RGBA8888);
pixmap.setColor(Color.GREEN);
pixmap.fill();
skin.add("white", new Texture(pixmap));
BitmapFont bfont=new BitmapFont();
bfont.scale(1);
skin.add("default",SGame.font);
textButtonStyle = new TextButtonStyle();
textButtonStyle.up = skin.newDrawable("white", Color.DARK_GRAY);
textButtonStyle.down = skin.newDrawable("white", Color.DARK_GRAY);
textButtonStyle.checked = skin.newDrawable("white", Color.LIGHT_GRAY);
textButtonStyle.over = skin.newDrawable("white", Color.LIGHT_GRAY);
textButtonStyle.font = SGame.font;
skin.add("default", textButtonStyle);
skin.add("logo", new Texture(Gdx.files.internal("data/sprites/logo.png")));
Drawable drawable = skin.getDrawable("logo");
ImageButton.ImageButtonStyle imageStyle = new ImageButton.ImageButtonStyle();
imageStyle.imageChecked = drawable;
imageStyle.imageCheckedOver = drawable;
imageStyle.imageDisabled = drawable;
imageStyle.imageDown = drawable;
imageStyle.imageOver = drawable;
imageStyle.imageUp = drawable;
skin.add("logostyle", imageStyle);
}
public void addListeners()
{
SInput.addKeyboardListener(this);
SInput.addGamepadListener(this);
SInput.addTouchListener(this);
}
public void clearListeners()
{
SInput.removeKeyboardListener(this);
SInput.removeGamepadListener(this);
SInput.removeTouchListener(this);
SInput.gamepadListeners.clear();
SInput.keyboardListeners.clear();
SInput.touchListeners.clear();
}
public Button createImageButton(String buttonName, EventListener activateEvent)
{
int spacing = StandardSpacing;
float x = SRuntime.SCREEN_WIDTH /2 - StandardButtonWidth / 2;
float y = SRuntime.SCREEN_HEIGHT - 150 - spacing * buttons.size();
int width = StandardButtonWidth;
int height = StandardButtonHeight;
return createImageButton(buttonName, activateEvent, x, y, width, height);
}
private Button createImageButton(String buttonName, final EventListener activateEvent, float x, float y, int width, int height)
{
return createButton(buttonName, activateEvent, x, y, width, height, SGame.stage, eButtonType.ImageButton);
}
private ImageButton createImageButton(float x, float y, int width, int height, String buttonName)
{
Drawable drawable = skin.getDrawable(buttonName);
ImageButton.ImageButtonStyle imageStyle = new ImageButton.ImageButtonStyle();
imageStyle.imageChecked = drawable;
imageStyle.imageCheckedOver = drawable;
imageStyle.imageDisabled = drawable;
imageStyle.imageDown = drawable;
imageStyle.imageOver = drawable;
imageStyle.imageUp = drawable;
ImageButton button = new ImageButton(imageStyle);
button.setName(buttonName);
button.setPosition(x, y);
button.setSize(width, height);
return button;
}
public Button createTextButton(String buttonText, EventListener activateEvent)
{
int spacing = StandardSpacing;
float x = SRuntime.SCREEN_WIDTH /2 - StandardButtonWidth / 2;
float y = SRuntime.SCREEN_HEIGHT - 150 - spacing * buttons.size();
int width = StandardButtonWidth;
int height = StandardButtonHeight;
return createTextButton(buttonText, activateEvent, x, y, width, height);
}
private Button createTextButton(String buttonText, final EventListener activateEvent, float x, float y, int width, int height)
{
return createButton(buttonText, activateEvent, x, y, width, height, SGame.stage, eButtonType.TextButton);
}
public Button createTextButton(String buttonText, EventListener activateEvent, Stage stage)
{
int spacing = StandardSpacing;
float x = SRuntime.SCREEN_WIDTH /2 - StandardButtonWidth / 2;
float y = SRuntime.SCREEN_HEIGHT - 150 - spacing * buttons.size();
int width = StandardButtonWidth;
int height = StandardButtonHeight;
return createButton(buttonText, activateEvent, x, y, width, height, stage, eButtonType.TextButton);
}
private TextButton createTextButton(float x, float y, int width, int height, String buttonText)
{
TextButton button = new TextButton(buttonText, textButtonStyle);
button.setPosition(x, y);
button.setSize(width, height);
button.setName(buttonText);
return button;
}
public Button createButton(String buttonText, final EventListener activateEvent, float x, float y, int width, int height, Stage stage, eButtonType buttonType)
{
//Button button;
if(buttonType == eButtonType.TextButton) {
final Button button = createTextButton(x, y, width, height, buttonText);
button.addListener(activateEvent);
button.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
button.fire(new ButtonActivatedEvent());
super.clicked(event, x, y);
}
});
stage.addActor(button);
registerButton(button);
return button;
}
else if(buttonType == eButtonType.ImageButton)
{
final Button button = createImageButton(x, y, width, height, buttonText);
button.addListener(activateEvent);
button.addListener(new ClickListener() {
@Override
public void clicked(InputEvent event, float x, float y) {
button.fire(new ButtonActivatedEvent());
super.clicked(event, x, y);
}
});
stage.addActor(button);
registerButton(button);
return button;
}
return null;
}
public void clearButtons()
{
buttons.clear();
selectedButton = -1;
menuBackButton = -1;
}
public TextButton getTextButton(String buttonName)
{
TextButton bButton = null;
for(Button button : buttons)
{
if(buttonName == button.getName())
bButton = (TextButton)button;
}
return bButton;
}
public ImageButton getImageButton(String buttonName)
{
ImageButton bButton = null;
for(Button button : buttons)
{
if(buttonName == button.getName())
bButton = (ImageButton)button;
}
return bButton;
}
public void registerButton(Button button)
{
buttons.add(button);
//button.setChecked(true);
//buttons.get(0).setChecked(true);
}
public void disableButton(String buttonName)
{
getTextButton(buttonName).setDisabled(true);
getTextButton(buttonName).setVisible(false);
}
public void enableButton(String buttonName)
{
getTextButton(buttonName).setDisabled(false);
getTextButton(buttonName).setVisible(true);
}
public void setMenuBackButton(int buttonId)
{
if(buttonId < 0)
buttonId = 0;
else if (buttonId > buttons.size() -1)
buttonId = buttons.size() -1;
menuBackButton = buttonId;
}
public boolean setMenuBackButton(String buttonName)
{
if(SGame.CurrentPlatform == SGame.ePlatform.Android)
return true;
boolean found = false;
int foundValue = -1;
for(int i = 0; i < buttons.size(); ++i)
{
if(buttonName == buttons.get(i).getName())
{
foundValue = i;
found = true;
}
}
if(found)
{
menuBackButton = foundValue;
}
return found;
}
public void setSelectedButton(int buttonId)
{
if(SGame.CurrentPlatform == SGame.ePlatform.Android)
return;
if(selectedButton < buttons.size())
if(selectedButton != -1)
buttons.get(selectedButton).setChecked(false);
if(buttonId < 0)
buttonId = 0;
else if (buttonId > buttons.size() -1)
buttonId = buttons.size() -1;
selectedButton = buttonId;
buttons.get(selectedButton).setChecked(true);
}
public boolean setSelectedButton(String buttonName)
{
if(SGame.CurrentPlatform == SGame.ePlatform.Android)
return true;
boolean found = false;
int foundValue = -1;
for(int i = 0; i < buttons.size(); ++i)
{
if(buttonName == buttons.get(i).getName())
{
foundValue = i;
found = true;
}
}
if(found)
{
if(selectedButton != -1)
buttons.get(selectedButton).setChecked(false);
selectedButton = foundValue;
buttons.get(selectedButton).setChecked(true);
}
return found;
}
void fireActivateButtonEvent()
{
if(!buttons.get(selectedButton).isDisabled())
buttons.get(selectedButton).fire(new ButtonActivatedEvent());
}
void fireMenuBackEvent()
{
if(menuBackButton != -1) {
if (!buttons.get(menuBackButton).isDisabled())
buttons.get(menuBackButton).fire(new ButtonActivatedEvent());
}
}
public void menuUp()
{
int oldBtn = selectedButton;
int newBtn = oldBtn - 1;
if(newBtn < 0)
newBtn = 0;
if(buttons.get(newBtn).isDisabled())
return;
buttons.get(oldBtn).setChecked(false);
buttons.get(newBtn).setChecked(true);
selectedButton = newBtn;
}
public void menuDown()
{
int oldBtn = selectedButton;
int newBtn = oldBtn + 1;
if(newBtn > buttons.size() -1)
newBtn = buttons.size() -1;
if(buttons.get(newBtn).isDisabled())
return;
buttons.get(oldBtn).setChecked(false);
buttons.get(newBtn).setChecked(true);
selectedButton = newBtn;
}
@Override
public boolean keyDown(int keycode) {
if(keycode == Keys.ENTER || keycode == Keys.SPACE)
{
fireActivateButtonEvent();
return true;
}
else if(keycode == Keys.ESCAPE || keycode == Keys.BACKSPACE)
{
fireMenuBackEvent();
return true;
}
else if(keycode == Keys.UP || keycode == Keys.LEFT)
{
menuUp();
return true;
}
else if(keycode == Keys.DOWN || keycode == Keys.RIGHT)
{
menuDown();
return true;
}
return false;
}
@Override
public boolean keyUp(int keycode) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean touchDown(int x, int y, int pointer, int button) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean touchUp(int x, int y, int pointer, int button) {
return false;
}
@Override
public boolean touchDragged(int x, int y, int pointer) {
return false;
}
@Override
public boolean povMoved(Controller controller, int povIndex, PovDirection value) {
switch(value)
{
case north:
case west:
menuUp();
break;
case south:
case east:
menuDown();
break;
default:
break;
}
return false;
}
public void update(float delta)
{
if(SGame.activeController != null)
updateAxis();
}
private void updateAxis(float axis)
{
if(timeSinceLast > 100)
{
if (axis > 0.5f) {
menuDown();
timeSinceLast = 0;
} else if (axis < -0.5f) {
menuUp();
timeSinceLast = 0;
}
}
}
private void updateAxis()
{
timeSinceLast += TimeUtils.timeSinceMillis(lastTime);
lastTime = TimeUtils.millis();
updateAxis(SInput.getAxisValue(Ouya.AXIS_LEFT_X));
updateAxis(SInput.getAxisValue(Ouya.AXIS_LEFT_Y));
//updateAxis(SGame.controller.getAxis(Ouya.AXIS_LEFT_X));
//updateAxis(SGame.controller.getAxis(Ouya.AXIS_LEFT_Y));
}
private long timeSinceLast = 0;
private long lastTime = 0;
@Override
public boolean axisMoved(Controller controller, int axisIndex, float value) {
/*
timeSinceLast += TimeUtils.timeSinceMillis(lastTime);
lastTime = TimeUtils.millis();
System.out.println(timeSinceLast);
if(timeSinceLast > 50)
{
if (axisIndex == Ouya.AXIS_LEFT_X || axisIndex == Ouya.AXIS_LEFT_Y) //1 is left stick y axis, 0 is x axis
{
if (value > 0.5f) {
menuDown();
timeSinceLast = 0;
return true;
} else if (value < -0.5f) {
menuUp();
timeSinceLast = 0;
return true;
}
}
}
*/
return false;
}
@Override
public boolean buttonDown(Controller controller, int buttonIndex) {
if(SInput.getButtonIndexMatch(buttonIndex, SInput.eControllerButtons.Menu_Accept))
//if(buttonIndex == 0 || buttonIndex == 7 || buttonIndex == Ouya.BUTTON_O || buttonIndex == Ouya.BUTTON_MENU) //0 is A, 7 is start
{
fireActivateButtonEvent();
return true;
}
if(SInput.getButtonIndexMatch(buttonIndex, SInput.eControllerButtons.Menu_Back))
//if(buttonIndex == 1 || buttonIndex == 6 || buttonIndex == Ouya.BUTTON_A) //1 is B, 6 is back
{
fireMenuBackEvent();
return true;
}
if(SInput.getButtonIndexMatch(buttonIndex, SInput.eControllerButtons.Menu_Up)
|| SInput.getButtonIndexMatch(buttonIndex, SInput.eControllerButtons.Menu_Left))
//if(buttonIndex == Ouya.BUTTON_DPAD_UP || buttonIndex == Ouya.BUTTON_DPAD_LEFT)
{
menuUp();
return true;
}
if(SInput.getButtonIndexMatch(buttonIndex, SInput.eControllerButtons.Menu_Down)
|| SInput.getButtonIndexMatch(buttonIndex, SInput.eControllerButtons.Menu_Right))
//if(buttonIndex == Ouya.BUTTON_DPAD_DOWN || buttonIndex == Ouya.BUTTON_DPAD_RIGHT)
{
menuDown();
return true;
}
return false;
}
}
|
JavaScript | UTF-8 | 1,500 | 4.3125 | 4 | [] | no_license | /* QUESTION: Working from left-to-right if no digit is exceeded by the digit to its left it is called an increasing number; for example, 134468.
Similarly if no digit is exceeded by the digit to its right it is called a decreasing number; for example, 66420.
We shall call a positive integer that is neither increasing nor decreasing a "bouncy" number; for example, 155349.
Clearly there cannot be any bouncy numbers below one-hundred, but just over half of the numbers below one-thousand (525) are bouncy. In fact, the least number for which the proportion of bouncy numbers first reaches 50% is 538.
Surprisingly, bouncy numbers become more and more common and by the time we reach 21780 the proportion of bouncy numbers is equal to 90%.
Find the least number for which the proportion of bouncy numbers is exactly 99%.
ANSWER: 1587000 (Takes ~900ms)
*/
console.time('time');
function isBouncy(n) {
let inc = 0;
let dec = 0;
n = n
.toString()
.split('')
.map(Number);
for (let i = 0; i < n.length; i++) {
if (n[i] > n[i + 1]) {
dec++;
} else if (n[i] < n[i + 1]) {
inc++
}
if (dec && inc) {
return true;
}
}
return false;
}
let count = 0;
let limit = 1587000; //found limit by manually narrowing the range (guessing xD)
for (let i = 100; i <= limit; i++) {
if (isBouncy(i)) count++;
}
console.log(count, limit, (count / limit) * 100);
console.timeEnd('time'); |
C | UTF-8 | 2,697 | 2.671875 | 3 | [] | no_license | /*
** EPITECH PROJECT, 2019
** MUL_my_hunter_2019
** File description:
** my_huter.c
*/
#include "../my_tower.h"
void display_nb_tow(sfRenderWindow *window, sprite_t *sprite)
{
char *text = cat(int_to_string(sprite->tow_alive), "/99");
sfText_setString(sprite->text_nb_tow, text);
sfText_setFont(sprite->text_nb_tow, sprite->font_life);
sfText_setCharacterSize(sprite->text_nb_tow, 35 * sprite->hight / 1920);
sfText_setColor(sprite->text_nb_tow, sfGreen);
sfRenderWindow_drawText(window, sprite->text_nb_tow, NULL);
sfText_setPosition(sprite->text_nb_tow, (sfVector2f){croix\
(783, 'l', sprite), croix(955, 'h', sprite)});
free(text);
}
void display_wave(sfRenderWindow *window, sprite_t *sprite)
{
char *text = cat("wave :", int_to_string(sprite->vague));
sfText_setString(sprite->text_wave, text);
sfText_setFont(sprite->text_wave, sprite->font_life);
sfText_setCharacterSize(sprite->text_wave, 50 * sprite->hight / 1920);
sfText_setColor(sprite->text_wave, sfBlack);
sfRenderWindow_drawText(window, sprite->text_wave, NULL);
sfText_setPosition(sprite->text_wave, (sfVector2f){croix\
(871, 'l', sprite), croix(1, 'h', sprite)});
free(text);
}
void display_pause(sfRenderWindow *window, sprite_t *sprite)
{
sfSprite_setScale(sprite->button_pause_sprt, (sfVector2f) {\
croix(1, 'l', sprite), croix(1, 'h', sprite)});
sfSprite_setPosition(sprite->button_pause_sprt, (sfVector2f) {\
croix(5, 'l', sprite), croix(5, 'h', sprite)});
sfRenderWindow_drawSprite(window, sprite->button_pause_sprt, NULL);
}
void display_menu_pause(sfRenderWindow *window, sprite_t *sprite)
{
if (sprite->pause == 1) {
sfSprite_setScale(sprite->menu_pause_sprt, (sfVector2f) {\
croix(1, 'l', sprite), croix(1, 'h', sprite)});
sfRenderWindow_drawSprite(window, sprite->menu_pause_sprt, NULL);
}
}
void game(sfRenderWindow *window, sprite_t *sprite)
{
if (sprite->pause == 0) {
update_type_enn(sprite);
move_enn(sprite);
update_enn(sprite);
shot_tow(sprite, window);
update_waves(sprite);
}
sfRenderWindow_clear(window, sfBlack);
sfSprite_setScale(sprite->map, (sfVector2f){1 * sprite->hight / 1920\
, 1 * sprite->weidth / 1080});
sfRenderWindow_drawSprite(window, sprite->map, NULL);
draw_tow(sprite, window);
draw_enn(sprite, window);
display_gold(sprite, window);
display_pause(window, sprite);
display_life(window, sprite);
display_wave(window, sprite);
display_nb_tow(window, sprite);
display_menu_pause(window, sprite);
draw_cursor(window, sprite);
sfRenderWindow_display(window);
} |
Markdown | UTF-8 | 2,811 | 2.578125 | 3 | [] | no_license | ---
titre: "Prédictions en temps réel de l'épidémie de maladie à virus Ebola 2018-2019 en République démocratique du Congo à l'aide de modèles de processus ponctuels de Hawkes."
auteurs: "Kelly et al."
journal: "Epidemics"
année: "2019"
lien: https://doi.org/10.1016/j.epidem.2019.100354
image: /images/publications/31395373.jpg
---
Prédictions en temps réel de l'épidémie de maladie à virus Ebola 2018-2019 en République démocratique du Congo à l'aide de modèles de processus ponctuels de Hawkes.
Kelly JD, Park J, Harrigan RJ, Hoff NA, Lee SD, Wannier R, Selo B, Mossoko M, Njoloko B, Okitolonda-Wemakoy E, Mbala-Kingebeni P, Rutherford GW, Smith TB, Ahuka-Mundeke S, Muyembe-Tamfum JJ, Rimoin AW, Schoenberg FP
Résumé
En 16 juin 2019, une épidémie de maladie à virus Ebola (MVE) a entraîné 2136 cas signalés dans la région nord-est de la République démocratique du Congo (RDC). Alors que cette épidémie continue de menacer la vie et les moyens de subsistance de personnes souffrant déjà de troubles civils et de conflits armés, des modèles mathématiques relativement simples et leurs prédictions à court terme ont le potentiel d'informer les efforts de réponse à Ebola en temps réel. Nous avons appliqué des processus ponctuels de Hawkes estimés de manière non paramétrique et récemment développés pour modéliser le nombre de cas cumulés attendus en utilisant le nombre de cas quotidiens de 3 mai 2018 a 16 juin 2019, initialement signalés par le ministère de la Santé de la RDC et confirmés ultérieurement dans les rapports de situation de l'Organisation mondiale de la santé. Nous avons généré des estimations probabilistes de l'épidémie de MVE en cours en RDC s'étendant à la fois avant et après le 16 juin 2019, et évalué leur précision en comparant les tailles d'épidémie prévues par rapport aux tailles réelles, les scores de log-vraisemblance hors échantillon et l'erreur par jour dans la prévision médiane. Les tailles médianes estimées des épidémies pour les projections prospectives à trois, six et neuf semaines réalisées à partir des données jusqu'au 16 juin 2019 étaient respectivement de 2317 (IP 95 % : 2222, 2464), 2440 (IP 95 % : 2250, 2790) et 2544 (IP 95 % : 2273, 3205). La projection sur neuf semaines a connu une certaine dégradation avec une erreur quotidienne dans la prévision médiane de 6,73 cas, tandis que les projections sur six et trois semaines étaient plus fiables, avec des erreurs correspondantes de 4,96 et 4,85 cas par jour, respectivement. Nos résultats suggèrent que le processus ponctuel de Hawkes peut servir de modèle statistique facile à appliquer pour prédire les trajectoires des épidémies d'EVD en temps quasi réel afin de mieux éclairer la prise de décision et l'allocation des ressources pendant les efforts de réponse à Ebola.
|
Swift | UTF-8 | 4,362 | 3.171875 | 3 | [
"MIT"
] | permissive | //
// ColorPaletteTests.swift
// UIKitSwagger
//
// Created by Sam Odom on 12/13/14.
// Copyright (c) 2014 Swagger Soft. All rights reserved.
//
import UIKit
import XCTest
@testable import UIKitSwagger
class ColorPaletteTests: XCTestCase {
var palette = ColorPalette()
var colors: [String:UIColor]!
override func setUp() {
super.setUp()
colors = [
"red": Red,
"blue": Blue,
"green": Green
]
}
func testCreatingEmptyPalette() {
XCTAssertEqual(palette.numberOfColors, 0, "There should be no colors in an empty palette")
}
func testCreatingPaletteWithColors() {
palette = ColorPalette(colors: colors)
XCTAssertEqual(palette.numberOfColors, 3, "The palette should be created with three colors")
XCTAssertEqual(palette.colorNamed("red")!, Red, "The supplied colors should be added to the palette")
XCTAssertEqual(palette.colorNamed("blue")!, Blue, "The supplied colors should be added to the palette")
XCTAssertEqual(palette.colorNamed("green")!, Green, "The supplied colors should be added to the palette")
}
func testPaletteProvidesColorDictionary() {
palette = ColorPalette(colors: colors)
XCTAssertEqual(palette.allColors, colors, "The palette should provide all of the colors with their names")
}
func testColorPaletteAddsColorsToDictionary() {
palette.addColor(Red, named: "rosso")
XCTAssertEqual(palette.numberOfColors, 1, "There should be one color in the dictionary")
XCTAssertEqual(palette.colorNamed("rosso")!, Red, "The palette should add colors to its dictionary by a name string")
palette.addColor(Blue, named: "blou")
XCTAssertEqual(palette.numberOfColors, 2, "There should be two colors in the dictionary")
XCTAssertEqual(palette.colorNamed("blou")!, Blue, "The palette should add colors to its dictionary by a name string")
}
func testColorPaletteReplacesColorsInDictionary() {
palette.addColor(Red, named: "rosso")
palette.addColor(Blue, named: "rosso")
XCTAssertEqual(palette.numberOfColors, 1, "There should be one color in the dictionary")
XCTAssertEqual(palette.colorNamed("rosso")!, Blue, "The palette should replace colors in its dictionary")
}
func testColorPaletteRemovesColorsFromDictionary() {
palette.addColor(Red, named: "red")
palette.removeColorNamed("red")
XCTAssertEqual(palette.numberOfColors, 0, "There should be no colors left in the dictionary")
}
func testColorPaletteRemovesAllColors() {
palette = ColorPalette(colors: colors)
palette.removeAllColors()
XCTAssertEqual(palette.numberOfColors, 0, "The palette should clear all of its colors")
}
func testColorPaletteReturnsColorsByName() {
palette = ColorPalette(colors: colors)
XCTAssertEqual(palette.colorNamed("red")!, Red, "The palette should return colors by their name")
XCTAssertEqual(palette.colorNamed("blue")!, Blue, "The palette should return colors by their name")
XCTAssertEqual(palette.colorNamed("green")!, Green, "The palette should return colors by their name")
XCTAssertNil(palette.colorNamed("pink"), "No color should be returned if it does not exist in the palette's dictionary")
}
func testSettingColorWithSubscript() {
palette["red"] = Red
XCTAssertEqual(palette.colorNamed("red")!, Red, "The palette should add the color named by the subscript")
}
func testReplacingColorWithSubscript() {
palette.addColor(Red, named: "red")
palette["red"] = Blue
XCTAssertEqual(palette.colorNamed("red")!, Blue, "The palette should replace the color named by the subscript")
}
func testGettingColorWithSubscript() {
palette.addColor(Red, named: "red")
XCTAssertEqual(palette["red"]!, Red, "The palette should return the color named by the subscript")
XCTAssertNil(palette["pink"], "The palette should not return a color if it is not part of the palette")
}
func testClearingColorWithSubscript() {
palette.addColor(Red, named: "red")
palette["red"] = nil
XCTAssertNil(palette.colorNamed("red"), "The palette should clear the color named by the subscript")
}
}
|
Python | UTF-8 | 741 | 3.671875 | 4 | [] | no_license | # def imprimir_mensaje():
# print("mensaje espécial :")
# print("estoy aprendiendo funciones")
# imprimir_mensaje()
# imprimir_mensaje()
# imprimir_mensaje()
# def impresion_datos(opcion):
# print("hola")
# print("hola como estas")
# print(opcion)
# print('adios')
# opcion = input("Elige una opcion(1,2,3): ")
# if opcion == '1':
# impresion_datos("Eligiste la opcion 1")
# elif opcion == '2':
# impresion_datos("Eligiste la opcion 2")
# elif opcion == '3':
# impresion_datos("Eligiste la opcion 3")
# else:
# print("eliga la opcion correcta")
def suma(a,b):
print("Se suman dos números")
resultado = a + b
return resultado
resultado_suma = suma(1,4)
print(resultado_suma)
|
Markdown | UTF-8 | 1,638 | 2.8125 | 3 | [] | no_license | # Visualizing Deep Similarity Networks
## 1.Abstract
对于优化图像嵌入的卷积神经网络模型,我们提出了一种方法来突出显示成对相似性最强的图像区域。 这项工作是为分类网络开发的可视化工具的必然结果,但适用于更适合于相似性学习的问题域。 可视化效果显示了经过微调的相似性网络如何学习专注于不同的功能。 我们还概括了使用不同池化策略嵌入网络的方法,并提供了一种简单的机制来支持对查询图像中的对象或子区域进行图像相似性搜索。
## 2.Conclusion
我们提出一种方法来可视化负责嵌入网络中成对相似性的图像区域。尽管先前的一些工作可视化了其中的一些组件,但我们发现最上面的几个组件并不能解释大多数相似性。我们的方法明确分解了两个图像之间的整体相似性评分,并将其分配给相关的图像区域。
我们说明了使用此可视化工具的多种可能方式,探讨了通过最大池化和平均池化训练的网络之间的差异,说明了网络的焦点在训练过程中如何变化,并提供了一种使用这种空间相似性分解来搜索匹配项的方法到图像中的对象或子区域。
相似性网络的研究领域非常活跃,探索池化策略的变化,学习或明确预定义的合并特征的线性变换,以及促进和合奏策略。
我们已经在[github](https://github.com/GWUvision/Similarity-Visualization)上共享了该项目的代码,其目标是这些可视化将提供关于嵌入如何受这些算法选择影响的更多见解。
|
Ruby | UTF-8 | 380 | 3.25 | 3 | [
"MIT"
] | permissive | (1..25).each do |d|
require_relative "day#{d}/main"
end
loop do
print 'Choose day to run (any non-number to exit): '
day = gets.to_i
break unless day.between? 1, 25
puts
puts "== DAY #{day} =="
ref = Object.const_get("Day#{day}")::Main.new(File.read("day#{day}/input.txt"))
puts "PART 1: #{ref.part1}"
puts "PART 2: #{ref.part2}"
puts '== END =='
puts
end
|
Python | UTF-8 | 1,959 | 2.578125 | 3 | [] | no_license | import numpy as np
from pypost.dynamicalSystem import DynamicalSystem
from pypost.planarKinematics.PlanarForwardKinematics import PlanarForwardKinematics
class Pendulum(DynamicalSystem, PlanarForwardKinematics):
def __init__(self, dataManager):
PlanarForwardKinematics.__init__(self, dataManager, 1)
DynamicalSystem.__init__(self, dataManager, 1)
self.maxTorque = np.array([30])
self.noiseState = 0
self.stateMinRange = np.array([-np.pi, -20])
self.stateMaxRange = np.array([ np.pi, 20])
self.linkProperty('stateMinRange', 'stateMinRange')
self.linkProperty('stateMaxRange', 'stateMaxRange')
self.linkProperty('maxTorque', 'maxTorque')
self.lengths = 0.5
self.masses = 10
self.inertias = self.masses * self.lengths**2 / 3
self.g = 9.81
self.sim_dt = 1e-4
self.friction = 0.2
self.dataManager.setRange('states', self.stateMinRange, self.stateMaxRange)
self.dataManager.setRange('actions', - self.maxTorque, self.maxTorque)
# self.initObject()
def transitionFunction(self, states, actions):
actions = np.maximum(-self.maxTorque, np.minimum(actions, self.maxTorque))
actionNoise = actions + self.getControlNoise(states, actions)
nSteps = self.dt / self.sim_dt
if nSteps != np.round(nSteps):
print('Warning from Pendulum: dt does not match up')
nSteps = np.round(nSteps)
c = self.g * self.lengths * self.masses / self.inertias
for i in range(0, int(nSteps)):
velNew = states[:, 1:2] + self.sim_dt * (c * np.sin(states[:, 0:1])
+ actionNoise / self.inertias
- states[:, 1:2] * self.friction )
states = np.concatenate((states[:, 0:1] + self.sim_dt * velNew, velNew), axis=1)
return states
|
Python | UTF-8 | 181 | 3.375 | 3 | [] | no_license | terus_tanya = True
while terus_tanya :
temp = raw_input('masukkan angka kurang dari 10 !! : ')
angka = int(temp)
if angka < 10:
terus_tanya = False
else:
terus_tanya = True
|
TypeScript | UTF-8 | 904 | 2.71875 | 3 | [] | no_license | import sql from 'mysql';
class Database {
private connection: sql.Connection;
constructor() {
this.connection = sql.createConnection({
host: process.env.DB_HOST,
user: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DB_DATABASE,
});
}
db(): sql.Connection {
// Add handlers.
// this.addDisconnectHandler();
// this.connection.connect();
// console.log('Connected to database.');
return this.connection;
}
private addDisconnectHandler(): void {
this.connection.on('error', error => {
if (error instanceof Error) {
if (error.code === 'PROTOCOL_CONNECTION_LOST') {
console.error(error.stack);
console.log('Lost connection. Reconnecting...');
this.db();
} else if (error.fatal) {
throw error;
}
}
});
}
}
export default Database;
|
Ruby | UTF-8 | 4,082 | 3.5 | 4 | [] | no_license | # 四則演算が1つのパターン
def check1(target_ar, check_target)
for i in 1...4 do
t1 = target_ar.values_at(0).join("").to_i
t2 = target_ar.values_at(1,2,3).join("").to_i
tmp = cal([t1, t2], i)
p "answer![0] --> #{tmp}" if tmp == check_target
t1 = target_ar.values_at(0,1).join("").to_i
t2 = target_ar.values_at(2,3).join("").to_i
tmp = cal([t1, t2], i)
p "answer![1] --> #{tmp}" if tmp == check_target
t1 = target_ar.values_at(0,1,2).join("").to_i
t2 = target_ar.values_at(3).join("").to_i
tmp = cal([t1, t2], i)
p "answer![2] --> #{tmp}" if tmp == check_target
end
end
# 四則演算が2つのパターン
def check2(target_ar, check_target)
t1 = target_ar.values_at(0).join("").to_i
t2 = target_ar.values_at(1,2).join("").to_i
t3 = target_ar.values_at(3).join("").to_i
tmp = cal2([t1,t2,t3])
ans = tmp.find {|num| num == check_target }
p "answer![3] --> #{ans}" unless ans.nil?
t1 = target_ar.values_at(0,1).join("").to_i
t2 = target_ar.values_at(2).join("").to_i
t3 = target_ar.values_at(3).join("").to_i
tmp = cal2([t1,t2,t3])
ans = tmp.find {|num| num == check_target }
p "answer![4] --> #{ans}" unless ans.nil?
t1 = target_ar.values_at(0).join("").to_i
t2 = target_ar.values_at(1).join("").to_i
t3 = target_ar.values_at(2,3).join("").to_i
tmp = cal2([t1,t2,t3])
ans = tmp.find {|num| num == check_target }
p "answer![5] --> #{ans}" unless ans.nil?
end
# 四則演算が3つのパターン
def check3(target_ar, check_target)
ret = []
t1 = target_ar[0].to_i
t2 = target_ar[1].to_i
t3 = target_ar[2].to_i
t4 = target_ar[3].to_i
ret << t1 + t2 + t3 + t4
ret << t1 + t2 - t3 - t4
ret << t1 + t2 - t3 + t4
ret << t1 + t2 - t3 * t4
ret << t1 + t2 * t3 * t4
ret << t1 + t2 * t3 - t4
ret << t1 + t2 * t3 + t4
ret << t1 - t2 - t3 - t4
ret << t1 - t2 + t3 + t4
ret << t1 - t2 + t3 - t4
ret << t1 - t2 + t3 * t4
ret << t1 - t2 * t3 * t4
ret << t1 - t2 * t3 - t4
ret << t1 - t2 * t3 + t4
ret << t1 * t2 * t3 * t4
ret << t1 * t2 + t3 + t4
ret << t1 * t2 + t3 - t4
ret << t1 * t2 + t3 * t4
ret << t1 * t2 * t3 * t4
ret << t1 * t2 * t3 - t4
ret << t1 * t2 * t3 + t4
ans = ret.find {|num| num == check_target }
p "answer![6] --> #{ans}" unless ans.nil?
end
def cal(ar, type)
total = 0
ar.each do |val|
if total == 0
total = val
next
end
total += val if type == 1
total -= val if type == 2
total *= val if type == 3
end
total
end
def cal2(ar)
ret = []
ret << ar[0] + ar[1] + ar[2]
ret << ar[0] + ar[1] - ar[2]
ret << ar[0] + ar[1] * ar[2]
ret << ar[0] - ar[1] + ar[2]
ret << ar[0] - ar[1] - ar[2]
ret << ar[0] - ar[1] * ar[2]
ret << ar[0] * ar[1] + ar[2]
ret << ar[0] * ar[1] - ar[2]
ret << ar[0] * ar[1] * ar[2]
ret
end
for target in 1000..9999 do
check_target = target.to_s.split("").reverse.join("").to_i
# 頭が0から始まる数は作れない
next unless check_target.to_s.length == 4
check1(target.to_s.split(""), check_target)
check2(target.to_s.split(""), check_target)
check3(target.to_s.split(""), check_target)
end
##########################
# best answer
##########################
# ※※rubyの場合0から始まる数値は8進数として扱われる為、0の場合の例外処理が必要
ops = ["+", "-", "*", "/", ""]
for target in 5931..5931 do
tt = target.to_s.split("")
check_target = target.to_s.split("").reverse.join("").to_i
ops.each do |op1|
ops.each do |op2|
ops.each do |op3|
cal = tt[0].to_s + op1 + tt[1].to_s + op2 + tt[2].to_s + op3 + tt[3].to_s
r = eval cal
p "target:#{target} --> #{r} : #{cal}" if check_target == r
end
end
end
end
|
Java | UTF-8 | 1,155 | 2.609375 | 3 | [] | no_license | package com.gaoxi.facade.redis;
import java.io.Serializable;
import java.util.Map;
public interface RedisService {
/**
* 批量删除
*
* @param keys key数组
*/
void remove(final String... keys);
/**
* 批量删除指定key
*/
void removePattern(final String pattern);
/**
* 删除指定key
*/
void remove(final String key);
/**
* 判断指定key是否存在
*/
boolean exists(final String key);
/**
* 获取指定key
*/
Object get(final String key);
/**
* 添加key-value(使用默认失效时间)
*/
boolean set(final String key, Serializable value);
/**
* 添加key-value(指定失效时间)
*
* @param expireTime 失效时间(单位秒)
*/
boolean set(final String key, Serializable value, Long expireTime);
/**
* 存储map
*
* @param expireTime 失效时间为null则永久生效(单位秒)
*/
<K, HK, HV> boolean setMap(K key, Map<HK, HV> map, Long expireTime);
/**
* 获取map
*/
<K, HK, HV> Map<HK, HV> getMap(final K key);
}
|
Markdown | UTF-8 | 2,323 | 2.765625 | 3 | [
"BSD-3-Clause"
] | permissive | # GrapesJS MJML
This plugin enables the usage of [MJML](https://mjml.io/) components inside the GrapesJS environment. MJML components are rendered in real-time using the official compiler, therefore the result is, almost, the same as using the [MJML Live Editor](https://mjml.io/try-it-live).
[Demo](http://grapesjs.com/demo-mjml.html)
<p align="center"><img src="http://grapesjs.com/img/grapesjs-mjml-demo.jpg" alt="GrapesJS" align="center"/></p>
<br/>
Supported components:
`mj-container`
`mj-section`
`mj-column`
`mj-text`
`mj-image`
`mj-button`
`mj-social`
`mj-divider`
`mj-spacer`
## Options
|Option|Description|Default|
|-|-|-
|`categoryLabel`|Category for blocks|`''`|
|`importPlaceholder`|Import placeholder MJML|`''`|
|`modalTitleImport`|Title for the import modal|`Import MJML`|
|`modalBtnImport`|Test for the import button|`Import`|
|`modalLabelImport`|Description for the import modal|`''`|
|`modalTitleExport`|Title for the export modal|`Export MJML`|
|`modalLabelExport`|Description for the export modal|`''`|
|`overwriteExport`|Overwrite default export command|`true`|
|`preMjml`|String before the MJML in export code|`''`|
|`postMjml`|String after the MJML in export code|`''`|
|`resetBlocks`|Clean all previous blocks if true|`true`|
|`resetDevices`|Clean all previous devices and set a new one for mobile|`true`|,
|`resetStyleManager`|Reset the Style Manager and add new properties for MJML|`true`|,
## Download
* `npm i grapesjs-mjml`
## Usage
```html
<link href="path/to/grapes.min.css" rel="stylesheet"/>
<script src="path/to/grapes.min.js"></script>
<script src="path/to/grapesjs-mjml.min.js"></script>
<div id="gjs">
<!-- Your MJML body here -->
<mj-container>
<mj-section>
<mj-column>
<mj-text>My Company</mj-text>
</mj-column>
</mj-section>
<mj-container>
</div>
<script type="text/javascript">
var editor = grapesjs.init({
fromElement: 1,
container : '#gjs',
plugins: ['grapesjs-mjml'],
pluginsOpts: {
'grapesjs-mjml': {/* ...options */}
}
});
</script>
```
## Development
Clone the repository
```sh
$ git clone https://github.com/artf/grapesjs-mjml.git
$ cd grapesjs-mjml
```
Install it
```sh
$ npm i
```
Start the dev server
```sh
$ npm start
```
## License
BSD 3-Clause
|
C# | UTF-8 | 2,113 | 2.953125 | 3 | [
"MIT"
] | permissive | using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using AnimalShelter.Models;
using System.Linq;
namespace AnimalShelter.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class AnimalsController : ControllerBase
{
private readonly AnimalShelterContext _db;
public AnimalsController(AnimalShelterContext db)
{
_db = db;
}
// GET api/animals
[HttpGet]
public async Task<ActionResult<IEnumerable<Animal>>> Get()
{
return await _db.Animals.ToListAsync();
}
// GET: api/Animals/5
[HttpGet("{id}")]
public async Task<ActionResult<Animal>> GetAnimal(int id)
{
var animal = await _db.Animals.FindAsync(id);
if (animal == null)
{
return NotFound();
}
return animal;
}
[HttpPost]
public async Task<ActionResult<Animal>> Post(Animal animal)
{
_db.Animals.Add(animal);
await _db.SaveChangesAsync();
return CreatedAtAction(nameof(GetAnimal), new { id = animal.AnimalId }, animal);
}
// PUT: api/Animals/5
[HttpPut("{id}")]
public async Task<IActionResult> Put(int id, Animal animal)
{
if (id != animal.AnimalId)
{
return BadRequest();
}
_db.Entry(animal).State = EntityState.Modified;
try
{
await _db.SaveChangesAsync();
}
catch (DbUpdateConcurrencyException)
{
if (!AnimalExists(id))
{
return NotFound();
}
else
{
throw;
}
}
return NoContent();
}
private bool AnimalExists(int id)
{
return _db.Animals.Any(e => e.AnimalId == id);
}
// DELETE: api/Animals/5
[HttpDelete("{id}")]
public async Task<IActionResult> DeleteAnimal(int id)
{
var animal = await _db.Animals.FindAsync(id);
if (animal == null)
{
return NotFound();
}
_db.Animals.Remove(animal);
await _db.SaveChangesAsync();
return NoContent();
}
}
}
|
Java | UTF-8 | 6,990 | 2.03125 | 2 | [] | no_license | /*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package fxml;
import Entities.personne;
import java.io.IOException;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.control.Alert;
import javafx.scene.control.Button;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javax.swing.text.Document;
import Services.personneService ;
/**
* FXML Controller class
*
* @author dorra
*/
public class ModCoordController implements Initializable {
@FXML
private TextField modnc;
@FXML
private TextField modpc;
@FXML
private PasswordField modmdpc;
@FXML
private Button bmod3;
@FXML
private Button bmod2;
@FXML
private Button bmod1;
@FXML
private Button rett;
@FXML
private TextField emailemail;
/**
* Initializes the controller class.
*/
@Override
public void initialize(URL url, ResourceBundle rb) {
// TODO
//modif nom
modnc.setText(LoginController.PERSONNECONNECTEE.getNom());
modpc.setText(LoginController.PERSONNECONNECTEE.getPrenom());
modmdpc.setText(LoginController.PERSONNECONNECTEE.getPassword());
emailemail.setText(LoginController.PERSONNECONNECTEE.getEmail());
bmod1.setOnAction(e->{
if(modnc.getText().equalsIgnoreCase("") ||emailemail.getText().equalsIgnoreCase("") ){
Alert alert = new Alert(Alert.AlertType.WARNING);
alert.setTitle("Erreur");
alert.setHeaderText(null);
alert.setContentText("Veuillez remplir tous les champs !");
alert.show();}
else{
personne p = new personne();
p.setEmail(emailemail.getText());
personneService ps1 = new personneService();
ps1.updateclient_n(modnc.getText(), emailemail.getText());
Parent root ;
try{
root=FXMLLoader.load(getClass().getResource("ModCoord.fxml"));
bmod1.getScene().setRoot(root);
} catch (IOException ex) {
Logger.getLogger(ModCoordController.class.getName()).log(Level.SEVERE, null, ex);
}
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("Confirmation");
alert.setHeaderText(null);
alert.setContentText("nom modifiée avec succés");
alert.show();}
});
//modif prenom
bmod2.setOnAction(e->{
if(modpc.getText().equalsIgnoreCase("") ||emailemail.getText().equalsIgnoreCase("") ){
Alert alert = new Alert(Alert.AlertType.WARNING);
alert.setTitle("Erreur");
alert.setHeaderText(null);
alert.setContentText("Veuillez remplir tous les champs !");
alert.show();}
else{
personne p = new personne();
p.setEmail(emailemail.getText());
personneService ps1 = new personneService();
ps1.updateclient_n(modpc.getText(), emailemail.getText());
Parent root ;
try{
root=FXMLLoader.load(getClass().getResource("ModCoord.fxml"));
bmod2.getScene().setRoot(root);
} catch (IOException ex) {
Logger.getLogger(ModCoordController.class.getName()).log(Level.SEVERE, null, ex);
}
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("Confirmation");
alert.setHeaderText(null);
alert.setContentText("prenom modifiée avec succés");
alert.show();}
});
//modif mdp
bmod3.setOnAction(e->{
if(modmdpc.getText().equalsIgnoreCase("") ||emailemail.getText().equalsIgnoreCase("") ){
Alert alert = new Alert(Alert.AlertType.WARNING);
alert.setTitle("Erreur");
alert.setHeaderText(null);
alert.setContentText("Veuillez remplir tous les champs !");
alert.show();}
else{
personne p = new personne();
p.setEmail(emailemail.getText());
personneService ps1 = new personneService();
ps1.updateclient_n(modmdpc.getText(), emailemail.getText());
Parent root ;
try{
root=FXMLLoader.load(getClass().getResource("ModCoord.fxml"));
bmod3.getScene().setRoot(root);
} catch (IOException ex) {
Logger.getLogger(ModCoordController.class.getName()).log(Level.SEVERE, null, ex);
}
Alert alert = new Alert(Alert.AlertType.INFORMATION);
alert.setTitle("Confirmation");
alert.setHeaderText(null);
alert.setContentText("Mot de passe modifiée avec succés");
alert.show();}
});
///////retour/////////
rett.setOnAction(e->{
try {
Parent root ;
root=FXMLLoader.load(getClass().getResource("acceuil1.fxml"));
rett.getScene().setRoot(root);
} catch (IOException ex) {
Logger.getLogger(ModifierActualiteController.class.getName()).log(Level.SEVERE, null, ex);
}
});
}
}
|
Python | UTF-8 | 3,967 | 3.234375 | 3 | [] | no_license | #!/usr/bin/env python
from math import ceil
import logging
class NewImageDimensions(object):
symbol_height = None
symbol_width = None
_epsilon = 0
def __init__(self, wh_ratio, data_len, symbol_shape, fixed_width = None):
self.wh_ratio = wh_ratio
self.data_len = data_len
self.symbol_shape = symbol_shape
self.fixed_width = fixed_width
def _round_up(self, val):
return int(ceil(val))
def _round_down(self, val):
return int(val)
def get_dims_fixed_width(self):
num_symbols_wide = int(self.fixed_width / float(self.symbol_width))
num_symbols_high = self.data_len / float(num_symbols_wide)
sym_width = num_symbols_wide
sym_height = self._round_up(num_symbols_high)
self.num_symbols_wide = sym_width
self.num_symbols_high = sym_height
def _calculate_symbol_dims(self):
# TODO(tierney): The full solution to the problem of calculating symbol
# dimensions appears to be a quadratically constrained linear program. While
# these roundings and methods are suboptimal, in practice, things seem to be
# good enough for now. Improvements welcome :)
# Rounding based on the following:
# xw = sqrt( ((r +- e)*bh*s) / bw )
# xh = S / xw
if self.wh_ratio < 1:
# Tall images.
num_symbols_wide = (((self.wh_ratio + self._epsilon) * \
self.symbol_height * self.data_len) \
/ (self.symbol_width)) ** .5
num_symbols_high = self.data_len / float(num_symbols_wide)
plus_sym_width = self._round_up(num_symbols_wide)
plus_sym_height = self._round_up(num_symbols_high)
sym_width, sym_height = plus_sym_width, plus_sym_height
else:
# Wide images.
num_symbols_wide = (((self.wh_ratio - self._epsilon) * \
self.symbol_height * self.data_len) \
/ (self.symbol_width)) ** .5
num_symbols_high = self.data_len / float(num_symbols_wide)
minus_sym_width = self._round_up(num_symbols_wide)
minus_sym_height = self._round_up(num_symbols_high)
sym_width, sym_height = minus_sym_width, minus_sym_height
logging.info('NewImageDimensions dimens: w (%d) h (%d) ratio '\
'(%.3f given %.3f).' % \
(sym_width * self.symbol_width,
sym_height * self.symbol_height,
(sym_width * self.symbol_width) / \
float(self.symbol_height * sym_height),
self.wh_ratio))
self.new_height = self.symbol_height * sym_height
self.new_width = self.symbol_width * sym_width
if (self.new_width) / float(self.new_height) > self.wh_ratio:
_desired_height = self.new_width / self.wh_ratio
symbol_rows_to_add = int((_desired_height - self.new_height) / \
float(self.symbol_height))
logging.info('symbol_rows_to_add %d.' % symbol_rows_to_add)
sym_height += symbol_rows_to_add
self.num_symbols_wide = sym_width
self.num_symbols_high = sym_height
def _calculate_num_symbols(self):
assert self.wh_ratio > 0
if self.fixed_width:
logging.info('Using fixed width: %d.' % self.fixed_width)
self.get_dims_fixed_width()
else:
logging.info('Using non-fixed width.')
self._calculate_symbol_dims()
self.new_width = self.num_symbols_wide * self.symbol_width
self.new_height = self.num_symbols_high * self.symbol_height
def _apply_symbol_shape(self):
# Symbol width is the same as "shape width".
self.symbol_width = self.symbol_shape.get_shape_width()
self.symbol_height = self.symbol_shape.get_shape_height()
def get_image_dimensions(self):
self._apply_symbol_shape()
self._calculate_num_symbols()
return self.new_width, self.new_height
def get_image_symbol_dimensions(self):
self._apply_symbol_shape()
self._calculate_num_symbols()
return self.num_symbols_wide, self.num_symbols_high
|
C++ | BIG5 | 492 | 2.875 | 3 | [] | no_license | #include <stdio.h>
#include <string.h>
char line[5000];
int main()
{
while(1){
int x;
scanf("%d", &x);///1
fgets(line, 5000, stdin);///eƦr᭱\nŪ
fgets(line, 5000, stdin);///o~Ou2
char * next = strtok(line, " \t");
while(next!=NULL){
int now;
sscanf(next, "%d", &now);
next = strtok(NULL, " \t");
printf("you read =%d=\n", now);
}
}
}
|
PHP | UTF-8 | 2,019 | 2.640625 | 3 | [] | no_license | <?php
include_once 'conection.php';
//métodos usados em diversos formulários
function selecionaUsuario($id){
$conn = conecta();
$query= "SELECT id, nome FROM usuario WHERE login NOT LIKE 'admin' ORDER BY nome";
$requisicao = mysqli_query($conn, $query);
$select = "<select id='selectUsuario' name='idUsuario' required>";
$select .= "<option value=''>Selecione um usuário</option>";
while($usuario = mysqli_fetch_assoc($requisicao)){
$select .= "<option value='".$usuario['id']."' ";
$select .= "".($usuario['id'] == $id ? "selected>" : ">" ).utf8_encode($usuario['nome'])."</option>";
}
$select .= "</select>";
desconecta($conn);
return $select;
}
function selecionaDepartamento($id){
$conn = conectaGLPI();
$query= "SELECT `id`, TRIM('Root entity > P.M.O. > ' FROM `completename`) as nome FROM `glpi_entities` WHERE `id` <> '0' AND `id` <> '22' ORDER BY `completename`";
$requisicao = mysqli_query($conn, $query);
$select = "<select name='departamento' required>";
$select .= "<option value=''>Selecione um departamento</option>";
while($departamento = mysqli_fetch_assoc($requisicao)){
if($departamento['id'] !== "0"){
$select .= "<option value='".$departamento['id']."' ";
$select .= ($departamento['id'] == $id? "selected>": ">").utf8_encode($departamento['nome'])."</option>";
}
}
$select .= "</select>";
desconecta($conn);
return $select;
}
function nomeDepartamento($id){
$conn = conectaGLPI();
$query= "SELECT TRIM('Root entity > P.M.O. > ' FROM `completename`) as nome FROM `glpi_entities` WHERE `id` = ".$id;
$requisicao = mysqli_query($conn, $query);
$nome = "";
if($requisicao){
while($departamento = mysqli_fetch_assoc($requisicao)){
$nome .= utf8_encode($departamento['nome']);
}
}
desconecta($conn);
return $nome;
}
|
Markdown | UTF-8 | 641 | 2.578125 | 3 | [] | no_license | ---
title: "HTML and CSS - part1"
date: 2020-06-03 18:00:00
categories: programming
---
#1. Bootstrap
https://getbootstrap.com/
#2. Bootstrap Grid System
https://www.w3schools.com/bootstrap/bootstrap_grid_system.asp
#3. CSS Class vs. ID
https://www.developintelligence.com/blog/2016/04/css-class-vs-id-which-one-to-use/
## Reference
1. HTML Tutorial: https://www.codecademy.com/learn/learn-html
2. HTML: Hypertext Markup Language: https://developer.mozilla.org/en-US/docs/Web/HTML
3. GitHub Io : https://pages.github.com/
4. Bootstrap Tutorial: https://scrimba.com/g/gbootstrap4
5. expo.getbootstrap.com : https://expo.getbootstrap.com/
|
Java | UTF-8 | 2,072 | 2.578125 | 3 | [
"Apache-2.0"
] | permissive | package org.apache.hadoop.contrib.ftp;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hdfs.DistributedFileSystem;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
/**
* Class to store DFS connection
*/
public class HdfsOverFtpSystem {
private static DistributedFileSystem dfs = null;
public static String HDFS_URI = "";
private static String superuser = "error";
private static String supergroup = "supergroup";
private final static Logger log = LoggerFactory.getLogger(HdfsOverFtpSystem.class);
private static void hdfsInit() throws IOException {
dfs = new DistributedFileSystem();
Configuration conf = new Configuration();
conf.set("hadoop.job.ugi", superuser + "," + supergroup);
try {
dfs.initialize(new URI(HDFS_URI), conf);
} catch (URISyntaxException e) {
log.error("DFS Initialization error", e);
}
}
public static void setHDFS_URI(String HDFS_URI) {
HdfsOverFtpSystem.HDFS_URI = HDFS_URI;
}
/**
* Get dfs
*
* @return dfs
* @throws IOException
*/
public static DistributedFileSystem getDfs() throws IOException {
if (dfs == null) {
hdfsInit();
}
return dfs;
}
/**
* Set superuser. and we connect to DFS as a superuser
*
* @param superuser
*/
public static void setSuperuser(String superuser) {
HdfsOverFtpSystem.superuser = superuser;
}
// public static String dirList(String path) throws IOException {
// String res = "";
//
// getDfs();
//
// Path file = new Path(path);
// FileStatus fileStats[] = dfs.listStatus(file);
//
// for (FileStatus fs : fileStats) {
// if (fs.isDir()) {
// res += "d";
// } else {
// res += "-";
// }
//
// res += fs.getPermission();
// res += " 1";
// res += " " + fs.getOwner();
// res += " " + fs.getGroup();
// res += " " + fs.getLen();
// res += " " + new Date(fs.getModificationTime()).toString().substring(4, 16);
// res += " " + fs.getPath().getName();
// res += "\n";
// }
// return res;
// }
}
|
JavaScript | UTF-8 | 1,556 | 3.84375 | 4 | [] | no_license | var qualificationDistance = 200;
var attempts = [120, 150, 160, 201, 203, 180, 202];
var qualified = false;
var averageBest = 0;
// Sorting in for loop of array
for (var currentIndex = 0; currentIndex <= attempts.length - 2; currentIndex++) {
var minValue = attempts[currentIndex];
for (var j = currentIndex + 1; j <= attempts.length - 1; j++) {
if (attempts[j] < minValue) {
minValue = attempts[j];
var swap = attempts[currentIndex];
attempts[currentIndex] = minValue;
attempts[j] = swap;
console.log('Change ' + swap + ' on ' + minValue);
console.log('Array now: ' + attempts);
}
}
console.log('The minimal element of ' + currentIndex + ' is ' + minValue);
}
// Identifying the three best jumps
console.log('Array length: ' + attempts.length);
var medianIndex1 = attempts.length - 1;
console.log(medianIndex1);
var bestJump1 = attempts[medianIndex1];
console.log(bestJump1);
var medianIndex2 = attempts.length - 2;
console.log(medianIndex2);
var bestJump2 = attempts[medianIndex2];
console.log(bestJump2);
var medianIndex3 = attempts.length - 3;
console.log(medianIndex3);
var bestJump3 = attempts[medianIndex3];
console.log(bestJump3);
// Calculation average of three best jumps
var averageBest = (bestJump1 + bestJump2 + bestJump3) / 3
// Identifying results of the qualification
if (averageBest > qualificationDistance) {
qualified = true;
console.log('Win! The average best jump is : ' + averageBest);
}
else {
qualified = false;
console.log('Lose! The average best jump is: ' + averageBest);
}
|
Markdown | UTF-8 | 1,802 | 2.8125 | 3 | [] | no_license | ---
title: 2016-03-01-english-comedy-night-w-chris-martin-david-morgan
event-title: English Comedy Night w/ Chris Martin & David Morgan
layout: post
ticket-url: https://www.weezevent.com/mar2016show1
fb-url: https://www.facebook.com/events/797724280354606/
image-url: https://www.weezevent.com/cache/images/affiche_156474.thumb53700.1454679302.jpg
---
Another brilliant line-up for this show!
### Chris Martin (GB)
Over the last years that Chris Martin supported Jack Whitehall (2011), Russell Kane (2012) & Milton Jones on his full tour for 2013.
He performed a sold out run at Edinburgh Festival in 2011 for his show “Chris Martin: No, Not That One” & is doing his first solo tour in the spring of 2014.
_"One of the UK's best young observationalists"_ — The guardian
_"Destined for greatness"_ — The Sunday times
### David Morgan (GB)
David did so well in August that I had many requests to get him back, so here he is!
‘A joy to behold’ — The Metro
David’s solo shows and his ability to make audiences ‘feel they’ve had a show performed specifically for them’ (London is Funny) cements him as a firm favorite in the industry.
In August 2014, he took his current show ‘Social Tool’ to the Edinburgh Fringe for a full run. Broadway Baby said that “David Morgan’s greatest strength and what makes him such an enjoyable comedian to watch is his seemingly innate ability to interact and connect with his audience.”
Due to David’s brilliant skills, he was asked to host the special one-off charity show ‘Take A Comedian Out’ at the Pleasance Grand, to an audience of 750 with a total of 35 comedians taking part.
_“Hilarious”_ — Heatworld
_“David Morgan is Funny, That’s Right. Capital F”_ — Attitude
_“David Morgan is a star in the making”_ — London is Funny |
C# | UTF-8 | 1,176 | 3.703125 | 4 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Exceptions2_Try_Catch_p165
{
class Program
{
static void Main(string[] args)
{
try
{
Console.WriteLine("How old are you?"); //ASK USER AGE
int age = Convert.ToInt32(Console.ReadLine());
if (age <= 0) { throw new FormatException(); }
if (age > 110) { throw new Exception(); }
int year = 2019 - age;
Console.WriteLine("You were likely born in " + year + " ...+/- 1 year"); //PRINT YR USER IS BORN
Console.ReadLine();
}
catch (FormatException ex)
{
Console.WriteLine("Error. Zero or negative numbers are not valid"); //ERROR MSSG FOR 0 OR (-)NUMS
}
catch (Exception ex)
{
Console.WriteLine(ex.Message); //ERROR MSSG REPEATED FOR ANY OTHER INPUT (IE: TEXT OR SYMBOL)
}
finally
{
Console.ReadLine();
}
}
}
}
|
C# | UTF-8 | 3,592 | 2.78125 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Yurchuk._2sem.laba._4
{
class Point3DF : IComparable
{
public double X;
public double Y;
public double Z;
public MyList<Line> Lines = new MyList<Line>();
public MyList<Poligon> Poligons = new MyList<Poligon>();
public bool OnlyPoint = false;
public bool Visible = true;
public Point3DF(double X, double Y, double Z)
{
this.X = (float)X;
this.Y = (float)Y;
this.Z = (float)Z;
}
public Point3DF(double X, double Y, double Z, bool OnlyPoint)
{
this.X = (float)X;
this.Y = (float)Y;
this.Z = (float)Z;
this.OnlyPoint = OnlyPoint;
}
public static Point3DF NormirVector(Point3DF vector)
{
double Len = Point3DF.LenVecor(vector);
return vector / Len;
}
public static double LenVecor(Point3DF vector)
{
return Math.Sqrt(Math.Pow(vector.X, 2) + Math.Pow(vector.Y, 2) + Math.Pow(vector.Z, 2));
}
public static Point3DF operator +(Double[] Mas, Point3DF obj)
{
if (Mas.Length != 3)
return new Point3DF(0, 0, 0);
return new Point3DF(obj.X + Mas[0], obj.Y + Mas[1], obj.Z + Mas[2], obj.OnlyPoint);
}
public static Point3DF operator +(Point3DF obj, Point3DF obj2)
{
return new Point3DF(obj.X + obj2.X, obj.Y + obj2.Y, obj.Z + obj2.Z, obj.OnlyPoint);
}
public static Point3DF operator -(Point3DF obj, Double[] Mas)
{
if (Mas.Length != 3)
return null;
return new Point3DF(obj.X - Mas[0], obj.Y - Mas[1], obj.Z - Mas[2], obj.OnlyPoint);
}
public static Point3DF operator -(Point3DF obj, Point3DF obj2)
{
return new Point3DF(obj.X - obj.X, obj.Y - obj.Y, obj.Z - obj.Y, obj.OnlyPoint);
}
public static Point3DF operator *(Double[,] Mas, Point3DF obj)
{
double[,] objM = new double[3, 1] { { obj.X }, { obj.Y }, { obj.Z } };
double[,] PoinMasRez = testgistogr.Matrix.MultiplicMatrix(Mas, objM);
return new Point3DF(PoinMasRez[0, 0], PoinMasRez[1, 0], PoinMasRez[2, 0], obj.OnlyPoint);
}
public static Point3DF operator *(Double Mas, Point3DF obj)
{
return new Point3DF(obj.X * Mas, obj.Y * Mas, obj.Z * Mas, obj.OnlyPoint);
}
public static Point3DF operator *(Point3DF obj, Double Mas)
{
return Mas * obj;
}
public static Point3DF operator /(Point3DF obj, Double Mas)
{
return new Point3DF(obj.X / Mas, obj.Y / Mas, obj.Z / Mas, obj.OnlyPoint);
}
static public bool EgualPoint(Point3DF P1, Point3DF P2)
{
bool rezult = P1.X == P2.X;
rezult = (P1.Y == P2.Y) && rezult;
rezult = (P1.Z == P2.Z) && rezult;
return rezult;
}
public int CompareTo(object obj)
{
if (obj is Point3DF)
{
if (X.CompareTo(((Point3DF)obj).X) != 0)
return X.CompareTo(((Point3DF)obj).X);
if (Y.CompareTo(((Point3DF)obj).Y) != 0)
return Y.CompareTo(((Point3DF)obj).Y);
return Z.CompareTo(((Point3DF)obj).Z);
}
return 0;
}
}
}
|
Java | UTF-8 | 907 | 2.609375 | 3 | [] | no_license | package mopaqlib;
public class HashTableEntry {
static final short INDEX_EMPTY=0xffffffff;
static final short INDEX_DELETED=0xfffffffe;
public int filePathHashA;
public int filePathHashB;
public long filePathHash;
public short language;
public short platform;
public int fileBlockIndex;
public BlockTableEntry fileBlock;
public String fileName;
public HashTableEntry(int filePathHashA,int filePathHashB,short language,short platform,int fileBlockIndex)
{
this.filePathHashA=filePathHashA;
this.filePathHashB=filePathHashB;
this.language=language;
this.platform=platform;
this.fileBlockIndex=fileBlockIndex;
filePathHash=(long)filePathHashA<<32 | ((long)filePathHashB & 0xffffffffl);
fileBlock=null;
fileName=null;
}
public boolean isIndexValid()
{
return (fileBlockIndex!=INDEX_EMPTY) && (fileBlockIndex!=INDEX_DELETED);
}
}
|
Python | UTF-8 | 4,137 | 2.984375 | 3 | [] | no_license | import requests
import argparse
from datetime import date
from time import sleep
from playsound import playsound
def initialize_parser():
parser = argparse.ArgumentParser()
parser.add_argument("-p", "--pin_code", type=str,
help="PIN_CODE to look in")
parser.add_argument("-a", "--age", type=int, help="AGE to look for")
parser.add_argument("-r", "--retry_in", type=int,
default=10, help="Retry lookup in RETRY_IN seconds")
parser.add_argument("-pi", "--print_in", type=int,
default=600, help="Print elapsed time every PRINT_IN seconds\n\
This should be a multiple of RETRY_IN")
return parser
def print_result(result):
print("\n\n")
if result == []:
print("Sorry, no centers for your parameters.\n")
return
for row in result:
print("CENTER DETAILS")
address = row[0]
sessions = row[1]
print("Center Name - {}\nCenter Pin Code - {}\nDistrict - {}\nBlock - {}\nCentre Fee - {}\n".format(*address))
print("Printing Sessions for this center:")
for session in sessions:
print("For", session[2], end='\t')
print("{} doses available with minimum age {} and vaccine {}".format(
session[0], session[1], session[3]))
print("\n")
def extract_info(data, age):
result = []
centers = data['centers']
for center in centers:
center_name = center['name']
centre_pincode = center['pincode']
district_name = center['district_name']
block_name = center['block_name']
centre_fee = center['fee_type']
sessions = center['sessions']
temp_result = []
for session in sessions:
available_capacity = int(session['available_capacity'])
if available_capacity == 0:
continue
session_age = int(session['min_age_limit'])
if session_age > age:
continue
session_date = session['date']
session_vaccine = session['vaccine']
if session_vaccine == '':
session_vaccine = 'unknown'
row = (available_capacity, session_age,
session_date, session_vaccine)
temp_result.append(row)
if temp_result != []:
address = (center_name, centre_pincode,
district_name, block_name, centre_fee)
row = (address, temp_result)
result.append(row)
return result
def main():
URL = "https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/calendarByPin"
args = initialize_parser().parse_args()
pin = args.pin_code
if not pin:
pin = input("Please enter pincode: ")
age = args.age
if not age:
age = int(input("Please enter your age: "))
retry_in = args.retry_in
print_in = args.print_in
today = date.today()
cowin_date = "{}-{}-{}".format(today.day, today.month, today.year)
PARAMS = {'pincode': pin, 'date': cowin_date}
idx = 0
while (1):
time_elapsed = idx * retry_in
try:
r = requests.get(url=URL, params=PARAMS)
data = r.json()
if r.status_code == 400:
print("Wrong input parameters. Please check. \n")
exit(0)
if not data:
print("Sorry. Not found.\n")
result = extract_info(data, age)
if result:
print('Register now!')
print_result(result)
while(1):
playsound('alarm.wav')
else:
if time_elapsed % print_in == 0:
print('Can not register yet. Time elapsed {} mins'.format(
time_elapsed / 60))
except requests.exceptions.ConnectionError:
print("Connection error. Will silently retry in {} seconds".format(retry_in))
# print("retry in how many seconds - "+str(retry_in))
sleep(retry_in)
idx += 1
if __name__ == '__main__':
main() |
TypeScript | UTF-8 | 8,306 | 2.78125 | 3 | [
"MIT"
] | permissive | //
// Shared microservices framework.
//
import { MicroService, IMicroServiceConfig, IMicroService, retry } from "@artlife/micro";
const inProduction = process.env.NODE_ENV === "production";
const JOB_QUEUE_HOST = process.env.JOB_QUEUE as string || "job-queue";
//
// Arguments to the register-jobs REST API.
//
export interface IRegisterAssetJobsArgs {
//
// Jobs to be registered.
//
jobs: IJobDetails<IJob>[];
}
//
// Defines a job that can be requested and processed.
//
export interface IJob {
//
// The ID of the job itself.
//
jobId: string;
}
//
// Defines an asset-based job that can be requested and processed.
//
export interface IAssetJob extends IJob {
//
// The ID of the user who contributed the asset.
//
userId: string;
//
// The ID of the asset to be classified.
//
assetId: string;
//
// The ID of the account that owns the asset.
//
accountId: string;
//
// The mimetype of the asset.
//
mimeType: string;
//
// The encoding of the asset.
//
encoding: string;
}
//
// Arguments to the job-complete message.
//
export interface IJobCompletedArgs {
//
// The ID of the job that was successfully completed.
//
jobId: string;
}
//
// Arguments to the job-failed message.
//
export interface IJobFailedArgs {
//
// The ID of the job that failed.
//
jobId: string;
//
// The error that caused the job failure.
//
error: any;
}
//
// Result returned by the request-job REST API.
//
export interface IRequestJobResult {
//
// Set to true if a job is avaialble for processing.
//
ok: boolean;
//
// The next job in the queue, if ok is set to true.
//
job?: IJob;
}
/**
* Configures a microservice.
*/
export interface IMicroJobConfig extends IMicroServiceConfig {
}
/**
* Defines a function to process a job.
*/
export type JobFn<JobT> = (service: IMicroJob, job: JobT) => Promise<void>;
/**
* Interface that represents a particular microservice instance.
*/
export interface IMicroJob extends IMicroService {
/**
* Register a function to process a job.
*
* This function will be called automatically when pending jobs are available in the job queue.
*
* @param jobName The name of the job.
*/
registerJob(jobDetails: IJobDetails<IJob>): Promise<void>;
/**
* Register a function to process an asset-based job.
*
* This function will be called automatically when pending jobs are available in the job queue.
*
* @param jobName The name of the job.
*/
registerAssetJob(jobDetails: IAssetJobDetails): Promise<void>;
}
//
// Define the job.
//
export interface IJobDetails<JobT> {
//
// Name of the job.
//
jobName: string;
//
// Name of the service that handles the job.
//
serviceName?: string;
//
// The function that is executed to process the job.
//
jobFn: JobFn<JobT>;
}
//
// Defines an asset-based job.
//
export interface IAssetJobDetails extends IJobDetails<IAssetJob> {
//
// The mimetype of the assets that this job processes.
//
mimeType: string; //todo: is this needed?
}
//
// Class that represents a job-based microservice.
//
class MicroJob extends MicroService implements IMicroJob {
//
// Records when the microservice has started.
//
private started: boolean = false;
//
// Registered jobs.
//
private jobList: IJobDetails<IJob>[] = [];
constructor(config: IMicroJobConfig) {
super(config);
}
/**
* Register a function to process a named job.
* This function will be called automatically when pending jobs are available in the job queue.
*
* @param jobName The name of the job.
*/
async registerJob(jobDetails: IJobDetails<IJob>): Promise<void> {
if (this.started) {
throw new Error(`Please register jobs before calling the 'start' function.`);
}
jobDetails = Object.assign({}, jobDetails);
jobDetails.serviceName = this.getServiceName();
const registerJobsArgs: IRegisterAssetJobsArgs = {
jobs: [ jobDetails as any as IJobDetails<IJob> ],
}
await retry(() => this.request.post(JOB_QUEUE_HOST, "/register-jobs", registerJobsArgs), 10, 1000);
this.jobList.push(jobDetails as any);
}
/**
* Register a function to process an asset based job.
* This function will be called automatically when pending jobs are available in the job queue.
*
* @param jobName The name of the job.
*/
async registerAssetJob(jobDetails: IAssetJobDetails): Promise<void> {
if (this.started) {
throw new Error(`Please register jobs before calling the 'start' function.`);
}
jobDetails = Object.assign({}, jobDetails);
jobDetails.serviceName = this.getServiceName();
const registerJobsArgs: IRegisterAssetJobsArgs = {
jobs: [ jobDetails as any as IJobDetails<IJob> ],
}
await retry(() => this.request.post(JOB_QUEUE_HOST, "/register-jobs", registerJobsArgs), 10, 1000);
this.jobList.push(jobDetails as any);
}
//
// Start processing jobs.
//
private async processJobs(): Promise<void> {
console.log(`Commencing job processing loop with ${this.jobList.length} registered jobs.`);
if (this.jobList.length === 0) {
throw new Error("No jobs registered with micro-job!");
}
while (true) {
for (const jobDetails of this.jobList) {
console.log("Requesting next job.");
const route = `/request-job?job=${jobDetails.jobName}&service=${this.getServiceName()}&id=${this.getInstanceId()}`;
const response = await retry(() => this.request.get(JOB_QUEUE_HOST, route), 10, 1000);
const requestJobResult: IRequestJobResult = response.data;
if (requestJobResult.ok) {
console.log("Have a job to do.");
const job = requestJobResult.job!;
try {
await jobDetails.jobFn(this, job);
//
// Let the job queue know that the job has completed.
//
const jobCompletedArgs: IJobCompletedArgs = { jobId: job.jobId! };
await this.emit("job-completed", jobCompletedArgs);
}
catch (err) {
console.error("Job failed, raising job-failed event.");
console.error(err && err.stack || err);
//
// Let the job queue know that the job has failed.
//
const jobFailedArgs: IJobFailedArgs = { jobId: job.jobId!, error: err.toString() };
await this.emit("job-failed", jobFailedArgs);
}
}
}
console.log("Waiting for next job.");
await this.waitForOneEvent("jobs-pending");
}
}
/**
* Starts the microservice.
* It starts listening for incoming HTTP requests and events.
*/
async start(): Promise<void> {
await super.start();
console.log("Starting job processing.");
if (this.jobList.length === 0) {
throw new Error("No jobs registered with micro-job!");
}
//TODO: Should have a retry forever function. Need to report an error if can't connect after 5 minutes, also want to exponentially back off.
retry(() => this.processJobs(), 10000, 1000 * 60)
.catch(err => {
console.error("Failed to start job processing.");
console.error(err && err.stack || err);
});
this.started = true;
}
}
/**
* Instantiates a jobs-based microservice.
*
* @param [config] Optional configuration for the microservice.
*/
export function micro(config: IMicroJobConfig): IMicroJob {
return new MicroJob(config);
} |
JavaScript | UTF-8 | 679 | 3.546875 | 4 | [] | no_license | import React, { useState } from 'react';
// short-circuit evaluation
// ternary operator
const ShortCircuit = () => {
const [text, setText] = useState('');
// const [text, setText] = useState('aaaa');
const firstValue = text || 'hello world';
const secondValue = text && 'hello world';
return (
<>
<h1>{firstValue}</h1>
<h1>value : {secondValue}</h1>
{/* {if(){console.log('hello world')}} */}
<h1>{text || 'if it is string or empty, bring back whatever here'}</h1>
{text && <h1>Hello Bahasht</h1>}
{/* or like that */}
{!text && <h1>Hello Bahasht</h1>}
</>
);
// <h2>short circuit</h2>;
};
export default ShortCircuit;
|
C | UTF-8 | 9,354 | 2.890625 | 3 | [
"MIT"
] | permissive | #include <stdio.h>
#include <string.h>
#include <stdbool.h>
#include "../c-head/board.h"
#include "../c-head/gameNoUI.h"
#include "../c-head/find.h"
#include "../c-head/getLine.h"
/**
* Play a game func
*/
int playAGame(){
/* code */
printf("Hello Sir. \nSo you want to play Hasami Shogi.\nHere are the rules:\n");
rules();
// Initialise board, and fill it with pawn of the right color at the right location
Board b = initBoard();
b = fillBoard(b);
printf("White pawns move first.\n\nPress Enter key to start\n");
getchar();
Status winner = gamePvP(b);
switch(winner){
case WhitePlayer :
printf("******************\n");
printf("White player wins.\n");
printf("******************\n");
break ;
case BlackPlayer :
printf("******************\n");
printf("Black player wins.\n");
printf("******************\n");
break ;
case Bot :
printf("******************\n");
printf("Computer wins [easy ~~].\n");
printf("******************\n");
break ;
case Draw :
printf("******************\n");
printf("Game ended with no winner\n");
printf("******************\n");
break ;
case Exit :
printf("Game quit before ending.\n");
freeBoard(b);
printf("Game ended\nBoard cleaned\n");
return 1;
case Playing :
printf("Error : Game ended while still tagged as continuing.\n");
default :
printf("/!\\/!\\/!\\ Something wrong happened /!\\/!\\/!\\ \n");
}
freeBoard(b);
printf("Game ended\nBoard cleaned\n");
return 0;
}
Status gamePvP(Board b){
int passCount = 0 ;
int n = 0 ;
Coord turnReturn ;
Status state ;
printf("Let the game begin !\n\n");
display(b);
while(true){
printf("Round %d\n",n++);
//printf("White pawn count : %d\nBlack pawn count : %d\n",b.whiteCount, b.blackCount);
//White player plays
printf("White player turn\nYour move ?\n");
turnReturn = playerTurn(&b, White);
if(isInBoard(b, turnReturn)){ // Turn went right
passCount = 0 ;
if((state = resolveGame(&b))!= Playing ){
return state ;
} else {
// Displaying the board after update
printf("\nHere is the board : \n");
display(b);
}
} else if(turnReturn.x == -1 ){
switch(turnReturn.y){
case 1 : // Player passed
passCount = passCount + 1 ;
// Draw check
if(passCount >= 2){
return Draw ;
}
break ;
case 2 : // Player gave up
return BlackPlayer ;
case 3 : // Hard quit
return Exit ;
default: // Something went wrong
return Playing ;
}
}
//Black player plays
printf("Black player turn\nYour move ?\n");
turnReturn = playerTurn(&b, Black);
//turnReturn = initCoord(-1, 1); // For testing purpose
if(isInBoard(b, turnReturn)){ // Turn went right
passCount = 0 ;
if((state = resolveGame(&b))!= Playing ){
return state ;
} else {
// Displaying the board after update
printf("\nHere is the board : \n");
display(b);
}
} else if(turnReturn.x == -1 ){
switch(turnReturn.y){
case 1 : // Player passed
passCount = passCount + 1 ;
// Draw check
if(passCount >= 2){
return Draw ;
}
break ;
case 2 : // Player gave up
return WhitePlayer ;
case 3 : // Hard quit
return Exit ;
default: // Something went wrong
return Playing ;
}
}
}
}
Coord playerTurn(Board* b, Pawn side){
char input[20] ;
Coord locationCoord, targetCoord ;
while(true){
printf(">>> ");
My_gets(input);
if (input == NULL) {
printf ("Error while reading input\n");
} else {
lower(input);
// printf("%s\n", input);
// Some process to determine whether player wants to play, pass,
// display the rules, or i don't know what else
if(inputIsAMove(input)){
int x1, y1, x2, y2 ;
if(processInputToMove(input, &x1, &y1, &x2, &y2)){
if(b->board[x1][y1]==enemyPawn(side)){
printf("Invalid play, can't move your opponent pawn. Please try again\n");
} else {
locationCoord = initCoord(x1, y1);
targetCoord = initCoord(x2, y2);
bool move = movePawn(*b, locationCoord, targetCoord);
if(move){
resolveMove(b, targetCoord);
return targetCoord ;
} else {
printf("Invalid play, can't go from %c%d to %c%d. Please try again\n",
numberToLetter(x1), y1, numberToLetter(x2), y2);
}
}
}else{
printf("Invalid play or error while processing. Please try again\n");
}
} else if(strcmp(input,"pass") == 0 ){
return initCoord(-1,1) ;
} else if(strcmp(input,"give up")==0){
return initCoord(-1,2) ;
} else if(strcmp(input,"exit") == 0 ){
return initCoord(-1,3) ;
} else if(strcmp(input,"rules")==0){
rules() ;
} else if(strcmp(input,"board")==0){
display(*b) ;
} else if(strcmp(input,"help")==0){
printf("Type pass to pass your turn.\n");
printf("Type give up to concede the victory.\n");
printf("Type rules to receive a quick explanation of the game.\n");
printf("Type board to display the current board.\n");
} else {
printf("Invalid command. Please try again. Type help to get help.\n");
}
}
}
}
void display(Board b) {
char none = '.', black = 'b', white = 'w';
printf(" ");
for (int i = 0; i < b.length; i++) {
printf("%d ", i);
}
printf("\n");
for (int i = 0; i < b.length; i++) {
// Line number
printf("%c ", numberToLetter(i));
for (int j = 0; j < b.length; j++) {
switch (b.board[i][j]) {
case Black:
printf("%c ", black);
break;
case White:
printf("%c ", white);
break;
default:
printf("%c ", none);
break;
}
}
printf("\n");
}
printf("\n");
}
void rules(){
// Display the rules.
printf("The rules.\nBest joke ever.\n");
}
bool inputIsAMove(char* input){
//apply regex "([A-Z]{1})([0-9]{1-2}) to ([A-Z]{1})([0-9]{1-2})"
//return reg_matches(input, "([A-Z]{1})([0-9]{1-2}) to ([A-Z]{1})([0-9]{1-2})");
return isAMove(input);
}
bool processInputToMove(char* input, int* x1, int* y1, int* x2, int* y2){
//return reg_find_move(input, "([A-Z]{1})([0-9]{1-2}) to ([A-Z]{1})([0-9]{1-2})", x1, y1, x2, y2);
return processMove(input, x1, y1, x2, y2);
}
int letterToNumber(char c){
if(c >= 'a' && c <= 'z'){
c = c + 'A' - 'a';
}
switch(c){
case 'A' : return 0 ;
case 'B' : return 1 ;
case 'C' : return 2 ;
case 'D' : return 3 ;
case 'E' : return 4 ;
case 'F' : return 5 ;
case 'G' : return 6 ;
case 'H' : return 7 ;
case 'I' : return 8 ;
case 'J' : return 9 ;
case 'K' : return 10 ;
case 'L' : return 11 ;
case 'M' : return 12 ;
case 'O' : return 13 ;
case 'P' : return 14 ;
case 'Q' : return 15 ;
case 'R' : return 16 ;
case 'S' : return 17 ;
case 'T' : return 18 ;
case 'U' : return 19 ;
default :
return -1 ;
}
}
char numberToLetter(int n){
switch(n){
case 0 : return 'A' ;
case 1 : return 'B' ;
case 2 : return 'C' ;
case 3 : return 'D' ;
case 4 : return 'E' ;
case 5 : return 'F' ;
case 6 : return 'G' ;
case 7 : return 'H' ;
case 8 : return 'I' ;
case 9 : return 'J' ;
case 10 : return 'K' ;
case 11 : return 'L' ;
case 12 : return 'M' ;
case 13 : return 'O' ;
case 14 : return 'P' ;
case 15 : return 'Q' ;
case 16 : return 'R' ;
case 17 : return 'S' ;
case 18 : return 'T' ;
case 19 : return 'U' ;
default :
return -1 ;
}
}
|
Markdown | UTF-8 | 3,197 | 3.140625 | 3 | [
"MIT"
] | permissive | ---
layout: post
title: "(캡스톤) 캡스톤[5.1]"
category: PYTHON
---
### 오늘 할일(5월 1일)
> 오늘의 목표다.
* seed를 만들자.
* seed를 만드는 이유? mysql data를 뽑아서 mongodb collection에 넣어줘야 하는 코드 까지 만들어야함.
* 가공하는 부분까지 코드를 만들어야 하니 어떤형태가 나올지 지금은 모른다.
* 그러니까 일단 해서 직접 뽑아서 내가 원하는 모양대로 만들어보자
### 시드를 만들어서 mysql에 넣어보자
<img src = '/post_img/201705/01/1.png' width="300"/><br/>
* 내가 시드를 넣을 테이블이다. UserId를 각각 가지고 있다.
* 유저가 각각 Recommendation table을 갖게 된다. distinctCode는 RecommendableCourses에 담겨있는 코드이다. 예측한 결과는 score가 빈 상태로 저장이 될 것이고 평가가 된 내용은 score가 0보다 큰 값이 입력될 것이다.
* 고로 우리가 넣을 데이터는 (일단은) distinctCode와 score, UserId를 채워줘 보자
* score는 1~5점, UserId는 1~10으로 해보자. 데이터가 각각 구분되는 distinctCode는 20개 내외 알파벳 A ~ 랜덤으로 선택되게 하자
```python
import time
import datetime
# 현재 시간 넣기
ts = time.time()
timestamp = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
distCode = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']
# 유저 만들기
randEmails = random.sample(distCode,11)
for email in randEmails:
randEmail = email + "@gg.com"
Query = "INSERT INTO Users (email, password, createdAt, updatedAt) VALUES (%s, %s, %s, %s)"
cursor.execute(Query, (randEmail, "ddd",timestamp,timestamp))
cnn.commit()
# 추천한 것 만들기
for userId in range(1,11):
randScr = random.randint(1, 5)
randCodes = random.sample(distCode,7)
for randCode in randCodes:
Query = "INSERT INTO UserRecommendations (distinctCode, score, UserId, createdAt, updatedAt) VALUES (%s, %s, %s, %s, %s)"
cursor.execute(Query, (randCode, randScr, userId,timestamp,timestamp))
cnn.commit()
cnn.close()
```
### 그걸 가지고 와서 MongoDB collection에 넣어보기
* UserRecommendations DB를 만들어서 scoreCollection에 일단 넣어줬다.
* 여기까진 쉽게 된다.
```python
mongoClient = MongoClient()
db = mongoClient.UserRecommendations
scoreCollection= db.scoreCollection
preScoreCollection = db.preScoreCollection
def get_data_from_Userrecommendations():
Query = "select distinctCode, score, UserId from UserRecommendations;"
cursor.execute(Query)
rows = cursor.fetchall()
for i in rows:
distCode = i[0]
score = i[1]
userId = i[2]
scoreCollection.update(
{
"_id": userId
},
{
"$set":
{
"subject." + distCode: score
}
},
upsert=True)
get_data_from_Userrecommendations()
```
<img src = '/post_img/201705/01/2.png'/><br/>
* 오늘은 많이 못했으니 내일 열심히 ㅠㅠ
<br/><br/>
|
C++ | UTF-8 | 5,118 | 2.84375 | 3 | [] | no_license | /* MicroKey. Physical keyboard shortcuts based on Arduino Micro, a keypad and an oled display.
*
* [Microkey ]
* [ ]
* [ ]
* [ ]
*
* [ 1 ][ 2 ][ 3 ][ A ]
* [ 4 ][ 5 ][ 6 ][ B ]
* [ 7 ][ 8 ][ 8 ][ C ]
* [ * ][ 0 ][ # ][ D ]
*
*
* Special thanks to Mark Stanley and Alexander Brevig for the Keypad library and Adafruit for SSD1306 driver.
*/
/*********************************************************************
This is an example for our Monochrome OLEDs based on SSD1306 drivers
Pick one up today in the adafruit shop!
------> http://www.adafruit.com/category/63_98
This example is for a 128x64 size display using I2C to communicate
3 pins are required to interface (2 I2C and one reset)
Adafruit invests time and resources providing this open source code,
please support Adafruit and open-source hardware by purchasing
products from Adafruit!
Written by Limor Fried/Ladyada for Adafruit Industries.
BSD license, check license.txt for more information
All text above, and the splash screen must be included in any redistribution
*********************************************************************/
#include <SPI.h>
#include <Wire.h>
#include <Adafruit_GFX.h>
#include <Adafruit_SSD1306.h>
#define OLED_RESET 4
Adafruit_SSD1306 display(OLED_RESET);
#include <Keypad.h>
#include "Keyboard.h"
const byte ROWS = 4; //four rows
const byte COLS = 4; //four columns
char keys[ROWS][COLS] = {
{'1','2','3','A'},
{'4','5','6','B'},
{'7','8','9','C'},
{'*','0','#','D'}
};
// | | | | | | | |
// | | | | | | | |
//16 15 14 1 6 11 10 9
byte rowPins[ROWS] = { 16, 15, 14, 1}; //connect to the row pinouts of the keypad
byte colPins[COLS] = { 6, 11, 10, 9}; //connect to the column pinouts of the keypad
Keypad keypad = Keypad( makeKeymap(keys), rowPins, colPins, ROWS, COLS );
void setup(){
display.begin(SSD1306_SWITCHCAPVCC, 0x3C); // initialize with the I2C addr 0x3D (for the 128x64)
delay(2000);
}
bool locked = true; // locked by default. Do nothing until unlock.
// set to 'false' to avoid lock MicroKey.
#define maxcmdl 4 // maximun cmd length
char cod[maxcmdl+1] = "1234"; // to save the code to unlock. 4 nums and the \n character.
char key = ' '; // to save the value of the key pressed.
char cmd = ' '; // to save the code of the command to execute.
int icmd;
void loop(){
/*
* The first time MicroKey is connected it is locked.
* You've to enter a code to unlock it. After that,
* if you enter a code you will see the
* text to send in the display and it will be sended
* when you press 'A'
*
*/
while(locked){ // locked by default. Do nothing until unlock.
welcome(); // Display initial message.
locked = check_lock();
}
// unlocked
welcome_unlocked();
key = keypad.getKey();
if (key){
// Activate. Execute the command "cmd".
if (key=='A') {
execute(cmd);
}else{
// Prepare the command to execute
cmd=key;
}
}
}
void welcome(){
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(0,0);
display.println("Microkey cmd locked");
display.println("Enter code to unlock");
display.display();
}
void welcome_unlocked(){
display.clearDisplay();
display.setTextSize(1);
display.setTextColor(WHITE);
display.setCursor(0,0);
display.println("Microkey cmd ");
display.println("'A' to confirm");
display.println(cmd);
print_cmd(cmd);
display.display();
}
void execute(char cmd){
switch(cmd){
case '1':
Keyboard.println("Password 1");
break;
case '2':
Keyboard.println("Password 2");
break;
case '3':
Keyboard.println("Salvador");
break;
case '4':
Keyboard.println("Salvador.rueda@gmail.com");
break;
}
}
void print_cmd(char cmd){
switch(cmd){
case '1':
display.println("Password 1");
break;
case '2':
display.println("Password 2");
break;
case '3':
display.println("Salvador");
break;
case '4':
display.println("Salvador.rueda@gmail.com");
break;
}
}
bool check_lock(){ // Wait for a 4 key code to mach with variable "cod".
//#define maxcmdl 4 // maximun cmd length
//char cod[maxcmdl+1] = "1234"; // to save the code to unlock. 4 nums and the \n character.
bool locked = true;
int icmd = 0;
bool fail = false; // true when a single character of the password fails.
welcome();
while (icmd<maxcmdl){ // ask as many characters as password length
key = keypad.getKey();
if(key){
display.print(key);
display.display();
if(key == cod[icmd] && !fail) locked = false;
// if the key is right and didn't fail before looked is false.
else{
fail = true;
locked = true;
}
icmd++;
}
}
return locked;
}
|
Markdown | UTF-8 | 3,464 | 2.90625 | 3 | [
"MIT"
] | permissive | ---
layout: page
title: "Pwn2Win 2017 Writeup: Baby Regex"
---
>Baby Regex
>
>Our team has gotten hands on this text and we know that it has been used by BloodSuckers Corp. as an admittance test for their applicants in the Counter Intelligence(CI) team, since these guys have an eye for pattern recognition! Get this achievement by helping the members of Rebellious Fingers that will soon try to infiltrate the CI team and will need this test's results.
>
>[Link]({{ site.baseurl }}/ctfs/pwn2win2017/baby_regex/regexbaby.txt)
>
>Pay close attention to the text in order to capture the sequence as it appears, understanding these instructions is also part of the challenge. The engine used is python2, everything is working as expected!
>
>P.S: In the challenge, wildcard refers exclusively to the asterisk ( * ).
>
>Server: nc 200.136.213.148 5000
>
>Id: baby_regex
>
>Total solves: 19
>
>Score: 298
>
>Categories: Misc
This was a terrific refresher of finer points of regex expression syntax. One catch may be the specific Python function to use when verifying your expressions - not all of them behave the same way in all cases. I asked the CTF admins and they recommended using ```re.findall()``` function, which helped me overcome some discrepancies I saw in testing expressions locally vs. testing against the server.
To test expressions locally I threw together a small script:
```python
import re,sys
data = open("regexbaby.txt","r").read()
print sys.argv[1], "len: %d" % len(sys.argv[1])
m = re.findall(sys.argv[1], data)
for x in m:
print x
```
After a lot of trial and error the following expressions worked (note that the expression with 38 characters has a trailing space):
```
$ nc 200.136.213.148 5000
Type the regex that capture: "from "Drivin" until the end of phrase, without
using any letter, single quotes or wildcards, and capturing "Drivin'" in a
group, and "blue." in another", with max. "16" chars: (.{7}).+-(.{5})$
Nice, next...
Type the regex that capture: "All "Open's", without using that word or [Ope-],
and no more than one point", with max. "11" chars: (?i)(oPEn)
Nice, next...
Type the regex that capture: "(BONUS) What's the name of the big american
television channel (current days) that matchs with this regex: .(.)\1", with
max. "x" chars: CNN
Nice, next...
Type the regex that capture: "Chips" and "code.", and it is only allowed the
letter "c" (insensitive)", with max. "15" chars: ([cC].{4})\n\n
Nice, next...
Type the regex that capture: "the follow words: "unfolds", "within" (just one
time), "makes", "inclines" and "shows" (just one time), without using hyphen,
a sequence of letters (two or more) or the words itself", with max. "38" chars:
(?:t|d) ([^F]\w{2,5}(?:i|e|w|d)[^d])
Nice, next...
Type the regex that capture: "the only word that repeat itself in the same
word, using a group called "a" (and use it!), and the group expression must
have a maximum of 3 chars, without using wildcards, plus signal, the word
itself or letters different than [Pa]", with max. "16" chars: (?P<a>..a)(?P=a)
Nice, next...
Type the regex that capture: "FLY until... Fly", without wildcards or the word
"fly" and using backreference", with max. "14" chars: (FL.).+(?i)\1
Nice, next...
Type the regex that capture: "<knowing the truth. >, without using "line break"",
with max. "8" chars: <[^z]*>
Nice, next...
CTF-BR{Counterintelligence_wants_you!}
```
The flag is ```CTF-BR{Counterintelligence_wants_you!}```. |
Java | UTF-8 | 2,364 | 2.65625 | 3 | [
"Apache-2.0"
] | permissive | package ch.ethz.bhepp.hybridstochasticsimulation.graphs;
import java.util.List;
import java.util.Set;
import org.jgrapht.alg.ConnectivityInspector;
import org.jgrapht.alg.StrongConnectivityInspector;
import org.jgrapht.graph.DefaultDirectedGraph;
import ch.ethz.bhepp.hybridstochasticsimulation.networks.MassActionReactionNetwork;
public class ComplexGraph extends DefaultDirectedGraph<ComplexVertex, ComplexEdge> {
private static final long serialVersionUID = 7992771587636755157L;
private ConnectivityInspector<ComplexVertex, ComplexEdge> ci;
private StrongConnectivityInspector<ComplexVertex, ComplexEdge> si;
public static ComplexGraph createFromReactionNetwork(MassActionReactionNetwork net) {
return new ComplexGraph(net);
}
protected ComplexGraph(MassActionReactionNetwork net) {
super(new ComplexEdgeFactory());
init(net);
}
private ComplexEdge createComplexEdge(ComplexVertex source, ComplexVertex target) {
return new ComplexEdge(source, target);
}
private ComplexVertex getComplexVertex(int[] stochiometries) {
ComplexVertex vertex = new ComplexVertex(stochiometries);
if (!containsVertex(vertex))
addVertex(vertex);
return vertex;
}
private void addComplexEdge(ComplexVertex consumptionVertex, ComplexVertex productionVertex) {
ComplexEdge edge = createComplexEdge(consumptionVertex, productionVertex);
addEdge(consumptionVertex, productionVertex, edge);
}
final private void init(MassActionReactionNetwork net) {
for (int r=0; r < net.getNumberOfReactions(); r++) {
int[] consumptionStochiometries = net.getConsumptionStoichiometries(r);
int[] productionStochiometries = net.getProductionStoichiometries(r);
ComplexVertex consumptionVertex = getComplexVertex(consumptionStochiometries);
ComplexVertex productionVertex = getComplexVertex(productionStochiometries);
addComplexEdge(consumptionVertex, productionVertex);
}
}
public List<Set<ComplexVertex>> getConnectedSets() {
initCi();
return ci.connectedSets();
}
public List<Set<ComplexVertex>> getStronglyConnectedSets() {
initSi();
return si.stronglyConnectedSets();
}
private void initCi() {
if (ci == null)
ci = new ConnectivityInspector<>(this);
}
private void initSi() {
if (si == null)
si = new StrongConnectivityInspector<>(this);
}
}
|
Java | UTF-8 | 428 | 2.09375 | 2 | [
"Apache-2.0"
] | permissive | package irvine.oeis.a196;
// Generated by gen_seq4.pl triprod at 2023-06-05 17:58
import irvine.oeis.a007.A007318;
import irvine.oeis.a136.A136572;
import irvine.oeis.triangle.Product;
/**
* A196347 Triangle T(n, k) read by rows, T(n, k) = n!*binomial(n, k).
* @author Georg Fischer
*/
public class A196347 extends Product {
/** Construct the sequence. */
public A196347() {
super(0, new A136572(), new A007318());
}
}
|
Java | UTF-8 | 2,227 | 2.671875 | 3 | [] | no_license | import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
public class MyTest {
public static void main(String[] args)throws Throwable {
Connection con = null;
Statement st = null;
ResultSet rs = null;
PreparedStatement ps=null;
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/test1";
String user = "root";
String password = "";
String file="excel1.csv";
try {
con = DriverManager.getConnection(url, user, password);
// st = con.createStatement();
ps=con.prepareStatement("LOAD DATA LOCAL INFILE '"+file+"' INTO TABLE emp_tbl(emp_id,empname,deg,salary,dept)");
// ps=conn.prepareStatement("LOAD DATA LOCAL INFILE '"+exceldatabase.xlsx+"' INTO TABLE emp_tbl(emp_id,ename,deg,salary,dept)")
// String query= "LOAD DATA LOCAL INFILE '"+exceldatabase.xlsx+"' INTO TABLE emp_tbl(emp_id,ename,deg,salary,dept)";
// String sSqlLinux="LOAD DATA LOCAL INFILE 'exceldatabase.xlsx' INTO TABLE emp_tbl(emp_id,ename,deg,salary,dept) " +
// " FIELDS TERMINATED BY ',' ENCLOSED BY '\"' " +
// " LINES TERMINATED BY '\\n'";
ps.executeUpdate();
System.out.println("------------------------------");
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(MyTest.class.getName());
lgr.log(Level.SEVERE, ex.getMessage(), ex);
} finally {
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(MyTest.class.getName());
lgr.log(Level.WARNING, ex.getMessage(), ex);
}
}
}
}
|
Python | UTF-8 | 4,478 | 2.703125 | 3 | [] | no_license | import json
import dateutil.parser
import requests
from bs4 import BeautifulSoup
from bson import json_util
# execute a request, if it fails then print and exit, other return souped text
def get_bs_request(url):
request_response = requests.get(url)
if not request_response.ok:
raise Exception(request_response)
return BeautifulSoup(request_response.text, 'html.parser')
# get all debate urls from the provided url
def get_debates(url):
page = 1
debates = set()
debate_results = get_bs_request(url + '/page/' + str(page) + '?view=all')
debate_results = debate_results.find_all('div', class_='fl-post-columns-post')
# while there are results
while len(debate_results) > 0:
for result in debate_results:
# add the transcript urls to the list
debates.add(result.find('a').attrs['href'])
page += 1
debate_results = get_bs_request(url + '/page/' + str(page) + '?view=all')
debate_results = debate_results.find_all('div', class_='fl-post-columns-post')
return debates
def scrape_url(debate_url, folder_name, is_debate):
debate = get_bs_request(debate_url)
# background info for the debate
intro_text = debate.find_all('div', class_='fl-rich-text')[1].text.strip()
title = debate.find('h1', class_='fl-heading').text.strip()
tags = []
if is_debate:
tags.append("debate")
# attempt to get the date from the background paragraph
try:
date = dateutil.parser.parse(intro_text, fuzzy=True, ignoretz=True)
except ValueError:
# otherwise set 0 date
date = dateutil.parser.parse('1970-01-01', ignoretz=True)
# get each response
parts = []
number = 1
speakers = set()
transcript_text = debate.find('div', class_='fl-callout-text')
for e in transcript_text.children:
if e.name == 'p' and len(e.contents) == 5:
# text
name = e.contents[0].split(':')[0].strip()
clock = e.contents[1].text
text = e.contents[4].strip()
if not parts:
# hopefully this signals the debate is only one part
parts.append({'number': None, 'video': None, 'text': []})
if parts[-1]['video'] is None:
# url for video is in the text, not the heading
parts[-1]['video'] = e.contents[1].attrs['href'].rsplit('&', 1)[0]
speakers.add(name)
parts[-1]['text'].append({'speaker': name, 'time': clock, 'text': text})
elif e.name == 'h2':
# new part
parts.append({'number': number, 'video': None, 'text': []})
number += 1
else:
print(debate_url)
print(e)
print()
# determine who are the candidates from the background info
candidates = set(c for c in speakers if c in intro_text)
other_speakers = speakers.difference(candidates)
# assemble all of the info in a dictionary
debate_info = {
'url': debate_url,
'title': title,
'tags': tags,
'date': date,
'candidates': list(candidates),
'other_speakers': list(other_speakers),
'description': intro_text,
'parts': parts
}
with open(folder_name + '/' + debate_url.split('/')[-1] + '.json', 'w', encoding='utf8') as f:
json.dump(debate_info, f, default=json_util.default, ensure_ascii=False)
# urls for the search pages
election_2020_url = 'https://www.rev.com/blog/transcript-category/2020-election-transcripts'
debates_url = 'https://www.rev.com/blog/transcript-category/debate-transcripts'
# list of debate transcript urls
debate_urls = get_debates(debates_url)
election_2020_urls = get_debates(election_2020_url) - debate_urls
bad = {'https://www.rev.com/blog/transcripts/transcript-of-the-kamala-harris-and-joe-biden-heated-exchange', 'https://www.rev.com/blog/transcripts/transcript-from-first-night-of-democratic-debates', 'https://www.rev.com/blog/transcripts/transcript-donna-brazile-tells-ronna-mcdaniel-go-to-hell-on-fox-news', 'https://www.rev.com/blog/transcripts/transcript-joe-biden-mistakenly-says-hes-a-united-states-senate-candidate-in-south-carolina-speech'}
debate_urls -= bad
election_2020_urls -= bad
# for each debate transcript url, get all info and save to a file
for url in debate_urls:
scrape_url(url, 'debates', True)
for url in election_2020_urls:
scrape_url(url, 'others', False)
|
Java | UTF-8 | 1,505 | 2.578125 | 3 | [
"MIT"
] | permissive | package fr.umlv.valuetype;
import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;
import org.junit.jupiter.api.Test;
@SuppressWarnings("static-method")
class VectorTests {
@Test
void testAdd() {
assertAll(
() -> assertEquals(Vector.of(4), Vector.of(1).add(Vector.of(3))),
() -> assertEquals(Vector.of(4, 6), Vector.of(1, 2).add(Vector.of(3, 4))),
() -> assertEquals(Vector.of(4, 6, 8), Vector.of(1, 2, 3).add(Vector.of(3, 4, 5))),
() -> assertEquals(Vector.of(4, 6, 8, 10), Vector.of(1, 2, 3, 4).add(Vector.of(3, 4, 5, 6))),
() -> assertEquals(Vector.of(4, 6, 8, 10, 12), Vector.of(1, 2, 3, 4, 5).add(Vector.of(3, 4, 5, 6, 7)))
);
}
@Test
void testSubtract() {
assertAll(
() -> assertEquals(Vector.of(-2), Vector.of(1).subtract(Vector.of(3))),
() -> assertEquals(Vector.of(-2, -2), Vector.of(1, 2).subtract(Vector.of(3, 4))),
() -> assertEquals(Vector.of(-2, -2, -2), Vector.of(1, 2, 3).subtract(Vector.of(3, 4, 5))),
() -> assertEquals(Vector.of(-2, -2, -2, -2), Vector.of(1, 2, 3, 4).subtract(Vector.of(3, 4, 5, 6))),
() -> assertEquals(Vector.of(-2, -2, -2, -2, -2), Vector.of(1, 2, 3, 4, 5).subtract(Vector.of(3, 4, 5, 6, 7)))
);
}
}
|
JavaScript | UTF-8 | 3,322 | 2.796875 | 3 | [] | no_license | import React, { Component } from 'react';
import './Form.css';
import DadosPessoais from './DadosPessoais';
import FormErrors from './FormErrors';
class Form extends Component {
constructor (props) {
super(props);
this.state = {
name: '',
email: '',
cpf: '',
address: '',
city: '',
countryState: '',
addressType: '',
resume: '',
role: '',
roleDescription: '',
hasEntered: false,
formErrors: {email: '', password: ''},
};
}
handleChange = event => {
let { name, value } = event.target;
if(name === 'name') value = value.toUpperCase()
if(name === 'address') value = this.validateAddress(value)
this.updateState(name, value)
}
// ----------------------------------------------------------
// Parte copiada do gabarito, precisa enteder os Regex
onBlurHandler = event => {
let { name, value } = event.target;
if(name === 'city') value = value.match(/^\d/) ? '' : value
this.updateState(name, value)
}
updateState(name, value) {
this.setState((state) => ({
[name]: value,
formErrors: {
...state.formErrors,
[name]: this.validateField(name, value)
}
}));
}
validateAddress = address => address.replace(/[^\w\s]/gi, '')
handleSubmit = event => {
event.preventDefault();
}
validateField(fieldName, value) {
switch(fieldName) {
case 'email':
const isValid = value.match(/^([\w.%+-]+)@([\w-]+\.)+([\w]{2})$/i)
return isValid ? '' : ' is invalid';
default:
break;
}
return '';
}
// ------------------------------------------------------------
render() {
return (
<div>
<h1>Estados e React - Cadastro de Curriculo</h1>
<form className='form'>
<DadosPessoais value={this.state} handleChange={this.handleChange} onBlurHandler={this.onBlurHandler} />
<fieldset>
<legend>Dados profissionais:</legend>
<div className="container">
Resumo do currículo:
<textarea
name="resume"
maxLength="1000"
required
value={this.state.resume}
onChange={this.handleChange}
/>
</div>
<div className="container">
Cargo:
<input
type="text"
name="role"
maxLength="40"
required
value={this.state.role}
onChange={this.handleChange}
onMouseEnter={() => {
alert('Preencha com cuidado esta informação.');
}}
/>
</div>
<div className="container">
Descrição do cargo:
<textarea
name="roleDescription"
maxLength="500"
value={this.state.roleDescription}
onChange={this.handleChange}
/>
</div>
</fieldset>
</form>
<div className="container">
<FormErrors formErrors={this.state.formErrors} />
</div>
</div>
);
}
}
export default Form; |
Java | ISO-8859-1 | 1,063 | 2.328125 | 2 | [] | no_license | package page;
import appium.core.BasePage;
public class AccordionPage extends BasePage {
public void clicarOpcao1() {
selecionarPorTexto("Opo 1");
}
public void clicarOpcao2() {
selecionarPorTexto("Opo 2");
}
public void clicarOpcao3() {
selecionarPorTexto("Opo 3");
}
public void clicarOpcao4() {
selecionarPorTexto("Opo 4");
}
public void clicarOpcao5() {
selecionarPorTexto("Opo 5");
}
public boolean obterTextoAccordion1() {
return existeElentoPorTexto("Esta a descrio da opo 1");
}
public boolean obterTextoAccordion2() {
return existeElentoPorTexto("Esta a descrio da opo 2");
}
public boolean obterTextoAccordion3() {
return existeElentoPorTexto("Esta a descrio da opo 3. Que pode, inclusive ter mais que uma linha");
}
public boolean obterTextoAccordion4() {
return existeElentoPorTexto("Esta a descrio da opo 4");
}
public boolean obterTextoAccordion5() {
return existeElentoPorTexto("Esta a descrio da opo 5");
}
} |
TypeScript | UTF-8 | 475 | 2.546875 | 3 | [] | no_license | import { Guest } from './guest';
export class Scrum {
id: string;
meetingTitle: string;
totalTime: Date;
minutesPerGuest: number;
isCountdown: boolean;
started: boolean;
guests: Guest[];
constructor(meetTitle: string, minPerGuest: number, countDown: boolean, guestList: Guest[]) {
this.meetingTitle = meetTitle,
this.totalTime = new Date(),
this.minutesPerGuest = minPerGuest,
this.isCountdown = countDown,
this.guests = guestList
}
}
|
Python | UTF-8 | 3,064 | 3 | 3 | [
"MIT"
] | permissive | import numpy as np
from scipy.optimize import linear_sum_assignment
from collections import deque
from object_tracking.kalman_filter import KalmanFilter
from object_tracking.association import compute_association
class Tracklet:
def __init__(self, track_id, x1, y1, x2, y2, class_id=1):
self.x1 = x1
self.y1 = y1
self.x2 = x2
self.y2 = y2
self.w = self.get_width()
self.h = self.get_height()
self.track_id = track_id
self.class_id = class_id
self.hits = 0
self.misses = 0
# create a new kalman filter instance for this track
self.kf = KalmanFilter()
# set initial detection bbox as first measurement
self.kf.update(self.get_z())
def get_width(self):
return self.x2 - self.x1
def get_height(self):
return self.y2 - self.y1
def get_bottom_right(self, w, h):
return self.x1 + w, self.y1 + h
def get_z(self):
"""
get measurement vector z for kalman filtering
"""
return np.array([self.x1, self.y1, self.get_width(), self.get_height()])
def set_state(self, state):
self.x1 = state[0]
self.y1 = state[1]
self.x2, self.y2 = self.get_bottom_right(state[2], state[3])
def predict(self):
# predict the new state
pred_state = self.kf.predict()
# update the track with the new predicted state
self.set_state(pred_state)
def update_and_predict(self, z):
# update kalman filter with measurement vector (detection)
self.kf.update(self.get_z())
self.predict()
class Tracker:
def __init__(self, min_hits=1, max_misses=4):
self.tracks = []
self.available_ids = deque(list(range(100)))
self.max_misses = max_misses
self.min_hits = min_hits
def track(self, detections):
matches, unmatched_detections, unmatched_tracks = compute_association(self.tracks, detections)
for match in matches:
tracklet = self.tracks[match[0]]
detection = detections[match[1]]
tracklet.update_and_predict(detection)
tracklet.hits += 1
tracklet.misses = 0
self.tracks[match[0]] = tracklet
for unmatched_detection in unmatched_detections:
tracklet = Tracklet(track_id=self.available_ids.popleft(), **detections[unmatched_detection])
tracklet.predict()
# add to tracks list
self.tracks.append(tracklet)
for unmatched_track in unmatched_tracks:
tracklet = self.tracks[unmatched_track]
tracklet.predict()
tracklet.misses += 1
self.tracks[unmatched_track] = tracklet
# return ids for deleted tracks
self.available_ids.extend([x.id for x in filter(lambda x: x.misses > self.max_misses, self.tracks)])
# filter out deleted tracks
self.tracks = list(filter(lambda x: x.misses < self.max_misses, self.tracks))
return self.tracks
|
Shell | UTF-8 | 4,009 | 3.453125 | 3 | [] | no_license | #!/bin/sh
##############################################################
# Add the NCDC GIF processing to the end of the gempak_gif job
# There is no timing issue with the NCDC GIF, so it is
# okay to just add it here. If timing becomes a problem
# in the future, we should move it above somewhere else.
##############################################################
export PS4='exgempakgif_ncdc_skewt:$SECONDS + '
set -xa
cd $DATA
msg="The NCDC GIF processing has begun"
postmsg "$jlogfile" "$msg"
export NTS=$USHgempak/restore
if [ $MODEL = GDAS -o $MODEL = GFS ]
then
case $MODEL in
GDAS) fcsthrs="00";;
GFS) fcsthrs="00 12 24 36 48";;
esac
export fhr
for fhr in $fcsthrs
do
icnt=1
maxtries=180
export GRIBFILE=${COMIN}/${RUN}_${PDY}${cyc}f0${fhr}
while [ $icnt -lt 1000 ]
do
if [ -r ${COMIN}/${RUN}_${PDY}${cyc}f0${fhr} ] ; then
sleep 5
break
else
msg="The process is waiting ... ${GRIBFILE} file to proceed."
postmsg "${jlogfile}" "$msg"
sleep 20
let "icnt=icnt+1"
fi
if [ $icnt -ge $maxtries ]
then
msg="ABORTING: after 1 hour of waiting for ${GRIBFILE} file at F$fhr to end."
postmsg "${jlogfile}" "$msg"
export err=7 ; err_chk
exit $err
fi
done
cp ${COMIN}/${RUN}_${PDY}${cyc}f0${fhr} gem_grids${fhr}.gem
# if [ $cyc -eq 00 -o $cyc -eq 12 ]
#then
$USHgempak/gempak_${RUN}_f${fhr}_gif.sh
#fi
done
fi
####################################################################################
echo "-----------------------------------------------------------------------------"
echo "GFS MAG postprocessing script exmag_sigman_skew_k_gfs_gif_ncdc_skew_t.sh "
echo "-----------------------------------------------------------------------------"
echo "History: Mar 2012 added to processing for enhanced MAG skew_t"
echo "2012-03-11 Mabe -- reworked script to add significant level "
echo " data to existing mandatory level data in a new file"
echo "2013-04-24 Mabe -- Reworked to remove unneeded output with "
echo " conversion to WCOSS"
# Add ms to filename to make it different since it has both mandatory
# and significant level data $COMOUT/${RUN}.${cycle}.msupperair
# $COMOUT/${RUN}.${cycle}.msupperairtble
#####################################################################################
set -x
cd $DATA
export RSHPDY=`echo $PDY | cut -c5-``echo $PDY | cut -c3-4`
cp $HOMEgfs/gempak/dictionaries/sonde.land.tbl .
cp $HOMEgfs/gempak/dictionaries/metar.tbl .
sort -k 2n,2 metar.tbl > metar_stnm.tbl
cp $COMINgfs/${model}.$cycle.adpupa.tm00.bufr_d fort.40
export err=$?
if [[ $err -ne 0 ]] ; then
echo " File ${model}.$cycle.adpupa.tm00.bufr_d does not exist."
exit $err
fi
# $RDBFMSUA >> $pgmout 2> errfile
${UTILgfs}/exec/rdbfmsua >> $pgmout 2> errfile
err=$?;export err ;err_chk
export filesize=` ls -l rdbfmsua.out | awk '{print $5}' `
################################################################
# only run script if rdbfmsua.out contained upper air data.
################################################################
if [ $filesize -gt 40 ]
then
if [ $SENDCOM = "YES" ]; then
cp rdbfmsua.out $COMOUT/${RUN}.${cycle}.msupperair
cp sonde.idsms.tbl $COMOUT/${RUN}.${cycle}.msupperairtble
if [ $SENDDBN = "YES" ]; then
$DBNROOT/bin/dbn_alert DATA MSUPPER_AIR $job $COMOUT/${RUN}.${cycle}.msupperair
$DBNROOT/bin/dbn_alert DATA MSUPPER_AIRTBL $job $COMOUT/${RUN}.${cycle}.msupperairtble
fi
fi
fi
############################################################
# GOOD RUN
set +x
echo "********** JGFS_ATMOS_GEMPAK_NCDC_UPAPGIF COMPLETED"
set -x
############################################################
if [ -e "$pgmout" ] ; then
cat $pgmout
fi
msg="HAS COMPLETED NORMALLY!"
exit
|
Python | UTF-8 | 2,464 | 4.875 | 5 | [] | no_license | """
This program requires creating a function using
def , return, print, input, if, in keywords,
.append(), .pop(), .remove() list methods,
As well as other standard Python
This program takes string input and checks if that
string is in a list of strings
1) if string is in the list, it removes the first instance from list
2) if string is not in the list, the input gets appended to the list
3) if the string is empty, then the last item is popped from the list
4) if the list becomes empty, the program ends
5) if the user enters "quit" , then the program ends
program has 2 parts
program flow which can be modified to ask for
specific type of item. This is the programmers choice.
Add a list of fish, trees, books, movies, songs.... your choice.
2)list-o-matic Function which takes arguments of a string and a list.
The function modifies the list and returns a message as seen below.
example 1 input/output
look at all the animals ['cat', 'goat', 'cat']
enter the name of an animal: horse
1 instance of horse appended to list
look at all the animals ['cat', 'goat', 'cat', 'horse']
enter the name of an animal: cat
1 instance of cat removed from list
look at all the animals ['goat', 'cat', 'horse']
enter the name of an animal: cat
1 instance of cat removed from list
look at all the animals ['goat', 'horse']
enter the name of an animal: (<-- entered empty string)
horse popped from list
look at all the animals ['goat']
enter the name of an animal: (<-- entered empty string)
goat popped from list
Goodbye!
example 2
look at all the animals ['cat', 'goat', 'cat']
enter the name of an animal: Quit
Goodbye!
"""
arr = ['cat', 'goat', 'cat']
def printAll(arr):
print("look at all the animals", end=" ")
print(arr)
def findIndex(arr, str):
for i in arr:
if i == str:
return arr.index(i)
return -1
printAll(arr)
print("enter the name of an animal:", end=" ")
Input = input()
while Input != "Quit":
index = findIndex(arr, Input)
if index != -1:
arr.pop(index)
print("1 instance of "+Input+" removed from list")
elif len(Input) == 0:
Input = arr.pop()
print(Input+" popped form list")
elif index == -1:
arr.append(Input)
print("1 instance of "+Input+" appended to list")
if len(arr) == 0:
break
printAll(arr)
print("enter the name of an animal:", end=" ")
Input = input()
print("GoodBye")
|
C++ | UTF-8 | 2,282 | 2.703125 | 3 | [] | no_license | #include "PaintHelper.h"
#include <QRectF>
#include <QLine>
#include <math.h>
PaintHelper::PaintHelper()
{
QLinearGradient gradient(QPointF(50, -20), QPointF(80,20));
gradient.setColorAt(0.0,Qt::white);
gradient.setColorAt(1.0,QColor(0xa6,0xce,0x39));
background = QBrush(QColor(0,0,0));
circleBrush = QBrush(gradient);
circlePen = QPen(Qt::white);
circlePen.setWidth(7);
circlePen.setCapStyle(Qt::RoundCap);
textPen = QPen(Qt::white);
textFont.setPixelSize(50);
linePen = QPen(Qt::white);
linePen.setWidth(1);
count = 0;
zeroAngle = 1440;
}
void PaintHelper::paint(QPainter *painter, QPaintEvent *event, int secondsElapsed, int minutesElapsed,int hoursElapsed)
{
painter->fillRect(event->rect(), background);
painter->translate(100, 100);
painter->save();
painter->setBrush(circleBrush);
painter->setPen(circlePen);
int spanAngleSeconds, spanAngleMinutes, spanAngleHours;
float spanAngleSecondsFloat, spanAngleMinutesFloat, spanAngleHoursFloat;
QRectF rectSeconds = QRectF(-70.0, -70.0, 140.0, 140.0);
if (secondsElapsed == 0)
spanAngleSecondsFloat = -5760.0;
else
spanAngleSecondsFloat = float(secondsElapsed)/60.0 * -5760.0; // 96 = 5760 / 60
spanAngleSeconds = int(spanAngleSecondsFloat);
painter->drawArc(rectSeconds, zeroAngle, spanAngleSeconds);
QRectF rectMinutes = QRectF(-60.0,-60.0,120.0,120.0);
if (minutesElapsed == 0)
spanAngleMinutesFloat = -5760.0;
else
spanAngleMinutesFloat = float(minutesElapsed)/60.0 * -5760.0;
spanAngleMinutes = int(spanAngleMinutesFloat);
painter->drawArc(rectMinutes, zeroAngle, spanAngleMinutes);
QRectF rectHours = QRectF(-50.0,-50.0,100.0,100.0);
if (hoursElapsed == 0)
spanAngleHoursFloat = -5760.0;
else
spanAngleHoursFloat = float(hoursElapsed%12)/12.0 * -5760.0;
spanAngleHours = int(spanAngleHoursFloat);
painter->drawArc(rectHours, zeroAngle, spanAngleHours);
painter->setPen(linePen);
QLine line_1 = QLine(0,-100,0,100);
for (int i=0;i<6;++i){
painter->rotate(30);
painter->drawLine(line_1);
}
painter->rotate(180);
painter->setPen(textPen);
painter->setFont(textFont);
painter->drawText(QRect(-50, -50, 100, 100), Qt::AlignCenter, QString::number(secondsElapsed%60,10));
painter->restore();
}
|
C | UTF-8 | 843 | 3.625 | 4 | [] | no_license | // Purpose: Make an address book
// File Name: Ch15_17
// Completion Date: 20210625
#include <stdio.h>
#include <stdlib.h>
struct addrbook
{
char name[15];
int areacode;
int phone;
char city[10];
char street[12];
int number; // house number
} book[3] = {"Undertaker", 02, 529527, "TPC", "Hell road", 100, // assign initial values
"SmileFox", 02, 525566, "TPC", "Heaven road", 30,
"Undertaker", 02, 529478, "TPC", "Earth road", 50};
int main(void)
{
int i; // outter for loop control
puts("Name\t\tPhone\t\tAddress");
for (i = 0; i < 3; i++) { // output addrbook's info
printf("%s \t%02d-%d\t%s %s %d\n", book[i].name, book[i].areacode, book[i].phone,
book[i].city, book[i].street, book[i].number);
}
return EXIT_SUCCESS;
} |
Markdown | UTF-8 | 4,477 | 2.703125 | 3 | [] | no_license | ---
title: ReactNative 原生与JS交互
date: 2017-12-12 19:22:08
tags:
---
ReactNative中原生与JS的交互大致可以有两种形式,一种是原生主动发送事件给JS,一种是JS主动调用原生暴露的方法。要实现这两种交互需要编写一个原生模块,该模块继承了`ReactContextBaseJavaModule` 。
以下是原生模块代码示例:
``` java
package com.bundletest.modules;
import com.facebook.react.bridge.Arguments;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.bridge.WritableMap;
import com.facebook.react.modules.core.DeviceEventManagerModule;
import android.app.Activity;
import android.os.Handler;
import android.os.Looper;
import android.widget.Toast;
import java.util.HashMap;
import java.util.Map;
/**
* Created by gyh on 2017/12/12.
*/
public class IdModule extends ReactContextBaseJavaModule{
private static final String DURATION_SHORT_KEY = "SHORT";
private static final String DURATION_LONG_KEY = "LONG";
public IdModule(final ReactApplicationContext reactContext) {
super(reactContext);
new Handler(Looper.getMainLooper()).postDelayed(
new Runnable() {
@Override
public void run() {
gotoMainPage();
}
}, 3000
);
}
/*
* ReactContextBaseJavaModule要求派生类实现
* getName 方法。这个函数用于返回一个字符串名字
* 这个名字在JS端标记这个模块
*/
@Override
public String getName() {
return "ModuleId";
}
/*
* 通过 RCTDeviceEventEmitter 来发送事件
*/
public void gotoMainPage() {
WritableMap params = Arguments.createMap();
params.putInt("name", 666);
reactApplicationContext
.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit("test", params);
}
/*
* 一个可选的方法 getContants 返回了需要导出给
* JS使用的常量。不一定需要实现,但在定义一些可以
* 被JS使用的预定义的值时非常有用
*/
@Override
public Map<String, Object> getConstants() {
final Map<String, Object> constants = new HashMap<>();
constants.put(DURATION_LONG_KEY, Toast.LENGTH_LONG);
constants.put(DURATION_SHORT_KEY, Toast.LENGTH_SHORT);
return constants;
}
/*
* 使用注解ReactMethod导出一个方法给JS使用
* 方法的返回类型必须为 void
*/
@ReactMethod
public void show(String message, int duration) {
Toast.makeText(getReactApplicationContext(), message, duration).show();
}
}
```
模块代码写完后还需要注册模块:
``` java
package com.bundletest.modules;
import com.facebook.react.ReactPackage;
import com.facebook.react.bridge.NativeModule;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.uimanager.ViewManager;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Created by gyh on 2017/12/12.
*/
public class IdModulePackage implements ReactPackage {
/*
* 需要在应用的Package类的createNativeModules
* 方法中添加这个模块
*/
@Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
List<NativeModule> modules = new ArrayList<>();
modules.add(new IdModule(reactContext));
return modules;
}
@Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Collections.emptyList();
}
}
```
然后在`MainApplication` 中添加这个 `Package`
``` java
@Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(),
new IdModulePackage()
);
}
```
经过上面几个步骤,原生模块添加完成,可以在JS端使用。
``` js
import { NativeModules, DeviceEventEmitter } from 'react-native';
// 通过NativeModules调用ReactMethod暴露的方法
NativeModules.ToastExample.show('Awesome', ToastExample.SHORT);
// 通过 DeviceEventEmitter 监听事件
DeviceEventEmitter.addListener('test', function(result) {
// handle event.
});
``` |
Java | UTF-8 | 1,648 | 2.421875 | 2 | [
"Apache-2.0"
] | permissive | /**
* Copyright 2015 Netflix, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.netflix.spectator.api;
/**
* Track the sample distribution of events. An example would be the response sizes for requests
* hitting and http server.
*
* The precise set of information maintained depends on the implementation. Most should try to
* provide a consistent implementation of {@link #count()} and {@link #totalAmount()},
* but some implementations may not. In particular, the implementation from {@link NoopRegistry}
* will always return 0.
*/
public interface DistributionSummary extends Meter {
/**
* Updates the statistics kept by the summary with the specified amount.
*
* @param amount
* Amount for an event being measured. For example, if the size in bytes of responses
* from a server. If the amount is less than 0 the value will be dropped.
*/
void record(long amount);
/** The number of times that record has been called since this timer was created. */
long count();
/** The total amount of all recorded events since this summary was created. */
long totalAmount();
}
|
Python | UTF-8 | 946 | 3.125 | 3 | [] | no_license | import sys
sys.setrecursionlimit(10000)
r, c = map(int, input().split())
board = [input() for _ in range(r)]
directions = [(1,0), (-1,0), (0, 1), (0, -1)]
result = 0
def promising(x, y, route):
if x<0 or x>=r or y<0 or y>=c:
return False
if board[x][y] in route:
return False
return True
def dfs(x, y, step): # 시간초과
global result
result = max(result, len(step))
for dx, dy in directions:
nx, ny = x+dx, y+dy
if promising(nx, ny, step):
dfs(nx, ny, step+board[nx][ny])
# 강의 bfs 사용
def bfs(x, y):
global result
q = set()
q.add((x, y, board[x][y]))
while q:
x, y, step = q.pop()
result = max(result, len(step))
for dx, dy in directions:
nx, ny = x+dx, y+dy
if promising(nx, ny, step):
q.add((nx, ny, step+board[nx][ny]))
#dfs(0, 0, board[0][0])
bfs(0, 0)
print(result)
|
C# | UTF-8 | 1,628 | 2.546875 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace UI_Notepad
{
public partial class frmHome : Form
{
public frmHome()
{
InitializeComponent();
}
public static string nomeProjeto;
MessageBox MessageBox = new MessageBox();
private void btnCriar_Click(object sender, EventArgs e)
{
if (txtNomeProjeto.Text.Length != 0)
{
nomeProjeto = txtNomeProjeto.Text;
frmNotepad objNotepad = new frmNotepad();
this.Hide();
objNotepad.Show();
}
else
{
MessageBox.lblTitulo.Text = "Ops... algo não deu certo";
MessageBox.lblDescricao.Text = "Você precisa digitar um nome válido para o projeto.";
MessageBox.btnSim.Visible = false;
MessageBox.btnNao.Text = "Ok";
MessageBox.btnFocus.Focus();
MessageBox.ShowDialog();
txtNomeProjeto.BackColor = Color.Red;
MessageBox.Default();
}
}
private void txtNomeProjeto_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyData == Keys.Enter)
{
btnCriar_Click(sender, e);
}
}
private void btnCancelar_Click(object sender, EventArgs e)
{
Application.Exit();
}
}
}
|
PHP | UTF-8 | 467 | 2.578125 | 3 | [] | no_license | <?php
//自动加载类
function __autoload($class_name){
require "./{$class_name}.class.php";
}
$c = isset($_GET['c'])?$_GET['c']:'Products'; //获取控制器
$a = isset($_GET['a'])?$_GET['a']:'list'; //获取方法
$controller_name = $c.'Controller'; //拼接控制器名
$action_name = $a.'Action'; //拼接方法名
$controller = new $class_name(); //实例化控制器
$controller -> $action_name(); //调用方法
?> |
Java | UTF-8 | 924 | 3.09375 | 3 | [] | no_license | package com.repeatednumber;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class ReapetedElement {
Object obj;
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((obj == null) ? 0 : obj.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ReapetedElement other = (ReapetedElement) obj;
if (this.obj == null) {
if (other.obj != null)
return false;
} else if (!this.obj.equals(other.obj))
return false;
return true;
}
public static void main(String[] args) {
int a[]={20,30,56,86,45,60};
for(int i=1;i<=20;i++){
if(i%5==0){
continue;
}
System.out.println(i);
}
}
}
|
C# | UTF-8 | 6,763 | 2.921875 | 3 | [] | no_license | using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace AlgoritmoGeneticoDP1
{
class Program
{
private const int MAX_ITERACIONES = 1000;
private const int MAX_REPETIDOS = 25;
public static void leerDataEntrada(ArrayList trabajadores, ArrayList procesos, ref int duracionTurno)
{
int numPuestosdeTrabajo = 0; //Indica el numero de puestos de trabajo
int numTrabajadores = 0; //Indica el numero de trabajadores en un dia de trabajo
StreamReader file = new StreamReader("data_input.csv");
// Leer cabeceras principales
file.ReadLine();
// Lectura de numero de trabajadores
// Lectura de numero de puestos de trabajo
// Lectura de alfa
// Lectura de duracion de turno
string[] line = file.ReadLine().Split(',');
numTrabajadores = Convert.ToInt32(line[0]);
numPuestosdeTrabajo = Convert.ToInt32(line[1]);
double alfa = Convert.ToDouble(line[2]); //No se usa alfa en algoritmo genético
duracionTurno = Convert.ToInt32(line[3]);
file.ReadLine();
// Creando los trabajadores
for (int i = 0; i < numTrabajadores; i++)
{
Trabajador trabajador = new Trabajador(i,"Trabajador "+(i+1));
trabajadores.Add(trabajador);
}
//Lectura de cabecera indices de rotura
string cabeceraIndices = file.ReadLine();
//Lectura indices de rotura de cada trabajador
for (int i = 0; i < numTrabajadores; i++)
{
line = file.ReadLine().Split(',');
for (int j = 0; j < numPuestosdeTrabajo; j++)
{
double rotura = Convert.ToDouble(line[j + 1]);
((Trabajador)trabajadores[i]).indicesRotura.Add(rotura);
}
}
file.ReadLine();
//Lectura de cabecera indices de tiempo
cabeceraIndices = file.ReadLine();
//Lectura indices de tiempo de cada trabajador
for (int i = 0; i < numTrabajadores; i++)
{
line = file.ReadLine().Split(',');
for (int j = 0; j < numPuestosdeTrabajo; j++)
{
int tiempo = Convert.ToInt32(line[j + 1]);
((Trabajador)trabajadores[i]).indicesTiempo.Add(tiempo);
}
}
file.ReadLine();
//lectura de vacantes
line = file.ReadLine().Split(',');
for (int i = 0; i < numPuestosdeTrabajo; i++)
{
//Indica las vacantes maximas de trabajadores en cada puesto de trabajo
int vacantes = Convert.ToInt32(line[i + 1]);
Proceso proceso = new Proceso(i, vacantes,"Proceso "+(i+1));
procesos.Add(proceso);
}
file.Close();
}
[STAThread]
private static void Main(string[] args)
{
int duracionTurno = 0; //Indica la duracion total de un dia de trabajo en minutos
ArrayList trabajadores = new ArrayList();
ArrayList procesos = new ArrayList();
//Se procede a leer la data inicial desde un archivo .csv
leerDataEntrada(trabajadores, procesos, ref duracionTurno);
StreamWriter reporte = new StreamWriter("reporte.txt");
var watch = System.Diagnostics.Stopwatch.StartNew();
//Se genera la población inicial
int generacion = 1; //Indica el numero de la generacion
Poblacion poblacion = new Poblacion(trabajadores, procesos, duracionTurno);
//Se obtiene el mejor cromosoma de la poblacion inicial
Cromosoma mejorCromosoma = poblacion.obtenerMejorCromosoma();
Cromosoma ultimoCromosoma = new Cromosoma();
reporte.WriteLine("Población inicial");
reporte.WriteLine("Mejor cromosoma");
mejorCromosoma.mostrarCromosoma(reporte);
int repetido = 0, i = 0;
// Condicion de parada del algoritmo genetico
while ((i < MAX_ITERACIONES) && (repetido < MAX_REPETIDOS))
{
reporte.WriteLine();
reporte.WriteLine("Generación " + generacion);
// Generar la siguiente generacion
poblacion.SiguienteGeneracion();
//Se obtiene el mejor cromosoma de la actual generacion
Cromosoma nuevoCromosoma = poblacion.obtenerMejorCromosoma();
//Se compara si el mejor cromosoma de la generacion actual es mejor que el mejor cromosoma historico
if (nuevoCromosoma.FitnessActual > mejorCromosoma.FitnessActual)
{
mejorCromosoma = nuevoCromosoma;
}
if (Math.Truncate(nuevoCromosoma.FitnessActual) == Math.Truncate(ultimoCromosoma.FitnessActual))
{
//Si el mejor cromosoma de la generacion actual es igual al mejor cromosoma de la generacion anterior
repetido++;
}
else
{
//Si el mejor cromosoma de la generacion actual no es igual al mejor cromosoma de la generacion anterior
repetido = 0;
}
generacion++;
i++;
// Se guarda el mejor cromosoma actual para tenerlo en cuenta en la siguiente generacion
ultimoCromosoma = nuevoCromosoma;
reporte.WriteLine("Mejor cromosoma:");
nuevoCromosoma.mostrarCromosoma(reporte);
}
reporte.WriteLine();
reporte.WriteLine("RESULTADOS");
reporte.WriteLine("Mejor cromosoma global");
mejorCromosoma.mostrarCromosoma(reporte);
reporte.Close();
// Se muestran las asignaciones correspondientes
//Console.WriteLine("Asignaciones");
//mejorCromosoma.mostrarAsignaciones();
mejorCromosoma.exportarCSV();
watch.Stop();
var elapsedMs = watch.ElapsedMilliseconds;
Console.WriteLine("Tiempo del algoritmo {0} segundos.", elapsedMs / 1000.0);
Console.WriteLine("Fitness del mejor cromosoma {0}.", mejorCromosoma.FitnessActual);
Console.WriteLine("Presione ENTER para continuar");
Console.ReadLine();
}
}
}
|
Java | UTF-8 | 4,568 | 2.046875 | 2 | [
"Apache-2.0"
] | permissive | /**
* Copyright 2016, KyoSherlock
* <p/>
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* <p/>
* http://www.apache.org/licenses/LICENSE-2.0
* <p/>
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.kyo.fitssystemwindows;
import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.support.v4.view.ViewCompat;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
/**
* Created by jianghui on 6/20/16.
*/
public class FitsSystemWindowsFrameLayout2 extends FitsSystemWindowsFrameLayout {
private int effectiveHeight;
private int lastLimitHeight;
private int lastBottomInset;
private OnKeyboardVisibleChangedListener onKeyboardVisibleChangedListener;
public FitsSystemWindowsFrameLayout2(Context context) {
super(context);
this.init(context);
}
public FitsSystemWindowsFrameLayout2(Context context, AttributeSet attrs) {
super(context, attrs);
this.init(context);
}
public FitsSystemWindowsFrameLayout2(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
this.init(context);
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public FitsSystemWindowsFrameLayout2(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
this.init(context);
}
public void setOnKeyboardVisibleChangedListener(OnKeyboardVisibleChangedListener onKeyboardVisibleChangedListener) {
this.onKeyboardVisibleChangedListener = onKeyboardVisibleChangedListener;
}
private void init(Context context) {
effectiveHeight = dp2px(context, 200);
}
public static int dp2px(Context context, float dp) {
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
final int px = (int) (metrics.density * dp + 0.5f);
if (px != 0) return px;
if (dp == 0) return 0;
if (dp > 0) return 1;
return -1;
}
public static int getActionBarHeight(Context context) {
int result = 0;
TypedValue tv = new TypedValue();
context.getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true);
if (tv.resourceId > 0) {
result = context.getResources().getDimensionPixelSize(tv.resourceId);
}
return result;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int mode = MeasureSpec.getMode(heightMeasureSpec);
if (mode == MeasureSpec.UNSPECIFIED) {
throw new IllegalStateException("WindowInsetsFrameLayout2 is not supported in this case!");
}
if (Build.VERSION.SDK_INT >= 21) {
final boolean applyInsets = lastInsets != null && ViewCompat.getFitsSystemWindows(this);
if (applyInsets) {
int bottomInset = FitsSystemWindowsFrameLayout2CompatApi21.getBottomInset(lastInsets);
Log.i("kyo", "lastBottomInset:" + lastBottomInset);
if (bottomInset > lastBottomInset) {
int distance = bottomInset - lastBottomInset;
if (distance > effectiveHeight) { // This judgment is superfluous
dispatchKeyboardVisibleChanged(true, distance);
}
} else if (bottomInset < lastBottomInset) {
int distance = lastBottomInset - bottomInset;
if (distance > effectiveHeight) {
dispatchKeyboardVisibleChanged(false, distance);
}
}
lastBottomInset = bottomInset;
}
} else {
int height = MeasureSpec.getSize(heightMeasureSpec);
if (lastLimitHeight == 0) {
lastLimitHeight = height;
} else {
if (height > lastLimitHeight) {
int distance = height - lastLimitHeight;
if (distance > effectiveHeight) {
dispatchKeyboardVisibleChanged(false, distance);
}
} else if (height < lastLimitHeight) {
int distance = lastLimitHeight - height;
if (distance > effectiveHeight) {
dispatchKeyboardVisibleChanged(true, distance);
}
}
lastLimitHeight = height;
}
}
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
private void dispatchKeyboardVisibleChanged(boolean visible, int height) {
if (onKeyboardVisibleChangedListener != null) {
onKeyboardVisibleChangedListener.onKeyboardVisibleChanged(visible, height);
}
}
} |
Swift | UTF-8 | 910 | 3.109375 | 3 | [] | no_license | //
// ImagePreviewViewModel.swift
// image-browser
//
// Created by Shivam Jaiswal on 22/05/20.
// Copyright © 2020 Shivam Jaiswal. All rights reserved.
//
import Foundation
protocol ImagePreviewViewModelProtocol {
func numberOfItems(inSection section: Int) -> Int
func item(at indexPath: IndexPath) -> ImageItem
var images: [ImageItem] { get }
var initialIndexPath: IndexPath { get }
}
class ImagePreviewViewModel: ImagePreviewViewModelProtocol {
private(set) var images = [ImageItem]()
let initialIndexPath: IndexPath
init(images: [ImageItem], initialIndexPath: IndexPath) {
self.images = images
self.initialIndexPath = initialIndexPath
}
}
extension ImagePreviewViewModel {
func numberOfItems(inSection section: Int) -> Int {
return images.count
}
func item(at indexPath: IndexPath) -> ImageItem {
return images[indexPath.row]
}
}
|
PHP | UTF-8 | 202 | 2.75 | 3 | [] | no_license | <?php
class Venta
{
public $usuario;
public $producto;
public function __construct($usuario, $producto)
{
$this->usuario = $usuario;
$this->producto = $producto;
}
} |
Java | UTF-8 | 2,771 | 3.8125 | 4 | [] | no_license | package Utils;
public class utils {
/**
* Méthode pour vérifier si la réponse du joueur est un Integer
* @param reponse String saisie par le joueur
* @return temp integer saisie par le joueur ou -1 valeur incohérente
*/
private static int VerificationInt(String reponse){
int temp;
try {
temp=Integer.parseInt(reponse);
} catch (NumberFormatException e) {
System.out.println("Votre réponse n'est pas un chiffre");
temp=-1;
}
return temp;
}
/**
* Méthode pour vérifier si la réponse est entre les valeurs mises en conditions
* @param temp int saisie ou -1 valeur incoherente si la saisie n'etai pas de type Int
* @param mini int valeur minimum
* @param maxi int valeur maximum
* @return ok boolean qui a false pour valeur si saisie incohérente
*/
private static boolean VerificationValeurDansPortee(int temp, int mini, int maxi){
boolean ok;
ok=((temp >= mini) && (temp <= maxi));
if(!ok)
System.out.println("Votre réponse doit être comprise entre "+mini+" et "+maxi);
return ok;
}
/**
* Méthode englobant les vérifications avec un boucle pour relancer la saisie
* @param question String informant le joueur de la futur caracteristique
* @param mini int valeur minimum
* @param maxi int valeur maximum
* @return intReponse la saisie cohérente
*/
public static int RetourDeValeur(String question, int mini, int maxi){
boolean nombreOk;
int intReponse;
String reponse;
do {
reponse=Saisie.Saisir(question);
intReponse= VerificationInt(reponse);
nombreOk=VerificationValeurDansPortee(intReponse, mini, maxi);
}while(!nombreOk);
return intReponse;
}
/**
* Methode de verification du niveau
* La sommme de la force, l'agilité et l'inteligence doivent être egaux au niveau
* @param force int saisi par le joueur
* @param agilite int saisi par le joueur
* @param intelligence int saisi par le joueur
* @param niveau int saisi par le joueur
* @return ok boolean qui aura false pour valeur si les criteres ne sont pas reunis
*/
public static boolean VerificationNiveau(int force, int agilite, int intelligence, int niveau){
boolean ok;
ok=false;
if((force+agilite+intelligence)==niveau)
ok = true;
else
System.out.println("La somme de votre force("+force+"), de votre agilité("+agilite+
") et de votre intelligence("+intelligence+") doit être egale a votre niveau("+niveau+")");
return ok;
}
}
|
Java | UTF-8 | 312 | 2.125 | 2 | [
"MIT"
] | permissive | package se.lnu.domain.error;
/**
* Created by Jakob on 2016-03-11.
*/
public class E4IllegalTFTPOperation extends TFTPError
{
private static byte[] errcode = new byte[]{0, 4};
public E4IllegalTFTPOperation()
{
super(errcode, "The operation code is not allowed according to TFTP");
}
}
|
TypeScript | UTF-8 | 665 | 2.796875 | 3 | [] | no_license | const mainButtonOptions: string[] = [
"I'm bored!",
"I have nothing to do!",
"Help!",
"Cure my boredom",
];
const waitingMessageOptions: string[] = [
"Really... again?",
"Ya know, Only boring people can be bored",
"Please wait...",
"Scanning your brain... hold still",
"Consulting the wizard... please wait",
];
const randomNumber = (options: unknown[]) => {
return Math.floor(Math.random() * Math.floor(options.length));
};
export const getButtonOption = () => {
return mainButtonOptions[randomNumber(mainButtonOptions)];
};
export const getWaitingOptions = () => {
return waitingMessageOptions[randomNumber(waitingMessageOptions)];
};
|
Java | UTF-8 | 4,059 | 4.15625 | 4 | [] | no_license | /* Add and Search Word
Design a data structure that supports the following two operations: addWord(word) and search(word)
search(word) can search a literal word or a regular expression string containing only letters a-z or ..
A . means it can represent any one letter.
Example
addWord("bad")
addWord("dad")
addWord("mad")
search("pad") // return false
search("bad") // return true
search(".ad") // return true
search("b..") // return true
*/
public class WordDictionary {
public class TrieNode {
public char c;
public HashMap<Character, TrieNode> children;
public boolean hasWord;
public TrieNode() {
children = new HashMap<Character, TrieNode>();
hasWord = false;
}
public TrieNode(char c) {
this.c = c;
children = new HashMap<Character, TrieNode>();
hasWord = false;
}
}
private TrieNode root;
public WordDictionary() {
root = new TrieNode();
}
// Adds a word into the data structure.
public void addWord(String word) {
// Write your code here
TrieNode curNode = root;
char[] wordArray = word.toCharArray();
HashMap<Character, TrieNode> children = root.children;
for(int i = 0; i < wordArray.length; i++) {
char curWord = wordArray[i];
if(!children.containsKey(curWord)) {
TrieNode newNode = new TrieNode(curWord);
children.put(curWord, newNode);
curNode = newNode;
}else {
curNode = children.get(curWord);
}
children = curNode.children;
if(i == wordArray.length - 1) {
curNode.hasWord = true;
}
}
}
private boolean find(char[] wordArray, int index, TrieNode curNode) {
char letter = wordArray[index]; //记住, 无论BFS或DFS都是word[index]与curNode.children 作比较, 因为index总是比root晚一步
if(index == wordArray.length - 1) {
if(letter == '.') {
if(curNode.children.size() > 0) {
boolean flag = false;
for(TrieNode child : curNode.children.values()) {
if(child.hasWord) {
flag = true;
}
}
return flag;
}else {
return false;
}
}else {
if(curNode.children.containsKey(letter)) {//记住, 无论BFS或DFS都是word[index]与curNode.children 作比较, 因为index总是比root晚一步
return curNode.children.get(letter).hasWord;
}else {
return false;
}
}
}
if(letter == '.') {
if(curNode.children.size() == 0) {
return false;
}else {
boolean flag = false;
for(TrieNode child : curNode.children.values()) {//记住, 无论BFS或DFS都是word[index]与curNode.children 作比较, 因为index总是比root晚一步
if(find(wordArray, index + 1, child)) {
flag = true;
}
}
return flag;
}
}else {
if(curNode.children.containsKey(letter)) {//记住, 无论BFS或DFS都是word[index]与curNode.children 作比较, 因为index总是比root晚一步
return find(wordArray, index + 1, curNode.children.get(letter));
}else {
return false;
}
}
}
// Returns if the word is in the data structure. A word could
// contain the dot character '.' to represent any one letter.
public boolean search(String word) {
// Write your code here
return find(word.toCharArray(), 0, root);
}
} |
Java | UTF-8 | 283 | 1.984375 | 2 | [] | no_license | package com.butterknife;
import android.app.Activity;
import android.view.View;
/**
* Created by zz on 2018/5/9.
*/
public class Utils {
public static <T extends View> T findViewById(Activity activity, int viewId){
return (T)activity.findViewById(viewId);
}
}
|
Markdown | UTF-8 | 3,502 | 3.09375 | 3 | [] | no_license | ---
layout: post
title: .Net not recognising regional settings
wordpress_id: 3
wordpress_url: http://blog.emson.co.uk/?p=3
---
#.Net not recognising regional settings
The other day I had the following problem.
One of my test servers had been setup with US regional settings and should have been setup with UK settings.
The problem had been unnoticed for a while until our C# .Net application tried to call a stored procedure on a database on another server. This database server had UK regional settings.
The stored procedure expected to get a date in UK 'Long format'. The error message was a database error saying something like:
convertion error can't convert from NVarChar to DateTime
As the application was already compiled and being used on a live server I could not modify the code, I therefore had to run SQL Profiler and see what values were being passed into the stored procedure. This is where I saw the US 'Long Date' format being passed in.
<!--more-->
##.Net regional settings fix##
So I tried changing the regional settings on my server back to the UK, but the application was still sending the US 'Long Date' value.
I dug real deep and suspected that IIS was doing something funny and found further regional settings in an **Advanced** tab, but still this didn't fix the issue.
The problem I soon discovered is that when you install the .Net framework it internalises the regional settings but when you try and change them on the server these internalised settings don't get changed.
The only solution to this is then to modify the <b>machine.config</b> file.
The <b>machine.config</b> file is in each installation of the .Net framework. I happen to have both .Net 1.1 and .Net 2.0, however I changed the <b>machine.config</b> file in only the .Net 1.1 installation directory (even though our application is .Net 2.0) and all worked fine.
The <b>machine.config</b> can be found in this directory:
C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322\CONFIG
If you are using .Net 2.0 I'm sure you can make the same changes to the **globalization** XML node.
Please change the **globalization** XML node to have the correct cultural settings in our case **en-GB**:
<globalization
fileEncoding="utf-8"
requestEncoding="utf-8"
responseEncoding="utf-8"
culture="en-GB"
uiCulture="en-GB"
/>
To test that a .Net application would send the correct settings I wrote a simple test app which would print the 'Long Date' to the console. Here is the source code if you want to quickly test it yourself:
**ShowLongDate.cs**
{% highlight c# %}
using System;
namespace examples
{
class ShowLongDate
{
static void Main(string[] args)
{
DateTime current = DateTime.Now;
string longDate = current.ToLongDateString();
System.Console.WriteLine(string.Format("Date as longDate: {0}", longDate));
}
}
}
{% endhighlight %}
##Interesting things I learned##
You can open the regional settings from the commandline or from **Start/Run** by typing
intl.cpl
Also all the regional settings are located in the registry here:
HKEY_CURRENT_USER/Control Panel/International
Useful URLs:
<a href="http://www.microsoft.com/globaldev/reference/localetable.mspx">http://www.microsoft.com/globaldev/reference/localetable.mspx</a>
Anyway I hope this helps if you have the same problem.
|
Java | UTF-8 | 907 | 3.5625 | 4 | [] | no_license | package Leetcode.third;
/**
* 合并两个排序的链表
*/
public class jianzhi25 {
public class ListNode{
private int val;
private ListNode next;
public ListNode(int x){
this.val = x;
}
}
public ListNode mergeTwoLists(ListNode l1,ListNode l2){
//这里有一个伪节点的思想,需要搞清楚
ListNode cur = new ListNode(0),dum = cur;
while(l1 != null && l2 != null){
if(l1.val < l2.val){
cur.next = l1;
//l1继续往下走
l1 = l1.next;
}else{
cur.next = l2;
//l2继续往下走
l2 = l2.next;
}
//cur继续往下走
cur = cur.next;
}
//剩下的没走完的继续走下去
cur.next = (l1!=null?l1:l2);
return dum.next;
}
}
|
Python | UTF-8 | 151 | 2.75 | 3 | [] | no_license | ra=int(input())
ea=[int(q) for q in input().split()]
ww=0
for q in range(ra):
for m in range(q):
if ea[m]<ea[q]:
ww+=ea[m]
print(ww)
|
PHP | UTF-8 | 2,907 | 2.6875 | 3 | [] | no_license | <?php
namespace Pok\Application\Console;
use Symfony\Component\DependencyInjection\Container,
Symfony\Component\Console\Output\OutputInterface,
Symfony\Component\Console\Input\InputInterface;
class Application extends \Symfony\Component\Console\Application {
protected $container;
public function __construct(Container $container) {
parent::__construct(
'Pok',
'@PACKAGE_VERSION@' == '@'.'PACKAGE_VERSION@' ? 'dev' : '@PACKAGE_VERSION@'
);
$this->setContainer($container);
}
public function run(InputInterface $input = null, OutputInterface $output = null)
{
if (null === $input) {
$input = new Input\ArgvInput();
}
return parent::run($input, $output);
}
public function doRun(InputInterface $input, OutputInterface $output) {
// Detect registry
$registryPath = $this->getRegistryPath($input);
if (realpath($registryPath . '/.pok') === false) {
// Run init registry command
$command = new Command\InitRegistryCommand();
$command->setApplication($this);
$this->runningCommand = $command;
$statusCode = $command->run($input, $output);
$this->runningCommand = null;
if (is_numeric($statusCode) && $statusCode !== 0) {
return $statusCode;
}
}
// Set registry into DI
$this->getContainer()->setParameter('pok.registryPath', $registryPath);
$output->write("<info>Using registry at $registryPath</info>", true);
return parent::doRun($input, $output);
}
/**
* Gets the help message.
*
* @return string A help message.
*/
public function getHelp()
{
$messages = array(
$this->getLongVersion(),
'',
'<comment>Usage:</comment>',
sprintf(" [/path/to/registry] [options] command [arguments]\n"),
'<comment>Options:</comment>',
);
foreach ($this->definition->getOptions() as $option) {
$messages[] = sprintf(' %-29s %s %s',
'<info>--'.$option->getName().'</info>',
$option->getShortcut() ? '<info>-'.$option->getShortcut().'</info>' : ' ',
$option->getDescription()
);
}
return implode("\n", $messages);
}
public function getRegistryPath(InputInterface $input)
{
$registryPath = getcwd();
if ($input instanceof Input\ArgvInput && $input->getRegistryPathArgument() !== false) {
$registryPath = $input->getRegistryPathArgument();
}
return $registryPath;
}
public function setContainer(Container $container)
{
$this->container = $container;
}
public function getContainer()
{
// TODO move this to a helper?
return $this->container;
}
} |
Java | UTF-8 | 4,472 | 1.929688 | 2 | [] | no_license | package com.easy.infra.util.mybatis.mapper;
import com.easy.infra.util.mybatis.method.EasyDeleteByIdMethodGenerator;
import com.easy.infra.util.mybatis.method.EasyInsertMethodGenerator;
import com.easy.infra.util.mybatis.method.EasySelectByIdMethodGenerator;
import com.easy.infra.util.mybatis.method.EasySelectMethodGenerator;
import com.easy.infra.util.mybatis.method.EasySelectOneMethodGenerator;
import com.easy.infra.util.mybatis.method.EasyUpdateMethodGenerator;
import org.mybatis.generator.api.CommentGenerator;
import org.mybatis.generator.api.dom.java.CompilationUnit;
import org.mybatis.generator.api.dom.java.FullyQualifiedJavaType;
import org.mybatis.generator.api.dom.java.Interface;
import org.mybatis.generator.api.dom.java.JavaVisibility;
import org.mybatis.generator.api.dom.java.TopLevelClass;
import org.mybatis.generator.codegen.mybatis3.javamapper.JavaMapperGenerator;
import org.mybatis.generator.codegen.mybatis3.javamapper.elements.AbstractJavaMapperMethodGenerator;
import org.mybatis.generator.internal.util.StringUtility;
import org.mybatis.generator.internal.util.messages.Messages;
import java.util.ArrayList;
import java.util.List;
/**
* @Author rzq
* @Desc
* @Date 2020-02-16
**/
public class EasyJavaMapperGenerator extends JavaMapperGenerator {
public List<CompilationUnit> getCompilationUnits() {
this.progressCallback.startTask(Messages.getString("Progress.17", this.introspectedTable.getFullyQualifiedTable().toString()));
CommentGenerator commentGenerator = this.context.getCommentGenerator();
FullyQualifiedJavaType type = new FullyQualifiedJavaType(this.introspectedTable.getMyBatis3JavaMapperType());
Interface interfaze = new Interface(type);
interfaze.setVisibility(JavaVisibility.PUBLIC);
commentGenerator.addJavaFileComment(interfaze);
String rootInterface = this.introspectedTable.getTableConfigurationProperty("rootInterface");
if (!StringUtility.stringHasValue(rootInterface)) {
rootInterface = this.context.getJavaClientGeneratorConfiguration().getProperty("rootInterface");
}
if (StringUtility.stringHasValue(rootInterface)) {
FullyQualifiedJavaType fqjt = new FullyQualifiedJavaType(rootInterface);
interfaze.addSuperInterface(fqjt);
interfaze.addImportedType(fqjt);
}
this.addInsertMethod(interfaze);
this.addUpdateMethod(interfaze);
// this.addDeleteByIdMethod(interfaze);
// this.addSelectByIdMethod(interfaze);
this.addSelectMethod(interfaze);
this.addSelectOneMethod(interfaze);
List<CompilationUnit> answer = new ArrayList();
if (this.context.getPlugins().clientGenerated(interfaze, (TopLevelClass) null, this.introspectedTable)) {
answer.add(interfaze);
}
List<CompilationUnit> extraCompilationUnits = this.getExtraCompilationUnits();
if (extraCompilationUnits != null) {
answer.addAll(extraCompilationUnits);
}
return answer;
}
protected void addInsertMethod(Interface interfaze) {
AbstractJavaMapperMethodGenerator methodGenerator = new EasyInsertMethodGenerator();
this.initializeAndExecuteGenerator(methodGenerator, interfaze);
}
protected void addSelectByIdMethod(Interface interfaze) {
AbstractJavaMapperMethodGenerator methodGenerator = new EasySelectByIdMethodGenerator();
this.initializeAndExecuteGenerator(methodGenerator, interfaze);
}
protected void addDeleteByIdMethod(Interface interfaze) {
AbstractJavaMapperMethodGenerator methodGenerator = new EasyDeleteByIdMethodGenerator();
this.initializeAndExecuteGenerator(methodGenerator, interfaze);
}
protected void addUpdateMethod(Interface interfaze) {
AbstractJavaMapperMethodGenerator methodGenerator = new EasyUpdateMethodGenerator();
this.initializeAndExecuteGenerator(methodGenerator, interfaze);
}
protected void addSelectMethod(Interface interfaze) {
AbstractJavaMapperMethodGenerator methodGenerator = new EasySelectMethodGenerator();
this.initializeAndExecuteGenerator(methodGenerator, interfaze);
}
protected void addSelectOneMethod(Interface interfaze) {
AbstractJavaMapperMethodGenerator methodGenerator = new EasySelectOneMethodGenerator();
this.initializeAndExecuteGenerator(methodGenerator, interfaze);
}
} |
Ruby | UTF-8 | 439 | 3.53125 | 4 | [] | no_license | require 'euler'
include Euler
# Each new term in the Fibonacci sequence is generated by adding the previous two terms.By starting with 1 and 2,
# the first 10 terms will be:
#
# 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
#
# By considering the terms in the Fibonacci sequence whose values do
# not exceed four million, find the sum of the even-valued terms.
puts fibonacci.take_while { |n| n < 4000000 }.select { |n| n % 2 == 0 }.reduce(:+)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.