language stringclasses 15
values | src_encoding stringclasses 34
values | length_bytes int64 6 7.85M | score float64 1.5 5.69 | int_score int64 2 5 | detected_licenses listlengths 0 160 | license_type stringclasses 2
values | text stringlengths 9 7.85M |
|---|---|---|---|---|---|---|---|
C++ | UTF-8 | 4,410 | 3.09375 | 3 | [] | no_license | #include <vector>
#include <list>
#include <map>
#include <set>
#include <deque>
#include <stack>
#include <bitset>
#include <algorithm>
#include <functional>
#include <numeric>
#include <utility>
#include <sstream>
#include <iostream>
#include <iomanip>
#include <cstdio>
#include <cmath>
#include <cstdlib>
#include <ctime>
using namespace std;
const int INF = 1000000000;
const int MOD = INF + 7;
class PalindromicSubstringsDiv2 {
public:
int count(vector <string>, vector <string>);
};
string a;
bool check(int s,int e){
while(s < e){
if(a[s] != a[e]){
return false;
} else {
s++;e--;
}
}
return true;
}
int PalindromicSubstringsDiv2::count(vector <string> S1, vector <string> S2) {
a = "";
for(string x : S1){
a += x;
}
for(string x : S2){
a += x;
}
int n = a.size();
int ans = n;
for(int i = 0 ; i < n ; i++){
for(int len = n-i ; len >= 1; len--){
if(i + len >= n) continue;
if(check(i,i+len)){
cout << i << " " << i+len << endl;
cout << ans << endl;
if(len <= 2){
ans += 1;
} else {
ans += (len+1)/2;
}
cout << ans << endl;
break;
}
}
}
return ans;
}
double test0() {
string t0[] = {"a","a",""};
vector <string> p0(t0, t0+sizeof(t0)/sizeof(string));
string t1[] = {"a"};
vector <string> p1(t1, t1+sizeof(t1)/sizeof(string));
PalindromicSubstringsDiv2 * obj = new PalindromicSubstringsDiv2();
clock_t start = clock();
int my_answer = obj->count(p0, p1);
clock_t end = clock();
delete obj;
cout <<"Time: " <<(double)(end-start)/CLOCKS_PER_SEC <<" seconds" <<endl;
int p2 = 6;
cout <<"Desired answer: " <<endl;
cout <<"\t" << p2 <<endl;
cout <<"Your answer: " <<endl;
cout <<"\t" << my_answer <<endl;
if (p2 != my_answer) {
cout <<"DOESN'T MATCH!!!!" <<endl <<endl;
return -1;
}
else {
cout <<"Match :-)" <<endl <<endl;
return (double)(end-start)/CLOCKS_PER_SEC;
}
}
double test1() {
string t0[] = {"zaz"};
vector <string> p0(t0, t0+sizeof(t0)/sizeof(string));
vector <string> p1;
PalindromicSubstringsDiv2 * obj = new PalindromicSubstringsDiv2();
clock_t start = clock();
int my_answer = obj->count(p0, p1);
clock_t end = clock();
delete obj;
cout <<"Time: " <<(double)(end-start)/CLOCKS_PER_SEC <<" seconds" <<endl;
int p2 = 4;
cout <<"Desired answer: " <<endl;
cout <<"\t" << p2 <<endl;
cout <<"Your answer: " <<endl;
cout <<"\t" << my_answer <<endl;
if (p2 != my_answer) {
cout <<"DOESN'T MATCH!!!!" <<endl <<endl;
return -1;
}
else {
cout <<"Match :-)" <<endl <<endl;
return (double)(end-start)/CLOCKS_PER_SEC;
}
}
double test2() {
string t0[] = {"top"};
vector <string> p0(t0, t0+sizeof(t0)/sizeof(string));
string t1[] = {"coder"};
vector <string> p1(t1, t1+sizeof(t1)/sizeof(string));
PalindromicSubstringsDiv2 * obj = new PalindromicSubstringsDiv2();
clock_t start = clock();
int my_answer = obj->count(p0, p1);
clock_t end = clock();
delete obj;
cout <<"Time: " <<(double)(end-start)/CLOCKS_PER_SEC <<" seconds" <<endl;
int p2 = 8;
cout <<"Desired answer: " <<endl;
cout <<"\t" << p2 <<endl;
cout <<"Your answer: " <<endl;
cout <<"\t" << my_answer <<endl;
if (p2 != my_answer) {
cout <<"DOESN'T MATCH!!!!" <<endl <<endl;
return -1;
}
else {
cout <<"Match :-)" <<endl <<endl;
return (double)(end-start)/CLOCKS_PER_SEC;
}
}
double test3() {
vector <string> p0;
string t1[] = {"daata"};
vector <string> p1(t1, t1+sizeof(t1)/sizeof(string));
PalindromicSubstringsDiv2 * obj = new PalindromicSubstringsDiv2();
clock_t start = clock();
int my_answer = obj->count(p0, p1);
clock_t end = clock();
delete obj;
cout <<"Time: " <<(double)(end-start)/CLOCKS_PER_SEC <<" seconds" <<endl;
int p2 = 7;
cout <<"Desired answer: " <<endl;
cout <<"\t" << p2 <<endl;
cout <<"Your answer: " <<endl;
cout <<"\t" << my_answer <<endl;
if (p2 != my_answer) {
cout <<"DOESN'T MATCH!!!!" <<endl <<endl;
return -1;
}
else {
cout <<"Match :-)" <<endl <<endl;
return (double)(end-start)/CLOCKS_PER_SEC;
}
}
int main() {
int time;
bool errors = false;
time = test0();
if (time < 0)
errors = true;
time = test1();
if (time < 0)
errors = true;
time = test2();
if (time < 0)
errors = true;
time = test3();
if (time < 0)
errors = true;
if (!errors)
cout <<"You're a stud (at least on the example cases)!" <<endl;
else
cout <<"Some of the test cases had errors." <<endl;
}
//Powered by [KawigiEdit] 2.0!
|
Java | UTF-8 | 822 | 2.859375 | 3 | [] | no_license | package ru.danilov.st.utils;
import ru.danilov.st.timeseries.TimeSeries;
public final class TimeSeriesUtil {
private TimeSeriesUtil() {}
public static double avg(TimeSeries series) {
return sum(series) / series.size();
}
public static double avgRange(TimeSeries series, int start, int end) {
return sumRange(series, start, end) / (end - start);
}
public static double sum(TimeSeries series) {
double sum = 0;
for (int i = 0; i < series.size(); i++) {
sum += series.get(i).getValue();
}
return sum;
}
public static double sumRange(TimeSeries series, int start, int end) {
double sum = 0;
for (int i = start; i < end; i++) {
sum += series.get(i).getValue();
}
return sum;
}
}
|
Java | UTF-8 | 220 | 1.882813 | 2 | [] | no_license | package co.simplon.dao;
import java.util.List;
import co.simplon.model.Pays;
public interface PaysDAO {
List<Pays> lister();
void ajouter ( Pays pays );
void modifier(Pays pays);
void effacer(Pays pays);
}
|
Markdown | UTF-8 | 6,180 | 3.078125 | 3 | [] | no_license | # Time_Series_Forest_Fire
#### Introduction
For my global warming study I used wildfire data from the National Centers for Environmental Information (NCEI) to examine the number of fires and acres burned from the years 2000 – 2021 within the United States. We can evaluate the data on a macro level for a trend in wildfires. Discovering a trend can lead to better preparation as well as act as a form of benchmarking previous strategies, “ Economic losses attributed to wildfires in 2018 alone are almost equal to the collective losses from wildfires incurred over the past decade…” (Fawzy et al., 2020). Wildfires themselves can lead to other issues such as health concerns from the smoke inhalation as well as further environmental degradation of already environmentally sensitive areas, “wildfire threatens surface drinking water sources with eroded contaminants” (Gannon et al., 2020).
#### Time Series Application.
When evaluating the variables within our dataset we notice that there is a correlation between the spokes of acres and numbers of fires, viewable in Figure 2 below when using acres burned per fire as the base line we can see the spokes of acres burned matching with number of fires however at different scales. The acres burned contains the most variance out of all the variables so we will use that as our evaluation metric for our Auto Regressive Integrated Moving Average (ARIMA) time series analysis.


Our first ARIMA model (0,1,0) has an uneven distribution of residuals as well as a significant lag spike at 1 and another close one at 4 producing a p-value of 0.004 shown in Figure 3. Adjusting the p, d, and q of the ARIMA function we produced another time series model, ARIMA (1,2,1) using 5 lags producing a p-value of 0.035. Here we notice a more even distribution but there is still a significant spike at lag 4 shown in Figure 6. With the first model, ARIMA(0,1,0), we get a forecast that appears to capture most of the variance but is clearly heavily influenced by the major spike. However, in the second forecast which used ARIMA(1,2,1) shows a model that appears to take the spike into account with a slight spread increase of the deviation predicted around 2023 – 2024 but it also shows the decreasing trend show slightly in the trends but missed by all the other models. Due to this I believe this model was the better of the two model. To evaluate this model I compared it by benchmarking it against a ARIMA(0,0,0) model to check our summary. Comparing our chosen model we notice that the ARIMA(0,0,0) function fails to account for the spike, only taking into account the cyclic spikes as well as missing the trend within the dataset.






#### Conclusions
Using this dataset we ran dynamic regression and ARIMA model on the dataset to predict potential future fires impact. We noticed an overall downward trend across the country in wildfires however we can still expect spikes despite the trend. “…Centre for Research on the Epidemiology of Disasters (CRED)… CRED also provides data on disasters over the past decade, which shows even higher annual averages in almost all areas, except for wildfire cases” (Fawzy et al., 2020). I believe this is due to the interconnected nature of wildfires and climate change as each wildfire can directly worsen the climate leading to more wildfires, “… wildfires are a direct source of CO2 emissions. Although wildfires are part of the natural system, it is clear that human-induced emissions are directly interfering and amplifying the impact of natural system emissions” (Fawzy et al., 2020). This is a macro level evaluation on wildfires in the US and does not account for singular devastations such as in California where on a micro level the wildfires have increased in devastation and occurrence, “two largest contemporary wildfires, and two most destructive wildfires all occurred during 2017 and 2018” (Goss et al., 2020). These wildfires need to not just be prevented but also be contained when they happen contain the risks associated, “…improved fire containment could reduce wildfire risk to the water source by 13.0 to 55.3% depending on impact measure and post-fire rainfall” (Gannon et al., 2020). Overall the downward trend with spikes shows the harsh reality that we are making progress in fighting climate change, indicated in the downward trend, however the worsening of the climate has means we can predict the worsening of disasters, “Climate change can thus be viewed as a wildfire ‘threat multiplier’ amplifying natural and human risk factors that are already prevalent throughout California” (Goss et al., 2020).
#### References
Fawzy, S., Osman, A. I., Doran, J., & Rooney, D. W. (2020). Strategies for mitigation of climate change: a review. Environmental Chemistry Letters. https://doi.org/10.1007/s10311-020-01059-w
Gannon, B. M., Wei, Y., & Thompson, M. P. (2020). Mitigating Source Water Risks with Improved Wildfire Containment. Fire, 3(3), 45. https://doi.org/10.3390/fire3030045
Goss, M., Swain, D. L., Abatzoglou, J. T., Sarhadi, A., Kolden, C., Williams, A. P., & Diffenbaugh, N. S. (2020). Climate change is increasing the risk of extreme autumn wildfire conditions across California. Environmental Research Letters, 15(9). https://doi.org/10.1088/1748-9326/ab83a7
|
C++ | GB18030 | 995 | 3.296875 | 3 | [] | no_license | #pragma once
#include <iostream>
using namespace std;
#define CONVERT_FIGURES (3) // λ һλ\0;
#define CONVERT_HEX (36) // 0-9 A-Z 36;
#define MAX_CONVERT_DIGIT (1295) // (CONVERT_HEXƽһ);
class Convert
{
public:
Convert()
{
for (int iIndex = 0; iIndex < CONVERT_HEX; iIndex++)
{
if (iIndex < 10)
{
m_hexCustom[iIndex] = '0' + iIndex;
}
else
{
m_hexCustom[iIndex] = 'A' + (iIndex - 10);
}
}
}
~Convert()
{
}
// ʼԶ;
bool InitCustomArry(char arry[MAX_CONVERT_DIGIT][CONVERT_FIGURES])
{
for (int iIndex = 0; iIndex < MAX_CONVERT_DIGIT; iIndex++)
{
int iDivision = iIndex / CONVERT_HEX;
int iRemainder = iIndex % CONVERT_HEX;
arry[iIndex][0] = m_hexCustom[iDivision];
arry[iIndex][1] = m_hexCustom[iRemainder];
arry[iIndex][2] = '\0';
}
return true;
}
private:
char m_hexCustom[CONVERT_HEX];
};
|
Markdown | UTF-8 | 6,768 | 3.140625 | 3 | [] | no_license | 六六
“我记得在文也念小学二年级的时候,我先生在公司里接受验血,回来就很不高兴。他问文也的血型。我想,完了!结果真的不同。我是A型,文也是O型。而我先生在验血前一直以为自己是B型,因为他的两个兄弟都是B型。”
“结果他不是B型!”
“嗯,检查结果是AB型。我先生也知道A型和AB型不可能生出O型的小孩。”
“您也是当时才发现的吗?”
“是啊,不过,老实说我并不意外。后来仔细一想,其实我在怀孕时,就有预感孩子不是他的,但是却故意忽视这种感觉。我早就发现,文也长得一点也不像我先生。”
“后来您有没有把真相告诉梶川先生?”
“我当然说了,因为根本不能再瞒下去了。”
“所以他一怒之下就离家出走了?”
“他的确是为了这个原因离家的,不过却不是怪我。他从来就没骂过我,在听了我的告白之后,显得异常冷静,即使喝醉酒也没有对我翻过旧帐,对文也的态度也和以前一样,只是变得不太喜欢讲话,总是望着窗外出神,好像在想甚么。在我说出真相的两个礼拜以后,他才离家出走,当时,他只带走一些随身衣物和文也的相本而已。”
“没有留下只字词组?”
“有啊!”根岸典子从皮包里取出一个白色信封,放在桌上。
“我可以看吗?”
可以啊!她答道。
平介拿起信封,里面有一张便条纸,打开一看,上面有一行潦草的字。“对不起!我没办法继续尽父亲的责任了。”
“我看了就忍不住哭了。”她说道。
“在离家出走前的那两个礼拜,他都没有骂过我,只是自己在考虑能不能继续当文也的父亲。我现在一想起来就好心痛,对他真的很抱歉。我很后悔瞒了他这么多年。”
平介点点头,并想象这些事情如果发生在自己身上,会怎么处理?要是直子对自己说出这种事,一定会臭骂她一顿,说不定还会出手打她呢!
“等一下,也就是说,梶川先生明明知道文也不是自己的孩子,却还是替他付学费……”
“是的。”根岸典子用手帕轻按眼角。“所以,我才会说您的推测与事实正好相反,需要赎罪的应该是我,但是他却不计前嫌。”
“为甚么?因为他还爱着您?”
她听了平介的话,轻轻摇摇头。
“当时,他已经另结新欢了,而且还说很爱老婆。”
“那……为甚么……”
“他是这么说的:他说,文也需要父亲,在母亲困苦的时候,父亲可以出面帮忙。但是,我却说:‘你又不是文也的亲生父亲,为甚么要这么做?’他却反问我,文也觉得怎样才幸福?”
“怎样?”
“承认我不是他的亲生父亲呢?还是把我当作他的父亲?我想了很久,才回答他:‘幸好你是他父亲。’然后他就说:‘是啊,我也是这么想,所以才想继续做那孩子的父亲。当他遇到困难时,我就以父亲的身分帮助他。当我知道我和文也没有血缘关系时,我只是一味地考虑能不能尽到为人父的责任,却没有想过让心爱的人幸福。我这么喜欢文也,选择离开了他,我真傻……’他说完了这些话,就在电话里哭了起来。”
根岸典子挺直了背,正襟危坐地叙述这件事。她的声音虽然有些颤抖,却没有哭出来。从她的表情就可以得知她想把整件事情解释清楚。
平介觉得呼吸变得有点不顺,心跳越来越快,胸口有些发疼。
“当我得知出了意外,本想立刻赶过去的,至少也要为他上一炷香。直到看了新闻报导,才知道肇事原因是他的疏忽,我忍不住想大叫,不是他的错,他是为了我们母子才硬撑着工作啊!但是,在文也面前我却装作毫不在乎。我受了他的照顾,却又假装甚么都不知道。”
根岸典子叹了一口气,喝了一口凉掉的奶茶。“但是,这次从文也那里听到关于杉田先生的事,让我觉得不应该再隐瞒下去了。就在三天前,我把所有的事都告诉了文也。”
“他有没有觉得打击很大?”
“多少有一点。”根岸典子笑道:“不过我很庆幸告诉了他。”
“是吗?”
“我认为您也该知道整件事的始末,所以才来拜访,也许您会觉得很无聊。”
“不,我很高兴知道事情的真相。”
“听您这么说,我这一趟总算值回票价了。”她把那个信封收进皮包里。
“其实,我还有一件事要拜托您。”
“甚么事?”
“听我儿子说,他的老婆已经过世了。”
“啊……”她指的是梶川征子吧!
“是啊,已经好几年了。”
“他们好像还有一个女儿。”
“嗯,叫逸美。”
“那……您知不知道怎么联络那孩子?我想见她一面,把她父亲的事告诉她,然后再尽力补偿她。”根岸典子边说边流露出诚挚的眼神。
“应该知道吧!她曾经寄给我贺年卡,等我确认之后再通知您。”
“对不起,那就麻烦您了!”他拿出名片放在平接口前,上面印着“熊吉拉面”的字样。
她收好皮包,忽然想起甚么似的,转头望着玻璃窗外的庭园。
“啊,真的下雪了,果然被我料中了。”平介也循着她的视线望过去,雪花就像白色花瓣般,无声无息地飘落下来。
§ 38
平介离开饭店之后,在通往东京车站的人行道走着。雪缓缓地飘落着。
根岸典子的话在他脑海中萦绕着,彷佛听到了未曾谋面的梶川幸广的声音:“让自己心爱的人幸福……”
我和你不一样,梶川先生!如果我的处境和你相同,或许我也能做得这么潇洒。但是现在的我……
又是一阵喘不过气来的感觉,彷佛甚么东西从胸口蹦出来。平介觉得很累,于是蹲了下来,脖子上的围巾掉在地上。
雪花在水泥地上融化,看样子应该不会积雪。片片飘落的雪,让平介联想到天真的小孩子。
“你没事吧!”一名年轻男子问道。
平介并没有看向对方,只是举起一只手说道:“嗯,我没事!不好意思。”
他站起来,立刻将围巾重新围好。问候他的人是一个矮小的上班族男子,身穿一件灰褐色外套。
“你没事吧!”男子又问了一次。
“嗯,我真的没事了,谢谢您!”
|
SQL | UTF-8 | 1,843 | 3.859375 | 4 | [] | no_license | CREATE DATABASE db_farmacia;
USE db_farmacia;
CREATE TABLE tb_categoria (
ID INT NOT NULL AUTO_INCREMENT,
medicamentos VARCHAR (255) NOT NULL,
genéricos VARCHAR(255) NOT NULL,
saúde VARCHAR (255) NOT NULL,
PRIMARY KEY (ID)
);
CREATE TABLE tb_produto(
id_produto INT AUTO_INCREMENT PRIMARY KEY,
preco DECIMAL (4,2),
quantidade INT (100),
tipo VARCHAR (50),
código INT (100),
descricao VARCHAR (255),
fk_ID INT,
FOREIGN KEY (fk_ID) REFERENCES tb_categoria(ID)
);
INSERT INTO tb_categoria (medicamentos, genéricos, saúde)
VALUES
('ALERGIAS', 'DOR', 'ALIMENTOS DIET'),
('DIABETES', 'MICOSES', 'DIAGNÓSTICO'),
('COLESTEROL', 'DOENÇA DOS OSSOS', 'HIGIENTE ÍNTIMA'),
('OLHOS', 'GRIPE', 'ACESSÓRIOS PARA SAÚDE'),
('PELE', 'INFECÇÕES', 'ALIMENTOS');
INSERT INTO tb_produto (preco, quantidade, tipo, código, descricao)
VALUES
(4.99, '10', 'COMPRIMIDO', '50088', 'ANALGÉSICO DORFLEX'),
(5.37, '30', 'COMPRIMIDO', '798322', 'METFORMINA 850MG - PRATI DONADUZZI - GENÉRICO'),
(9.56, '100', 'LÍQUIDO', '801221', 'ADOÇANTE ZERO CAL SUCRALOSE 100ML'),
(6.99, '30', 'COMPRIMIDO', '6304', 'SINVASTATINA 20MG - SANDOZ - GENÉRICO'),
(4.99, '30', 'CÁPSULAS', '797183', 'ISOTRETINOÍNA 20MG 30 CÁPSULAS (C2) - BAUSCH - GENÉRICO'),
(20.53, '15', 'LÍQUIDO', '9969', 'LACRIMA PLUS COLÍRIO 15ML'),
(28.49, '30', 'COMPRIMIDO', '800724', 'MONTELUCASTE 10MG - BIOSINTÉTICA - GENÉRICO'),
(99.77, '30', 'COMPRIMIDO', '797774', 'TRAYENTA 5MG');
SELECT descricao, preco FROM tb_produto WHERE preco > 50.00;
SELECT preco, descricao FROM tb_produto WHERE preco BETWEEN 3.00 AND 60.00;
SELECT descricao FROM tb_produto WHERE descricao LIKE "%B%";
SELECT * FROM tb_categoria INNER JOIN tb_produto ON tb_produto.id_produto = tb_categoria.ID;
SELECT tipo, descricao FROM tb_produto WHERE tipo = 'COMPRIMIDO'; |
JavaScript | GB18030 | 4,473 | 2.59375 | 3 | [] | no_license | var status = -1;
var sel = -1;
function action(mode, type, selection) {
if (mode == 1) {
status++;
} else {
if (status == 0) {
cm.dispose();
}
status--;
}
if (status == 0) {
var selStr = "Dzɿ #bŵ#k\r\n";
if (cm.getPlayer().getProfessionLevel(92010000) > 0) {
selStr += "#L2##b#eɿ#nȼ#l\r\n#L3#ɿʼ#k#l\r\n#L4##b#t4011010##k#l";
} else {
selStr += "#L0##bȡй#eɿ#n˵#l\r\n#L1#ѧϰ#eɿ#n#k#l";
}
cm.sendSimple(selStr);
} else if (status == 1) {
sel = selection;
if (sel == 0) {
status = -1;
cm.sendNext("ɿʮָ֮ĹߣɼͼϵĿʯļܡɼĿʯ#p9031007#۵ұװƷIJϡ");
} else if (sel == 1) {
if (cm.getPlayer().getProfessionLevel(92000000) > 0) {
cm.sendOk("Ѿѧҩҽѧϰ#bװ#k#bƷ#kô");
cm.dispose();
return;
}
if (cm.getPlayerStat("LVL") < 30) {
cm.sendOk("Сë㻹ǿѧϰרҵ#bٱﵽ302תϣ3תϣӰ˫2ת+#kѧϰרҵȴﵽ֮Ұɡ");
} else if (cm.getProfessions() >= 2) {
cm.sendNext("ţѾѧϰ2רҵѧϰĻͱȷһּ");
} else if (cm.getPlayer().getProfessionLevel(92010000) > 0) {
cm.sendNext("ѾѧЩ#eɿ#nѵѧ");
} else {
cm.sendOk("ϲɹѧϰ#eɿ#n");
cm.teachSkill(92010000, 0x1000000, 0);
if (cm.canHold(1512000, 1)) {
cm.gainItem(1512000, 1);
}
}
cm.dispose();
} else if (sel == 2) {
cm.sendNext("Ȼû֮ҡ");
cm.dispose();
} else if (sel == 3) {
if (cm.getPlayer().getProfessionLevel(92020000) > 0) {
cm.sendOk("ѧϰװʼʼĻ͵ȶװƷгʼ");
cm.dispose();
} else if (cm.getPlayer().getProfessionLevel(92030000) > 0) {
cm.sendOk("ѧϰƷʼʼĻ͵ȶװƷгʼ");
cm.dispose();
} else if (cm.getPlayer().getProfessionLevel(92010000) > 0) {
status = 3;
cm.sendYesNo("#eɿ#n֮ǰ۵ĵȼȡŬͽǮӰҪʼ");
}
} else if (sel == 4) {
if (!cm.haveItem(4011010, 100)) {
cm.sendOk("#b#t4011010#100#kԽ#i2028067:##b#t2028067#1#kȥѼһЩ#t4011010#");
} else if (!cm.canHold(2028067, 1)) {
cm.sendOk("ռ䲻㡣");
} else {
cm.sendOk("һɹ.");
cm.gainItem(2028067, 1);
cm.gainItem(4011010, -100);
}
cm.dispose();
}
} else if (status == 2) {
cm.sendOk("ءõģϸһ£Ȼҡ");
cm.dispose();
} else if (status == 4) {
if (cm.getPlayer().getProfessionLevel(92010000) > 0) {
cm.sendOk("ɿѾʼѧϰҡ");
cm.teachSkill(92010000, 0, 0);
if (cm.isQuestActive(3197)) {
cm.forfeitQuest(3197);
}
if (cm.isQuestActive(3198)) {
cm.forfeitQuest(3198);
}
} else {
cm.sendNext("ûѧϰ#eɿ#nʼʧܡ");
}
cm.dispose();
}
} |
C++ | UTF-8 | 874 | 2.828125 | 3 | [] | no_license | /*
Viz:
Takes in a source text, and produces output for graphviz processing.
Example Usage:
viz source.txt | dot -Tpng > source-cfg.png
*/
#include <iostream>
#include "program_knowledge_base/pkb_manager.h"
#include "simple_parser/interface.h"
using namespace std;
int main(int argc, char** argv) {
if (argc != 2) {
std::cout << "Received " << argc - 1 << " arguments, expecting 1.";
exit(1);
}
std::string source_path = std::string(argv[1]);
AST ast = Simple::SimpleInterface::getAstFromFile(source_path);
PKB::PKBManager* pkb = new PKB::PKBManager(ast);
auto adj_list = pkb->getCFG();
std::cout << "digraph cfg {" << std::endl;
for (const auto& node : adj_list) {
for (const auto& outward_node : node.second) {
std::cout << node.first << " -> " << outward_node << std::endl;
}
}
std::cout << "}";
return 0;
}
|
Python | UTF-8 | 283 | 2.78125 | 3 | [] | no_license | from typing import List
def parse(txt_block: str)->List[tuple]:
# there's probably some clever regex that we can do here... but fuck it
blocks = txt_block.strip().rsplit('>')[1:]
return [(x[0], x[1].replace('\n','')) for x in [block.split('\n', 1) for block in blocks]] |
C++ | UTF-8 | 2,057 | 2.9375 | 3 | [
"MIT"
] | permissive | #include "license.txt"
#include <time.h>
#ifdef _WIN32
#define CLOCK clock
#else
#include <sys/time.h> // for wall-clock timer (as opposed to clock cycle timer)
/** Linux keeps track of time this way. clock() returns CPU cycles, not time. */
long long clock_NIX()
{
static timeval g_startTime = {0,0};
if(!g_startTime.tv_sec)
gettimeofday(&g_startTime, NULL); // start the timer
timeval now;
__time_t seconds, useconds, ms;
gettimeofday(&now, NULL);
seconds = now.tv_sec - g_startTime.tv_sec;
useconds = now.tv_usec - g_startTime.tv_usec;
ms = seconds*1000 + useconds/1000;
return ms;
}
#define CLOCK clock_NIX
#endif
/**
* @return relatively random bit sequence (on a fast CPU). Use sparingly!
* Expected runtime is about (a_numBits*2)+1 milliseconds (a little less),
* during which 100% of CPU is used
*/
int randomIntTRNG(int a_numBits)
{
long instructionsTillOneMS, iter;
int index = 0, result = 0;
time_t now = CLOCK();
while(CLOCK() == now); // start timing at the turn of the millisecond
for(int i = 0; i < a_numBits; ++i)
{
for(now = CLOCK(), instructionsTillOneMS = 0; CLOCK() == now;
++instructionsTillOneMS);
for(now = CLOCK(), iter = 0; CLOCK() == now; ++iter);
result |= (int)(iter > instructionsTillOneMS) << index++;
}
return result;
}
static unsigned int nSeed = 5223;
void randomSeed(int a_seed)
{
nSeed = a_seed;
}
static int random()
{
// Take the current seed and generate a new value
// from it. Due to our use of large constants and
// overflow, it would be very hard for someone to
// predict what the next number is going to be from
// the previous one.
nSeed = (8253729 * nSeed + 2396403);
// return a value between 0 and 2.14 billion
return nSeed & 0x7fffffff;
}
int randomInt()
{
return random();
}
float randomFloat()
{
int i = random() & 0xffffff;
return i / (float)(0x1000000);
}
float randomFloat(float min, float max)
{
float delta = max-min;
float number = randomFloat()*delta;
number += min;
return number;
}
|
C# | UTF-8 | 1,606 | 2.703125 | 3 | [
"BSD-3-Clause"
] | permissive | using System.Collections.Generic;
using System.Linq;
namespace mesoBoard.Common
{
public enum PostingPermissionValue
{
None = 0,
Reply,
Thread,
Sticky,
Announcments
}
public class PostingPermission : PermissionBase<PostingPermissionValue>
{
public PostingPermission(PostingPermissionValue value, string name) : base(value, name) { }
}
public class PostingPermissions : PermissionCollection<PostingPermissionValue, PostingPermission>
{
public static PostingPermission None = new PostingPermission(PostingPermissionValue.None, "None");
public static PostingPermission Reply = new PostingPermission(PostingPermissionValue.Reply, "Reply");
public static PostingPermission Thread = new PostingPermission(PostingPermissionValue.Thread, "Thread");
public static PostingPermission Sticky = new PostingPermission(PostingPermissionValue.Sticky, "Sticky");
public static PostingPermission Announcments = new PostingPermission(PostingPermissionValue.Announcments, "Announcments");
public new static IEnumerable<PostingPermission> List
{
get
{
yield return None;
yield return Reply;
yield return Thread;
yield return Sticky;
yield return Announcments;
}
}
public static PermissionCollection<PostingPermissionValue, PostingPermission> Class =
new PermissionCollection<PostingPermissionValue, PostingPermission>(List.ToList());
}
} |
Java | UTF-8 | 5,684 | 1.953125 | 2 | [] | no_license | package com.yunos.tvtaobao.payment.alipay.task;
import android.content.Context;
import android.os.AsyncTask;
import android.text.TextUtils;
import com.ali.auth.third.core.MemberSDK;
import com.ali.auth.third.core.callback.LoginCallback;
import com.ali.auth.third.core.model.Session;
import com.ali.auth.third.offline.login.LoginService;
import com.yunos.tvtaobao.payment.alipay.AlipayTaskListener;
import com.yunos.tvtaobao.payment.alipay.request.AlipaySignQueryRequest;
import com.yunos.tvtaobao.payment.alipay.request.AlipaySignRequest;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;
import mtopsdk.mtop.domain.MtopRequest;
import mtopsdk.mtop.domain.MtopResponse;
import mtopsdk.mtop.intf.Mtop;
/**
* Created by rca on 12/12/2017.
*/
public class AlipayAuthTask extends AsyncTask {
public static final int FAIL_RETRY_DELAY_MILLIS = 5000;
public static final int QUERY_DELAY_MILLIS = 3000;
public static final int EXPIRATION_MILLIS = 5 * 60 * 1000;
public static class AlipayAuthTaskResult {
private int step;
private int status;
private Object object;
AlipayAuthTaskResult(int step, int status, Object object) {
this.step = step;
this.status = status;
this.object = object;
}
public int getStep() {
return step;
}
public int getStatus() {
return status;
}
public Object getObject() {
return object;
}
}
public interface AlipayAuthTaskListener {
void onReceivedAlipayAuthStateNotify(AlipayAuthTaskResult result);
}
private AlipayAuthTaskListener mListener;
public void setListener(AlipayAuthTaskListener listener) {
this.mListener = listener;
}
public static final int STEP_GEN = 0, STEP_QUERY = 1, STEP_LOGIN = 2;
public static final int STATUS_SUCCESS = 0, STATUS_FAIL = 1, STATUS_EXPIRE = 2;
private Context mContext;
private boolean finish = false;
public AlipayAuthTask(Context context) {
super();
mContext = context;
}
private MtopRequest currentRequest;
private int step = STEP_GEN;
private String loginToken = null;
private String alipayUserId = null;
private long timeStamp = 0L;
public void setAlipayUserId(String alipayUserId) {
this.alipayUserId = alipayUserId;
}
@Override
protected Object doInBackground(Object[] objects) {
while (!finish && !isCancelled()) {//整个业务循环 TODO isCancelled方法判断不足以屏蔽回调,cancel之后循环体内请求完成仍然会回调,需要解决
if (isExpire())
step = STEP_GEN;
if (step == STEP_GEN) {
currentRequest = new AlipaySignRequest(alipayUserId);
MtopResponse response = Mtop.instance(mContext).build(currentRequest, null).useWua().setConnectionTimeoutMilliSecond(5000).setSocketTimeoutMilliSecond(3000).syncRequest();
if (!response.isApiSuccess()) {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
continue;
}
JSONObject data = response.getDataJsonObject();
AlipaySignResult result = AlipaySignResult.resolveFromJson(data);
publishProgress(new AlipayAuthTaskResult(STEP_GEN, STATUS_SUCCESS, result.qrCode));
timeStamp = System.currentTimeMillis();
step = STEP_QUERY;
} else if (step == STEP_QUERY) {
if (doAuthQuery())
break;
}
}
return null;
}
private boolean isExpire() {
long time = System.currentTimeMillis();
return time - timeStamp > EXPIRATION_MILLIS;
}
/**
* send AuthQuery request and handle response
*
* @return true if query is success & auth is complete , false else
*/
private boolean doAuthQuery() {
currentRequest = new AlipaySignQueryRequest();
MtopResponse response = Mtop.instance(mContext).build(currentRequest, null).useWua().setConnectionTimeoutMilliSecond(5000).setSocketTimeoutMilliSecond(3000).syncRequest();
if (!response.isApiSuccess()) {
try {
Thread.sleep(FAIL_RETRY_DELAY_MILLIS);
return false;
} catch (InterruptedException e) {
e.printStackTrace();
}
} else {
//TODO
AlipayQueryResult result = AlipayQueryResult.resolveFromJson(response.getDataJsonObject());
if (!TextUtils.isEmpty(result.token) && !TextUtils.isEmpty(result.agreementNo)) {
publishProgress(new AlipayAuthTaskResult(STEP_QUERY, STATUS_SUCCESS, null));
loginToken = result.token;
return true;
}
try {
Thread.sleep(QUERY_DELAY_MILLIS);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return false;
}
@Override
protected void onProgressUpdate(Object[] values) {
super.onProgressUpdate(values);
if (values.length == 1) {
AlipayAuthTaskResult result = (AlipayAuthTaskResult) values[0];
notifyResult(result);
}
}
private void notifyResult(AlipayAuthTaskResult result) {
if (mListener != null) {
mListener.onReceivedAlipayAuthStateNotify(result);
}
}
}
|
C++ | UTF-8 | 1,548 | 3.046875 | 3 | [] | no_license | #include "DynamicPositionComponent.h"
#include <iostream>
DynamicPositionComponent::DynamicPositionComponent(std::shared_ptr<Object> owner, sf::Vector2f position, Gravity& gravity,
sf::Vector2f speed, sf::Vector2f currentSpeed) : PositionComponent(owner, position), gravity(gravity), currentSpeed(currentSpeed),
speed(speed), inAir(true), startedToFall(false) {
std::cout << "here\n";
}
void DynamicPositionComponent::update(float timeElapsed)
{
if (!inAir && startedToFall)
{
//std::cout << "Started to fall\n";
gravity.addObject(owner);
inAir = true;
}
position.x += timeElapsed * currentSpeed.x;
position.y += timeElapsed * currentSpeed.y;
currentSpeed.x = 0;
startedToFall = true;
}
void DynamicPositionComponent::move(sf::Vector2f toMove)
{
currentSpeed += toMove;
}
void DynamicPositionComponent::setSpeed(sf::Vector2f speed)
{
this->speed = speed;
}
void DynamicPositionComponent::setCurrentSpeedX(float x)
{
currentSpeed.x = x;
}
void DynamicPositionComponent::setCurrentSpeedY(float y)
{
currentSpeed.y = y;
}
void DynamicPositionComponent::setCurrentSpeed(sf::Vector2f& speed)
{
this->currentSpeed = speed;
}
void DynamicPositionComponent::moveX(float distance)
{
position.x += distance;
}
void DynamicPositionComponent::moveY(float distance)
{
position.y += distance;
}
void DynamicPositionComponent::moveX(int distance)
{
position.x += distance;
}
void DynamicPositionComponent::moveY(int distance)
{
position.y += distance;
}
void DynamicPositionComponent::setInAir(bool InAir)
{
inAir = InAir;
}
|
Python | UTF-8 | 1,101 | 2.765625 | 3 | [] | no_license | from datetime import datetime
from spending_app.domain.incoming import Incoming
def test_incoming_init():
incoming = Incoming(id=81, user_id=9, date=datetime(2018, 4, 20), sum=67, text='work')
assert incoming.id == 81
assert incoming.user_id == 9
assert incoming.date == '2018-04-20'
assert incoming.sum == 67
assert incoming.text == 'work'
def test_incoming_from_dict():
incoming = Incoming.from_dict(
{
'id': 81,
'user_id': 9,
'date': datetime(2018, 4, 20),
'sum': 67,
'text': 'work'
}
)
assert incoming.id == 81
assert incoming.user_id == 9
assert incoming.date == '2018-04-20'
assert incoming.sum == 67
assert incoming.text == 'work'
def test_incoming_to_dict():
incoming = Incoming(id=81, user_id=9, date=datetime(2018, 4, 20), sum=67, text='work')
adict = incoming.to_dict()
expected_dict = {
'id': 81,
'user_id': 9,
'date': '2018-04-20',
'sum': 67,
'text': 'work'
}
assert adict == expected_dict
|
Java | UTF-8 | 6,270 | 2.265625 | 2 | [
"Apache-2.0"
] | permissive | package io.piano.android.api.publisher.model;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
public class SubscriptionSummaryModelDefinition {
private String date = null;
private String newSubscriptionAmount = null;
private String newSubscriptionTpFeeAmount = null;
private Integer newSubscriptionCount = null;
private Integer newTrialSubscriptionCount = null;
private Integer subscriptionCancelledCount = null;
private Integer subscriptionFailedOrExpiredCount = null;
private String subscriptionRefundedAmount = null;
private String subscriptionRefundedTpFeeAmount = null;
private Integer subscriptionRefundedCount = null;
private String subscriptionRenewedAmount = null;
private String subscriptionRenewedTpFeeAmount = null;
private Integer subscriptionRenewedCount = null;
/**
* Date
**/
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
/**
* New subscription amount
**/
public String getNewSubscriptionAmount() {
return newSubscriptionAmount;
}
public void setNewSubscriptionAmount(String newSubscriptionAmount) {
this.newSubscriptionAmount = newSubscriptionAmount;
}
/**
* New subscription TP fee amount
**/
public String getNewSubscriptionTpFeeAmount() {
return newSubscriptionTpFeeAmount;
}
public void setNewSubscriptionTpFeeAmount(String newSubscriptionTpFeeAmount) {
this.newSubscriptionTpFeeAmount = newSubscriptionTpFeeAmount;
}
/**
* New subscription count
**/
public Integer getNewSubscriptionCount() {
return newSubscriptionCount;
}
public void setNewSubscriptionCount(Integer newSubscriptionCount) {
this.newSubscriptionCount = newSubscriptionCount;
}
/**
* New trial subscription count
**/
public Integer getNewTrialSubscriptionCount() {
return newTrialSubscriptionCount;
}
public void setNewTrialSubscriptionCount(Integer newTrialSubscriptionCount) {
this.newTrialSubscriptionCount = newTrialSubscriptionCount;
}
/**
* Subscription cancelled count
**/
public Integer getSubscriptionCancelledCount() {
return subscriptionCancelledCount;
}
public void setSubscriptionCancelledCount(Integer subscriptionCancelledCount) {
this.subscriptionCancelledCount = subscriptionCancelledCount;
}
/**
* Subscription failed or expired count
**/
public Integer getSubscriptionFailedOrExpiredCount() {
return subscriptionFailedOrExpiredCount;
}
public void setSubscriptionFailedOrExpiredCount(Integer subscriptionFailedOrExpiredCount) {
this.subscriptionFailedOrExpiredCount = subscriptionFailedOrExpiredCount;
}
/**
* Subscription refunded amount
**/
public String getSubscriptionRefundedAmount() {
return subscriptionRefundedAmount;
}
public void setSubscriptionRefundedAmount(String subscriptionRefundedAmount) {
this.subscriptionRefundedAmount = subscriptionRefundedAmount;
}
/**
* Subscription refunded tp fee amount
**/
public String getSubscriptionRefundedTpFeeAmount() {
return subscriptionRefundedTpFeeAmount;
}
public void setSubscriptionRefundedTpFeeAmount(String subscriptionRefundedTpFeeAmount) {
this.subscriptionRefundedTpFeeAmount = subscriptionRefundedTpFeeAmount;
}
/**
* Subscription refunded count
**/
public Integer getSubscriptionRefundedCount() {
return subscriptionRefundedCount;
}
public void setSubscriptionRefundedCount(Integer subscriptionRefundedCount) {
this.subscriptionRefundedCount = subscriptionRefundedCount;
}
/**
* Subscription renewed amount
**/
public String getSubscriptionRenewedAmount() {
return subscriptionRenewedAmount;
}
public void setSubscriptionRenewedAmount(String subscriptionRenewedAmount) {
this.subscriptionRenewedAmount = subscriptionRenewedAmount;
}
/**
* Subscription renewed tp fee amount
**/
public String getSubscriptionRenewedTpFeeAmount() {
return subscriptionRenewedTpFeeAmount;
}
public void setSubscriptionRenewedTpFeeAmount(String subscriptionRenewedTpFeeAmount) {
this.subscriptionRenewedTpFeeAmount = subscriptionRenewedTpFeeAmount;
}
/**
* Subscription renewed count
**/
public Integer getSubscriptionRenewedCount() {
return subscriptionRenewedCount;
}
public void setSubscriptionRenewedCount(Integer subscriptionRenewedCount) {
this.subscriptionRenewedCount = subscriptionRenewedCount;
}
public static SubscriptionSummaryModelDefinition fromJson(JSONObject json) throws JSONException {
SubscriptionSummaryModelDefinition subscriptionSummaryModelDefinition = new SubscriptionSummaryModelDefinition();
subscriptionSummaryModelDefinition.date = json.optString("date");
subscriptionSummaryModelDefinition.newSubscriptionAmount = json.optString("new_subscription_amount");
subscriptionSummaryModelDefinition.newSubscriptionTpFeeAmount = json.optString("new_subscription_tp_fee_amount");
subscriptionSummaryModelDefinition.newSubscriptionCount = json.optInt("new_subscription_count");
subscriptionSummaryModelDefinition.newTrialSubscriptionCount = json.optInt("new_trial_subscription_count");
subscriptionSummaryModelDefinition.subscriptionCancelledCount = json.optInt("subscription_cancelled_count");
subscriptionSummaryModelDefinition.subscriptionFailedOrExpiredCount = json.optInt("subscription_failed_or_expired_count");
subscriptionSummaryModelDefinition.subscriptionRefundedAmount = json.optString("subscription_refunded_amount");
subscriptionSummaryModelDefinition.subscriptionRefundedTpFeeAmount = json.optString("subscription_refunded_tp_fee_amount");
subscriptionSummaryModelDefinition.subscriptionRefundedCount = json.optInt("subscription_refunded_count");
subscriptionSummaryModelDefinition.subscriptionRenewedAmount = json.optString("subscription_renewed_amount");
subscriptionSummaryModelDefinition.subscriptionRenewedTpFeeAmount = json.optString("subscription_renewed_tp_fee_amount");
subscriptionSummaryModelDefinition.subscriptionRenewedCount = json.optInt("subscription_renewed_count");
return subscriptionSummaryModelDefinition;
}
}
|
Python | UTF-8 | 2,000 | 3.25 | 3 | [] | no_license | max = 20
import random
class Cola():
def __init__(self):
self.datos = []
for i in range(0, max):
self.datos.append(None)
self.frente = 0
self.final = -1
self.tamanio = 0
def arribo(cola, dato):
cola.final += 1
if cola.final == max:
cola.final = 0
cola.datos[cola.final] = dato
cola.tamanio += 1
def atencion(cola):
aux = cola.datos[cola.frente]
cola.frente += 1
cola.tamanio -= 1
if cola.frente == max:
cola.frente = 0
return aux
def cola_vacia(cola):
return cola.tamanio == 0
def cola_llena(cola):
return cola.tamanio == max
def tamanioc(cola):
return cola.tamanio
def barridoc(cola):
caux = Cola()
while not cola_vacia(cola):
aux = atencion(cola)
print(aux)
arribo(caux, aux)
while not cola_vacia(caux):
aux = atencion(caux)
arribo(cola, aux)
def mover_al_final(cola):
aux = atencion(cola)
arribo(cola, aux)
def cargaAutoStr(cola):
abc = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
while (not cola_llena(cola)):
arribo(cola, random.choice(abc))
def cargautomatica1(cola):
while not cola_llena(cola):
dato = random.randint(0, 20)
arribo(cola, dato)
def cargaAutomEnteros(cola):
while not cola_llena(cola):
dato = random.randint(-50, 50)
arribo(cola, dato)
def cargacaract(cola):
caract = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ,.;/*-+=%#!?"
while not cola_llena(cola):
arribo(cola, random.randint(0, 20))
arribo(cola, random.choice(caract))
def primo(n):
pri = True
if n < 2:
return True
elif n == 2:
return True
else:
i = 2
while (i < n) and pri:
if (n % i == 0):
pri = False
i += 1
return pri
|
JavaScript | UTF-8 | 2,901 | 2.609375 | 3 | [] | no_license | const jwt = require('jsonwebtoken');
const usersModel = require('../components/users/users.model');
// Funcion que valida la existencia de un token por usuario
/*let verifyToken = (req, res, next) => {
if (!req.headers.authorization) return res.status(401).json({ message: "No esta autorizado para ver esto" });
let token = req.headers.authorization.split(' ')[1];
if (token === 'null') return res.status(401).json({ message: "No esta autorizado para ver esto" });
let payload = jwt.verify(token, 'urocalskey');
req.user_email = payload._id;
next();
}*/
// Funcion que valida la existencia de un token por usuario
verificarToken = (req, res, next) => {
let token = req.headers["x-access-token"];
if (!token) return res.status(403).send({ message: "No token provided!" });
jwt.verify(token, process.env.SECRET, (err, decoded) => {
if (err) return res.status(401).send({ message: "Unauthorized!" });
req.userId = decoded.id;
next();
});
};
// Verificar si el usuario es administrador
isAdmin = (req, res, next) => {
console.log("Dentro de isAdmin: " + req.body);
usersModel.getUserByPk(req.id).then(user => {
if (user.usutipo === "administrador") {
next();
return;
}
res.status(403).send({ message: "Require Admin Role!" });
return;
});
/*User.findByPk(req.userId).then(user => {
user.getRoles().then(roles => {
for (let i = 0; i < roles.length; i++) {
if (roles[i].name === "admin") {
next();
return;
}
}
res.status(403).send({
message: "Require Admin Role!"
});
return;
});
});*/
};//----
/*
isModerator = (req, res, next) => {
User.findByPk(req.userId).then(user => {
user.getRoles().then(roles => {
for (let i = 0; i < roles.length; i++) {
if (roles[i].name === "moderator") {
next();
return;
}
}
res.status(403).send({
message: "Require Moderator Role!"
});
});
});
};
isModeratorOrAdmin = (req, res, next) => {
User.findByPk(req.userId).then(user => {
user.getRoles().then(roles => {
for (let i = 0; i < roles.length; i++) {
if (roles[i].name === "moderator") {
next();
return;
}
if (roles[i].name === "admin") {
next();
return;
}
}
res.status(403).send({
message: "Require Moderator or Admin Role!"
});
});
});
};*/
const authJwt = { verificarToken, isAdmin };
module.exports = authJwt; |
Markdown | UTF-8 | 1,398 | 2.578125 | 3 | [
"MIT"
] | permissive | # Minimizing Bundle Size
For convenience, rrtr exposes its full API on the top-level `rrtr` import. However, this causes the entire rrtr library and its dependencies to be included in client bundles that include code that makes any imports from the top-level CommonJS bundle.
There are two options for minimizing client bundle size by excluding unused modules.
## Import from `rrtr/lib`
Bindings exported from `rrtr` are also available in `rrtr/lib`. When using CommonJS models, you can import directly from `rrtr/lib` to avoid pulling in unused modules.
Assuming you are transpiling ES2015 modules into CommonJS modules, instead of
```js
import { Link, Route, Router } from 'rrtr'
```
use
```js
import Link from 'rrtr/lib/Link'
import Route from 'rrtr/lib/Route'
import Router from 'rrtr/lib/Router'
```
The public API available in this manner is defined as the set of imports available from the top-level `rrtr` module. Anything not available through the top-level `rrtr` module is a private API, and is subject to change without notice.
## Use a Bundler with ES2015 Module Support
React Router offers a ES2015 module build under `es/` and defines a `jsnext:main` entry point. If you are using a bundler that supports ES2015 modules and tree-shaking such as webpack 2 or Rollup, you can directly import from `rrtr`, as long as you are correctly resolving to the ES2015 module build.
|
Java | UTF-8 | 147 | 1.914063 | 2 | [] | no_license | package org.sma.balls;
public class TestBalls {
public static void main(String[] args) {
Balls b = new Balls(10);
System.out.println(b);
}
}
|
C++ | UTF-8 | 5,815 | 2.53125 | 3 | [
"CC0-1.0"
] | permissive | // *********************************************************************
//
// main.cpp
//
// Created by: Elie Dolgin, University of Edinburgh
// Mofified by: Kamil S. Jaron, University of Lausanne
//
// First started: March 11, 2005
// Last edited:
//
// *********************************************************************
#include <iostream>
#include <fstream>
#include <vector>
#include <stdlib.h>
#include <cstring>
#include <ctype.h>
#include <stdio.h>
#include <unistd.h>
#include "time.h"
#include "../include/Population.h"
#include "../include/gitversion.h"
#include "../include/Genome.h"
using namespace std;
int main(int argc, char **argv){
/* constants - input and output files */
const char *detailed_out = "detailed.txt";
const char *input_file = "input.txt";
bool sex = false;
string runnig_sex = "False";
int replicates = 10;
int generations = 990;
int sex_report_period = 90;
int burnin = 20;
int index;
int c;
double prerepTEs = 0, postrepTEs = 0, modifier_freq = 0;
opterr = 0;
while ((c = getopt (argc, argv, "hvsmb:r:g:p:i:o:")) != -1)
switch (c)
{
case 'b':
burnin = atoi(optarg);
break;
case 'r':
replicates = atoi(optarg);
break;
case 'g':
generations = atoi(optarg);
break;
case 'p':
sex_report_period = atoi(optarg);
break;
case 's':
sex = true;
runnig_sex = "True";
break;
case 'i':
input_file = optarg;
break;
case 'o':
detailed_out = optarg;
break;
case 'h':
cout << "most of parameters are read form an input file input.txt" << endl;
cout << "details are in README.md file" << endl;
cout << "Usage: \n \t TEAscus [options]" << endl;
cout << "Options: \n \t [-h] \t \t print help of TEAscus and die" << endl
<< " \t [-v] \t \t print version of TEAscus and die" << endl
<< " \t [-s] \t \t sex every [-p] generations (False)" << endl
<< " \t [-g] \t INT \t number of generations (990)" << endl
<< " \t [-b] \t INT \t number of burn-in generations before simumlation (20)" << endl
<< " \t [-r] \t INT \t number of replicates (10)" << endl
<< " \t [-p] \t INT \t period of saves and sex if -s option is set (90)" << endl
<< " \t [-i] \t FILE \t name of input file (input.txt)" << endl
<< " \t [-o] \t FILE \t name of output file (detailed.txt)" << endl;
return 0;
case 'v':
cout << "TEAscus fork of Transposon ( doi : 10.1534%2Fgenetics.106.060434 )" << endl;
cout << "\thttps://github.com/KamilSJaron/TEAscus" << endl;
cout << "\tcommit: " << GITVERSION << endl;
return 0;
case '?':
if (isprint (optopt))
fprintf (stderr, "Unknown option `-%c'.\n", optopt);
else
fprintf (stderr,
"Unknown option character `\\x%x'.\n",
optopt);
return 1;
default:
abort ();
}
for (index = optind; index < argc; index++)
printf ("Non-option argument %s\n", argv[index]);
cerr << "Running TEAscus" << endl;
/* start of dev vesion */
cerr << "Commit: " << GITVERSION << endl;
/* end */
cerr << "Input : " << input_file << endl;
cerr << "Output : " << detailed_out << endl;
cerr << "Number of generations : " << generations << endl;
cerr << "Number of burn-in generations : " << burnin << endl;
cerr << "Number of replicates : " << replicates << endl;
cerr << "Sex every " << sex_report_period << " generations : " << runnig_sex << endl;
// For testing input
// return 0;
for (int run=1; run <= replicates; run++) {
std::cerr << "Running simualtion: " << run << endl;
std::ifstream fin(input_file);
if (! fin.is_open())
{ cerr << "Error opening file : " << input_file << endl; exit (1); }
// Initialize population size & whether to generate new population or load from file
int N;
char tempChar[100];
fin.getline(tempChar,100);
N=strtol(tempChar,0,10);
fin.getline(tempChar,100);
modifier_freq=strtod(tempChar,0);
fin.close();
Population * pop = new Population(N, modifier_freq);
// cerr << "Population created" << endl;
Population * new_population;
int size = pop->GetPopSize();
// cerr << "Population size : " << size << endl;
pop->Initialize();
// cerr << "Population initiated" << endl;
pop->SaveParameters(detailed_out);
if (run==1) {
pop->PrintParameters();
}
/// Burn in serves to generate some variability
for (int gen = 1; gen <= burnin; gen++){
// cerr << "Runnin burnin" << endl;
pop->MitoticTransposition();
pop->Exision();
}
pop->SummaryStatistics(detailed_out, 0);
for (int gen = 1; gen <= generations; gen++) {
if (pop->GetPopulationTECount() == 0 or ((double)pop->GetPopulationTECount()/(double)size) > 150.0) {
// cerr << "No TEs at generation [" << gen << "]." << endl << endl;
// cerr << "Population extinction at generation [" << gen << "]." << endl << endl;
pop->SummaryStatistics(detailed_out, gen);
break;
}
// cerr << "Reproducing " << endl;
// REPRODUCTION
int popSize = pop->GetPopSize();
prerepTEs = (double)pop->GetPopulationTECount() / popSize;
if ( gen % sex_report_period == 0 and sex ){
new_population = pop->SexualReproduction();
} else {
new_population = pop->AsexualReproduction();
/// mitotic transpostion practically happens in the reproduced individuals
new_population->MitoticTransposition();
}
postrepTEs = (double)new_population->GetPopulationTECount() / popSize;
delete pop;
pop = new_population;
// cerr << "Transposon loss " << endl;
/// LOSS
pop->Exision();
if(gen % 10 == 0){
std::cout << gen << "\t" << prerepTEs << "\t" << postrepTEs << "\t" << pop->GetModifierFrequency() << std::endl;
}
/// printing results after transposition
if (gen % sex_report_period == 0) {
pop->SummaryStatistics(detailed_out, gen);
}
}
delete pop;
std::cerr << "DONE!" << endl;
}
return 0;
}
|
JavaScript | UTF-8 | 6,915 | 2.640625 | 3 | [] | no_license | // Calling page must define projectLatLng to center the map in case there are no facts available.
var markers = new Array();
var map;
var bounds;
var infowindow;
var paletteControl;
var newMarkerControl;
function init_map(){
infowindow = new google.maps.InfoWindow();
var google_map_options = {
mapTypeControl: true,
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP,
mapTypeControlOptions: { style: google.maps.MapTypeControlStyle.DROPDOWN_MENU },
navigationControlOptions: { style: google.maps.NavigationControlStyle.ZOOM_PAN },
center: projectLatLng
};
map = new google.maps.Map(document.getElementById("map_content"), google_map_options);
bounds = new google.maps.LatLngBounds();
if(setupMarkers()){
map.fitBounds(bounds);
} else {
map.setZoom(11);
map.panTo(projectLatLng);
}
var newMarkerControlDiv = document.createElement('div');
newMarkerControl = new NewMarkerControl(map, newMarkerControlDiv);
newMarkerControlDiv.index = 2;
map.controls[google.maps.ControlPosition.RIGHT].push(newMarkerControlDiv);
var paletteControlDiv = document.createElement('div');
paletteControl = new PaletteControl(map, paletteControlDiv);
paletteControlDiv.index = 1;
setupTags(paletteControl);
map.controls[google.maps.ControlPosition.TOP_RIGHT].push(paletteControlDiv);
var projectControl = document.getElementById("project");
map.controls[google.maps.ControlPosition.TOP_LEFT].push(projectControl);
applyEditor();
jQuery('.tag-link').live('click', function(){
jQuery('.tag_list').val(jQuery(this).attr('title'));
jQuery('.current_tag').removeClass('current_tag');
jQuery(this).children('img').addClass('current_tag');
return false;
});
jQuery("#open_new_fact").fancybox({'autoDimensions':true});
};
function setupMarker(id, dom_id, title, latLng, icon){
var marker = new google.maps.Marker({ position: latLng, title: title, map: map, draggable: true, icon: icon });
jQuery.data(marker, 'fact_id', id);
bounds.extend(latLng);
google.maps.event.addListener(marker,'click',function(){
infowindow.setContent(jQuery('#' + dom_id).html());
infowindow.open(map, marker);
applyEditor();
});
google.maps.event.addListener(marker,'dragstart',function(event){
infowindow.close();
});
google.maps.event.addListener(marker,'dragend',function(event){
// Update object location on server
jQuery.post('/facts/' + jQuery.data(marker, 'fact_id'), { '_method': 'put', 'format': 'js', 'lat': this.position.lat(), 'lng': this.position.lng() });
});
return marker;
}
function setFormContent(data){
var container = document.createElement('div');
container.style.width = "500px";
container.style.height = "490px";
container.style.backgroundColor = 'white';
container.innerHTML = data;
infowindow.setContent(container);
}
function latLngString(latLng){
return latLng.lat() + ',' + latLng.lng();
}
// New Marker control
function NewMarkerControl(map, controlDiv) {
this.map = map;
this.controlDiv = controlDiv;
this.controlDiv.style.padding = '5px';
// Set CSS for the control border
var controlUI = document.createElement('DIV');
controlUI.style.backgroundColor = 'white';
controlUI.style.borderStyle = 'solid';
controlUI.style.borderWidth = '1px';
controlUI.style.cursor = 'pointer';
controlUI.style.textAlign = 'center';
controlUI.title = 'Click to add a new fact';
this.controlDiv.appendChild(controlUI);
// Set CSS for the control interior
var controlText = document.createElement('DIV');
controlText.style.fontFamily = 'Arial,sans-serif';
controlText.style.fontSize = '12px';
controlText.style.padding = '0 28px';
controlText.innerHTML = 'New';
controlUI.appendChild(controlText);
google.maps.event.addDomListener(controlUI, 'click', function() {
jQuery("#open_new_fact").trigger('click');
});
}
// Palette control
function PaletteControl(map, controlDiv) {
this.map = map;
this.controlDiv = controlDiv;
this.controlDiv.style.padding = '2px';
}
PaletteControl.prototype.addTool = function(img) {
var me = this;
var icon = document.createElement('img');
icon.src = img;
this.controlDiv.appendChild(icon);
google.maps.event.addDomListener(icon, 'click', function(event) {
me.killMarker();
cleanUp(true);
jQuery("#map_content").append('<img id="current_cursor_icon" src="' + img + '" />');
me.map.setOptions({draggableCursor: 'crosshair', draggingCursor: 'crosshair'});
jQuery("#map_content").mousemove(function(e){
var cursor = jQuery('#current_cursor_icon');
var height = cursor.height();
var width = cursor.width() / 2;
cursor.css({ position: "absolute", marginLeft: 0, marginTop: 0, top: (e.pageY - height), left: (e.pageX - width) });
});
var clickListener;
var rightClickListener;
clickListener = google.maps.event.addDomListener(me.map, 'click', function(event) {
cleanUp(false);
me.createMarker(event.latLng, img);
resetCursor();
});
rightClickListener = google.maps.event.addDomListener(me.map, 'rightclick', function(event) {
cleanUp(true);
});
jQuery(document).bind('keypress', function(event) {
if (event.keyCode == '27') {
cleanUp(true);
}
});
function cleanUp(remove_cursor){
jQuery('#map_content').unbind('mousemove');
jQuery(document).unbind('keypress');
if(clickListener) { google.maps.event.removeListener(clickListener); }
if(rightClickListener) { google.maps.event.removeListener(rightClickListener); }
if(remove_cursor) { resetCursor(); }
}
function resetCursor(){
jQuery('#current_cursor_icon').remove();
me.map.setOptions({draggableCursor: null, draggingCursor: null});
}
});
}
PaletteControl.prototype.createMarker = function(latLng, icon) {
var me = this;
this.create_marker = new google.maps.Marker({ position: latLng, map: map, draggable: true, icon: icon });
infowindow.close();
// jQuery("#new-fact img[src*='" + icon + "']").addClass('current_tag');
var tag = jQuery("#new-fact img[src*='" + icon + "']").parent().attr('title');
jQuery('#new-fact #fact_tag_list').val(tag);
jQuery('#new-fact #fact_location').val(latLngString(latLng));
setFormContent(jQuery('#new-fact').html());
infowindow.open(map, this.create_marker);
apply_ajax_forms();
this.closeClickListener = google.maps.event.addListener(infowindow,'closeclick',function(){
me.killMarker();
});
jQuery(document).bind('keypress', function(event) {
if (event.keyCode == '27') {
me.killMarker();
}
});
}
PaletteControl.prototype.killMarker = function(){
if(this.create_marker) {
this.shutDownKillMarker();
infowindow.close();
}
}
PaletteControl.prototype.shutDownKillMarker = function(){
if(this.create_marker) {
if(this.closeClickListener) { google.maps.event.removeListener(this.closeClickListener) };
jQuery(document).unbind('keypress');
this.create_marker.setMap(null);
this.create_marker = null;
}
}
|
Python | UTF-8 | 537 | 4.09375 | 4 | [] | no_license | # while
a = 0
while a < 10:
a += 1
if a == 5: continue
if a == 7: break
print(a)
else:
print('while 수행')
print('while 수행 후 %d'%a)
import random
num = random.randint(1,10)
#print(num)
while True:
print('1 ~ 10 사이이 컴이 가진 수를 입력')
guess = input()
su = int(guess)
if su == num:
print('성공 ' * 5)
break
elif su > num:
print('더 작은 수 입력')
elif su < num:
print('더 큰 수 입력') |
PHP | GB18030 | 928 | 2.890625 | 3 | [] | no_license | <?php if(defined(BASEPATH)) exit('No direct script access allowed');
/**
* һļ
* @date 2013-12-7 11:46:57
* @author Yongsen
* @version 0.0.0
*/
class config{
//ó˽ ñ˶д ṩȡ
private static $config = '';
function __construct(){
$this->get_config_file();
}
function get_config_file($filename=FALSE){
if(!$filename){
$filename = CONFIG_INI_FILE;
}
if(!$filename )exit('ļƲΪ');
if(!file_exists(CONFIG_DIR.$filename.'.config.ini'))exit('ļ');
$config = parse_ini_file(CONFIG_DIR.$filename.'.config.ini',true);
self::$config = $config['default'];
}
/**
* ˶ȡ (óָܶȡ)
* @date: 2013-12-7
* @author: Yongsen
* @return: return_type
*/
public static function get_config_value($name){
return self::$config[$name];
}
} |
Java | UTF-8 | 422 | 1.75 | 2 | [] | no_license | package com.fading.puppy.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping("/doOutBound/")
public class OutBoundController {
@RequestMapping("getIndex")
public ModelAndView getIndex(){
return new ModelAndView("jsp/outbound");
}
}
|
PHP | UTF-8 | 244 | 2.734375 | 3 | [] | no_license | <?php
require_once './MovieService.php';
$ms = new MovieService();
$list = $ms->movies();
//echo var_dump($list);
//echo $list;
for($i=0;$i<sizeof($list);$i++)
{
$r = new stdClass();
$r = $list[$i];
echo $r->thumbnail.'<br>';
}
|
TypeScript | UTF-8 | 1,416 | 2.609375 | 3 | [
"MIT"
] | permissive | import { base64ToImgElement } from './utils';
class CanvasServiceSrc {
readonly canvas = document.createElement('canvas');
readonly canvasCtx = this.canvas.getContext('2d') as CanvasRenderingContext2D;
readonly helperCanvas = document.createElement('canvas');
readonly helperCanvasCtx = this.helperCanvas.getContext('2d') as CanvasRenderingContext2D;
constructor() {
}
drawBase64(base64: string): Promise<void> {
return new Promise<void>(resolve => {
base64ToImgElement(base64).then(img => {
this.canvas.width = img.width;
this.canvas.height = img.height;
this.canvasCtx.drawImage(img.imgElement, 0, 0);
resolve();
});
});
}
crop(width: number, height: number) {
this.helperCanvas.width = width;
this.helperCanvas.height = height;
this.helperCanvasCtx.drawImage(this.canvas, 0, 0, width, height, 0, 0, width, height);
this.canvas.width = width;
this.canvas.height = height;
this.canvasCtx.drawImage(this.helperCanvas, 0, 0);
}
resize(width: number, height: number) {
this.helperCanvas.width = width;
this.helperCanvas.height = height;
this.helperCanvasCtx.drawImage(this.canvas, 0, 0, width, height);
this.canvas.width = width;
this.canvas.height = height;
this.canvasCtx.drawImage(this.helperCanvas, 0, 0);
}
}
export const canvasService = new CanvasServiceSrc();
|
Python | UTF-8 | 5,186 | 2.515625 | 3 | [] | no_license | qimport requests
from bs4 import BeautifulSoup
from datetime import datetime
import pytz
from pytz import timezone
from icalendar import Calendar, vText, Event
import json
import re
base_url = "https://www.portal.reinvent.awsevents.com/connect/"
favorites_url = "https://www.portal.reinvent.awsevents.com/connect/interests.ww"
login_url = "https://www.portal.reinvent.awsevents.com/connect/processLogin.do"
scheduling_url = "https://www.portal.reinvent.awsevents.com/connect/dwr/call/plaincall/ConnectAjax.getSchedulingJSON.dwr"
vegas = timezone("US/Pacific")
# Set username and password for reinvent event website
USERNAME = 'YOUR_USERNAME'
PASSWORD = 'YOUR_PASSWORD'
# login and start a session
session = requests.session()
payload = {"password": PASSWORD, "username": USERNAME }
resp = session.post(login_url, data=payload)
# get all the favorites
resp = session.get(favorites_url)
html = resp.content
soup = BeautifulSoup(html, "html.parser")
# find all selected sessions
selected_sessions = soup.findAll("div", {"class": "sessionRow"})
session_data = []
abbreviation_normalizer = re.compile("-R\d?")
abstract_cleaner = re.compile(".*>\n\n", re.DOTALL)
# loop through all sessions, and gather the needed information
for selected_session in selected_sessions:
# get the link
link = selected_session.find("a", {"class": "openInPopup"})
url = link['href']
# get the session title
abbreviation = link.find("span", {"class": "abbreviation"}).text
title = link.find("span", {"class": "title"}).text
normalized_abbreviation = abbreviation_normalizer.sub("", abbreviation)
# get the abstract
abstract = selected_session.find("span", {"class": "abstract"}).text
abstract = abstract_cleaner.sub("", abstract)
session_url = "%s%s" % (base_url, url)
# this contains the session id (int)
session_id = url.split("=")[-1]
# get my schedule status
schedule_status = selected_session.find("span", {"class": "scheduleStatus"}).text.strip(' \t\n\r').split(" ")[-1]
if len(schedule_status) > 0:
schedule_status = "{" + schedule_status[0] + "} "
else:
schedule_status = ""
# get the scheduling information and location from the magic json url
payload = {
"callCount":"1",
"windowName":"",
"c0-scriptName":"ConnectAjax",
"c0-methodName":"getSchedulingJSON",
"c0-id":"0",
"c0-param0":"string:%s" % session_id,
"batchId":"4",
"instanceId":"0",
"page":"%2Fconnect%2Finterests.ww",
"scriptSessionId":"OGxWNAOpsVunFAFyWddX2cGpNYl/RTNxNYl-Roe8DFsEq",
}
resp = session.post(scheduling_url, data=payload)
# do some magic and actually get the escaped json
json_response = resp.content.split("\n")[5].replace('r.handleCallback("4","0","',"").replace('");',"").replace('\\"','"').replace("\\'","'")
schedule_data = json.loads(json_response)['data'][0]
print abbreviation + title
# Friday, Dec 1, 9:15 AM
# print schedule_data
start_dt = datetime.strptime(schedule_data['startTime'], '%A, %b %d, %I:%M %p').replace(year=2017, tzinfo=vegas)
schedule_data['startDatetime'] = start_dt
end_dt = datetime.strptime(schedule_data['endTime'], '%I:%M %p').replace(day=start_dt.day, month=start_dt.month, year=2017, tzinfo=vegas)
schedule_data['endDatetime'] = end_dt
session_data.append({
"abbreviation": abbreviation,
"title": title,
"abstract": abstract,
"link": link,
"schedule": schedule_data,
"schedule_status": schedule_status,
"normalized_abbreviation": normalized_abbreviation
})
# avoid duplication
print ""
for session in session_data:
for session2 in session_data:
if session2 != session and session2['normalized_abbreviation'] == session['normalized_abbreviation']:
if session2['schedule_status'] != "" and session2['schedule_status'] != "{O} " and session['schedule_status'] != "" and session['schedule_status'] != "{O} ":
print "WARN: Multiple reservations for " + session['abbreviation'] + " / " + session2['abbreviation']
elif session2['schedule_status'] == "" and session['schedule_status'] != "" and session['schedule_status'] != "{O} ":
session2['schedule_status'] = "{O} "
# ok, we have everything we need, now generate an ical file
cal = Calendar()
cal.add('prodid', '-//Re-Invent plan generator product//mxm.dk//')
cal.add('version', '2.0')
for session in session_data:
event = Event()
event.add('summary', session['schedule_status'] + session['abbreviation'] + session['title'].replace("'","\'"))
event.add('description', session['abstract'])
event.add('location', session['schedule']['room'])
event.add('dtstart', session['schedule']['startDatetime'])
event.add('dtend', session['schedule']['endDatetime'])
event.add('url', base_url + "/sessionDetail.ww?SESSION_ID=" + session['normalized_abbreviation'].replace(" - ", ""))
event.add('dtstamp', session['schedule']['startDatetime'])
cal.add_component(event)
# write the ical file
with open("reinvent.ics","w") as f:
f.write(cal.to_ical())
|
JavaScript | UTF-8 | 2,228 | 2.78125 | 3 | [] | no_license | import { DilActionAnimation } from "./DilActionAnimation";
describe('AnimationAction', () => {
describe('_indexToCoordinate', () => {
let dilActionAnimation;
const setup = (rows, columns) => {
dilActionAnimation = new DilActionAnimation(
{ rows, columns },
0, 3,
50
);
};
it('when passed index, then will map to texture coordinate', () => {
setup(3, 3);
const expected = { x: 2/3, y: 2/3 };
expect(dilActionAnimation._indexToCoordinate(8)).toEqual(expected);
});
it('when passed middle index, then will map to correct texture coordinate', () => {
setup(3, 3);
const expected = { x: 1/3, y: 1/3 };
expect(dilActionAnimation._indexToCoordinate(4)).toEqual(expected);
});
it('when passed non-square shape, then will map to correct texture coordinate', () => {
setup(4, 3);
const expected = { x: 0/4, y: 3/4 };
expect(dilActionAnimation._indexToCoordinate(9)).toEqual(expected);
});
});
describe('animate', () => {
let dilActionAnimation;
const setup = (animationTime) => {
dilActionAnimation = new DilActionAnimation(
{ rows: 2, columns: 2 },
0, 3,
animationTime
);
};
it('when called with time less than frame time, then currentIndexTextureCoordinate will not change', () => {
setup(200);
expect(dilActionAnimation.currentIndexTextureCoordinate()).toEqual({ x: 0, y: 0 });
dilActionAnimation.animate(25);
expect(dilActionAnimation.currentIndexTextureCoordinate()).toEqual({ x: 0, y: 0 });
});
it('when called with time greater than frame time, then currentIndexTextureCoordinate will increment', () => {
setup(200);
expect(dilActionAnimation.currentIndexTextureCoordinate()).toEqual({ x: 0, y: 0 });
dilActionAnimation.animate(50);
expect(dilActionAnimation.currentIndexTextureCoordinate()).toEqual({ x: 1/2, y: 0 });
});
});
}) |
Python | UTF-8 | 651 | 3.921875 | 4 | [] | no_license | def headline(text, centered = False):
#type: (str, bool) -> str
if not centered:
return f"{text.title()}\n{'-' * len(text)}"
else:
return f" {text.title()} ".center(50, "o")
def headline2(
text,
width=80,
fill_char='-',
):
return f" {text.title()} ".center(width, fill_char)
if __name__=='__main__':
print(headline2("these type comments also work", width=70))
print(headline("python type checking"))
print(headline("use mypy", centered=True))
pi = 3.142 # type: float
try:
print(headline(pi)) # will throw an error
except Exception as err:
print(f'error! {err}') |
Java | UTF-8 | 619 | 2.25 | 2 | [] | no_license | package com.skripsi.area31.model.response;
import com.skripsi.area31.model.course.Course;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data @Builder @AllArgsConstructor @NoArgsConstructor public class CheckCustomResponse {
private Integer code;
private String message;
private Course course;
public CheckCustomResponse(int code, Course course) {
this.code = code;
this.course = course;
}
public CheckCustomResponse(int code, String message) {
this.code = code;
this.message = message;
}
}
|
C++ | UTF-8 | 6,180 | 2.625 | 3 | [
"Unlicense",
"LicenseRef-scancode-public-domain"
] | permissive | // This is free and unencumbered software released into the public domain.
// For more information, please refer to <http://unlicense.org/>
#include "models/sagtension/catenary_cable_reloader.h"
#include "gtest/gtest.h"
#include "models/base/helper.h"
#include "test/factory.h"
class CatenaryCableReloaderTest : public ::testing::Test {
protected:
CatenaryCableReloaderTest() {
// builds dependency object - cable
cable_ = factory::BuildSagTensionCable();
// builds dependency object - catenary
Vector3d spacing_endpoints(1200, 0, 0);
Vector3d weight_unit(0, 0, 1.094);
catenary_.set_spacing_endpoints(spacing_endpoints);
catenary_.set_tension_horizontal(6000);
catenary_.set_weight_unit(weight_unit);
// builds dependency object - reference cable model
CableState state;
state.temperature = 60;
state.type_polynomial =
SagTensionCableComponent::PolynomialType::kLoadStrain;
CableStretchState state_stretch;
state_stretch.load = 0;
state_stretch.temperature = 0;
state_stretch.type_polynomial =
SagTensionCableComponent::PolynomialType::kLoadStrain;
model_reference_ = factory::BuildCableElongationModel(cable_);
model_reference_->set_state(state);
model_reference_->set_state_stretch(state_stretch);
// builds dependency object - reloaded cable model
state = CableState();
state.temperature = 60;
state.type_polynomial =
SagTensionCableComponent::PolynomialType::kLoadStrain;
state_stretch = CableStretchState();
state_stretch.load = 0;
state_stretch.temperature = 0;
state_stretch.type_polynomial =
SagTensionCableComponent::PolynomialType::kLoadStrain;
model_reloaded_ = factory::BuildCableElongationModel(cable_);
model_reloaded_->set_state(state);
model_reloaded_->set_state_stretch(state_stretch);
// builds dependency object - reloaded unit weight
weight_unit_reloaded_ = Vector3d(0, 0, 1.094);
// builds fixture object
c_.set_catenary(&catenary_);
c_.set_model_reference(model_reference_);
c_.set_model_reloaded(model_reloaded_);
c_.set_weight_unit_reloaded(&weight_unit_reloaded_);
}
~CatenaryCableReloaderTest() {
factory::DestroySagTensionCable(cable_);
delete model_reference_;
delete model_reloaded_;
}
// allocated dependency objects
SagTensionCable* cable_;
Catenary3d catenary_;
CableElongationModel* model_reference_;
CableElongationModel* model_reloaded_;
Vector3d weight_unit_reloaded_;
// test object
CatenaryCableReloader c_;
};
TEST_F(CatenaryCableReloaderTest, LengthUnloaded) {
double value = -999999;
// unstretched original catenary cable
value = c_.LengthUnloaded();
EXPECT_EQ(1201.04, helper::Round(value, 2));
}
TEST_F(CatenaryCableReloaderTest, CatenaryReloaded) {
double value = -999999;
Catenary3d catenary;
CableState state = c_.model_reloaded()->state();
CableStretchState state_stretch = c_.model_reloaded()->state_stretch();
// nothing is modified - original and reloaded parameters are equal
catenary = c_.CatenaryReloaded();
value = catenary.tension_horizontal();
EXPECT_EQ(6000, helper::Round(value, 0));
// tests temperature changes
state.temperature = 0;
model_reloaded_->set_state(state);
c_.set_model_reloaded(model_reloaded_);
catenary = c_.CatenaryReloaded();
value = catenary.tension_horizontal();
EXPECT_EQ(6788, helper::Round(value, 0));
state.temperature = 212;
model_reloaded_->set_state(state);
c_.set_model_reloaded(model_reloaded_);
catenary = c_.CatenaryReloaded();
value = catenary.tension_horizontal();
EXPECT_EQ(4701, helper::Round(value, 0));
// changes temperature to zero and tests unit weight changes
state.temperature = 0;
model_reloaded_->set_state(state);
c_.set_model_reloaded(model_reloaded_);
weight_unit_reloaded_.set_y(2.072);
weight_unit_reloaded_.set_z(3.729);
c_.set_weight_unit_reloaded(&weight_unit_reloaded_);
catenary = c_.CatenaryReloaded();
value = catenary.tension_horizontal();
EXPECT_EQ(17123, helper::Round(value, 0));
weight_unit_reloaded_.set_y(1.405);
weight_unit_reloaded_.set_z(2.099);
c_.set_weight_unit_reloaded(&weight_unit_reloaded_);
catenary = c_.CatenaryReloaded();
value = catenary.tension_horizontal();
EXPECT_EQ(12146, helper::Round(value, 0));
// sets stretch load and tests all above cases again
const double kLoadStretch = catenary.TensionAverage();
EXPECT_EQ(12178, helper::Round(kLoadStretch, 0));
state_stretch.load = kLoadStretch;
model_reloaded_->set_state_stretch(state_stretch);
c_.set_model_reloaded(model_reloaded_);
state.temperature = 60;
model_reloaded_->set_state(state);
c_.set_model_reloaded(model_reloaded_);
weight_unit_reloaded_.set_y(0);
weight_unit_reloaded_.set_z(1.094);
c_.set_weight_unit_reloaded(&weight_unit_reloaded_);
catenary = c_.CatenaryReloaded();
value = catenary.tension_horizontal();
EXPECT_EQ(5561, helper::Round(value, 0));
state.temperature = 0;
model_reloaded_->set_state(state);
c_.set_model_reloaded(model_reloaded_);
catenary = c_.CatenaryReloaded();
value = catenary.tension_horizontal();
EXPECT_EQ(6321, helper::Round(value, 0));
state.temperature = 212;
model_reloaded_->set_state(state);
c_.set_model_reloaded(model_reloaded_);
catenary = c_.CatenaryReloaded();
value = catenary.tension_horizontal();
EXPECT_EQ(4527, helper::Round(value, 0));
state.temperature = 0;
model_reloaded_->set_state(state);
c_.set_model_reloaded(model_reloaded_);
weight_unit_reloaded_.set_y(2.072);
weight_unit_reloaded_.set_z(3.729);
c_.set_weight_unit_reloaded(&weight_unit_reloaded_);
catenary = c_.CatenaryReloaded();
value = catenary.tension_horizontal();
EXPECT_EQ(17123, helper::Round(value, 0));
weight_unit_reloaded_.set_y(1.405);
weight_unit_reloaded_.set_z(2.099);
c_.set_weight_unit_reloaded(&weight_unit_reloaded_);
catenary = c_.CatenaryReloaded();
value = catenary.tension_horizontal();
EXPECT_EQ(12146, helper::Round(value, 0));
}
TEST_F(CatenaryCableReloaderTest, Validate) {
EXPECT_TRUE(c_.Validate(false, nullptr));
}
|
JavaScript | UTF-8 | 206 | 3.671875 | 4 | [] | no_license | const a = Number(prompt("Enter first mark"));
const b = Number(prompt("Enter second mark"));
const c = Number(prompt("Enter third mark"));
alert(`The average of ${a}, ${b} and ${c} is ${(a + b + c) / 3}`); |
Ruby | UTF-8 | 191 | 3.28125 | 3 | [] | no_license | x = 2520
was_clean = true
while true do
(11..20).each do |i|
if !(x % i == 0)
was_clean = false
end
end
if was_clean
puts x
exit
else
x += 20
was_clean = true
end
end
|
Java | UTF-8 | 1,345 | 2.34375 | 2 | [] | no_license | package com.bingo.showme.service.impl;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import org.springframework.stereotype.Service;
import org.springframework.web.client.ResourceAccessException;
import com.bingo.showme.entity.User;
import com.bingo.showme.service.UserService;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@Service
public class UserServiceImpl implements UserService {
private final AtomicLong atomicLong = new AtomicLong();
private final Map<Long, User> data = new ConcurrentHashMap<>();
@Override
public Flux<User> list() {
return Flux.fromIterable(data.values());
}
@Override
public Flux<User> getByIds(Flux<Long> ids) {
return ids.flatMap(id -> Mono.justOrEmpty(data.get(id)));
}
@Override
public Mono<User> getById(Long id) {
return Mono.justOrEmpty(data.get(id))
.switchIfEmpty(Mono.error(new ResourceAccessException("User not found.")));
}
@Override
public Mono<User> createOrUpdate(User user) {
if (user.getId() == null) {
user.setId(atomicLong.incrementAndGet());
}
data.put(user.getId(), user);
return Mono.just(user);
}
@Override
public Mono<User> deleteById(Long id) {
return Mono.justOrEmpty(data.remove(id));
}
}
|
Python | UTF-8 | 814 | 3.171875 | 3 | [] | no_license | # -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as pl
from scipy.optimize import fsolve
###Inverse transform sampling
#karmi się liczbą superkropelek i srednim promieniem
#wypluwa listę
#r_sr = 30.531*10**(-6)
def inverse_transform_sampling(n, r_sr):
v_sr = 4 * np.pi * r_sr**3 /3
list = np.random.uniform(0,1,n)
radius=[]
for i in range(n):
#function for fsolve, f=0
def f(x):
return 1-np.exp(-x/v_sr)-list[i]
#finding volume corresponding to generated number
y = fsolve(f,v_sr)
#radius from volume
r = (3*y[0]/(4 * np.pi))**(1/3)
#appending
radius.append(r)
return radius
#for testing
#lista=inverse_transform_sampling(10000,30.531*10**(-6))
#fig = pl.hist(lista,25) |
Java | UTF-8 | 3,618 | 2.453125 | 2 | [] | no_license | package Controladores;
import Negocio.Agricultor;
import Negocio.Criptografia;
import Repositorio.implementacoes.RepositorioImplementacaoAgricultorDB;
import Repositorio.interfaces.RepositorioInterfaceAgricultor;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
@ManagedBean(name = "ControladorA")
@SessionScoped
public class ControladorAgricultor {
private RepositorioInterfaceAgricultor agricultores = null;
public ControladorAgricultor() {
this.agricultores = new RepositorioImplementacaoAgricultorDB();
}
public String adicionar(Agricultor agricultor) {
if (agricultor.getNome().equals("") || agricultor.getNome() == null) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Digite o Nome!", ""));
return null;
} else if (agricultor.getCelular().equals("") || agricultor.getCelular() == null) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Digite o Celular!", ""));
return null;
} else if (agricultor.getUsuario().getEmail().equals("") || agricultor.getUsuario().getEmail() == null) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Digite o Email!", ""));
return null;
} else if (agricultor.getNome().equals("") && agricultor.getNome() == null && agricultor.getCelular().equals("") && agricultor.getCelular() == null && agricultor.getUsuario().getEmail().equals("")
&& agricultor.getUsuario().getSenha().equals("") && agricultor.getUsuario().getSenha() == null) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Por Favor digite os dados!", ""));
} else if (agricultor.getCelular().equals("") || agricultor.getCelular() == null) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Digite o Celular!", ""));
return "null";
} else if (agricultor.getUsuario().getEmail().equals("") || agricultor.getUsuario().getEmail() == null) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Digite o Email!", ""));
return "null";
} else if (agricultor.getUsuario().getSenha().equals("") || agricultor.getUsuario().getSenha() == null) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Digite a Senha!", ""));
} else if (validarEmail(agricultor.getUsuario().getEmail()) == false || agricultor.getUsuario().getEmail() == null) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Digite o Email Novamente!!!", ""));
}
agricultor.getUsuario().setSenha(Criptografia.criptografar(agricultor.getUsuario().getSenha()));
this.agricultores.adicionar(agricultor);
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage("O Agricultor " + agricultor.getNome() + " Foi cadastrado com Sucesso!", "Mensagem"));
return "Login.xhtml";
}
private boolean validarEmail(String email) {
String padrao = "^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$";
if (padrao.matches(email)) {
return true;
}
return false;
}
}
|
Java | UTF-8 | 8,240 | 1.570313 | 2 | [] | no_license | package com.tenghen.ireader.ui.fragment;
import android.content.Intent;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.chengx.mvp.widget.CircleImageView;
import com.tenghen.ireader.CommonUtils;
import com.tenghen.ireader.R;
import com.tenghen.ireader.base.BaseFragment;
//import com.tenghen.ireader.qqapi.QQAPI;
import com.tenghen.ireader.module.UserInfo;
import com.tenghen.ireader.module.Wallet;
import com.tenghen.ireader.net.Api;
import com.tenghen.ireader.ui.activity.AboutActivity;
import com.tenghen.ireader.ui.activity.BindPhoneActivity;
import com.tenghen.ireader.ui.activity.CostLogActivity;
import com.tenghen.ireader.ui.activity.LatestReadActivity;
import com.tenghen.ireader.ui.activity.LoginActivity;
import com.tenghen.ireader.ui.activity.ModifyPwdActivity;
import com.tenghen.ireader.ui.activity.MyCommentActivity;
import com.tenghen.ireader.ui.activity.MyMsgActivity;
import com.tenghen.ireader.ui.activity.MyShelfActivity;
import com.tenghen.ireader.ui.activity.ProblemsActivity;
import com.tenghen.ireader.ui.activity.RechargeActivity;
import com.tenghen.ireader.ui.activity.RechargeLogActivity;
import com.tenghen.ireader.ui.activity.SettingActivity;
import com.tenghen.ireader.ui.present.UserPresent;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;
import com.umeng.socialize.media.UMWeb;
import butterknife.BindView;
import butterknife.OnClick;
/**
* 作者:chengx
* 日期:2017/2/23
* 描述:
*/
public class UserFragment extends BaseFragment<UserPresent> {
public static final int OPT_TO_RECHARGE = 1;
public static final int OPT_TO_MY_SHELF = 2;
public static final int OPT_TO_RECHARGE_LOG = 3;
public static final int OPT_TO_COST_LOG = 4;
public static final int OPT_TO_LETAST_READ = 5;
public static final int OPT_TO_MY_COMMENT = 6;
public static final int OPT_TO_MY_MSG = 7;
public static final int OPT_TO_DOWNLOAD = 8;
public static final int OPT_TO_RESET_PSD = 9;
public static final int OPT_TO_SETTING = 10;
@BindView(R.id.avatarIv)
CircleImageView avatarIv;
@BindView(R.id.nickNameTv)
TextView nickNameTv;
@BindView(R.id.userIdTv)
TextView userIdTv;
@BindView(R.id.phoneNumTv)
TextView phoneNumTv;
@BindView(R.id.walletTv)
TextView walletTv;
@Override
public void initToolBar() {
}
@Override
public int getLayoutId() {
return R.layout.fragment_user;
}
@Override
public void initData() {
getPresent();
}
@Override
public void initViews() {
}
@Override
public void setListener() {
}
@Override
public UserPresent newPresent() {
return new UserPresent();
}
@OnClick(R.id.avatarIv)
public void login(){
if (isLogin()){
}else {
LoginActivity.launch(this,0);
}
}
@Override
public void onResume() {
super.onResume();
if (CommonUtils.isLogin()){
getData();
}else {
clearUserInfo();
}
}
@OnClick(R.id.phoneNumTv)
public void bindPhone(View v){
BindPhoneActivity.launch(getContext());
}
@OnClick(R.id.latestReadBtn)
public void toLatestRead(){
if (isLogin())
LatestReadActivity.launch(getContext());
else
LoginActivity.launch(this,OPT_TO_LETAST_READ);
}
@OnClick(R.id.myShelfBtn)
public void toMyShelf(){
if (isLogin())
MyShelfActivity.launch(getContext());
else
LoginActivity.launch(this,OPT_TO_MY_SHELF);
}
@OnClick(R.id.rechargeLogBtn)
public void toRechargeLog(){
if (isLogin())
RechargeLogActivity.launch(getContext());
else
LoginActivity.launch(this,OPT_TO_RECHARGE_LOG);
}
@OnClick(R.id.costLogBtn)
public void toCostLog(){
if (isLogin())
CostLogActivity.launch(getContext());
else
LoginActivity.launch(this,OPT_TO_COST_LOG);
}
@OnClick(R.id.myCommentBtn)
public void toMyComment(){
if (isLogin())
MyCommentActivity.launch(getContext());
else
LoginActivity.launch(this,OPT_TO_MY_COMMENT);
}
@OnClick(R.id.myMsgBtn)
public void toMyMsg(){
if (isLogin())
MyMsgActivity.launch(getContext());
else
LoginActivity.launch(this,OPT_TO_MY_MSG);
}
private void getData(){
getPresent().getUserData();
getPresent().getSignData();
getPresent().getWalletData();
}
public void setUserInfo(UserInfo userInfo){
UserInfo.BaseInfo baseInfo = userInfo.getBase_info();
if (baseInfo != null) {
userIdTv.setText("ID:"+baseInfo.getId());
Glide.with(this).load(Api.IMG_HOST+baseInfo.getUser_image()).into(avatarIv);
String phoneNum = baseInfo.getMobile();
phoneNumTv.setText(TextUtils.isEmpty(phoneNum)?"绑定手机":phoneNum);
phoneNumTv.setClickable(TextUtils.isEmpty(phoneNum));
nickNameTv.setText(baseInfo.getName());
phoneNumTv.setVisibility(View.VISIBLE);
userIdTv.setVisibility(View.VISIBLE);
}
}
public void setWalletInfo(Wallet walletInfo){
walletTv.setVisibility(View.VISIBLE);
walletTv.setText(walletInfo.getMoney()+"腾币");
}
public void clearUserInfo(){
nickNameTv.setText("注册/登录");
avatarIv.setImageResource(R.drawable.ic_user_avatar);
userIdTv.setVisibility(View.GONE);
phoneNumTv.setVisibility(View.GONE);
walletTv.setVisibility(View.INVISIBLE);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (isLogin())
getData();
else
clearUserInfo();
switch (requestCode){
case OPT_TO_LETAST_READ:
if (isLogin())
LatestReadActivity.launch(getContext());
break;
case OPT_TO_MY_SHELF:
if (isLogin())
MyShelfActivity.launch(getContext());
break;
case OPT_TO_RECHARGE_LOG:
if (isLogin())
RechargeLogActivity.launch(getContext());
break;
case OPT_TO_COST_LOG:
if (isLogin())
CostLogActivity.launch(getContext());
break;
case OPT_TO_MY_COMMENT:
if (isLogin())
MyCommentActivity.launch(getContext());
break;
case OPT_TO_MY_MSG:
if (isLogin())
MyMsgActivity.launch(getContext());
break;
case OPT_TO_RECHARGE:
if (isLogin())
RechargeActivity.launch(getContext());
break;
case OPT_TO_RESET_PSD:
if (isLogin())
ModifyPwdActivity.launch(getContext(),"2");
break;
}
}
@OnClick(R.id.rechargeBtn)
public void recharge(View view){
if (isLogin())
RechargeActivity.launch(getContext());
else
LoginActivity.launch(this,OPT_TO_RECHARGE);
}
@OnClick(R.id.modifyPwdBtn)
public void modifyPwd(View view){
if (isLogin())
ModifyPwdActivity.launch(getContext(),"2");
else
LoginActivity.launch(this,OPT_TO_RESET_PSD);
}
@OnClick(R.id.shareBtn)
public void share(View view){
}
@OnClick(R.id.problemBtn)
public void toProblem(View view){
ProblemsActivity.launch(getContext());
}
@OnClick(R.id.aboutBtn)
public void toAbout(View view){
AboutActivity.launch(getContext());
}
@OnClick(R.id.settingBtn)
public void toSetting(View view){
SettingActivity.launch(getContext());
}
}
|
Java | UTF-8 | 9,682 | 1.804688 | 2 | [] | no_license | /**
* Copyright (c) 2009 International Health Terminology Standards Development
* Organisation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.dwfa.ace.task;
import java.awt.Component;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.Collection;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import org.dwfa.ace.api.I_ConfigAceFrame;
import org.dwfa.ace.api.I_HostConceptPlugins;
import org.dwfa.ace.api.I_HostConceptPlugins.TOGGLES;
import org.dwfa.bpa.process.Condition;
import org.dwfa.bpa.process.I_EncodeBusinessProcess;
import org.dwfa.bpa.process.I_Work;
import org.dwfa.bpa.process.TaskFailedException;
import org.dwfa.bpa.tasks.AbstractTask;
import org.dwfa.util.bean.BeanList;
import org.dwfa.util.bean.BeanType;
import org.dwfa.util.bean.Spec;
/**
* <h1>SetRefSetPreferences</h1> <br>
* <p>
* The <code>SetRefSetPreferences</code> class turns on various refSet options
* as specified by passed parameters.
* </p>
* <p>
* It is added as a task under tasks/ide/gui/signpost, which enables it to be
* added to a business process.
* </P>
*
* <br>
* <br>
*
* @see <code>org.dwfa.bpa.tasks.AbstractTask</code>
* @author PeterVawser
*
*/
@BeanList(specs = { @Spec(directory = "tasks/ide/gui/signpost", type = BeanType.TASK_BEAN) })
public class SetRefSetPreferences extends AbstractTask {
private static final long serialVersionUID = 1;
private static final int dataVersion = 3;
private TOGGLES toggle = TOGGLES.ATTRIBUTES;
private I_ConfigAceFrame config;
public TOGGLES getToggle() {
return toggle;
}
public void setToggle(TOGGLES toggle) {
this.toggle = toggle;
}
private void writeObject(ObjectOutputStream out) throws IOException {
out.writeInt(dataVersion);
out.writeObject(toggle);
}// End method writeObject
private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
int objDataVersion = in.readInt();
if (objDataVersion <= dataVersion) {
toggle = (TOGGLES) in.readObject();
} else {
throw new IOException("Can't handle dataversion: " + objDataVersion);
}
}// End method readObject
/**
* @see org.dwfa.bpa.process.I_DefineTask#evaluate(org.dwfa.bpa.process.I_EncodeBusinessProcess,
* org.dwfa.bpa.process.I_Work)
*/
public Condition evaluate(I_EncodeBusinessProcess process, final I_Work worker) throws TaskFailedException {
try {
config = (I_ConfigAceFrame) worker.readAttachement(WorkerAttachmentKeys.ACE_FRAME_CONFIG.name());
/*
* Create an option pane to be used for user input, and a panel to
* layout
* input objects to be displayed in the user input dialog.
*/
final JOptionPane optionPane = new JOptionPane();
final JPanel optionsPanel = new JPanel(new GridBagLayout());
/*
* Set gridbag layout configuration
*/
final GridBagConstraints c = new GridBagConstraints();
c.fill = GridBagConstraints.BOTH;
c.gridx = 0;
c.gridy = 0;
c.fill = GridBagConstraints.VERTICAL;
c.weighty = 0.5;
c.anchor = GridBagConstraints.NORTHWEST;
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
/*
* Add and label a checkbox for each refset type, for a
* selected toggle to the panel.
* Inital value should be set to the toggles refset type
* value.
*/
for (I_HostConceptPlugins.REFSET_TYPES refSetTypes : I_HostConceptPlugins.REFSET_TYPES.values()) {
JCheckBox cb = new JCheckBox(refSetTypes.toString());
cb.setSelected(config.isRefsetInToggleVisible(
I_HostConceptPlugins.REFSET_TYPES.valueOf(refSetTypes.toString()), toggle));
c.gridy += 1;
optionsPanel.add(cb, c);
}// End for loop
/*
* Create an object array to be added to the option pane
* dialog.
* This needs to have hvae an entry for the text to be
* dispalyed and one for the checkboxes (panel)
*/
Object msg[] = { "Select refsets to be displayed:", optionsPanel };
/*
* Set configuration of option pane
*/
optionPane.setMessage(msg);
optionPane.setMessageType(JOptionPane.QUESTION_MESSAGE);
optionPane.setOptionType(JOptionPane.OK_CANCEL_OPTION);
/*
* Create a frame object to be used as the parent frame for
* the option pane.
* Ensure the frame closes when exited.
*/
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JDialog dialog = optionPane.createDialog(frame, "Displayed refSets for " + toggle.toString());
dialog.setVisible(true);
/*
* Determine what action the user took and perform
* appropriate processing.
*/
Object value = optionPane.getValue();
if (value == null || !(value instanceof Integer)) {
System.out.println("Closed");
} else {
int i = ((Integer) value).intValue();
if (i == JOptionPane.OK_OPTION) {
/*
* User clicked ok. Now need to apply selections to
* preferences.
*/
for (Component comp : optionsPanel.getComponents()) {
System.out.println("comp == " + ((JCheckBox) comp).getText() + " "
+ ((JCheckBox) comp).isSelected());
/*
* Toggle the desired refset display to
* true/false.
* If true, set to false. If false, set to true.
*/
config.setRefsetInToggleVisible(
I_HostConceptPlugins.REFSET_TYPES.valueOf(((JCheckBox) comp).getText()),
TOGGLES.valueOf(toggle.toString()), ((JCheckBox) comp).isSelected());
}// End for loop
}// End if OK_OPTION
}// End if/else
/*
* Ensure refsets in component toggle are set to visible.
*/
config.setTogglesInComponentPanelVisible(I_HostConceptPlugins.TOGGLES.REFSETS, true);
/*
* Apply changes to current config frame.
* For some reason, without the fireCommit, the process
* worked
* on the initial execution but not on subsequent
* executions, unless the viewer was restarted.
* Call to fireCommit fixed this issue.
*/
// config.setActive(true);
config.fireCommit();
}
});
} catch (InterruptedException e) {
throw new TaskFailedException(e);
} catch (IllegalArgumentException e) {
throw new TaskFailedException(e);
} catch (InvocationTargetException e) {
throw new TaskFailedException(e);
}
return Condition.CONTINUE;
}// End method evaluate
/**
* @see org.dwfa.bpa.process.I_DefineTask#complete(org.dwfa.bpa.process.I_EncodeBusinessProcess,
* org.dwfa.bpa.process.I_Work)
*/
public void complete(I_EncodeBusinessProcess process, I_Work worker) throws TaskFailedException {
// Nothing to do
}// End method complete
/**
* @see org.dwfa.bpa.process.I_DefineTask#getConditions()
*/
public Collection<Condition> getConditions() {
return CONTINUE_CONDITION;
}// End method getConditions
/**
* @see org.dwfa.bpa.process.I_DefineTask#getDataContainerIds()
*/
public int[] getDataContainerIds() {
return new int[] {};
}// End method getDataContainerIds
}// End class SetRefSetPreferences
|
Java | UTF-8 | 2,121 | 3.375 | 3 | [] | no_license | package Aug_05;
import Aug_05.models.SportsCar;
public class Driver {
static SportsCar myCar = new SportsCar(2, "black", "RX-8, R3", 3 , true);
public static void main(String[] args) {
myCar.move(200);
boolean con = true;
System.out.println("--------------");
while(myCar.getHasTurbo() && con) {
System.out.println("In first while loop");
if (con) {
System.out.println("in if statement");
con = false;
continue;
}
System.out.println("I am at the end of my while loop");
}
System.out.println("--------------");
//
while(con & myCar.getHasTurbo()) {
System.out.println("In second while loop");
if (con) {
System.out.println("in if statement");
con = false;
continue;
}
System.out.println("I am at the end of my while loop");
}
System.out.println("--------------");
// it doesnt show nothing
while(con && myCar.getHasTurbo()) {
System.out.println("In third while loop");
if (con) {
System.out.println("in if statement");
con = false;
continue;
}
System.out.println("I am at the end of my while loop");
}
System.out.println("--------------");
do {
System.out.println("I will do this once");
myCar.hasTurbo = !myCar.hasTurbo;
}while(myCar.getHasTurbo());
System.out.println("--------------");
for(int i = 0; i <= myCar.seats; i++) {
System.out.println("you have filled " + i + " seats in your car");
}
System.out.println("--------------");
switch(myCar.color) {
case "White": System.out.println("White - my car");break;
case "black": System.out.println("black - mycar");break;
case "Purple": System.out.println("Purple - mycar");break;
default: System.out.println("what color?");break;
}
System.out.println("--------------");
switch(myCar.color) {
case "White": System.out.println("White - my car");break;
case "black": System.out.println("black - mycar");
case "Purple": System.out.println("Purple - mycar");break;
default: System.out.println("what color?");break;
}
System.out.println("--------------");
}
}
|
Java | UTF-8 | 3,775 | 2.390625 | 2 | [] | no_license | package GetTestCase.LessonCreatFlow;
import com.alibaba.fastjson.JSONObject;
import com.mizholdings.me2.Global_enum;
import com.mizholdings.util.JsonFuncUtil;
import com.mizholdings.util.SampleAssert;
import com.mizholdings.util.javabean.LessonEditBean;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.Test;
public class SuperAdminLessonEditTestCase extends BaseTestCase {
LessonEditBean lessonEditBean;
@BeforeClass
public void beforeClass() {
// TODO 修改课程信息,是否有效
lessonEditBean = new LessonEditBean();
lessonEditBean.addGradeId(Global_enum.GRADEID.FIVE); //5
lessonEditBean.addGradeId(Global_enum.GRADEID.NINE); //9
lessonEditBean.setClassroomCount(3);
lessonEditBean.setCustRelease(Global_enum.CustRelease.CLASS_LIB);
lessonEditBean.setLesson_type_id(Global_enum.LESSON_TYPE_ID.MAT);//数学
lessonEditBean.setLessonName("新修改后的名称");
lessonEditBean.setStartDay(1);
JSONObject object = superAdmin.getManage().lessonAgent().edit(lessonId, lessonEditBean);
SampleAssert.assertCode200(object);
}
@Test(description = "管理员 课程详情")
public void superAdmin_lessonInfo_test() {
Info info = superAdmin_getLessonInfoById(lessonId);
info_assert(info);
}
@Test(description = "教师 课程详情")
public void teacher_lessonInfo_test() {
Info info = teacher_getLessonInfoById(lessonId);
info_assert(info);
}
public void info_assert(Info info) {
info.lessonInfo.ifPresent(i -> {
//年级检测
String gradeIds = i.getString("gradeIds");
String gradeNames = i.getString("gradeNames");
lessonEditBean.getGrade().forEach(gradeId -> {
assert gradeIds.contains(gradeId.value) : "gradeIds 值" + gradeIds + " 中不存在" + gradeId.value;
assert gradeNames.contains(gradeId.gradeName) : "gradeNames 值" + gradeNames + " 中不存在" + gradeId.gradeName;
});
//学科检测
String lessonTypeId = i.getString("lessonTypeId");
String lessonTypeName = i.getString("lessonTypeName");
Global_enum.LESSON_TYPE_ID now_type = lessonEditBean.getLesson_type_id();
assert lessonTypeId.equals(now_type.value) : "学科id不正确 应是" + now_type.value + " 实际是" + lessonTypeId;
assert lessonTypeName.equals(now_type.name) : "学科name不正确 应是" + now_type.name + " 实际是" + lessonTypeName;
//custRelease
String custRelease = i.getString("custRelease");
Global_enum.CustRelease now_cust = lessonEditBean.getCustRelease();
assert now_cust.value.equals(custRelease) : "custRelease不正确 应是" + now_cust.value + " 实际是" + custRelease;
//lessonName
String lessonName = i.getString("lessonName");
String now_lessonName = lessonEditBean.getLessonName();
assert now_lessonName.equals(lessonName) : "lessonName不正确 应是" + now_lessonName + " 实际是" + lessonName;
});
info.array.ifPresent(array -> {
assert array.size() == 3 : "课时数量不正确";
array.forEach(i -> {
JSONObject o = (JSONObject) i;
assert PUB_APPLY_PASS.equals(o.getString("pubType")) :
"管理员添加的课时应该都是通过审核的,但该课时状态为" + o.getString("pubType");
String teacherId = o.getString("teacherId");
assert teacher.getUserId().equals(teacherId) : "课时的主讲人不正确";
});
});
}
}
|
Java | UTF-8 | 2,002 | 2 | 2 | [
"Apache-2.0",
"BSD-3-Clause",
"MIT"
] | permissive | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.kylin.tool.daemon.handler;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import org.apache.kylin.common.util.Unsafe;
import org.apache.kylin.tool.daemon.CheckResult;
import org.apache.kylin.tool.daemon.HandleResult;
import org.apache.kylin.tool.daemon.HandleStateEnum;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SuicideStateHandler extends AbstractCheckStateHandler {
private static final Logger logger = LoggerFactory.getLogger(SuicideStateHandler.class);
@Override
public HandleResult doHandle(CheckResult checkResult) {
logger.info("Start to suicide ...");
String pidFile = getKylinHome() + "/kgid";
File file = new File(pidFile);
try {
if (Files.deleteIfExists(file.toPath())) {
logger.info("Deleted file: {}", pidFile);
} else {
logger.warn("Can not delete the file: {}", pidFile);
}
} catch (IOException e) {
logger.error("Failed to delete the file: {}", pidFile);
}
Unsafe.systemExit(0);
return new HandleResult(HandleStateEnum.STOP_CHECK);
}
}
|
PHP | UTF-8 | 4,054 | 3.140625 | 3 | [] | no_license | <?php
declare(strict_types=1);
class Calculator
{
protected $cleanRequest = '';
public function __construct(string $request)
{
$this->cleanRequest = preg_replace("~[^0-9*+\-()^/]~", "", $request);
}
protected $variables = [];
public function getResult() : float
{
$tokens = $this->tokenize($this->cleanRequest);
$stack = $this->getOutput($tokens);
return $this->calculate($stack);
}
protected function calculate(StackData $stackData) : float
{
while (($operator = $stackData->pop()) && $operator->isOperator()) {
$value = $operator->operate($stackData);
if (!is_null($value)) {
$stackData->add(CalcItem::factory($value));
}
}
return $operator ? $operator->render() : $this->show($stackData);
}
protected function getOutput(array $tokens) : StackData
{
$output = new StackData();
$operators = new StackData();
foreach ($tokens as $token) {
$token = $this->extractVariables($token);
$expression = CalcItem::factory($token);
if ($expression->isOperator()) {
$this->parseOperator($expression, $output, $operators);
} elseif ($expression->isBrackets()) {
$this->getBrackets($expression, $output, $operators);
} else {
$output->add($expression);
}
}
while ($op = $operators->pop()) {
if ($op->isBrackets()) {
throw new \RuntimeException('Mismatched Parenthesis');
}
$output->add($op);
}
return $output;
}
protected function registerVariable($name, $value) : void
{
$this->variables[$name] = $value;
}
protected function extractVariables($token)
{
if ($token[0] === '$') {
$key = substr($token, 1);
return $this->variables[$key] ?? 0;
}
return $token;
}
protected function show(StackData $stackData) : string
{
$output = '';
while ($el = $stackData->pop()) {
$output .= $el->render();
}
if ($output) {
return $output;
}
throw new RuntimeException('Could not render output');
}
protected function getBrackets(CalcItem $expression, StackData $output, StackData $operators) : void
{
if ($expression->isOpened()) {
$operators->add($expression);
} else {
$clean = false;
while ($end = $operators->pop()) {
if ($end->isBrackets()) {
$clean = true;
break;
}
$output->add($end);
}
if (!$clean) {
throw new RuntimeException('Mismatched Parenthesis');
}
}
}
protected function parseOperator(CalcItem $expression, StackData $output, StackData $operators) : void
{
$end = $operators->getLast();
if (!$end) {
$operators->add($expression);
} elseif ($end->isOperator()) {
do {
if ($expression->isLeftAssoc() && $expression->getPrecedence() <= $end->getPrecedence()) {
$output->add($operators->pop());
} elseif (!$expression->isLeftAssoc() && $expression->getPrecedence() < $end->getPrecedence()) {
$output->add($operators->pop());
} else {
break;
}
} while (($end = $operators->getLast()) && $end->isOperator());
$operators->add($expression);
} else {
$operators->add($expression);
}
}
protected function tokenize(string $string) : array
{
$parts = preg_split(
'~(\d+|\+|\^|-|\*|/|\(|\))~',
$string,
-1,
PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE
);
return $parts;
}
} |
C++ | UTF-8 | 740 | 2.546875 | 3 | [] | no_license | #ifndef _JOEPACK_H
#define _JOEPACK_H
#include <cstdio>
#include <string>
#include <cstring>
#include <iostream>
#include <fstream>
#include <cmath>
#include <cassert>
using namespace std;
#include <map>
class JOEPACK_FADATA
{
public:
JOEPACK_FADATA() {offset = 0; length = 0;}
unsigned int offset;
unsigned int length;
};
class JOEPACK
{
private:
map < string, JOEPACK_FADATA> fat;
FILE * f;
JOEPACK_FADATA * curfa;
public:
JOEPACK() {f = NULL;curfa = NULL;}
~JOEPACK() {ClosePack();}
bool LoadPack(string fn);
void ClosePack();
bool Pack_fopen(string fn);
void Pack_fclose();
int Pack_fread(void * buffer, unsigned int size, unsigned int count);
map <string, JOEPACK_FADATA> & GetFAT() {return fat;}
};
#endif
|
PHP | UTF-8 | 1,163 | 3.0625 | 3 | [
"MIT"
] | permissive | <?php
namespace Pucene\Component\QueryBuilder\Query\TermLevel;
use Pucene\Component\QueryBuilder\Query\QueryInterface;
class Term implements QueryInterface
{
const NAME = 'term';
/**
* @var string
*/
private $field;
/**
* @var string
*/
private $term;
/**
* @param string $field
* @param string $term
*/
public function __construct($field, $term)
{
$this->field = $field;
$this->term = $term;
}
/**
* Returns field.
*
* @return string
*/
public function getField()
{
return $this->field;
}
/**
* Set field.
*
* @param string $field
*
* @return $this
*/
public function setField($field)
{
$this->field = $field;
return $this;
}
/**
* Returns term.
*
* @return string
*/
public function getTerm()
{
return $this->term;
}
/**
* Set term.
*
* @param string $term
*
* @return $this
*/
public function setTerm($term)
{
$this->term = $term;
return $this;
}
}
|
Java | UTF-8 | 2,677 | 3.140625 | 3 | [] | no_license | package _1월3주차;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class 배열에서이동 {
static int N, answer;
static int[][] map;
static int[][] direction = {{-1, 0}, {1, 0}, {0, 1}, {0, -1}};
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
N = Integer.parseInt(br.readLine());
map = new int[N + 1][N + 1];
int min = 201, max = 0;
for (int i = 1; i <= N; i++) {
StringTokenizer st = new StringTokenizer(br.readLine());
for (int j = 1; j <= N; j++) {
map[i][j] = Integer.parseInt(st.nextToken());
min = Math.min(min, map[i][j]);
max = Math.max(max, map[i][j]);
}
}
answer = 201;
int l = 0, r = max - min;
while (l <= r) {
int mid = (l + r) / 2;
if (bfs(mid)) {
l = mid + 1;
} else {
r = mid - 1;
}
}
System.out.println(answer);
}
private static boolean bfs(int target) {
Queue<Position> queue = new LinkedList<>();
boolean[][] visited = new boolean[N + 1][N + 1];
queue.add(new Position(1, 1, 201, 0));
visited[1][1] = true;
int result = 201;
while (!queue.isEmpty()) {
Position now = queue.poll();
if (now.x == N && now.y == N) {
System.out.println("max:" + now.max + " min:" + now.min + " diff:" + (now.max - now.min));
result = Math.min(result, now.max - now.min);
}
for (int[] dir : direction) {
int nx = now.x + dir[0];
int ny = now.y + dir[1];
if (nx < 1 || ny < 1 || nx > N || ny > N || visited[nx][ny]) continue;
// if(now.min > target || now.max < target) continue;
visited[nx][ny] = true;
queue.add(new Position(nx, ny,
Math.min(now.min, map[nx][ny]),
Math.max(now.max, map[nx][ny])
));
}
}
System.out.println("target = " + target + " result = " + result);
return target < result;
}
static class Position {
int x, y, min, max;
Position(int x, int y, int min, int max) {
this.x = x;
this.y = y;
this.min = min;
this.max = max;
}
}
}
|
Java | UTF-8 | 994 | 2.859375 | 3 | [] | no_license | package com.zyblogs.concurrency.pattern.chapter04;
import lombok.Getter;
/**
* @Title: ObservableRunnable.java
* @Package com.zyblogs.concurrency.pattern.chapter04
* @Description: TODO
* @Author ZhangYB
* @Version V1.0
*/
public abstract class ObservableRunnable implements Runnable {
final protected LifecycleListener listener;
public ObservableRunnable(final LifecycleListener listener) {
this.listener = listener;
}
protected void notifyChange(final RunnableEvent event) {
listener.onEvent(event);
}
public enum RunnableState {
RUNNING, ERROR, DONE;
}
@Getter
public static class RunnableEvent {
private final RunnableState state;
private final Thread thread;
private final Throwable cause;
public RunnableEvent(RunnableState state, Thread thread, Throwable cause) {
this.state = state;
this.thread = thread;
this.cause = cause;
}
}
}
|
JavaScript | UTF-8 | 10,124 | 3.234375 | 3 | [] | no_license | /*CodularHome • Writers • RSS Starting with Node and Web Sockets
Let us worry about building your integrations. Focus on your core product.
ads via Carbon
Introduction
Web Sockets are probably in use more around you now than you think, most things with real-time interactions are most probably running through these little gems. Web sockets are commonly used with a suitable polyfill used where they're not fully supported.
They're great for instant transfers of data from one machine to one or many other connected clients, used in things like instant chats, collaborative sketch environments and many more. Unfortunately support is still only in recent browsers so we can look to use a polyfill, or third party library to help - one of the best being socket.io.
Here we'll be covering the basics of using Web Sockets with node.js, and not using socket.io.
node.js
This is a great platform that is built on the same JavaScript engine that is used in Google Chrome, and is event driven making it ideal for the situation where you want to use Web Sockets. For this article, you'll need access to somewhere which has node installed and an IP address (or domain) you can access it on. We're going to be using a micro instance on Amazon EC2, as it's a cheap effective way to play around.
Getting Started
We're going to split this into two parts, one that is the server side, and one that is the client side. This is a very basic example, and will not include any security checking as that is well outside the scope of this for now. But you should be aware of checking the origin of requests, and ensuring they come from where you're expecting. Also, escaping HTML etc, if you're injecting returned strings straight into your DOM as HTML content.
Server Side (node)
There are a few steps that we need to follow to get the node side working, these are:
Create instance of the server and listen to a specific port
Create a web socket server
Listen for connections
Callback for connections
Create server and listen
For this, we need to require the http library, and then create a new server:
*/
var http = require('http');
var server = http.createServer(function(request, response) {});
//We're using an empty function within the createServer, as we're not actually serving anything through a HTTP request. Next, we need to tell this server to listen on a particular port, for fun we'll use the port 1234:
server.listen(1234, function() {
console.log((new Date()) + ' Server is listening on port 1234');
});
/*The first parameter here is the port that we want to listen two, and the second is a function that is a callback method, we've just thrown a quick message output to let us know that it's connected.
We now have a server that's running and listening on port 1234, we now need to use this to create our WebSocket Server:
Create Web Socket Server
We now create the Web Socket Server on the back of the HTTP server that we established. Here we need to require the websocket library. If this isn't available you will need to use npm to install it. Onwards:
*/
var WebSocketServer = require('websocket').server;
wsServer = new WebSocketServer({
httpServer: server
});
/*We now have a web socket server that is running, and available for us to start adding some event listeners. In this case, we want to add one for when a new request to join is made:
Listening for Connections
To do this, we use the .on method within the WebSocketServer object that we have created previously, listening for the event request. We then provide a callback where we will then put all of our code which will execute when someone joins to the socket server.
*/
wsServer.on('request', function(r){
// Code here to run on connection
});
/*We can now move on to the bulk of the code that will fit within these connections:
Callback for connections
This is the code that will be placed within that function outlined above, this has a few purposes to fulfill:
Accept the connection
Store connected clients
Listen for incoming messages and broadcast messages to clients
Listen for a client disconnecting and remove from list of clients
Accept the connection
We must accept the connection before we can do anything with it, this gives us an object that represents that client that is connected. We're going to be using the echo-protocol for the connection, and using the accept method within the request object that is passed into the callback as a parameter (which we have identified as r):
*/
var connection = r.accept('echo-protocol', r.origin);
/*
Now, we can use this connection to send messages to the client, or add specific listeners for the client etc.
Store connected clients
Now, we need to create an object that will have the clients in as well as an incrementing number to identify each client. These must sit outside of this event listener:
*/
var count = 0;
var clients = {};
//Next, within the event listener, we need to store the id for this client, and cache their connection to the clients:
// Specific id for this client & increment count
var id = count++;
// Store the connection method so we can loop through & contact all clients
clients[id] = connection;
//Note: We can quickly throw in a quick logging message to show that we have a new client connected:
console.log((new Date()) + ' Connection accepted [' + id + ']');
/*Listen for incoming messages and broadcast
Now, we can attach event listeners to the connection, meaning we can add one for when we get a message from the client to the server. Within this, we want to take the message that they have sent us, and simply send it out to every other client that is connected. Super, super simple:
*/
// Create event listener
connection.on('message', function(message) {
// The string message that was sent to us
var msgString = message.utf8Data;
// Loop through all clients
for(var i in clients){
// Send a message to the client with the message
clients[i].sendUTF(msgString);
}
});
/*Realistically, you wouldn't want to just send a message around like this, you'd want to send something more refined to the other clients, this in most cases would be a JSON string which carries other meta-data, such as time and sender.
Listen for client disconnecting
This is as simple as listening for the close event, and then deleting the disconnecting client from the client storage object. We'll throw in a console message just for fun, and to keep track of things!*/
connection.on('close', function(reasonCode, description) {
delete clients[id];
console.log((new Date()) + ' Peer ' + connection.remoteAddress + ' disconnected.');
});
//We now have a very basic system setup now on the server side that should accept web socket connections and broadcast our message out to every connected client. Next, we need to work on the front end.
/*Client Side (HTML/JS)
We're going to be using standard JavaScript, no need for that jQuery nonsense here. Sure, you can make things slide in, and out more easily and make it all beautiful but ... we're learning, not beautifying!
Crack open your favourite editor, and lay out the key elements:
A div for the messages from the server to go in (give it an id of chatlog)
An input of type button that will send the message out.
An input of type text that will have the message entered (give it an id of message)
note: ids are dirty, but that's cool as we're learning, not making production ready code
JavaScript
Here is where we bring the whole thing to life. The logic is this:
Connect to the web socket server
When the button is pressed send out our message to the server
Listen to a response from the server, add it to the chatlog div that we created
Connect to web socket server
This can't be easier, we instantiate a new instance of the WebSocket object, and pass it two parameters:
Address of the web socket server, including the port. Note: we need to use the ws protocol here, not http
The protocol we're using for this transfer as we outlined in our node script we need echo-protocol
Let's go:
*/
var ws = new WebSocket('ws://some-address-here.com:1234', 'echo-protocol');
/*Now we have an active web socket connection, if you're doing this in increments and run this now with the node script running, you should see a new connection logged in the console on your server.
Send our message to the server
We're not going to be doing much fancy stuff here, we're going to add an event to the button - be dirty, do it inline, I dare you - that will use the send method of our web socket server to send our message:*/
function sendMessage(){
var message = document.getElementById('message').value;
ws.send(message);
}
/*Simple as that, nothing complicated, nothing hard. Now, there's no real point testing that, as we'll not get any response or anything at the moment. However, let's throw in an event listener for when the server sends us a message:*/
/*Listen for server response
Now, we just write an event listener, and take the message that's passed to use and append it to the div. We're going to be super dirty, and use innerHTML. But realistically you should use DOM manipulation, because it's faster.*/
ws.addEventListener("message", function(e) {
// The data is simply the message that we're sending back
var msg = e.data;
// Append the message
document.getElementById('chatlog').innerHTML += '<br>' + msg;
});
/*Now you should be able to throw everything together, and talk to yourself. If you want to try with more people simply open a new window and run the page in that.
When you disconnect you should see a console message stating that someone has disconnected, and the unique id of that user.*/
ws.send('Conclusion');
/*This was a super super simple introduction to some Node and Web Socket fun. Nothing too complex, but enough to get started on the basics for what could be used for real time gaming, conversations or anything that requires some data transfer in real time. Remember it's best to cache elements in JavaScript, and to optimise your code, but that's for you to do.*/
|
Markdown | UTF-8 | 312 | 2.515625 | 3 | [] | no_license | # Animated-Display
This is terminal based script which asks for your name and displays it like a moving banner.
It is made using python as a part of learning python.
# How To Run?
- Download this repo
- run `python display.py` in terminal
- Enter Your Name and see the magic :wink:
# Screens

|
Java | UTF-8 | 568 | 2.4375 | 2 | [] | no_license | public class VIP extends Vartotojas
{
public VIP()
{
}
public VIP(String username, String password)
{
super(username, password);
}
public VIP(String username, String password, int gimDataMetai, int gimDataMenuo, int gimDataDiena)
{
super(username, password, gimDataMetai, gimDataMenuo, gimDataDiena);
}
@Override
public String vartotojoIsvedimas()
{
String tempTekstas = super.vartotojoIsvedimas();
tempTekstas += "\n" + "ŠIS VARTOTOJAS YRA: VIP";
return tempTekstas;
}
}
|
Java | UTF-8 | 823 | 2.4375 | 2 | [] | no_license | package vpamok;
import org.junit.Assert;
import org.junit.Test;
public class SymDogTest {
SymDog underTest = new SymDog("", "");
@Test
public void shouldRustFromTick() {
underTest.tick();
int result = underTest.getRust();
Assert.assertEquals(10, result);
}
@Test
public void shouldDecreaseHealthFromRust() {
underTest.tick();
underTest.tick();
underTest.tick();
int result = underTest.getHealth();
Assert.assertEquals(80, result);
}
// @Test
// public void oilShouldReduceRust() {
// underTest.giveOil();
// }
@Test
public void shouldHaveInheritedHappy() {
int result = underTest.getHappiness();
Assert.assertEquals(50, result);
}
@Test
public void shouldIncreaseHappyFromWalk() {
underTest.walk();
int result = underTest.getHappiness();
Assert.assertEquals(65, result);
}
}
|
C# | UTF-8 | 3,764 | 3.21875 | 3 | [] | no_license | using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace OOPClassObjectLesson1
{
public partial class Default : System.Web.UI.Page
{
// Random random = new Random();
protected void Page_Load(object sender, EventArgs e)
{
//Car MyNewCar = new Car();
// string[] Cars = new string[] { MyNewCar.carColor(), MyNewCar.carColor(), MyNewCar.carColor() };
}
private void displayImage(string[] carColors)
{
Image1.ImageUrl = "/Images/" + carColors[0] + ".jpg";
Image2.ImageUrl = "/Images/" + carColors[1] + ".jpg";
Image3.ImageUrl = "/Images/" + carColors[2] + ".jpg";
}
public void Button1_Click(object sender, EventArgs e)
{
Car MyNewCar = new Car();
MyNewCar.Make = "oldschool";
MyNewCar.Model = "mercedez";
MyNewCar.Year = 1867;
MyNewCar.color = "White";
string[] Cars = new string[] { MyNewCar.carColor(), MyNewCar.carColor(), MyNewCar.carColor() };
displayImage(Cars);
resultLabel.Text = String.Format("The price of this Car is:{0:C},and the colors is:{1}-Make:{2}-Model:{3}-Year:{4}", evaluateCarPrice(Cars),
typeColor(Cars, MyNewCar), MyNewCar.Make, MyNewCar.Model, MyNewCar.Year);
}
// determine how many white cars
private int determineWhiteCars(string[] Cars)
{
int whiteCount = 0;
if (Cars[0] == "White") whiteCount++;
if (Cars[1] == "White") whiteCount++;
if (Cars[2] == "White") whiteCount++;
return whiteCount;
}
// if there are 3 whites cars in the spin return the price to get the cars with bonus
private int CarsPriceBonus(string[] cars)
{
int whiteCount = determineWhiteCars(cars);
if (whiteCount == 1) return 2000;
if (whiteCount == 2) return 4000;
if (whiteCount == 3) return 1000;
return 0;
}
private int evaluateCarPrice(string[] cars)
{
if (isOtherColors(cars))return 0;
int amount = 0;
if (iswhitecars(cars, out amount)) return amount;
return 0;
}
private bool isOtherColors(string[] cars)
{
if (cars[0] != "White" || cars[1] != "White" || cars[2] != "White") return true;
return false;
}
private bool iswhitecars(string[] cars, out int amount)
{
amount = CarsPriceBonus(cars);
if (amount > 0)
return true;
return false;
}
private string typeColor(string[] cars, Car Mycar)
{
if(cars[0]=="White" || cars[1] == "White" || cars[2] == "White")
return Mycar.color;
return "We are dealing with White Cars";
}
}
class Car
{
Random random = new Random();
public string Make { get; set; } // is just like any variable I have work with thus far;
public string Model { get; set; } //but it is meant to describe the attributes that are common to object's class.
public int Year { get; set; }
public string color { get; set; }
public string carColor()
{
string[] carColor = new string[] {"White"};
return carColor[random.Next(0)];
}
}
}
|
C# | UTF-8 | 1,453 | 2.671875 | 3 | [
"MIT"
] | permissive | //TODO: Get your AppSID and AppKey at https://dashboard.groupdocs.cloud (free registration is required).
using GroupDocs.Classification.Cloud.Sdk.Api;
using GroupDocs.Classification.Cloud.Sdk.Model;
using GroupDocs.Classification.Cloud.Sdk.Model.Requests;
using System;
namespace GroupDocs.Classification.Cloud.Examples.CSharp
{
// Classify Document from Storage
class Classify_Document_from_Storage
{
public static void Run()
{
var configuration = new Configuration
{
AppSid = Common.MyAppSid,
AppKey = Common.MyAppKey
};
var apiInstance = new ClassificationApi(configuration);
try
{
var request = new ClassifyRequest(new BaseRequest()
{
Document = new FileInfo()
{
Name = "one-page.docx",
Folder = ""
},
},
bestClassesCount: "3");
// Get classification results
ClassificationResponse response = apiInstance.Classify(request);
Console.WriteLine(response.ToString());
}
catch (Exception e)
{
Console.WriteLine("Exception when calling ClassificationApi: " + e.Message);
}
}
}
} |
Java | UTF-8 | 1,360 | 2.34375 | 2 | [] | no_license | package com.springweb.controller;
import java.util.List;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.springweb.model.Offer;
import com.springweb.service.OfferServiceImpl;
@Controller
public class OffersController {
private OfferServiceImpl offerservice;
@Autowired
public void setOfferservice(OfferServiceImpl offerservice) {
this.offerservice = offerservice;
}
@RequestMapping(value = "/offer")
public String showOffer(Model model) {
List<Offer> getdata = offerservice.getOffers();
model.addAttribute("hello", getdata);
return "offer";
}
@RequestMapping(value = "/create", method = RequestMethod.GET)
public String OfferCreate() {
return "createOffer";
}
@RequestMapping(value = "/created", method = RequestMethod.POST)
public String OfferCreateted( @Valid @ModelAttribute("offer") Offer offer, BindingResult result) {
if (result.hasErrors()) {
return "createOffer";
}
offerservice.create(offer);
return "createdOffer";
}
}
|
Markdown | UTF-8 | 609 | 2.640625 | 3 | [] | no_license | # 浏览器插件
## 安装依赖项
```shell
npm install
```
## 项目打包
> 打包之后会生成一个`dist`文件夹,浏览器加载插件时,选择该文件夹。
```shell
npm build
```
## 插件配置文件
> 加载插件之前,需要将`dist2`文件夹下的`4`个文件,拷贝到`dist`文件夹下。
```
dist2
|__ js
|__ background.js
|__ content.js
|__ logo.png
|__ manifest.json
```
## 加载浏览器插件
> 文件拷贝到`dist`文件夹之后,在浏览器中输入网址[chrome://extensions/](chrome://extensions/),打开扩展程序管理页面。
|
Ruby | UTF-8 | 812 | 2.84375 | 3 | [
"MIT"
] | permissive | require "socket"
require "rufus-json"
class Statsd
def initialize(host = "localhost", port = 8125)
@host = host
@port = port
@socket = UDPSocket.new
end
def time(stat)
start = Time.now
result = yield
timing(stat, ((Time.now - start) * 1000).round)
result
end
def inc(stat, delta = 1)
announce :action => "inc", :delta => delta, :name => stat
end
def dec(stat, delta = 1)
announce :action => "dec", :delta => delta, :name => stat
end
def mark(stat, count = 1)
announce :action => "mark", :count => count, :name => stat
end
private
def timing(name, duration)
announce :action => "timing", :duration => duration, :name => name
end
def announce(hash)
@socket.send(Rufus::Json.encode(hash), 0, @host, @port)
end
end
|
Java | UTF-8 | 3,194 | 1.671875 | 2 | [] | no_license | package com.lucianms.constants.skills;
public class Aran {
public static final int BLESSING_OF_THE_FAIRY = 20000012;
public static final int TUTORIAL_SKILL1 = 20000014;
public static final int TUTORIAL_SKILL2 = 20000015;
public static final int TUTORIAL_SKILL3 = 20000016;
public static final int TUTORIAL_SKILL_COMBO = 20000017;
public static final int TUTORIAL_SKILL5 = 20000018;
public static final int FOLLOW_THE_LEAD = 20000024;
public static final int THREE_SNAILS = 20001000;
public static final int RECOVERY = 20001001;
public static final int AGILE_BODY = 20001002;
public static final int LEGENDARY_SPIRIT = 20001003;
public static final int MONSTER_RIDER = 20001004;
public static final int ECHO_OF_HERO = 20001005;
public static final int JUMP_DOWN = 20001006;
public static final int MAKER = 20001007;
public static final int BAMBOO_THRUST = 20001009;
public static final int INVINCIBLE_BARRIER = 20001010;
public static final int METEO_SHOWER = 20001011;
public static final int HELPER = 20001013;
public static final int YETI_RIDER = 20001019;
public static final int RAGE_OF_PHARAOH = 20001020;
public static final int YETI_MOUNT = 20001022;
public static final int WITCHS_BROOMSTICK = 20001023;
public static final int BARLOG_MOUNT = 20001031;
public static final int PIGS_WEAKNESS = 20009000;
public static final int STUMPS_WEAKNESS = 20009001;
public static final int SLIMES_WEAKNESS = 20009002;
public static final int COMBO_ABILITY = 21000000;
public static final int DOUBLE_SWING = 21000002;
public static final int COMBAT_STEP = 21001001;
public static final int POLEARM_BOOSTER = 21001003;
public static final int POLEARM_MASTERY = 21100000;
public static final int TRIPLE_SWING = 21100001;
public static final int FINAL_CHARGE = 21100002;
public static final int COMBO_SMASH = 21100004;
public static final int COMBO_DRAIN = 21100005;
public static final int BODY_PRESSURE = 21101003;
public static final int COMBO_CRITICAL = 21110000;
public static final int FULL_SWING = 21110002;
public static final int FINAL_CROSS = 21110003;
public static final int COMBO_PENRIL = 21110004;
public static final int ROLLING_SPIN = 21110006;
public static final int HIDDEN_FULL_SWING_DOUBLE_SWING = 21110007;
public static final int HIDDEN_FULL_SWING_TRIPLE_SWING = 21110008;
public static final int SMART_KNOCKBACK = 21111001;
public static final int SNOW_CHARGE = 21111005;
public static final int HIGH_MASTERY = 21120001;
public static final int OVER_SWING = 21120002;
public static final int HIGH_DEFENSE = 21120004;
public static final int FINAL_BLOW = 21120005;
public static final int COMBO_TEMPEST = 21120006;
public static final int COMBO_BARRIER = 21120007;
public static final int HIDDEN_OVER_SWING_DOUBLE_SWING = 21120009;
public static final int HIDDEN_OVER_SWING_TRIPLE_SWING = 21120010;
public static final int MAPLE_WARRIOR = 21121000;
public static final int FREEZE_STANDING = 21121003;
public static final int HEROS_WILL = 21121008;
} |
Markdown | UTF-8 | 4,792 | 3.1875 | 3 | [] | no_license | ---
author: hzmangel
categories:
- Happy coding
date: '2013-05-07T23:30:25'
tags:
- Programming
- rails
title: Uploading multiple attachments with carrierwave/mongoid/nested_form
---
Recently I have met a requirement that need to upload multiple attachments to
a rails project. After some investigations, I choose `carrierwave` finally.
Also, I selected `nested_form` to manage uploading and deleting multiple
attachments.<!--more-->### Gemfile
First thing to use those gems is updating `Gemfile` in the project, so those
lines have been added to the file:
# Mongoid
gem "mongoid"
# File upload
gem 'carrierwave'
gem 'carrierwave-mongoid', :require => 'carrierwave/mongoid'
gem "mini_magick"
# Form for multi model
gem 'nested_form'
After the modification, remember to run `bundle update` to update/install the
gems and dependencies.
### Model
The next step is creating the models. For simplicity, there are only two
models in the project. One model named `Foo`, which contains a title field and
a relationship field with the other model `FooImage`. Here is the definition
of model `Foo`.
class Foo
include Mongoid::Document
field :title, type: String
has_many :foo_images # Photoes of the dish
accepts_nested_attributes_for :foo_images, :allow_destroy => true
end
The `accepts_nested_attributes_for` keyword enables saving associated records
though the parent, while the `:allow_destroy` parameter allows deleting
associated though attributes hash.
Here comes the `FooImage` model:
class FooImage
include Mongoid::Document
attr_accessible :image
mount_uploader :image, FooUploader
belongs_to :foo
end
This model only contains one field `:image`, and the difference between others
is the `mount_uploader` keyword, which is used to mount given uploader to the
given column, then assigning and reading from this field will upload and
retrieve files. The _uploader_ is introduced by `carrierwave`, which will be
introduced in next section.
### Uploader
Uploader is used to handle the file uploaded to the server, which will save
the file to specified location with multiple version. A uploader can be
created by the command listed below:
rails g uploader Foo
A new uploader `foo_uploader.rb` will be generated under directory
`app/uploaders/` after command return. The uploader generated by default can
handle file uploading, and you can add some other function, such as scaling
image, set whitelisted extension, in the uploader. Remember to remove the
comment character from either `CarrierWave::RMagick` or
`CarrierWave::MiniMagick` line to enable scaling function. `Carrierwave` alwo
support uploading file to cloud storage such as s3 directly, please refer to
the document for detail. In this uploader, I scale the uploaded image to
`800x600` and add a thumbnail version with size `80x60`, here is the code:
process :resize_to_fill => [800, 600]
version :thumb do
process :resize_to_fill => [80, 60]
end
**NOTICE**: The generated uploader uses `scale` for resizing, remember to replace it with existing function like `resize_to_fill`.
### Views
The last thing is the view. I plan to use two views in the project. Since this
is just a simple demo, I have only created one record and shown the title and
images with table.
By the way, if you want to deploy this application on production environment,
please make sure those two configuration:
* Make sure your web server, such as `Nginx`, `Apache`, has write permission to its temp path. If you don't know which directory is it, you can use this simple method to determine: First, check whether the production server can complete process of uploading attachment (Just uploading only, showing of image may have another problem which will be talked about below ). If there is no error, then the permission issue has already done. But if error occurred, please refer to the error log or access log of web server for tracing.
* Now the second problem, showing the image. After uploading successfully, you may can't see the uploaded file. The problem is because production server do not serve static files. The quick fix for this is changing line `config.serve_static_assets = false` to `true`, but it is not the recommended way, since the production server can't server static file efficiently. The better method is configuring web server to serve those static file directly, please refer to web server's manual for detail.
So, that's it. Thanks for reading, and here is the [link of project on
GitHub](https://github.com/hzmangel/carrierwave-nestedform-mongoid), any
comments are appreciated. |
Java | UTF-8 | 2,024 | 3.53125 | 4 | [] | no_license | package main.java.Objekt;
import java.util.ArrayList;
/**
* Created by Spiks on 2016-04-08.
* In the project Buss_System
*/
/**
* A Object that represents the line a buss will take.
* The Line id is a two digit number.
* More information about the stops and buss can be found in theyre files.
*/
public class Line {
private String id;
private ArrayList<Stop> stops = new ArrayList<>();
private Buss buss = new Buss();
private Stop source = new Stop();
private Stop dest = new Stop();
public Line (String id, Buss buss){
this.id = id;
this.buss = buss;
}
public Line (){}
public Stop getSource() {
return source;
}
public void setSource(Stop source) {
this.source = source;
}
public Stop getDest() {
return dest;
}
public void setDest(Stop dest) {
this.dest = dest;
}
public Buss getBuss() {
return buss;
}
public void setBuss(Buss buss) {
this.buss = buss;
}
public void setId(String inId){
id = inId;
}
public String getId(){
return id;
}
public void addStops(Stop stop){
stops.add(stop);
}
public void setStops(ArrayList<Stop> Stops){
this.stops = Stops;
}
public ArrayList<Stop> getStops(){
return stops;
}
public void removeStop(String stopId){
for (int i = 0; i < stops.size(); i++){
if (stops.get(i).getId().equals(stopId)){
stops.remove(i);
}
}
}
public void updateStop(String id, String name, String loc){
stops.stream().forEach(stop1 -> {
if (stop1.getId().equals(id)){
stop1.setName(name);
stop1.setLocation(loc);
}
});
}
public String toString(){
for (int i = 0; i < stops.size(); i++){
System.out.println("Buss Stop: " + stops.get(i).toString());
}
return "I got this";
}
}
|
Java | UTF-8 | 249 | 1.5 | 2 | [] | no_license | package com.bjsxt.service;
import com.bjsxt.common.pojo.DataResult;
import javax.xml.crypto.Data;
public interface ItemParamService {
DataResult selectItemParamByid(Long cid);
DataResult insertItemParam(Long itemCid,String paramData);
}
|
Java | UTF-8 | 504 | 1.898438 | 2 | [] | no_license | package com.yc.springframework;
import com.yc.bean.HelloWorld;
import com.yc.springframework.stereotype.MyBean;
import com.yc.springframework.stereotype.MyComponentScan;
import com.yc.springframework.stereotype.MyConfiguration;
/**
* @program: testspring
* @description:
* @author: ErFeng_V
* @create: 2021-04-05 11:46
*/
@MyConfiguration
@MyComponentScan(basePackages ={"com.yc.bean"})
public class MyAppConfig {
@MyBean
public HelloWorld hw2(){
return new HelloWorld();
}
}
|
JavaScript | UTF-8 | 4,757 | 2.515625 | 3 | [
"MIT"
] | permissive | (function (angular) {
'use strict';
angular
.module('cogeoApp')
.factory('directMessagesFactory', directMessagesFactory);
directMessagesFactory.$inject = [
'httpRequest',
'$rootScope',
'cozenEnhancedLogs'
];
function directMessagesFactory(httpRequest, $rootScope, cozenEnhancedLogs) {
var messages = [];
// Public functions
return {
subscribe : subscribe,
getMessages : getMessages,
updateMessage: updateMessage,
addMessage : addMessage,
httpRequest : {
getMessages : httpRequestGetMessages,
addMessage : httpRequestAddMessage,
editMessage : httpRequestEditMessage,
removeMessage: httpRequestRemoveMessage
}
};
function subscribe(scope, callback) {
var handler = $rootScope.$on('directMessagesFactoryMessagesChanged', callback);
scope.$on('$destroy', handler);
}
function _notify() {
$rootScope.$emit('directMessagesFactoryMessagesChanged');
}
function getMessages(username1, username2, autoFetchFromDatabase) {
var myMessages = {
messages: []
};
if (Methods.isNullOrEmptyStrict(autoFetchFromDatabase)) {
autoFetchFromDatabase = true;
}
for (var i = 0, length = messages.length; i < length; i++) {
if ((messages[i].username1 == username1 && messages[i].username2 == username2)
|| (messages[i].username1 == username2 && messages[i].username2 == username1)) {
myMessages = messages[i];
}
}
// Get messages from database
if (autoFetchFromDatabase) {
httpRequestGetMessages({
username1: username1,
username2: username2
}, function (response) {
updateMessage(response.data.data);
});
}
return myMessages;
}
function updateMessage(newMessage) {
for (var i = 0, length = messages.length; i < length; i++) {
if (messages[i]._id == newMessage._id) {
messages[i].messages = newMessage.messages;
break;
}
}
messages.push(newMessage);
_notify();
}
function addMessage(messageId, newMessage) {
for (var i = 0, length = messages.length; i < length; i++) {
if (messages[i]._id == messageId) {
messages[i].messages.push(newMessage);
break;
}
}
_notify();
}
/// HTTP REQUEST ///
function httpRequestGetMessages(data, callbackSuccess, callbackError) {
httpRequest.requestPost('direct-messages/get', data, callbackSuccess, callbackError)
.then(function (response) {
})
;
}
function httpRequestAddMessage(messageId, data, callbackSuccess, callbackError) {
httpRequest.requestPost('direct-messages/' + messageId + '/add', data, callbackSuccess, callbackError)
.then(function (response) {
addMessage(messageId, response.data.data);
cozenEnhancedLogs.explodeObject(response.data.data, true);
// The bot answered this message
if (!Methods.isNullOrEmpty(response.data.newBotMessage)) {
cozenEnhancedLogs.info.customMessage('directMessagesFactory', 'New bot message');
addMessage(messageId, response.data.newBotMessage);
cozenEnhancedLogs.explodeObject(response.data.newBotMessage, true);
}
})
;
}
function httpRequestEditMessage(messageId, data, callbackSuccess, callbackError) {
httpRequest.requestPut('direct-messages/' + messageId + '/edit', data, callbackSuccess, callbackError)
.then(function (response) {
updateMessage(response.data.data);
})
;
}
function httpRequestRemoveMessage(messageId, data, callbackSuccess, callbackError) {
httpRequest.requestPut('direct-messages/' + messageId + '/remove', data, callbackSuccess, callbackError)
.then(function (response) {
updateMessage(response.data.data);
})
;
}
}
})(window.angular);
|
Python | UTF-8 | 3,532 | 3.25 | 3 | [] | no_license | import numpy as np
import matplotlib.pyplot as plt
'''
Transfer matrix method
Inputs
wvl: wavelength
fulln: array with all refractive indices
fullw: array with all layer widths
Outputs:
r: reflection coefficient
t: transmission coefficient
x: position
Nn: refractive indices (vs x)
E: optical field (vs x)
'''
def tmm(wvl, fulln, fullw):
# Exponent factors
d = fullw*2*np.pi/wvl*fulln
# Initiate arrays
x = []
E = []
Nn = []
N = len(fulln)
M = np.zeros((2,2,N-1),dtype=complex)
rs = np.zeros(N-1)
ts = np.zeros(N-1)
# Loop through layers
for ii in range(N-1):
# n of adjacent layers
n1 = fulln[ii]
n2 = fulln[ii+1]
# Fresnel relations
rs[ii] = (n1 - n2)/(n1+n2)
ts[ii] = 2*n1/(n1+n2)
# Compose transfer matrix
M[:,:,ii] = np.dot([[np.exp(-1j*d[ii]),0],
[0,np.exp(1j*d[ii])]],
[[1, rs[ii]],[rs[ii],1]]) * 1/ts[ii]
# Multiply with full matrix (if exists)
if ii >= 1:
Mt = np.dot(Mt,M[:,:,ii])
else:
Mt = M[:,:,0]
# Reflection and transmission coefficients
r = Mt[1,0]/Mt[0,0]
t = 1/Mt[0,0]
# Initiate arrays
v1 = np.zeros(len(fullw),dtype=complex)
v2 = np.zeros(len(fullw),dtype=complex)
v1[0] = 1
v2[0] = r
for ii in range(1,N):
# Coefficients
vw = np.linalg.solve(M[:,:,ii-1], [v1[ii-1],v2[ii-1]])
v1[ii] = vw[0]
v2[ii] = vw[1]
# Location array
xloc = np.arange(0,fullw[ii],5)
# Electric fields
Eloc1 = v1[ii]*np.exp(1j*2*np.pi/wvl*fulln[ii]*xloc)
Eloc2 = v2[ii]*np.exp(-1j*2*np.pi/wvl*fulln[ii]*xloc)
# Append to arrays
x = np.hstack((x,xloc+sum(fullw[:ii])))
E = np.hstack((E,(Eloc1+Eloc2)))
Nn = np.hstack((Nn,fulln[ii]+(xloc*0)))
# Sort arrays()
ix = np.argsort(x)
x = x[ix]
E = E[ix]
Nn = Nn[ix]
return r, t, x, Nn, E
######################################
## Example DBR
if __name__ == "__main__":
# Wavelength (in nm)
wvl = 1000
# Refractive indices
n2 = 1.38
n1 = 2.32
n0 = 1
ns = 1.5
# Number of layers
Nstk = 4
# Mirror stack n and width
Mirrn = np.tile([n1,n2],Nstk)
Mirrw = np.tile([wvl/(4*n1),wvl/(4*n2)],Nstk)
# Add air and substrate
fulln = np.insert([1,n0,ns],2,Mirrn)
fullw = np.insert([0,wvl/n0,wvl/ns],2,Mirrw)
# Run transfer matrix function
r,t,x,Nn,E = tmm(wvl,fulln, fullw)
# Units in um and offset
x = x/1e3-1
# Plot n and E
fig, ax = plt.subplots(2,1,sharex=True)
ax[0].plot(x,Nn,'b')
ax[0].set_ylabel('Refractive index n')
ax[0].set_title('r = %.5f, t = %.5f' %(abs(r),abs(t)))
ax[1].plot(x,abs(E)**2,'r')
ax[1].set_ylabel('Normalized |E|^2')
ax[1].set_xlabel('Distance (um)')
ax[1].set_xlim([min(x),max(x)])
# Redefine (fixed) mirror
Mirrw = np.tile([107.7586,181.1594],Nstk)
fullw = np.insert([0,1000,666.6667],2,Mirrw)
# Wavelengths array
wvls = np.linspace(wvl-600,wvl+600,301)
# Loop through wavelengths
R = []
for ii in range(len(wvls)):
r,t,x,Nn,E = tmm(wvls[ii],fulln, fullw)
R.append(abs(r)**2 * 100)
# Plot reflectance vs wvls
plt.figure()
plt.plot(wvls,R,'b')
plt.ylabel('Reflectance (%)')
plt.xlabel('Wavelength (nm)')
plt.xlim(min(wvls),max(wvls))
plt.ylim(0,100)
plt.show()
|
Java | UTF-8 | 899 | 2.46875 | 2 | [] | no_license | package task1.job8;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Mapper;
import java.io.IOException;
/**
* Created by guichi on 18/04/2015.
*/
public class FinalMapper extends Mapper<LongWritable,Text,IntWritable,Text>{
@Override
protected void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
String line =value.toString();
String [] parts=line.split("\t");
String []lineParts=parts[1].split("\\$");
int rank=Integer.parseInt(lineParts[0]);
String tagcount=parts[0];
String countryCount=lineParts[1];
String url=lineParts[2];
String tag=lineParts[3];
context.write(new IntWritable(rank),new Text(url+"\t"+countryCount+"\t"+tag+"\t"+tagcount+"\t"));
}
}
|
Java | UTF-8 | 1,025 | 2.703125 | 3 | [] | no_license | package me.johnkagga.funbook.Model;
import android.graphics.Color;
/**
* Created by John Kagga on 7/5/2015.
*/
public class FactPage {
private String mFactNumber;
private String mFactText;
private String mColor;
private Choice mChoice1;
private Choice mChoice2;
public FactPage(String factNumber, String factText, String color, Choice choice1, Choice choice2) {
mFactNumber = factNumber;
mFactText = factText;
mColor = color;
mChoice1 = choice1;
mChoice2 = choice2;
}
public String getFactNumber() {
return mFactNumber;
}
public String getFactText() {
return mFactText;
}
public String getColor() {
return mColor;
}
public Choice getChoice1() {
return mChoice1;
}
public Choice getChoice2() {
return mChoice2;
}
/*
This method converts a hex string into an int
*/
public int factColor(String color){
return Color.parseColor(color);
}
}
|
TypeScript | UTF-8 | 130 | 2.546875 | 3 | [] | no_license | export interface ITasks {
id: string;
text: string;
isComplited?: boolean;
}
export interface IState {
tasks: ITasks[];
}
|
JavaScript | UTF-8 | 331 | 3.359375 | 3 | [] | no_license | function largest()
{
var tCount = [];
for (var x = 0; x < 3; x++)
{
var t = prompt("Number plz" + "("+x+")");
tCount.push(t);
}
var v = 0;
for(var y = 0; y < 3; y++)
{
if(v < parseInt(tCount[y] - tCount[y + 1]))
{
v = tCount[y];
}
}
alert("Sum is: " + v);
}
$(document).ready(function (){
largest();
}) |
PHP | UTF-8 | 427 | 2.59375 | 3 | [] | no_license | <?php
namespace hypeJunction\Scraper;
use Elgg\Hook;
use hypeJunction\Fields\Collection;
class AddFormField {
/**
* Add slug field
*
* @param Hook $hook Hook
*
* @return mixed
*/
public function __invoke(Hook $hook) {
$fields = $hook->getValue();
/* @var $field Collection */
$fields->add('web_location', new WebLocationField([
'type' => 'url',
'priority' => 415,
]));
return $fields;
}
}
|
Python | UTF-8 | 509 | 3.046875 | 3 | [] | no_license | import pandas as pd
df = pd.read_csv('D:\Labs\python\datos.csv', sep=';')
import matplotlib.pylab as plt
plt.scatter(df['alcohol'], df['quality'])
plt.xlabel('Alcohol')
plt.ylabel('Quality')
plt.title('Alcohol Against Quality')
plt.show()
from sklearn.feature_extraction.text import CountVectorizer
corpus = [
'UNC played Duke in basketball',
'Duke lost the basketball game',
'I ate a sandwich'
]
vectorizer = CountVectorizer()
print vectorizer.fit_transform(corpus).todense()
print vectorizer.vocabulary_ |
Java | UTF-8 | 275 | 1.757813 | 2 | [] | no_license | package com.WebTable;
import org.openqa.selenium.firefox.FirefoxDriver;
public class FirstRow_FirstColumn_CityName {
public static void main(String[] args)
{
FirefoxDriver driver=new FirefoxDriver();
driver.get("https://www.timeanddate.com/worldclock");
}
}
|
Java | UTF-8 | 863 | 1.992188 | 2 | [] | no_license | package presenter.presenter.dao;
import android.content.ContentValues;
import model.model.entity.Alarm;
import java.util.List;
/**
* Created by csantamaria on 11/05/2016.
*/
public interface AlarmDAOI {
String TABLE_NAME = "alarms";
String COLUMN_CODE = "code";
String COLUMN_NAME = "name";
String COLUMN_HOUR = "hour";
String COLUMN_DAYS = "days";
String COLUMN_WEEK_REPEAT = "week_repeat";
String COLUMN_SOUND = "sound";
String COLUMN_REPEAT = "repeat";
String COLUMN_LEAVE_ALARM_TYPE = "leave_alarm_type";
String COLUMN_ACTIVE = "active";
String COLUMN_STATE_ID = "state_id";
List<Alarm> selectAllAlarms();
void addAlarm(ContentValues cv);
void updateAlarm(int code, ContentValues valuesToUpdate);
void deleteAlarm(int code);
void stateAlarm(int code, int state);
int getMaxCode();
}
|
Markdown | UTF-8 | 5,595 | 2.71875 | 3 | [] | no_license | Nunchuckoo
==========
Adapt a Wii Nunchuck to work with Arduino and Processing

This project was developed primarily to get a Wii Nunchuck working with it's sister project [SCRAPE](https://github.com/c-flynn/SCRAPE) but can be applied to any Processing sketch. Click the image below to see Nunchuckoo in action with SCRAPE:
[  ](https://www.youtube.com/watch?v=Wz4LDeIwH18 "SCRAPE In A CAVE")
Setup
=====
The following instructions demonstrate how to get a Wii Nunchuck working with a Processing sketch. The code repository also contains a basic sketch in order to test the Nunchuck and to demonstrate how the different Nunchuck controls can work within a sketch.
Step 1
------
Firstly you will need to obtain the following items:
* A Wii Nunchuck.
* An [Arduino board](http://arduino.cc/en/Main/Products). For this project I used an Arduino Duemilanove but you should be able to use newer versions such as an Arduino UNO.
* The [Arduino software](http://arduino.cc/en/Main/Software).
* A [WiiChuck adapter](http://todbot.com/blog/2008/02/18/wiichuck-wii-nunchuck-adapter-available). Alternatively you can attach breadboard wires directly to the Nunchuck and Arduino. If attaching the board directly, this [image link](http://www.instructables.com/files/deriv/FOA/0I6U/GFRWRNI0/FOA0I6UGFRWRNI0.LARGE.jpg) shows the connections that need to be made. For this project I used the WiiChuck adapter.
* A USB printer cable to connect your Arduino to a computer.
* A copy of [Processingv1.5.1](http://processing.org/download/) installed on the connecting computer.
Step 2
------
If you're new to Arduino go to the [Getting Started](http://arduino.cc/en/Guide/HomePage) page of the Arduino website and follow the setup instructions for your particular OS. As a general rule it is a good idea to test that you can get your Arduino's onboard LED to blink on and off to ensure that it is setup correctly. This is the most basic program you can run on an Arduino and simple instructions can be found [here](http://arduino.cc/en/Tutorial/Blink)
Step 3
------
Connect your Wii Nunchuck to your arduino board.
If you are using a [WiiChuck adapter](http://todbot.com/blog/2008/02/18/wiichuck-wii-nunchuck-adapter-available). The following image should help you to connect your Nunchuck to your Arduino:

Black Wire - Arduino Gnd
Red Wire - Arduino 3V3
White Wire - Arduino Analog 4
Grey Wire - Arduino Analog 5
Step 4
------
Connect the Arduino to your computer via a USB printer cable and launch the Arduino software.
Now we need to upload some code on to the Arduino board which will be able to read the data from the Nunchuck controller and pass it back in a readable format to your computer. Code to do this is available from the [pragmatic programmers website](http://pragprog.com/titles/msard/source_code) as part of the excellent book [Arduino: A Quick Start Guide](http://pragprog.com/book/msard/arduino). Download and unzip the file and go to _Arduino_1_0 -> MotionSensor -> NunchuckDemo_. Copy the files to your Arduino sketchbook path and upload the code on to your Arduino board. Using Arduino's serial monitor you should now be able to see a stream of data displayed in 7 separate columns which will change as you interact with your Nunchuck.
It should look something like this:
45 150 400 350 600 1 0
47 155 410 357 611 1 0
49 161 417 361 617 0 1
. . . . . . .
. . . . . . .
Alternative but similar code is also available from: https://github.com/todbot/wiichuck_adapter. This has not been tested as part of this project so some modifications may be required.
Step 5
------
Now that we are receiving a readable data stream from the Nunchuck through the Arduino and onto a computer, the next step is to test it. At this point we know we are receiving the data and in the correct format so we can close the Arduino software if it is still open.
Download the **NunchuckooTest** folder and place it in your Processing sketchbook folder.
Ensure your Nunchuck and Arduino are connected, Launch Processing and open the NunchuckooTest sketch. This will open a small window which displays a grey box in the centre of the window on a black background. All going well you should be able to rotate the box in different directions with your Nunchuck.

In order to move the box using the Nunchucks accelerometers be sure to hold down the the Z trigger button on the controller. This acts like a safety catch to stop the box from rotating like crazy as soon as you start the sketch. If you are having difficulties getting the Nunchuck to work with the sketch check out the [Issues](https://github.com/c-flynn/Nunchuckoo/issues) list which highlights some potential problems.
You are now ready to use your Nunchuck in any of your Processing projects. The code in NunchuckooTest.pde has been made as simple and readable as possible so that you can take what you need and apply it to any sketch. If you are intending to use the Nunchuck with SCRAPE please go to https://github.com/c-flynn/SCRAPE for full details.
[](http://githalytics.com/c-flynn/Nunchuckoo)
|
Java | UTF-8 | 2,884 | 2.4375 | 2 | [] | no_license | package com.revature.project_0.entity;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import org.junit.After;
import org.junit.Test;
import com.revature.project_0.connection.ConnectionHelper;
import com.revature.project_0.repository.Repository;
import com.revature.project_0.repository.model.AccountInfoModel;
import com.revature.project_0.repository.model.AccountStatus;
public class AdministratorManualTest {
// @Test
// public void TestMakeDeposit() {
// final double AMOUNT = 500.00;
// Administrator administrator = new Administrator(new Repository());
// FundsTransactionManager ft = administrator.getFundsTransactionManager();
// int result = ft.makeDeposit(AccountInfoModel.getBuilder()
// .withAccountId(5)
// .withBalance(0)
// .withStatus(AccountStatus.APPROVED)
// .build(), AMOUNT, "tester");
// assertEquals(TransactionOutcome.SUCCESS, result);
// }
// @Test
// public void TestMakeWithdrawalFail() {
// final double AMOUNT = 600.00;
// Repository repository = new Repository();
// Administrator administrator = new Administrator(repository);
// AccountInfoModel account = repository.getAccountInfo(5);
// assertNotNull(account);
// FundsTransactionManager ft = administrator.getFundsTransactionManager();
// int result = ft.makeWithdrawal(account, AMOUNT, "tester");
// assertEquals(TransactionOutcome.INSUFFICIENT_FUNDS, result);
// assertTrue(500.00 == account.getBalance());
// }
// @Test
// public void TestMakeWithdrawalPass() {
// final double AMOUNT = 450.00;
// Repository repository = new Repository();
// Administrator administrator = new Administrator(repository);
// AccountInfoModel account = repository.getAccountInfo(5);
// assertNotNull(account);
// FundsTransactionManager ft = administrator.getFundsTransactionManager();
// int result = ft.makeWithdrawal(account, AMOUNT, "tester");
// assertEquals(TransactionOutcome.SUCCESS, result);
// }
// @Test
// public void TestMakeTransferSuccess() {
// final double AMOUNT = 15.00;
// Repository repository = new Repository();
// Administrator administrator = new Administrator(repository);
// AccountInfoModel from = repository.getAccountInfo(5);
// assertNotNull(from);
// assertEquals(AccountStatus.APPROVED, from.getStatus());
// AccountInfoModel to = repository.getAccountInfo(2);
// assertNotNull(to);
// administrator.setEmployeeId("ApproverOfAccount");
// administrator.approveAccount(to.getAccountId());
// assertEquals(AccountStatus.APPROVED, to.getStatus());
// FundsTransactionManager ft = administrator.getFundsTransactionManager();
// int result = ft.makeTransferOfFunds(to, from, AMOUNT, "tester");
// assertEquals(TransactionOutcome.SUCCESS, result);
// }
// @After
// public void finish() {
// ConnectionHelper.getinstance().closeConnection();
// }
}
|
Markdown | UTF-8 | 628 | 3.109375 | 3 | [] | no_license | # Snake Game With a Twist!
(Project for UTSC CSCB58)
A simple game of snake using FPGA board, Verilog and VGA monitor.
Using KEY3 to KEY0 to control the snake, players strive to eat the white blob (apple) to earn points, while increasing in length, and not going out of bounds. Players can eat any of the 4 powerups, where red is the most dangerous one, which eats up your points (those under 100). Eating green reduces your length to 1. Eating dark blue increases your speed to 2, and light blue slows you down to 1.
With a visible score board and high score, players can compete in turns to see who gets the highest score!
|
Java | UTF-8 | 637 | 2.40625 | 2 | [] | no_license | package info.hexin.jmacs.lang.reflect.model;
public class BooleanA {
private boolean boolean1;
private Boolean boolean2;
public BooleanA() {
}
public BooleanA(boolean boolean1, Boolean boolean2) {
this.boolean1 = boolean1;
this.boolean2 = boolean2;
}
public boolean isBoolean1() {
return boolean1;
}
public void setBoolean1(boolean boolean1) {
this.boolean1 = boolean1;
}
public Boolean getBoolean2() {
return boolean2;
}
public void setBoolean2(Boolean boolean2) {
this.boolean2 = boolean2;
}
}
|
Markdown | UTF-8 | 3,020 | 3.34375 | 3 | [] | no_license | ##### **Udacity Deep Reinforcement Learning Nanodegree**
# Project 1: Continuous Control

## **Introduction**
In this project we will train a Deep Deterministic Policy Gradient (DDPG) Agent to control a double jointed arm to move and reach target locations.
A reward of **+0.1** is provided for each step that the agent's hand is in the goal location. Thus, the goal of the agent is to maintain its position at the target location for as many time steps as possible.
The **state space consists of 33 variables** corresponding to position, rotation, velocity, and angular velocities of the arm. Each **action is a vector with four numbers**, corresponding to torque applicable to two joints. **Every entry in the action vector should be a number between -1 and 1.**
**The environment is considered solved, when the average (over 100 episodes) score is at least +30.**
## **Getting Started**
To get started with the project, first we need to download the environment.
You can download the environment from the links given below based on your platform of choice.
- **Linux: [Click Here](https://s3-us-west-1.amazonaws.com/udacity-drlnd/P2/Reacher/Reacher_Linux.zip)**
- **Mac OSX: [Click Here](https://s3-us-west-1.amazonaws.com/udacity-drlnd/P2/Reacher/Reacher.app.zip)**
- **Windows (32-bit): [Click Here](https://s3-us-west-1.amazonaws.com/udacity-drlnd/P2/Reacher/Reacher_Windows_x86.zip)**
- **Windows (64-bit): [Click Here](https://s3-us-west-1.amazonaws.com/udacity-drlnd/P2/Reacher/Reacher_Windows_x86_64.zip)**
**Once the file is downloaded, please extract the zip file into the root of the project.**
### **Setup the python environment**
Please create and activate a virtual environment with conda with the following command.
```sh
conda create -n drlnd python=3.6
conda activate drlnd
```
Once the environment is active run the follwoing command from the root of the project to install the required packages.
```sh
pip install -r requirements.txt
```
Create an IPython kernel for the **drlnd** environment.
```sh
python -m ipykernel install --user --name drlnd --display-name "drlnd"
```
## **Instructions**
The Training and Testing code is implemented in the [Continuous_Control.ipynb](./Continuous_Control.ipynb) Notebook.
To start the jupyter notebook run the below command from the root of this project folder.
```sh
jupyter notebook
```
Once the jupyter notebook server is started open your browser and go to http://localhost:8888/ and click on the **Continuous_Control.ipynb** file to open the notebook. Once the Notebook is open click on **Kernel > Change Kernel > drlnd** menu to change the kernel.
Run all the cells in order to train a DDPG-Agent from scratch and test it. Once training is completed successfully the model checkpoint will be stored as **model.pt** at the root of the project folder.
**In case you dont want to train the agent from scratch then please skip the code cell which calls the train method.**
|
Markdown | UTF-8 | 2,009 | 2.921875 | 3 | [] | no_license | # royal-game-of-ur
A very simple implementation of the Royal Game of Ur (https://en.wikipedia.org/wiki/Royal_Game_of_Ur)
Can be run in three different modes:
1. REST server
2. gRPC server
3. Standalone
## How to run the REST server
`mvn clean package && java -jar spring-boot/target/spring-boot-0.0.1-SNAPSHOT.jar`
To start a new game:</br>
`GET http://localhost:8080/new-game`
To get the game-state:</br>
`GET http://localhost:8080/game`
To get the board-state:</br>
`GET http://localhost:8080/board`
To roll the 'dice':</br>
`GET http://localhost:8080/roll`
To move a specific game piece:</br>
`POST http://localhost:8080/move/{gamePieceId}`
To move a random game piece:</br>
`GET http://localhost:8080/move`
To make the game play itself out by rolling and moving random game pieces until one player has won:</br>
`GET http://localhost:8080/play`
## How to run the gRPC server and client
### gRPC Server
Find `UrGrpcServer` and run it. Now the server has started on `localhost:8081`
### gRPC Client
Download the code and run `mvn clean install`
Add this Maven dependency:
```
<dependency>
<groupId>se.stromvap.royal.game.of.ur</groupId>
<artifactId>grpc</artifactId>
<version>0.0.1-SNAPSHOT</version>
</dependency>
```
Implement your AI by using the interface `RemoteAi`. Start the client with the code below.
(_Note that you need two players before the game will start_)
```
UrGrpcClient.playRoyalGameOfUr("localhost", 8081, new RemoteAi() {
@Override
public String getName() {
return "Patrik";
}
@Override
public GamePiece yourTurn(Game game) {
// Your AI code goes here
}
@Override
public void gameOver(Player winner) {
}
});
```
## How to run AIs in Standalone mode
Create a class that implements `se.stromvap.royal.game.of.ur.ai.Ai`.
Go to `se.stromvap.royal.game.of.ur.ai.AiArenaMain` and use your new AI against another AI.
Currently the `SimpleAi` has a win rate of 95% vs `RandomAi`.
## TODO
TODO: Create UI |
PHP | UTF-8 | 952 | 2.75 | 3 | [] | no_license | <?php
namespace models;
class Brand extends Model
{
// 设置这个模型对应的表
protected $table = 'brand';
// 设置允许接收的字段
protected $fillable = ['brand_name','logo'];
//添加修改之前被调用
public function _before_write(){
$this->delete_img();
//添加上传图片的代码
$upload = \libs\Upload::getInstance();
$logo = '/uploads/'.$upload->upload('logo','brand');
//吧logo加到数组中 插入数据库
$this->data['logo'] = $logo;
}
//删除之前被调用
public function _before_delete(){
$this->delete_img();
}
public function delete_img(){
//如果修改就删除原图片
if(isset($_GET['id'])){
//取出原来logo 并且删除
$oldlogo = $this->findOne($_GET['id']);
@unlink(ROOT.'public'.$oldlogo['logo']);
}
}
} |
Markdown | UTF-8 | 1,099 | 3.8125 | 4 | [] | no_license | # Apple Stocks
###### Sample Question
_Writing programming interview questions hasn't made me rich yet... so I might give up and start trading AAPL stocks all day instead._
First, I want to know how much money I could have made yesterday if I'd been trading AAPL stocks all day.
So I grabbed AAPL's stock prices from yesterday and put them in an array called stock_prices, where:
* The indices are the time (in minutes) past trade opening time, which was 9:30am local time.
* The values are the price (in USD) of one share of AAPL stock at that time.
So if the stock cost $500 at 10:30am, that means `stock_prices[60] = 500`.
**Write an efficient method that takes stock_prices and returns the best profit I could have made from one purchase and one sale of one share of AAPL stock yesterday.**
---
For example:
```
stock_prices = [10, 7, 5, 8, 11, 9]
get max_profit(stock_prices)
# returns 6 (buying for $5 and selling for $11)
```
---
Notes:
* No "shorting" - you need to buy before you can sell.
* Also, you can't buy and sell in the same time step — at least 1 minute has to pass.
|
Python | UTF-8 | 631 | 3.15625 | 3 | [] | no_license | # -*- coding: utf-8 -*-
def PalinSort(c,num):
palin=[]
for i in range(1,num):
x=c%10
c=int(c/10)
palin.append(x)
return palin
def CheckPalin(pa,num):
i=0
result = False
while i<num/2:
if pa[-(1+i)]!=pa[i]:
result=False
break
result=True
i=i+1
if result:
return pa
a=0
b=999
start=999
stop=900
ch=False
for b in range(start,stop,-1):
for a in range(b,900,-1):
c=a*b
pa = PalinSort(c,7)
res=CheckPalin(pa,7)
if res:
print res,a,b
|
JavaScript | UTF-8 | 1,143 | 3.3125 | 3 | [
"MIT"
] | permissive | module.exports = function zeros(expression) {
let factorials = expression.split("*");
let doubleFact = [];
let onceFact = [];
let fives = 0;
let deuces = 0;
for (let i = 0; i < factorials.length; i++) {
if (factorials[i].includes("!!")) {
doubleFact.push(factorials[i].slice(0, -2));
} else {
onceFact.push(factorials[i].slice(0, -1));
}
}
for (let i = 0; i < onceFact.length; i++) {
let number = onceFact[i];
for (let j = 5; j <= number; j *= 5) {
fives += Math.floor(number / j);
}
for (let j = 2; j <= number; j *= 2) {
deuces += Math.floor(number / j);
}
}
for (let i = 0; i < doubleFact.length; i++) {
number = doubleFact[i];
for (let j = 5; j <= number; j *= 5) {
if (number % 2 !== 0) {
fives += Math.ceil(Math.floor(number / j) / 2);
} else {
fives += Math.floor(Math.floor(number / j) / 2);
}
}
for (let j = 2; j <= number; j *= 2) {
if (number % 2 == 0) {
deuces += Math.floor(number / 2);
} else {
deuces += 0;
}
}
}
return fives > deuces ? deuces : fives;
};
|
Java | UTF-8 | 2,545 | 2.109375 | 2 | [
"MIT"
] | permissive | package com.blsa.ezilog.filter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;
import com.blsa.ezilog.config.util.CustomRequestWrapper;
import com.blsa.ezilog.config.util.CustomResponseWrapper;
import com.blsa.ezilog.config.util.LoggingUtil;
import com.blsa.ezilog.dao.RequestLogDao;
import com.blsa.ezilog.dao.ResponseLogDao;
import com.blsa.ezilog.model.log.RequestLog;
import com.blsa.ezilog.model.log.ResponseLog;
@Component
public class RequestResponseLoggerFilter extends GenericFilterBean {
@Autowired
ResponseLogDao responseLogDao;
@Autowired
RequestLogDao requestLogDao;
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
Pattern pattern = Pattern.compile("multipart");
boolean isMultipart = request.getContentType() == null ? false : pattern.matcher(request.getContentType()).find();
if (request.getContentType() != null && isMultipart) {
chain.doFilter(request, response);
} else {
final HttpServletRequest wrapper = new CustomRequestWrapper(request);
RequestLog rqlog = LoggingUtil.makeLoggingRequestMap(wrapper);
chain.doFilter(wrapper, response);
final HttpServletResponse res = new CustomResponseWrapper(response);
Map<String, Object> rqHeader = new HashMap<>();
ResponseLog rplog = new ResponseLog();
try {
requestLogDao.save(rqlog);
Optional<RequestLog> optrequest = requestLogDao.getLastInsert();
if (optrequest.isPresent()) {
RequestLog last = optrequest.get();
ResponseLog rslog = LoggingUtil.makeLoggingResponseMap(res, last.getId());
responseLogDao.save(rslog);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
|
Java | UTF-8 | 1,002 | 2.390625 | 2 | [] | no_license | package am.ik.openenquete.session;
import org.springframework.data.rest.core.annotation.HandleBeforeCreate;
import org.springframework.data.rest.core.annotation.HandleBeforeSave;
import org.springframework.data.rest.core.annotation.RepositoryEventHandler;
import org.springframework.stereotype.Component;
import am.ik.openenquete.seminar.Seminar;
import am.ik.openenquete.seminar.SeminarRepository;
import lombok.RequiredArgsConstructor;
@RepositoryEventHandler(ResponseForSession.class)
@Component
@RequiredArgsConstructor
public class ResponseForSessionHandler {
private final SeminarRepository seminarRepository;
@HandleBeforeCreate
@HandleBeforeSave
public void check(ResponseForSession response) {
Session session = response.getSession(); // must not be null
Seminar seminar = seminarRepository.findBySessions(session).get(); // NoSuchElementException
// => 404
if (!seminar.isOpen()) {
throw new IllegalStateException("The seminar has been closed.");
}
}
}
|
C++ | UTF-8 | 2,761 | 2.8125 | 3 | [] | no_license | #include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <fstream>
using namespace std;
/* void getTag(const string &str)
{
string & ptag = "<p>";
size_t posptag = string::npos;
while (( posptag = str.find(ptag) ) != string::npos) {
str.erase(posptag, ptag.size());
}
string::size_type start = str.find("<p>");
if (start != str.npos) {
string::size_type end = str.find("<p>", start + 1);
if (end != str.npos){
++start;
std::string::size_type count = end - start;
return str.substr(start, count); }
}
return "";
} */
int main() {
ifstream file("text.txt");
string test;
//string test = "<p> Hello World <p><p> He he hoo hoo <p><br><p> Giggity goo <p><hr>";
// getTag(test);
if (file) {
getline(file, test);
// file.close();
}
else cout << "yikers\n";
vector<size_t> pposits;
vector<size_t> brposits;
vector<size_t> hrposits;
int size;
string para = "<p>";
string br = "<br>";
string hr = "<hr>";
size_t npos = test.find(para);
cout << "Enter line character limit(>28): ";
cin >> size;
cout << endl;
while (npos != string::npos) {
pposits.push_back(npos);
npos = test.find(para, npos + para.size());
}
//test.replace(posits[0], 3, " ");
for (int i = 0; i < pposits.size(); i++) {
test.replace(pposits[i] - i*3 + i*2, 3, "\n\n");
//cout << x << endl;
}
// cout << test << endl;
for (auto x: pposits) {
cout << x << endl;
}
// return 0;
/*for (int i = 0; i < (int)(test.size() / 35); i++) {
test.replace(i*35, 0, "\n");
}*/
npos = test.find(br);
while (npos != string::npos){
brposits.push_back(npos);
npos = test.find(br, npos + br.size());
}
for (int i = 0; i < brposits.size(); i++) {
test.replace(brposits[i] - i*4 + i, 4, "\n");
//cout << x << endl;
}
npos = test.find(hr);
while (npos != string::npos){
hrposits.push_back(npos);
npos = test.find(hr, npos + hr.size());
}
for (int i = 0; i < hrposits.size(); i++) {
test.replace(hrposits[i] - i*4 + i, 4, "------------------------------");
//cout << x << endl;
}
// cout << test << endl;
// return 0;
// cout << test << endl;
int l = 0;
string temp;
for (int i = 1; i < test.size(); i++) {
l++;
if (l > size) {
//cout << "bucktee" << endl;
for (int j = i; j > 0; j--){
if(test.substr(j-1, 1).compare(" ") == 0) {
// cout << "xd";
// cout << "doot";
temp = test.substr(0,j);
temp += "\n";
temp += test.substr(j, test.size() - j);
test = temp;
i = j + 1;
break;
}
}
}
if(test.substr(i-1,1).compare("\n") == 0) {
//cout << "doot";
l = 0;
}
}
cout << test << endl;
file.close();
return 0;
}
//<p>(.+?)<p>
|
Java | UTF-8 | 797 | 2.921875 | 3 | [] | no_license | import java.util.concurrent.ConcurrentHashMap;
class MultiTonManage {
ConcurrentHashMap<String, Reusable1> pool = new ConcurrentHashMap<>();
static int count = 1;
private MultiTonManage() {}
private static MultiTonManage instance = new MultiTonManage();
public Reusable1 getFor(String key) {
Reusable1 r = pool.get(key);
if (r != null) return r;
insertFor(key);
return pool.get(key);
}
private synchronized void insertFor(String key) {
if (pool.get(key) != null) return;
pool.put(key, new Reusable1(count++));
}
}
class Reusable1 {
final int value;
public Reusable1(int value) {
this.value = value;
}
@Override
public String toString() {
return "Reusable [value=" + value + "]";
}
}
public class SingletonMultiTon {
public static void main(String[] args) {
}
}
|
Java | UTF-8 | 936 | 1.914063 | 2 | [] | no_license | package com.opnitech.esb.processor.persistence.elastic.repository.document;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import com.opnitech.esb.processor.common.data.ElasticIndexMetadata;
import com.opnitech.esb.processor.persistence.elastic.model.shared.ElasticSourceDocument;
import com.opnitech.esb.processor.persistence.elastic.repository.shared.ElasticRepository;
/**
* @author Rigre Gregorio Garciandia Sonora
*/
public class DocumentRepository extends ElasticRepository {
public DocumentRepository(ElasticsearchTemplate elasticsearchTemplate) {
super(elasticsearchTemplate);
}
public ElasticSourceDocument retrieveDocument(ElasticIndexMetadata elasticIndexMetadata, String id) {
ElasticSourceDocument elasticSourceDocument = executeGetById(elasticIndexMetadata.getIndexName(),
elasticIndexMetadata.getDocumentTypeName(), id);
return elasticSourceDocument;
}
}
|
Markdown | UTF-8 | 9,240 | 3.609375 | 4 | [
"MIT",
"LicenseRef-scancode-warranty-disclaimer"
] | permissive | # The Dropdown Component
A more opinionated version of the Popover component.
Instantiates a button with a menu that will appear at the bottom of the button.
### React Component
#### `<Dropdown>`
#### Props
| Prop | Type | Default | Description |
| --------------- | -------------------------------------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `children` | react.node | required | Content to display inside the Dropdown. Can accept a child function that contains the close event as first parameter |
| `buttonContent` | react.node | required | Content to display within the Dropdown Button |
| `placement` | ['start', 'center', 'end', PopperPlacements] | 'start' | Positioning of the Dropdown content. By default, it will be aligned left (aka the start). For a full list of all additional PopperPlacements, please consult [the popper documentation](https://popper.js.org/popper-documentation.html#Popper.placements) |
```js
import React from 'react';
import { Dropdown } from '@lightspeed/flame/Dropdown';
const MyApp = () => (
<div>
<Dropdown buttonContent="Button Text">
This is the content that will appear when we click on the button.
</Dropdown>
<Dropdown buttonContent="Another Button">
{close => (
<div>
This is the content that will appear when we click on the button.
<button type="button" onClick={close}>
Clicking on me will close the dropdown
</button>
</div>
)}
</Dropdown>
</div>
);
export default MyApp;
```
#### `<DropdownContent>`
A pre-styled `<Box>` with the appropriate margins setup. Use it within the Dropdown.
```js
import React from 'react';
import { Dropdown, DropdownContent } from '@lightspeed/flame/Dropdown';
const MyApp = () => (
<div>
<Dropdown buttonContent="Button Text">
<DropdownContent>I will have the correct margin applied to me</DropdownContent>
</Dropdown>
</div>
);
export default MyApp;
```
#### `useDropdown()`
A simple hook to access the close event for a Dropdown. You may use this instead of passing a child function.
It's a particularly useful for complex dom structures.
```js
import React from 'react';
import { Dropdown, DropdownContent, useDropdown } from '@lightspeed/flame/Dropdown';
const MyDropdownContent = () => {
const { closeDropdown } = useDropdown();
return (
<div>
This is the content that will appear when we click on the button.
<button type="button" onClick={closeDropdown}>
Clicking on me will close the dropdown
</button>
</div>
);
};
const MyApp = () => (
<div>
<Dropdown buttonContent="Button Text">
<MyDropdownContent />
</Dropdown>
</div>
);
export default MyApp;
```
### Building your own dropdown/popover component using hooks
Dropdown and Popover are quite opinionated and might not do everything you want.
But worry not! It's possible to quickly create your own implementation of Dropdown and Popover using a few hooks provided.
Creating your own dropdown component requires using the `usePopper` hook and 2 components that will be linked via the `usePopper` hook.
These two components are called the "Target" and the "Popper".
The "Target" is the component in which we will use as an anchor point for our "Popper".
The "Popper" component will attempt to always attach itself to the "Target".
```jsx
import * as React from 'react';
import { usePopper } from '@lightspeed/flame/hooks';
const MyCustomDropdown = ({ children }) => {
// Let's create the references for our two components
const targetRef = React.createRef();
const popperRef = React.createRef();
// Let's tell popper to use these two component references.
usePopper(targetRef, popperRef);
return (
<React.Fragment>
<button ref={targetRef}>Menu Button</button>
{/* This is the content that will float around the button */}
<div ref={popperRef}>{children}</div>
</React.Fragment>
);
};
```
By default, `usePopper` will attempt to always position the "Popper" component (in the previous example, our `div`) to the bottom of the "Target" component (the `button`). Should you wish to adjust the positioning of the "Popper" component, you may pass in additional options to the hook. For further details, check the [hooks documentation](https://github.com/lightspeed/flame/blob/master/packages/flame/src/hooks/README.md).
Now that we have positioning done, let us add some state to manage whether to display or hide our "Popper" content.
Although you can do this yourself, there is an additional hook called `useToggle` that we can leverage.
```jsx
import * as React from 'react';
import { usePopper, useToggle } from '@lightspeed/flame/hooks';
const MyCustomDropdown = ({ children }) => {
const targetRef = React.createRef();
const popperRef = React.createRef();
usePopper(targetRef, popperRef);
// Use toggle exports a couple of helper functions/variables
// But the two main important ones are: `toggle` and `isActive`
// `toggle` is a function that will automatically swap between active and inactive state
// `isActive` is a boolean variable that indicates whether or not our state is active or inactive
const { toggle, isActive } = useToggle();
return (
<React.Fragment>
{/* Bind the toggle function on the button's onClick handler */}
<button ref={targetRef} onClick={toggle}>
Menu Button
</button>
{/* use `isActive` boolean state to determine whether to show or hide content */}
{isActive && <div ref={popperRef}>{children}</div>}
</React.Fragment>
);
};
```
Now, when we click on the button, we can quickly open/close our popper content.
Of course, we may want to close our content if we click outside the `div` or after pressing a key (like "Escape"). Luckily, we have more little hooks to give use these functionalities.
For further details on the hooks used in the example below, check the [hooks documentation](https://github.com/lightspeed/flame/blob/master/packages/flame/src/hooks/README.md).
```jsx
import * as React from 'react';
import { usePopper, useToggle, useOnClickOutside, useEventListener } from '@lightspeed/flame/hooks';
const MyCustomDropdown = ({ children }) => {
const targetRef = React.createRef();
const popperRef = React.createRef();
usePopper(targetRef, popperRef);
const { toggle, isActive } = useToggle();
// if we click outside the popperRef, our callback function gets triggered.
useOnClickOutside(popperRef, () => isActive && toggle());
// if we press "Escape" on the keyboard, we trigger the toggle action.
useEventListener(() => {
if (event.key === 'Escape' && isActive) {
toggle();
}
}, 'keyup'); // Escape can only be triggered on keyup or keydown events
return (
<React.Fragment>
<button ref={targetRef} onClick={toggle}>
Menu Button
</button>
{isActive && <div ref={popperRef}>{children}</div>}
</React.Fragment>
);
};
```
And there we have it, a simple and easy to understand custom Dropdown/Popover component. From here, you may style the "Target" and "Popper" element however you want. You may also use some prebuilt styling from other components that use this pattern. For example, the base `Dropdown` component has exports for the "Popper" container.
```jsx
import * as React from 'react';
// Let's import the DropdownContainer to have a similar styling.
import { DropdownContainer } from '@lightspeed/flame/Dropdown';
import { usePopper, useToggle, useOnClickOutside, useEventListener } from '@lightspeed/flame/hooks';
const MyCustomDropdown = ({ children }) => {
const targetRef = React.createRef();
const popperRef = React.createRef();
usePopper(targetRef, popperRef);
const { toggle, isActive } = useToggle();
useOnClickOutside(popperRef, () => isActive && toggle());
useEventListener(() => {
if (event.key === 'Escape' && isActive) {
toggle();
}
}, 'keyup');
return (
<React.Fragment>
<button ref={targetRef} onClick={toggle}>
Menu Button
</button>
{/* Simply plug the container in! */}
{isActive && (
<DropdownContainer ref={popperRef} light>
{children}
</DropdownContainer>
)}
</React.Fragment>
);
};
```
|
TypeScript | UTF-8 | 2,891 | 2.671875 | 3 | [
"MIT"
] | permissive | import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { NonNullableFormBuilder, FormGroup, FormControl } from '@angular/forms';
import { InputControls } from '../shared/inputcontrols';
import { UnitConversion } from '../shared/UnitConversion';
import { ValidatorGroups } from '../shared/ValidatorGroups';
@Component({
selector: 'app-altitude',
templateUrl: './altitude.component.html',
styleUrls: ['./altitude.component.scss']
})
export class AltitudeComponent implements OnInit {
@Output()
public inputChange = new EventEmitter<number>();
/** In m.a.s.l */
@Input()
public altitude = 0;
public altitudeForm!: FormGroup<{
altitude: FormControl<number>;
}>;
private metricLevels = [0, 300, 800, 1500];
private imperialLevels = [0, 1000, 2600, 5000];
constructor(private fb: NonNullableFormBuilder,
private inputs: InputControls,
private validators: ValidatorGroups,
public units: UnitConversion) { }
public get altitudeBound(): number {
return this.units.fromMeters(this.altitude);
}
public get smallHill(): string {
return this.levelLabel(1);
}
public get mountains(): string {
return this.levelLabel(2);
}
public get highMountains(): string {
return this.levelLabel(3);
}
public get altitudeInvalid(): boolean {
const altitudeField = this.altitudeForm.controls.altitude;
return this.inputs.controlInValid(altitudeField);
}
public ngOnInit(): void {
this.altitudeForm = this.fb.group({
altitude: [this.altitudeBound, this.validators.altitude]
});
}
public altitudeChanged(): void {
if (this.altitudeForm.invalid) {
return;
}
const newValue = Number(this.altitudeForm.value.altitude);
this.altitude = this.units.toMeters(newValue);
this.inputChange.emit(this.altitude);
}
public seaLevel(): void {
this.setLevel(0);
}
public setHill(): void {
this.setLevel(1);
}
public setMountains(): void {
this.setLevel(2);
}
// we don't change the values for imperial units here
// simply lets fit closes rounded value
public setHighMountains(): void {
this.setLevel(3);
}
private setLevel(index: number): void {
const level = this.selectLevels()[index];
this.altitudeForm.patchValue({
altitude: level
});
this.altitudeChanged();
}
private levelLabel(index: number): string {
const level = this.selectLevels()[index];
return `${level} ${this.units.altitude}`;
}
private selectLevels(): number[] {
if (this.units.imperialUnits) {
return this.imperialLevels;
}
return this.metricLevels;
}
}
|
Java | UTF-8 | 427 | 2.953125 | 3 | [] | no_license | package com.future.threads;
import java.util.concurrent.*;
public class ThreadNameFetcher implements Callable<String> {
public ThreadNameFetcher (){
}
@Override
public String call() throws Exception {
// Thread.sleep(waitTime);
//return the thread name executing this callable task
System.out.println("Thread fetcher call");
return Thread.currentThread().getName();
}
} |
JavaScript | UTF-8 | 13,218 | 2.859375 | 3 | [
"MIT"
] | permissive | /*
* Handout Script
*
* Runs rendered Markdown handouts with embedded exercises and other features.
*/
// create a hover interaction
// will either update an attribute of a target element inside this element,
// or show only targets matching an indexed selector, as the user hovers over
// elements matching a selector
function createHoverInteraction() {
var elt = $(this);
var selector = elt.data('selector');
var target = $(elt.data('target'), elt);
var pick = elt.data('pick');
if (pick) {
var updateTarget = function() {
var filter = pick.replace(/\{index\}/g, $(this).index(selector)+1);
target.hide().filter(filter).show();
}
} else {
var attr = elt.data('attr');
var template = elt.data('template');
var updateTarget = function() {
var value = template.replace(/\{index\}/g, $(this).index(selector));
target.attr(attr, value);
}
}
var update = function() {
$(selector).removeClass('highlighted');
$(this).addClass('highlighted');
updateTarget.apply(this);
}
$(selector).addClass('hover-figure-select').on('click mouseenter', update);
update.apply($(selector).first());
}
// move this element to follow the on-screen match to the selector
function followLeaders(selector) {
return function() {
var follower = $(this);
var leaders = $(selector);
Array.prototype.reverse.call(leaders); // iterate from bottom to top of page
var current = undefined;
$(document).on('scroll', function() {
leaders.each(function() {
if (this.getBoundingClientRect().top < window.innerHeight * 0.9) {
if (current != this) {
current = this;
follower.remove();
$(this).prepend(follower);
}
return false; // stop at bottommost leader element above the scroll position
}
});
});
$(document).scroll();
};
}
// all exercises on the page
window.handoutExercises = [];
// serialize an exercise (or exercises) to JSON, converting jQuery DOM pointers to outline labels
function handoutExerciseJSON(exercise) {
return JSON.stringify(exercise, function(key, value) {
if (value && value.jquery) { return value.attr('data-outline'); }
return value;
});
}
// create an interactive exercise
function createExercise() {
// build the exercise data structure with pointers to DOM nodes...
$('.exercise-panel', this).each(function() {
var exercise = {
id: $(this).data('ex-id'),
category: $(this).data('ex-category'),
node: $(this),
flags: {
no_iterate: $(this).data('ex-no-iterate')
},
parts: $('.exercise-part', this).map(function() {
return {
node: $(this),
choices: $('.exercise-choice', this).map(function() {
var expected = $(this).data('ex-expected');
var regex = $(this).data('ex-regex');
return {
node: $(this),
expected: typeof expected == 'string' ? decodeURIComponent(expected) : expected,
regex: typeof regex == 'string' ? decodeURIComponent(regex) : undefined,
answer: $('.exercise-answer', this).first()
};
}).get()
};
}).get(),
explanations: $('.exercise-explain', this).map(function() {
return {
node: $(this),
html: this.innerHTML.trim()
};
}).get(),
progress: $('.exercise-progress', this).first(),
error: $('.exercise-error', this).first()
};
// ... and remember it
window.handoutExercises.push(exercise);
// handle check/explain buttons
var handler = exercise.node.data('ex-remote') ? remoteHandler : localHandler;
$('.exercise-submit, .exercise-reveal', this).on('click', clearError.bind(null, exercise));
$('.exercise-submit', this).on('click', handler.onSubmit.bind(null, exercise));
$('.exercise-reveal', this).on('click', handler.onReveal.bind(null, exercise));
// collapsing exercise A to show exercise B might push the top of B off the page,
// so scroll it back on
$(this).on('shown.bs.collapse', function() {
var top = this.getBoundingClientRect().top;
if (top < 0) {
$(document.body).animate({ scrollTop: document.body.scrollTop + top - 32 });
}
});
});
}
function FN(method) { return method.call.bind(method); }
function AND(x, y) { return x && y; }
function OR(x, y) { return x || y; }
// read the value of a choice
function value(choice) {
if (choice.node.is('.checkbox, .radio')) {
return $('input', choice.node).prop('checked');
}
if (choice.node.is('.dropdown')) {
return $('select option:selected', choice.node).text();
}
if (choice.node.is('.textfield')) {
return $('input, textarea', choice.node).val().replace(/\s+/g, ' ').trim();
}
return undefined;
}
// is this part considered to have a value?
function hasValue(part) {
return part.choices.map(function(choice) {
if (choice.node.is('.checkbox')) {
return true;
}
return value(choice);
}).reduce(OR);
}
// return true iff phpRegex (of the form "/.../flags" where flags can only include i or m)
// matches value anchored
function matchRegex(phpRegex, value) {
var m = phpRegex.match(/^\/(.+)\/([imxo]*)/);
if (!m) throw new Error("regex should have format /.../[im]: " + phpRegex);
var jsRegex = new RegExp("^(" + m[1] + ")$", m[2]);
var string = value.toString();
return string.match(jsRegex) != null;
}
// handle local check/explain
var localHandler = {
onSubmit: function(exercise) {
if ( ! displayExerciseAttempted(exercise)) { return; }
exercise.correct = exercise.parts.map(function(part) {
return part.correct = part.choices.map(function(choice) {
var v = value(choice);
choice.correct = choice.regex ? matchRegex(choice.regex, v) : (v == choice.expected);
return choice.correct;
}).reduce(AND);
}).reduce(AND);
displayExerciseAnswered(exercise);
},
onReveal: function(exercise) {
displayExerciseReveal(exercise);
}
};
// handle remote check/explain
var remoteHandler = {
onSubmit: function(exercise) {
if ( ! displayExerciseAttempted(exercise)) { return; }
ajax(exercise, { reveal: exercise.flags.no_iterate }, function handleSubmit(response) {
exercise.correct = response.result.correct;
exercise.parts.forEach(function(part) {
part.correct = response.result.parts.shift().correct;
});
if (response.exercise) {
updateExercise(exercise, response);
}
displayExerciseAnswered(exercise);
});
},
onReveal: function(exercise) {
ajax(exercise, { reveal: true }, function handleReveal(response) {
updateExercise(exercise, response);
displayExerciseReveal(exercise);
});
}
};
// make a XHR for the given exercise: sends exercise JSON, displays progress and errors
function ajax(exercise, data, success) {
exercise.progress.fadeIn();
data.handout = exercise.node.data('ex-handout');
data.student = handoutExerciseJSON(exercise);
$.ajax({
method: 'POST',
url: exercise.node.data('ex-remote'),
data: data,
xhrFields: { withCredentials: true },
}).done(success).fail(function(xhr, status, err) {
showError(exercise, status, xhr.responseText || err || 'sorry about that');
if (console && console.error) { console.error('exercise error', xhr.responseText, status, err); }
}).always(function() {
exercise.progress.hide();
});
}
// update local exercise data with remote answers and explanations
function updateExercise(exercise, response) {
// incorporate correct answers
exercise.parts.forEach(function(part) {
var respart = response.exercise.parts.shift();
part.choices.forEach(function(choice) {
choice.expected = respart.choices.shift().expected;
choice.answer.html('');
});
});
// incorporate explanations
exercise.explanations.forEach(function(explain) {
explain.node.html(response.exercise.explanations.shift().html);
});
}
// display attempt feedback
// return true iff all parts are attempted
function displayExerciseAttempted(exercise) {
var complete = exercise.parts.map(function(part) {
part.choices.forEach(function(choice) {
choice.input = value(choice);
});
var complete = hasValue(part);
part.node.toggleClass('exercise-incomplete', ! complete);
return complete;
}).reduce(AND);
if ( ! complete) {
if (exercise.flags.no_iterate) {
showError(exercise, 'before you submit your answers', 'you must answer every part');
} else {
showError(exercise, 'before you check your answers', 'please attempt every part');
}
}
return complete;
}
// display answer feedback
function displayExerciseAnswered(exercise) {
exercise.parts.forEach(function(part) {
part.node.addClass('exercise-answered').toggleClass('exercise-correct', part.correct);
});
$('.exercise-reveal', exercise.node).show();
if (exercise.correct || exercise.flags.no_iterate) {
$('.exercise-submit', exercise.node).prop('disabled', true);
displayExerciseReveal(exercise);
}
}
// display correct answers and explanations
function displayExerciseReveal(exercise) {
exercise.parts.forEach(function(part) {
part.choices.forEach(function(choice) {
choice.node.filter('.checkbox, .radio').each(function() {
if (choice.expected) {
choice.answer.html('<span class="glyphicon glyphicon-check">');
}
});
choice.node.filter('.dropdown, .textfield').each(function() {
choice.answer.text(choice.expected);
});
});
});
$('.exercise-answer', exercise.node).fadeIn();
$('.exercise-explain', exercise.node).slideDown();
$('.exercise-reveal', exercise.node).prop('disabled', true);
}
// display an error
function showError(exercise, title, error) {
var alert = $('<div>').addClass('alert alert-info alert-dismissable')
.text(': ' + error)
.prepend($('<strong>').text(title.replace(/\w/, FN(String.prototype.toUpperCase))))
.prepend($('<button>').addClass('close').attr('data-dismiss', 'alert').html('×'));
exercise.error.empty().append(alert);
}
// remove any error
function clearError(exercise) {
exercise.error.empty();
}
// create a video player link
function createVideo() {
$(this).on('click', function() {
$('.video-embed').empty();
var player = $('<iframe>').addClass('embed-responsive-item').attr('src', $(this).attr('href'));
$('.video-embed').append(player);
$('.video-player').show();
return false;
});
}
// close the video player
function closeVideo() {
$('.video-embed').empty();
$('.video-player').hide();
}
// report visible parts of the page after scrolling
function createHeatmap() {
var url = this.getAttribute('data-handx-url') + 'heatmap.php';
var id = this.getAttribute('data-handx-id') || undefined;
var win = $(window);
var elts = document.querySelectorAll('[id]');
win.on('scroll.handx', scrolled);
function scrolled() {
win.off('scroll.handx');
setTimeout(function() {
heat();
win.on('scroll.handx', scrolled);
}, 1000 * 2);
}
function heat() {
var visible = Array.prototype.filter.call(elts, function(elt) {
var rect = elt.getBoundingClientRect();
return rect.y > 0 && rect.y + 20 < window.innerHeight && $(elt).is(':visible');
}).map(function(elt) { return elt.id; });
$.ajax({
url: url, method: 'POST',
xhrFields: { withCredentials: true },
data: { id: id, visible: JSON.stringify(visible) },
});
}
}
//
// main
//
$(document).ready(function() {
// wire up table of contents
$('body').scrollspy({ target: '.table-of-contents', offset: 120 });
// wire up interactive elements
$('.hover-figure').each(createHoverInteraction);
// wire up exercises
$('.exercises').each(createExercise);
$('.exercises-status').each(followLeaders('.handout-title, .exercises'));
// wire up videos
$('.video-play').each(createVideo);
$('.video-close').on('click', closeVideo);
// on delivered handouts...
if (window.HANDOUT_DELIVER === undefined) {
// wire up heatmap
$('[data-handx-url]').not('.footer-archived ~ *').first().each(createHeatmap);
}
// handle fragment identifiers
if (location.hash) {
var elt = document.getElementById(decodeURIComponent(location.hash.substr(1)));
if (elt) {
$(elt).filter('.exercise-panel.collapse').addClass('in'); // jump to an exercise
$('.exercise-panel.collapse', elt).addClass('in'); // jump to an exercise
$(elt).nextAll('.exercise-panel.collapse').addClass('in'); // jump to header of exercise
$(elt).parents('.exercise-panel.collapse').addClass('in'); // jump inside an exercise
elt.scrollIntoView();
}
}
window.handoutReady = true;
if (window.HANDOUT_DELIVER) {
// done rendering
setTimeout(window.handoutDeliveryCallback, 0);
} else {
// ready callback
if (window.HANDOUT_READY) { window.HANDOUT_READY(); }
if (window.onHandoutReady) { window.onHandoutReady(); }
}
});
|
Java | UTF-8 | 1,911 | 3.53125 | 4 | [
"MIT"
] | permissive | import java.util.LinkedList;
import java.util.Queue;
import java.util.StringTokenizer;
public class SerializeAndDeserializeBinaryTree_297 {
// Encodes a tree to a single string.
public String serialize(TreeNode root) {
StringBuilder sb = new StringBuilder();
sb.append('[');
Queue<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (queue.size() != 0) {
TreeNode cur = queue.poll();
if (cur == null) sb.append("null,");
else {
sb.append(cur.val); sb.append(',');
queue.offer(cur.left); queue.offer(cur.right);
}
}
if (sb.charAt(sb.length() - 1) == ',') sb.deleteCharAt(sb.length() - 1);
sb.append(']');
return sb.toString();
}
// Decodes your encoded data to tree.
public TreeNode deserialize(String data) {
StringTokenizer tokens = new StringTokenizer(data.substring(1, data.length() - 1), ",");
int length = tokens.countTokens();
if (length == 0) return null;
Queue<TreeNode> queue = new LinkedList<>();
TreeNode root = null;
String token;
if (tokens.hasMoreTokens() && !"null".equals(token = tokens.nextToken()))
queue.offer(root = new TreeNode(Integer.parseInt(token)));
while (tokens.hasMoreTokens()) {
TreeNode parent = queue.poll();
if (!"null".equals(token = tokens.nextToken()))
queue.offer(parent.left = new TreeNode(Integer.parseInt(token)));
if (tokens.hasMoreTokens() && !"null".equals(token = tokens.nextToken()))
queue.offer(parent.right = new TreeNode(Integer.parseInt(token)));
}
return root;
}
private static class TreeNode {
int val;
TreeNode left;
TreeNode right;
TreeNode(int x) { val = x; }
}
}
|
Markdown | UTF-8 | 2,920 | 2.984375 | 3 | [
"MIT"
] | permissive | # serve-dynamic-favicon
[](https://www.npmjs.com/package/serve-dynamic-favicon)
[](https://nodei.co/npm/serve-dynamic-favicon/)
# PLEASE NOTE THIS IS IN ALPHA
Node.js middleware for serving a favicon that is generated on the fly.
Using the first letter of the the `<title>` tag overlayed a background color fetched from the `<meta name="theme-color" content="#007BB6">` you'll reduce the cognitive load when switching between browser tabs.
You may specify any url you want for where the metadata will be fetched from, or you can pass the letter and theme-color and save the initial request.
This is very useful for when you're running expressjs or BrowserSync servers.
## Install
```bash
npm install serve-dynamic-favicon --production --no-optional
```
## API
### favicon(url:string || options:object)
Create new middleware to serve a favicon generated from metadata fetched from the given `url` to a fetchable html document.
Pass an object with options to switch the middleware from auto mode to manual mode. Manual mode require you to at least specify `themeColor`. `symbol` is optional, omitting it will render a solid color without any foreground text as logo.
#### Options
##### themeColor
The backdrop color to the generated icon. Any css color value, with or without alpha, is supported.
##### symbol
The text letter, usually the first character found in the `<title>` tag when `url` is defined.
##### symbolColor
Optionally set the color of `symbol`. Defaults to `#ffffff`.
## Examples
Typically this middleware will come very early in your stack (maybe even first)
to avoid processing any other middleware if we already know the request is for
`/favicon.ico`.
### express
```javascript
var express = require('express');
var favicon = require('serve-dynamic-favicon');
var app = express();
app.use(favicon('https://github.com'));
// Add your routes here, etc.
app.listen(3000);
```
### connect
```javascript
var connect = require('connect');
var favicon = require('serve-dynamic-favicon');
var app = connect();
app.use(favicon('https://github.com'));
// Add your middleware here, etc.
app.listen(3000);
```
### vanilla http server
This middleware can be used anywhere, even outside express/connect. It takes
`req`, `res`, and `callback`.
```javascript
var http = require('http');
var favicon = require('serve-dynamic-favicon');
var finalhandler = require('finalhandler');
var _favicon = favicon();
var server = http.createServer(function onRequest(req, res) {
var done = finalhandler(req, res);
_favicon(req, res, function onNext(err) {
if (err) return done(err);
// continue to process the request here, etc.
res.statusCode = 404;
res.end('oops');
});
});
server.listen(3000);
```
## License
[MIT](LICENSE)
|
C++ | UTF-8 | 1,413 | 3.46875 | 3 | [] | no_license | // { Driver Code Starts
//Initial Template for C++
#include <bits/stdc++.h>
#include <string>
using namespace std;
// } Driver Code Ends
//User function Template for C++
class Solution
{
public:
//Function to find list of all words possible by pressing given numbers.
void keypad(string output, string k[], vector<string> &res, int a[], int n) {
if(n-1<0){
res.push_back(output);
return;
}
int n1 = a[n-1];
string s = k[n1];
for(int i=0; i<s.length(); i++)
keypad(s[i]+output, k, res, a, n-1);
}
vector<string> possibleWords(int a[], int N)
{
string output = "";
string k[] = { "", "", "abc", "def", "ghi", "jkl", "mno", "pqrs", "tuv", "wxyz" };;
vector<string> res;
keypad(output, k, res, a, N);
sort(res.begin(), res.end());
return res;
}
};
// { Driver Code Starts.
int main() {
int T;
cin >> T; //testcases
while(T--){ //while testcases exist
int N;
cin >> N; //input size of array
int a[N]; //declare the array
for(int i =0;i<N;i++){
cin >> a[i]; //input the elements of array that are keys to be pressed
}
Solution obj;
vector <string> res = obj.possibleWords(a,N);
for (string i : res) cout << i << " ";
cout << endl;
}
return 0;
} // } Driver Code Ends |
JavaScript | UTF-8 | 2,456 | 2.53125 | 3 | [] | no_license | var dataObject = [
{
name: 'Java',
rank: 1,
ad: '降',
change: -0.0001
},
{
name: 'C',
rank: 2,
ad: '升',
change: 0.0244
},
{
name: 'Python',
rank: 3,
ad: '升',
change: 0.0141
},
{
name: 'C++',
rank: 4,
ad: '降',
change: -0.0258
},
{
name: 'C#',
rank: 5,
ad: '升',
change: 0.0207
},
{
name: 'Visual Basic .NET',
rank: 6,
ad: '降',
change: -0.0117
},
{
name: 'JavaScript',
rank: 7,
ad: '降',
change: -0.0085
}
];
var hotElement = document.getElementById('hot');
var hotSettings = {
data: dataObject,
columns: [
{
data: 'name',
type: 'text'
},
{
data: 'rank',
type: 'numeric'
},
{
data: 'ad',
type: 'text'
},
{
data: 'change',
type: 'numeric',
numericFormat: {
pattern: '+0.00%'
}
}
],
stretchH: 'all',
width: 800,
autoWrapRow: true,
height: 350,
rowHeights: 45,
colWidths: 35,
className: "htCenter htMiddle",
maxRows: 22,
manualRowMove: true,
manualColumnMove: true,
rowHeaders: false,
colHeaders: [
'语言名称',
'排名',
'升或降',
'变化幅度'
],
manualRowResize: true,
manualColumnResize: true,
contextMenu: true,
filters: true,
dropdownMenu: false
};
var hot = new Handsontable(hotElement, hotSettings);
var myChart = echarts.init(document.getElementById('main'));
var option = {
title: {
text: 'JavaScript语言排名变化'
},
tooltip: {
show: true,
trigger : 'axis',
axisPointer: {
type: 'line',
lineStyle: {
color: '#555',
width: 1,
type: 'solid'
},
},
formatter: '<div style="text-align:center;">{a}<br/>{b}: {c}</div>'
},
xAxis: {
data: [2000, 2005, 2010, 2015, 2020],
axisPointer: {
show: true
}
},
yAxis: {},
series: [{
name: '排名',
type: 'line',
data: [6, 9, 8, 8, 7]
}]
};
myChart.setOption(option);
|
TypeScript | UTF-8 | 1,995 | 2.6875 | 3 | [
"MIT"
] | permissive | import { Injectable } from '@nestjs/common';
import fs from 'fs-extra';
import path from 'path';
import { ConfigService } from '../../../config/config.service';
import { Asset } from '../../../entity/asset/asset.entity';
import { AssetService } from '../../../service/services/asset.service';
@Injectable()
export class AssetImporter {
private assetMap = new Map<string, Asset>();
constructor(private configService: ConfigService, private assetService: AssetService) {}
/**
* Creates Asset entities for the given paths, using the assetMap cache to prevent the
* creation of duplicates.
*/
async getAssets(assetPaths: string[]): Promise<{ assets: Asset[]; errors: string[] }> {
const assets: Asset[] = [];
const errors: string[] = [];
const { importAssetsDir } = this.configService.importExportOptions;
const uniqueAssetPaths = new Set(assetPaths);
for (const assetPath of uniqueAssetPaths.values()) {
const cachedAsset = this.assetMap.get(assetPath);
if (cachedAsset) {
assets.push(cachedAsset);
} else {
const filename = path.join(importAssetsDir, assetPath);
if (fs.existsSync(filename)) {
const fileStat = fs.statSync(filename);
if (fileStat.isFile()) {
try {
const stream = fs.createReadStream(filename);
const asset = await this.assetService.createFromFileStream(stream);
this.assetMap.set(assetPath, asset);
assets.push(asset);
} catch (err) {
errors.push(err.toString());
}
}
} else {
errors.push(`File "${filename}" does not exist`);
}
}
}
return { assets, errors };
}
}
|
Markdown | UTF-8 | 5,157 | 2.875 | 3 | [
"MIT"
] | permissive | ## デバッグ方法
実行時のプログラム内の変数の値や挙動を確認する方法として、次の2つがある。
### ログによる挙動確認
最も簡単な挙動確認方法としては、Eclipseのコンソールタブ欄に表示される出力を見ることである。
ログとは、システムが動作した履歴を文字列ベースで出力したものである。
本課題のログは次の形式で出力されている。それぞれの内容を下記表にまとめる。
```
時刻 [実行したスレッド名] ログレベル 実行したクラス - メッセージ
```
|項目名|概要|
|:---|:---|
|時刻|ログを出力した時刻|
|実行したスレッド名|プログラムを実行しているスレッドの名前(今回のデバックでは用いないので無視して問題ない。)
|ログレベル|実行環境によっては出力するログに制限をつけ一部のログだけ出力したいときもある。その時に利用するためのレベル。(今回のデバックでは用いないので無視して問題ない。)|
|実行したクラス|実行したクラス名が出力される。末尾の名前がクラス名となる。|
|メッセージ|実行した処理の内容を出力している。このメッセージは任意で設定できる。|
実際に動かしてログを見てみると以下のようになっている。試してみてほしい。
```
2019-06-12 15:50:56.045 INFO 13704 --- [ main] system.Application : Started Application in 16.049 seconds (JVM running for 17.456)
2019-06-12 15:51:14.860 INFO 13704 --- [io-8080-exec-10] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring FrameworkServlet 'dispatcherServlet'
2019-06-12 15:51:14.860 INFO 13704 --- [io-8080-exec-10] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization started
2019-06-12 15:51:14.989 INFO 13704 --- [io-8080-exec-10] o.s.web.servlet.DispatcherServlet : FrameworkServlet 'dispatcherServlet': initialization completed in 129 ms
2019-06-12 15:51:15.674 INFO 13704 --- [io-8080-exec-10] system.common.LogInterceptor : class system.controller.BookController.listBooks() Start.
2019-06-12 15:51:15.697 INFO 13704 --- [io-8080-exec-10] system.common.LogInterceptor : class system.service.BookService.findAllBooks() Start.
Hibernate:
SELECT
*
from
Book
2019-06-12 15:51:15.854 INFO 13704 --- [io-8080-exec-10] system.common.LogInterceptor : class system.service.BookService.findAllBooks() End.
2019-06-12 15:51:15.855 INFO 13704 --- [io-8080-exec-10] system.common.LogInterceptor
```
上記ログから分かることは、以下の通り。
- 書籍管理システムの起動が完了したこと。
- ``BookController``クラスの``listBooks``メソッドが呼ばれ、DBクラスによりSQLを実行、そのメソッドの処理が完了したこと。
- 実行したSQLが、``SELECT * from Book``であること。
また、Eclipseのコンソールにメッセージを出力させたい場合は、出力したい箇所で``System.out.println("[メッセージ]");``を記述すればよい。
例えば、``listBooks``メソッドが呼ばれたときに「testtest」と出力させたい場合は、以下のように記述すればよい。
```java
public String listBooks(TitleSearch search, ModelMap model) {
// コンソール出力を記述
System.out.println("testtest");
// サービスより、書籍を全件取得する。
List<Book> books = service.findAllBooks();
// サービスから取得した書籍リストを画面に設定する。
model.addAttribute("books", books);
// 一覧画面を返却する。
return "list";
}
```
### デバッガ―による挙動確認
デバッガにより逐次実行しながら、プログラムの挙動を確認することもできる。簡単に手順を以下に示す。
1. 挙動を確認したいプログラムを開き、左側行番号隣のスペースをダブルクリックする。すると、青い円形マークが付く。
デバッグ実行すると、この場所でプログラムが一時停止することになる。

1. Application.javaをを右クリックし、「デバッグ」から「Javaアプリケーション」を選択する。
1. デバッガのパースペクティブを開きますかとのメッセージが表示されるので、「はい」を押下する。

1. ツールバー上のステップオーバーのボタンを押下すると次の行に進めることができる。
- ステップインは、そのメソッドの中も逐次実行することを意味する。
- ステップオーバーは、そのメソッドの中は飛ばして次の行に進めることを意味する。
1. 確認したいところをステップ実行できたら、「再開」ボタンを押下する。

元の画面に戻すときは、右上のJavaボタンを押下する。
|
Python | UTF-8 | 3,853 | 2.53125 | 3 | [] | no_license | # https://blog.csdn.net/qq_27261889/article/details/90675051
import cv2
import numpy as np
import matplotlib.pyplot as plt
from scipy import fftpack
def high_pass_filter(img, radius=80):
r = radius
rows, cols = img.shape
center = int(rows / 2), int(cols / 2)
mask = np.ones((rows, cols, 2), np.uint8)
x, y = np.ogrid[:rows, :cols]
mask_area = (x - center[0]) ** 2 + (y - center[1]) ** 2 <= r * r
mask[mask_area] = 0
return mask
def low_pass_filter(img, radius=100):
r = radius
rows, cols = img.shape
center = int(rows / 2), int(cols / 2)
mask = np.zeros((rows, cols, 2), np.uint8)
x, y = np.ogrid[:rows, :cols]
mask_area = (x - center[0]) ** 2 + (y - center[1]) ** 2 <= r * r
mask[mask_area] = 1
return mask
def bandreject_filters(img, r_out=300, r_in=35):
rows, cols = img.shape
crow, ccol = int(rows / 2), int(cols / 2)
radius_out = r_out
radius_in = r_in
mask = np.zeros((rows, cols, 2), np.uint8)
center = [crow, ccol]
x, y = np.ogrid[:rows, :cols]
mask_area = np.logical_and(((x - center[0]) ** 2 + (y - center[1]) ** 2 >= r_in ** 2),
((x - center[0]) ** 2 + (y - center[1]) ** 2 <= r_out ** 2))
mask[mask_area] = 1
mask = 1 - mask
return mask
def guais_low_pass(img, radius=10):
rows, cols = img.shape
center = int(rows / 2), int(cols / 2)
mask = np.zeros((rows, cols, 2), np.float32)
x, y = np.ogrid[:rows, :cols]
for i in range(rows):
for j in range(cols):
distance_u_v = (i - center[0]) ** 2 + (j - center[1]) ** 2
mask[i, j] = np.exp(-0.5 * distance_u_v / (radius ** 2))
return mask
def guais_high_pass(img, radius=10):
rows, cols = img.shape
center = int(rows / 2), int(cols / 2)
mask = np.zeros((rows, cols, 2), np.float32)
x, y = np.ogrid[:rows, :cols]
for i in range(rows):
for j in range(cols):
distance_u_v = (i - center[0]) ** 2 + (j - center[1]) ** 2
mask[i, j] = 1 - np.exp(-0.5 * distance_u_v / (radius ** 2))
return mask
def laplacian_filter(img, radius=10):
rows, cols = img.shape
center = int(rows / 2), int(cols / 2)
mask = np.zeros((rows, cols, 2), np.float32)
x, y = np.ogrid[:rows, :cols]
for i in range(rows):
for j in range(cols):
distance_u_v = (i - center[0]) ** 2 + (j - center[1]) ** 2
mask[i, j] = -4 * np.pi ** 2 * distance_u_v
return mask
def log_magnitude(img):
magnitude_spectrum = 20 * np.log(cv2.magnitude(img[:, :, 0], img[:, :, 1]))
return magnitude_spectrum
def get_condidate(fimg, thre=200):
img = cv2.imread(fimg)
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# first step: compute the FFT of original images
img_dft = cv2.dft(np.float32(img), flags=cv2.DFT_COMPLEX_OUTPUT)
img_dft_shift = np.fft.fftshift(img_dft)
# second step: compute the mask
# mask = bandreject_filters(img, r_out=90, r_in=40)
# mask = high_pass_filter(img, radius=50)
# mask = low_pass_filter(img, radius=100)
# mask = guais_low_pass(img, radius=30)
# mask = guais_high_pass(img, radius=50)
mask = laplacian_filter(img, radius=50)
# third step: fft of original images multiply the filter
fshift = img_dft_shift * mask
# do log to minize the region
spectrum_after_filtering = log_magnitude(fshift)
# Fourth step: IFFT
f_ishift = np.fft.ifftshift(fshift)
img_after_filtering = cv2.idft(f_ishift)
img_after_filtering = log_magnitude(img_after_filtering)
tmp = list(img_after_filtering.flatten())
tmp.sort(reverse=True)
thre = tmp[thre]
img_after_filtering = (img_after_filtering >= thre).astype(int)
return img_after_filtering
# get_condidate("data/attack_pic_2/patched_resnet50_0.1_50_37.jpg")
|
TypeScript | UTF-8 | 698 | 2.6875 | 3 | [] | no_license | export enum ElementType {
title,
subtitle,
text,
hr,
counter,
checkbox
}
export interface ElementData {
id: string;
type: ElementType;
label: string;
options: any;
value?: number;
}
export interface ElementProps {
data: ElementData;
isEditable: boolean;
onChange?: (elementData: ElementData) => void,
onRemove?: (elementData: ElementData) => void,
onUp?: (elementData: ElementData) => void,
onDown?: (elementData: ElementData) => void,
}
export type ScoutingTemplate = ElementData[];
export interface ScoutingData {
id: string,
isQRCodeScanned?: boolean;
matchID: string;
teamID: string;
values: number[]
} |
Markdown | UTF-8 | 21,295 | 3.25 | 3 | [
"MIT"
] | permissive | <style>
.section .reveal .state-background {
background: #ffffff;
}
.section .reveal h1,
.section .reveal h2,
.section .reveal p {
color: black;
margin-top: 50px;
text-align: center;
}
</style>
Introduction to hypothesis testing part II
========================================================
date: 04/16/2020
autosize: true
incremental: true
width: 1920
height: 1080
<h2 style="text-align:left"> Instructions:</h2>
<p style='text-align:left'>Use the left and right arrow keys to navigate the presentation forward and backward respectively. You can also use the arrows at the bottom right of the screen to navigate with a mouse.<br></p>
========================================================
<h2>Outline</h2>
* The following topics will be covered in this lecture:
* A short review of hypothesis testing
* Hypothesis testing and confidence intervals
* Examples of testing a hypothesis about a population proportion
* Examples of testing a hypothesis about a population mean
========================================================
## Review of hypothesis testing
<div style="float:left; width:45%;text-align:center;">
<img src="hypothesis_flow.png" style="width:100%" alt="Flowchart for hypothesis testing.">
<p style="text-align:center">
Courtesy of Mario Triola, <em>Essentials of Statistics</em>, 6th edition
</p>
</div>
<div style="float:left; width:55%">
<ul>
<li>We will begin a review of hypothesis testing -- recall:</li>
<ol>
<li><b>$H_0$</b> -- <strong>this is the null hypothesis</strong>.</li>
<ul>
<li>The null hypothesis is <b>symbolically</b> a statement about some <b style="color:#1b9e77">population parameter</b> <strong>begin equal $(=)$ to some value</strong>.</li>
</ul>
<li><b>$H_1$</b> -- <strong>this is the alternative hypothesis</strong>.</li>
<ul>
<li>The alternative hypothesis is the statement that the <b style="color:#1b9e77">population parameter</b> is <strong>different than the null</strong>.</li>
<li><b>Symbolically</b>, it will always take the form of <strong>$( > / < / \neq)$</strong> in terms of the <b style="color:#1b9e77">parameter</b> in question.</li>
<li>The form of the alternative hypothesis determines whether we consider a:</li>
<ol>
<li><b>$<$</b> -- left-sided test;</li>
<li><b>$>$</b> -- right-sided test; or a</li>
<li><b>$\neq$</b> -- two-sided test;</li>
</ol>
<li>in the measure of "extremeness" of the test statistic with respect to the null hypothesis.</li>
</ul>
</ol>
<li>Typically, our <b>research hypothesis</b> is phrased in terms of an <strong>inequality so that it is written as the alternative hypothesis</strong>.</li>
</ul>
========================================================
### Review of hypothesis testing continued
<div style="float:left; width:45%;text-align:center;">
<img src="hypothesis_flow.png" style="width:100%" alt="Flowchart for hypothesis testing.">
<p style="text-align:center">
Courtesy of Mario Triola, <em>Essentials of Statistics</em>, 6th edition
</p>
</div>
<div style="float:left; width:55%">
<ul>
<li>The first step is thus to <b>identify the claim</b> and <strong>write it as an equality, or more typically as an inequality</strong>.</li>
<li>We then write the contradictory claim and identify the <b>null hypothesis $H_0$</b> <strong>$(=)$</strong> and <b>alternative hypothesis $H_1$</b> <strong>$(< / > / \neq)$</strong>.</li>
<li>We then <b>assume the null hypothesis</b> and <strong>select a significance level $\alpha$</strong>.</li>
<ul>
<li>The significance level $\alpha$ is defined as<b>
$$\begin{align}
\alpha= P(\text{Rejecting the null }H_0\text{ when }H_0\text{ is actually true}).
\end{align}$$</b></li>
</ul>
<li>This is precisely due to the fact that,
<blockquote>
we reject the null hypothesis when the probability of observing a sample at-least-as extreme as our test statistic is less than $\alpha$, under the assumption of $H_0$.
</blockquote></li>
<li>The test statistic is the evidence from sampling that we compare with the null hypothesis;</li>
<ul>
<li>there is a possiblity that we <strong>incorrectly reject $H_0$</strong> due to chance based on sampling error, and this is with <b>probability $\alpha$</b>.</li>
</ul>
<li>This type of mistake is known as <b>type I error</b>, or a <strong>false positive in terms of favoring the alternative</strong>.</li>
<li>We measure <strong>how extreme a test statistic</strong> is (usually) with <b>P-values</b> or (less commonly) with <b>critical values</b>.</li>
</ul>
</div>
========================================================
### Review of hypothesis testing continued
<div style="float:left; width:55%;text-align:center;">
<img src="hypothesis_flow2.png" style="width:100%" alt="Flowchart for hypothesis testing.">
<p style="text-align:center">
Courtesy of Mario Triola, <em>Essentials of Statistics</em>, 6th edition
</p>
</div>
<div style="float:left; width:45%">
<ul>
<li>Actually, P-values and critical values are <strong>equivalent representations</strong> of the same measure of <b>at-least-as-extreme</b> as.</li>
<li>In the case of critical values, we construct the region for which:</li>
<ol>
<li><b>$H_1:<$</b> -- there is probability of $\alpha$ for randomly selecting an observation to the left of this region;</li>
<li><b>$H_1:>$</b> -- there is a probability of $\alpha$ for randomly selecting an observation to the right of this region; or</li>
<li><b>$H_1: \neq$</b> -- there is a probability of $\frac{\alpha}{2}$ of randomly selecting an observation to the left, or $\frac{\alpha}{2}$ of randomly selecting an observation to the right.</li>
</ol>
</ul>
</div>
<div style="float:left; width:100%">
<ul>
<li>With P-values, instead of graphically considering the region, we numerically compute the probability (P-value) of randomly selecting an observation at-least-as extreme as our test statistic directly.</li>
<li>We make the same considerations as above with respect to the form of the alternative hypothesis when we compute this probability.</li>
<li>For left or right sided tests, we find the <strong>probability of randomly selecting an observation at-least-as far left / far right</strong> (<b>$H_1: <$</b> or <b>$H_1: >$</b>).</li>
<li>For two sided tests, we find the <strong>probability of randomly selecting an observation at-least-as far from the center in either direction</strong> <b>$H_1:\neq$</b>.</li>
</ul>
</div>
========================================================
## Confidence intervals and hypothesis testing
<ul>
<li>Before we go through examples, we should make one note about the correspondence between hypothesis testing and confidence intervals.</li>
<li>Actually, <b>hypothesis tests / confidence intervals of the mean and the standard deviation</b>, these are <strong>totally equivalent</strong>.</li>
<li>Indeed, let us suppose that we have some confidence interval,
$$(\overline{x} - E, \overline{x} - E)$$
at a $(1-\alpha)\times 100\%$ level of confidence.</li>
<li>Remember, this confidence interval depends on a random realization of the <b style="color:#d95f02">sample mean $\overline{x}$</b> and, possibly, a random realization of the <b style="color:#d95f02">sample standard deviation $s$</b>.</li>
<li>Suppose we had a <b>hypothetical value for the mean $\tilde{\mu}$</b> that we wanted to test as the null,
$$H_0: \mu = \tilde{\mu},$$
with $\alpha$ significance.</li>
<li>If we found that <strong>$\tilde{\mu}$ was not in the interval</strong>
$$(\overline{x} - E, \overline{x} + E),$$
we could equivalently <b>reject the null $H_0:\mu=\tilde{\mu}$ with $\alpha$ significance</b>.</li>
<li>The same is not true for hypothesis tests and our earlier confidence intervals of population proportions, due to the approximations we made for this confidence interval.</li>
<li>More advanced techniques, mentioned briefly, don't suffer from this inconsistency however, and modern statistical software can make this consistent in the calculation.</li>
</ul>
========================================================
## Examples of testing hypotheses for a population proportion
<div style="float:left; width:30%;text-align:center;">
<img src="p_value_method.png" style="width:100%" alt="P-value of the hypothesis test.">
<img src="critical_value_method.png" style="width:100%" alt="Critical region of the hypothesis test.">
<p style="text-align:center">
Courtesy of Mario Triola, <em>Essentials of Statistics</em>, 6th edition
</p>
</div>
<div style="float:left; width:70%">
<ul>
<li>We will now demonstrate how to solve the earlier example of drone-based delivery but with technology, in both the P-value and critical value methods.</li>
<li>Let's recall that there were $n=1009$ total observations in the survey in which participants were asked if they were uncomfortable with drone-based delivery of household goods.</li>
<li>$545$ participants responded that they were uncomfortable with drone-based delivery.</li>
<li>This means that using the <b>normal distribution approximation is OK</b>, because there are at <strong>least $5$ successes and at least $5$ failures</strong>, when we count a success as a response is opposed to drone-based delivery.</li>
<li>The null and alternative hypotheses were given
$$\begin{align}
H_0:p=0.5 & & H_1: p> 0.5.
\end{align}$$
and we selected a significance level of $\alpha=0.05$.</li>
<li>We computed the test statistic as,
$$\frac{\hat{p} - p}{\sqrt{\frac{p\times q}{n}}} = \frac{0.540 - 0.50}{\sqrt{\frac{0.5\times 0.5}{1006}}} \approx 2.54.$$</li>
<li>To the left, we see equivalent wasy of viewing the test statistic -- on the top with the P-value and on the bottom with the critical region with $z_\alpha = 1.645$ corresponding to $\alpha\times 100\% = 5\%$.</li>
<li>We will now go through how to compute both of these directly in StatCrunch.</li>
</ul>
</div>
========================================================
### Examples of testing hypotheses for a population proportion continued
<ul>
<li>Let us now consider a new example.</li>
<li>In a study in Neurology magazine, the authors found that approximately $29.2\%$ of studied participants among $19,136$ total had sleepwalked at some point.</li>
<li><b>Consider the following:</b> let $p$ be the population parameter for the number of US adults who have sleep walked.</li>
<li>Suppose we want to claim that fewer than $30\%$ of the population of US adults have sleepwalked. What would be the appropriate null $H_0$ and alternative $H_1$ hypothesis in this case?</li>
<ul>
<li>Notice that our claim is given as $p< 0.3$, so that the contradictory claim would be given as $p\geq 0.3$.</li>
<li>Then, the smallest proportion of US adults who could have sleepwalked without being less than $30\%$ is exactly $p=0.3$.</li>
<li>When we identify the null hypothesis $H_0:=$ and the alternative hypothesis $H_1: > / < / \neq$, we should find
$$\begin{align}
H_0: p=0.3 & & H_1: p < 0.3.
\end{align}$$</li>
</ul>
<li>Suppose we want to test this hypothesis with a significance level of $\alpha =0.05$. Recall that in StatCrunch we had to input the total number of observations and the total number of successes.</li>
<li>However, we only have a value of $\hat{p}=29.2\%$ of the sample in this case.</li>
<li><b>Consider the following:</b> if $x$ is the value of the number of successes, i.e., the number total participants in the sample who have sleep walked, how can we find this from the above?</li>
<ul>
<li>Recall, $\hat{p}= \frac{x}{n}$ so that,
$$n \times \hat{p} = 19136 \times 0.292 = 5587.712 \approx x .$$</li>
<li>We need to round this to a whole number of participants, so the closest one is $x= 5588$, which we will take in this example.</li>
</ul>
</ul>
========================================================
### Examples of testing hypotheses for a population proportion continued
<ul>
<li>Recall, our test statistic for the hypothesis test is the z score of $\hat{p} = \frac{5588}{19136}$ under the null hypothesis that the mean of the sampling distribution is $p =0.3$, with standard deviation (standard error)
$$\sigma_{\hat{p}} = \sqrt{\frac{p\times q }{n}}.$$
</li>
<li><b>Consider the following:</b> can you compute the test statistic given the above information?</li>
<ul>
<li>Given the above, we have $q = 1.0 - 0.3 = 0.7$ so that the z score is given
$$z = \frac{\hat{p} - p }{\sqrt{\frac{p\times q}{n}}} =\frac{\frac{5588}{19136} - 0.3}{\sqrt{\frac{0.3\times 0.7}{19136}}}\approx -2.41$$
</ul>
<li>If you remember the value for the $z_\alpha = z_{0.05}\approx 1.645$ you can deduce the critical region for the left-sided hypothesis test by the symmetry of the normal distribution.</li>
<li>However, we will now use StatCrunch to evaluate the hypothesis directly in the following.</li>
</ul>
========================================================
### Examples of testing hypotheses for a population proportion continued
<ul>
<li>We should emphasize that using the <b>z score as the test statistic</b> is usually only appropriate when there are <strong>at least $5$ successes and at least $5$ failures for the binomial trial</strong>.</li>
<li>This is what allows us to use the <b>normal distribution</b> as a good <strong>approximation for the binomial distribution</strong>.</li>
<li>However, when we use statistical software, we will usually compute the test statistic exactly from the binomial distribution, without the normal approximation.</li>
<li>Therefore, we can make a hypothesis test with a small number of samples using statistical software directly.</li>
<li>Suppose we have a small sample size of $10$ couples who are given a fertility treatment which is claimed to increase the rate of new born girls above $75\%$.</li>
<li><b>Consider the following:</b> let's suppose that $9$ out of $10$ babies are girls -- can we claim with $\alpha=0.05$ significance that this is correct?</li>
<ul>
<li>Notice that if $p$ is the population proportion of girls born under the treatment then
$$\begin{align}
H_0:p=0.75 && H_1:p>0.75
\end{align}$$
as $p=0.75$ is the largest proportion of baby girls that can contradict the claim.</li>
<li>The z score is no longer relevant here because we have too few samples, but we can compute the hypothesis test directly in StatCrunch as follows.</li>
</ul>
</ul>
========================================================
## Examples of testing hypotheses for a population mean
<ul>
<li>We will now consider some examples of making hypothesis tests for a population mean.</li>
<li>We should recall here the requirements that we have for making such a test, which are the same as for computing a confidence interval:</li>
<ul>
<li>Observations should come from <b>simple random sampling</b>.</li>
<li>The observations $x_1, \cdots, x_n$ can come from <b>any underlying distribution</b>...</li>
<li> however, if it is <b>non-normal</b>, <strong>there should be $n>30$ observations in the sample for the distribution of $\overline{x}$ to be sufficiently normal</strong>.</li>
<li>Generally we <b>do not know $\sigma$</b>, and in this case we use the test statistic,
$$\frac{\overline{x} - \mu}{\frac{s}{\sqrt{n}}},$$
distributed according to a <b>student t</b> with <strong>$n-1$ degrees of freedom</strong>.</li>
<li>In the rare case when <b>$\sigma$ is known</b>, we can use the test statistic,
$$\frac{\overline{x} - \mu}{\frac{\sigma}{\sqrt{n}}}$$
which is distributed as a <b>standard normal</b>.</li>
</ul>
<li>In general, we will of course try to use modern statistical software to make these computations, but it is important to understand how these pieces fit together even when we use software.</li>
</ul>
========================================================
### Examples of testing hypotheses for a population mean continued
<div style="float:left; width:55%;text-align:center;">
<img src="normality.png" style="width:100%" alt="Histogram and q-q plot of the sample.png" style="width:100%" alt="Critical region of the hypothesis test.">
<p style="text-align:center">
Courtesy of Mario Triola, <em>Essentials of Statistics</em>, 6th edition
</p>
</div>
<div style="float:left; width:45%">
<ul>
<li>Let's suppose that the $n=12$ observations to the left come from a simple random sample of US adults.</li>
<li>The measurments are the number of hours of sleep that each individual has per night on average over the year.</li>
<li>The sample mean is given as $\overline{x}\approx 6.8333$ hours and the sample standard deviation is given as $s =1.9924$ hours.</li>
</ul>
</div>
<div style="float:left; width:100%">
<ul>
<li><b>Consider the following</b> can we use a hypothesis test with this data to claim with $\alpha=0.05$ significance that the population mean number of hours of sleep is less than $7$ hours? Are the necessary assumptions satisfied?</li>
<ul>
<li>Using the histogram and the Q-Q plot, we can see that the <b>sample is approximately normal</b>:</li>
<ul>
<li>there is a <strong>symmetric bell shape to the histogram with no outliers, and the Q-Q plot roughly follows the diagonal line</strong>.</li>
</ul>
<li>Then, given the above claim we have,
$$\begin{align}
H_0: \mu = 0.7 & & H_1: \mu < 0.7
\end{align}$$
as $\mu=0.7$ is the largest number of hours of sleep that contradicts the above claim.</li>
<li>The test statistic is thus given as
$$\frac{\overline{x} - \mu}{\frac{s}{\sqrt{n}}} = \frac{6.8333 - 0.7 }{\frac{1.9924}{\sqrt{12}}} \approx -0.290.$$
</ul>
</ul>
========================================================
### Examples of testing hypotheses for a population mean continued
<div style="float:left; width:35%;text-align:center;">
<img src="mean_critical_value.png" style="width:100%" alt="Histogram and q-q plot of the sample.png" style="width:100%" alt="Critical region of the hypothesis test.">
<p style="text-align:center">
Courtesy of Mario Triola, <em>Essentials of Statistics</em>, 6th edition
</p>
</div>
<div style="float:left; width:65%">
<ul>
<li>From the last slide we had a test statistic
$$\frac{\overline{x} - \mu}{\frac{s}{\sqrt{n}}} = \frac{6.8333 - \mu }{\frac{1.9924}{\sqrt{12}}} \approx -0.290.$$
which must be <b>t distributed</b> because we used the <b style="color:#d95f02">sample standard deviation $s$</b>.</li>
<li>Also, we know that with $n=12$ observations, we have precisely <b>$n-1=11$ degrees of freedom</b> for the student t distribution.</li>
<li>With the test statistic in hand, we can evaluate the hypothesis test by either:</li>
<ol>
<li>the <b>left-sided critical value</b>; or</li>
<li>the <b>left-sided P-value</b>;
</ol>
<li>to measure <b>if the probability of randomly selecting a sample mean at least as extreme as $\overline{x}=6.8333$</b> <strong>under the null hypothesis is less than $\alpha=0.05$</strong>.</li>
<li>Moreover, for the <b>hypothesis tests of the mean</b>, this is <strong>completely equivalent to finding the $(1-\alpha)\times 100\%=95\%$ confidence interval for the mean</strong>.</li>
</ul>
</div>
<div style="float:left; width:100%">
<ul>
<li>We will examine each of these methods in StatCrunch directly as follows.</li>
</ul>
</div>
========================================================
### Examples of testing hypotheses for a population mean continued
<ul>
<li>As a final example, we will consider the claim that the population mean body temperature is $\mu=98.6$ degrees F.</li>
<li>We suppose that we have have $n=106$ observations with a sample mean of $98.20$ degrees F, and a sample standard deviation of $s= 0.62$ degrees F, and that we wish to test this with $\alpha=0.05$ significance.</li>
<li><b>Consider the following:</b> in this example, what are the null and alternative hypotheses?</li>
<ul>
<li>In this case, the <b>contradictory claim</b> is <strong>actually the alternative hypothesis</strong>,
$$\begin{align}
H_0: \mu = 98.6 & & H_1: \mu \neq 98.6
\end{align}$$</li>
</ul>
<li>In this case, because we <b>can only reject the null in favor of the alternative</b>, <strong>we cannot provide proof that $\mu=98.6$ degrees F</strong>.</li>
<ul>
<li>Indeed, we only have the possibility of providing evidence that $\mu=98.6$ degrees F is unlikely.</li>
</ul>
<li>The test statistic,
$$\frac{\overline{x} - \mu}{\frac{s}{\sqrt{n}}} = \frac{98.2 - 98.6}{\frac{0.62}{\sqrt{106}}} \approx -6.64.$$
<li>We have $n=106$ observations, so we have enough data to perform the hypothesis test by the critical value method, the P-value method, or by confidence intervals for the mean.</li>
<li>We will go through each of these in the following.</li>
</ul>
|
Java | UTF-8 | 1,129 | 3.015625 | 3 | [] | no_license | package game;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import org.junit.Before;
import org.junit.Test;
import commands.Command;
import state.StateMachine;
import utils.Props;
public class GameBoardTest {
private int size;
@Before
public void setup() throws NumberFormatException, Exception {
this.size = Props.readGridSize();
}
@Test
public void stateMachineIsSuccessfullyCreated() throws Exception {
GameBoard gameBoard = new GameBoard();
StateMachine stateMachine = StateMachine.getInstance();
stateMachine.mutateState(new Command(0, 0, "X"));
gameBoard.injectStateMachine(stateMachine);
assertNotNull("State Machine is created.", gameBoard.stateMachine);
assertEquals(this.size, gameBoard.stateMachine.getState().length);
}
@Test
public void gameBoardIsDrawedCorrectly() throws Exception {
GameBoard gameBoard = new GameBoard();
StateMachine stateMachine = StateMachine.getInstance();
stateMachine.mutateState(new Command(0, 0, "X"));
gameBoard.injectStateMachine(stateMachine);
gameBoard.draw();
}
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.