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
Python
UTF-8
1,341
2.96875
3
[]
no_license
# -*- coding: utf-8 -*- """ Created on Wed Apr 20 12:54:18 2016 @author: Administrator """ import csv def SplitTime(): read_user = csv.reader(file(r'tianchi_fresh_comp_train_user.csv', 'rb')) writer = csv.writer(file('WashedData-simplified.csv', 'wb')) i=0; for row in read_user: if i==0: writer.writerow(['user_id', 'item_id', 'behavior_type','month','day','hour']); i+=1; else: a=row[5].replace('-',' '); a=a.split(); b=[(row[0]),(row[1]),(row[2]),(a[1]),(a[2]),(a[3])]; writer.writerow(b); def ExtractDayXtoY(x,y): # x and y belong to 1 to 31 read_user = csv.reader(file(r'WashedData-simplified.csv', 'rb')) writer = csv.writer(file('Day'+str(x)+'To'+str(y)+'.csv', 'wb')) firstday = 17+x; lastday = 17+y; month = 12; i=0; for row in read_user: if i==0: writer.writerow(['user_id', 'item_id', 'behavior_type']); i+=1; else: temp=int(row[4]); if int(row[3])==month: temp+=30; if temp>=firstday and temp<=lastday: writer.writerow([(row[0]),(row[1]),(row[2])]); if __name__=="__main__": # SplitTime(); # ExtractDayXtoY(1,3); ExtractDayXtoY(29,31);
C++
UTF-8
1,067
3.078125
3
[]
no_license
using namespace std; class find_ { protected: int lb,ub; //STUDENT CODE HERE---------------------------------- public: void get(); }; class der_prime:public find{ protected: int num,i,j,k,count=0; int a[100],b[100]; public: void detect_prime(); void print(); }; void find::get(){ cin>>lb>>ub; } void der_prime::detect_prime(){ for(i=lb;i<=ub;i++) { for(j=0;j<=ub;j++) { a[j]=i; } } for(i=0;i<ub;i++) { for(k=0;k<ub;k++){ for(j=2;j<ub;j++) { if(a[i]%j==0) { count++; break; } if(count==0) { a[i]=b[k]; } } } }//for storing,finding prime from range //now for occurance/frequency }//func bracket void der_prime::print(){ } //---------------------------------------------------- int main() { static der_prime d1; d1.get(); //function in base class to enter lower bound(lb) and upper bound values(ub) d1.detect_prime(); // this function is responible for logic building in derived class(der_prime) d1.print_();//print the desired output in derived class return 0; }
JavaScript
UTF-8
1,551
3.40625
3
[]
no_license
// Je vous présente ici une liste de film // chaque film dispose de trois élement: Un tableau de tags, un nom, et une notes // Nous voulons rajouter un film à ce tableau // Vérifiez si cet élément n'est pas déjà présent dans le tableau // Trouvez une méthode permettant de chercher simplement dans un tableau tout en renvoyant vrai ou faux // Pour vérifier vos résultats lancez la commande "npm run test:7" dans votre terminal function test() { var films = [ { nom: 'Star wars - 1 ère trilogie', note: 9, tags: ['sf', 'espace', 'pewpew'] }, { nom: 'Seigneur des anneaux', note: 8, tags: ['fantaisie', 'forêt', 'piedspoilus'] }, { nom: 'Matrix', note: 6, tags: ['sf', 'pillule', 'smith'] }, { nom: '300', note: 7, tags: ['historique', 'baston', 'hommetoutnus'] }, { nom: 'Les razmokets', note: 10, tags: ['dessin annimés', 'Dynosaure', 'enfant'] } ] const nouveauFilm = { nom: 'Seigneur des anneaux', note: 8, tags: ['fantaisie', 'forêt', 'piedspoilus'] } return films .some(function(item) { return item.nom === nouveauFilm.nom }) // Le résultat doit être de la manière suivante : true // Envoyez votre résultat en faisant "return <variableContenantLeRésultat>" } module.exports = test;
JavaScript
UTF-8
498
3.609375
4
[]
no_license
const increment = document.querySelector('button[data-action="increment"]'); const decrement = document.querySelector('button[data-action="decrement"]'); const span = document.querySelector('#value'); let counterValue = Number(span.textContent); const updateValue = value => { counterValue = counterValue + value; span.textContent = counterValue; }; increment.addEventListener('click', () => { updateValue(1); }); decrement.addEventListener('click', () => { updateValue(-1); });
PHP
SHIFT_JIS
810
3.25
3
[]
no_license
<pre> <?php /* uPCRE(Perl݊)v̕NX͗ႦΈȉ̂悤Ȃ̂܂B \d@Ƀ}b`܂B[0-9]ƓłB \s@zCgXy[XɃ}b`܂B[\n\r\t\f]ƓłB \w@PꕶɃ}b`܂B[a-zA-Z0-9]ƓłB ܂Aqu啶vɂƈӖ]̂ŁÂ悤ɊoĂƂ悢ł傤B \D@ȊOɃ}b`܂B[^0-9]ƓłB \S@zCgXy[XȊOɃ}b`܂B[^\n\r\t\f]ƓłB \W@PꕶȊOɃ}b`܂B[^a-zA-Z0-9]ƓłB */ // $string = '0123456789abcdefghijk'; $ret = preg_match('/\w/', $string, $matches); var_dump($ret); var_dump($matches);
Python
UTF-8
3,401
2.78125
3
[]
no_license
#!/usr/bin/env python import unittest from dominion import Card, Game, Piles ############################################################################### class Card_Courtier(Card.Card): def __init__(self): Card.Card.__init__(self) self.cardtype = Card.CardType.ACTION self.base = Card.CardExpansion.INTRIGUE self.desc = """Reveal a card from your hand. For each type it has (Action, Attack, etc.), choose one: +1 Action; or +1 Buy; or +3 Coin; or gain a Gold. The choices must be different.""" self.name = "Courtier" self.cost = 5 def special(self, game, player): cards = player.card_sel() if not cards: return if isinstance(cards[0].cardtype, list): num_types = len(cards[0].cardtype) else: num_types = 1 chosen = [] for _ in range(num_types): choices = [] if "action" not in chosen: choices.append(("+1 Action", "action")) if "buy" not in chosen: choices.append(("+1 Buy", "buy")) if "coin" not in chosen: choices.append(("+3 Coin", "coin")) if "gold" not in chosen: choices.append(("Gain Gold", "gold")) opt = player.plr_choose_options("Select one", *choices) chosen.append(opt) if opt == "action": player.add_actions(1) if opt == "buy": player.buys.add(1) if opt == "coin": player.coins.add(3) if opt == "gold": player.gain_card("Gold") ############################################################################### class Test_Courtier(unittest.TestCase): def setUp(self): self.g = Game.TestGame(numplayers=1, initcards=["Courtier", "Moat"]) self.g.start_game() self.plr = self.g.player_list(0) self.card = self.g["Courtier"].remove() self.plr.piles[Piles.HAND].set("Copper", "Moat", "Estate") self.plr.add_card(self.card, Piles.HAND) def test_play_action(self): self.plr.test_input = ["Copper", "+1 Action"] self.plr.play_card(self.card) self.assertEqual(self.plr.actions.get(), 1) self.assertEqual(self.plr.buys.get(), 1 + 0) self.assertEqual(self.plr.coins.get(), 0) self.assertNotIn("Gold", self.plr.piles[Piles.DISCARD]) def test_play_buy(self): self.plr.add_card(self.card, Piles.HAND) self.plr.test_input = ["Moat", "+1 Buy", "+3 Coin"] self.plr.play_card(self.card) self.assertEqual(self.plr.actions.get(), 0) self.assertEqual(self.plr.buys.get(), 1 + 1) self.assertEqual(self.plr.coins.get(), 3) self.assertNotIn("Gold", self.plr.piles[Piles.DISCARD]) def test_play_gold(self): self.plr.add_card(self.card, Piles.HAND) self.plr.test_input = ["Estate", "Gain Gold"] self.plr.play_card(self.card) self.assertEqual(self.plr.actions.get(), 0) self.assertEqual(self.plr.buys.get(), 1 + 0) self.assertEqual(self.plr.coins.get(), 0) self.assertIn("Gold", self.plr.piles[Piles.DISCARD]) ############################################################################### if __name__ == "__main__": # pragma: no cover unittest.main() # EOF
Java
UTF-8
831
2.375
2
[]
no_license
package http.servlet; import http.responserequest.Request; import http.responserequest.Response; /** * @author: chain * @create: 2020/02/17 **/ public class RegistServlet implements ServletInterface { @Override public void service() { System.out.println("正在使用注册服务..."); } @Override public void service(Request request, Response response) { response.print("<html>"); response.print("<head>"); response.print("<title>"); response.print("regist_servlet"); response.print("</title>"); response.print("</head>"); response.print("<body>"); response.print("regist:"+request.getParamValue("uname")); response.print("</body>"); response.print("</html"); System.out.println("注册成功..."); } }
Python
UTF-8
8,892
3.09375
3
[ "MIT" ]
permissive
import re from nltk import pos_tag from nltk import word_tokenize import requests from bs4 import BeautifulSoup from nltk.corpus import wordnet as wn import sys def load_comment_idioms(filename): samples = [] with open(filename,'r', encoding="utf-8") as f: f.readline() for l in f: l = l.strip().replace('\n','').split('\t') if len(l) == 3: samples.append((l[0].strip(),l[1].strip(),l[2].strip())) return samples def crawl_dict(idiom): ''' Obtain the paraphrases from the lists of synonyms stored in the dictionary :param idiom: string :return: idiomatic paraphrase if available, one word paraphrase if not ''' not_found = False article = ["a", "the", "(you)", "to", "something"] tokens = idiom.lower().split() idiom_suff = "-".join(tokens) link = 'https://www.macmillanthesaurus.com/' + idiom_suff page = requests.get(link) replacement_idiom = 0 replacement_word = 0 # if there is no entry for the idiom, try to modify it: if str(page) == "<Response [404]>": # try to vary get and come if "get" in tokens: index = idiom.find("get") + 3 tokens = idiom[index:].split() idiom_suff = idiom[:index] + "-come-" + "-".join(tokens) idiom = idiom[:index] + "/come" + idiom[index:] link = 'https://www.macmillanthesaurus.com/' + idiom_suff page = requests.get(link) else: # try articles, "some", "you" i = 0 while (str(page) == "<Response [404]>" and i < len(article)): if ("(" or ")") in article[i]: idiom_suff = article[i][1:-1] + "-" + "-".join(tokens) new_idiom = "\\" + article[i][:-1] + "\\)" + " " + idiom elif article[i] == "something": idiom_suff = "-".join(tokens) + "-" + article[i] new_idiom = idiom + " " + article[i] else: idiom_suff = article[i] + "-" + "-".join(tokens) new_idiom = article[i] + " " + idiom link = 'https://www.macmillanthesaurus.com/' + idiom_suff page = requests.get(link) i += 1 idiom = new_idiom # if after the trial the idiom was not found if str(page) == "<Response [404]>": print("Idiom not found: {}".format(idiom)) not_found = True return 0,0 if not_found == False: print("Processing idiom {}".format(idiom)) soup = BeautifulSoup(page.content, 'html.parser') # print(soup) search_string = "Synonyms for '{}': ".format(idiom) pattern = re.compile(r'(?<={0}).+(?=" name=\"description\")'.format(search_string)) # print(pattern) syns = re.findall(pattern, str(soup)) # print(syns) if len(syns) == 0: return 0, 0 else: syn_list = syns[0].split(", ") idiom_syns = [syn for syn in syn_list if (len(syn.split()) >= 3 and "(" in syn)] word_syns = [syn for syn in syn_list if not syn in idiom_syns] print("Found replacements") if len(idiom_syns) > 0 and len(word_syns) > 0: replacement_idiom = idiom_syns[0] replacement_word = word_syns[0] # print("Found 1") elif len(idiom_syns) == 0 and len(word_syns) > 1: replacement_idiom = word_syns[0] replacement_word = word_syns[1] # print("Found 2") elif len(word_syns) == 0 and len(idiom_syns) > 1: replacement_idiom = idiom_syns[0] replacement_word = idiom_syns[1] # print("Found 3") else: print("No replacements found") replacement_idiom = 0 replacement_word = 0 return replacement_idiom, replacement_word def get_non_paraphrases(idiom): ''' Obtain bad paraphrases (literal replacements) from wordnet :param idiom: string - idiom :return: ''' nouns = ["NN", "NNP", "NNS"] verbs = ["VB", "VBD", "VBG", "VBN", "VBP", "VBZ"] tokens = word_tokenize(idiom) parse = pos_tag(tokens) hypernyms = {} hyponyms = {} result_hypers = {} result_hypos = {} for element in parse: if element[1] in nouns: w_senses = wn.synsets(element[0], pos='n') elif element[1] in verbs: w_senses = wn.synsets(element[0], pos='v') else: continue if len(w_senses) == 0: print("No senses found for idiom: {}".format(idiom)) break else: i = 0 hypers = w_senses[i].hypernyms() while len(hypers) == 0 and i < len(w_senses)-1: i+=1 hypers = w_senses[i].hypernyms() if len(hypers) == 0: break else: hyper = w_senses[i].hypernyms()[0].name() hypernyms[element[0]] = hyper j = 0 hypos = w_senses[j].hyponyms() while len(hypos) == 0 and j < len(w_senses)-1: j += 1 hypos = w_senses[j].hyponyms() if len(hypos) == 0: break else: hypo = w_senses[j].hyponyms()[0].name() hyponyms[element[0]] = hypo if not len(hypernyms) == 0: for word, syn in hypernyms.items(): index = syn.find(".") syn = syn[:index].replace("_", " ") result_hypers[word] = syn if not len(hyponyms) == 0: for word, syn in hyponyms.items(): index = syn.find(".") syn = syn[:index].replace("_", " ") result_hypos[word] = syn nonpara1 = [] for word in tokens: if word in result_hypers.keys(): nonpara1.append(result_hypers[word]) else: nonpara1.append(word) nonpara1 = " ".join(nonpara1) nonpara2 = [] for word in tokens: if word in result_hypos.keys(): nonpara2.append(result_hypos[word]) else: nonpara2.append(word) nonpara2 = " ".join(nonpara2) return nonpara1, nonpara2 if __name__ == '__main__': samples = load_comment_idioms(sys.argv[1]) print("{} samples found".format(len(samples))) target_count = int(sys.argv[4]) done_count = 0 failed_count = 0 with open(sys.argv[2], 'a', encoding="utf-8") as w: with open(sys.argv[3], 'a', encoding="utf-8") as failed_p: w.write( "Idiom\tContextSentence\tFullComment\tTextParaphrase\tParaphraseValue\n") # for Paraphrase Value 0 = non paraphrase, 1 = paraphrase for sample in samples: if done_count == target_count: print("You have reached your goal to create {} samples. SICK!".format(target_count)) break paraphrase1, paraphrase2 = crawl_dict(sample[0]) print("Got paraphrases") nonparaphrase1, nonparaphrase2 = get_non_paraphrases(sample[0]) print("Got non-paraphrases") if paraphrase1 != 0 and paraphrase2 != 0: done_count += 1 w.write("{}\t{}\t{}\t{}\t{}\n".format(sample[0], sample[1], sample[2], sample[1].replace(sample[0], paraphrase1), 1)) w.write("{}\t{}\t{}\t{}\t{}\n".format(sample[0], sample[1], sample[2], sample[1].replace(sample[0], paraphrase2), 1)) w.write("{}\t{}\t{}\t{}\t{}\n".format(sample[0], sample[1], sample[2], sample[1].replace(sample[0], nonparaphrase1), 0)) w.write("{}\t{}\t{}\t{}\t{}\n".format(sample[0], sample[1], sample[2], sample[1].replace(sample[0], nonparaphrase2), 0)) else: failed_count +=1 failed_p.write("{}\t{}\t{}\t{}\t{}\n".format(sample[0], sample[1], sample[2], paraphrase1, 1)) failed_p.write("{}\t{}\t{}\t{}\t{}\n".format(sample[0], sample[1], sample[2], paraphrase2, 1)) failed_p.write("{}\t{}\t{}\t{}\t{}\n".format(sample[0], sample[1], sample[2], sample[1].replace(sample[0], nonparaphrase1), 0)) failed_p.write("{}\t{}\t{}\t{}\t{}\n".format(sample[0], sample[1], sample[2], sample[1].replace(sample[0], nonparaphrase2), 0)) print("Total: {}; Processed: {}, Paraphrased: {}; Failed: {}".format(len(samples), done_count+failed_count, done_count, failed_count))
Shell
UTF-8
2,458
3.234375
3
[ "MIT" ]
permissive
#!/usr/bin/env bash # _ __ ___ _ __ ___ ___ ___ # | '__/ _ \ '_ ` _ \ _____ / _ \/ __| # | | | __/ | | | | |_____| (_) \__ \ # |_| \___|_| |_| |_| \___/|___/ # # Install Script # Made by ablazingeboy#7375 # Why the fxxk did I spend time on this echo -e "\nInstalling necessary software, $USER-sama. No bloat, I promise.\n" PKGS=( 'base-devel' # Dev tools 'wget' # Remote content retrieval 'htop' # Process viewer 'fbv' # Framebuffer image viewer 'fortune-mod' # Fortune 'catimg' # Image backend 'micro' # Text editor 'python3' # Scripting language 'python3-pip' # Package manager for python 'lazygit' # Git client ) for PKG in "${PKGS[@]}"; do echo "Installing ${PKG}, $USER-sama" sudo xbps-install -S -y "$PKG" done echo -e "\nDone installing packages, $USER-sama!\n" micro -plugin install filemanager # ------------------------------------------------------------------------ echo -e "\nWriting a few notes for you, $USER-sama." DIRECTORY=$(cd `dirname $0` && pwd) strfile $DIRECTORY/resources/remquotes sudo rm -rf /usr/share/fortunes/* sudo mv $DIRECTORY/resources/remquotes $DIRECTORY/resources/remquotes.dat /usr/share/fortunes/ # ------------------------------------------------------------------------ echo -e "\nBuilding yaft, $USER-sama." cd $HOME git clone https://github.com/uobikiemukot/yaft cd yaft rm conf.h cp $DIRECTORY/resources/conf.h $HOME/yaft/ export LANG=en_US.UTF-8 make sudo make install # ------------------------------------------------------------------------ echo -e "\nMoving files, $USER-sama." cp $DIRECTORY/resources/bg.jpg $HOME cp $DIRECTORY/resources/rempixel.png $HOME cp $DIRECTORY/resources/.bashrc $HOME cp $DIRECTORY/resources/micro/settings.json $HOME/.config/micro mkdir $HOME/bin cp $DIRECTORY/resources/ufetch-rem $HOME/bin chmod +x $HOME/bin/ufetch-rem # ------------------------------------------------------------------------ echo -e "\nSetting your keymap to Colemak, $USER-sama\n" sudo sed -i -e "s|#\?KEYMAP=.*|KEYMAP=colemak|" /etc/rc.conf cd $pwd echo " ############################################################################### # Done! Enjoy your system, $USER-sama! Make sure to restart! ############################################################################### "
PHP
UTF-8
2,086
3.140625
3
[]
no_license
<?php // <!-- phpDesigner :: Timestamp [11/03/2016 06:00:20 p. m.] --> /** * MultiFacturas.com 2016 * Author: I.R.G. */ class GetTransactionFromPeriodResult { public static function fromArray($array) { // Se valida que sea un arreglo if(!is_array($array)) { throw new Exception(sprintf("%s::%s El parámetro de entrada debe ser un array.", __CLASS__, __FUNCTION__)); } // Se verifica que exista el elemento 'GetTransactionFromPeriodResult' if(!array_key_exists(__CLASS__, $array)) { throw new Exception(sprintf("%s::%s No se encontro el elemento '%s'.", __CLASS__, __FUNCTION__, __CLASS__)); } // Se extrae el código XML $xmlResponse = $array[__CLASS__]; // Se verifica que contenga algo la respuesta if(empty($xmlResponse)) { return array(); } // Se valida que sea un string (Código XML) if(!is_string($xmlResponse)) { throw new Exception(sprintf("%s::%s El parámetro debe ser del tipo string.", __CLASS__, __FUNCTION__)); } // Se convierte a UTF-8 $xmlResponse = utf8_encode($xmlResponse); // Se crea el documento apartir del XML $doc = new DOMDocument('1.0', 'utf-8'); $doc->loadXML($xmlResponse); // Se verifica el Nodo raíz del documento if($doc->documentElement->nodeName != __CLASS__) { throw new Exception(sprintf("%s::%s Error al procesar XML", __CLASS__, __FUNCTION__)); } // Arreglo de Transacciones de Venta $transactions = array(); // Se recorren los nodos hijos (Product) foreach($doc->documentElement->childNodes as $nodo) { if($nodo->nodeType == XML_ELEMENT_NODE) { // Se crea el producto $transaction = Product::fromXMLElement($nodo); // Se agrega al arreglo array_push($transactions, $transaction); } } // Se devuelven las transacciones return $transactions; } }
Markdown
UTF-8
4,541
3.0625
3
[]
no_license
--- title: 內建規則標籤 url: /user-guide/built-in-rule-tags/ --- 標籤是對規則和問題進行分類的一種方法。問題規則地繼承了引發它們的標籤。有些標籤僅適用於特定語言,但更多的標籤卻是跨語言的。使用者可以加入標籤至規則與問題中,但多數的規則都已具有現成的標籤。以下是部份內建規則標籤含義的列表: *注意:以下的連結 [rules.sonarsource.com](https://rules.sonarsource.com) 已針對 Java 語法進行篩選* * [大腦超載(brain-overload)](https://rules.sonarsource.com/java/tag/brain-overload):一時間有太多事情需要記住。 * [壞習慣(bad-practice)](https://rules.sonarsource.com/java/tag/bad-practice):程式照著設計方向撰寫,但其設計方式實質上被廣泛認為是一個壞主意。 * [憑證(cert)](https://rules.sonarsource.com/java/tag/cert):與 [憑證](https://www.securecoding.cert.org/confluence/x/BgE) 中的標準有關。目前有三種 CRET 標準:[C](https://www.securecoding.cert.org/confluence/x/HQE)、[C++](https://www.securecoding.cert.org/confluence/x/fQI) 和 [Java](https://www.securecoding.cert.org/confluence/x/Ux)。其中許多規則並不只限定於特定語言,而是良好的程式撰寫習慣。這就是為什麼您會在非 C、C++ 或 Java 的規則上看到這些標籤的原因。 * [笨拙(clumsy)](https://rules.sonarsource.com/java/tag/clumsy):可以更清楚、簡潔地完成某件事,卻使用額外的步驟完成。(例如:對字串使用 .toString() 語法)。 * [模糊(confusing)](https://rules.sonarsource.com/java/tag/confusing):將使程式維護人員花費較多的時間在理解程式碼,而不是由程式的實際作用來證明其合理性。 * [慣例(convention)](https://rules.sonarsource.com/java/tag/convention):程式碼慣例(coding convention);通常格式化(typically formatting);命名(naming);空白字元(whitespace)等。 * [通用缺陷列表 CWE](https://rules.sonarsource.com/java/tag/cwe):與 [通用缺陷列表(Common Weakness Enumeration)](http://cwe.mitre.org/) 中的規則相關。有關 CWE 和一般與安全相關的規則的更多信息,請參見 [安全相關規則(Security-related rules)](/user-guide/security-rules/)。 * [設計(design)](https://rules.sonarsource.com/java/tag/design):與程式碼設計有關的問題。 * [鎖(lock-in)](https://rules.sonarsource.com/java/tag/lock-in):使用於特定環境的功能。 * [misra](https://rules.sonarsource.com/java/tag/misra):與 [MISRA](http://www.misra.org.uk/) 標準中之規則相關。儘管 MISRA 規則主要是與 C 和 C++ 相關,但其中許多的規則並不只適用於特定語言(例如:不以浮點數作為迴圈計數器(loop counter)使用,而是良好的程式撰寫習慣。這就是為什麼您會在非 C 或 C++ 的規則上看到這些標籤的原因。 * [開放式Web應用程式安全項目(owasp)](https://rules.sonarsource.com/java/tag/owasp):與 [OWASP Top Ten](https://www.owasp.org/index.php/Category:OWASP_Top_Ten_Project) 中的安全標準規則有關。注意,OWASP Top Ten 是一系列高階漏洞的列表,它演變成許多潛在規則。 * [陷阱(pitfall)](https://rules.sonarsource.com/java/tag/pitfall):當下沒有錯誤,但是未來可能會出問題;先前設下的陷阱可能會使將來落入圈套,並弄亂程式碼。 * [sans-top25](https://rules.sonarsource.com/java/tag/sans-top25):與 [SANS 25 個最常見的軟體錯誤](http://www.sans.org/top25-software-errors/) 以及安全性相關。須注意的是,SANS TOP 25 的列表是直接取自 CWE。 * [可疑(suspicious)](https://rules.sonarsource.com/java/tag/suspicious):無法保證這是一個**程式錯誤**,但看起來卻十分地可疑。至少應該對程式碼進行檢查,且為了清楚起見可以嘗試對其進行重構。 * [不可預測(unpredictable)](https://rules.sonarsource.com/java/tag/unpredictable):程式碼在當前條件下可能會正常工作,但如果條件發生變化,則可能會失敗。 * [未使用(unused)](https://rules.sonarsource.com/java/tag/unused):未用碼(unused code),例如:一個從未使用過的私有變數。 * [使用者體驗(user-experience)](https://rules.sonarsource.com/java/tag/user-experience):在技術層面上,您的程式碼沒有錯誤,但這可能導致部份或全部的使用者對您感到厭惡。
C++
UTF-8
2,359
2.65625
3
[ "MIT" ]
permissive
#ifndef Intensity_Data_h #define Intensity_Data_h #include "Fem_Quadrature.h" #include "Angular_Quadrature.h" #include "Cell_Data.h" #include "Eigen/Dense" #include "Materials.h" #include "Input_Reader.h" #include "MMS_Intensity.h" class Intensity_Data { public: /// Will set n_grp, n_el, n_dir, n_leg, m_i will be zero Intensity_Data(const Cell_Data& cell_data, const Angular_Quadrature& ang_quad, const Fem_Quadrature& fem_quad); Intensity_Data(const Cell_Data& cell_data, const Angular_Quadrature& ang_quad, const Fem_Quadrature& fem_quad, Materials& materials, const Input_Reader& input_reader); virtual ~Intensity_Data(){} double get_intensity(const int el, const int cell, const int group, const int dir) const; /// Public accessor functions void get_cell_intensity(const int cell, const int group, const int dir, Eigen::VectorXd& loc_i_vec) const; /// Public functions to save values void set_cell_intensity(const int cell, const int group, const int dir, const Eigen::VectorXd& val); private: /// total number of cells in the problem const int m_cells; /// total number of groups in the problem const int m_groups; /// total number of directions in the problem const int m_dir; /// number of DFEM unknowns in each cell const int m_el_per_cell; /// quantities necessary for faster indexing of intensity const int m_dir_div_2; /// offset from negative mu to positive mu data ordering const int m_offset; const int m_el_times_dir_div_2; const int m_el_times_dir_div_2_times_grp; /// total length of the intensity data const int m_i_length; /// actual storage structure to store intensities std::vector<double> m_i; /* *************************************************** * * Protected Functions * *************************************************** */ void set_cell_intensity(const int cell, const int group, const int dir, const double val); bool intensity_range_check(const int el, const int cell, const int grp, const int dir) const; int intensity_data_locator(const int el, const int cell, const int group, const int dir) const; bool intensity_bounds_check(const int loc) const; }; #endif
Rust
UTF-8
436
2.84375
3
[ "MIT", "LicenseRef-scancode-other-permissive", "Apache-2.0", "BSD-3-Clause", "BSD-2-Clause", "NCSA" ]
permissive
#![feature(generators, generator_trait)] use std::ops::{Generator, GeneratorState}; use std::pin::Pin; fn dangle(x: &mut i32) -> &'static mut i32 { let mut g = || { yield; x }; loop { match Pin::new(&mut g).resume() { GeneratorState::Complete(c) => return c, //~^ ERROR explicit lifetime required GeneratorState::Yielded(_) => (), } } } fn main() {}
C
UTF-8
1,218
3.046875
3
[]
no_license
#include<stdio.h> #include<stdlib.h> #include<string.h> int stack[120]; int problem[120]; int hard[120]; int pos; int hardstack[120]; int hardpos; int N,P; int fun(){ int i,j; int min; int max; int t; scanf("%d %d ", &N, &P); memset(problem,0,sizeof(problem)); memset(hard,0,sizeof(hard)); pos = 0; hardpos = 0; for(i=0;i<N;i++){ min = 1001; max = -1; for(j=0;j<P;j++){ scanf("%d ", &t); if(t < min){ pos = 0; stack[pos++] = j; min = t; } else if(t == min){ stack[pos++] = j; } if(t > max){ hardpos = 0; hardstack[hardpos++] = j; max = t; } else if(t == max){ hardstack[hardpos++] = j; } } for(j=0;j<pos;j++){ problem[stack[j]] ++; } for(j=0;j<hardpos;j++){ hard[hardstack[j]] ++; } } t = N/2; j = 0; for(i=0;i<P;i++){ if(!hard[i] && problem[i] > t){ if(j) printf(" "); printf("%d", i+1); j ++; } } if(j==0) printf("0"); printf("\n"); } int main(){ int tstcase; scanf("%d ", &tstcase); while(tstcase --){ fun(); if(tstcase) printf("\n"); } return 0; }
C
UTF-8
3,295
3.734375
4
[]
no_license
//usage ./03_2.c < 03.txt // #include <stdio.h> #include <stdlib.h> #include <string.h> void substring(char s[], char sub[], int p, int l); int main(void) { int fabric[1200][1200]; //note this is about the largest a static array can be, bigger causes seg faults int claim[1349][4]; //store input for part 2 int x = 0; //curser x int y = 0; //curser y int w = 0; // cut width (in x) int h = 0; //cut height (in y) int d = 0; // #squares duplicated //string processing int at; int comma; int colon; int mult; for(int k = 0; k< 1349; k++) { char s[BUFSIZ]; if (fgets(s, 25, stdin) != NULL) //loop through lines { for(int i2=0; i2 < 25; i2++) //process string to get measurements { switch(s[i2]) { case '@': at = i2; break; case ',': comma = i2; break; case ':': colon = i2; break; case 'x': mult = i2; break; } } char ss[5]; substring(s,ss,at + 2, comma - at - 2); x = atoi(ss); claim[k][0] = x; substring(s,ss,comma + 1, colon - comma - 1); y = atoi(ss); claim[k][1] = y; substring(s,ss,colon + 2, mult - colon - 2); w = atoi(ss); claim[k][2] = w; substring(s,ss,mult + 1, strlen(s) - mult - 1); h = atoi(ss); claim[k][3] = h; // printf("%i %i %i %i\n",x,y,w,h); //debugging // draw on fabric for(int i = 0; i < w; i++) { for(int j = 0; j < h; j++) { fabric[x+i][y+j]++; if(fabric[x+i][y+j] == 2) //count the first time a square is duplicated { d++; } } } } else { break; } } printf("Part one: %i\n",d); //part two, run through again, but look at marked up pattern and report claim that has all ones on the fabric for(int k = 0; k< 1349; k++) { // look at claim area of fabric d=1; for(int i = 0; i < claim[k][2]; i++) { for(int j = 0; j < claim[k][3]; j++) { if(fabric[claim[k][0]+i][claim[k][1]+j] != 1) //check for unused or duplicate squares { d=0; } } } if(d==1) //no unused or duplicate squares encountered: this is the winning claim { printf("Part two: %i\n", k+1); return 0; } } } // C substring function definition // start counting at 0 void substring(char s[], char sub[], int p, int l) { int sl = strlen(s); if (p > sl - 1) { exit(1); } else if (l > sl - p) { l = sl - p; } int c = 0; while (c < l) { sub[c] = s[p+c]; c++; } sub[c] = '\0'; }
Python
UTF-8
1,910
4.0625
4
[]
no_license
####DATE: 04/12/2016 #######DEFINITION DES FONFCTIONS################################################# def motSaisi(): motSaisi=input("Entrez un mot qui est composé que les lettres d'alphabet:") while (not(motSaisi.isalpha())): print('False') motSaisi=input("Entrez un mot qui est composé que les lettres d'alphabet:") return motSaisi def verifierMot(motInconnu): '''la Fonction verifierMot(motInconnu, motSaisi) qui compare le mot caché motInconnu et le mot saisi par le joueur motSaisi et affiche les symboles « T , V, - » si les mots sont différents. Cette fonction retourne True si les mots sont identiques et False sinon.''' mot=motSaisi() sortie="" if len(motInconnu)==len(mot): if motInconnu==mot: return True else: for k in range(len(mot)): if motInconnu[k]==mot[k]: sortie=sortie+"T" elif mot[k] in motInconnu: sortie+="V" else: sortie+="-" print(mot) print(sortie) return False else: print("Désolé,le mot n'a pas la même longueur.") return False def unePartieDeMotus(motInconnu,n): '''afin de garantir au joueur n essais pour deviner le mot''' for w in range(n): print("Essai N°",w+1,"il reste",n-w,"essais") chaine="Entrez un mot de "+str(len(motInconnu))+" caractères:" if verifierMot(motInconnu): print("Vous avez gagné!!!") break elif w==n-1: print("Perdu,le mot Inconnu est:",motInconnu) #######PROGRAMME PRINCIPAL########################################" print("Nous avons besoin d'un mot à deviner.") motInconnu=motSaisi() n=int(input("Entrez un nombre d'essai souhaité:")) unePartieDeMotus(motInconnu,n)
C
UTF-8
213
3.578125
4
[]
no_license
#include <stdio.h> int main () { int x; printf ("Digite um valor\n"); scanf ("%d", &x); if (!x) printf ("%d\n", 1); else { for (int i = x-1; i != 0; i--) { x *= i; } printf ("%d\n", x); } }
C++
UTF-8
1,979
3.109375
3
[]
no_license
#ifndef CYCLE_FINDER_H #define CYCLE_FINDER_H //#define TEST_CYCLE_FINDER_H //Author : Suvojit Manna //Application : CurveSim //Header for Cycle Finder API //Finds and enumerates over all simple and Greedy cycle //Use DFS to start looking for cycle from each vertex //If cycle is found insert in a List. //For each vertex choose the edge with lowest latency //to find the Greedy Cycle #include <algorithm> #include <vector> #include <queue> #include "Edge.h" #include "Graph.h" #include "SimpleCycle.h" class CycleFinder { private: std::vector<SimpleCycle> simple; //store simple cycles std::vector<SimpleCycle> greedy; //store greedy cycles std::deque<bool> onStack; //maintain stack list std::deque<bool> ignore; //maintain ignore list std::vector<size_t> stack; //stack of vertex path //Use Depth First Search to enumerate over all cycle //from a given vertex v //Complexity : O(|V|*|C|*(|E| + 1)) //@param G Graph State Diagram as a Graph //@param v pair Starting vertex map of v //@return None void dfs(const Graph& G, std::pair<std::bitset<STATES>, size_t> vMap, std::vector<SimpleCycle>& fromV, SimpleCycle& c); public: //Finds cycle in Weighted Directed Graph CycleFinder(const Graph& G); //Return Simple Cycle Count //@param None //@return size_t No of Simple Cycles size_t simple_cycle_count(void) const; //Return Greedy Cycle Count //@param None //@return size_t No of Greedy Cycle size_t greedy_cycle_count(void) const; //Return list of Simple Cycles //@param None //@return vector<SimpleCycle> All Simple Cycles const std::vector<SimpleCycle>& simple_cycles(void) const; //Return list of Greedy Cycles //@param None //@return vector<SimpleCycle> All Greedy Cycles const std::vector<SimpleCycle>& greedy_cycles(void) const; //Return Greedy Cycle with minimum Latency //@param None //Return SimpleCycle the Greedy cycle leading to MAL SimpleCycle& min_greedy(void); }; #endif
C#
UTF-8
2,687
3.8125
4
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DominoClasses { /* Lab 4 - Complete the Set and Hand (of dominos) classes as discussed in class. * Write a console application to test the classes. *** / means done • dominos (list of Dominos) / • DominosRemaining (property get) / • IsEmpty (property get) / • Set (default constructor - creates a set of double 12 dominos) / • Set (int numPips - creates a set of dominos with double blanks to double the number of pips in the parameter) / • Shuffle (no parameters and no return value) / • Deal (no parameters and returns a Domino) / • ToString (the usual) / */ public class Set { private List<Domino> mySet = new List<Domino>(); #region Properties public int DominosRemaining { get { return mySet.Count; } } public bool IsEmpty { get { if (mySet.Count == 0) return true; else return false; } } #endregion #region Default constructor public Set() { for (int pip1 = 0; pip1 <= 12; pip1++) { for (int pip2 = 0; pip2 <= 12; pip2++) { mySet.Add(new Domino(pip1, pip2)); } } } public Set(int numDomino) { for (int pip1 = 0; pip1 <= numDomino; pip1++) { for (int pip2 = 0; pip2 <= numDomino; pip2++) { mySet.Add(new Domino(pip1, pip2)); } } } #endregion #region Methods public void Shuffle() { Random random = new Random(); for (int i = 0; i < mySet.Count; i++) { int rnd = random.Next(0, mySet.Count); Domino temp = mySet[i]; mySet[i] = mySet[rnd]; mySet[rnd] = temp; } } public Domino Deal() { Domino tempCard = mySet[0]; mySet.RemoveAt(0); return tempCard; } public override string ToString() { string str = ""; foreach (Domino d in mySet) { str += (d.ToString() + "\n"); } return str; } #endregion } }
TypeScript
UTF-8
356
3.015625
3
[]
no_license
/** * 人物信息管理类 */ class PlayerInfoManager extends BaseClass { private _info: PlayerInfo; public constructor() { super(); } public setup(): void { let self = this; self._info = new PlayerInfo(); } set Info(value: PlayerInfo) { this._info = value; } /** 人物信息 */ get Info(): PlayerInfo { return this._info; } }
Java
UTF-8
14,703
2.296875
2
[]
no_license
package com.example.eriks.appfinal; import android.app.Activity; import android.content.ContentValues; import android.content.Intent; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.Spinner; import android.widget.Toast; public class otros extends Activity implements View.OnClickListener{ Bundle bundle; String img, img2, img3; CheckBox c1,c2,c3; boolean ch1 = false, ch2 = false, ch3 = false; String [] eleccion1 = {""}; String s1 ="",s2="",s3=""; String precio = "",precio2 = "",precio3 = ""; int und1 = 0, und2 = 0, und3 = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_otros); bundle = getIntent().getExtras(); if (bundle == null){ bundle = new Bundle(); } Button volver = (Button)findViewById(R.id.volver); Button facturar = (Button)findViewById(R.id.cesta); ImageButton borrar = (ImageButton) findViewById(R.id.borrar); borrar.setOnClickListener(this); volver.setOnClickListener(this); facturar.setOnClickListener(this); borrar.setImageResource(R.drawable.x); //BD BD acceso = new BD(this); SQLiteDatabase BD = acceso.getWritableDatabase(); ContentValues DatosInsertar = new ContentValues(); //Insertamos1 DatosInsertar.put("COD", 3); DatosInsertar.put("NOMBRE","BALÓN"); DatosInsertar.put("PRECIO",25); DatosInsertar.put("IMG","R.drawable.balon"); long err = BD.insert("PRODUCTOS", null, DatosInsertar); if (err==-1){ // Toast.makeText(this, "Ya estaba creada la fila", Toast.LENGTH_LONG).show(); } //Insertamos2 DatosInsertar.put("COD",6); DatosInsertar.put("NOMBRE","GORRA"); DatosInsertar.put("PRECIO",20); DatosInsertar.put("IMG","R.drawable.gorra"); err = BD.insert("PRODUCTOS", null, DatosInsertar); if (err==-1){ // Toast.makeText(this, "Ya estaba creada la fila", Toast.LENGTH_LONG).show(); } //Insertamos3 DatosInsertar.put("COD",9); DatosInsertar.put("NOMBRE","CHANCLAS"); DatosInsertar.put("PRECIO",20); DatosInsertar.put("IMG","R.drawable.chanclas"); err = BD.insert("PRODUCTOS", null, DatosInsertar); if (err==-1){ // Toast.makeText(this, "Ya estaba creada la fila", Toast.LENGTH_LONG).show(); } //SELECCIONO LAS RUTAS DE LAS IMAGENES String campos [] = new String [] {"IMG"}; Cursor cr5 = BD.query("PRODUCTOS", campos, "(COD == 3)", null, null, null, null); cr5.moveToFirst(); img = cr5.getString(cr5.getColumnIndex("IMG")).substring(11,cr5.getString(cr5.getColumnIndex("IMG")).length()); Cursor cr6 = BD.query("PRODUCTOS", campos, "(COD == 6)", null, null, null, null); cr6.moveToFirst(); img2 = cr6.getString(cr6.getColumnIndex("IMG")).substring(11,cr6.getString(cr6.getColumnIndex("IMG")).length()); Cursor cr = BD.query("PRODUCTOS", campos, "(COD == 9)", null, null, null, null); cr.moveToFirst(); img3 = cr.getString(cr.getColumnIndex("IMG")).substring(11,cr.getString(cr.getColumnIndex("IMG")).length()); //SELECCIONO DE LA BD, LOS NOMBRES Y PRECIOS DE LOS PRODUCTOS String nombres [] = new String [] {"NOMBRE"}; String precios [] = new String [] {"PRECIO"}; //IMG1 Cursor c = BD.query("PRODUCTOS", nombres, "(COD == 3)", null, null, null, null); c.moveToFirst(); String name = c.getString(c.getColumnIndex("NOMBRE")); c = BD.query("PRODUCTOS", precios, "(COD == 3)", null, null, null, null); c.moveToFirst(); precio = c.getString(c.getColumnIndex("PRECIO")); //IMG2 c = BD.query("PRODUCTOS", nombres, "(COD == 6)", null, null, null, null); c.moveToFirst(); String name2 = c.getString(c.getColumnIndex("NOMBRE")); c = BD.query("PRODUCTOS", precios, "(COD == 6)", null, null, null, null); c.moveToFirst(); precio2 = c.getString(c.getColumnIndex("PRECIO")); //IMG3 c = BD.query("PRODUCTOS", nombres, "(COD == 9)", null, null, null, null); c.moveToFirst(); String name3 = c.getString(c.getColumnIndex("NOMBRE")); c = BD.query("PRODUCTOS", precios, "(COD == 9)", null, null, null, null); c.moveToFirst(); precio3 = c.getString(c.getColumnIndex("PRECIO")); //--------------CHECKBOX-------------- c1 = (CheckBox)findViewById(R.id.c1); c2 = (CheckBox)findViewById(R.id.c2); c3 = (CheckBox)findViewById(R.id.c3); ImageView i = (ImageView) findViewById(R.id.img1); ImageView i2 = (ImageView) findViewById(R.id.img2); ImageView i3 = (ImageView) findViewById(R.id.img3); i.setOnClickListener(this); i2.setOnClickListener(this); i3.setOnClickListener(this); c1.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked){ if(c1.isChecked()){ //Toast.makeText(getApplicationContext(), "Has pulsado 1", Toast.LENGTH_LONG).show(); ch1 = true; c2.setChecked(false); c3.setChecked(false); }else{ // Toast.makeText(getApplicationContext(), "Has Despulsado 1", Toast.LENGTH_LONG).show(); ch1 = false; } } }); c2.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked){ if(c2.isChecked()){ // Toast.makeText(getApplicationContext(), "Has pulsado 2", Toast.LENGTH_LONG).show(); ch2 = true; c1.setChecked(false); c3.setChecked(false); }else{ // Toast.makeText(getApplicationContext(), "Has Despulsado 2", Toast.LENGTH_LONG).show(); ch2 = false; } } }); c3.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked){ if(c3.isChecked()){ //Toast.makeText(getApplicationContext(), "Has pulsado 3", Toast.LENGTH_LONG).show(); ch3 = true; c1.setChecked(false); c2.setChecked(false); }else{ //Toast.makeText(getApplicationContext(), "Has Despulsado 3", Toast.LENGTH_LONG).show(); ch3 = false; } } }); c1.setText(name + " " + precio + "€"); c2.setText(name2 + " " + precio2 + "€"); c3.setText(name3 + " " + precio3 + "€"); //COLOCO LAS IMAGENES int ide=getResources().getIdentifier(img,"drawable",getPackageName()); i.setImageResource(ide); ide=getResources().getIdentifier(img2,"drawable",getPackageName()); i2.setImageResource(ide); ide=getResources().getIdentifier(img3,"drawable",getPackageName()); i3.setImageResource(ide); //TALLAS DE LOS PRODUCTOS final String [] tallas = {"45","44","43","42","41","40"}; final String [] cantidad = {"1", "2", "3", "4", "5"}; Spinner spin = (Spinner) findViewById(R.id.spin); Spinner cant1 = (Spinner) findViewById(R.id.cant1); Spinner cant2 = (Spinner) findViewById(R.id.cant2); Spinner cant3 = (Spinner) findViewById(R.id.cant3); ArrayAdapter<String> adaptador = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, tallas); spin.setAdapter(adaptador); ArrayAdapter<String> adaptador2 = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, cantidad); cant1.setAdapter(adaptador2); cant2.setAdapter(adaptador2); cant3.setAdapter(adaptador2); //SPIN 1 spin.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){ @Override public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long id) { if (position == 0) { eleccion1[0] = tallas[0]; } if (position == 1){ eleccion1[0] = tallas[1]; } if (position == 2){ eleccion1[0] = tallas[2]; } if (position == 3){ eleccion1[0] = tallas[3]; } if (position == 4){ eleccion1[0] = tallas[4]; } if (position == 5){ eleccion1[0] = tallas[5]; } // Toast.makeText(getApplicationContext(), "Ha pulsado el item " + position, Toast.LENGTH_SHORT).show(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); cant1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){ @Override public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long id) { if (position == 0) { und1 = 1; } if (position == 1){ und1 = 2; } if (position == 2){ und1 = 3; } if (position == 3){ und1 = 4; } if (position == 4){ und1 = 5; } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); cant2.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){ @Override public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long id) { if (position == 0) { und2 = 1; } if (position == 1){ und2 = 2; } if (position == 2){ und2 = 3; } if (position == 3){ und2 = 4; } if (position == 4){ und2 = 5; } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); cant3.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){ @Override public void onItemSelected(AdapterView<?> arg0, View arg1, int position, long id) { if (position == 0) { und3 = 1; } if (position == 1){ und3 = 2; } if (position == 2){ und3 = 3; } if (position == 3){ und3 = 4; } if (position == 4){ und3 = 5; } } @Override public void onNothingSelected(AdapterView<?> parent) { } }); //BOTONES DE AÑADIR PRODUCTO Button b = (Button)findViewById(R.id.b1); Button b2 = (Button)findViewById(R.id.b2); Button b3 = (Button)findViewById(R.id.b3); b.setOnClickListener(this); b2.setOnClickListener(this); b3.setOnClickListener(this); } @Override public void onClick(View v) { Intent paso = new Intent (this, productos.class); Intent paso2 = new Intent (this, comprar.class); switch (v.getId()){ case R.id.volver: paso.putExtras(bundle); startActivity(paso); finish(); break; case R.id.cesta: paso2.putExtras(bundle); startActivity(paso2); finish(); break; case R.id.b2: if(ch1 == true) { s1 = String.valueOf(und1) + " " + (String) c1.getText(); Toast.makeText(getApplicationContext(), "Has añadido a la cesta: " + s1, Toast.LENGTH_LONG).show(); bundle.putString("otros1",s1); bundle.putInt("po1",Integer.parseInt(precio)*und1); } break; case R.id.b1: if(ch2 == true) { s2 = String.valueOf(und2) + " " + (String) c2.getText(); Toast.makeText(getApplicationContext(), "Has añadido a la cesta: " + s2, Toast.LENGTH_LONG).show(); bundle.putString("otros2",s2); bundle.putInt("po2",Integer.parseInt(precio2)*und2); } break; case R.id.b3: if(ch3 == true) { s3 = String.valueOf(und3) + " " + c3.getText() + " Talla:" + eleccion1[0]; Toast.makeText(getApplicationContext(), "Has añadido a la cesta: " + s3, Toast.LENGTH_LONG).show(); bundle.putString("otros3",s3); bundle.putInt("po3",Integer.parseInt(precio3)*und3); } break; case R.id.borrar: bundle.putString("otros1",null); bundle.putString("otros2",null); bundle.putString("otros3",null); bundle.putInt("po1", 0); bundle.putInt("po2", 0); bundle.putInt("po3", 0); Toast.makeText(getApplicationContext(),"Has deseleccionado los complementos", Toast.LENGTH_LONG).show(); break; } } public void onBackPressed() { } }
Python
UTF-8
1,330
4.03125
4
[]
no_license
##https://courses.edx.org/courses/course-v1:MITx+6.00.1x_8+1T2016/courseware/Week_2/Basic_Problem_Set_1/ ## ##Counting and Grouping ## ##A catering company has hired you to help with organizing and preparing customer's orders. You are given a list of each customer's ##desired items, and must write a program that will count the number of each items needed for the chefs to prepare. The items that a ##customer can order are: salad, hamburger, and water. ## ##Write a function called item_order that takes as input a string named order. The string contains only words for the items the customer ##can order separated by one space. The function returns a string that counts the number of each item and consolidates them in the ##following order: salad:[# salad] hamburger:[# hambruger] water:[# water] ## ##If an order does not contain an item, then the count for that item is 0. Notice that each item is formatted as ##[name of the item][a colon symbol][count of the item] and all item groups are separated by a space. def item_order(order): s_order=order.split(" ") c_s=0 c_h=0 c_w=0 for i in s_order: if i=="salad": c_s+=1 if i=="hamburger": c_h+=1 if i=="water": c_w+=1 return "salad:"+str(c_s)+" hamburger:"+str(c_h)+" water:"+str(c_w)
Java
UTF-8
229
1.632813
2
[]
no_license
package com.rds.judicial.model; import lombok.Data; /** * 异常描述 * @author 少明 * */ @Data public class RdsJudicialExceptionTypeModel { private String type_id; private String type_desc; private int is_delete; }
PHP
UTF-8
7,023
3.046875
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
<?php namespace PHPFUI\MySQLSlowQuery; class Parser { private const PORT = 'TCP Port: '; private const TIME = '# Time: '; /** @var array<int, \PHPFUI\MySQLSlowQuery\Entry> */ private array $entries = []; /** @var array<int, string> */ private array $extraLines = []; // @phpstan-ignore-next-line private $handle; /** @var array<int, \PHPFUI\MySQLSlowQuery\Session> */ private array $sessions = []; private string $sortColumn = 'Query_time'; private string $sortOrder = 'desc'; /** * Parse a MySQL Slow Query Log file */ public function __construct(private string $fileName) { } /** * Return \PHPFUI\MySQLSlowQuery\Entry entries from file * * @param int $session return entries from the specified session * * @throws Exception\EmptyLog * @throws Exception\LogLine * @return array<int, \PHPFUI\MySQLSlowQuery\Entry> * */ public function getEntries(int $session = -1) : array { if (! $this->entries) { $this->parse(); } if ($session > -1) { $entries = []; foreach ($this->entries as $entry) { if ($entry->Session == $session) { $entries[] = $entry; } } return $entries; } return $this->entries; } /** * @throws Exception\EmptyLog * @throws Exception\LogLine * @return array<int, \PHPFUI\MySQLSlowQuery\Session> sessions from file * */ public function getSessions() : array { if (! $this->sessions) { $this->parse(); } return $this->sessions; } /** * Sort \PHPFUI\MySQLSlowQuery\Entry entries. Defaults to Query_time, desc * * @throws Exception\EmptyLog * @throws Exception\LogLine */ public function sortEntries(string $sortColumn = 'Query_time', string $sortOrder = 'desc') : self { $this->sortColumn = $sortColumn; $this->sortOrder = $sortOrder; if (! $this->entries) { $this->parse(); } \usort($this->entries, [$this, 'entrySort']); return $this; } protected function entrySort(\PHPFUI\MySQLSlowQuery\Entry $lhs, \PHPFUI\MySQLSlowQuery\Entry $rhs) : int { $column = $this->sortColumn; if ('desc' == $this->sortOrder) { return $rhs->{$column} <=> $lhs->{$column}; } return $lhs->{$column} <=> $rhs->{$column}; } private function getNextLine() : string { if ($this->extraLines) { return \array_shift($this->extraLines); } $line = \fgets($this->handle); return $line; } /** * Derive a string value that determines how the log is parsed. */ private function getParseMode(string $sessionHeaderFirstLine) : string { return \stripos($sessionHeaderFirstLine, 'MariaDB') ? 'mariadb' : ''; } private function parse() : void { $this->handle = @\fopen($this->fileName, 'r'); if (! $this->handle) { throw new Exception\EmptyLog(self::class . ': ' . $this->fileName . ' appears to not exist or is empty'); } $newSessionHeader = []; $parseMode = ''; $previousTimeLine = ''; $processingSessionHeader = true; // Get line from stack (if pushed in below loop) or file. Any comment line // not starting with "# Time: " gets discarded. while (\strlen($line = $this->getNextLine())) { if (0 === \stripos($line, self::PORT)) { $newSessionHeader[] = $line; $parseMode = $this->getParseMode($newSessionHeader[0]); // eat the next line $this->getNextLine(); // create a new session $this->sessions[] = new \PHPFUI\MySQLSlowQuery\Session($newSessionHeader, $parseMode); $newSessionHeader = []; $processingSessionHeader = false; // The next line is expected to be a comment connected to the first // query in this session. In non backward compatible mode, check this: // if it's not a comment line, this is assumed to be the start of the // next session header (i.e. there are zero queries in this session). if ('mariadb' === $parseMode && \strlen($line = $this->getNextLine()) > 0) { if ('#' !== $line[0]) { $processingSessionHeader = true; } $this->pushLine($line); } } elseif ($processingSessionHeader) // not in session yet { // store lines until "TCP Port: " is found in a next line $newSessionHeader[] = $line; } elseif ('#' === $line[0]) // start of log entry { $entry = new \PHPFUI\MySQLSlowQuery\Entry(['parse_mode' => $parseMode]); $query = []; if ('' === $parseMode) { // Backward compatible parsing: // - Ignore comment lines up until "# Time:" // - Iarse exactly three lines. If any of these are non-comments, // throw an exception. // - If there are more than three comment lines, the query below // them is ignored. if (! \str_starts_with($line, self::TIME)) { continue; } $entry->setFromLine($line); $entry->setFromLine(\fgets($this->handle)); $entry->setFromLine(\fgets($this->handle)); } else { $timeLineFound = false; // Parse any following comment lines, and interpret the next // non-comment line as a query line. do { $entry->setFromLine($line); if ('mariadb' == $parseMode && \str_starts_with($line, self::TIME)) { $timeLineFound = true; $previousTimeLine = $line; } } while (\strlen($line = $this->getNextLine()) > 0 && '#' === $line[0]); // @phpstan-ignore-line if ('mariadb' == $parseMode && ! $timeLineFound && $previousTimeLine) // @phpstan-ignore-line { // Always add the Time property. Assume that if it is not in the // log, it's the same as the previous logged query, and that the // line contains no other properties we don't want to add. $entry->setFromLine($previousTimeLine); } $query[] = \trim($line); } // gather (more) query lines until a non-query line is reached while (\strlen($line = $this->getNextLine()) > 0 && '#' !== $line[0]) // @phpstan-ignore-line { if (0 === \stripos($line, self::PORT)) // found a new session header { $this->pushLine($line); // Push this and previous line back on to stack. (Implicitly assume // "TCP Port: " is on the second line of the new session header.) if (\count($query)) { $this->pushLine(\array_pop($query)); } $line = ''; $newSessionHeader = []; $processingSessionHeader = true; break; } $query[] = \trim($line); } // push unprocessed comment line (for next query) back on to stack if (\strlen($line) && '#' === $line[0]) { $this->pushLine($line); } $entry->Query = $query; $entry->Session = \count($this->sessions) - 1; $this->entries[] = $entry; } } \fclose($this->handle); } /** * Push line back on to stack for further processing. * * Lines will later be processed by getNextLine() in the reverse order as * they are pushed. */ private function pushLine(string $line) : self { \array_unshift($this->extraLines, $line); return $this; } }
C++
UTF-8
2,119
3.375
3
[]
no_license
#include <iostream> #include <vector> #include <set> #include <algorithm> long long int MODULO = 1000000007; class BitMatrix { public: BitMatrix() : main_numbers() , zero_options(1) {} void ReduceNumber(long long int& number) const { while (number > 0) { if (main_numbers.size() == 0) { break; } auto lower_it = main_numbers.lower_bound(number); bool decreased = false; if (lower_it != main_numbers.begin()) { --lower_it; if ((number ^ (*lower_it)) < number) { number = number ^ (*lower_it); decreased = true; } ++lower_it; } if (lower_it != main_numbers.end() && (number ^ (*lower_it)) < number) { number = number ^ (*lower_it); decreased = true; } if (!decreased) { break; } } } void AddNumber(long long int number) { ReduceNumber(number); if (number == 0) { zero_options *= 2; zero_options %= MODULO; } else { main_numbers.insert(number); } } long long int GetOptionsCount(long long int number) const { ReduceNumber(number); if (number == 0) { return zero_options; } else { return 0; } } private: std::set<long long int> main_numbers; long long int zero_options; }; int main() { std::ios::sync_with_stdio(false); int n,q; std::cin >> n >> q; std::vector<long long int> a(n); for (int i = 0; i < n; ++i) { std::cin >> a[i]; } std::vector<BitMatrix> prefix_matrices(n + 1); for (int i = 0; i < n; ++i) { prefix_matrices[i + 1] = prefix_matrices[i]; prefix_matrices[i + 1].AddNumber(a[i]); } for (int j = 0; j < q; ++j) { int l, x; std::cin >> l >> x; std::cout << prefix_matrices[l].GetOptionsCount(x) << std::endl; } return 0; }
Java
UTF-8
9,678
2.171875
2
[ "Apache-2.0" ]
permissive
package com.example.dlpbgj; import android.annotation.SuppressLint; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.NonNull; import androidx.annotation.Nullable; import androidx.appcompat.app.AppCompatActivity; import com.google.android.gms.tasks.OnFailureListener; import com.google.android.gms.tasks.OnSuccessListener; import com.google.firebase.firestore.CollectionReference; import com.google.firebase.firestore.EventListener; import com.google.firebase.firestore.FirebaseFirestore; import com.google.firebase.firestore.FirebaseFirestoreException; import com.google.firebase.firestore.QueryDocumentSnapshot; import com.google.firebase.firestore.QuerySnapshot; import java.util.ArrayList; import java.util.HashMap; public class AcceptBook extends AppCompatActivity { String bookISBN; User currentUser; TextView ISBN; Spinner spinner; ArrayList<String> borrowers; ArrayList<String> bookNames; ArrayList<HashMap<String,String>> maps; String borrower; String book; HashMap<String,String> finalMap; Button scan; Button returnBook; @SuppressLint("SetTextI18n") @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_return_book); scan = findViewById(R.id.scanisbn); returnBook = findViewById(R.id.returnBook); ISBN = findViewById(R.id.ISBN_book); spinner = findViewById(R.id.returnList); borrowers = new ArrayList<>(); bookNames = new ArrayList<>(); maps = new ArrayList<>(); returnBook.setText("Confirm Return"); TextView acceptreturn = findViewById(R.id.acceptreturn); acceptreturn.setText("Book will be returned from :"); scan.setOnClickListener(new View.OnClickListener() { @Override /** * @param view (View) * This method takes in the given view, it initialize the new activity * To scan the barcode for the isbn purposes. * @return null * This method initialize another activity and it doesn't return anything. */ public void onClick(View view) { Intent intent = new Intent(getApplicationContext(), barcode_scanner.class); startActivityForResult(intent, 1); } }); returnBook.setOnClickListener(new View.OnClickListener() { @Override /** The given method is initialized when the button "return book" * is clicked * @param view (View) View according to the context of the environment * @return null The method returns nothing but does display important * messages for the user. While simultaneously making changes in the firebasedatabase * The function primarily serves the important function to display the message to the user and * scan the ISBN of the book entered and search through out the entire database. */ public void onClick(View view) { if (borrowers.size() == 0) { if (bookISBN == null) { Toast toast = Toast.makeText(getApplicationContext(), "Please scan an ISBN code to confirm book returned!", Toast.LENGTH_SHORT); toast.show(); } else { borrower = null; book = null; bookISBN = null; ISBN.setText("ISBN-"); Toast toast = Toast.makeText(getApplicationContext(), "Scanned ISBN code does not match any book that is currently borrowed or returned by the borrower!\nPlease scan again.", Toast.LENGTH_SHORT); toast.show(); } } else if (borrower == null) { Toast toast = Toast.makeText(getApplicationContext(), "Please select a user to get the book from!", Toast.LENGTH_SHORT); toast.show(); } else { FirebaseFirestore db = FirebaseFirestore.getInstance(); CollectionReference collectionReference = db.collection("Users/" + currentUser.getUsername() + "/MyBooks"); HashMap<String, Object> data = new HashMap<>(); finalMap.put(borrower,null); data.put("Borrower", null); data.put("Book Status", "Available"); data.put("Requests",finalMap); collectionReference .document(book) .update(data) .addOnSuccessListener(new OnSuccessListener<Void>() { @Override public void onSuccess(Void aVoid) { Log.d("Get Book Back", "Book values successfully updated!"); } }) .addOnFailureListener(new OnFailureListener() { @Override public void onFailure(@NonNull Exception e) { Log.d("Get Book Back", "Book values failed to update!"); } }); Toast toast = Toast.makeText(getApplicationContext(), "Book successfully retrieved from" + borrower + " !", Toast.LENGTH_SHORT); toast.show(); finish(); startActivity(getIntent()); } } }); spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override /** @param adapterView (AdapterView) * @param view (View) * @param i (int) * @param l (long) */ public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { borrower = borrowers.get(i); book = bookNames.get(i); finalMap = maps.get(i); } @Override /** * @param adapterView (AdapterView) */ public void onNothingSelected(AdapterView<?> adapterView) { borrower = null; book = null; finalMap = null; } }); } @SuppressLint("SetTextI18n") @Override /** * @param requestCode * @param resultCode * @param data */ public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == 1) { if (resultCode == -1) { bookISBN = data.getStringExtra("ISBN"); ISBN.setText("ISBN - " + bookISBN); String temp = bookISBN; checkFunc(temp); } } } /** * * @param isbn */ public void checkFunc(final String isbn) { borrowers.clear(); bookNames.clear(); final FirebaseFirestore db = FirebaseFirestore.getInstance(); currentUser = (User) getIntent().getSerializableExtra("User"); final CollectionReference userCollection = db.collection("Users/" + currentUser.getUsername() + "/MyBooks"); userCollection.addSnapshotListener(new EventListener<QuerySnapshot>() { @Override /** * @param QuerySnapshot value * @param FirebaseFirestoreException error */ public void onEvent(@Nullable QuerySnapshot value, @Nullable FirebaseFirestoreException error) { for (QueryDocumentSnapshot newBook : value) { ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item, borrowers); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); if ((isbn.equals((String)newBook.getData().get("Book ISBN")))) { if (null != (String)newBook.getData().get("Borrower")) { String temp = (String) newBook.getData().get("Borrower"); HashMap<String,String> map = (HashMap<String, String>)newBook.getData().get("Requests"); if (("Borrowed").equals(map.get(temp))){ borrowers.add(temp); bookNames.add(newBook.getId()); maps.add(map); setSpinner(); } } } } } }); } /** * */ public void setSpinner() { ArrayAdapter<String> adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item, borrowers); adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinner.setAdapter(adapter); } }
C#
UTF-8
752
2.5625
3
[]
no_license
using System.Collections; using System.Collections.Generic; using System.Text.RegularExpressions; using UnityEngine; public class WallScript : MonoBehaviour, IColorable { private Renderer[] _mat; public Color wallCol = Color.gray; // Use this for initialization void Start () { _mat = GetComponentsInChildren<Renderer>(); GameManager.colChange += HelloWorld; } // Update is called once per frame void Update () { } public void HelloWorld() { Debug.Log("Hello from: " + this.name.ToString()); } public void ChangeColor(Color col) { //Debug.Log("Hello from: "+ this.name.ToString()); foreach (Renderer _matCol in _mat) { _matCol.material.color = col; } } }
Shell
UTF-8
1,931
2.984375
3
[]
no_license
# Drop the tables in case they exists echo "DROP TABLE price; DROP TABLE base; DROP TABLE split; DROP TABLE dividend;" | \ mclient -d fintime # Create tables, note columns here must be lower case echo 'CREATE TABLE "base" ( "id" char(30), "ex" char(3), "descr" varchar(256), "sic" char(30), "spr" char(4), "cu" char(5), "create_date" date );' | mclient -d fintime echo 'CREATE TABLE "split" ( "id" char(30), "split_date" date, "entry_date" date, "split_factor" double );' | mclient -d fintime echo 'CREATE TABLE "price" ( "id" char(30), "trade_date" date, "high_price" double, "low_price" double, "close_price" double, "open_price" double, "volume" bigint );' | mclient -d fintime echo 'CREATE TABLE "dividend" ( "id" char(30), "xdivdate" date, "divamt" double, "announcedate" date );' | mclient -d fintime DATAPATH=$(pwd)/../../data/ function nrows { wc -l $1 | awk '{print $1-1}' } # populate tables with pipe delimited data # skip header, so count rows first PRICEN=$(nrows ${DATAPATH}/hist-price-file) BASEN=$(nrows ${DATAPATH}/hist-base-file) SPLITN=$(nrows ${DATAPATH}/hist-split-file) DIVIDENDN=$(nrows ${DATAPATH}/hist-dividend-file) echo "COPY ${PRICEN} OFFSET 2 RECORDS INTO price FROM '${DATAPATH}/hist-price-file' USING DELIMITERS '|', '\n';" | mclient -d fintime echo "COPY ${BASEN} OFFSET 2 RECORDS INTO base FROM '${DATAPATH}/hist-base-file' USING DELIMITERS '|', '\n';" | mclient -d fintime echo "COPY ${SPLITN} OFFSET 2 RECORDS INTO split FROM '${DATAPATH}/hist-split-file' USING DELIMITERS '|', '\n';" | mclient -d fintime echo "COPY ${DIVIDENDN} OFFSET 2 RECORDS INTO dividend FROM '${DATAPATH}/hist-dividend-file' USING DELIMITERS '|', '\n';" | mclient -d fintime
C
UTF-8
754
3.828125
4
[]
no_license
#include "holberton.h" /** * read_textfile -reads a text file and prints it to the POSIX standard output. * @filename: file to be read. * @letters: number of letters to read and print * Return:numbers it could read and print */ ssize_t read_textfile(const char *filename, size_t letters) { int fd, fd_write, fd_read; char *buffer; if (filename == NULL) { return (0); } buffer = malloc(sizeof(char) * letters); if (buffer == NULL) { return (0); } fd = open(filename, O_RDONLY); if (fd == -1) { return (0); } fd_read = read(fd, buffer, letters); if (fd_read == -1) { return (0); } fd_write = write(STDOUT_FILENO, buffer, fd_read); if (fd_write == -1) { return (0); } free(buffer); close(fd); return (fd_write); }
Markdown
UTF-8
8,193
2.796875
3
[ "LicenseRef-scancode-unknown-license-reference", "CC-BY-4.0", "LicenseRef-scancode-public-domain", "MIT" ]
permissive
--- pcx_content_type: concept title: Smart Placement (beta) --- {{<beta>}}Smart Placement{{</beta>}} By default, [Workers](/workers/) and [Pages Functions](/pages/platform/functions/) are invoked in a data center closest to where the request was received. If you are running back-end logic in a Worker, it may be more performant to run that Worker closer to your back-end infrastructure rather than the end user. Smart Placement automatically places your workloads in an optimal location that minimizes latency and speeds up your applications. You may benefit from Smart Placement if you are making multiple round trips to a centralized database, API or origin server in a Worker. ## Background The following example demonstrates how moving your Worker close to your back-end services could decrease application latency: You have a user in Sydney, Australia who is accessing an application running on Workers. This application makes multiple round trips to a database located in Frankfurt, Germany in order to serve the user’s request. ![A user located in Sydney, AU connecting to a Worker in the same region which then makes multiple round trips to a database located in Frankfurt, DE. ](/images/workers/platform/workers-smart-placement-disabled.png) The issue is the time that it takes the Worker to perform multiple round trips to the database. Instead of the request being processed close to the user, the Cloudflare network, with Smart Placement enabled, would process the request in a data center closest to the database. ![A user located in Sydney, AU connecting to a Worker in Frankfurt, DE which then makes multiple round trips to a database also located in Frankfurt, DE. ](/images/workers/platform/workers-smart-placement-enabled.png) ## Understand how Smart Placement (beta) works Smart Placement is enabled on a per-Worker basis. Once enabled, fetch requests (also known as subrequests) from your Worker are analyzed regularly. The Smart Placement algorithm determines the optimal placement to minimize the round-trip time (RTT) between the Worker and the back-end service the Worker is communicating with. Smart Placement is only active for Workers that **make more than one roundtrip** to back-end infrastructure. If your Worker does less than one subrequest on average, Smart Placement will run the Worker at the data center closest to the user. Smart Placement is a best-effort attempt. Smart Placement will not take action unless it is more performant than the default (which is running the Worker at the data center closest to the user). ### Unsupported back-end services There are some back-end services that are not considered by the Smart Placement algorithm: - **Globally distributed services**: If the services that your Worker communicates with are geo-distributed in many regions (for example, CDNs, distributed databases, distributed APIs), Smart Placement is not a good fit. We automatically rule these out of the Smart Placement optimization. - Examples: Google APIs, services using Fastly or Akamai's CDN. - **Analytics or logging services**: Requests to analytics or logging services should not be in the critical path of your application. [`waitUntil()`](/workers/runtime-apis/fetch-event/?ref=blog.cloudflare.com#waituntil) should be used so that the response back to users is not blocked when instrumenting your code. Since `waitUntil()` does not impact the request duration from a user’s perspective, we automatically rule analytics and logging services out of the Smart Placement optimization. - Examples: New Relic, Datadog, Tinybird, Grafana, Amplitude, Honeycomb. ## Enable Smart Placement (beta) Smart Placement is available to users on all Workers plans. Smart Placement is intended for latency-sensitive Workers and as such, does not currently work with [Cron Triggers](/workers/configuration/cron-triggers/). ### Enable Smart Placement via Wrangler To enable Smart Placement via Wrangler: 1. Make sure that you have `wrangler@2.20.0` or later [installed](/workers/wrangler/install-and-update/). 2. Add the following to your Worker project's `wrangler.toml` file: ```toml [placement] mode = "smart" ``` 3. Send some initial traffic (approximately 20-30 requests) to your Worker. It takes a few minutes after you have sent traffic to your Worker for Smart Placement to take effect. 4. View your Worker's [request duration analytics](/workers/observability/metrics-and-analytics/). ### Enable Smart Placement via the dashboard To enable Smart Placement via the dashboard: 1. Log in to the [Cloudflare dashboard](https://dash.cloudflare.com) and select your account. 2. In **Account Home**, select **Workers & Pages**. 3. In **Overview**,select your Worker. 4. Select **Settings** > **General**. 5. Under **Placement**, choose **Smart**. 6. Send some initial traffic (approximately 20-30 requests) to your Worker. It takes a few minutes after you have sent traffic to your Worker for Smart Placement to take effect. 7. View your Worker's [request duration analytics](/workers/observability/metrics-and-analytics/) ## Observability ### Placement Status A Worker's metadata contains details about a Worker's placement status. Query your Worker's placement status through the following Workers API endpoint: ```bash $ curl -X GET https://api.cloudflare.com/client/v4/accounts/{ACCOUNT_ID}/workers/services/{WORKER_NAME} \ -H "Authorization: Bearer <TOKEN>" \ -H "Content-Type: application/json" | jq . ``` Possible placement states include: - _(not present)_: The Worker has not been analyzed for Smart Placement yet. - `INSUFFICIENT_INVOCATIONS`: Not enough requests for Smart Placement to make a placement decision. - `NO_VALID_HOSTS`: The Worker does not send subrequests to [back-end services supported by Smart Placement](/workers/configuration/smart-placement/#supported-back-end-services). - `INSUFFICIENT_SUBREQUESTS`: The Worker does not send enough subrequests to valid back-end services. - `SUCCESS`: The Worker has been successfully analyzed and will be optimized by Smart Placement. ### Request Duration Analytics Once Smart Placement is enabled, data about request duration gets collected. Request duration is measured at the data center closest to the end user. By default, one percent (1%) of requests are not routed with Smart Placement. These requests serve as a baseline to compare to. ### `cf-placement` header Once Smart Placement is enabled, Cloudflare adds a `cf-placement` header to all requests. This can be used to check whether a request has been routed with Smart Placement and where the Worker is processing the request (which is shown as the nearest airport code to the data center). For example, the `cf-placement: remote-LHR` header's `remote` value indicates that the request was routed using Smart Placement to a Cloudflare data center near London. The `cf-placement: local-EWR` header's `local` value indicates that the request was not routed using Smart Placement and the Worker was invoked in a data center closest to where the request was received, close to Newark Liberty International Airport (EWR). {{<Aside type="warning" header="Beta use only">}} We may remove the `cf-placement` header before Smart Placement enters general availability. {{</Aside>}} ## Best practices If you are building full-stack applications on Workers, we recommend splitting up the front-end and back-end logic into different Workers and using [Service Bindings](/workers/runtime-apis/service-bindings/) to connect your front-end logic and back-end logic Workers. ![Smart Placement and Service Bindings](/images/workers/platform/smart-placement-service-bindings.png) Enabling Smart Placement on your back-end Worker will invoke it close to your back-end service, while the front-end Worker serves requests close to the user. This architecture maintains fast, reactive front-ends while also improving latency when the back-end Worker is called. ## Give feedback on Smart Placement Smart Placement is in beta. To share your thoughts and experience with Smart Placement, join the [Cloudflare Developer Discord](https://discord.gg/cloudflaredev).
Python
UTF-8
1,130
3.875
4
[]
no_license
def longest_subsequence_problem(string_a, string_b): """ A DP implementation for finding longest common sub sequence :param string_a: String a :param string_b: String b :return: The longest common sub sequence """ # Get the length of the strings len_a = len(string_a) len_b = len(string_b) # Create a memo, and extra row for creating a row and column with indices zero. # Helps in reducing complexity of code memo = [[0] * (len_b + 1) for i in range(0, (len_b + 1))] # For skipping index 0, we add 1 to range for _index_b in range(len_b + 1): for _index_a in range(len_a + 1): if _index_b == 0 or _index_a == 0: memo[_index_b][_index_a] = 0 # As we have added 1 to index, we need subtract 1 to find the exact from the string elif string_b[_index_b - 1] == string_a[_index_a - 1]: memo[_index_b][_index_a] = 1 + memo[_index_b - 1][_index_a - 1] else: memo[_index_b][_index_a] = max(memo[_index_b - 1][_index_a], memo[_index_b][_index_a - 1]) for row in memo: print(*row) return memo[len_b][len_a] if __name__ == "__main__": print(longest_subsequence_problem("AGGTAB", "GXTXAYB"))
C#
UTF-8
17,522
2.90625
3
[]
no_license
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace form_idle { public partial class Form1 : Form { double num = 0, prev, result; bool func, neg = false; string state, tempstate, temptext, record; public Form1() { InitializeComponent(); textBox1.Text = Convert.ToString(num); textBox1.Focus(); textBox1.SelectAll(); } //calculation state assignments #region events private void calculate() { switch (state) { case "plus": result = prev + num; //add break; case "minus": result = prev - num; //minus break; case "time": result = prev * num; //multiply break; case "divide": result = prev / num; //divide break; case "power": result = Math.Pow(prev, num);//power break; case "root": result = Math.Pow(prev, (1 / num));//root break; } switch (tempstate) { case "exp": result = prev * Math.Pow(10, num); break; default: break; } record += num; if (state != null) historyBox.Items.Add(record + "=" + result.ToString()); num = result; update(); state = null; tempstate = null; label1.Text = null; } //calculate then put result in historybox and reset everything private void plus() { state = "plus"; prev = num; record = prev + "+"; num = 0; update(); recording(); } private void minus() { state = "minus"; prev = num; record = prev + "-"; num = 0; update(); recording(); } private void time() { state = "time"; prev = num; record = prev + "x"; num = 0; update(); recording(); } private void divide() { state = "divide"; prev = num; record = prev + "÷"; num = 0; update(); recording(); } private void power() { state = "power"; prev = num; record = prev + "^"; num = 0; update(); recording(); } private void root() { state = "root"; prev = num; record = prev + "√"; num = 0; update(); recording(); } private void recording() { label1.Text += record; } //record the current number and calculate state to label private void update() { if (tempstate == "exp") { textBox1.Text = temptext + num.ToString(); } else textBox1.Text = num.ToString(); } //update textbox to be the same as num #endregion //calculation events //calculation button press events #region calc state private void bplus_Click(object sender, EventArgs e)//+ { if (state == null) { plus(); } else if (state != "+") { calculate(); plus(); } textBox1.Focus(); textBox1.SelectAll(); } private void bminus_Click(object sender, EventArgs e)//- { if (state == null) { minus(); } else if (state != "-") { calculate(); minus(); } textBox1.Focus(); textBox1.SelectAll(); } private void btime_Click(object sender, EventArgs e)//* { if (state == null) { time(); } else if (state != "*") { calculate(); time(); } textBox1.Focus(); textBox1.SelectAll(); } private void bdiv_Click(object sender, EventArgs e)//÷ { if (state == null) { divide(); } else if (state != "/") { calculate(); divide(); } textBox1.Focus(); textBox1.SelectAll(); } #endregion //input events #region input private void bnum1_Click(object sender, EventArgs e)//1 { num = num * 10 + 1; update(); } private void bnum2_Click(object sender, EventArgs e)//2 { num = num * 10 + 2; update(); } private void bnum3_Click(object sender, EventArgs e)//3 { num = num * 10 + 3; update(); } private void bnum4_Click(object sender, EventArgs e)//4 { num = num * 10 + 4; update(); } private void bnum5_Click(object sender, EventArgs e)//5 { num = num * 10 + 5; update(); } private void bnum6_Click(object sender, EventArgs e)//6 { num = num * 10 + 6; update(); } private void bnum7_Click(object sender, EventArgs e)//7 { num = num * 10 + 7; update(); } private void bnum8_Click(object sender, EventArgs e)//8 { num = num * 10 + 8; update(); } private void bnum9_Click(object sender, EventArgs e)//9 { num = num * 10 + 9; update(); } private void bnum0_Click(object sender, EventArgs e)//0 { num = num * 10; update(); } private void bcalc_Click(object sender, EventArgs e)//= { calculate(); update(); } #endregion number //key presses detection #region keypress detect private void bc_Click(object sender, EventArgs e) { prev = 0; num = 0; state = null; label1.Text = null; textBox1.Text = Convert.ToString(num); } private void bback_Click(object sender, EventArgs e) { if (textBox1.Text.Length == 1) { num = 0; update(); } else { num = Convert.ToDouble(num.ToString().Substring(0, num.ToString().Length - 1)); } update(); } private void Form1_KeyDown(object sender, KeyEventArgs e) { switch (e.KeyCode) { case Keys.Add: bplus_Click(null, null); break; case Keys.Subtract: bminus_Click(null, null); break; case Keys.Multiply: btime_Click(null, null); break; case Keys.Divide: bdiv_Click(null, null); break; case Keys.Return: bcalc_Click(null, null); break; } switch (e.KeyCode) { case Keys.NumPad0: bnum0_Click(null, null); break; case Keys.NumPad1: bnum1_Click(null, null); break; case Keys.NumPad2: bnum2_Click(null, null); break; case Keys.NumPad3: bnum3_Click(null, null); break; case Keys.NumPad4: bnum4_Click(null, null); break; case Keys.NumPad5: bnum5_Click(null, null); break; case Keys.NumPad6: bnum6_Click(null, null); break; case Keys.NumPad7: bnum7_Click(null, null); break; case Keys.NumPad8: bnum8_Click(null, null); break; case Keys.NumPad9: bnum9_Click(null, null); break; } } private void textBox1_KeyDown(object sender, KeyEventArgs e) { switch (e.KeyCode) { case Keys.Add: bplus_Click(null, null); break; case Keys.Subtract: bminus_Click(null, null); break; case Keys.Multiply: btime_Click(null, null); break; case Keys.Divide: bdiv_Click(null, null); break; case Keys.Return: bcalc_Click(null, null); break; } } #endregion //toolbar functions (WIP) #region toolbar private void bxx_Click(object sender, EventArgs e) { if (func == false) textBox1.Text = Math.Pow(Convert.ToDouble(textBox1.Text), 2).ToString(); else textBox1.Text = Math.Pow(Convert.ToDouble(textBox1.Text), 3).ToString(); update(); } private void bxn_Click(object sender, EventArgs e) { if (func == false) { if (state == null) { update(); state = "^"; prev = num; num = 0; label1.Text = Convert.ToString(prev) + " ^"; textBox1.Text = "0"; } else if (state != "^") { state = "^"; label1.Text = Convert.ToString(prev) + " ^"; } textBox1.Focus(); textBox1.SelectAll(); } else { if (state == null) { update(); state = "√"; prev = num; num = 0; label1.Text = Convert.ToString(prev) + " √"; textBox1.Text = "0"; } else if (state != "√") { state = "√"; label1.Text = Convert.ToString(prev) + " √"; } textBox1.Focus(); textBox1.SelectAll(); } } private void bsin_Click(object sender, EventArgs e) { double sin = 0; if (func == false) { sin = (Math.Sin(Convert.ToDouble(textBox1.Text) % 360 * Math.PI / 180)); sin = Math.Floor(sin * 1000000) / 1000000; textBox1.Text = Convert.ToString(sin); } else { sin = (Math.Asin(Convert.ToDouble(textBox1.Text) % 360 * Math.PI / 180)); sin = Math.Floor(sin * 1000000) / 1000000; textBox1.Text = Convert.ToString(sin); } } private void bcos_Click(object sender, EventArgs e) { double cos = 0; if (func == false) { cos = (Math.Cos(Convert.ToDouble(textBox1.Text) % 360 * Math.PI / 180)); cos = Math.Floor(cos * 1000000) / 1000000; textBox1.Text = Convert.ToString(cos); } else { cos = (Math.Acos(Convert.ToDouble(textBox1.Text) % 360 * Math.PI / 180)); cos = Math.Floor(cos * 1000000) / 1000000; textBox1.Text = Convert.ToString(cos); } } private void btan_Click(object sender, EventArgs e) { double tan = 0; if (Convert.ToDouble(textBox1.Text) == 90 || Convert.ToDouble(textBox1.Text) == 270) textBox1.Text = "不存在"; else if (func == false) { tan = (Math.Tan(Convert.ToDouble(textBox1.Text) % 360 * Math.PI / 180)); tan = Math.Round(tan * 1000000) / 1000000; textBox1.Text = Convert.ToString(tan); } else { tan = (Math.Atan(Convert.ToDouble(textBox1.Text) % 360 * Math.PI / 180)); tan = Math.Round(tan * 1000000) / 1000000; textBox1.Text = Convert.ToString(tan); } } private void bdx_Click(object sender, EventArgs e) { if (func == false) { if (state == null) { state = "√"; prev = num; num = 0; label1.Text = Convert.ToString(prev) + " √"; update(); } else if (state != "√") { state = "√"; label1.Text = Convert.ToString(prev) + " √"; } textBox1.Focus(); textBox1.SelectAll(); } //else { } } private void b10n_Click(object sender, EventArgs e) { } private void blog_Click(object sender, EventArgs e) { } private void bexp_Click(object sender, EventArgs e) { if (func == false) { tempstate = "exp"; prev = num; textBox1.Text += ".e+"; temptext = textBox1.Text; num = 0; } } private void bstep_Click(object sender, EventArgs e) { double tempn = 1; if (num == 0) { num = 1; update(); } else for (double n = 1; n <= num; n++) tempn = tempn * n; num = tempn; update(); } private void bmod_Click(object sender, EventArgs e) { } #endregion //button function unrelated to calculation #region misc private void recordClear_Click(object sender, EventArgs e) { historyBox.Items.Clear(); } //history box clear private void bup_Click(object sender, EventArgs e) { if (func == false) { func = true; bup.BackColor = SystemColors.ButtonShadow; bxx.Text = "x³"; bxn.Text = "n√x"; bsin.Text = "sin⁻¹"; bcos.Text = "cos⁻¹"; btan.Text = "tan⁻¹"; bdx.Text = "1/x"; b10n.Text = "eⁿ"; blog.Text = "ln"; bexp.Text = "dms"; bmod.Text = "deg"; } else { func = false; bup.BackColor = SystemColors.ButtonFace; bxx.Text = "x²"; bxn.Text = "xⁿ"; bsin.Text = "sin"; bcos.Text = "cos"; btan.Text = "tan"; bdx.Text = "√"; b10n.Text = "10ⁿ"; blog.Text = "log"; bexp.Text = "Exp"; bmod.Text = "Mod"; } update(); } //alt switch for toolbar private void bus_Click(object sender, EventArgs e) { if (neg == false) { textBox1.Text = "-" + textBox1.Text; neg = true; } else { textBox1.Text.Replace("-", string.Empty); neg = false; } } //negative assignemnt private void bce_Click(object sender, EventArgs e) { num = 0; textBox1.Text = Convert.ToString(num); } //clear private void textBox1_KeyPress(object sender, KeyPressEventArgs e) { if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && (e.KeyChar != '.')) { e.Handled = true; } // only allow one decimal point if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1)) { e.Handled = true; } if ((e.KeyChar == '-') && ((sender as TextBox).Text.IndexOf('-') > -1)) { e.Handled = true; } } //only allow numbers and one decimal point #endregion } }
C#
UTF-8
1,833
2.546875
3
[]
no_license
using System.Drawing; using Esri.ArcGISRuntime.Geometry; using Esri.ArcGISRuntime.Symbology; using Esri.ArcGISRuntime.UI; namespace QBasket_demo { public class EsriSketchEd { private SketchCreationMode _mode; private SketchEditConfiguration _config; private LineSymbol _outline; private Symbol _symbol; private Geometry _geometry; public SketchCreationMode mode { get => _mode; set { _mode = value; } } public SketchEditConfiguration config { get => _config; set { _config = value; } } public LineSymbol outline { get => _outline; set { _outline = value; } } public Symbol symbol { get => _symbol; set { _symbol = value; } } public Geometry geometry { get => _geometry; set { _geometry = value; } } public EsriSketchEd() { mode = new SketchCreationMode(); config = new SketchEditConfiguration(); outline = new SimpleLineSymbol(); } /// <summary> /// Create the graphic /// </summary> /// <param name="geometry"></param> /// <returns></returns> public void ConfigRedRect() { outline.Color = Color.Red; outline.Width = 2; // Create a graphic to display the specified geometry symbol = new SimpleFillSymbol() { Outline = outline, Style = SimpleFillSymbolStyle.Null }; // Create graphics area for a re-drawable rectangle mode = (SketchCreationMode)6; config = new SketchEditConfiguration(); config.AllowMove = true; config.AllowRotate = false; config.ResizeMode = (SketchResizeMode)1; } } }
C
UTF-8
321
3.046875
3
[]
no_license
#include <stdio.h> void f(unsigned long int x, unsigned long int y, unsigned long int z) { printf("x = %lu\n",x); printf("y = %lu\n",y); printf("z = %lu\n",z); y = 4UL; printf("x = %lu\n",x); printf("y = %lu\n",y); printf("z = %lu\n",z); } int main() { f(1UL,2UL,3UL); return 0; }
Java
UTF-8
2,481
1.984375
2
[]
no_license
package com.happymall.webservice.domain; import java.util.Date; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.OneToOne; import javax.persistence.Transient; import org.springframework.format.annotation.DateTimeFormat; @Entity public class Payment { @javax.persistence.Id @GeneratedValue(strategy = GenerationType.IDENTITY) private int id; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "card_detail_id") private CardDetail cardDetail; @OneToOne(fetch = FetchType.LAZY) private Orders orders; private double paymentTotal; @DateTimeFormat(pattern = "MM/dd/yyyy") private Date paymentDate; @Column private String status; @DateTimeFormat(pattern = "MM/dd/yyyy") private Date createDate; @DateTimeFormat(pattern = "MM/dd/yyyy") private Date modifiedDate; @Transient private List<Transaction> listTransaction; public int getId() { return id; } public void setId(int id) { this.id = id; } public CardDetail getCardDetail() { return cardDetail; } public void setCardDetail(CardDetail cardDetail) { this.cardDetail = cardDetail; } public Orders getOrders() { return orders; } public void setOrders(Orders orders) { this.orders = orders; } public double getPaymentTotal() { return paymentTotal; } public void setPaymentTotal(double paymentTotal) { this.paymentTotal = paymentTotal; } public Date getPaymentDate() { return paymentDate; } public void setPaymentDate(Date paymentDate) { this.paymentDate = paymentDate; } public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } public Date getModifiedDate() { return modifiedDate; } public void setModifiedDate(Date modifiedDate) { this.modifiedDate = modifiedDate; } public List<Transaction> getListTransaction() { return listTransaction; } public void setListTransaction(List<Transaction> listTransaction) { this.listTransaction = listTransaction; } }
Python
UTF-8
3,945
2.75
3
[]
no_license
#from __future__ import division import math from PIL import Image import numpy as np import datetime def makebasis(u,v): yaw = (0.5 - u) * (-2.0*math.pi); pitch = (0.5 - v) * (math.pi); R_p =np.matrix(([1.0, 0.0, 0.0],[ 0.0 ,math.cos(pitch),math.sin(pitch)],[0.0,-math.sin(pitch),math.cos(pitch)])) R_y =np.matrix(([math.cos(yaw),0.0 , -math.sin(yaw)],[0.0,1.0,0.0],[math.sin(yaw),0.0,math.cos(yaw)])) R_p = R_p.getT() R_ = np.matmul(R_y,R_p) x_basis = R_[:, 0] y_basis = R_[:, 1] z_basis = R_[:, 2] return [x_basis,y_basis,z_basis] #img.show() def make_2Dimage(img,u,v,fovX,fovY,lookup_index): inwidth, inheight = img.size # fovX =math.pi/2 #fovY =math.pi/2 outwidth =700 #outheight = int(outwidth * fovY/fovX) outheight=700 img2 = Image.new(img.mode,(outwidth,outheight),0) #generate float image code basis =makebasis(u,v) #center point (u,v) (0,0-left top) x0 = basis[0][0, 0] x1 = basis[0][1, 0] x2 = basis[0][2, 0] y0 = basis[1][0, 0] y1 = basis[1][1, 0] y2 = basis[1][2, 0] z0 = basis[2][0, 0] z1 = basis[2][1, 0] z2 = basis[2][2, 0] #print basis lookup = dict(); for y in xrange(outheight): #print y for x in xrange(outwidth): #xx = 2*(y+0.5) / width - 1.0 xx = ((x-outwidth/2.0)/outwidth * math.tan(fovX/2.0) *2.0) #yy = 2*(y+0.5)/ height - 1.0 yy = ((outheight/2.0 -y) /outheight *math.tan(fovY/2.0)*2.0) #dir_0 = xx*basis[0][0,0] + yy*basis[1][0,0] - basis[2][0,0] #dir_1 = xx * (basis[0])[1,0] + yy * basis[1][1,0] - basis[2][1,0] #dir_2 = xx * basis[0][2,0] + yy * basis[1][2,0] - basis[2][2,0] dir_0 = xx*x0 + yy*y0 - z0 dir_1 = xx * x1 + yy *y1 - z1 dir_2 = xx * x2+ yy * y2 - z2 # print outheight #print 'index xx %f' %xx #print 'math tan %f' %math.tan(fovX/2.0) len = math.sqrt(dir_0*dir_0 +dir_1*dir_1+ dir_2*dir_2) #ix and iy must be integers #ix = int((0.5 * lng / math.pi + 0.5) * width - 0.5) ix = int((math.atan2( dir_0,-(dir_2))/(2*math.pi)+ 0.5)*inwidth) iy = int((0.5-math.asin( dir_1/len)/math.pi)*inheight ) if(ix>=inwidth): ix= inwidth-1 if(ix<0): ix=0 if(iy>=inheight): iy = inheight -1 if(iy<0): iy=0 #not sure of this part to remap the image newpixel = pixel[ix, iy] #print xx img2.putpixel([x, y], newpixel) tuple1 = (lookup_index,x,y) tuple2 = (ix,iy) lookup[tuple1] = tuple2 return (img2,lookup) #break #break img_index=0 image_path ='./splited_image/test' img = Image.open('./test_panorama/pano_aohmbsejqkhebw.jpg') img = img.convert('RGB') pixel = img.load() #I tries as mentionned in the following code to invert x and y in the two previous lines but the index error out of range comes back ##img2.show() f1 = open("./2D_index.txt",'r') lines1 = [line1.rstrip() for line1 in f1.readlines()] for line1 in lines1: print 'making cubemap image... %d/8' % (img_index + 1) index = line1.split('\t')[0] u = line1.split('\t')[1] v = line1.split('\t')[2] a = datetime.datetime.now() tmp = make_2Dimage(img, float(u), float(v), math.pi / 1.8, math.pi / 1.8,img_index) print (datetime.datetime.now() - a) img2 = tmp[0] table = tmp[1] #print table image_name = image_path + str(index) + '.jpg' img2.save(image_name) img_index =img_index +1 if img_index>7: break #print "{},{}".format(u,v) #dir_key = dir_key.replace("\\", "/")
Python
UTF-8
2,245
3.34375
3
[]
no_license
from controller import Robot timeStep = 32 # Set the time step for the simulation max_velocity = 6.28 # Set a maximum velocity time constant nothing = 0 # Make robot controller instance robot = Robot() # Define the wheels wheel1 = robot.getDevice("wheel1 motor") # Create an object to control the left wheel wheel2 = robot.getDevice("wheel2 motor") # Create an object to control the right wheel # Set the wheels to have infinite rotation wheel1.setPosition(float("inf")) wheel2.setPosition(float("inf")) # Define distance sensors s5 = robot.getDevice("ps5") # adelante izquierda s7 = robot.getDevice("ps7") # costado izquierda s0 = robot.getDevice("ps0") # adelante derecha s2 = robot.getDevice("ps2") # costado derecha # Enable distance sensors N.B.: This needs to be done for every sensor s5.enable(timeStep) s7.enable(timeStep) s0.enable(timeStep) s2.enable(timeStep) start = robot.getTime() while robot.step(timeStep) != -1: speed1 = max_velocity speed2 = max_velocity vel = 0 def turn_left_on_place(motors, smoothness_factor = 10): #right motors wheel1.setVelocity(vel/smoothness_factor) # left motors whelel2.setVelocity(-vel/smoothness_factor) def avanzar(vel): speed1 = vel speed2 = vel def girar_derecha(vel): speed1 = vel speed2 = -vel def girar_izquierda(): speed1 = -vel speed2 = vel def quieto(): speed1 = nothing speed2 = nothing if (s7.getValue() > 0.1 and s0.getValue() > 0.1): # Pregunta si ve algo con alguno de los sensores de adelante. En ese caso, avanza. avanzar(max_velocity) print("avanzar") else: turn_left_on_place() print("derecha") # if (s7.getValue() < 0.1 and s0.getValue() < 0.1): # Si detecta algo con los sensores de adelante, pregunta si ve algo con los sensores de los costados # if (s2.getValue() < 0.1): # girar_derecha(vel) # if (s5.getValue() < 0.1): # girar_izquierda(vel) # Set the wheel velocity wheel1.setVelocity(speed1) wheel2.setVelocity(speed2)
Java
UTF-8
562
1.65625
2
[]
no_license
package cn.wtu.broadcast.openapi.api; import cn.wtu.broadcast.openapi.model.BBroadcastTemp; import cn.wtu.broadcast.openapi.vo.BBroadcastTempVO; import cn.wtu.broadcast.parent.exceptions.BizException; import cn.wtu.broadcast.parent.service.api.ParentService; import com.github.pagehelper.PageInfo; import java.util.Map; /** * Created on 11/03/2019 16:09 * * @author LY */ public interface BBroadcastTempService extends ParentService<BBroadcastTemp> { public PageInfo<BBroadcastTempVO> queryPage(Map<String, Object> paramMap) throws BizException ; }
JavaScript
UTF-8
1,799
2.84375
3
[]
no_license
var inputImage = function (element) { element.on('change', function (e) { var files = e.target.files; if (files.length) { // create a FormData object which will be sent as the data payload in the // AJAX request var formData = new FormData(); // loop through all the selected files and add them to the formData object for (var i = 0; i < files.length; i++) { var file = files[i]; // add the files to formData object for the data payload if (isFileValid(file)) { formData.append('uploads[]', file, file.name); } else { alert("Image is not suitable for this resource"); } } $.ajax({ url: '/post/uploads', type: 'POST', data: formData, processData: false, contentType: false, withCredentials: true, success: function (data) { formData.getAll('uploads[]').forEach(function (img) { var el = $("iframe").contents().find("body#tinymce"); addImgToPost(img.name, el); }); }, error: function (err) { console.log("can't upload file " + err); } }); } }); }; function addImgToPost(imgName, container) { var imgContainer = "<div class='uploadedImg'><img src='" + "/uploads/" + imgName + "' alt=" + imgName + "/></div>"; container.append(imgContainer); } function isFileValid(file) { console.log(file.size); return file.name.match(/.+\.(jpg|png)$/i) && file.size <= 2000000; }
TypeScript
UTF-8
2,692
2.671875
3
[]
no_license
import httpRequest from "./http-request"; const { JSDOM } = require('jsdom'); const overrideNames: any = { 4115: "Nihonium", 9999: "Debug" } export default class EntityDataPage { readonly id: number; name: string | undefined = undefined; information: string | undefined = undefined; is: number[] | undefined = undefined; are: number[] | undefined = undefined; constructor(id: number) { this.id = id; } populate() { return new Promise<void>(async (resolve, reject) => { const httpResponse = await httpRequest('chemthes.com', '/entity_datapage.php?id=' + this.id); const dom = new JSDOM(httpResponse); const tables: any[] = []; const mainPage = dom.window.document.querySelector(".main_page"); if (mainPage === null) return reject('Page does not contain .main_page'); mainPage.childNodes.forEach((el: any) => { if (el.rows !== undefined) tables.push(el); }); const dataTable = tables[0]; const inheritanceTable = tables[1]; // Data this.information = dataTable.rows[2].children[1].innerHTML.replace(/<table[\s\S]*<\/table>/g, '').replace(/<br>/g, '\n').trim(); if (this.information === 'undefined') return reject('Cannot find entity information'); // Inheritance this.name = overrideNames[this.id] ?? inheritanceTable.rows[0].children[1].children[1].textContent.trim(); if (this.name === undefined) return reject('Cannot find entity name.'); this.is = []; const isTable = inheritanceTable.rows[1].children[0].children[0]; if (isTable !== undefined) { Array.from(isTable.rows).forEach((row: any) => { let id = parseInt(row.children[0].children[1].href.split('=')[1]); if (!this.is?.includes(id)) this.is?.push(id); }); } this.are = []; const areTable = inheritanceTable.rows[1].children[1].children[0]; if (areTable !== undefined) { Array.from(areTable.rows).forEach((row: any) => { let id = parseInt(row.children[0].children[1].href.split('=')[1]); if (!this.are?.includes(id)) this.are?.push(id); }); } resolve(); }); } }
Rust
UTF-8
1,279
2.890625
3
[ "MIT", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
#![no_std] use hotg_rune_proc_blocks::{ProcBlock, Tensor, Transform}; use num_traits::{FromPrimitive, ToPrimitive}; pub fn modulo<T>(modulus: f32, values: &mut [T]) where T: ToPrimitive + FromPrimitive, { for item in values { let float = item.to_f32().unwrap(); *item = T::from_f32(float % modulus).unwrap(); } } #[derive(Debug, Clone, Copy, PartialEq, ProcBlock)] pub struct Modulo { modulus: f32, } impl Modulo { pub fn new() -> Self { Modulo { modulus: 1.0 } } } impl Default for Modulo { fn default() -> Self { Modulo::new() } } impl<'a, T> Transform<Tensor<T>> for Modulo where T: ToPrimitive + FromPrimitive, { type Output = Tensor<T>; fn transform(&mut self, input: Tensor<T>) -> Tensor<T> { let modulus = self.modulus; input.map(|_, item| { let float = item.to_f32().unwrap(); T::from_f32(float % modulus).unwrap() }) } } #[cfg(test)] mod tests { use super::*; #[test] fn mod_360() { let number = 42 + 360; let mut m = Modulo::new(); m.set_modulus(360.0); let input = Tensor::single(number); let got = m.transform(input); assert_eq!(got, Tensor::single(42_i64)); } }
Java
UTF-8
3,011
2.328125
2
[]
no_license
package com.guns21.web.servlet; import com.alibaba.fastjson.JSON; import com.guns21.domain.result.light.Result; import com.guns21.web.annotation.AuthAnnotation; import com.guns21.web.constant.SpringConstant; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.method.HandlerMethod; import org.springframework.web.servlet.HandlerInterceptor; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import java.io.*; /** * */ public class AuthTokenInterceptor implements HandlerInterceptor { private static Logger logger = LoggerFactory.getLogger(AuthTokenInterceptor.class); public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object arg2, Exception arg3) throws Exception { } public void postHandle(HttpServletRequest request, HttpServletResponse response, Object arg2, ModelAndView arg3) throws Exception { } public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { if (handler.getClass().isAssignableFrom(HandlerMethod.class)) { HandlerMethod handlerMethod = (HandlerMethod) handler; AuthAnnotation authAnnotation = handlerMethod.getMethodAnnotation(AuthAnnotation.class); if (authAnnotation == null) { return true; } else { return validateToken(request, response); } } return true; } protected boolean validateToken(HttpServletRequest request, HttpServletResponse response) throws IOException { /* * 1.当客户端连接服务器是都会生成session,都有session id * 2.只有登陆成功才会返回token,并且设置session中的LOGIN_USER属性为当前登录用户 * 3.当有人拿到session id时需要判断LOGIN_USER属性是否为空,来判断是否登录过 * */ String tokenId = request.getHeader(SpringConstant.TOKEN_KEY); HttpSession currentSession = request.getSession(false); if (null == tokenId && null == currentSession) { response.setCharacterEncoding("utf-8"); response.getWriter().print(JSON.toJSONString(Result.fail("未登陆", "0010003"))); return false; } else if (null != tokenId && null == currentSession) { //token过期 response.setCharacterEncoding("utf-8"); response.getWriter().print(JSON.toJSONString(Result.fail("token过期", "0010004"))); return false; } else if (null != tokenId && null != currentSession) { //授权通过 return true; } else { logger.error("授权验证未知情况出现,需要验证该情况"); return false; } } }
Markdown
UTF-8
1,854
3.453125
3
[ "MIT" ]
permissive
--- title: 憤怒在衝突中的角色 date: 04/06/2019 --- 誰沒有或多或少有過憤怒的感受?當這種憤怒針對某個家人時,則會令人更加難受。伴隨著拒絕饒恕而產生的憤怒可能會轉變成毒藥,給家庭、家人和親情帶來巨大的痛苦和折磨。 `閱讀弗4:26-27和傳7:9。憤怒作為一種情緒和憤怒作為一種罪惡,兩種理解如何達到平衡?二者有何區別?` `雅各在雅1:19-20說了什麼,是我們應當隨時應用在生活中的,尤其當家人的行為、態度和言語讓我們生氣時?` 如果你為了某件事情而感到氣憤,與其讓它像烏雲籠罩你的生活,不如從積極的一面來改變它。為那些傷害、辱駡你的人禱告。饒恕他們,讓自己成為他們的祝福。雖然一開始這樣做可能很難,但當你下定決心並堅持下去時,上帝會負責到底。 有時憤怒起源於我們成長的家庭。愛生氣的人通常來自於一個怒氣十足的家,因為他們會從這個榜樣身上學習,不但在自己的生活中表現出相同的行為,最終還會影響下一代。有時怒氣可能來自於未得滿足的需求或嫉妒,就像該隱的例子,最終導致他謀殺了自己的弟兄。 也許你有充分的理由發火,但不要以此為藉口來維持這種狀態。不要否認,也不要將其合理化,反而應該祈求上帝説明你以正面的方式解決這一問題。使徒保羅給了我們很好的建議:「你不可為惡所勝,反要以善勝惡。」(羅12:21) `我們都會遇到讓我們生氣的事情,有時甚至讓我們倍感痛苦。而且,在某些情況下,我們的發怒的理由也許完全是正當的。問題是我們如何借助上帝的力量,讓這憤怒不給自己和身邊的人造成痛苦?`
Rust
UTF-8
11,943
2.515625
3
[ "Apache-2.0", "MIT" ]
permissive
use std::marker::PhantomData; use num_bigint::BigUint; use num_traits::ToPrimitive; use serde::de::Deserialize; use serde::ser::Serialize; use crate::drgraph::graph_height; use crate::error::{Error, Result}; use crate::hasher::{Domain, Hasher}; use crate::merkle::{MerkleProof, MerkleTree}; use crate::parameter_cache::ParameterSetIdentifier; use crate::proof::{NoRequirements, ProofScheme}; #[derive(Debug, Clone)] pub struct SetupParams { /// How many leaves the underlying merkle tree has. pub leaves: usize, /// The number of sectors that are proven over. pub sectors_count: usize, /// How many challenges there are in total. pub challenges_count: usize, } #[derive(Debug, Clone)] pub struct PublicParams { // NOTE: This assumes all sectors are the same size, which may not remain a valid assumption. /// How many leaves the underlying merkle tree has. pub leaves: usize, /// The number of sectors that are proven over. pub sectors_count: usize, /// How many challenges there are in total. pub challenges_count: usize, } impl ParameterSetIdentifier for PublicParams { fn parameter_set_identifier(&self) -> String { format!( "porc::PublicParams{{leaves: {} sectors_count: {} challenges_count: {}}}", self.leaves, self.sectors_count, self.challenges_count, ) } } #[derive(Debug, Clone)] pub struct PublicInputs<'a, T: 'a + Domain> { /// The challenges, which leafs to prove. pub challenges: &'a [usize], pub challenged_sectors: &'a [usize], /// The root hashes of the underlying merkle trees. pub commitments: &'a [T], } #[derive(Debug, Clone)] pub struct PrivateInputs<'a, H: 'a + Hasher> { pub trees: &'a [&'a MerkleTree<H::Domain, H::Function>], } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Proof<H: Hasher>( #[serde(bound( serialize = "MerkleProof<H>: Serialize", deserialize = "MerkleProof<H>: Deserialize<'de>" ))] Vec<MerkleProof<H>>, ); impl<H: Hasher> Proof<H> { pub fn leafs(&self) -> Vec<&H::Domain> { self.0.iter().map(MerkleProof::leaf).collect() } pub fn commitments(&self) -> Vec<&H::Domain> { self.0.iter().map(MerkleProof::root).collect() } pub fn paths(&self) -> Vec<&Vec<(H::Domain, bool)>> { self.0.iter().map(MerkleProof::path).collect() } } #[derive(Debug, Clone)] pub struct PoRC<'a, H> where H: 'a + Hasher, { _h: PhantomData<&'a H>, } impl<'a, H: 'a + Hasher> ProofScheme<'a> for PoRC<'a, H> { type PublicParams = PublicParams; type SetupParams = SetupParams; type PublicInputs = PublicInputs<'a, H::Domain>; type PrivateInputs = PrivateInputs<'a, H>; type Proof = Proof<H>; type Requirements = NoRequirements; fn setup(sp: &Self::SetupParams) -> Result<Self::PublicParams> { Ok(PublicParams { leaves: sp.leaves, sectors_count: sp.sectors_count, challenges_count: sp.challenges_count, }) } fn prove<'b>( pub_params: &'b Self::PublicParams, pub_inputs: &'b Self::PublicInputs, priv_inputs: &'b Self::PrivateInputs, ) -> Result<Self::Proof> { if priv_inputs.trees.len() != pub_params.sectors_count { return Err(Error::MalformedInput); } if priv_inputs.trees.len() != pub_params.sectors_count { return Err(Error::MalformedInput); } if pub_inputs.challenges.len() != pub_params.challenges_count { return Err(Error::MalformedInput); } if pub_inputs.challenged_sectors.len() != pub_params.challenges_count { return Err(Error::MalformedInput); } let proofs = pub_inputs .challenges .iter() .zip(pub_inputs.challenged_sectors) .map(|(challenged_leaf, challenged_sector)| { let tree = priv_inputs.trees[*challenged_sector]; if pub_inputs.commitments[*challenged_sector] != tree.root() { return Err(Error::InvalidCommitment); } Ok(MerkleProof::new_from_proof( &tree.gen_proof(*challenged_leaf), )) }) .collect::<Result<Vec<_>>>()?; Ok(Proof(proofs)) } fn verify( pub_params: &Self::PublicParams, pub_inputs: &Self::PublicInputs, proof: &Self::Proof, ) -> Result<bool> { if pub_inputs.challenges.len() != pub_params.challenges_count { return Err(Error::MalformedInput); } if pub_inputs.challenged_sectors.len() != pub_params.challenges_count { return Err(Error::MalformedInput); } // validate each proof for (merkle_proof, (challenged_leaf, challenged_sector)) in proof.0.iter().zip( pub_inputs .challenges .iter() .zip(pub_inputs.challenged_sectors.iter()), ) { // validate the commitment if merkle_proof.root() != &pub_inputs.commitments[*challenged_sector] { return Ok(false); } // validate the path length if graph_height(pub_params.leaves) != merkle_proof.path().len() { return Ok(false); } if !merkle_proof.validate(*challenged_leaf) { return Ok(false); } } Ok(true) } } pub fn slice_mod(challenge: impl AsRef<[u8]>, count: usize) -> usize { // TODO: verify this is the correct way to derive the challenge let big_challenge = BigUint::from_bytes_be(challenge.as_ref()); (big_challenge % count) .to_usize() .expect("failed modulus operation") } #[cfg(test)] mod tests { use super::*; use paired::bls12_381::Bls12; use rand::{Rng, SeedableRng, XorShiftRng}; use crate::drgraph::{new_seed, BucketGraph, Graph}; use crate::fr32::fr_into_bytes; use crate::hasher::{Blake2sHasher, HashFunction, PedersenHasher, Sha256Hasher}; use crate::merkle::make_proof_for_test; fn test_porc<H: Hasher>() { let rng = &mut XorShiftRng::from_seed([0x3dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); let leaves = 32; let pub_params = PublicParams { leaves, sectors_count: 1, challenges_count: 2, }; let data: Vec<u8> = (0..32) .flat_map(|_| fr_into_bytes::<Bls12>(&rng.gen())) .collect(); let graph = BucketGraph::<H>::new(32, 5, 0, new_seed()); let tree = graph.merkle_tree(data.as_slice()).unwrap(); let pub_inputs = PublicInputs { challenges: &vec![rng.gen_range(0, leaves), rng.gen_range(0, leaves)], challenged_sectors: &[0, 0], commitments: &[tree.root()], }; let priv_inputs = PrivateInputs::<H> { trees: &[&tree] }; let proof = PoRC::<H>::prove(&pub_params, &pub_inputs, &priv_inputs).expect("proving failed"); let is_valid = PoRC::<H>::verify(&pub_params, &pub_inputs, &proof).expect("verification failed"); assert!(is_valid); } #[test] fn porc_pedersen() { test_porc::<PedersenHasher>(); } #[test] fn porc_sha256() { test_porc::<Sha256Hasher>(); } #[test] fn porc_blake2s() { test_porc::<Blake2sHasher>(); } // Construct a proof that satisfies a cursory validation: // Data and proof are minimally consistent. // Proof root matches that requested in public inputs. // However, note that data has no relationship to anything, // and proof path does not actually prove that data was in the tree corresponding to expected root. fn make_bogus_proof<H: Hasher>( pub_inputs: &PublicInputs<H::Domain>, rng: &mut XorShiftRng, ) -> MerkleProof<H> { let bogus_leaf: H::Domain = rng.gen(); let hashed_leaf = H::Function::hash_leaf(&bogus_leaf); make_proof_for_test( pub_inputs.commitments[0], hashed_leaf, vec![(hashed_leaf, true)], ) } fn test_porc_validates<H: Hasher>() { let rng = &mut XorShiftRng::from_seed([0x3dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); let pub_params = PublicParams { leaves: 32, sectors_count: 1, challenges_count: 2, }; let data: Vec<u8> = (0..32) .flat_map(|_| fr_into_bytes::<Bls12>(&rng.gen())) .collect(); let graph = BucketGraph::<H>::new(32, 5, 0, new_seed()); let tree = graph.merkle_tree(data.as_slice()).unwrap(); let pub_inputs = PublicInputs::<H::Domain> { challenges: &vec![rng.gen(), rng.gen()], challenged_sectors: &[0, 0], commitments: &[tree.root()], }; let bad_proof = Proof(vec![ make_bogus_proof::<H>(&pub_inputs, rng), make_bogus_proof::<H>(&pub_inputs, rng), ]); let verified = PoRC::verify(&pub_params, &pub_inputs, &bad_proof).expect("verification failed"); // A bad proof should not be verified! assert!(!verified); } #[test] fn porc_actually_validates_sha256() { test_porc_validates::<Sha256Hasher>(); } #[test] fn porc_actually_validates_blake2s() { test_porc_validates::<Blake2sHasher>(); } #[test] fn porc_actually_validates_pedersen() { test_porc_validates::<PedersenHasher>(); } fn test_porc_validates_challenge_identity<H: Hasher>() { let rng = &mut XorShiftRng::from_seed([0x3dbe6259, 0x8d313d76, 0x3237db17, 0xe5bc0654]); let leaves = 32; let pub_params = PublicParams { leaves, sectors_count: 1, challenges_count: 2, }; let data: Vec<u8> = (0..32) .flat_map(|_| fr_into_bytes::<Bls12>(&rng.gen())) .collect(); let graph = BucketGraph::<H>::new(32, 5, 0, new_seed()); let tree = graph.merkle_tree(data.as_slice()).unwrap(); let pub_inputs = PublicInputs { challenges: &vec![rng.gen_range(0, leaves), rng.gen_range(0, leaves)], challenged_sectors: &[0, 0], commitments: &[tree.root()], }; let priv_inputs = PrivateInputs::<H> { trees: &[&tree] }; let proof = PoRC::<H>::prove(&pub_params, &pub_inputs, &priv_inputs).expect("proving failed"); let different_pub_inputs = PublicInputs { challenges: &vec![rng.gen_range(0, leaves), rng.gen_range(0, leaves)], challenged_sectors: &[0, 0], commitments: &[tree.root()], }; let verified = PoRC::<H>::verify(&pub_params, &different_pub_inputs, &proof) .expect("verification failed"); // A proof created with a the wrong challenge not be verified! assert!(!verified); } #[test] fn porc_actually_validates_challenge_identity_sha256() { test_porc_validates_challenge_identity::<Sha256Hasher>(); } #[test] fn porc_actually_validates_challenge_identity_blake2s() { test_porc_validates_challenge_identity::<Blake2sHasher>(); } #[test] fn porc_actually_validates_challenge_identity_pedersen() { test_porc_validates_challenge_identity::<PedersenHasher>(); } #[test] fn test_slice_mod() { let cases: [(Vec<u8>, usize, usize); 5] = [ (vec![0], 10, 0), (vec![1], 10, 1), (vec![9], 10, 9), (vec![10], 10, 0), (vec![100, 0, 0, 1], 10, 1), ]; for (challenge, count, expected) in &cases { assert_eq!(slice_mod(challenge, *count), *expected); } } }
C++
UTF-8
685
3.140625
3
[]
no_license
#include<cstdio> #include<iostream> using namespace std; const int maxn = 10010; void vowels(char str1[], char str2[]){ int i = 0, j = 0; while ( str1[i] != '\0' ) { if ( str1[i] == 'a' || str1[i] == 'A' ) str2[j++] = str1[i]; else if ( str1[i] == 'e' || str1[i] == 'E' ) str2[j++] = str1[i]; else if ( str1[i] == 'i' || str1[i] == 'I' ) str2[j++] = str1[i]; else if ( str1[i] == 'o' || str1[i] == 'O' ) str2[j++] = str1[i]; else if ( str1[i] == 'u' || str1[i] == 'U' ) str2[j++] = str1[i]; i++; } str2[j++] = '\0'; } int main(){ char str1[maxn], str2[maxn]; scanf("%s", str1); vowels(str1, str2); printf("%s\n", str2); system("pause"); return 0; }
Python
UTF-8
1,061
2.6875
3
[]
no_license
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes from cryptography.hazmat.backends import default_backend def key_unwrap(kek, ciphertext, iv): n = len(ciphertext) // 8 - 1 a = ciphertext[:8] r = [None] for i in range(1, n + 1): r.append(ciphertext[i*8:(i + 1)*8]) for j in range(5, -1, -1): for i in range(n, 0, -1): t = n*j+i b = AES_decrypt(kek, xor(a, t) + r[i]) a = msb(64, b) r[i] = lsb(64, b) if a != iv: raise ValueError("Integrity Check Failed.") return r[1:] def AES_decrypt(key, b): backend = default_backend() cipher = Cipher(algorithms.AES(key), modes.ECB(), backend=backend) decryptor = cipher.decryptor() return decryptor.update(b) + decryptor.finalize() def msb(j, W): j //= 8 return W[0:j] def lsb(j, W): j //= 8 return W[len(W) - j:] def xor(arr, i): l = len(arr) r = int.from_bytes(arr, byteorder='big') ^ i return int.to_bytes(r, byteorder='big', length=l)
C++
UTF-8
2,068
2.71875
3
[]
no_license
// dp with monotone queue, binary search on answer // https://codeforces.com/gym/100801/attachments (problem J) // 2015 NEERC Northern Subregional #include <bits/stdc++.h> using namespace std; using ll = long long; using ld = long double; #define rep(i, a, b) for(auto i = (a); i < (b); ++i) #define trav(a, x) for(auto& a: x) #define all(x) begin(x),end(x) #define sz(x) (int)x.size() template <typename T, class Operation> struct monotoneQueue { int sz = 0; deque <T> elements; Operation op; monotoneQueue(Operation o) : op(o) {} void insert(T elem) { while (!elements.empty() and op(elem, elements.back())) elements.pop_back(); elements.push_back(elem), sz++; } void erase(T elem) { if(elements.front() == elem) elements.pop_front(); sz--; } T query() const {return elements.front();} }; int main() { ios_base::sync_with_stdio(false); cin.tie(nullptr); freopen("journey.in", "r", stdin); freopen("journey.out", "w", stdout); int n, t; cin >> n >> t; t -= (n - 1); vector<int> p(n); rep(i, 1, n) cin >> p[i]; vector<int> d(n); rep(i, 2, n) cin >> d[i]; auto cmp = less<>{}; auto feas = [&](ll range) { auto q = monotoneQueue<ll, decltype(cmp)>(cmp); vector<ll> dp(n); q.insert(0); rep(i, 2, n) { auto possible = q.query(); dp[i] = d[i] + q.query(); q.insert(dp[i]); if (i > range) q.erase(dp[i - range]); } return q.query(); }; int lo = 1, hi = n - 1; while (lo < hi) { auto mid = (lo + hi) / 2; if (feas(mid) <= t) hi = mid; else lo = mid + 1; } auto best = *min_element(next(begin(p), lo), end(p)); cout << best << '\n'; }
PHP
UTF-8
668
3.640625
4
[]
no_license
<?php $x = 10; $y = 25.500; // echo floor($y); // Sadece tam sayıları algılar. // echo ceil($y); // Üst sayıya yuvarlar // echo round($y); // Küsürat sayı 5 den büyükse yukarı yuvlarlar 5 ten küçükse aşağı yuvarlar // Trigonometri // echo cos($x); // cho sin($x); // echo tan($x); // echo rand(100,999); // Rastgele sayı belirtir. // echo sqrt(25); // Karekök Hesaplama // echo pow(3,2); // Üstünü alma işlemleri // echo abs(-30); // Mutlak değer işlemleri // echo max(10, 20, 30, 40, 500, 800); // Sayıların içinde en yüksek sayıyı verir // echo min(10, 20, 30, 40, 500, 800); // Sayıların içinde en düşük sayıyı verir ?>
Python
UTF-8
468
3.015625
3
[]
no_license
import unittest from src.song import Song from src.room import Room class TestSong(unittest.TestCase): def setUp(self): self.song = Song("Helicopter", "Bloc Party", "Indie") def test_song_has_a_title(self): self.assertEqual("Helicopter", self.song.title) def test_song_has_an_artist(self): self.assertEqual("Bloc Party", self.song.artist) def test_song_has_a_genre(self): self.assertEqual("Indie", self.song.genre)
Python
UTF-8
56
2.703125
3
[ "MIT" ]
permissive
def recursive_power(num, power): return num ** power
Ruby
UTF-8
1,285
3
3
[]
no_license
describe Ability do it 'has a default score of 10' do expect(subject.score).to eq 10 end it 'has a setable score' do subject.score = 15 expect(subject.score).to be 15 end it 'can have a score of 1' do expect { subject.score = 1 }.not_to raise_error end it 'can have a score of 20' do expect { subject.score = 20 }.not_to raise_error end it 'cannot have a score less than 1' do expect { subject.score = 0 }.to raise_error end it 'cannot have a score greater than 20' do expect { subject.score = 21 }.to raise_error end context 'when calculating modifiers' do def verify_modifier score, modifier subject.score = score expect(subject.modifier).to eq modifier end it 'has a modifier of -5 for a score of 1' do verify_modifier 1, -5 end it 'has a modifier of -1 for a score of 9' do verify_modifier 9, -1 end it 'has a modifier of 0 for a score of 10' do verify_modifier 10, 0 end it 'has a modifier of 0 for a score of 11' do verify_modifier 11, 0 end it 'has a modifier of +1 for a score of 12' do verify_modifier 12, +1 end it 'has a modifier of +5 for a score of 20' do verify_modifier 20, +5 end end end
C
UTF-8
620
3.234375
3
[]
no_license
#include <stdio.h> #include <stdlib.h> int main() { FILE *f = fopen("input.txt", "r"), *q = fopen("output.txt", "w"); char *s = (char*)malloc(53), *t = (char*)malloc(53), *k; int n, a, b, c, d, m = 1441; fscanf(f, "%d", &n); while (n--) { int i = 1; while (getc(f) != '"'); t[0] = '"'; while ((t[i++] = getc(f)) != '"'); t[i] = '\0'; fscanf(f, "%d:%d %d:%d", &a, &b, &c, &d); d += (c - a) * 60 - b; if (d <= 0) d += 1440; if (d < m) m = d, k = t, t = s, s = k; } fprintf(q, "The fastest train is %s.\nIts speed is %d km/h, approximately.", s, (int)(650.0 * 60 / m + 0.5)); return 0; }
Markdown
UTF-8
198
3.3125
3
[]
no_license
## Operators You can use multiply (`*`) to multiply strings: ```Python 'la' * 3 # the result is 'lalala' ``` ### Boolean NOT, OR, and AND are represented as `not`, `or`, and `and` respectively.
Java
UTF-8
1,756
2.390625
2
[]
no_license
package com.ctran79.clinic.backend.domain.prescription; import com.ctran79.clinic.backend.domain.BaseEntity; import com.ctran79.clinic.backend.domain.patient.Patient; import com.sun.istack.NotNull; import lombok.Getter; import lombok.Setter; import javax.persistence.*; import java.util.HashSet; import java.util.Set; import java.util.stream.Collectors; /** @author ctran79 */ @Entity @Getter @Setter @Table(name = "prescriptions") public class Prescription extends BaseEntity { @NotNull @JoinColumn(name = "patient_id") @OneToOne(cascade = CascadeType.MERGE) private Patient patient; @OneToMany( fetch = FetchType.EAGER, orphanRemoval = true, cascade = CascadeType.ALL, mappedBy = "prescription") private Set<Diagnosis> diagnoses = new HashSet<>(); @OneToMany( fetch = FetchType.EAGER, orphanRemoval = true, cascade = CascadeType.ALL, mappedBy = "prescription") private Set<Indication> indications = new HashSet<>(); private String note; public void addDiagnosis(Diagnosis diagnosis) { diagnosis.setPrescription(this); this.diagnoses.add(diagnosis); } public void addIndication(Indication indication) { indication.setPrescription(this); this.indications.add(indication); } public PrescriptionDto toDto() { return PrescriptionDto.builder() .id(id) .createDate(createDate) .patient(patient.toDto()) .diagnoses(diagnoses.stream().map(Diagnosis::toDto).collect(Collectors.toSet())) .indications(indications.stream().map(Indication::toDto).collect(Collectors.toSet())) .note(note) .build(); } public Prescription toEntity(PrescriptionDto dto) { note = dto.getNote(); return this; } }
Markdown
UTF-8
1,994
3.046875
3
[]
no_license
# wkhtmltox-promise A simple wrapper for wkhtmltopdf/wkhtmltoimage for ES 2016/2017 using promises. Downloads and installs the latest wkhtmtopdf lib (0.12.4) on linux. ## Installation: npm i wkhtmltox-promise ## API: pdf(source, dest, options) returns Promise image(source, dest, options[, ignore]) returns Promise source = any valid URI dest = any valid URI options = (optional*) array of arguments passed to wkhtmltopdf / wkhtmltoimage > see [https://wkhtmltopdf.org/usage/wkhtmltopdf.txt] for details. ignore = (optional*) array( or object of keys) of errors, or string error to ignore in the child. If the substring in the childs stderr, the promise will resolve anyway. This feature is intended to support some wkhtmltox errors that don't prevent the pdf generation from succeeding, but nonetheless report an exit status > 0 and would otherwise reject. ## Examples: PDF ```javascript const convert = require("wkhtmltox-promise"); convert.pdf("http://www.google.com", "out.pdf") .then(result => { var stdout = result.stdout; console.log('stdout: ', stdout); // do something with out.pdf }) .catch(function (err) { console.error('ERROR: ', err, err.stderr); }); ``` Image ```javascript const convert = require("wkhtmltox-promise"); convert.image("http://www.google.com", "out.png") .then(result => { var stdout = result.stdout; console.log('stdout: ', stdout); // do something with out.png }) .catch(function (err) { console.error('ERROR: ', err, err.stderr); }); ``` Ignoring errors ```javascript const convert = require("wkhtmltox-promise"); convert.pdf("http://www.google.com", "out.png", ['--quiet'], ['UnknownContentError']) .then(result => { var stdout = result.stdout; console.log('stdout: ', stdout); // do something with out.pdf }) .catch(function (err) { console.error('ERROR: ', err, err.stderr); }); ``` [wkhtmltopdf](http://wkhtmltopdf.org/index.html)
JavaScript
UTF-8
2,124
3.21875
3
[]
no_license
console.log("Welcome, traveler."); function sortTags(key) { let sortKey = null; if (key == 0) { // alphabetic sortKey = function (a, b) { function strcmp(a, b) { return a < b ? -1 : a > b ? 1 : 0; } return strcmp(a.textContent, b.textContent); }; } else if (key == 1) { // numeric sortKey = function (a, b) { return ( parseInt(a.getAttribute("data-count")) - parseInt(b.getAttribute("data-count")) ); }; } else { return; } // https://stackoverflow.com/a/8837300 let ul = document.getElementById("tag-list"); let new_ul = ul.cloneNode(false); let lis = []; for (var i = ul.childNodes.length; i--; ) { if (ul.childNodes[i].nodeName === "LI") lis.push(ul.childNodes[i]); } lis.sort(sortKey); for (var i = 0; i < lis.length; i++) new_ul.appendChild(lis[i]); ul.parentNode.replaceChild(new_ul, ul); } let list = document.querySelectorAll(".tag-sort-option"); // document-ordered for (var i = list.length; i--; ) { // reverse list[i].onchange = (function (k) { return function () { sortTags(k); }; })(i); // gotta use IIFE to create closure to save value of 'i' } function updatePosts(tag, hide) { // console.log(tag,hide); let list = document.querySelectorAll("#posts > li"); for (var i = list.length; i--; ) { // tag delimiter == | // TODO -- fix this lmao if (list[i].getAttribute("data-tags").split("|").includes(tag)) { if (hide) list[i].style.visibility = "hidden"; else list[i].style.visibility = "visible"; } // yea lmao make this nicer // we could remove/add things to update the list indices (for display instead of visibile) // but also gotta save the state of selected tags for better filtering } } list = document.querySelectorAll("#tag-list > li"); for (var i = list.length; i--; ) { list[i].onclick = function (e) { let hide = e.target.classList.contains("active"); if (hide) e.target.classList.remove("active"); else e.target.classList.add("active"); updatePosts(e.target.getAttribute("data-tag"), hide); }; }
Python
UTF-8
2,241
4.46875
4
[]
no_license
""" Consider a city where the streets are perfectly laid out to form an infinite square grid. In this city finding the shortest path between two given points (an origin and a destination) is much easier than in other more complex cities. As a new Uber developer, you are tasked to create an algorithm that does this calculation. Given user's departure and destination coordinates, each of them located on some street, find the length of the shortest route between them assuming that cars can only move along the streets. Example For departure = [0.4, 1] and destination = [0.9, 3], the output should be perfectCity(departure, destination) = 2.7. """ def distance(a, b): return abs(a-b) def find_abs_diff(new_corner, original): return distance(new_corner[0], original[0]), distance(new_corner[1], original[1]) def find_new_corner_coord(departure_coord, destination_coord): if int(departure_coord) == int(destination_coord): if distance(departure_coord, int(departure_coord)+1) < 0.5 or \ distance(destination_coord, int(destination_coord)+1) < 0.5: return int(departure_coord)+1 else: return int(departure_coord) elif departure_coord < destination_coord: # go + return int(departure_coord)+1 else: # go - return int(departure_coord) def find_new_corner(original_corner, target_node): return find_new_corner_coord(original_corner[0], target_node[0]), \ find_new_corner_coord(original_corner[1], target_node[1]) def perfectCity(departure, destination): # Find appropriate corner node for departure depart_corner = find_new_corner(departure, destination) depart_abs_diff = find_abs_diff(depart_corner, departure) # Find appropriate corner node for destination dest_corner = find_new_corner(destination, depart_corner) dest_abs_diff = find_abs_diff(dest_corner, destination) # Distance btw 2 corner nodes corners_dist = distance(depart_corner[0], dest_corner[0]) + distance(depart_corner[1], dest_corner[1]) # Total Distance total_dist = depart_abs_diff[0] + depart_abs_diff[1] + dest_abs_diff[0] + dest_abs_diff[1] + corners_dist return float("{0:.1f}".format(total_dist))
Markdown
UTF-8
26,759
2.859375
3
[]
no_license
# Cleaning the data and Feature Engineering Andrea Fernandes <andrea.c.fernandes1@gmail.com> 22 June 2016 ****** #### Cleaning the Data ****** Introductory note The aim of this file is to generate a cleaned dataset. This file explains the variables available in the raw data set, the cleaning process, the variables that will be needed for analysis and the generation of new features/variables (feature engineering) and provides a data dictionary of all the variables in the cleaned dataset. The end product of the following code generates a new dataset named `edclean`. This is data used for exploration of trends in the association of ethnic density with death by suicide. The Data Dictionary is provided in this file. ****** #### Description of the raw (`ed`) dataset ****** The `str(ed)` output (not shown) shows that this raw dataset `ed` contains data or variables that can be sectioned into categories: - the patient demographics, - ethnic density score (which is the main exposure variable), - suicide variable (the main outcome variable), and - other variables (e.g. ethnic density scores and numbers), which may be confounding variables or redundant. In addition, - there are 47581 observations (i.e. patients) and 67 variables, - lots of NA values (see screenshot below), - inexplicable column headings, - redundant variables, - potentially duplicate variables and - several continuous and categorical data variables, that may or may not contain the same data or need to be manipulated for more utility, - not all the 67 variables are infomative or useful ****** Here's a missing map image displaying all the observations and variables in the raw `ed` dataset. The missing values are color coded (red for values, non-red for missing values). ![**Screenshot of the Missing Data Map in the raw dataset**](./missmap.png) ****** Details of the data cleaning required on the raw (`ed`) dataset | Variable Name | Notes | |:-------------------|:-----------------------------------------------| | JunkID | can be deleted, redundant | | Gender_Cleaned | There are 2 "empty" Gender cells. Will replace them with NA | | DOB_Cleaned | one NA value in row 45501, not sure what to do with it, will leave until further analysis | | Marital_Cleaned | 3803 blank values, no NA values. 3803 blank values assigned to NA | | primary_diagnosis | can be deleted, redundant. lots of different diagnosis in unstructured and structured format. and is potentially redundant because there are other variables that are flag variables for the main diagnoses. Diagnosis and diagnosis date columns contain more than 50% NA values. The NA values imply patients who are not diagnosed with the particular disorder. Will replace NA with 0. | | ethnicitycleaned | is fine, no NA or blank values | | imd_score | 49 NA values, not sure what to do here. will leave it in until further anlysis. | | diagnosis_date to Bipolar_Diag_Date | these variables are dates of the main diagnoses and binary flag variables for diagnoses, NA in these variables means patient does not have the disorder. So perhaps better to change it to 0 instead. | | ons_date_of_death | 5310 deaths in the cohort| | Suicide | 263 suicides in the cohort| | ICD10_UnderlyingCause | redundant variable, delete| | LSOAClosestToDiagnosis | LSOA area level address code| | LSOA11 | redundant, delete| | lsoa01 | redundant, delete| | LSOA_NAME | name of boroughs | | C and D | are empty delete| | All_Usual_Residents to AP | variable names are not informative and need to be renamed. These variables are ethnic density (number and percentage of people of different ethnic groups in the corresponding LSOA code) will be needed to generate the main exposure variable "ethnicdensityscore". Some variables with variables names not decipherable and need renaming (e.g. "AL" = OtherBlack_EDPercent). Original names available from original Stata database (not shown). The exposure variable "ethnic density scores" will need to generated using the available columns in the dataset. | ****** #### Code to Clean the Data ****** Cleaning the Gender variable ```r # tabulating the data to check columns table(ed$Gender_Cleaned) # tabulating the data to check NA values table(is.na(ed$Gender_Cleaned)) # no NA values, 2 blank ("") values. # Female Male # 2 23106 24473 #recoding blank gender values as NA ed$Gender_Cleaned[ed$Gender_Cleaned == ""] <- NA table(ed$Gender_Cleaned) table(is.na(ed$Gender_Cleaned)) #identify where gender NA rows are which(is.na(ed$Gender_Cleaned)) # row 682 and 30844 samples_to_remove <- which(is.na(ed$Gender_Cleaned)) # row 682 and 30844 #removing samples from original data "ed" # overwriting ed with new ed. ed <- ed[-samples_to_remove, ] table(is.na(ed$Gender_Cleaned)) table(ed$Gender_Cleaned) # Female Male # 23106 24473 ``` ****** Cleaning the Marital Status variable ```r # tabulating data table(ed$Marital_Cleaned) # 3803 blank ("") values. table(is.na(ed$Marital_Cleaned)) # no NA values # replacing blank values in Marital_Cleaned variable with "Unknown" ed$Marital_Cleaned[ed$Marital_Cleaned == ""] <- "Unknown" table(ed$Marital_Cleaned) # New category name is "Unknown" = 3803 ``` ******* Cleaning the Diagnoses columns ```r # replacing NAs with 0 in the diagnosis columns ed$Schizophrenia_Diag[is.na(ed$Schizophrenia_Diag)] <- 0 ed$SchizoAffective_Diag[is.na(ed$SchizoAffective_Diag)] <- 0 ed$Bipolar_Diag[is.na(ed$Bipolar_Diag)] <- 0 ed$Depressive_Diag[is.na(ed$Depressive_Diag)] <- 0 ed$Manic_Diag[is.na(ed$Manic_Diag)] <- 0 ed$SubAbuse_Diag[is.na(ed$SubAbuse_Diag)] <- 0 ``` ****** Renaming and deleting redundant variables ```r #renaming columns ed <- ed %>% rename(TotalResidentsInLSOA = All_Usual_Residents, WhiteBrit_EDPercent = G, WhiteIrish_EDPercent = White_Irish_Percentage, OtherWhite_EDPercent = White_Other_White_GypsyIrishTrav, WhiteBlackCarib_EDPercent = P, WhiteBlackAfri_EDPercent = R, WhiteAsian_EDPercent = T, OtherMixed_EDPercent = V, BritIndian_EDPercent = Asian_Asian_British_Indian_Perce, BritPakistani_EDPercent = Asian_Asian_British_Pakistani_Pe, BritBangladeshi_EDPercent = AB, BritChinese_EDPercent = Asian_Asian_British_Chinese_Perc, OtherAsian_EDPercent = Asian_Asian_British_OtherAsian_P, African_EDPercent = AH, Caribbean_EDPercent = AJ, OtherBlack_EDPercent = AL, WhiteBrit_Residents = White_English_Welsh_Scottish_Nor, TotalIrish_Residents = White_Irish_Count, OtherWhite_Residents = White_Gypsy_Irish_Traveller_Coun, MixedCaribbean_Residents = Mixed_Multiple_Ethnic_Groups_Whi, MixedAsian_Residents = S, OtherMixed_Residents = Mixed_Multiple_Ethnic_Groups_Oth, BritIndian_Residents = Asian_Asian_British_Indian_Count, BritPakistani_Residents = Asian_Asian_British_Pakistani_Co, BritBangladeshi_Residents = Asian_Asian_British_Bangladeshi_, BritChinese_Residents = Asian_Asian_British_Chinese_Coun, OtherAsian_Residents = Asian_Asian_British_OtherAsian_C, African_Residents = Black_African_Caribbean_BlackBr, Caribbean_Residents = Black_African_Caribbean_Black_Br, OtherBlack_Residents = AK, OtherEthnicity_Residents = Other_Ethnic_Group_AnyOtherEthni) ``` ****** Cleaning Area-level deprivation score (imd_score) ```r table(is.na(ed$imd_score)) #49 NA values. To remove #identifying and assigning deprivation score NA values to "sample to remove" sample_to_remove <- which(is.na(ed$imd_score)) ed <- ed[-sample_to_remove, ] table(is.na(ed$imd_score)) # no NA values # removed 49 rows from entire dataset (these had missing imd_score values) # save save(ed, file = "Cleaned_Data_ED.Rdata", compress = TRUE) ``` ****** ```r # Columns to delete because they are redundant or empty # C and D # lsoa01 # ICD10_UnderlyingCause # primary_diagnosis # JunkID # total dimensions of raw dataset # dim(ed) # 47530 67 ed <- ed %>% select(-C, -D, -lsoa01, -ICD10_UnderlyingCause, -primary_diagnosis, -JunkID) # total dimensions of cleaned dataset # dim(ed) # 47530 61 ``` ****** Cleaned data saved as "Cleaned_Data_ED.Rdata". This contains dataframe `ed`. ```r # save ed save(ed, file = "Cleaned_Data_ED.Rdata", compress = TRUE) ``` ****** ### Feature Engineering ****** List of new features added: - The main exposure variable: Ethnic Density Score (named "ethnicdensityscore") - Ethnicity (named "ethnicity") - Age variables (named "ageatdiagnosis", "ageatdeath" and "agegroups") - Age at Diagnosis", "Age at Death" and "Age Group" - Borough variable (named "LSOA_4boroughs"): Croydon, Lewisham, Southwark, Lambeth and Other - Cause of Death Variable (named "DeathBy") Below is the code used to generate the listed new features. ****** __Ethnic Density Score (named "ethnicdensityscore")__ ```r rm(list=ls()) load("Cleaned_Data_ED.Rdata") # # - The main exposure variable of the dataset is Ethnic Density (ED) score. # Ethnic density is defined as the composition of each ethnic group # residing in a geographical area of a given size (usually a fairly large # geographical area, known as Lower Super Output Area (LSOA) which # consists of around 1500 residents). # # - Since, in the original dataset `ed`, each patient was already assigned # to ethnic density (for every ethnic group) based on their LSOA code, # to assign OWN ethnicity ethnic density score to each individual, the # relevant ethnic density score based on patient ethnicity was selected # and assigned to each patient. # Code generating an ethnic density score for each patient edclean <- ed %>% mutate(ethnicdensityscore = ifelse(ethnicitycleaned == "British (A)", WhiteBrit_EDPercent, ifelse(ethnicitycleaned == "African (N)", African_EDPercent, ifelse(ethnicitycleaned == "Irish (B)", WhiteIrish_EDPercent, ifelse(ethnicitycleaned == "Any other Asian background (L)", OtherAsian_EDPercent, ifelse(ethnicitycleaned == "Any other black background (P)", OtherBlack_EDPercent, ifelse(ethnicitycleaned == "Any other mixed background (G)", OtherMixed_EDPercent, ifelse(ethnicitycleaned == "Any other white background (C)", OtherWhite_EDPercent, ifelse(ethnicitycleaned == "Bangladeshi (K)", BritBangladeshi_EDPercent, ifelse(ethnicitycleaned == "Caribbean (M)", Caribbean_EDPercent, ifelse(ethnicitycleaned == "Chinese (R)", BritChinese_EDPercent, ifelse(ethnicitycleaned == "Indian (H)", BritIndian_EDPercent, ifelse(ethnicitycleaned == "Pakistani (J)", BritPakistani_EDPercent, ifelse(ethnicitycleaned == "White and Asian (F)", WhiteAsian_EDPercent, ifelse(ethnicitycleaned == "White and Black African (E)", WhiteBlackAfri_EDPercent, ifelse(ethnicitycleaned == "White and black Caribbean (D)", WhiteBlackCarib_EDPercent, " " )))))))))))))))) %>% mutate(ethnicdensityscore = as.numeric(ethnicdensityscore)) # save ed with new feature into new dataset "edclean" save(edclean, file = "Data_ED_new_features.Rdata", compress = TRUE) ``` ******* __Ethnicity variable (named "ethnicity")__ Some of the ethnic groups are too small in numbers, these groups will be aggregated while still maintaining their own-ethnic group ethnic density scores and their respective suicide numbers also decrease (data not shown), which make it difficult to analyse and could potentially bias estimates towards ethnic groups that have larger sizes. Grouping ethnic groups into larger ethnic categories (White, Other White, Irish, Black, Other Black, Caribbean, Asian and Mixed Race). ```r #Create broader groups of ethnicity (a new __"ethnicity"__ variable). edclean <- edclean %>% mutate(ethnicity = ifelse(ethnicitycleaned == "British (A)", "White", ifelse(ethnicitycleaned == "African (N)", "Black", ifelse(ethnicitycleaned == "Irish (B)", "Irish", ifelse(ethnicitycleaned == "Any other Asian background (L)", "Asian", ifelse(ethnicitycleaned == "Any other black background (P)", "Other Black", ifelse(ethnicitycleaned == "Any other mixed background (G)", "Mixed Race", ifelse(ethnicitycleaned == "Any other white background (C)", "Other White", ifelse(ethnicitycleaned == "Bangladeshi (K)", "Asian", ifelse(ethnicitycleaned == "Caribbean (M)", "Caribbean", ifelse(ethnicitycleaned == "Chinese (R)", "Asian", ifelse(ethnicitycleaned == "Indian (H)", "Asian", ifelse(ethnicitycleaned == "Pakistani (J)", "Asian", ifelse(ethnicitycleaned == "White and Asian (F)", "Mixed Race", ifelse(ethnicitycleaned == "White and Black African (E)", "Mixed Race", ifelse(ethnicitycleaned == "White and black Caribbean (D)", "Mixed Race", NA)))))))))))))))) # save new feature into new dataset "edclean" save(edclean, file = "Data_ED_new_features.Rdata", compress = TRUE) ``` ****** __Age variables (named "ageatdiagnosis", "ageatdeath" and "agegroups")__ The dataset only has pseudonymised date of birth variables and age can be generated from them using date of diagnosis. Summaries and counts provided below the code. ```r edclean <- edclean %>% #First format necessary date variables to make sure they are in date format mutate(dateofbirth = as.Date(DOB_Cleaned, format = "%d/%m/%y")) %>% mutate(diagnosisdate = as.Date(diagnosis_date, format = "%d/%m/%y")) %>% mutate(dateofdeath = as.Date(ons_date_of_death, format = "%d/%m/%y")) %>% #Then create age at diagnosis and age at Suicide using simple substractions mutate(ageatdiagnosis = year(diagnosisdate) - year(dateofbirth)) %>% mutate(ageatdeath = year(dateofdeath) - year(dateofbirth)) %>% #Then create an age category group mutate(agegroups = ifelse(ageatdiagnosis %in% 0:25, "< 25", ifelse(ageatdiagnosis %in% 26:40, "26-40", ifelse(ageatdiagnosis %in% 41:60, "41-60", ifelse(ageatdiagnosis %in% 61:104, "61-100", NA))))) #Checks # edclean[,c("diagnosis_date","diagnosisdate")] # they match # edclean[,c("ons_date_of_death","dateofdeath")] # they match # edclean[,c("ageatdiagnosis","agegroups")] # they match table(is.na(edclean$agegroups)) # 1 NA value # identifying and assigning NA agegroup value to x x <- which(is.na(edclean$agegroups)) # removing NA agegroup value from edclean dataset edclean <- edclean[-x, ] table(is.na(edclean$agegroups)) # no NA values # save new feature into new dataset "edclean" save(edclean, file = "Data_ED_new_features.Rdata", compress = TRUE) ``` ```r # summary(edclean$ageatdiagnosis) # Age at Diagnosis Summary # Min. 1st Qu. Median Mean 3rd Qu. Max. # 0.00 30.00 40.00 42.57 52.00 104.00 # table(edclean$agegroups) # Patient counts by age groups # < 25 26-40 41-60 61-100 # 7726 16075 16532 7196 # summary(edclean$ageatdeath) # Age at Death Summary # Min. 1st Qu. Median Mean 3rd Qu. Max. NA's # 10.00 52.00 69.00 66.49 82.00 107.00 42222 ``` ****** __Code for generating Borough variable (named "LSOA_4boroughs")__ ```r # tabulating patient LSOA code # these need to grouped into the main boroughs for this particular Trust # table(edclean$LSOA_NAME) # generating borough variable ("LSOA_4boroughs") edclean <- edclean %>% mutate (LSOA_4boroughs = ifelse(grepl("^Southw", edclean$LSOA_NAME) %in% TRUE, "SOUTHWARK", ifelse(grepl("^Croy", edclean$LSOA_NAME) %in% TRUE, "CROYDON", ifelse(grepl("^Lambe", edclean$LSOA_NAME) %in% TRUE, "LAMBETH", ifelse(grepl("^Lewish", edclean$LSOA_NAME) %in% TRUE, "LEWSIHAM", "OTHER"))))) x <- as.data.frame(table(edclean$LSOA_4boroughs)) kable(x) # |Var1 | Freq| # |:---------|-----:| # |CROYDON | 10419| # |LAMBETH | 9979| # |LEWSIHAM | 8135| # |OTHER | 9941| # |SOUTHWARK | 9104| table(is.na(edclean$LSOA_4boroughs)) # no NA values # save new feature into new dataset "edclean" save(edclean, file = "Data_ED_new_features.Rdata", compress = TRUE) ``` ****** __Generating Cause of Death Variable (named "DeathBy")__ - Create flag variables for individuals: i) who died by suicide ii) who died of other causes iii) who are not dead - Count summary provided below. ```r # Checking Suicide variable table(edclean$Suicide) #263 deaths by suicide table(is.na(edclean$Suicide)) #no NA values # Checking date of death variable #table(edclean$ons_date_of_death) table(is.na(edclean$ons_date_of_death)) # 42271 NA values; 5310 date of deaths # formatting date of death to date format. edclean <- edclean %>% mutate(ons_date_of_death = as.Date(ons_date_of_death, format = "%d/%m/%Y")) # generating DeathBy variable edclean <- edclean %>% mutate(DeathBy = ifelse(Suicide == 1, "Suicide", ifelse(year(ons_date_of_death) > 1901 & Suicide == 0, "OtherCause", NA))) # checking DeathBy variable table(is.na(edclean$DeathBy)) #there are still NAs, these are patients who are alive, these NA values need to be change to "Not Died" edclean$DeathBy[is.na(edclean$DeathBy)] <- "NotDied" table(edclean$DeathBy) table(is.na(edclean$DeathBy)) # dim(edclean) # 47529 38 # save new feature into new dataset "edclean" save(edclean, file = "Data_ED_new_features.Rdata", compress = TRUE) ``` ```r table(edclean$DeathBy) # NotDied OtherCause Suicide # 42222 5045 262 ``` ******** ## Data Dictionary ******** __Outcome__ |Variable Name| Definition/Categories | |:-------|:-------| | Suicide | binary variable for patient who died by suicide; 0 = Not died by suicdie, 1 = died by suicide | ****** __Exposure: Ethnic Density Score__ |Variable Name| Definition/Categories | |:-------|:-------| | ethnicdensityscore | Defined as the percentage composition of each ethnic group residing in a geographical area of a given size. | ****** __Demographics__ |Variable Name| Definition/Categories | |:-------|:-------| | Gender_Cleaned | Female, Male, Unknown | | Marital_Cleaned | Divorced / Separated / Widowed ; Married / Cohabiting ; Single ; Undisclosed | | DOB_Cleaned | Patient date of birth (dob) | | ethnicitycleaned | Patient ethnicity | | ethnicity | Aggregated ethnic groups: White, Other White, Black, Asian and Mixed | | imd_score | patient's area level deprivation score. The higher the score, the more deprived the area | | imd_quartiles | this is quartiles of deprivation score | | ageatdeath | age at death (any cause of death) | | ageatdiagnosis | age at primary diagnosis | | agegroups | age groups according to age at diagnosis | | LSOA_4boroughs | Boroughs; CROYDON; LAMBETH; LEWSIHAM; OTHER; SOUTHWARK | ****** __Death related variables__ |Variable Name| Definition/Categories | |:-------|:-------| | dateofdeath | date of death for patients who died | | DeathBy | cause of death | ****** __Diagnosis related variables__ |Variable Name| Definition/Categories | |:-------|:-------| | primary_diagnosis | first diagnosis closest to the start of the observation window | | diagnosisdate | date of primary diagnosis | | Schizophrenia_Diag | binary variable to indicate if the patient has had a diagnosis of Schizophrenia disorder at some point during the observation window | | SchizoAffective_Diag | binary variable to indicate if the patient has had a diagnosis of Schizoaffective disorder at some point during the observation window | | Depressive_Diag| binary variable to indicate if the patient has had a diagnosis of Depressive disorder (mild to severe) at some point during the observation window | | SubAbuse_Diag | binary variable to indicate if the patient has had a diagnosis of Substance Abuse disorder at some point during the observation window | | Manic_Diag | binary variable to indicate if the patient has had a diagnosis of Manic disorder at some point during the observation window | | Bipolar_Diag | binary variable to indicate if the patient has had a diagnosis of Bipolar disorder at some point during the observation window | ****** __Overall Ethnic Density in each known LSOA variable__ |Variable Name| Definition/Categories | |:-------|:-------| | LSOA11 | Each patients' area-level address code. This geographical code, covers an ares of ~1500 residents | | TotalResidentsInLSOA | The actual number of residents in the corresponding LSOA code | | WhiteBrit_EDPercent | The percentage ethnic density, or ethnic composition, of White British ethnic group in the corresponding LSOA code | | WhiteIrish_EDPercent | The percentage ethnic density, or ethnic composition, of Irish ethnic group in the corresponding LSOA code | | OtherWhite_EDPercent | The percentage ethnic density, or ethnic composition, of White British ethnic group in the corresponding LSOA code | | WhiteBlackCarib_EDPercent | The percentage ethnic density, or ethnic composition, of Mixed White and Black Caribbean ethnic group in the corresponding LSOA code | | WhiteBlackAfri_EDPercent | The percentage ethnic density, or ethnic composition, of Mixed White and Black African ethnic group in the corresponding LSOA code | | WhiteAsian_EDPercent | The percentage ethnic density, or ethnic composition, of Mixed White and Asian ethnic group in the corresponding LSOA code | | OtherMixed_EDPercent | The percentage ethnic density, or ethnic composition, of any other Mixed Race ethnic group in the corresponding LSOA code | | BritIndian_EDPercent | The percentage ethnic density, or ethnic composition, of the Indian ethnic group in the corresponding LSOA code | | BritPakistani_EDPercent | The percentage ethnic density, or ethnic composition, of the Pakistani ethnic group in the corresponding LSOA code | | BritBangladeshi_EDPercent | The percentage ethnic density, or ethnic composition, of the Bangladeshi ethnic group in the corresponding LSOA code | | BritChinese_EDPercent | The percentage ethnic density, or ethnic composition, of the Chinese ethnic group in the corresponding LSOA code | | OtherAsian_EDPercent | The percentage ethnic density, or ethnic composition, of any other Asian ethnic groups in the corresponding LSOA code | | African_EDPercent | The percentage ethnic density, or ethnic composition, of Black British or African ethnic group in the corresponding LSOA code | | Caribbean_EDPercent | The percentage ethnic density, or ethnic composition, of the Caribbean ethnic group in the corresponding LSOA code | | OtherBlack_EDPercent | The percentage ethnic density, or ethnic composition, of any other Black ethnic group in the corresponding LSOA code | ****** ## The Final Dataset ****** ```r # generating the final dataset edclean <- edclean %>% select(Gender_Cleaned, DOB_Cleaned, Marital_Cleaned, diagnosisdate, ageatdiagnosis, Schizophrenia_Diag, SchizoAffective_Diag,Depressive_Diag,SubAbuse_Diag, Manic_Diag,Bipolar_Diag,ethnicitycleaned,ethnicity, ethnicdensityscore,imd_score,dateofdeath,Suicide, ageatdeath,agegroups,LSOA_4boroughs,LSOA11,DeathBy, TotalResidentsInLSOA, WhiteBrit_EDPercent, WhiteIrish_EDPercent, OtherWhite_EDPercent, WhiteBlackCarib_EDPercent, WhiteBlackAfri_EDPercent, WhiteAsian_EDPercent, OtherMixed_EDPercent, BritIndian_EDPercent, BritPakistani_EDPercent, BritBangladeshi_EDPercent, BritChinese_EDPercent, OtherAsian_EDPercent, African_EDPercent, Caribbean_EDPercent, OtherBlack_EDPercent) # this is important before doing regression analysis (as is converting all the # other categorical variables into factors). edclean$Suicide <- as.factor(edclean$Suicide) # save new feature into new dataset "edclean" save(edclean, file = "Data_ED_new_features.Rdata", compress = TRUE) ``` ****** ```r sessionInfo() ``` ``` ## R version 3.3.0 (2016-05-03) ## Platform: x86_64-apple-darwin13.4.0 (64-bit) ## Running under: OS X 10.11.5 (El Capitan) ## ## locale: ## [1] en_GB.UTF-8/en_GB.UTF-8/en_GB.UTF-8/C/en_GB.UTF-8/en_GB.UTF-8 ## ## attached base packages: ## [1] grid stats graphics grDevices utils datasets methods ## [8] base ## ## other attached packages: ## [1] caret_6.0-68 lattice_0.20-33 Amelia_1.7.4 Rcpp_0.12.5 ## [5] knitr_1.13 gridExtra_2.2.1 GGally_1.0.1 gmodels_2.16.2 ## [9] ggplot2_2.1.0 dplyr_0.4.3 tidyr_0.4.1 lubridate_1.5.6 ## [13] foreign_0.8-66 ## ## loaded via a namespace (and not attached): ## [1] highr_0.6 nloptr_1.0.4 formatR_1.4 ## [4] plyr_1.8.3.9000 iterators_1.0.8 tools_3.3.0 ## [7] lme4_1.1-12 digest_0.6.9 evaluate_0.9 ## [10] gtable_0.2.0 nlme_3.1-128 mgcv_1.8-12 ## [13] Matrix_1.2-6 foreach_1.4.3 DBI_0.4-1 ## [16] yaml_2.1.13 parallel_3.3.0 SparseM_1.7 ## [19] stringr_1.0.0 MatrixModels_0.4-1 gtools_3.5.0 ## [22] stats4_3.3.0 nnet_7.3-12 reshape_0.8.5 ## [25] R6_2.1.2 rmarkdown_0.9.6 minqa_1.2.4 ## [28] gdata_2.17.0 car_2.1-2 reshape2_1.4.1 ## [31] magrittr_1.5 splines_3.3.0 scales_0.4.0 ## [34] codetools_0.2-14 htmltools_0.3.5 MASS_7.3-45 ## [37] pbkrtest_0.4-6 assertthat_0.1 colorspace_1.2-6 ## [40] quantreg_5.24 stringi_1.0-1 lazyeval_0.1.10 ## [43] munsell_0.4.3 ```
PHP
UTF-8
3,689
2.5625
3
[ "MIT" ]
permissive
<?php namespace App\Http\Controllers\Api; use Illuminate\Http\Request; use Spatie\Permission\Models\Role; use Spatie\Permission\Models\Permission; use App\Http\Resources\PermissionResource; use App\Http\Controllers\Controller; class PermissionController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index(Request $request) { if($request->has('per_page')){ $per_page = $request->per_page; } else { $per_page = config('general.items_per_page'); } return PermissionResource::collection(Permission::paginate($per_page)); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $request->validate([ 'name' => 'required|alpha_dash|unique:permissions,name', ]); $permission = Permission::create($request->all()); if($permission) { $message = __('general.permission.CREATE_SUCCESS'); } else { $message = __('general.permission.CREATE_FAILURE'); } return response()->json([ 'message' => $message, 'data' => new PermissionResource($permission) ], 200); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { $permission = Permission::find($id); return response()->json([ "data" => new PermissionResource($permission) ], 200); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $request->validate([ 'name' => 'required|alpha_dash|unique:permissions,name,' . $id ]); $permission = Permission::find($id); if($permission->update($request->all())) { $message = __('general.permission.UPDATE_SUCCESS'); } else { $message = __('general.permission.UPDATE_FAILURE'); } return response()->json([ "message" => $message, "data" => $permission ], 200); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $permission = Permission::find($id); if($permission->delete()) { $message = __('general.permission.DELETE_SUCCESS'); } else { $message = __('general.permission.DELETE_FAILURE'); } return response()->json([ "message" => $message ], 200); } /** * Assign permission to role. * * @param Request * * @return \Illuminate\Http\Response * */ public function assignment(Request $request) { $role = Role::find($request->role_id); $permission = Permission::find($request->permission_id); if($role->givePermissionTo($permission)) { $message = __('general.permission.ASSIGNMENT_SUCCESS'); } else { $message = __('general.permission.ASSIGNMENT_FAILURE'); } return response()->json([ "message" => $message ], 200); } }
Java
UTF-8
481
1.703125
2
[]
no_license
package com.mes.old.meta; // Generated 2017-5-22 1:25:24 by Hibernate Tools 5.2.1.Final /** * IvMonthcheckdetail generated by hbm2java */ public class IvMonthcheckdetail implements java.io.Serializable { private IvMonthcheckdetailId id; public IvMonthcheckdetail() { } public IvMonthcheckdetail(IvMonthcheckdetailId id) { this.id = id; } public IvMonthcheckdetailId getId() { return this.id; } public void setId(IvMonthcheckdetailId id) { this.id = id; } }
Java
UTF-8
6,304
3.5625
4
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package pl.edu.ur.polab4.wprowadzDane; import java.util.Scanner; /** * * @author MICHAL */ public class Tablica { Student tab1[] = new Student[5]; public void wypelnienie(){ for(int i = 0;i<5;i++){ Student student = new Student("", "", 0, "", 0); tab1[i] = student; } } public void menu(){ Scanner in = new Scanner(System.in); int menu = 1; while (menu !=0){ System.out.println("Wybierz akcje ktora chcesz wykonac: "); System.out.println("---------------------------------------------"); System.out.println("1. Wprowadz dane studentow"); System.out.println("2. Edycja danych studenta"); System.out.println("3. Usuniecie danych studenta"); System.out.println("4. Wyswietlanie danych jednego studenta"); System.out.println("5. Wyswietlanie danych wszystkich studentow"); System.out.println("6. Wyswietlanie danych kilku studentow"); System.out.println("0. Koniec"); System.out.println("---------------------------------------------"); menu = in.nextInt(); switch(menu){ case 1: wprowadzanie(); break; case 2: edycja(); break; case 3: usuwanie(); break; case 4: wyswietl1(); break; case 5: wyswietlWszystkich(); break; case 6: wyswietlZakres(); break; case 0: break; } } } private void wprowadzanie(){ Scanner inImie = new Scanner(System.in); Scanner inNazwisko = new Scanner(System.in); Scanner inSpecjalnosc = new Scanner(System.in); Scanner in = new Scanner(System.in); System.out.println("Wprowadzanie danych"); System.out.println("Podaj indeks pod ktorym chcesz wprowadzic dane:"); int id = in.nextInt(); System.out.println("Podaj imie: "); tab1[id].setImie(inImie.nextLine()); System.out.println("Podaj nazwisko: "); tab1[id].setNazwisko(inNazwisko.nextLine()); System.out.println("Podaj numer indeksu: "); tab1[id].setNr_indeksu(in.nextInt()); System.out.println("Podaj nazwe specjalnosci: "); tab1[id].setNazwa_specjalnosci(inSpecjalnosc.nextLine()); System.out.println("Podaj rok studiow"); tab1[id].setRok_studiow(in.nextInt()); } private void edycja(){ Scanner inImie = new Scanner(System.in); Scanner inNazwisko = new Scanner(System.in); Scanner inSpecjalnosc = new Scanner(System.in); Scanner in = new Scanner(System.in); System.out.println("Zmiana danych"); System.out.println("Podaj indeks pod ktorym chcesz zmienic dane"); int id = in.nextInt(); System.out.println("Podaj zmienione imie: "); tab1[id].setImie(inImie.nextLine()); System.out.println("Podaj zmienione nazwisko: "); tab1[id].setNazwisko(inNazwisko.nextLine()); System.out.println("Podaj zmieniony numer indeksu: "); tab1[id].setNr_indeksu(in.nextInt()); System.out.println("Podaj zmieniona nazwe specjalnosci: "); tab1[id].setNazwa_specjalnosci(inSpecjalnosc.nextLine()); System.out.println("Podaj zmieniony rok studiow"); tab1[id].setRok_studiow(in.nextInt()); } private void usuwanie(){ Scanner in = new Scanner(System.in); System.out.println("Usuwanie danych"); System.out.println("Podaj indeks pod ktorym chcesz usunac dane:"); int id = in.nextInt(); tab1[id].setImie(""); tab1[id].setNazwisko(""); tab1[id].setNr_indeksu(0); tab1[id].setNazwa_specjalnosci(""); tab1[id].setRok_studiow(0); } private void wyswietl1(){ Scanner in = new Scanner(System.in); System.out.println("Wyswietlanie danych jednego studenta"); System.out.println("Podaj indeks ktory chcesz wyswietlic:"); int id = in.nextInt(); System.out.println("Wybrane ID: " + id); System.out.println("Imie: " + tab1[id].getImie()); System.out.println("Nazwisko: " + tab1[id].getNazwisko()); System.out.println("Nr indeksu: " + tab1[id].getNr_indeksu()); System.out.println("Nazwa specjalnosci: " + tab1[id].getNazwa_specjalnosci()); System.out.println("Rok studiow: " + tab1[id].getRok_studiow()); System.out.println(); } private void wyswietlWszystkich(){ for(int i = 0; i < 5; i++){ System.out.println("Index: " + i); System.out.println("Imie: " + tab1[i].getImie()); System.out.println("Nazwisko: " + tab1[i].getNazwisko()); System.out.println("Nr indeksu: " + tab1[i].getNr_indeksu()); System.out.println("Nazwa specjalnosci: " + tab1[i].getNazwa_specjalnosci()); System.out.println("Rok studiow: " + tab1[i].getRok_studiow()); System.out.println(); } } private void wyswietlZakres(){ Scanner in = new Scanner(System.in); System.out.print(" Podaj poczatek zakresu: "); int indexP = in.nextInt(); System.out.print(" Podaj koniec zakresu: "); int indexK = in.nextInt(); for (int i = indexP; i<=indexK; i++){ System.out.println("Index: " + i + "\nImie: " + tab1[i].getImie() + "\nNazwisko: " + tab1[i].getNazwisko() + "\nNr indeksu: " + tab1[i].getNr_indeksu() + "\nNazwa specjalnosci: " + tab1[i].getNazwa_specjalnosci() + "\nRok studiow: " + tab1[i].getRok_studiow()); } } }
Python
UTF-8
537
2.96875
3
[]
no_license
def pdf_contains_image(cv): "Checks to see if a PDF contains an image." for pi in range(cv.numPages): pg = cv.getPage(pi) if '/XObject' in pg['/Resources']: xObject = pg['/Resources']['/XObject'].getObject() for obj in xObject: if xObject[obj]['/Subtype'] == '/Image': # If it's in portrait it's a headshot (our assumption) if xObject[obj]['/Height'] > xObject[obj]['/Width']: return True return False
Python
UTF-8
4,146
2.609375
3
[ "Apache-2.0" ]
permissive
"""Basic subscription tests: - create the subscription with a 60 minute expiry - get by ID - get by search - delete """ import datetime import re from ..infrastructure import default_scope from . import common from .common import SCOPE_READ @default_scope(SCOPE_READ) def test_sub_does_not_exist(session, sub1_uuid): resp = session.get('/subscriptions/{}'.format(sub1_uuid)) assert resp.status_code == 404 assert resp.json()['message'] == 'resource not found: {}'.format(sub1_uuid) @default_scope(SCOPE_READ) def test_create_sub(session, sub1_uuid): """ASTM Compliance Test: DSS0030_C_PUT_SUB.""" time_start = datetime.datetime.utcnow() time_end = time_start + datetime.timedelta(minutes=60) resp = session.put( '/subscriptions/{}'.format(sub1_uuid), json={ 'extents': { 'spatial_volume': { 'footprint': { 'vertices': common.VERTICES, }, 'altitude_lo': 20, 'altitude_hi': 400, }, 'time_start': time_start.strftime(common.DATE_FORMAT), 'time_end': time_end.strftime(common.DATE_FORMAT), }, 'callbacks': { 'identification_service_area_url': 'https://example.com/foo' }, }) assert resp.status_code == 200 data = resp.json() assert data['subscription']['id'] == sub1_uuid assert data['subscription']['notification_index'] == 0 assert data['subscription']['callbacks'] == { 'identification_service_area_url': 'https://example.com/foo' } assert data['subscription']['time_start'] == time_start.strftime( common.DATE_FORMAT) assert data['subscription']['time_end'] == time_end.strftime( common.DATE_FORMAT) assert re.match(r'[a-z0-9]{10,}$', data['subscription']['version']) assert 'service_areas' in data @default_scope(SCOPE_READ) def test_get_sub_by_id(session, sub1_uuid): """ASTM Compliance Test: DSS0030_E_GET_SUB_BY_ID.""" resp = session.get('/subscriptions/{}'.format(sub1_uuid)) assert resp.status_code == 200 data = resp.json() assert data['subscription']['id'] == sub1_uuid assert data['subscription']['notification_index'] == 0 assert data['subscription']['callbacks'] == { 'identification_service_area_url': 'https://example.com/foo' } @default_scope(SCOPE_READ) def test_get_sub_by_search(session, sub1_uuid): """ASTM Compliance Test: DSS0030_F_GET_SUBS_BY_AREA.""" resp = session.get('/subscriptions?area={}'.format(common.GEO_POLYGON_STRING)) assert resp.status_code == 200 assert sub1_uuid in [x['id'] for x in resp.json()['subscriptions']] @default_scope(SCOPE_READ) def test_get_sub_by_searching_huge_area(session, sub1_uuid): resp = session.get('/subscriptions?area={}'.format(common.HUGE_GEO_POLYGON_STRING)) assert resp.status_code == 413 @default_scope(SCOPE_READ) def test_delete_sub_empty_version(session, sub1_uuid): resp = session.delete('/subscriptions/{}/'.format(sub1_uuid)) assert resp.status_code == 400 @default_scope(SCOPE_READ) def test_delete_sub_wrong_version(session, sub1_uuid): resp = session.delete('/subscriptions/{}/fake_version'.format(sub1_uuid)) assert resp.status_code == 400 @default_scope(SCOPE_READ) def test_delete_sub(session, sub1_uuid): """ASTM Compliance Test: DSS0030_D_DELETE_SUB.""" # GET the sub first to find its version. resp = session.get('/subscriptions/{}'.format(sub1_uuid)) assert resp.status_code == 200 version = resp.json()['subscription']['version'] # Then delete it. resp = session.delete('/subscriptions/{}/{}'.format(sub1_uuid, version)) assert resp.status_code == 200 @default_scope(SCOPE_READ) def test_get_deleted_sub_by_id(session, sub1_uuid): resp = session.get('/subscriptions/{}'.format(sub1_uuid)) assert resp.status_code == 404 @default_scope(SCOPE_READ) def test_get_deleted_sub_by_search(session, sub1_uuid): resp = session.get('/subscriptions?area={}'.format(common.GEO_POLYGON_STRING)) assert resp.status_code == 200 assert sub1_uuid not in [x['id'] for x in resp.json()['subscriptions']]
Python
UTF-8
209
3.140625
3
[]
no_license
S=int(input()) #S=x1y2-x2y1 #S+x2y1=x1y2 #S+y1=10**9y2 (x1=10**9, x2=1) #S+y1が10**9の倍数になるようにy1を決める Y1=10**9-S%(10**9) if S%10**9 else 0 Y2=(S+Y1)//(10**9) print(10**9,Y1,1,Y2,0,0)
PHP
UTF-8
1,518
2.796875
3
[ "MIT" ]
permissive
<?php namespace Pucene\Component\QueryBuilder\Query\Specialized\MoreLikeThis; use Pucene\Component\QueryBuilder\Query\QueryInterface; class MoreLikeThisQuery implements QueryInterface { /** * @var array */ private $like; /** * @var string[] * * TODO default '_all' */ private $fields; /** * @var int */ private $maxQueryTerms = 25; /** * @var int */ private $minTermFreq = 2; /** * @var int */ private $minDocFreq = 5; public function __construct(array $like, array $fields = []) { $this->like = $like; $this->fields = $fields; } public function getLike(): array { return $this->like; } public function getFields(): array { return $this->fields; } public function getMaxQueryTerms(): int { return $this->maxQueryTerms; } public function setMaxQueryTerms(int $maxQueryTerms): self { $this->maxQueryTerms = $maxQueryTerms; return $this; } public function getMinTermFreq(): int { return $this->minTermFreq; } public function setMinTermFreq(int $minTermFreq): self { $this->minTermFreq = $minTermFreq; return $this; } public function getMinDocFreq(): int { return $this->minDocFreq; } public function setMinDocFreq(int $minDocFreq): self { $this->minDocFreq = $minDocFreq; return $this; } }
Java
UTF-8
823
2.296875
2
[]
no_license
package com.trj.jk.web.domain.entity; public class BuyCarInfoBean { private String title; private byte status; private byte isFill; private String statusStr; public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public byte getStatus() { return status; } public void setStatus(byte status) { this.status = status; } public byte getIsFill() { return isFill; } public void setIsFill(byte isFill) { this.isFill = isFill; } public String getStatusStr() { return statusStr; } public void setStatusStr(String statusStr) { this.statusStr = statusStr; } @Override public String toString() { return "BuyCarInfoBean [title=" + title + ", status=" + status + ", isFill=" + isFill + ", statusStr=" + statusStr + "]"; } }
TypeScript
UTF-8
1,059
2.515625
3
[ "MIT" ]
permissive
import {RedisService} from "../services/redis.service"; import {RedisClient} from "redis"; import {RedisConnectionTypes} from "../constants/redis-connection-types.constants"; import {RedisError} from "../exceptions/redis.exception"; import {EXCEPTIONS} from "../constants/exceptions.constant"; export class RedisModel { public instance: RedisClient; public type: RedisConnectionTypes; protected db: number; protected host: string; public get redis() { return this.instance; } constructor(db: number, type: RedisConnectionTypes = RedisConnectionTypes.QUERY, host: string = null) { this.db = db; this.host = host; this.type = type; this.instance = RedisService.builder(db + type, db, host); } subscribe(event: string) { if (this.type !== RedisConnectionTypes.SUB) throw new RedisError(EXCEPTIONS.WRONG_INSTANCE_TYPE_SUBSCRIBE.message, EXCEPTIONS.WRONG_INSTANCE_TYPE_SUBSCRIBE.code, RedisConnectionTypes[this.type]); this.redis.subscribe(event); } }
Java
UTF-8
2,986
2.6875
3
[]
no_license
package com.example.pgg.qboxdemo.me.weather.draw; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import java.util.ArrayList; /** * Created by pgg on 2018/5/10. */ public class CloudyDrawer extends BaseDrawer { final ArrayList<CircleHolder> holders = new ArrayList<>(); private Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); public CloudyDrawer(Context context, boolean isNight) { super(context, isNight); } @Override protected void setSize(int width, int height) { super.setSize(width, height); if (holders.size()==0){ holders.add(new CircleHolder(0.20f * width, -0.30f * width, 0.06f * width, 0.022f * width, 0.56f * width, 0.0015f, isNight ? 0x183c6b8c : 0x28ffffff)); holders.add(new CircleHolder(0.58f * width, -0.35f * width, -0.15f * width, 0.032f * width, 0.6f * width, 0.00125f, isNight ? 0x223c6b8c : 0x33ffffff)); holders.add(new CircleHolder(0.9f * width, -0.19f * width, 0.08f * width, -0.015f * width, 0.44f * width, 0.0025f, isNight ? 0x153c6b8c : 0x15ffffff)); } } @Override public boolean drawWeather(Canvas canvas, float alpha) { for (CircleHolder holder:holders){ holder.updateAndDraw(canvas,paint,alpha); } return true; } @Override protected int[] getSkyBackgroundGradient() { return isNight?SkyBackground.CLOUDY_N:SkyBackground.CLOUDY_D; } public static class CircleHolder{ private final float cx,cy,dx,dy,radius; private final int color; private boolean isGrowing=true; private float curpercent=0f; private final float percentSpeed; public CircleHolder(float cx,float cy,float dx,float dy,float radius,float percentSpeed,int color){ this.cx=cx; this.cy=cy; this.dx=dx; this.dy=dy; this.radius=radius; this.percentSpeed=percentSpeed; this.color=color; } public void updateAndDraw(Canvas canvas, Paint paint,float alpha){ float randomPercentSpeed=getRandom(percentSpeed*0.7f,percentSpeed*1.3f); if (isGrowing){ curpercent+=randomPercentSpeed; if (curpercent>1f){ curpercent=1f; isGrowing=false; } }else { curpercent-=randomPercentSpeed; if (curpercent<0f){ curpercent=0f; isGrowing=true; } } float curCX=cx+dx*curpercent; float curCY=cy+dy*curpercent;; int curColor=convertAlphaColor(alpha*(Color.alpha(color)/255f),color); paint.setColor(curColor); canvas.drawCircle(curCX,curCY,radius,paint); } } }
Markdown
UTF-8
2,808
2.84375
3
[ "MIT" ]
permissive
--- layout: post title: "Faster Algorithms for Large-scale Machine Learning using Simple Sampling Techniques" date: 2018-01-18 04:31:40 categories: arXiv_AI tags: arXiv_AI Tracking author: Vinod Kumar Chauhan, Kalpana Dahiya, Anuj Sharma mathjax: true --- * content {:toc} ##### Abstract Now a days, the major challenge in machine learning is the `Big~Data' challenge. The big data problems due to large number of data points or large number of features in each data point, or both, the training of models have become very slow. The training time has two major components: Time to access the data and time to process the data. In this paper, we have proposed one possible solution to handle the big data problems in machine learning. The focus is on reducing the training time through reducing data access time by proposing systematic sampling and cyclic/sequential sampling to select mini-batches from the dataset. To prove the effectiveness of proposed sampling techniques, we have used Empirical Risk Minimization, which is commonly used machine learning problem, for strongly convex and smooth case. The problem has been solved using SAG, SAGA, SVRG, SAAG-II and MBSGD (Mini-batched SGD), each using two step determination techniques, namely, constant step size and backtracking line search method. Theoretical results prove the same convergence for systematic sampling, cyclic sampling and the widely used random sampling technique, in expectation. Experimental results with bench marked datasets prove the efficacy of the proposed sampling techniques. ##### Abstract (translated by Google) 现在机器学习面临的主要挑战是“大数据”挑战。大数据问题由于数据点数量众多或每个数据点的特征数量大,或者两者兼而有之,模型的训练变得非常缓慢。培训时间有两个主要部分:访问数据的时间和处理数据的时间。在本文中,我们提出了一个可能的解决方案来处理机器学习中的大数据问题。重点在于通过提供系统采样和循环/连续采样来从数据集中选择小批量,通过减少数据访问时间来缩短培训时间。为了证明所提出的抽样技术的有效性,我们用经验风险最小化(这是常用的机器学习问题)作为强凸和平滑的情况。使用SAG,SAGA,SVRG,SAAG-II和MBSGD(小批量SGD)已经解决了这个问题,每个都使用两步测定技术,即恒定步长和回溯线搜索方法。理论结果证明,系统采样,循环采样和广泛使用的随机采样技术在期望方面具有相同的收敛性。用标准数据集进行的实验结果证明了所提出的抽样技术的有效性。 ##### URL [http://arxiv.org/abs/1801.05931](http://arxiv.org/abs/1801.05931) ##### PDF [http://arxiv.org/pdf/1801.05931](http://arxiv.org/pdf/1801.05931)
Java
UTF-8
5,263
2.84375
3
[]
no_license
package dbmsproj.service; import dbmsproj.entity.ReservationForm; import java.sql.*; import java.time.LocalDate; import java.util.ArrayList; import java.util.Calendar; import java.util.List; public class ReservationFormDAO { private PostgreSqlConnection postgreSqlConnection; public void saveCurrentReservation(LocalDate dateOfMade, int tenantNumber, int standNumber, double totalPrice) { postgreSqlConnection = PostgreSqlConnection.getInstance(); try (Connection conn = postgreSqlConnection.getConnection(); Statement stmt = conn.createStatement()) { String sql = "INSERT INTO reservation_form (date_of_made, tenantno, standno, total_price)" + " VALUES(?,?,?,?)"; PreparedStatement preparedStatement = conn.prepareStatement(sql); preparedStatement.setDate(1, Date.valueOf(dateOfMade)); preparedStatement.setInt(2, tenantNumber); preparedStatement.setInt(3, standNumber); preparedStatement.setInt(4, (int) totalPrice); int r = preparedStatement.executeUpdate(); System.out.println(r); } catch (Exception ex) { ex.printStackTrace(); } } public int getReservationNumberByTenantAndStandNumber(int tenantNumber, int standNumber, LocalDate date) { postgreSqlConnection = PostgreSqlConnection.getInstance(); int reservationNumber = 0; try (Connection conn = postgreSqlConnection.getConnection(); Statement stmt = conn.createStatement()) { String sql = "SELECT * FROM reservation_form WHERE tenantno=? AND standno=? AND date_of_made=?"; PreparedStatement ps = conn.prepareStatement(sql); ps.setInt(1, tenantNumber); ps.setInt(2, standNumber); ps.setDate(3, Date.valueOf(date)); ResultSet rs = ps.executeQuery(); while(rs.next()) { reservationNumber = rs.getInt(1); } } catch (Exception ex) { ex.printStackTrace(); } return reservationNumber; } public List<ReservationForm> getReservationFormsByTenantNumber(int tenantNumber) { postgreSqlConnection = PostgreSqlConnection.getInstance(); List<ReservationForm> reservations = new ArrayList<>(); try (Connection conn = postgreSqlConnection.getConnection(); Statement stmt = conn.createStatement()) { String sql = "SELECT * FROM reservation_form WHERE tenantno=?"; PreparedStatement preparedStatement = conn.prepareStatement(sql); preparedStatement.setInt(1, tenantNumber); ResultSet rs = preparedStatement.executeQuery(); while(rs.next()) { ReservationForm reservation = new ReservationForm(); reservation.setReservationNumber(rs.getInt("reservationno")); reservation.setDateOfMade(convertDateToLocalDate(rs.getDate("date_of_made"))); reservation.setTenantNumber(rs.getInt("tenantno")); reservation.setStandNumber(rs.getInt("standno")); reservation.setTotalPrice(rs.getDouble("total_price")); reservations.add(reservation); } } catch (Exception ex) { ex.printStackTrace(); } return reservations; } public boolean deleteByReservationNumber(int reservationNumber) { postgreSqlConnection = PostgreSqlConnection.getInstance(); try (Connection conn = postgreSqlConnection.getConnection(); Statement stmt = conn.createStatement()) { String sql = "DELETE FROM reservation_form WHERE reservationno=?"; PreparedStatement preparedStatement = conn.prepareStatement(sql); preparedStatement.setInt(1, reservationNumber); int i = preparedStatement.executeUpdate(); System.out.println(preparedStatement.getWarnings()); if (i != 1) return false; } catch (Exception ex) { ex.printStackTrace(); } return true; } public void updateDateOfMadeByReservationNumber(int reservationNumber, LocalDate newDateOfMade) { postgreSqlConnection = PostgreSqlConnection.getInstance(); try (Connection conn = postgreSqlConnection.getConnection(); Statement stmt = conn.createStatement()) { String sql = "UPDATE reservation_form SET date_of_made=? WHERE reservationno=?"; PreparedStatement ps = conn.prepareStatement(sql); ps.setDate(1, Date.valueOf(newDateOfMade)); ps.setInt(2, reservationNumber); ps.executeUpdate(); } catch (Exception ex) { ex.printStackTrace(); } } public LocalDate convertDateToLocalDate(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); LocalDate localDate = LocalDate.of( calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH) + 1, calendar.get(Calendar.DAY_OF_MONTH) ); return localDate; } }
Ruby
UTF-8
2,817
2.59375
3
[]
no_license
describe 'load_config' do before(:each) do @config_obj = load_config "spec/fixtures/correct_sample.ini" end it 'should return a ConfigObject that can be queried' do expect(Object.send(:load_config, "spec/fixtures/correct_sample.ini", [])).to be_a INI::ConfigObject end describe "should return an object with query capabilities with a correct file" do it "should return a config object with a hash" do expect(@config_obj.common).not_to eq(nil) expect(@config_obj.common.class).to eq(CustomConfigHash) expect(@config_obj.common.basic_size_limit).to eq(262_144_00) expect(@config_obj.ftp).not_to eq(nil) expect(@config_obj.http).not_to eq(nil) end it "should return symbols for keys in the hashes" do expect(@config_obj.common[:basic_size_limit]).to eq(262_144_00) end it "should return nil and not error out for queries that don't match any data" do expect(@config_obj.common.bar).to eq(nil) expect(@config_obj.hagrid).to eq(nil) end end describe "should properly handle overrides" do it "should use the override if passed in as a symbol or string" do override_config = load_config "spec/fixtures/correct_sample.ini", [:itscript, "production"] expect(override_config.common).not_to eq(nil) expect(override_config.common.path).to eq("/srv/tmp/itscript") expect(override_config.http.path).to eq("/srv/var/tmp/prod") end it "should use the last override defined in the file if multiple are passed in" do override_config_multiple = load_config "spec/fixtures/correct_sample.ini", ["ubuntu", :production] expect(override_config_multiple.ftp).not_to eq(nil) expect(override_config_multiple.ftp.path).to eq("/etc/var/uploads/ubuntu") end end describe "should properly return all boolean types" do it "should return a config object with correct boolean types" do bool_config = load_config "spec/fixtures/various_bools.ini" expect(bool_config.bools).not_to eq(nil) expect(bool_config.bools.yes).to eq(true) expect(bool_config.bools.no).to eq(false) expect(bool_config.bools.one).to eq(true) expect(bool_config.bools.zero).to eq(false) expect(bool_config.bools.false).to eq(false) expect(bool_config.bools.true).to eq(true) end end describe "should properly return all numeric types" do it "should return a config object with correct numeric types" do num_config = load_config "spec/fixtures/numeric.ini" expect(num_config.numeric).not_to eq(nil) expect(num_config.numeric.floater).to eq(1.23) expect(num_config.numeric.floater.class).to eq(Float) expect(num_config.numeric.intval).to eq(100) expect(num_config.numeric.intval.class).to eq(Fixnum) end end end
Markdown
UTF-8
1,252
2.84375
3
[ "Apache-2.0" ]
permissive
--- title: | 053 For us Jesus was baptiz’d. - Hymns for the Poor of the Flock metadata: description: | Hymns for the Poor of the Flock 053. For us Jesus was baptiz’d.. F ob us Jesus was b a p tiz ’d For us He was ag on iz’d ; Mighty vengeance, like a flood, Overwhelm’d the Lamb of God. keywords: | Hymns for the Poor of the Flock, adventhymnals, advent hymnals, For us Jesus was baptiz’d., F ob us Jesus was b a p tiz ’d , author: Brian Onang'o --- #### Advent Hymnals ## 053. For us Jesus was baptiz’d. #### Hymns for the Poor of the Flock ```txt 1. F ob us Jesus was b a p tiz ’d For us He was ag on iz’d ; Mighty vengeance, like a flood, Overwhelm’d the Lamb of God. 2. Come, ye saints, with wonder view What the Lord has done for you; View the mighty waters roll, Breaking in upon His soul. 3. View the swelling floods of wrath Sinking Jesus into death; Grief Him cover’d like a grave, When He died your souls to save. 4. This was baptism indeed; Well might mountains shake with dread; Baptism serves in type to show, What our Lord did undergo.5 Sons of God, lift up your eyes; See the martyr’d Saviour rise; He has conquer’d death and hell; With Him you shall ever dwell. ```
Python
UTF-8
2,564
3.3125
3
[]
no_license
import nmap from pprint import pprint while True: print("""\nSelect the option from below List.\n 1 - Device Scan 2 - Network Scan 0 - Close Application""") inp = input("\nEnter your choice here: ") if inp == "1": scanner = nmap.PortScanner() # Target contains the ip address target = input("\nEnter the IP address of the target: ") # Scanning and storing result in raw_data = scanner.scan(target, '1-1024', '-v -sS -sV -O -A -e eth0') #Extracting usefull data out of raw data print("\n ****************************** {} ******************************".format(target)) #Device Specific information #Displaying MAC address try: mac_addr = raw_data['scan'][target]['addresses']['mac'] print("\n====>>>> MAC address: {}".format(mac_addr)) except KeyError: pass #Displaying Operating system operating_system = raw_data['scan'][target]['osmatch'][0]['name'] print("====>>>> Operating system: {}".format(operating_system)) #Displaying Device uptime uptime = raw_data['scan'][target]['uptime']['lastboot'] print("====>>>> Device uptime: {}".format(uptime)) #Ports Information print("\n\n******PORTS******\n") for port in list(raw_data['scan'][target]['tcp'].items()): print("====>>>> {} | {} | {}".format(port[0], port[1]['name'], port[1]['state'])) #More information print("\n\n****** More Information ******\n") #NMAP command print("====>>>> NMAP command: {}".format(raw_data['nmap']['command_line'])) #NMAP version version = str(scanner.nmap_version()[0]) + "." + str(scanner.nmap_version()[1]) print("====>>>> NMAP version: {}".format(version)) #Time elapsed print("====>>>> Time elapsed: {}".format(raw_data['nmap']['scanstats']['elapsed'] + "seconds")) elif inp == "2": scanner = nmap.PortScanner() print("\n Scanning.....") #Scanning the device raw_data = scanner.scan(ports = '1-1024', arguments = '-sS -e eth0 -iL /home/Desktop/ip.txt') for device in raw_data['scan']: print("\nPorts open on {}:".format(device)) for port in raw_data['scan'][device]['tcp'].items(): if port[1]['state'] == 'open': print("====>>>>" + str(port[0]) + "|" + port[1]['name']) continue elif inp == "0": print('\nTerminating....\n') break else: print("\nInvalid input\n") continue
Markdown
UTF-8
900
2.734375
3
[ "MIT" ]
permissive
--- layout: post title: Jekyll + Github Pages 搭建静态博客 - 评论篇 categories: [blog] description: some word here keywords: blog, jekyll, gitment music_id: -1 --- # [Gitment](https://github.com/imsun/gitment) 国人开发的利用 Github issue 功能充当博客系统的评论区,相当有才。 ## 新建一个仓库充当评论区 ## 为你的博客开启 OAuth application ## 使用方法 [集成方法请看这里Gitment博客](https://imsun.net/posts/gitment-introduction/) 在我上一篇博客 [Jekyll + Github Pages 搭建静态博客 - 初始篇](http://smily.space/2017/06/24/use-github-pages-to-set-up-blog/)中,我所使用的主题,原作者已集成了Gitment,直接在配置文件中配置即可。(当伸手党真是太好了:smile:) [48 个你需要知道的 Jekyll 使用技巧](https://crispgm.com/page/48-tips-for-jekyll-you-should-know.html) kk
Python
UTF-8
355
2.59375
3
[]
no_license
from PIL import Image import pyautogui import pytesseract def pega_localizacao(): x,y,w,h = pyautogui.locateOnScreen(r'data\images\teste.png') return x,y,w,h #print( pytesseract.image_to_string(Image.open(r'data\images\1.png')))# Extraindo o texto da imagem '''x,y,w,h = pyautogui.locateOnScreen(r'data\images\teste.png') print(x,y,w,h)'''
Java
UTF-8
4,813
2.3125
2
[]
no_license
package gal.san.clemente.tarefa_4_orm.view.clientes; import gal.san.clemente.tarefa_4_orm.model.Cliente; public class DetalleClientePanel extends javax.swing.JPanel { private Cliente cliente; private boolean editable; public Cliente getCliente() { return cliente; } public void setCliente(Cliente cliente) { this.cliente = cliente; } public boolean isEditable() { return editable; } //método controlar la edicción de datos public void setEditable(boolean editable) { this.editable = editable; nomeCliente.setEditable(editable); apelidosCliente.setEditable(editable); emailCliente.setEditable(editable); } //método cargar datos public void loadData() { if(cliente != null) { nomeCliente.setText(cliente.getNome()); apelidosCliente.setText(cliente.getApelidos()); emailCliente.setText(cliente.getEmail()); } else { nomeCliente.setText(""); apelidosCliente.setText(""); emailCliente.setText(""); } nomeCliente.requestFocus(); } //método guardar datos public void saveData() { if(cliente == null) { cliente = new Cliente(); } cliente.setNome(nomeCliente.getText()); cliente.setApelidos(apelidosCliente.getText()); cliente.setEmail(emailCliente.getText()); } public DetalleClientePanel() { initComponents(); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); nomeCliente = new javax.swing.JTextField(); apelidosCliente = new javax.swing.JTextField(); emailCliente = new javax.swing.JTextField(); jLabel1.setText("Nome Cliente"); jLabel2.setText("Apelidos Cliente"); jLabel3.setText("Email Cliente"); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this); this.setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addComponent(jLabel2) .addComponent(jLabel3)) .addGap(36, 36, 36) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(nomeCliente) .addComponent(apelidosCliente) .addComponent(emailCliente, javax.swing.GroupLayout.DEFAULT_SIZE, 210, Short.MAX_VALUE)) .addContainerGap(31, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(nomeCliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(apelidosCliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(16, 16, 16) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(emailCliente, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JTextField apelidosCliente; private javax.swing.JTextField emailCliente; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JTextField nomeCliente; // End of variables declaration//GEN-END:variables }
C#
UTF-8
12,970
2.859375
3
[ "LicenseRef-scancode-unknown-license-reference", "ECL-2.0", "Apache-2.0", "LicenseRef-scancode-unknown" ]
permissive
/// <copyright file="HalfedgeGraph.Vertex.cs" company="Eötvös Loránd University (ELTE)"> /// Copyright (c) 2011-2022 Roberto Giachetta. Licensed under the /// Educational Community 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://opensource.org/licenses/ECL-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. /// </copyright> /// <author>Máté Cserép</author> using System; using System.Collections.Generic; using System.Linq; namespace ELTE.AEGIS.Topology { /// <summary> /// Represents a halfedge graph data structure that stores topology. /// </summary> public partial class HalfedgeGraph { /// <summary> /// Represents a vertex of the topology graph. /// </summary> private class Vertex : IVertex { #region Public properties /// <summary> /// A halfedge that originates from the vertex. /// </summary> public Halfedge Halfedge { get; set; } /// <summary> /// The graph the vertex belongs to. /// </summary> public HalfedgeGraph Graph { get; set; } /// <summary> /// The index of this face in the internal vertex list of the graph. /// </summary> public Int32 Index { get; set; } #endregion #region Public iterators /// <summary> /// An iterator for the halfedges originating from the vertex. /// </summary> public IEnumerable<Halfedge> Halfedges { get { Halfedge halfedge = Halfedge; if (halfedge == null) yield break; do { yield return halfedge; halfedge = halfedge.Opposite.Next; } while (halfedge != Halfedge); } } /// <summary> /// An iterator for the vertices in the one ring neighborhood. /// </summary> public IEnumerable<Vertex> Vertices { get { return Halfedges.Select(h => h.ToVertex); } } /// <summary> /// An iterator for edges connected to the vertex. /// </summary> public IEnumerable<Edge> Edges { get { return Halfedges.Select(h => h.Edge); } } /// <summary> /// An iterator for the faces bounding with the vertex. /// </summary> public IEnumerable<Face> Faces { get { return Halfedges.Where(h => h.Face != null).Select(h => h.Face); } } #endregion #region Constructors /// <summary> /// Initializes a new instance of the <see cref="Vertex"/> class. /// </summary> /// <param name="position">The position of the vertex.</param> public Vertex(Coordinate position) { Position = position; Identifiers = new HashSet<Int32>(); } /// <summary> /// Initializes a new instance of the <see cref="Vertex"/> class. /// </summary> /// <param name="position">The position.</param> /// <param name="identifiers">The identifiers of the vertex.</param> public Vertex(Coordinate position, ISet<Int32> identifiers) { Position = position; Identifiers = new HashSet<Int32>(identifiers); } #endregion #region Public methods /// <summary> /// Searches for a halfedge pointing to a vertex from this vertex. /// </summary> /// <param name="vertex">A vertex pointed to by the halfedge to search for.</param> /// <returns>The halfedge from this vertex to the specified vertex. If none exists, returns null.</returns> public Halfedge FindHalfedgeTo(IVertex vertex) { return Halfedges.FirstOrDefault(h => h.ToVertex == vertex); } /// <summary> /// Searches for the halfedge pointing to the specified face from this vertex. /// </summary> /// <param name="face">The face the halfedge to find points to.</param> /// <returns>The halfedge if it is found, otherwise null.</returns> public Halfedge FindHalfedgeTo(IFace face) { return Halfedges.FirstOrDefault(h => h.Face == face); } /// <summary> /// Searches for the edge associated with the specified vertex. /// </summary> /// <param name="vertex">A vertex sharing an edge with this vertex.</param> /// <returns>The edge if it is found, otherwise null.</returns> public Edge FindEdgeTo(IVertex vertex) { return Halfedges.Where(h => h.ToVertex == vertex).Select(h => h.Edge).FirstOrDefault(); } /// <summary> /// Searches for an indexed halfedge by iterating. /// </summary> /// <param name="index">The index of the halfedge to return.</param> /// <exception cref="ArgumentOutOfRangeException">Thrown when <paramref name="index"/> is negative or too large.</exception> /// <returns>The specified halfedge.</returns> public Halfedge GetHalfedge(Int32 index) { if (index < 0) throw new ArgumentOutOfRangeException("index", index, "The given index cannot be negative."); try { return Halfedges.Skip(index).First(); } catch (InvalidOperationException) { throw new ArgumentOutOfRangeException("index", index, "The given index is too large."); } } /// <summary> /// Searches for an indexed vertex by iterating. /// </summary> /// <param name="index">The index of the vertex to return.</param> /// <exception cref="ArgumentOutOfRangeException">Thrown when <paramref name="index"/> is negative or too large.</exception> /// <returns>The specified vertex.</returns> public Vertex GetVertex(Int32 index) { if (index < 0) throw new ArgumentOutOfRangeException("index", index, "The given index cannot be negative."); try { return Vertices.Skip(index).First(); } catch (InvalidOperationException) { throw new ArgumentOutOfRangeException("index", index, "The given index is too large."); } } /// <summary> /// Searches for an indexed edge by iterating. /// </summary> /// <param name="index">The index of the edge to return.</param> /// <exception cref="ArgumentOutOfRangeException">Thrown when <paramref name="index"/> is negative or too large.</exception> /// <returns>The specified edge.</returns> public Edge GetEdge(Int32 index) { if (index < 0) throw new ArgumentOutOfRangeException("index", index, "The given index cannot be negative."); try { return Edges.Skip(index).First(); } catch (InvalidOperationException) { throw new ArgumentOutOfRangeException("index", index, "The given index is too large."); } } /// <summary> /// Searches for an indexed face by iterating. /// </summary> /// <param name="index">The index of the face to return.</param> /// <exception cref="ArgumentOutOfRangeException">Thrown when <paramref name="index"/> is negative or too large.</exception> /// <returns>The specified face.</returns> public Face GetFace(Int32 index) { if (index < 0) throw new ArgumentOutOfRangeException("index", index, "The given index cannot be negative."); try { return Faces.Skip(index).First(); } catch (InvalidOperationException) { throw new ArgumentOutOfRangeException("index", index, "The given index is too large."); } } #endregion #region IVertex properties /// <summary> /// Gets or sets the identifiers of the vertex. /// </summary> public ISet<Int32> Identifiers { get; set; } /// <summary> /// Gets or sets the position of the vertex. /// </summary> public Coordinate Position { get; set; } /// <summary> /// Checks whether the vertex is on the boundary of the graph. /// </summary> public Boolean OnBoundary { get { if (Halfedge == null) return true; // Search adjacent faces for any that are null return Edges.Any(e => e.OnBoundary); } } #endregion #region IVertex properties (explicit) /// <summary> /// A halfedge that originates from the vertex. /// </summary> IHalfedge IVertex.Halfedge { get { return Halfedge; } } /// <summary> /// The graph the vertex belongs to. /// </summary> IHalfedgeGraph IVertex.Graph { get { return Graph; } } /// <summary> /// An iterator for the halfedges originating from the vertex. /// </summary> IEnumerable<IHalfedge> IVertex.Halfedges { get { return Halfedges; } } /// <summary> /// An iterator for the vertices in the one ring neighborhood. /// </summary> IEnumerable<IVertex> IVertex.Vertices { get { return Vertices; } } /// <summary> /// An iterator for edges connected to the vertex. /// </summary> IEnumerable<IEdge> IVertex.Edges { get { return Edges; } } /// <summary> /// An iterator for the faces bounding with the vertex. /// </summary> IEnumerable<IFace> IVertex.Faces { get { return Faces; } } /// <summary> /// Searches for a halfedge pointing to a vertex from this vertex. /// </summary> /// <param name="vertex">A vertex pointed to by the halfedge to search for.</param> /// <returns>The halfedge from this vertex to the specified vertex. If none exists, returns null.</returns> IHalfedge IVertex.FindHalfedgeTo(IVertex vertex) { return FindHalfedgeTo(vertex); } /// <summary> /// Searches for the halfedge pointing to the specified face from this vertex. /// </summary> /// <param name="face">The face the halfedge to find points to.</param> /// <returns>The halfedge if it is found, otherwise null.</returns> IHalfedge IVertex.FindHalfedgeTo(IFace face) { return FindHalfedgeTo(face); } /// <summary> /// Searches for the edge associated with the specified vertex. /// </summary> /// <param name="vertex">A vertex sharing an edge with this vertex.</param> /// <returns>The edge if it is found, otherwise null.</returns> IEdge IVertex.FindEdgeTo(IVertex vertex) { return FindEdgeTo(vertex); } #endregion } } }
Ruby
UTF-8
1,119
2.578125
3
[]
no_license
#!/usr/bin/env ruby # -*- ruby encoding: utf-8 -*- require 'tinkerforge/ip_connection' require 'tinkerforge/bricklet_nfc' include Tinkerforge HOST = 'localhost' PORT = 4223 UID = 'XYZ' # Change XYZ to the UID of your NFC Bricklet ipcon = IPConnection.new # Create IP connection nfc = BrickletNFC.new UID, ipcon # Create device object ipcon.connect HOST, PORT # Connect to brickd # Don't use device before ipcon is connected # Register reader state changed callback nfc.register_callback(BrickletNFC::CALLBACK_READER_STATE_CHANGED) do |state, idle| if state == BrickletNFC::READER_STATE_IDLE nfc.reader_request_tag_id elsif state == BrickletNFC::READER_STATE_REQUEST_TAG_ID_READY tag_id = Array.new ret = nfc.reader_get_tag_id ret[1].each do |v| tag_id.push "0x%X" % v end puts ret.class puts "Found tag of type #{ret[0]} with ID [#{tag_id.join(" ")}]" elsif state == BrickletNFC::READER_STATE_REQUEST_TAG_ID_ERROR puts 'Request tag ID error' end end # Enable reader mode nfc.set_mode BrickletNFC::MODE_READER puts 'Press key to exit' $stdin.gets ipcon.disconnect
Java
UTF-8
3,865
2.421875
2
[]
no_license
/** * Sample Skeleton for 'DecryptScreen.fxml' Controller Class */ package com.nt.cryptotool.GUIFiles; import java.io.File; import java.net.URL; import java.util.ResourceBundle; import com.nt.cryptotool.miscobjects.Task; import com.nt.cryptotool.objects.Key; import com.nt.cryptotool.objects.TargetFile; import com.nt.cryptotool.utils.Decrypter; import com.nt.cryptotool.utils.Encrypter; import javafx.event.ActionEvent; import javafx.event.EventHandler; import javafx.fxml.FXML; import javafx.scene.control.Button; import javafx.scene.control.Label; import javafx.scene.control.TextField; import javafx.scene.layout.BorderPane; import javafx.stage.FileChooser; public class DecryptScreenController { private File keyfile,targetFile; @FXML // ResourceBundle that was given to the FXMLLoader private ResourceBundle resources; @FXML // URL location of the FXML file that was given to the FXMLLoader private URL location; @FXML // fx:id="rootPane" private BorderPane rootPane; // Value injected by FXMLLoader @FXML // fx:id="decryptButton" private Button decryptButton; // Value injected by FXMLLoader @FXML // fx:id="decryptTitleText" private Label decryptTitleText; // Value injected by FXMLLoader @FXML // fx:id="selectKeyFileButton" private Button selectKeyFileButton; // Value injected by FXMLLoader @FXML // fx:id="selectTargetFileButton" private Button selectTargetFileButton; // Value injected by FXMLLoader @FXML // fx:id="passwordField" private TextField passwordField; // Value injected by FXMLLoader @FXML // This method is called by the FXMLLoader when initialization is complete void initialize() { assert rootPane != null : "fx:id=\"rootPane\" was not injected: check your FXML file 'DecryptScreen.fxml'."; assert decryptButton != null : "fx:id=\"decryptButton\" was not injected: check your FXML file 'DecryptScreen.fxml'."; assert decryptTitleText != null : "fx:id=\"decryptTitleText\" was not injected: check your FXML file 'DecryptScreen.fxml'."; assert selectKeyFileButton != null : "fx:id=\"selectKeyFileButton\" was not injected: check your FXML file 'DecryptScreen.fxml'."; assert selectTargetFileButton != null : "fx:id=\"selectTargetFileButton\" was not injected: check your FXML file 'DecryptScreen.fxml'."; assert passwordField != null : "fx:id=\"passwordField\" was not injected: check your FXML file 'DecryptScreen.fxml'."; selectKeyFileButton.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Choose Keyfile"); keyfile = fileChooser.showOpenDialog(rootPane.getScene().getWindow()); } }); selectTargetFileButton.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { FileChooser fileChooser = new FileChooser(); fileChooser.setTitle("Choose Target File"); targetFile = fileChooser.showOpenDialog(rootPane.getScene().getWindow()); } }); decryptButton.setOnAction(new EventHandler<ActionEvent>() { @Override public void handle(ActionEvent event) { try { TargetFile targetFile1 = new TargetFile(targetFile.getAbsolutePath(), Task.Decrypt); Key theKey = new Key(keyfile,passwordField.getText().trim()); Decrypter decrypter = new Decrypter(targetFile1,theKey); decrypter.decryptFile(); } catch (Exception e) { e.printStackTrace(); } } }); } }
C++
UTF-8
1,426
2.703125
3
[]
no_license
#include <iostream> #include "../../shared/PNG.h" #include <time.h> #include <vector> using namespace std; int main(int argc, char* argv[]){ if(argc < 2){ cout << "Not enough arguments." << endl; return 0; } srand(time(0)); int swp = 0; int swpc = 0; vector<int> memory; Image* scrmbl = readPng(argv[1]); for(int j=0; j<scrmbl->height; j++){ swp = j; if(argc >= 2 && argc != 3){ swp = rand()%scrmbl->height; } for(int k=0; k<scrmbl->width*4; k=k+4){ if(argc < 3){ swpc = k; }else{ if(j == 0){ swpc = (rand()%scrmbl->width)*4; memory.push_back(swpc); }else{ swpc = memory[k/4]; } } int tmp = scrmbl->data[k+j*scrmbl->width*4]; scrmbl->data[k+j*scrmbl->width*4] = scrmbl->data[swpc+swp*scrmbl->width*4]; scrmbl->data[swpc+swp*scrmbl->width*4] = tmp; tmp = scrmbl->data[k+j*scrmbl->width*4+1]; scrmbl->data[k+j*scrmbl->width*4+1] = scrmbl->data[swpc+swp*scrmbl->width*4+1]; scrmbl->data[swpc+swp*scrmbl->width*4+1] = tmp; tmp = scrmbl->data[k+j*scrmbl->width*4+2]; scrmbl->data[k+j*scrmbl->width*4+2] = scrmbl->data[swpc+swp*scrmbl->width*4+2]; scrmbl->data[swpc+swp*scrmbl->width*4+2] = tmp; tmp = scrmbl->data[k+j*scrmbl->width*4+3]; scrmbl->data[k+j*scrmbl->width*4+3] = scrmbl->data[swpc+swp*scrmbl->width*4+3]; scrmbl->data[swpc+swp*scrmbl->width*4+3] = tmp; } } writePng("scramble.png",scrmbl); return 0; }
Markdown
UTF-8
6,680
2.6875
3
[]
no_license
# 任务分解 ## 系统总体架构 ![architecture](images/architecture.png) ### 业务组件 #### 产品管理服务 fund-service 产品管理服务提供系统中各类基础信息的管理。 需要完成的工作: * 各类基础信息数据的管理与查询 #### 投资服务 invest-service 投资服务主要用于管理投资指令的信息。 投资服务包含一系列具体的投资服务实现,它们以子模块的形式存在。投资服务的接口,需要派发到各个子模块中做具体实现。不同的子模块对于同一个接口的实现可能是不同的。 需要完成的工作: * 总体接口实现: * 子模块的管理和指令派发。 * 各子模块的接口实现: * 指令草稿的管理 * 提交、修改、撤销指令 * 设置指令下达原因/备注/紧急程度 * 查询指令 * 委托分配计划管理 * 风险试算 #### 交易服务 trade-service 交易服务主要用于管理委托。 交易服务包含一系列具体的交易服务实现,它们以子模块的形式存在。交易服务的接口,针对具体的交易服务,需要派发到各个子模块中做具体实现。不同的子模块对于同一个接口的实现可能是不同的。 需要完成的工作: * 总体接口实现: * 子模块的管理和指令派发。 * 查询指定投资服务对应的可用交易服务 * 各子模块的接口实现: * 返回指定投资指令对应的委托记录 * 发起委托请求 * 发起撤单请求 * 返回交易参数 * 计算相关指标 * 返回指定交易服务的交易日/交易日历信息 * 查询指定服务相关指标信息(此接口不对外公开) * 盘后清算 #### 资金持仓服务 inventory-service 资金持仓服务主要用于资金和持仓的计算。 资金和持仓在一次计算中需要事务性处理,同时成功或同时失败。为简化处理,将它们放在一个服务中。 资金持仓服务包含一系列具体的资金服务实现和持仓服务实现。资金持仓服务的接口,针对具体的资金或持仓服务,需要派发到各个子模块中做具体实现。不同的子模块对于同一个接口的实现可能是不同的。 需要完成的工作: * 总体接口实现: - 子模块的管理和指令派发。 - 查询指定投资服务对应的可用资金与持仓服务 * 各子模块的接口实现: - 资金转帐处理 - 返回资金参数 - 计算相关指标 - 返回指定服务的相关指标信息 - 盘后清算 #### 事务服务 routine-service 事务服务根据不同的类型有很大的差别。需要逐个单独设计规划。 待定。 #### 风控服务 risk-service 主要用于风控。 由投资服务触发启动。风控服务启动后向其他服务请求相关指标并进行风险判断。判断完成后向投资服务及前台推送风控结果,同时将风控结果保存备查。 需要完成的工作: * 实现启动、停止风控接口 * 实现查询风控结果的接口 * 实现风控Lua脚本执行环境 * 实现风控Lua脚本的上传及管理 * 调用其他组件的接口获得相关指标 * 向前台风控结果 #### 行情服务 marketdata-service 行情服务分成公共行情服务和系统内行情服务两个部分。公共行情服务用于将行情源数据转换成系统内部格式,并向系统内行情服务提供订阅、推送和查询接口。 系统内行情服务接受系统内其他组件的订阅请求并将需要的行情、板块等数据发送给它们。 需要完成的工作: * 公共行情服务: * 跟行情源(东财行情)的对接 * 实现订阅、推送、查询接口 * 身份认证 * 传输数据的压缩和加密 * 系统内行情服务: * 跟公共行情服务的连接 * 对系统内组件提供订阅和查询接口 #### 报盘服务 offer-service 报盘服务提供向柜台系统的交易通道。用于收取成交回报信息及发送委托。 报盘服务根据柜台系统的不同,可能会有不同的实现。各实现之间是独立的。 需要完成的工作: * 跟柜台系统的对接 * 向系统推送成交回报 * 实现委托报单的接口 #### 认证授权服务 security-service 认证授权服务提供系统安全所需的身份认证及授权。该服务给出对应的授权信息。具体对于授权的使用,由其他各服务自身完成。 需要完成的工作: * 用户安全信息与授权信息的管理。 * 身份验证。 * 权限信息的查询与使用 #### 时序服务 sequence-service 时序服务提供时间及序列相关的信息。目前它提供指标计算所需的序列号信息,以及清算所需的定时触发信号。 #### 网页界面 web-ui web ui提供web前端界面展现。由web网关和前端两个部分组成。 ##### web网关 web-gateway web网关(web-gateway)用于向前端提供统一地址的API转发或重组,同时托管前端的静态资源。web网关还需要负责前端数据的推送。 ##### web前台 web-frontend 前端(web-frontend)由html、js和CSS组成,提供用户交互界面。前端的数据都向web-gateway请求,由web-gateway根据需要向后台组件转发或进行数据重组。 需要完成的工作: * 前端的界面设计、功能: * 用户登录 * 资管公司 * 基金产品 * 投资指令 * …… * web网关对后台组件接口的转发 * web网关自有接口的实现 * web网关推送功能的实现 #### 移动端界面 mobile-ui 移动客户端和网页界面是同等地位的两个组件,具体内容待今后补充。 ##### 移动端网关 mobile-gateway ##### android客户端 android-front ##### ios客户端 ios-front ### 基础设施 #### 系统编排工具 系统编排工具处理全系统所有组件的运行、依赖、扩展、健康检查等功能。需要考虑集中管理多客户系统的情况,以及客户服务器资源有限的情况。 #### 持续集成工具 持续集成工具负责处理开发时代码管理、编译、测试、发布、部署等一系列工作流程的自动化和标准化。需要完成工具的部署、流程设计及流程实现。 #### 日志、监控、度量、分布式调用跟踪工具 这些工具负责监控系统运行时状况并在出问题时帮助排查。需要完成工具的部署。需要考虑集成管理多客户系统的情况。 ### 框架 #### 指标计算 指标计算框架参考并基于Kafka streams框架实现,提供了流式计算指标的能力。目前已经实现了基本的计算功能。未来要完善该框架在高可用性方面的功能。
Swift
UTF-8
410
3.28125
3
[]
no_license
// // Place.swift // KarrotHome // // Created by 이재은 on 2021/07/21. // import Foundation enum Place: String { /// 홍제동 case Hongje /// 수내1동 case Sunae1 } extension Place { /// 동네 일반 이름 var name: String { switch self { case .Hongje: return "홍제동" case .Sunae1: return "수내1동" } } }
PHP
UTF-8
444
2.9375
3
[]
no_license
<?php declare(strict_types=1); namespace App\Entity; use DateInterval; class SummableDateInterval extends DateInterval { public function add(DateInterval $interval) { foreach (str_split('ymdhis') as $prop) { $this->$prop += $interval->$prop; } $this->i += (int)($this->s / 60); $this->s = $this->s % 60; $this->h += (int)($this->i / 60); $this->i = $this->i % 60; } }
Python
UTF-8
4,664
3.265625
3
[]
no_license
from sklearn.model_selection import cross_val_score,train_test_split from sklearn.ensemble import RandomForestClassifier import numpy as np import pandas as pd import scipy from sklearn.tree import DecisionTreeClassifier from sklearn import tree from sklearn.linear_model import LogisticRegression from sklearn.naive_bayes import GaussianNB from scipy import stats from sklearn import model_selection from scipy import stats # create data frame containing your data, each column can be accessed df = pd.read_csv('/Users/tushar/Desktop/DAL/Machinelearning_for_bigdata/Qusetion_1/animals.csv', sep=",", index_col=False) df = df.values scoring = 'accuracy' #let's divide the dataset into train and test. test dataset contains the final column with class values train = np.array(df[:,0:25]) test = np.array(df[:,25:26]) #The parameter test_size is given value 0.3 # it means test sets will be 30 percent of whole dataset and training dataset size will be 70 percent of the entire dataset. X_train, X_test, y_train, y_test = train_test_split(train, test,test_size = 0.3,random_state = 0) kfold = model_selection.KFold(n_splits=10, random_state=None) #Random forest classifier clf = RandomForestClassifier() # 10-Fold Cross validation scores = model_selection.cross_val_score(clf, X_train, y_train.ravel(), cv=kfold, scoring=scoring) Rf_Mean_Acc = scores.mean() Rf_Std_Dev = scores.std() print("Random forest classifier Accuracy: %0.2f (+/- %0.2f)" % (Rf_Mean_Acc, Rf_Std_Dev)) #Decision Tree Classifier clf = DecisionTreeClassifier() # 10-Fold Cross validation scores = cross_val_score(clf, X_train, y_train.ravel(), cv=kfold, scoring =scoring) Dt_Mean_Acc = scores.mean() Dt_Std_Dev = scores.std() print("Decision Tree Classifier Accuracy: %0.2f (+/- %0.2f)" % (Dt_Mean_Acc, Dt_Std_Dev)) #Naive Bayes classifier clf = GaussianNB() # 10-Fold Cross validation scores = cross_val_score(clf, X_train, y_train.ravel(), cv=kfold, scoring =scoring) NB_Mean_Acc = scores.mean() NB_Std_Dev = scores.std() print("Naive Bayes classifier Accuracy: %0.2f (+/- %0.2f)" % (NB_Mean_Acc, NB_Std_Dev)) #Logistics Regression classifier clf = LogisticRegression() # 10-Fold Cross validation scores = cross_val_score(clf, X_train, y_train.ravel(), cv=kfold, scoring =scoring) LR_Mean_Acc = scores.mean() LR_Std_Dev = scores.std() print("Logistics Regression classifier Accuracy: %0.2f (+/- %0.2f)" % (LR_Mean_Acc, LR_Std_Dev)) # Given alpha value in question alpha=0.05 # Calculating statistical test for Mean and standard deviation of accuracy scores in Decision Tree and Random Forest print("Ttest Random forest vs Decision tree") t, p = scipy.stats.ttest_ind_from_stats(Rf_Mean_Acc, Rf_Std_Dev, 10, Dt_Mean_Acc, Dt_Std_Dev, 10, equal_var=False) print("ttest_ind_from_stats: t = %g p = %g" % (t, p)) # Determinig the Statistical significance using ttest and alpha if (p<alpha): print("P is less than alpha(0.05), hence there is a significant difference between the Random Forest and Decision Tree classification") else: print("There is no significant difference between the Random Forest and Decision Tree classification") print("Ttest Random forest vs Naivebayes") # Calculating statistical test for Mean and standard deviation of accuracy scores in NaiveBayes and Random Forest t, p = stats.ttest_ind_from_stats(Rf_Mean_Acc, Rf_Std_Dev, 10, NB_Mean_Acc, NB_Std_Dev, 10, equal_var=False) print("ttest_ind_from_stats: t = %g p = %g" % (t, p)) # Determinig the Statistical significance using ttest and alpha if (p<alpha): print("P is less than alpha(0.05), hence there is a significant difference between the Random Forest and NaiveBayes classification") else: print("There is no significant difference between the Random Forest and NaiveBayes classification") print("Ttest Random forest vs Logistics Regression") # Calculating statistical test for Mean and standard deviation of accuracy scores in Logistics Regression and Random Forest t, p = stats.ttest_ind_from_stats(Rf_Mean_Acc, Rf_Std_Dev, 10, LR_Mean_Acc, LR_Std_Dev, 10, equal_var=False) print("ttest_ind_from_stats: t = %g p = %g" % (t, p)) # Determinig the Statistical significance using ttest and alpha if (p<alpha): print("P is less than alpha(0.05), hence there is a significant difference between the Random Forest and Logistics Regression classification") else: print("There is no significant difference between the Random Forest and Logistics Regression classification")
PHP
UTF-8
12,885
3.25
3
[]
no_license
<?php class Tools { /* * methods */ // retrieve an outside html page and convert into a string function getHTML( string $url ) : string { $user_agent = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_4)' . ' AppleWebKit/537.36 (KHTML, like Gecko)' . ' Chrome/50.0.2661.102' . ' Safari/537.36'; // establish cURL options $cOptions = array( CURLOPT_CONNECTTIMEOUT => 10, // 10 seconds CURLOPT_FOLLOWLOCATION => true, CURLOPT_HEADER => false, // no need to print header in the output CURLOPT_RETURNTRANSFER => true, // allow transfer of output as a string to a variable CURLOPT_URL => $url, CURLOPT_USERAGENT => $user_agent, ); // start cURL session $cSession = curl_init(); // send cURL options to the session curl_setopt_array( $cSession, $cOptions ); // place output into string variable upon execution of session (string) $html = curl_exec( $cSession ); // end CURL session curl_close( $cSession ); // return string return $html; } // Retrieve data from HTML pages by matching strings with regular expressions function scrapeHTML( string $url, string $regex ) : array { (string) $html = Tools::getHTML( $url ); (array) $result = preg_match( $regex, $html, $matches ) ? $matches : array( 'not found' ); return $result; } // retrieve JSON data from outside APIs and parse into PHP array function getJsonArray( string $url ) : array { (string) $html = Tools::getHtml( $url ); return json_decode( $html, true ); } // Returns a pop-up alert; // mostly for testing. function alertThis( string $text ) : string { return "<script type='text/javascript'>alert('{$text}');</script>"; } /* * evaluate incoming string data re: * Required * Maximum Length * optional Regex matching */ function evaluateData( string $field, string $data, bool $required, int $maxchars, string $regex = '' ) : string { $result = ''; if ( $required ) if( empty( $data ) ) $result = "{$field}: Required."; elseif( $maxchars ) if ( strlen( $data ) > $maxchars ) $result = "{$field}: Must not exceed {$maxchars} characters."; elseif( $regex ) if( !preg_match( $regex, $data ) ) $result = "{$field}: Improperly formatted."; if ( $result ) $result = "<li>{$result}</li>"; return $result; } /* * Use primaryPanel() to create overview/biography panels; */ function panelOverview( string $type, string $source, string $text ) : string { $panelOverview = ''; $title = ''; $footer = ''; if( strlen($text) ) { $title = "{$type} from {$source}"; $text = "<p style=\"font-size: 1.2em;\">{$text}</p>"; $footer = 'Click the heading above to show or hide the text.'; $panelOverview = Tools::createPanel($title, $text, $footer, TRUE, 'default'); } return $panelOverview; } /* * Use primaryPanel() to create Credits panels; */ function panelCredits( int $count, string $type, string $text ) : string { $panelCredits = ''; $title = ''; $footer = ''; if( $count ) { $title = "{$type}"; $footer = 'Click the heading above to show or hide the list.'; $panelCredits = Tools::createPanel($title, $text, $footer, TRUE, 'default'); } return $panelCredits; } /* * Create Bootstrap panel with optional collapsibility */ function createPanel( string $title, string $text, string $footer, bool $isCollapsible, string $style = 'default' // default; primary; etc. ) : string { $panelTitle = $title; $id = ''; $idBody = ''; $collapseClass = ''; if( $isCollapsible ) { $id = preg_replace( '/\s+/', '', $title ); $panelTitle = "<a data-toggle=\"collapse\" href=\"#{$id}\" title=\"Click for {$title}\">{$title}</a> <span class=\"caret\"></span>"; $collapseClass = " panel-collapse collapse in"; $idBody = " id=\"{$id}\""; } $panelHeading = "<div class=\"panel-heading\">" . "<h3 class=\"panel-title\">{$panelTitle}</h3>" . "</div>"; $panelBody = "<div{$idBody} class=\"panel-body{$collapseClass} credits-scroll\">{$text}</div>"; $panelFooter = "<div class=\"panel-footer\">" . "<p style=\"font-size: 1.1em;\"></p>" . "</div>"; $panelFooter = ( $footer ) ? "<div class=\"panel-footer\">" . "<p style=\"font-size: 1.1em;\">{$footer}</p>" . "</div>" : ''; $primaryPanel = "<div class=\"panel panel-{$style}\">{$panelHeading}{$panelBody}{$panelFooter}</div>"; return $primaryPanel; } /* * create a URL which might open a topic's Wikipedia page */ function toWikipedia( string $topic, string $lang="en" ) : string { /* * lang = 2-letter string denoting language Wikipedia might support (or not); * default = en (as in English) * * topic = an occasionally accurate search term * which one might enter into a Wikipedia search form * * Sometimes a Wikipedia page might not exist yet for a topic, * and sometimes Wikipedia might remove a page completely for a topic; * either may result in Wikipedia suggesting * that a user create a new page if topic not found. * * Wikipedia might also do the following with the url: * post an error page * suggest hints on a disambiguation page * go to a topic page which might hint at at least one alternative * go directly to the exact topic page. */ // format topic string by replacing space characters with underscores $wiki_topic = preg_replace( '/\s+/', '_', trim( $topic ) ); // build WikiPedia URL $url = "http://{$lang}.wikipedia.org/wiki/{$wiki_topic}"; // output URL return $url; } /* * replace ampersands, for spaceless hashtags */ function ampAnd( $string ) : string { return preg_replace( '~[&]+~', 'And', $string ); } /* * and a half (replace representations of half, for spaceless hashtags) */ function andAHalf( $string ) : string { /* * TODO: stumped re '1/2' */ return preg_replace( '~[\½]+~', 'AndAHalf', $string ); } /* * and a third (replace representations of third, for spaceless hashtags) */ function andAThird( $string ) : string { /* * TODO: stumped re '1/3' */ return preg_replace( '~[\⅓]+~', 'AndAThird', $string ); } /** * Replace diacritical characters with natural characters * * @param $string * @return mixed * @link http://myshadowself.com/coding/php-function-to-convert-accented-characters-to-their-non-accented-equivalant/ */ function replaceDiacriticals( $string ) : string { $diacriticals = array( 'À', 'Á', 'Â', 'Ã', 'Ä', 'Å', 'Æ', 'Ç', 'È', 'É', 'Ê', 'Ë', 'Ì', 'Í', 'Î', 'Ï', 'Ð', 'Ñ', 'Ò', 'Ó', 'Ô', 'Õ', 'Ö', 'Ø', 'Ù', 'Ú', 'Û', 'Ü', 'Ý', 'ß', 'à', 'á', 'â', 'ã', 'ä', 'å', 'æ', 'ç', 'è', 'é', 'ê', 'ë', 'ì', 'í', 'î', 'ï', 'ñ', 'ò', 'ó', 'ô', 'õ', 'ö', 'ø', 'ù', 'ú', 'û', 'ü', 'ý', 'ÿ', 'Ā', 'ā', 'Ă', 'ă', 'Ą', 'ą', 'Ć', 'ć', 'Ĉ', 'ĉ', 'Ċ', 'ċ', 'Č', 'č', 'Ď', 'ď', 'Đ', 'đ', 'Ē', 'ē', 'Ĕ', 'ĕ', 'Ė', 'ė', 'Ę', 'ę', 'Ě', 'ě', 'Ĝ', 'ĝ', 'Ğ', 'ğ', 'Ġ', 'ġ', 'Ģ', 'ģ', 'Ĥ', 'ĥ', 'Ħ', 'ħ', 'Ĩ', 'ĩ', 'Ī', 'ī', 'Ĭ', 'ĭ', 'Į', 'į', 'İ', 'ı', 'IJ', 'ij', 'Ĵ', 'ĵ', 'Ķ', 'ķ', 'Ĺ', 'ĺ', 'Ļ', 'ļ', 'Ľ', 'ľ', 'Ŀ', 'ŀ', 'Ł', 'ł', 'Ń', 'ń', 'Ņ', 'ņ', 'Ň', 'ň', 'ʼn', 'Ō', 'ō', 'Ŏ', 'ŏ', 'Ő', 'ő', 'Œ', 'œ', 'Ŕ', 'ŕ', 'Ŗ', 'ŗ', 'Ř', 'ř', 'Ś', 'ś', 'Ŝ', 'ŝ', 'Ş', 'ş', 'Š', 'š', 'Ţ', 'ţ', 'Ť', 'ť', 'Ŧ', 'ŧ', 'Ũ', 'ũ', 'Ū', 'ū', 'Ŭ', 'ŭ', 'Ů', 'ů', 'Ű', 'ű', 'Ų', 'ų', 'Ŵ', 'ŵ', 'Ŷ', 'ŷ', 'Ÿ', 'Ź', 'ź', 'Ż', 'ż', 'Ž', 'ž', 'ſ', 'ƒ', 'Ơ', 'ơ', 'Ư', 'ư', 'Ǎ', 'ǎ', 'Ǐ', 'ǐ', 'Ǒ', 'ǒ', 'Ǔ', 'ǔ', 'Ǖ', 'ǖ', 'Ǘ', 'ǘ', 'Ǚ', 'ǚ', 'Ǜ', 'ǜ', 'Ǻ', 'ǻ', 'Ǽ', 'ǽ', 'Ǿ', 'ǿ', 'Ά', 'ά', 'Έ', 'έ', 'Ό', 'ό', 'Ώ', 'ώ', 'Ί', 'ί', 'ϊ', 'ΐ', 'Ύ', 'ύ', 'ϋ', 'ΰ', 'Ή', 'ή' ); $naturals = array( 'A', 'A', 'A', 'A', 'A', 'A', 'AE', 'C', 'E', 'E', 'E', 'E', 'I', 'I', 'I', 'I', 'D', 'N', 'O', 'O', 'O', 'O', 'O', 'O', 'U', 'U', 'U', 'U', 'Y', 's', 'a', 'a', 'a', 'a', 'a', 'a', 'ae', 'c', 'e', 'e', 'e', 'e', 'i', 'i', 'i', 'i', 'n', 'o', 'o', 'o', 'o', 'o', 'o', 'u', 'u', 'u', 'u', 'y', 'y', 'A', 'a', 'A', 'a', 'A', 'a', 'C', 'c', 'C', 'c', 'C', 'c', 'C', 'c', 'D', 'd', 'D', 'd', 'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'G', 'g', 'G', 'g', 'G', 'g', 'G', 'g', 'H', 'h', 'H', 'h', 'I', 'i', 'I', 'i', 'I', 'i', 'I', 'i', 'I', 'i', 'IJ', 'ij', 'J', 'j', 'K', 'k', 'L', 'l', 'L', 'l', 'L', 'l', 'L', 'l', 'l', 'l', 'N', 'n', 'N', 'n', 'N', 'n', 'n', 'O', 'o', 'O', 'o', 'O', 'o', 'OE', 'oe', 'R', 'r', 'R', 'r', 'R', 'r', 'S', 's', 'S', 's', 'S', 's', 'S', 's', 'T', 't', 'T', 't', 'T', 't', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'W', 'w', 'Y', 'y', 'Y', 'Z', 'z', 'Z', 'z', 'Z', 'z', 's', 'f', 'O', 'o', 'U', 'u', 'A', 'a', 'I', 'i', 'O', 'o', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'A', 'a', 'AE', 'ae', 'O', 'o', 'Α', 'α', 'Ε', 'ε', 'Ο', 'ο', 'Ω', 'ω', 'Ι', 'ι', 'ι', 'ι', 'Υ', 'υ', 'υ', 'υ', 'Η', 'η' ); $result = (string) str_replace( $diacriticals, $naturals, $string ); return $result; } /* * prepare names and titles for hashtags re sharing */ function hashNameTitle( $string ) : string { $amp = Tools::ampAnd( $string ); $half = Tools::andAHalf( $amp ); $third = Tools::andAThird( $half ); $diacriticals = Tools::replaceDiacriticals( $third ); // replace $ (TODO: Refine if needed) $dollars = preg_replace( '~[\$]+~', 'Dollars', $diacriticals ); // trim spaces $result = preg_replace( '~[\s\W]+~', '', $dollars ); // output result return $result; } /* * seeks a match from an indexed array */ function getArrayValue ( array $array, string $index ) : string { $result = ''; foreach( $array as $key => $value ) { if( $index == $key ) { $result = $value; } else { continue; } return $result; } } // Returns 's' if "https" version is called // (to be appended to this project's URLs) function isHttpS() : string { $result = !empty($_SERVER['HTTPS']) ? 's' : ''; return $result; } }
Java
UTF-8
5,590
2.296875
2
[]
no_license
package com.nawaf.jobfinder.ui; import android.content.Intent; import android.net.Uri; import android.os.Handler; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.widget.TextView; import com.nawaf.jobfinder.R; import com.nawaf.jobfinder.common.OnRecyclerItemClickLister; import com.nawaf.jobfinder.common.Utils; import com.nawaf.jobfinder.models.FilterModel; import com.nawaf.jobfinder.models.JobModel; import com.nawaf.jobfinder.models.Providers; import com.nawaf.jobfinder.retrofit.DataSource; import java.util.ArrayList; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; /** * This activity contains the list of the jobs retried */ public class MainActivity extends AppCompatActivity implements SearchFragment.OnSearchListener, OnRecyclerItemClickLister<String>, JobAdapter.OnLoadMoreListener { // views private TextView tvSearch; private TextView tvMessage; private JobAdapter jobAdapter; // objects FilterModel filterModel; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initRecycler(); initFilter(); initViews(); requestDataFromApi(filterModel, 1); // jobAdapter.addLoadingFooter(); } private void initViews() { tvSearch = findViewById(R.id.tvSearchValues); tvMessage = findViewById(R.id.tvMessage); tvSearch.setOnClickListener(v -> { getSupportFragmentManager().beginTransaction() .replace(R.id.container, SearchFragment.newInstance(filterModel)) .addToBackStack(SearchFragment.class.getName()) .commit(); }); } private void initFilter() { filterModel = new FilterModel(); filterModel.setProviders(Providers.GITHUB); } /** * Initialize the recycler layoutManager ,adapter and the scroll listener. */ private void initRecycler() { RecyclerView rvJobs = findViewById(R.id.rvJobs); LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this); rvJobs.setLayoutManager(linearLayoutManager); jobAdapter = new JobAdapter(rvJobs); jobAdapter.setOnRecyclerItemClickLister(this); jobAdapter.setOnLoadMoreListener(this); rvJobs.setAdapter(jobAdapter); } /** * Method to request job list from apis based on the parameters passed * * @param filterModel object with filter model * @param page page number needed */ private void requestDataFromApi(FilterModel filterModel, int page) { if (!Utils.isNetworkAvailable(this)) { tvMessage.setText(R.string.error_message_internet); } jobAdapter.addLoadingFooter(); try { DataSource.getJobsByProvider(filterModel, page).enqueue(new Callback<ArrayList<JobModel>>() { @Override public void onResponse(Call<ArrayList<JobModel>> call, Response<ArrayList<JobModel>> response) { jobAdapter.removeLoadingFooter(); tvMessage.setText(""); if (response.body() != null) { new Handler().post(new Runnable() { @Override public void run() { if (page == 1) { if (response.body().isEmpty()) { jobAdapter.clear(); tvMessage.setText(R.string.empty_job_list); } else { jobAdapter.addItems(response.body()); } } else { jobAdapter.setLoaded(); if (response.body().isEmpty()) { } else { jobAdapter.addItems(response.body()); } } } }); } } @Override public void onFailure(Call<ArrayList<JobModel>> call, Throwable t) { // jobAdapter.removeLoadingFooter(); } }); } catch (Exception e) { e.printStackTrace(); // jobAdapter.removeLoadingFooter(); } } @Override public void onSearchClicked(FilterModel filterModel) { String hint = String.format("%s / %s / %s", filterModel.getProviders().getName(), filterModel.getTitle(), filterModel.getLocation()); tvSearch.setText(hint); jobAdapter.clear(); requestDataFromApi(filterModel, 1); if (getSupportFragmentManager().getBackStackEntryCount() > 0) { getSupportFragmentManager().popBackStack(); } } @Override public void onItemClicked(String url) { if (url != null) { Intent browse = new Intent(Intent.ACTION_VIEW); browse.setData(Uri.parse(url)); startActivity(browse); } } @Override public void onLoadMore(int page) { requestDataFromApi(filterModel, page); } }
JavaScript
UTF-8
592
4.40625
4
[]
no_license
//Operadores // sume two number let numberOne = 60; let numberTwo = 100; let result = numberOne+numberTwo; console.log(result); // cont two strings let name = "Luis"; let lastName = "Meneses"; let space = " "; let compleateName = name+space+lastName; console.log(compleateName); //Compare two numbers let numberOne1 = 371924; let numberTwo2 = 917341; let mayor = numberOne1 > numberTwo2; let menor = numberOne1 < numberTwo2; let igual = numberOne1 == numberTwo2; let diferente = numberOne1 != numberTwo2; console.log(mayor); console.log(menor); console.log(igual); console.log(diferente);
C++
UTF-8
1,209
3.09375
3
[]
no_license
/*Input: jobDifficulty = [6,5,4,3,2,1], d = 2 Output: 7 Explanation: First day you can finish the first 5 jobs, total difficulty = 6. Second day you can finish the last job, total difficulty = 1. The difficulty of the schedule = 6 + 1 = 7 Input: jobDifficulty = [1,1,1], d = 3 Output: 3 Explanation: The schedule is one job per day. total difficulty will be 3. */ class Solution { public: int n,maxVal = 1e7;; int solve(vector<int>& jobd, int indx,int d,vector<vector<int>> &dp) { if(indx==n && d==0) return 0; if(d<0 || indx>=n) { return maxVal; } if(dp[indx][d]!=-1) return dp[indx][d]; int work = 0; int res = maxVal; for(int i=indx;i<n;i++) { work = max(work,jobd[i]); res = min(res,work + solve(jobd,i+1,d-1,dp)); //cout<<res<<" "; } return dp[indx][d] = res; } int minDifficulty(vector<int>& jobd, int d) { n = jobd.size(); if(n<d) return -1; vector<vector<int>> dp(n+1,vector<int>(d+1,-1)); return solve(jobd,0,d,dp); } };
Markdown
UTF-8
29,201
3.125
3
[]
no_license
# ==01-Nodejs模块化介绍== ## 1.1-Nodejs三种模块 * 1.在nodejs中所有的js文件都是一个模块。换言之,所有的模块都是js文件组成(js文件 = 模块) * 2.nodejs中只有三种模块 * 第一种:原生模块/内置模块/核心模块 * 原生模块就是nodejs官网中提供的模块,这些js文件随着node环境一起被下载安装 * 第二种:第三方模块 * 第三方模块就是npm网站下载的模块: 需要使用`npm install [模块名]`来安装 * 第三方模块:文件模块(也就是我们自己写的js文件,在nodejs中只要是js文件就是模块) * 如果是我们自己写的js文件模块,导入时使用文件的路径`require('我们的js文件路径')` ```javascript //nodejs模块化:在nodejs中,所有的js文件都是一个模块。换言之,所有的模块都是js文件组成 //nodejs中的模块只有三种 //1.内置模块/原生模块/核心模块:nodejs官方文档中的模块(随着安装node环境一并安装,直接使用) const fs = require('fs'); //2.第三方模块:npm网站下载的模块(需要下载后使用 `npm i 模块名`) const crawler = require('crawler');//爬虫模块 //3.js文件模块:我们自己写的js文件(只要是js文件都是模块) /*如果是自定义模块 a. require()参数是 js文件路径 b. require()返回值是 js文件中的 module.exports 对象 */ const mokuai = require('./mokuai.js'); console.log(mokuai); ``` ## 1.2-CommonJS规范 * 官网传送门:<http://www.commonjs.org/> * 1.世界上的编程规范有很多种,CommonJS只是其中一种 * 2.CommonJS规范不是只为Nodejs服务,有很多平台都遵循CommonJS规范,Nodejs平台只是其中之一 * 3.CommonJS规范只有三句话 * 1.导入模块使用:`require()` * 2.导出模块使用:`module.exports` * 3.导出模块一定要使用ZZZZS使用:`module.exports`(重要是事说两遍) ```javascript /* 1.每一个js文件都是一个独立的作用域,外部无法访问*/ let name = '张三'; let age = 18; let sayHi = ()=>{ console.log('我是张三'); }; /* 2.每一个js文件都有一个默认的全局对象 module.exports, 当外部使用 require() 导入这个js文件模块,就会得到这个module.exports对象 */ module.exports = { name, age }; ``` * 课外拓展知识点介绍 * 1.CommonJS由来:JavaScript是一个强大面向对象语言,它有很多快速高效的解释器。官方JavaScript标准定义的API是为了构建基于浏览器的应用程序。其实JavaScript设计之初不仅仅是针对客户端设计的语言。后来只是由于Web的迅速流行,加之Netscape和微软之间之争过早的将JavaScipt标准化,导致目前JS仅仅包括基本的API,并不是具有服务端编程语言的特性。 * CommonJS API定义很多普通应用程序(主要指非浏览器的应用,例如服务端)使用的API,从而填补了这个空白。它的终极目标是提供一个类似Python,Ruby和Java标准库。这样的话,开发者可以使用CommonJS API编写应用程序,然后这些应用可以运行在不同的JavaScript解释器和不同的主机环境中。在兼容CommonJS的系统中,你可以实用JavaScript程序开发 * 服务器端JavaScript应用程序命令行工具 * 图形界面应用程序 * 混合应用程序(如,Titanium或Adobe AIR) * 2.CommonJS规范:根据CommonJS规范,一个单独的文件就是一个模块。加载模块使用require方法,该方法读取一个文件并执行,最后返回文件内部的exports对象。 * require - 用来引入依赖 * export - 用来导出模块,包括标识符(identifier)和模块内容(contents) * CommonJS与AMD及CMD的关系 * 这三个规范都是为javascript模块化加载而生的,都是在用到或者预计要用到某些模块时候加载该模块,使得大量的系统巨大的庞杂的代码得以很好的组织和管理。模块化使得我们在使用和管理代码的时候不那么混乱,而且也方便了多人的合作。 * CommonJS 加载模块是同步的,所以只有加载完成才能执行后面的操作。像Node.js主要用于服务器的编程,加载的模块文件一般都已经存在本地硬盘,所以加载起来比较快,不用考虑异步加载的方式,所以CommonJS规范比较适用。但如果是浏览器环境,要从服务器加载模块,这是就必须采用异步模式。所以就有了 AMD CMD 解决方案。 * 1.用途区别 * CommonJS是服务端的模块化规范 * AMD和CMD是客户端(浏览器)的模块化规范 * 2.加载区别 * CommonJS和CMD都是同步加载模块化规范 * AMD是异步加载模块化规范 * 3.平台区别 * CommonJS是`Nodejs`使用的规范 * AMD(Asynchronous Module Definition 异步模块定义)是 `RequireJS` 在推广过程中对模块定义的规范化产出 * CMD(Common Module Definition通用模块定义) 是 SeaJS 在推广过程中对模块定义的规范化产出 ## 1.3-Nodejs模块加载缓存机制 * 1.加载模块时,node会首先从缓存中查找,如果缓存中存在则从缓存中读取,如果不存在则读取并且放入缓存 * 2.也就是说,一个模块在第一次导入时会被node放入缓存中,第二次再导入不会重新加载而是从缓存中读取 * (1)避免的重复导入模块的资源浪费 * (2)从缓存中读取模块速度更快 ```javascript //nodejs模块缓存机制 /*每一个模块在第一次导入之后会被node放入缓存中,第二次导入不会重新加载而是从缓存中读取 a.避免重复导入模块的资源浪费 b.从缓存中读取模块速度更快 */ //第一次加载:会执行模块中的代码,之后放入缓存中 const mokuai1 = require('./mokuai.js'); //第二次加载:直接从缓存中读取 const mokuai2 = require('./mokuai.js'); console.log(mokuai1 === mokuai2);//true ``` ## 1.4-使用模块化思想重构项目 * 将路由功能封装到自定义模块中 ```javascript const fs = require('fs'); const path = require('path'); const url = require('url'); const querystring = require('querystring'); //操作hero.json文件模块(数据库) const hero = require('./data/hero.js'); //导出一个函数 module.exports = (req, res) => { //使用url模块将路径解析出来 var urlObjc = url.parse(req.url, true); //接口文档中的路由实际上是url的pathname部分 var urlPath = urlObjc.pathname; //设计路由 if (urlPath == '/' && req.method == 'GET') { //首页 //服务端重定向到view/heroList.html res.writeHead(302, { 'Location': 'views/heroList.html' }); res.end(); } else if (urlPath == '/heroList' && req.method == 'GET') { //1.展示首页列表数据 hero.find((err, jsonData) => { console.log(jsonData); if (err) { throw err; } else { res.end(jsonData); }; }); } else if (urlPath === '/heroAdd' && req.method === 'POST') { //2.添加英雄列表 postParse(req, (data) => { //完成解析之后,将得到的数据存入json文件 hero.add(data, (err) => { if (err) { //服务端不能直接返回js对象,因为服务器是给所有客户端使用,需要返回json对象 console.dir(err); res.end(JSON.stringify({ err_code: 500, //500表示服务器内部错误 err_msg: err })); } else { res.end(JSON.stringify({ err_code: 0, err_msg: 'success' })); } }); }); } else if (urlPath === '/heroInfo' && req.method === 'GET') { //3.查看英雄详情(参数英雄id) //1.获取get请求参数 console.log(urlObjc.query); var heroID = urlObjc.query.id; //2.处理 hero.find(heroID, (err, data) => { if (err) { throw err; } else { res.end(data); }; }); } else if (urlPath === '/heroDelete' && req.method === 'GET') { //4.删除英雄(参数英雄id) //(1)获取请求参数 let heroID = urlObjc.query.id; //(2)处理请求 hero.delete(heroID, (err) => { if (err) { throw (err); } else { //服务端重定向刷新首页 res.writeHead(302, { 'Location': 'views/heroList.html' }); res.end(); } }) } else if (urlPath.indexOf('/node_modules') === 0 || urlPath.indexOf('/views') === 0) { //读取静态资源 fs.readFile(path.join(__dirname, urlPath), function (err, data) { if (err) { throw err; } res.end(data); }) } else { //404错误页面 res.end('404 not found' + req.url); }; }; /* 我们自己封装的原生解析post请求参数的函数 第一个参数:请求对象 第二个参数:完成回调 * postObject:post请求参数对象 */ function postParse(req, callback) { console.log(req); //1.1 给req注册一个data事件 let postData = ""; req.on('data', function (chuck) { postData += chuck; console.log(postData); }); //1.2给req注册一个end事件 req.on('end', function () { //1.3 使用 querystring模块解析post参数 let postObjc = querystring.parse(postData); //调用回调函数 callback(postObjc); }); }; ``` * index.js中导入路由模块 ```javascript //1.导入模块 const http = require('http'); const router = require('./router.js'); //2.创建服务器 let server = http.createServer((req, res) => { console.log(req.url + ":" + req.method); //使用路由模块处理请求 router(req,res); }); //3.启动服务器 server.listen(3000, () => { console.log('欢迎来到王者荣耀'); }); ``` # ==02-Express框架学习== ## 1.1-Express框架介绍 * 1.Express是NodeJS开发中一个非常重量级的第三方框架,它对于NodeJS服务端就相当于Jquery对于HTML客户端。 * **如果连Express都不会用,基本上都不好意思跟别人说你会NodeJS** * 2.Express官网: * http://www.expressjs.com.cn/ * http://expressjs.com/ * 一般我们学习一个新的技术,都是去官网文档查看它的API,然后多多尝试,熟能生巧 * 3.Express的github地址:<https://github.com/expressjs/express> * Express的原作者TJ在node社区非常的有名,他写过200多个框架,目前他已经将Express交给了朋友维护,宣布不再维护NodeJS框架,转向Go语言<https://github.com/tj> * 4.Express官网是这样介绍自己的:基于 Node.js 平台,快速、开放、极简的 web 开发框架。 * *Express一个非常重要的亮点就是它没有改变nodejs已有的特性,而是在它的基础上进行了拓展* * **也就是说,使用Express你既可以使用nodejs原生的任何API,也能使用Express的API** ![1550771343771](day04.assets/1550771343771.png) ## 1.2-Express基本使用 ```javascript //1.导入模块 const express = require('express'); //2.创建服务器 /* express() 相当于http模块的http.createServer() */ let app = express(); //3.接收客户端请求 /*(1)express最大的特点就是自带路由功能,我们无需在一个方法中处理所有请求 (2)在express中,每一个请求都是一个单独的方法 */ app.get('/',(req,res)=>{ //响应客户端数据 //express响应数据 send方法:自动帮我们设置好了响应头,无需担心中文乱码问题 res.send('欢迎来到黑马程序员'); // //以前的做法;如果是中文,需要设置响应头解决乱码问题 // res.writeHead(200,{ // 'Content-Type':'text/plain;charset=utf8' // }); // res.end('欢迎来到黑马程序员'); }); app.get('/heroInfo',(req,res)=>{ //express自动帮我们解析了get请求参数,我们直接通过req.query获取即可 console.log(req.query); }); //4.开启服务器 app.listen(3000,()=>{ console.log('服务器启动成功'); }); ``` ## 1.3-Express三大特性介绍 ​ * 1.托管静态资源 * 第二天讲的nodejs实现静态服务器功能在express中只需要一行代码 * 2.路由 * express自带路由功能,让Node服务端开发变得极其简单 * express支持链式语法,可以让代码看起来更加简洁 * 3.中间件 * Express最为核心的技术和思想,万物皆中间件 * 中间件虽然理解起来有点困难,但是使用起来非常方便,类似于jquery的插件一样,由于jquery库自身的功能无法满足开发需求,所以通过插件来拓展功能 # 03-Express特性1-托管静态资源 * ***将第二天的nodejs实现静态服务器功能用Express实现*** ```javascript //1.导入模块 const express = require('express'); //2.创建服务器 let app = express(); //托管静态资源(相当于我们之前写的一大坨模拟apache服务器功能代码) /* 第一个参数:客户端请求路径(一般与托管文件夹名字一致) 第二个参数:要托管的文件夹绝对路径 */ app.use('/resource',express.static( __dirname + '/resource')); //3.处理请求 app.get('/',(req,res)=>{ //res.sendFile:响应客户端文件 参数是文件路径 res.sendFile(__dirname + '/resource/html/index.html'); }); //4.开启服务器 app.listen(3000,()=>{ console.log('success'); }); ``` # ==04-Express特性2-中间件== * 中间件是Express框架学习中最难的部分,同时也是最为核心的技术,我们的学习路线如下 * 1.什么是中间件 * 2.Express中间件的本质及工作原理 * 3.自定义解析post请求参数的中间件 * 4.第三方中间件使用 ## 1.1-什么是中间件 * **下图是一个自来水净化的过程,这张图可以更好的理解什么是中间件** * 水库的水并不是直接取出来就送到用户的家中使用,而是经过一些净化过滤处理之后才送到用户的家中,在这个过程中水还是水,本质上还是同一个东西,但是却多了一些东西 * 水库中原始的水可以理解为是浏览器的原始请求request * 最终用户喝到的水可以理解为是express最终获取的请求request * 而过滤中的一些加絮凝剂、过滤池等操作就是中间件,可以理解为给我们原始的请求request添加了一些属性或者方法(如post参数解析之后的对象等) ![1550771994249](day04.assets/1550771994249.png) ## 1.2-中间件的本质及工作原理 * 1.中间件其实就是一个函数 * `function(req,res,next){ req:请求对象 res:响应对象 next:下一个中间件 }` * 2.Express如何使用中间件?:三种方式 ​ `app.use('pathname',中间件) : ​ pathname不写: 任何请求路径都会执行这个中间件 ​ pathname写了:任何以pathname开头的请求路径都会执行这个中间件 ​ app.get('pathname',中间件) : 请求路径为pathname的get请求会执行这个中间件 ​ app.post('pathname',中间件) : 请求路径为pathname的post请求会执行这个中间件` * 3.中间件工作流程(Express处理网络请求流程) ​ `a.从上往下依次匹配请求路径,如果匹配成功则执行该中间件 ​ b.如果这个中间件中调用了:next() ,则会继续往下匹配 ​ c.如果所有的中间件都无法匹配,则会自动进入一个兜底的中间件响应返回404 not found错误` ```javascript //导入模块 const express = require('express'); //创建服务器 let app = express(); /*1.什么是express中间件?: 其实就是一个函数(这个函数有三个参数) function(req,res,next){ req:请求对象 res:响应对象 next:下一个中间件 } */ /*2.express如何使用中间件?: 三种方式 app.use('pathname',中间件) : pathname不写: 任何请求路径都会执行这个中间件 pathname写了:任何以pathname开头的请求路径都会执行这个中间件 app.get('pathname',中间件) : 请求路径为pathname的get请求会执行这个中间件 app.post('pathname',中间件) : 请求路径为pathname的post请求会执行这个中间件 */ /* 3.express处理网络请求的流程 a.从上往下依次匹配请求路径,如果匹配成功则执行该中间件 b.如果这个中间件中调用了:next() ,则会继续往下匹配 c.如果所有的中间件都无法匹配,则会自动进入一个兜底的中间件响应返回404 not found错误 */ app.use('/abc',(req,res,next)=>{ //污水净化第一步:添加絮凝剂 console.log(11111); req.a = '添加了絮凝剂'; next(); }); app.use('/abc',(req,res,next)=>{ //污水净化第二步:添加活性炭 console.log(22222); req.b = '添加活性炭'; next(); }); app.post('/abc',(req,res,next)=>{ console.log(33333); next(); }); app.get('/abc',(req,res,next)=>{ console.log(44444); //看下污水净化到这一步加了什么 console.log(req.a); console.log(req.b); res.send('hello'); }); //express底层有一个默认的兜底中间件,如果上面所有的中间件都无法匹配或者没有结束响应,则会进入这个中间件 //自定义一个兜底中间件,覆盖默认的 app.use((req,res)=>{ console.log(55555); res.send('你的路径是不是写错啦'); }); //开启服务器 app.listen(3000, () => { console.log('success'); }); ``` ## 1.3-自定义解析post请求参数中间件 * ***使用postman测试*** * bodyParse ```javascript const querystring = require('querystring'); /* 导出中间件(函数) 第一个参数:请求对象 第二个参数:完成回调 * postObject:post请求参数对象 */ module.exports = (req, res, next) => { /*如果本次请求是post请求,则解析post请求参数, 并且将解析好的参数对象作为req的属性传递给下一个中间件*/ if (req.method == 'POST') { //1.1 给req注册一个data事件 let postData = ""; req.on('data', function (chuck) { postData += chuck; }); //1.2给req注册一个end事件 req.on('end', function () { //1.3 使用 querystring模块解析post参数 let postObjc = querystring.parse(postData); //将解析好的参数对象添加到req的属性中 req.body = postObjc; //执行下一个中间件 next(); }); } } ``` * index.js ```javascript //导入模块 const express = require('express'); //创建服务器 let app = express(); //使用中间件 //任何请求都会进入我们自己写的中间件,并且只要是post请求就会帮你解析好参数放入req.body中 app.use(require('./bodyParse.js')); app.post('/abc',(req,res,next)=>{ console.log(req.body); //告诉客户端我收到的参数 res.send(req.body); }); app.post('/efg',(req,res,next)=>{ console.log(req.body); //告诉客户端我收到的参数 res.send(req.body); }); //开启服务器 app.listen(3000, () => { console.log('success'); }); ``` ## 1.4-第三方中间件使用 * 1.在Express官网,有非常多得第三方中间件,它们可以让我们的Nodejs开发变得极其简单 * 2.所有的第三方框架学习套路都是一样的 * 1.进官网,查文档 * 2.CTRL+C 与 CTRL+V * 3.第三方中间件使用步骤一般都是固定两步 * 一: 安装 `npm i xxxx`(官网复制粘贴) * **第三方中间件都需要使用npm安装,可以理解为是一种特殊的第三方模块** * 二: 使用 `app.use(xxx)`(官网复制粘贴) ![1550772451014](day04.assets/1550772451014.png) ### body-parse第三方中间件:解析post请求参数 ```javascript //导入模块 const express = require('express'); //创建服务器 let app = express(); //使用第三方中间件 /*所有的第三方模块思路都是一样 1.进官网,查文档 2.找examples(使用示例),复制粘贴 a.安装第三方模块:`npm i body-parser` b.使用中间件: arr.use(具体用法请复制粘贴) 使用body-parser中间件之后,你的req会增加一个body属性,就是你的post请求参数 */ //(1)导入模块 var bodyParser = require('body-parser');//导入模块 // parse application/x-www-form-urlencoded //(2)使用中间件 app.use(bodyParser.urlencoded({ extended: false })) app.post('/abc',(req,res,next)=>{ console.log(req.body); //告诉客户端我收到的参数 res.send(req.body); }); app.post('/efg',(req,res,next)=>{ console.log(req.body); //告诉客户端我收到的参数 res.send(req.body); }); //开启服务器 app.listen(3000, () => { console.log('success'); }); ``` # 05-Express特性3-路由中间件 ```javascript /*路由中间件是express自带的中间件,使用步骤有4个 1.在router.js中导入express: const express = require('express'); 2.在router.js中创建路由容器: let app = express(); 3.在router.js中导出路由容器: moudule.exports = app; 4.在index.js中使用路由容器: app.use(require('./router.js')) */ ``` * router.js ```javascript /* express路由使用流程 */ //1.导入express模块 var express = require('express'); //2.创建路由容器(这个app相当于index.js中app的复制品) var app = express(); //express支持链式语法 app.get('/abc',(req,res)=>{ res.send('你的请求路径是/abc'); }) .get('/def',(req,res)=>{ res.send('你的请求路径是/def'); }); //3.导出路由模块 module.exports = app; ``` * index.js ```javascript //导入模块 const express = require('express'); //创建服务器 let app = express(); /* 1.index.js是服务器入口文件,所有的网络请求都会进入这里,假如我有100个请求,那这个文件 就会非常臃肿 2.路由中间件作用:将网络请求分发到路由模块 */ /*路由中间件是express自带的中间件,使用步骤有4个 1.在router.js中导入express: const express = require('express'); 2.在router.js中创建路由容器: let app = express(); 3.在router.js中导出路由容器: moudule.exports = app; 4.在index.js中使用路由容器: app.use(require('./router.js')) */ //4.使用路由模块 app.use(require('./router.js')); //开启服务器 app.listen(3000, () => { console.log('success'); }); ``` # 06-使用Express框架三大特性来重构项目 * index.js * 1.导入express模块 * 2.创建服务器 * 3.配置各种中间件 * 静态资源 * body-parser * 路由 * 4.启动服务器 ```javascript //1.导入模块 const express = require('express'); //2.创建服务器 let app = express(); //3.配置中间件 //3.1托管静态资源 app.use('/node_modules', express.static(__dirname + '/node_modules')); app.use('/views', express.static(__dirname + '/views')); //3.2 body-parser //(1)导入模块 var bodyParser = require('body-parser');//导入模块 // parse application/x-www-form-urlencoded //(2)使用中间件 app.use(bodyParser.urlencoded({ extended: false })) //3.3 配置路由中间件 app.use(require('./router.js')); //如果客户端请求了服务器没处理的请求,express会自动返回404 //4.启动服务器 app.listen(3001, () => { console.log('欢迎来到王者荣耀'); }); ``` * router.js ```javas //操作hero.json文件模块 const hero = require('./data/hero.js'); /* express路由使用流程 */ //1.导入express模块 var express = require('express'); //2.创建路由 var app = express(); //处理请求 //首页 app.get('/', (req, res) => { console.log(1111); //服务端重定向到view/heroList.html res.writeHead(302, { 'Location': 'views/heroList.html' }); res.end(); }); //英雄列表 app.get('/heroList', (req, res) => { //1.展示首页列表数据 hero.find((err, jsonData) => { console.log(jsonData); if (err) { throw err; } else { res.end(jsonData); }; }); }); //添加英雄 app.post('/heroAdd', (req, res) => { //完成解析之后,将得到的数据存入json文件 hero.add(req.body, (err) => { if (err) { //服务端不能直接返回js对象,因为服务器是给所有客户端使用,需要返回json对象 res.end(JSON.stringify({ err_code: 500, err_msg: err })); } else { res.end(JSON.stringify({ err_code: 0, err_msg: 'success' })); } }); }); //查询英雄 app.get('/heroInfo', (req, res) => { var heroID = req.query.id; //2.处理 hero.find(heroID, (err, data) => { if (err) { throw err; } else { res.end(data); }; }); }); //删除英雄 app.get('/heroDelete',(req,res)=>{ //(1)获取请求参数 let heroID = req.query.id; //(2)处理请求 hero.delete(heroID, (err) => { if (err) { throw (err); } else { //服务端重定向刷新首页 res.writeHead(302, { 'Location': 'views/heroList.html' }); res.end(); } }); }); //3.导出路由模块 module.exports = app; ``` # 07-服务端MVC架构介绍 MVC架构本质:确定每一个js文件的职责 * index.js:负责接收请求 * router.js:负责将请求分发给C层 * controller.js:C层负责处理业务逻辑(V与M之间的沟通) * views:V层:负责展示页面 * model: M层:负责处理数据(增删改查) ![1550773661089](day04.assets/1550773661089.png) ![1550772980676](day04.assets/1550772980676.png) ![1550773152421](day04.assets/1550773152421.png) ```javascript /* 路由模块:只负责分发网络请求给C层,不处理 */ //导入C层 const controller = require('./controller.js'); //1.导入express模块 const express = require('express'); //2.创建路由 var app = express(); //路由分发 //Express支持链式语法 app.get('/',controller.showHeroList) .get('/heroList',controller.getHeroList) .post('/heroAdd',controller.doHeroAdd) .get('/heroInfo',controller.getHeroInfo) .get('/heroDelete',controller.doHeroDelete); //3.导出路由模块 module.exports = app; ``` ```javascript /* C层:负责业务逻辑处理:M与C层之间的沟通 */ //M层:操作数据库增删改查 const hero = require('./model/hero.js'); module.exports = { showHeroList: (req, res) => { //服务端重定向到view/heroList.html res.writeHead(302, { 'Location': 'views/heroList.html' }); res.end(); }, getHeroList: (req, res) => { //1.展示首页列表数据 hero.find((err, jsonData) => { console.log(jsonData); if (err) { throw err; } else { res.end(jsonData); }; }); }, doHeroAdd: (req, res) => { //完成解析之后,将得到的数据存入json文件 hero.add(req.body, (err) => { if (err) { //服务端不能直接返回js对象,因为服务器是给所有客户端使用,需要返回json对象 res.end(JSON.stringify({ err_code: 100, err_msg: err.err_msg })); } else { res.end(JSON.stringify({ err_code: 0, err_msg: 'success' })); } }); }, getHeroInfo: (req, res) => { var heroID = req.query.id; //处理 hero.find(heroID, (err, data) => { if (err) { throw err; } else { res.end(data); }; }); }, doHeroDelete: (req, res) => { //(1)获取请求参数 let heroID = req.query.id; //(2)处理请求 hero.delete(heroID, (err) => { if (err) { throw (err); } else { //服务端重定向刷新首页 res.writeHead(302, { 'Location': 'views/heroList.html' }); res.end(); } }); } } ```
C#
UTF-8
1,788
3.046875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using Todo01.Infrastructure.Persistence.Model; namespace Todo01.Infrastructure.Persistence.Repositories { public class TodoRepository { public IList<TodoItem> All(DateTime fromDate, DateTime toDate, TaskStatus state) { using (var db = new TodoDatabase()) { var tasks = (from t in db.TodoItems where t.DueDate >= fromDate.Date && t.DueDate <= toDate.Date && ((int) t.State <= (int) state) orderby t.State descending, t.DueDate select t).ToList(); return tasks; } } public int Save(TodoItem task) { using (var db = new TodoDatabase()) { db.TodoItems.Add(task); db.SaveChanges(); } return task.Id; } public void Update(int id, TaskStatus state) { using (var db = new TodoDatabase()) { var task = (from t in db.TodoItems where t.Id == id select t).FirstOrDefault(); if (task == null) return; // NB: THIS IS A CRUD APPROACH task.State = state; db.SaveChanges(); } } public void Delete(int id) { using (var db = new TodoDatabase()) { var task = (from t in db.TodoItems where t.Id == id select t).FirstOrDefault(); if (task == null) return; db.TodoItems.Remove(task); db.SaveChanges(); } } } }
PHP
UTF-8
564
2.78125
3
[]
no_license
<?php /** * An application... It doesn't do much yet! */ class Model_Application extends RedBean_SimpleModel { /** * Returns a nicer formatter name for the select-box base in the application path(path on the dev server) * @return string */ public function getName() { $a = explode('/', $this->path); return $a[(count($a) - 2)] . ' - ' . $a[(count($a) - 1)]; } /** * */ public function getProjectName() { $a = explode('/', $this->path); return $a[(count($a) - 1)]; } public function update() { unset($this->uniqueIdentifier); } }
Swift
UTF-8
983
2.640625
3
[]
no_license
// // Model.swift // ListOfPlan // // Created by admin on 20.06.2020. // Copyright © 2020 admin. All rights reserved. // import Foundation import UIKit import RealmSwift import UserNotifications class Items : Object { @objc dynamic var name = "" @objc dynamic var date : Date = Date() @objc dynamic var completed = false } func setNotification(item:Items) { let content = UNMutableNotificationContent() content.title = "DO NOT FORGET:" content.body = item.name content.sound = UNNotificationSound.default let targetDate = item.date let trigger = UNCalendarNotificationTrigger(dateMatching:Calendar.current.dateComponents([.year, .month, .day, .hour, .minute],from: targetDate),repeats: false) let reguest = UNNotificationRequest(identifier: "notification", content: content, trigger: trigger) UNUserNotificationCenter.current().add(reguest) { (error) in print(error?.localizedDescription as Any) } }
JavaScript
UTF-8
1,300
2.734375
3
[]
no_license
var levelsStartingPoint = []; levelsStartingPoint.push({x: 560, y: 31}); var levels = []; // CODE: // 1, 2 = WALLS // 3, N = DOORS, N = Associated Lever // 4, N = SPIKE, N = Delay to trigger in seconds // 100 = POWER UP // 5 = COFFIN // 0 = EMPTY SPACE // 70, N = PORTAL, N = Destination var level1 = []; level1.push([1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]); level1.push([1,0,0,0,[3,7],0,7,0,0,[3,8],0,0,8,[4,4],0,0,100,100,0,0,1]); level1.push([1,0,2,2,2,1,1,1,1,1,1,1,1,1,1,1,0,0,0,0,1]); level1.push([1,0,2,0,2,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1]); level1.push([1,0,0,0,0,100,100,1,0,0,0,0,0,0,0,0,0,0,0,0,1]); level1.push([1,0,0,2,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,1]); level1.push([1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]); level1.push([1,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,1]); level1.push([1,1,1,[4,1],[4,1],1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]); level1.push([1,0,0,1,1,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1]); level1.push([1,0,0,1,1,0,0,0,0,0,0,0,1,0,1,0,1,0,0,0,1]); level1.push([1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]); level1.push([1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]); level1.push([1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1]); level1.push([1,0,0,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,5,1]); level1.push([1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1]); levels.push(level1);
Java
UTF-8
2,022
2.40625
2
[]
no_license
package com.appatstudio.epicdungeontactics2.screens.game.gameScreen.actions.characterActions; import static com.appatstudio.epicdungeontactics2.global.WorldConfig.TILE_SIZE; import com.appatstudio.epicdungeontactics2.global.WorldConfig; import com.appatstudio.epicdungeontactics2.global.enums.SpellEnum; import com.appatstudio.epicdungeontactics2.global.primitives.CoordsFloat; import com.appatstudio.epicdungeontactics2.screens.game.gameScreen.characters.CharacterDrawable; import com.badlogic.gdx.scenes.scene2d.actions.Actions; import com.badlogic.gdx.scenes.scene2d.actions.SequenceAction; import com.badlogic.gdx.scenes.scene2d.ui.Image; public class Shot extends SequenceAction { public Shot(CharacterDrawable attacker, CharacterDrawable target, Image projectile, SpellEnum effect, int dmg) { projectile.setSize(TILE_SIZE, TILE_SIZE); projectile.setOrigin(TILE_SIZE/2f, TILE_SIZE/2f); CoordsFloat start = new CoordsFloat( attacker.getTileStandingOn().getPositionFloat().x, attacker.getTileStandingOn().getPositionFloat().y ); CoordsFloat end = new CoordsFloat( target.getTileStandingOn().getPositionFloat().x, target.getTileStandingOn().getPositionFloat().y ); float projectileRotation = (float) Math.toDegrees(Math.atan2( end.y - start.y, end.x - start.x)); projectileRotation += 220; //correction if (projectileRotation < 0) projectileRotation += 360; System.out.println("ROTATION: " + projectileRotation); System.out.println("SIZE: " + projectile.getWidth()); this.addAction(Actions.moveTo( start.x, start.y)); this.addAction(Actions.rotateTo(projectileRotation)); this.addAction( Actions.moveTo( end.x, end.y, WorldConfig.SHOT_DURATION )); } }
PHP
UTF-8
2,491
3.140625
3
[]
no_license
<? namespace App\Helper; /** * FormatHelper * */ class FormatHelper { private $lang; private $options; /** * FormatHelper constructor. */ public function __construct($options, $lang) { $this->options = $options; $this->setLang($lang); } public function currency($price) { $formatted = self::number($price, 2); $currency = $this->options[$this->lang]['currency']; return ($currency === null) ? $formatted : $formatted . ' ' . $currency; } public function currency3dec($price) { $formatted = self::number($price, 3); $currency = $this->options[$this->lang]['currency']; return ($currency === null) ? $formatted : $formatted . ' ' . $currency; } /** * Formats number (integer or float) SK, CZ locale default * * @param mixed $number * @param int $decimals number of decimal places * @param string $decPoint decimal separator * @param string $thoudsandsSep thousands separator * @param bool $trimZeros trim right zeros from float numbers? * * @return string */ public function number($number, $decimals = 2, $decPoint = '.', $thoudsandsSep = " ", $trimZeros = false) { $fixed = self::fixFloat($number); if (strpos($fixed, '.') === false) { //int $number = (int)$number; return number_format($number, 0, $decPoint, $thoudsandsSep); } else { //float $number = (float)$fixed; return ($trimZeros) ? rtrim(rtrim(number_format($number, $decimals, $decPoint, $thoudsandsSep), '0'), $decPoint) : number_format($number, $decimals, $decPoint, $thoudsandsSep); } } /** * Unifies float numbers. All "," are replaced with "." * * @param string $float * * @return string */ public function fixFloat($float) { return str_replace(',', '.', $float); } /** * @return mixed */ public function getLang() { return $this->lang; } /** * @param mixed $lang */ public function setLang($lang) { $this->lang = $lang; } /** * @return mixed */ public function getOptions() { return $this->options; } /** * @param mixed $options */ public function setOptions($options) { $this->options = $options; } }
Java
UTF-8
9,685
2.890625
3
[ "MIT" ]
permissive
package client; import java.io.*; import java.net.Socket; import java.util.Scanner; import java.util.logging.Level; import java.util.logging.Logger; import message.*; /** * A client application used for connecting to a chat server and talking to other online users. */ public class Client { /** * Construct a client that communicates with the specified server on the provided port. * * @param servAddress The server's ip address. * @param serverPort The server port. * @param usrName The user name used for identification purposes on the server. */ private Client(String servAddress, int serverPort, String usrName) { serverAddress = servAddress; nbPort = serverPort; userName = usrName; serverListen = true; crtMessagePrinter = new MessagePrinterConsole(""); crtListener = null; } /** * Construct a client that communicates with the specified server on the provided port. * * @param servAddress The server's ip address. * @param serverPort The server port. * @param usrName The user name used for identification purposes on the server. * @param msgPrinter The message printer where the output will be printed in. (only for a non console application) */ public Client(String servAddress, int serverPort, String usrName, MessagePrinter msgPrinter) { serverAddress = servAddress; nbPort = serverPort; userName = usrName; serverListen = true; crtMessagePrinter = msgPrinter; crtListener = null; } private synchronized boolean listenerStopped() { return !serverListen; } /** * Send a message to the chat server. * * @param crtMessage The message to be sent. */ public void SendMessage(MsgBase crtMessage) { try { outputStream.writeObject(crtMessage); } catch (Exception e) { crtMessagePrinter.setString(ClientStrTab.STREAM_COMM_ERR.toString()); crtMessagePrinter.flushString(); } } /** * Start the current client app and connect to the specified server on the specified port. * * @return Indicates if the communication has been established */ public boolean start() { try { crtSocket = new Socket(serverAddress, nbPort); } catch (Exception e) { crtMessagePrinter.setString(ClientStrTab.ERR_CONN_SERVER.toString()); crtMessagePrinter.flushString(); return false; } crtMessagePrinter.setString(String.format(ClientStrTab.SRV_CONN_SUCCESSFUL.toString(), crtSocket.getInetAddress().toString(), nbPort)); crtMessagePrinter.flushString(); try { outputStream = new ObjectOutputStream(crtSocket.getOutputStream()); inputStream = new ObjectInputStream(crtSocket.getInputStream()); } catch (Exception e) { crtMessagePrinter.setString(ClientStrTab.STREAM_COMM_ERR.toString()); crtMessagePrinter.flushString(); return false; } crtListener = new Thread(new SrvEvListener()); crtListener.start(); try { MsgBase connectMsg = MessageFactory.createMessage(MessageType.CONNECT, userName, ""); outputStream.writeObject(connectMsg); } catch (Exception e) { crtMessagePrinter.setString(ClientStrTab.STREAM_COMM_ERR.toString()); crtMessagePrinter.flushString(); return false; } return true; } /** * Close the currently input and output streams. */ private void closeStreams() { try { inputStream.close(); outputStream.close(); } catch (IOException e) { crtMessagePrinter.setString(ClientStrTab.ERR_CLOSING_RES.toString()); crtMessagePrinter.flushString(); } } /** * Close the current socket used to communicate with the server. */ private void closeSocket() { try { crtSocket.close(); } catch (IOException ex) { crtMessagePrinter.setString(ClientStrTab.ERR_CLOSING_RES.toString()); crtMessagePrinter.flushString(); } } /** * Disconnect the current client from the server. */ public void disconnectFromServer() { serverListen = false; try { crtListener.join(); } catch (InterruptedException ex) { Logger.getLogger(Client.class.getName()).log(Level.SEVERE, null, ex); } closeStreams(); closeSocket(); } public static void main(String[] args) { int nbArgs = args.length; int portNb; if (nbArgs != 3) { System.out.println(ClientStrTab.IMPROPER_CMD_LINE.toString()); } else { String srvString = args[0]; String portString = args[1]; String userString = args[2]; if (!portString.matches("-\\d+")) { System.out.println(ClientStrTab.IMPROPER_CMD_LINE.toString()); } else { String srvParse = srvString.replaceFirst("-", ""); String portNbParse = portString.replaceFirst("-", ""); String usrParse = userString.replaceFirst("-", ""); portNb = Integer.parseInt(portNbParse); Client clInstance = new Client(srvParse, portNb, usrParse); clInstance.start(); Scanner commandScanner = new Scanner(System.in); MsgBase disconnectMsg = MessageFactory.createMessage(MessageType.DISCONNECT, usrParse, ""); MsgBase listUsrMsg = MessageFactory.createMessage(MessageType.LIST_ACTIVE_USERS, usrParse, ""); MsgBase messageMsg = MessageFactory.createMessage(MessageType.MESSAGE, usrParse, ""); while (true) { String command = commandScanner.nextLine(); if (command.equalsIgnoreCase(MessageType.DISCONNECT.toString())) { clInstance.SendMessage(disconnectMsg); clInstance.disconnectFromServer(); clInstance.crtMessagePrinter.setString(ClientStrTab.DISCONNECTED.toString()); clInstance.crtMessagePrinter.flushString(); } else if (command.equalsIgnoreCase(MessageType.LIST_ACTIVE_USERS.toString())) { clInstance.SendMessage(listUsrMsg); } else { MessageMsg msg = (MessageMsg) messageMsg; msg.setBody(command); clInstance.SendMessage(msg); } } } } } // - Members private ObjectInputStream inputStream; private ObjectOutputStream outputStream; private Socket crtSocket; private final String serverAddress, userName; private final int nbPort; private volatile boolean serverListen; private final MessagePrinter crtMessagePrinter; private Thread crtListener; /** * A threaded class that acts as a listener for server events. */ class SrvEvListener implements Runnable { @Override public void run() { while (true) { try { Object messageReceived = inputStream.readObject(); MsgBase baseMsg = (MsgBase) messageReceived; MessageType msgType = baseMsg.getMessageType(); String messageStringOutput; if (msgType == MessageType.MESSAGE) { MessageMsg msgObject = (MessageMsg) baseMsg; messageStringOutput = msgObject.getSenderID() + " : " + msgObject.getMessageBody(); } else messageStringOutput = baseMsg.getSenderID() + " : " + baseMsg.getMessageType().toString(); if (listenerStopped()) return; crtMessagePrinter.setString(messageStringOutput); crtMessagePrinter.flushString(); } catch (IOException | ClassNotFoundException e) { // - if I reach this line this means that the server already closed the streams and sockets for the crt user crtMessagePrinter.setString(ClientStrTab.SRV_CONN_CLOSED.toString()); crtMessagePrinter.flushString(); break; } } } } /** * Terminal message printer class for flushing strings */ class MessagePrinterConsole extends MessagePrinter { /** * Create a printer that contains the associated message * @param msg Message body */ MessagePrinterConsole(String msg) { super(msg); } /** * Flush the specified string */ @Override public void flushString() { System.out.println(crtString); } } }
JavaScript
UTF-8
3,551
2.90625
3
[]
no_license
var URL = "http://localhost:8080/projeto-teste/rs/setor"; var botaoEnviar = document.getElementById("enviar"); var botaoAtualizar = document.getElementById("atualizar"); const HTTP_STATUS_OK = 200; const HTTP_STATUS_CREATED = 201; window.addEventListener("load", function(event) { temDadosLocalStorage(); }); botaoEnviar.addEventListener("click", function (event) { event.preventDefault(); if(validaVazioOuNulo(formulario.nome)){ var id = document.getElementById('id').value; var json = serialize(); var xhttp = new XMLHttpRequest(); xhttp.open("POST", URL, true); xhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); xhttp.send(json); xhttp.onreadystatechange = function(){ if(xhttp.readyState === XMLHttpRequest.DONE){ if(xhttp.status == HTTP_STATUS_CREATED){ exibeToast(xhttp.responseText); } else { exibeToast("Error ao adicionar setor"); } } } } }); botaoAtualizar.addEventListener("click", function (event){ event.preventDefault(); if(validaVazioOuNulo(formulario.nome)){ var id = document.getElementById('id').value; var json = serialize(); var xhttp = new XMLHttpRequest(); xhttp.open("PUT",URL.concat('/', id), true); xhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8"); xhttp.send(json); xhttp.onreadystatechange = function(){ if(xhttp.readyState === XMLHttpRequest.DONE){ if(xhttp.status == HTTP_STATUS_OK){ exibeToast(xhttp.responseText); initDadosForm(); } else { exibeToast("Error ao atualizar setor"); } } } } }); function temDadosLocalStorage(){ if(localStorage.getItem('idSetor')){ var id = localStorage.getItem('idSetor'); localStorage.removeItem('idSetor'); var xhttp = new XMLHttpRequest(); xhttp.open("GET", URL.concat('/', id), true); xhttp.send(); xhttp.onreadystatechange = function() { if (xhttp.status == HTTP_STATUS_OK) { var setor = JSON.parse(xhttp.responseText); preencheDadosForm(setor); exibeBotaoAtualizarEOcultaBotaoEnviar(); } else { console.log("Algo deu errado"); } }; } } function exibeBotaoAtualizarEOcultaBotaoEnviar(){ document.getElementById('atualizar').style.display = 'inline'; document.getElementById('enviar').style.display = 'none'; } function preencheDadosForm(setor){ formulario.id.value = setor.id; formulario.nome.value = setor.nome; } function initDadosForm(){ formulario.id = ''; formulario.nome = ''; } var serialize = function () { var json = {}; var form = document.getElementById('formulario'); var data = new FormData(form); var keys = data.keys(); for (var key = keys.next(); !key.done; key = keys.next()) { var values = data.getAll(key.value); json[key.value] = values.length == 1 ? values[0] : values; } return JSON.stringify(json); } function validaVazioOuNulo(valor){ if(valor.value == '' || valor.value == null){ valor.focus(); exibeToast("Campo nome está vazio ou é nulo"); return false; } return true; } function exibeToast(mensagem){ document.getElementById("paragrafoToast").innerHTML = mensagem; $('#toastMensagem').toast('show'); }
Java
UTF-8
785
1.929688
2
[]
no_license
package com.wisrc.sys.webapp.dao; import com.wisrc.sys.webapp.entity.SysUserWorktileEntity; import org.apache.ibatis.annotations.Delete; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Select; @Mapper public interface SysUserWorktileDao { @Select("select worktile_id,username,access_token from sys_user_worktile where worktile_id = #{worktileId}") SysUserWorktileEntity findById(String worktileId); @Insert("insert into sys_user_worktile(worktile_id, username, access_token) values(#{worktileId}, #{username}, #{accessToken})") void insert(SysUserWorktileEntity ele); @Delete("delete from sys_user_worktile where worktile_id = #{worktileId}") void delete(String worktileId); }
C++
UTF-8
3,262
2.890625
3
[ "ISC", "BSD-3-Clause", "Apache-2.0" ]
permissive
#pragma once #include <jni/functions.hpp> #include <jni/object.hpp> #include <jni/array.hpp> namespace jni { template < char... chars > struct StringLiteral { operator const char *() const { static const char result[] = { chars..., 0 }; return result; } }; constexpr std::size_t StringLiteralLength(const char * str, std::size_t len = 0) { return str[0] ? StringLiteralLength(str + 1, len + 1) : len; } template < class, class > struct TagLiteralImpl; template < class Tag, std::size_t... Is > struct TagLiteralImpl< Tag, std::index_sequence<Is...> > { using Value = StringLiteral< Tag::Name()[Is]... >; }; template < class Tag > using TagLiteral = typename TagLiteralImpl< Tag, std::make_index_sequence<StringLiteralLength(Tag::Name())> >::Value; template < char... As, char... Bs > constexpr auto Concat(const StringLiteral<As...>&, const StringLiteral<Bs...>&) { return StringLiteral<As..., Bs...>(); } template < class A, class B, class... Rest > constexpr auto Concat(const A& a, const B& b, const Rest&... rest) { return Concat(Concat(a, b), rest...); } template < class > struct TypeSignature; template <> struct TypeSignature< jboolean > { constexpr auto operator()() const { return StringLiteral<'Z'>(); } }; template <> struct TypeSignature< jbyte > { constexpr auto operator()() const { return StringLiteral<'B'>(); } }; template <> struct TypeSignature< jchar > { constexpr auto operator()() const { return StringLiteral<'C'>(); } }; template <> struct TypeSignature< jshort > { constexpr auto operator()() const { return StringLiteral<'S'>(); } }; template <> struct TypeSignature< jint > { constexpr auto operator()() const { return StringLiteral<'I'>(); } }; template <> struct TypeSignature< jlong > { constexpr auto operator()() const { return StringLiteral<'J'>(); } }; template <> struct TypeSignature< jfloat > { constexpr auto operator()() const { return StringLiteral<'F'>(); } }; template <> struct TypeSignature< jdouble > { constexpr auto operator()() const { return StringLiteral<'D'>(); } }; template <> struct TypeSignature< void > { constexpr auto operator()() const { return StringLiteral<'V'>(); } }; template < class TheTag > struct TypeSignature< Object<TheTag> > { constexpr auto operator()() const { return Concat(StringLiteral<'L'>(), TagLiteral<TheTag>(), StringLiteral<';'>()); } }; template < class E > struct TypeSignature< Array<E> > { constexpr auto operator()() const { return Concat(StringLiteral<'['>(), TypeSignature<E>()()); } }; template < class R, class... Args > struct TypeSignature< R (Args...) > { constexpr auto operator()() const { return Concat(StringLiteral<'('>(), TypeSignature<Args>()()..., StringLiteral<')'>(), TypeSignature<R>()()); } }; }
C#
UTF-8
4,342
3.765625
4
[]
no_license
//You are given a tree of N nodes represented as a set of N-1 pairs //of nodes (parent node, child node), each in the range (0..N-1). //Write a program to read the tree and find: //a) the root node //b) all leaf nodes //c) all middle nodes //d)* the longest path in the tree //e)* all paths in the tree with given sum S of their nodes //f)* all subtrees with given sum S of their nodes using System; using System.Collections.Generic; using System.Linq; namespace Task1TreeManipulation { class TreeManipulation { static Node<int> FindRoot(Node<int>[] nodes) { var hasParent = new bool[nodes.Length]; foreach (var node in nodes) { foreach (var child in node.Children) { hasParent[child.Value] = true; } } for (int i = 0; i < hasParent.Length; i++) { if (!hasParent[i]) { return nodes[i]; } } throw new ArgumentException("nodes", "The tree has no root."); } static List<Node<int>> FindLeaf(Node<int>[] nodes) { List<Node<int>> leaves = new List<Node<int>>(); foreach (var node in nodes) { if (node.Children.Count == 0) { leaves.Add(node); } } if (leaves.Count == 0) { throw new ArgumentException("The tree has no leaves."); } return leaves; } private static List<Node<int>> FindMiddleNode(Node<int>[] nodes) { List<Node<int>> middleNodes = new List<Node<int>>(); foreach (var node in nodes) { if (node.HasParent && node.Children.Count > 0) { middleNodes.Add(node); } } return middleNodes; } private static int TreeHeight(Node<int> root) { if (root.Children.Count == 0) { return 0; } int maxPath = 0; foreach (var node in root.Children) { maxPath = Math.Max(maxPath, TreeHeight(node)); } return maxPath + 1; } static void Main(string[] args) { int n = int.Parse(Console.ReadLine()); var nodes = new Node<int>[n]; //Creating new empty tree for (int i = 0; i < n; i++) { nodes[i] = new Node<int>(i); } //Initializing the tree for (int i = 1; i <= n - 1; i++) { string edgeAsString = Console.ReadLine(); var edgeParts = edgeAsString.Split(' '); int parentID = int.Parse(edgeParts[0]); int childID = int.Parse(edgeParts[1]); nodes[parentID].Children.Add(nodes[childID]); nodes[childID].HasParent = true; } //Task A - find the root of the tree var root = FindRoot(nodes); Console.WriteLine("The root of the tree is: {0}", root.Value); //Task B - find all leaves var leaves = FindLeaf(nodes); Console.WriteLine("The leaves it the tree are:"); foreach (var leaf in leaves) { Console.Write("{0} ", leaf.Value); } //Task C - find all middle nodes var middleNodes = FindMiddleNode(nodes); Console.WriteLine("The leaves it the tree are:"); foreach (var node in middleNodes) { Console.Write("{0} ", node.Value); } //Task D - find the longest path from the root(height oh the tree) //and longest path var treeheight = TreeHeight(FindRoot(nodes)); Console.WriteLine("The height of the tree is: {0}", treeheight); //Task E - find all paths in the tree with given sum S of their nodes Console.Write("Enter the sum you want to check if it exists S= "); //int s = int.Parse(Console.ReadLine()); } } }