language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
C
UTF-8
2,382
2.53125
3
[]
no_license
/* * pwmdriver.c * * Created by Tobias Gall <toga@tu-chemnitz.eu> * Based on Adafruit's python code for PCA9685 16-Channel PWM Servo Driver * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. * * */ #include <math.h> #include "pwmdriver.h" void pwmSetup(__u8 addr, __u8 busnum) { rpiI2cSetup(addr, busnum); rpiI2cWrite(MODE1, 0x00); } void pwmSetPWMFreq(float_t freq) { float_t prescaleval = 25000000.0; prescaleval /= 4096.0; prescaleval /= freq; prescaleval -= 1.0; float_t prescale; prescale = floorf(prescaleval + 0.5); __u8 oldmode = rpiI2cRead8(MODE1); __u8 newmode = (oldmode & 0x7F) | 0x10; rpiI2cWrite(MODE1, newmode); __u8 pre_scale = floorf(prescale); rpiI2cWrite(PRESCALE, pre_scale); rpiI2cWrite(MODE1, oldmode); usleep(500); rpiI2cWrite(MODE1, oldmode | 0x80); } void pwmSetPWM(__u8 channel, __s16 on, __s16 off) { rpiI2cWrite(LED0_ON_L+4*channel, on & 0xFF); rpiI2cWrite(LED0_ON_H+4*channel, on >> 8); rpiI2cWrite(LED0_OFF_L+4*channel, off & 0xFF); rpiI2cWrite(LED0_OFF_H+4*channel, off >> 8); } void servosSetup() { rpiI2cWrite(LED0_ON_L, 0x00); rpiI2cWrite(LED0_ON_H, 0x00); rpiI2cWrite(LED1_ON_L, 0x00); rpiI2cWrite(LED1_ON_H, 0x00); } void servosSetSpeeds(__s16 left, __s16 right) { right = -right; if(left >= -5 && left <= 5) left = 0; else if(left < -100) left = 400-200; else if(left >= 100) left = 400+200; else left = 400 + (left*2); if(right >= -5 && right <= 5) right = 0; else if(right < -100) right = 404-200; else if(right >= 100) right = 404+200; else right = 404 + (right*2); rpiI2cWrite(LED0_OFF_L, left); rpiI2cWrite(LED0_OFF_H, left >> 8); rpiI2cWrite(LED1_OFF_L, right); rpiI2cWrite(LED1_OFF_H, right >> 8); }
Java
UTF-8
721
2.40625
2
[]
no_license
package com.zerobank.stepdefinitions; import com.zerobank.pages.PayBillsPage; import io.cucumber.java.en.When; import java.util.Map; public class AddNewPayee { @When("creates new payee using following information") public void creates_new_payee_using_following_information(Map<String,String> payeeInfo) { PayBillsPage payBillsPage = new PayBillsPage(); payBillsPage.txt_payeeName.sendKeys(payeeInfo.get("Payee Name")); payBillsPage.txt_payeeAddress.sendKeys(payeeInfo.get("Payee Address")); payBillsPage.txt_account.sendKeys(payeeInfo.get("Account")); payBillsPage.txt_payeeDetails.sendKeys(payeeInfo.get("Payee details")); payBillsPage.btn_add.click(); } }
Java
UTF-8
2,227
2
2
[]
no_license
package com.afiperu.ui.fragment; import android.os.Bundle; import android.view.View; import android.widget.ListView; import com.afiperu.AfiAppComponent; import com.afiperu.R; import com.afiperu.common.BaseFragment; import com.afiperu.common.BasePresenter; import com.afiperu.component.DaggerDocumentComponent; import com.afiperu.module.DocumentModule; import com.afiperu.presenter.DocumentPresenter; import com.afiperu.syncmodel.SyncDocument; import com.afiperu.ui.adapter.DocumentsAdapter; import com.afiperu.ui.viewmodel.DocumentView; import com.afiperu.util.NetworkManager; import java.util.List; import javax.inject.Inject; /** * Created by Nevermade on 20/10/2015. */ public class PeriodReportFragment extends BaseFragment implements DocumentView { @Inject DocumentPresenter presenter; @Inject DocumentsAdapter adapter; @Override public int getLayout() { return R.layout.documents; } @Override public void setUpComponent(AfiAppComponent appComponent) { DaggerDocumentComponent.builder() .afiAppComponent(appComponent) .documentModule(new DocumentModule(this)) .build() .inject(this); } @Override protected BasePresenter getPresenter() { return null; } @Override public void prepareView(View rootView, Bundle args, Bundle savedInstanceState){ ListView docsList = (ListView)rootView.findViewById(R.id.docs_list); docsList.setAdapter(adapter); docsList.setEmptyView(rootView.findViewById(R.id.empty_docs_list)); if(NetworkManager.isNetworkConnected(getContext())){ rootView.findViewById(R.id.progress_bar).setVisibility(View.VISIBLE); } presenter.getAllDocuments(getContext(), 1); } @Override public void displayDocuments(List<SyncDocument> documents) { adapter.update(documents); if(getView() != null) { getView().findViewById(R.id.progress_bar).setVisibility(View.GONE); } } @Override public void onFailure(){ if(getView() != null) { getView().findViewById(R.id.progress_bar).setVisibility(View.GONE); } } }
Markdown
UTF-8
1,482
2.515625
3
[]
no_license
### Helper for teaching universal remotes custom codes. Normally, a remote controle is used to create a lirc configuratiomn file by using `irrecord`. The project provides the tools for doing the reverse. Create a config file manually, then, teach the codes to a universal remote control. ### 1. Hardware - Nodemcu - BC337 Transistor - 1KΩ Resistor - 47Ω Resistor - IR LED 940nm ![schematics](hardware.png) ![schematics](hardware.jpg) ### 2. IRremoteESP8266 Installation 1. Click the _"Sketch"_ -> _"Include Library"_ -> _"Manage Libraries..."_ Menu items. 2. Enter `IRremoteESP8266` into the _"Filter your search..."_ top right search box. 3. Click on the IRremoteESP8266 result of the search. 4. Select the version you wish to install and click _"Install"_. > Update your wifi & password in the `esp8266-ir.ino` source file then compile and upload `esp8266-ir.ino` ### 3. LIRC Copy `irc.default` as `lirc.conf` and add the customized IR codes, then copy it to the required device ``` sudo systemctl restart lirc ``` ### 4. Configure your universal remote control > update the ESP8266 IP address in the `remote.py` (`server_ip`) Start the server (`python remote.py`) on your local machine and go to: `http://127.0.0.1:8989/` The page will show you al list of button name configured in `lirc.conf` and when clicked it would send a request to the NodeMCU which in turn will send the respective IR code. Follow the remote control instruction to learn new codes
Python
UTF-8
2,010
3.84375
4
[]
no_license
#!/usr/bin/python3 # text.py by Barron Stone # This is an exercise file from Python GUI Development with Tkinter on lynda.com from tkinter import * #create top level window root = Tk() #create text box text = Text(root, width = 40, height = 10) text.pack() #wraps text and ends at the nearst word text.config(wrap = 'word') #1.0 would be the beginning of the text box, end refers to the last character of the text box #which will return the entire contents of the text box print(text.get('1.0', 'end')) #after the last character in line 1 print(text.get('1.0', '1.end')) #inserting, deleting and replacing by indexes that are passed text.insert('1.0 + 2 lines', 'Inserted message') text.insert('1.0 + 2 lines lineend', ' and\nmore and\nmore.') text.delete('1.0') text.delete('1.0', '1.0 lineend') text.delete('1.0', '3.0 lineend + 1 chars') text.replace('1.0', '1.0 lineend', 'This is the first line.') #text config method to set the states text.config(state = 'disabled') text.delete('1.0', 'end') #setting the state back to normal text.config(state = 'normal') text.tag_add('my_tag', '1.0', '1.0 wordend') text.tag_configure('my_tag', background = 'yellow') text.tag_remove('my_tag', '1.1', '1.3') print(text.tag_ranges('my_tag')) print(text.tag_names()) text.replace('my_tag.first', 'my_tag.last', 'That was') text.tag_delete('my_tag') #marks specify a single position which exist betwen two characters text.mark_names() text.insert('insert', '_') text.mark_set('my_mark', 'end') #gravity method either left or right to see where the mark will follow text.mark_gravity('my_mark', 'right') #removes mark text.mark_unset('my_mark') image = PhotoImage(file = 'python_logo.gif').subsample(5, 5) # Change path as needed text.image_create('insert', image = image) text.image_create('insert', image = image) #creating a button as a child of the text widget button = Button(text, text = 'Click Me') #passing the index and window property text.window_create('insert', window = button) root.mainloop()
Python
UTF-8
4,235
3.234375
3
[]
no_license
import nltk nltk.download('gutenberg') from nltk.corpus import gutenberg from nltk import bigrams, trigrams from collections import Counter, defaultdict import random class ngram: model = defaultdict(lambda: defaultdict(lambda: 0)) cur_index=0 def __init__(self, wordlist): self.wordlist=list(wordlist) self.listlength=len(wordlist) self.wordused=[0]*len(wordlist) self.threshold=0.01 def train(self): self.model = defaultdict(lambda: defaultdict(lambda: 0)) for sentence in gutenberg.sents(): for a, b, c in trigrams(sentence, pad_right=True, pad_left=True): if not(a=='None' or b=='None' or c=='None'): if(isinstance(a, str) and isinstance(b, str) and isinstance(c, str)): if not (a.isdigit() or b.isdigit() or c.isdigit()): self.model[(a,b)][c]+=1 else: self.model[(a,b)][c]+=1 for a_b in self.model: total=float(sum(self.model[a_b].values())) for c in self.model[a_b]: self.model[a_b][c]/=total def starting_bigram(self): bigrams=[['She','was'],['It','was'],['She','was'],['I','thought'],['I','have'],['To','be'],['That','is'],['Well',','],['I','was'],['I','wonder']] chosen=random.choice(bigrams) return chosen #safe words: afraid def generate(self): starting_words=self.starting_bigram() cur_word=0 words_done=0 sentence_end=0 cur_bigram=[starting_words[0],starting_words[1]] sent=[starting_words[0],starting_words[1]] sent_length=0 self.wordlist.append('edhfjeifkgjrjdf') while(sentence_end==0): new_word=self.choose_word(self.wordlist[cur_word],cur_bigram) if (new_word == self.wordlist[cur_word]): cur_word+=1 if (cur_word == self.listlength): words_done=1 if (new_word=='#END'): sentence_end=1 new_word=' ' if (words_done == 1): if (new_word=='.' or new_word==';' or new_word=='!' or new_word=='?' or new_word=='#END'): sentence_end=1 if (new_word == ';' or new_word =='#END'): new_word='.' cur_bigram[0]=cur_bigram[1] cur_bigram[1]=new_word if (new_word is not None): sent.append(new_word) sent_length+=1 if (sent_length>100): sentence_end=1 self.cur_index=cur_word print(sent) return sent def choose_word(self, ourword,cur_bigram): ourword_used=0 chosen_word='' bag=[] for word in self.model[cur_bigram[0],cur_bigram[1]]: if (self.model[cur_bigram[0],cur_bigram[1]].get(word) >= self.threshold): if word==ourword: print(word) chosen_word=word ourword_used=True break if isinstance(word,str): if not word.isdigit(): bag.append(word) if (ourword_used)==False: if (len(bag)==0): chosen_word='#END' else: chosen_word=random.choice(bag) #print('Chosen word is',chosen_word) return chosen_word def generatetext(words): a=ngram(words) a.train() c=0 text=[] while(a.cur_index < a.listlength): s=a.generate() text = text + ["(" + str(c+1)+ ")"] + s if (c>4): break c+=1 return text def translations(words): lines=[line.strip() for line in open('indonesian.txt')] eng=[] man=[] translated=[] for line in lines: a,b=line.split() eng.append(a) man.append(b) for w in words: if w in eng: i=eng.index(w) else: i=0 translated.append(man[i]) print(translated) return translated
TypeScript
UTF-8
648
2.65625
3
[]
no_license
import { start, push, pull, stop, Callbag } from './callbag'; describe('start(talkback)', () => { it('returns a start identifiable signal', () => { const talkback = (() => null) as Callbag; expect(start(talkback).isStart).toBe(true); }); }); describe('createPush(value)', () => { it('returns a push identifiable signal', () => { expect(push(5).isPush).toBe(true); }); }); describe('pull()', () => { it('returns a pull identifiable signal', () => { expect(pull().isPull).toBe(true); }); }); describe('stop()', () => { it('returns a stop identifiable signal', () => { expect(stop().isStop).toBe(true); }); });
C#
UTF-8
3,064
2.640625
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Common.Logger.Log4Net; namespace Common.Logger { public interface ILogger { /// <summary> /// Log debug message /// </summary> /// <param name="message"> The debug message </param> /// <param name="args"> the message argument values </param> void Debug(string message,LoggerType type = LoggerType.FileRollingLogger); /// <summary> /// Log debug message /// </summary> /// <param name="message"> The message </param> /// <param name="exception"> Exception to write in debug message </param> /// <param name="args"></param> void Debug(string message, Exception exception, LoggerType type = LoggerType.FileRollingLogger); /// <summary> /// Log debug message /// </summary> /// <param name="item"> The item with information to write in debug </param> void Debug(object item, LoggerType type = LoggerType.FileRollingLogger); /// <summary> /// Log FATAL error /// </summary> /// <param name="message"> The message of fatal error </param> /// <param name="args"> The argument values of message </param> void Fatal(string message, LoggerType type = LoggerType.FileRollingLogger); /// <summary> /// log FATAL error /// </summary> /// <param name="message"> The message of fatal error </param> /// <param name="exception"> The exception to write in this fatal message </param> void Fatal(string message, Exception exception, LoggerType type = LoggerType.FileRollingLogger); /// <summary> /// Log message information /// </summary> /// <param name="message"> The information message to write </param> /// <param name="args"> The arguments values </param> void Info(string message, LoggerType type = LoggerType.FileRollingLogger); /// <summary> /// Log warning message /// </summary> /// <param name="message"> The warning message to write </param> /// <param name="args"> The argument values </param> void Warning(string message, LoggerType type = LoggerType.FileRollingLogger); /// <summary> /// Log error message /// </summary> /// <param name="message"> The error message to write </param> /// <param name="args"> The arguments values </param> void Error(string message, LoggerType type = LoggerType.FileRollingLogger); /// <summary> /// Log error message /// </summary> /// <param name="message"> The error message to write </param> /// <param name="exception"> The exception associated with this error </param> /// <param name="args"> The arguments values </param> void Error(string message, Exception exception, LoggerType type = LoggerType.FileRollingLogger); } }
JavaScript
UTF-8
472
4.09375
4
[]
no_license
// https://codingdojo.org/kata/FizzBuzz/ for (let i = 1; i <= 50; i++) { let m = "" if (i % 3 === 0) { m += "Fizz" } if (i % 5 === 0) { m += "Buzz" } if (m === "") { m = i} console.log(m) } function fizzbuzz(x) { let m = "" if (x % 3 === 0) { m += "Fizz" } if (x % 5 === 0) { m += "Buzz" } if (m === "") { m = x.toString() } return m } let arr = Array.from({length: 50}, (_, i) => i +1).map(x => fizzbuzz(x) ) console.log(arr)
Markdown
UTF-8
5,724
2.796875
3
[]
no_license
# Transformers on Bounded Dyck Languages Code for ACL 2021 paper [Self-Attention Networks Can Process Bounded Hierarchical Languages](https://arxiv.org/abs/2105.11115) ## Getting started * Install the required packages. ``` pip install -r requirements.txt ``` * Evaluate different positional encoding schemes (Figure 4 (a)): ```bash for d in acl2021/experiments_embedding/*; do python src/run_lm.py ${d} done ``` * Compare Transformer and LSTM with different memory dims (Figure 4 (b, c)): ```bash for d in acl2021/experiments_memory/*; do python src/run_lm.py ${d} done ``` ## The config file for specifying experiments This repository exclusively uses `yaml` configuration files for specifying each experiment. Here's an explanation of what each part of the `yaml` configs means: The first portions specify the datasets' locations and properties of the specific Dyck-(k,m) language. For generating data with `rnns-stacks/generate_mbounded_dyck.py`, only this portion is needed. - `corpus`: - `train_corpus_loc`: The filepath for the training corpus - `dev_corpus_loc`: The filepath for the development corpus - `test_corpus_loc`: The filepath for the test corpus - `language`: - `train_bracket_types`: The number of unique bracket types, also _k_ in Dyck-(k,m) for the training set. - `train_max_length`: The maximum length of any training example - `train_min_length`: The minimum length of any training example - `train_max_stack_depth`: The maximum number of unclosed open brackets at any step of a training example - `train_sample_count`: Number of samples in tokens (!!) not lines, for the training set. - `dev_bracket_types`: The number of unique bracket types in the development set, also _k_ in Dyck-(k,m). - `dev_max_length`: The maximum length of any development example - `dev_min_length`: The minimum length of any development example - `dev_max_stack_depth`: The maximum number of unclosed open brackets at any step of a development example - `dev_sample_count`: Number of samples in tokens (!!) not lines, for the development set. - `test_bracket_types`: The number of unique bracket types, also _k_ in Dyck-(k,m) for the test set. - `test_max_length`: The maximum length of any test example - `test_min_length`: The minimum length of any test example - `test_max_stack_depth`: The maximum number of unclosed open brackets at any step of a test example - `test_sample_count`: Number of samples in tokens (!!) not lines, for the test set. Note that running an experiment training an LM with a specific `corpus` and `language` configuration doesn't generate the corresponding dataset; instead, you should first run `rnns-stacks/generate_mbounded_dyck.py` to generate the dataset, and then use `rnns-stacks/run_lm.py` to train and evaluate the LM. The next portions of the `yaml` configuration files is for specifying properties of the LSTM LMs. - `lm`: - `embedding_dim`: The dimensionality of the word embeddings. - `hidden_dim`: The dimensionality of the LSTM hidden states. - `lm_type`: Chooses RNN type; pick from RNN, GRU, LSTM. - `num_layers`: Chooses number of stacked RNN layers - `save_path`: Filepath (relative to reporting directory) where model parameters are saved. - `reporting`: - `reporting_loc`: Path specifying where to (optionally construct a folder, if it doesn't exist) to hold the output metrics and model parameters. - `reporting_methods`: Determines how to evaluate trained LMs. `constraints` provides an evaluation metric determining whether models know which bracket should be closed, whether the sequence can end, and whether an open bracket can be seen at each timestep. - `training`: - `batch_size`: Minibatch size for training. Graduate student descent has found that smaller batches seems to be better in general. (100: too big. 1: maybe the best? But very slow. 10: good) - `dropout`: Dropout to apply between the LSTM and the linear (softmax matrix) layer constructing logits over the vocabulary. - `learning_rate`: Learning rate to initialize Adam to. Note that a 0.5-factor-on-plateau decay is implemented; each time the learning rate is decayed, Adam is restarted. - `max_epochs`: Number of epochs after which to halt training if it has not already early-stopped. - `seed`: Doesn't actually specify random seed; used to distinguish multiple runs in summarizing results. Maybe should have specified random seeds, but wouldn't replicate across different GPUs anyway... ## Code layout - `generate_mbounded_dyck.py`: Code for generating samples from distributions over Dyck-(k,m). - `run_lm.py`: Code for running experiments with `yaml` configs. - `rnn.py`: Classes for specifying RNN models. - `transformer.py`: Classes for specifying Transformer models. - `lm.py`: Classes for specifying probability distributions given an encoding of the sequence. - `dataset.py`: Classes for loading and serving examples from disk. - `training_regimen.py`: Script for training an LM on samples - `reporter.py`: Classes for specifying how results should be reported on a given experiment. - `utils.py`: Provides some constants (like the Dyck-(k,m) vocabulary) as well as paths to corpora and results. ## Citation ``` @inproceedings{yao2021dyck, title={Self-Attention Networks Can Process Bounded Hierarchical Languages}, author={Yao, Shunyu and Peng, Binghui and Papadimitriou, Christos and Narasimhan, Karthik}, booktitle={Association for Computational Linguistics (ACL)}, year={2021} } ``` ## Acknowledgements The code heavily borrows from [dyckkm-learning](https://github.com/john-hewitt/dyckkm-learning). Thanks John! For any questions please contact Shunyu Yao `<shunyuyao.cs@gmail.com>`.
JavaScript
UTF-8
4,292
3.234375
3
[]
no_license
//Access children of a node var bodyChildren = document.body.children; console.log(bodyChildren); //To see the ul children var ulChildren = document.querySelector('ul'); console.log(ulChildren); //add a new child to the body //Html selctor pointing out var h1 = document.querySelector('h1'); var p = document.createElement('p'); var divselector = document.querySelector('div'); var textnode = document.createTextNode("Hey I am newly added"); console.log(divselector); p.append(textnode); divselector.append(p); //Adding paragraph var h1 = document.querySelector('h1'); var p = document.createElement('p'); var textnode = document.createTextNode('this is a next paragraph 4'); console.log(p); p.append(textnode); //Adding in class name is a html collection var newdiv = document.getElementsByClassName('new'); var p10 = document.createElement("p"); var node1 = document.createTextNode("Hey I am in the htmlCollection"); HTMLCollection.prototype.foreach = Array.prototype.forEach; newdiv.foreach(function(event){ event.node1; }) //add a new child to the body var para = document.createElement('li'); var text = document.createTextNode('Hey this is second ok'); para.appendChild(text); console.log(para); // Access a sibling var sibling = p1.nextElementSibling.nextElementSibling; console.log(sibling); //access first child and last var list = document.querySelector("ul"); console.log(list.firstChild); console.log(list.lastChild); // To go to the parent node var bmw = document.querySelector("li"); console.log(bmw.parentNode); //change new text/ Change the paragraph like java script is fun and html Style var p2 = document.getElementById("p2"); p2.innerHTML = "This is a fun lanugage"; p2.style.backgroundColor = "red"; p2.style.color = "white"; //Set attribute link var link = document.querySelector('a'); link.setAttribute('href', 'http://forcescabs.co.uk'); // using the foreach method, need to add new brand to each list: var newul = document.getElementsByTagName('ul'); newul.foreach(function(event){ event.innerHTML += "<li>Ford</li>"; event.style.backgroundColor = "Green"; event.style.color="white"; }) // by class name var pink = document.getElementsByClassName('green'); pink.foreach(function(event){ event.style.backgroundColor= "pink"; }) // //Remove a child Element // // var list1 = document.getElementById("list1"); // // var item1 = document.getElementById("item1"); // // list1.removeChild(item1); // //There is no any method for remove an item we need to build ourself // //Global cunstructure calle Element represent html element like .remove or any // // Element.prototype.remove = function(){ // // var parent = this.parentElement; // // parent.removeChild(this); // // } // // list1.remove(); // * Event listner Mouse down //All Element var button1 = document.getElementById("button1"); var img = document.querySelector("img"); button1.addEventListener('mousedown', fmousedown); function fmousedown(event){ if(event.which == 1){ newdiv.foreach(function(event){ event.innerHTML = "you clicked left button"; }); }; if(event.which == 3){ newdiv.foreach(function(event){ event.innerHTML = "you clicked right button"; }); } console.log(event); } //mouse move //mousemove addEventListener("mousemove", fmousemove); function fmousemove(event){ img.style.left = event.pageX + "px"; img.style.top = event.pageY + "px"; } addEventListener('mousedown',fmousedown); function fmousedown(event){ var img2 = document.createElement("img"); img2.setAttribute("src","http://pngimg.com/uploads/butterfly/butterfly_PNG1066.png"); img2.setAttribute("height","40px"); img2.setAttribute("width","40px"); img2.style.position = "fixed"; document.body.appendChild(img2); img2.style.left = event.pageX + "px"; img2.style.top = event.pageY + "px"; }
Python
UTF-8
1,302
3.46875
3
[]
no_license
import csv from collections import Counter with open("height-weight.csv", newline="")as f: reader=csv.reader(f) file_data = list(reader) file_data.pop(0) newData = [] for i in range(len(file_data)): n = file_data[i][1] newData.append(float(n)) #mean a = len(newData) total = 0 for x in newData: total += x mean = total/a print("mean: "+str(mean)) #median newData.sort() if a%2 == 0: m1 = float(newData[a//2]) m2 = float(newData[a//2-1]) median = (m1+m2)/2 else: meadian = newData[a//2] print("median: "+str(median)) #mode data = Counter(newData) mode_dataForRange = { "50-60": 0, "60-70": 0, "70-80": 0 } for height, occurance in data.items(): if 50<float(height)<60: mode_dataForRange["50-60"]+= occurance if 60<float(height)<70: mode_dataForRange["60-70"]+= occurance if 70<float(height)<80: mode_dataForRange["70-80"]+= occurance modeRange, modeOccurance = 0,0 for range, occurance in mode_dataForRange.items(): if occurance> modeOccurance: modeRange,modeOccurance = [int(range.split("-")[0]),int(range.split("-")[1])],occurance mode = float((modeRange[0]+modeRange[1])/2) print(f"mode: {mode:2f} " )
Java
UTF-8
9,253
2.203125
2
[ "Apache-2.0" ]
permissive
package com.youran.generate.pojo.po; import com.fasterxml.jackson.annotation.JsonIgnore; import com.youran.common.constant.ErrorCode; import com.youran.common.exception.BusinessException; import com.youran.generate.pojo.dto.MetaMtmEntityFeatureDTO; import java.util.List; import java.util.Objects; /** * 多对多关联关系 * * @author: cbb * @date: 2017/7/4 */ public class MetaManyToManyPO extends BasePO { private Integer mtmId; /** * 所属项目id */ private Integer projectId; /** * 关联表名 */ private String tableName; /** * 模式名 */ private String schemaName; /** * 关联描述 */ private String desc; /** * 实体A的id */ private Integer entityId1; /** * 实体B的id */ private Integer entityId2; /** * 实体A是否持有B引用 */ private Boolean holdRefer1; /** * 实体B是否持有A引用 */ private Boolean holdRefer2; /** * 实体A对应多对多关联表的id字段名 * 2019-08-07新增 */ private String entityIdField1; /** * 实体B对应多对多关联表的id字段名 * 2019-08-07新增 */ private String entityIdField2; /** * 是否需要自增id字段 * 2019-08-07新增 */ private Boolean needId; /** * id字段是否bigint * 2019-08-07新增 */ private Boolean bigId; /** * 特性json * 后续有新的特性直接往里加,省的再扩展新字段 */ private String feature; /** * 引用实体A */ @JsonIgnore private transient MetaEntityPO refer1; /** * 引用实体B */ @JsonIgnore private transient MetaEntityPO refer2; /** * 实体A持有的级联扩展列表 */ @JsonIgnore private transient List<MetaMtmCascadeExtPO> cascadeExtList1; /** * 实体B持有的级联扩展列表 */ @JsonIgnore private transient List<MetaMtmCascadeExtPO> cascadeExtList2; /** * 外键字段别名A-sql字段 */ @JsonIgnore private transient String fkAliasForSql1; /** * 外键字段别名B-sql字段 */ @JsonIgnore private transient String fkAliasForSql2; /** * 外键字段别名A-java字段 */ @JsonIgnore private transient String fkAliasForJava1; /** * 外键字段别名B-java字段 */ @JsonIgnore private transient String fkAliasForJava2; /** * 实体1特性 */ @JsonIgnore private transient MetaMtmEntityFeatureDTO f1; /** * 实体2特性 */ @JsonIgnore private transient MetaMtmEntityFeatureDTO f2; /** * 获取多对多实体特性 * * @param entityId * @return */ public MetaMtmEntityFeatureDTO getEntityFeature(Integer entityId) { if (Objects.equals(entityId, entityId1)) { return f1; } else if (Objects.equals(entityId, entityId2)) { return f2; } throw new BusinessException(ErrorCode.INNER_DATA_ERROR, "获取多对多实体特性异常,mtm_id=" + mtmId + ",entityId=" + entityId); } /** * 判断传入的实体id是否持有对方引用 * * @param entityId * @return */ public boolean isHold(Integer entityId) { if (Objects.equals(entityId, entityId1)) { return holdRefer1; } else if (Objects.equals(entityId, entityId2)) { return holdRefer2; } throw new BusinessException(ErrorCode.INNER_DATA_ERROR, "获取多对多实体是否持有引用异常,mtm_id=" + mtmId + ",entityId=" + entityId); } /** * 根据传入的实体id获取其对应的外键字段别名 * * @param entityId 实体id * @param forSql 是否sql字段 * @return */ public String getFkAlias(Integer entityId, boolean forSql) { if (Objects.equals(entityId, entityId1)) { if (forSql) { return fkAliasForSql1; } else { return fkAliasForJava1; } } else if (Objects.equals(entityId, entityId2)) { if (forSql) { return fkAliasForSql2; } else { return fkAliasForJava2; } } throw new BusinessException(ErrorCode.INNER_DATA_ERROR, "获取多对多外键字段别名异常,mtm_id=" + mtmId + ",entityId=" + entityId); } /** * 传入宿主实体id,获取宿主实体持有的级联扩展列表 * * @param entityId 宿主实体id * @return */ public List<MetaMtmCascadeExtPO> getCascadeExtList(Integer entityId) { if (Objects.equals(entityId1, entityId)) { return cascadeExtList1; } else if (Objects.equals(entityId2, entityId)) { return cascadeExtList2; } else { throw new BusinessException(ErrorCode.INNER_DATA_ERROR, "获取多对多级联扩展数据异常,mtm_id=" + mtmId + ",entityId=" + entityId); } } public String getSchemaName() { return schemaName; } public void setSchemaName(String schemaName) { this.schemaName = schemaName; } public String getDesc() { return desc; } public void setDesc(String desc) { this.desc = desc; } public String getTableName() { return tableName; } public void setTableName(String tableName) { this.tableName = tableName; } public MetaEntityPO getRefer2() { return refer2; } public void setRefer2(MetaEntityPO refer2) { this.refer2 = refer2; } public MetaEntityPO getRefer1() { return refer1; } public void setRefer1(MetaEntityPO refer1) { this.refer1 = refer1; } public Integer getMtmId() { return mtmId; } public void setMtmId(Integer mtmId) { this.mtmId = mtmId; } public Integer getProjectId() { return projectId; } public void setProjectId(Integer projectId) { this.projectId = projectId; } public Integer getEntityId1() { return entityId1; } public void setEntityId1(Integer entityId1) { this.entityId1 = entityId1; } public Integer getEntityId2() { return entityId2; } public void setEntityId2(Integer entityId2) { this.entityId2 = entityId2; } public Boolean getHoldRefer1() { return holdRefer1; } public void setHoldRefer1(Boolean holdRefer1) { this.holdRefer1 = holdRefer1; } public Boolean getHoldRefer2() { return holdRefer2; } public void setHoldRefer2(Boolean holdRefer2) { this.holdRefer2 = holdRefer2; } public String getEntityIdField1() { return entityIdField1; } public void setEntityIdField1(String entityIdField1) { this.entityIdField1 = entityIdField1; } public String getEntityIdField2() { return entityIdField2; } public void setEntityIdField2(String entityIdField2) { this.entityIdField2 = entityIdField2; } public Boolean getNeedId() { return needId; } public void setNeedId(Boolean needId) { this.needId = needId; } public Boolean getBigId() { return bigId; } public void setBigId(Boolean bigId) { this.bigId = bigId; } public List<MetaMtmCascadeExtPO> getCascadeExtList1() { return cascadeExtList1; } public void setCascadeExtList1(List<MetaMtmCascadeExtPO> cascadeExtList1) { this.cascadeExtList1 = cascadeExtList1; } public List<MetaMtmCascadeExtPO> getCascadeExtList2() { return cascadeExtList2; } public void setCascadeExtList2(List<MetaMtmCascadeExtPO> cascadeExtList2) { this.cascadeExtList2 = cascadeExtList2; } public String getFkAliasForSql1() { return fkAliasForSql1; } public void setFkAliasForSql1(String fkAliasForSql1) { this.fkAliasForSql1 = fkAliasForSql1; } public String getFkAliasForSql2() { return fkAliasForSql2; } public void setFkAliasForSql2(String fkAliasForSql2) { this.fkAliasForSql2 = fkAliasForSql2; } public String getFkAliasForJava1() { return fkAliasForJava1; } public void setFkAliasForJava1(String fkAliasForJava1) { this.fkAliasForJava1 = fkAliasForJava1; } public String getFkAliasForJava2() { return fkAliasForJava2; } public void setFkAliasForJava2(String fkAliasForJava2) { this.fkAliasForJava2 = fkAliasForJava2; } public String getFeature() { return feature; } public void setFeature(String feature) { this.feature = feature; } public MetaMtmEntityFeatureDTO getF1() { return f1; } public void setF1(MetaMtmEntityFeatureDTO f1) { this.f1 = f1; } public MetaMtmEntityFeatureDTO getF2() { return f2; } public void setF2(MetaMtmEntityFeatureDTO f2) { this.f2 = f2; } }
Java
UTF-8
436
1.851563
2
[]
no_license
package com.practice.springboot; import org.springframework.stereotype.Controller; import org.springframework.web.servlet.ModelAndView; @Controller public class HeloController4 { // @RequestMapping("/") public ModelAndView index(ModelAndView mav){ mav.setViewName("index2"); mav.addObject("msg", "current data"); DataObject obj = new DataObject(123,"hanako","hanako@flower"); mav.addObject("object",obj); return mav; } }
Markdown
UTF-8
2,422
2.578125
3
[]
no_license
# [Champiurns](http://www.reddit.com/r/twitchplayspokemon/comments/2belbz/tppbb_16_champiurns/) ## by [/u/SlowpokeIsAGamer](http://www.reddit.com/user/SlowpokeIsAGamer) **===Hall of Fame===** **Chloe**: I can't believe it, we actually made it.... **Voices**: So Jimmy never made it here after all.... **Chloe**: What? You were expecting to find Jimmy here? **Voices**: We'd left Jimmy thinking he would become champion on his own. He did beat the Elite 4, N, and Ghetsis; plus capture Reshiram. But he never did. **Chloe**: Well is that really a bad thing? I mean maybe Jimmy didn't want to be the very best trainer in Unova? **Voices**: Did you want to be the very best? **Chloe**: Well... yeah. **Voices**: But didn't you tell your mother you didn't want a Pokemon? **Chloe**: Yeah, I did. But that's because my mom always wanted me to become some fancy research assistant for Professor Juniper. I didn't want to just catch a few hundred Pokemon and get a certificate about it. I wanted to catch friends..... **Chloe**: …. Man that sounds weird. **Voices**: Yeah, it does. But we understand. Sharing an adventure can do that, it's like when we were with Camilla, or Alice, or Napoleon, or Jimmy. **Chloe**: Oh, what happened then? **Voices**: We learned stuff from them. Like how Pokemon can be friends, or how letting our hosts have a loose leash makes them less prone to striking out against us. --- **===Outside===** **Voices**: Well then, Chloe. Where to now? **Chloe**: Where? **Voices**: Yes, where? Anywhere in the world. **Chloe**: Isn't this the part where you leave me, though? I saved the region, you made me a champion, deal's done. **Voices**: Oh yes, well you see those deals are more of a suggestion. We don't have any reason to go if you don't want us to. **Chloe**: Well, in chat case, I recall N wanting to see us again. **Voices**: Ah yes, N. You know what, Chloe? **Chloe**: What? **Voices**: There are places out there where the sky is burning, the seas sleep, and the rivers dream. There are Pokemon the likes of which we've never seen. Somewhere there's people in danger, and injustice to Pokemon. Somewhere Pokemon aren't even allowed to evolve! **Chloe**: You mean other regions, right? **Voices**: Eventually, yes. But eventually is not today, and until then we're going to stay here and help make Unova a better place. So come on, Chloe, we have an N to go visit!
C
UTF-8
1,898
2.90625
3
[]
no_license
/* ************************************************************************** */ /* */ /* ::: :::::::: */ /* extract.c :+: :+: :+: */ /* +:+ +:+ +:+ */ /* By: arcohen <marvin@42.fr> +#+ +:+ +#+ */ /* +#+#+#+#+#+ +#+ */ /* Created: 2018/07/09 15:02:06 by arcohen #+# #+# */ /* Updated: 2018/07/20 12:23:36 by arcohen ### ########.fr */ /* */ /* ************************************************************************** */ #include "../includes/filler.h" void get_player(t_map *map, char *line) { map->player = 'x'; map->enemy = 'o'; if (strstr(line, "p1")) { map->player = 'o'; map->enemy = 'x'; } } char **fillmap(int offset, int rows, char *line) { int i; char **arr; arr = (char **)malloc(sizeof(char *) * (rows + 1)); i = 0; while (i < rows) { get_next_line(0, &line); arr[i++] = ft_strdup(line + offset); } arr[i] = 0; return (arr); } void mapsize(int *y, int *x, int offset, char *line) { *y = ft_atoi(line + offset); *x = ft_atoi(ft_strchr((line + offset), ' ') + 1); } void extract(t_map *map) { char *line; get_next_line(0, &line); if (map->first) { get_player(map, line); get_next_line(0, &line); mapsize(&map->map_size_y, &map->map_size_x, 8, line); } get_next_line(0, &line); map->map = fillmap(4, map->map_size_y, line); get_next_line(0, &line); mapsize(&map->token_size_y, &map->token_size_x, 6, line); map->token = fillmap(0, map->token_size_y, line); map->first = 0; }
Java
ISO-8859-7
566
2
2
[]
no_license
package com.xinlan.sheering; import com.badlogic.gdx.backends.lwjgl.LwjglApplication; import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration; /** * * @author Administrator * */ public class Demo { /** * @param args */ public static void main(String[] args) { LwjglApplicationConfiguration config= new LwjglApplicationConfiguration(); config.fullscreen = false; config.width=1000; config.height = 600; config.title="˶"; new LwjglApplication(new ThreeBodyApp(),config); } }//end class
Java
UTF-8
219
2.46875
2
[]
no_license
package pers.qiyan.parkinglot; public enum VehicleSize { Large(1), Compact(0); private final int size; VehicleSize(int i) { size = i; } public int size(){ return size; } }
PHP
UTF-8
3,789
2.609375
3
[]
no_license
<?php class kvstore_filesystem extends kvstore_abstract implements kvstore_base { public $header = '<?php exit(); ?>'; function __construct($prefix) { $this->prefix= $prefix; $this->header_length = strlen($this->header); $dir_data = dirname(__FILE__).'/../../../kvdata'; define('DATA_DIR',$dir_data); }//End Function public function store($key, $value, $ttl=0) { $this->check_dir(); $data = array(); $data['value'] = $value; $data['ttl'] = $ttl; $data['dateline'] = time(); $org_file = $this->get_store_file($key); $tmp_file = $org_file . '.' . str_replace(' ', '.', microtime()) . '.' . mt_rand(); if(file_put_contents($tmp_file, $this->header.serialize($data))){ if(copy($tmp_file, $org_file)){ @unlink($tmp_file); return true; } } return false; }//End Function public function fetch($key, &$value, $timeout_version=null) { $file = $this->get_store_file($key); if(file_exists($file)){ $data = unserialize(substr(file_get_contents($file),$this->header_length)); if(!isset($data['dateline'])) $data['dateline'] = @filemtime($file); //todo:兼容老版本 if($timeout_version < $data['dateline']){ if(isset($data['expire'])){ if($data['expire'] == 0 || $data['expire'] >= time()){ $value = $data['value']; return true; } return false; //todo:兼容老版本 }else{ if($data['ttl'] > 0 && ($data['dateline']+$data['ttl']) < time()){ return false; } $value = $data['value']; return true; } } } return false; }//End Function public function delete($key) { $file = $this->get_store_file($key); if(file_exists($file)){ return @unlink($file); } return false; }//End Function public function recovery($record) { $this->check_dir(); $key = $record['key']; $data['value'] = $record['value']; $data['dateline'] = $record['dateline']; $data['ttl'] = $record['ttl']; $org_file = $this->get_store_file($key); $tmp_file = $org_file . '.' . str_replace(' ', '.', microtime()) . '.' . mt_rand(); if(file_put_contents($tmp_file, $this->header.serialize($data))){ if(copy($tmp_file, $org_file)){ @unlink($tmp_file); return true; } } return false; }//End Function private function check_dir() { if(!is_dir(DATA_DIR.'/kvstore/'.$this->prefix)){ $this->mkdir_p(DATA_DIR.'/kvstore/'.$this->prefix); } }//End Function private function get_store_file($key) { return DATA_DIR.'/kvstore/'.$this->prefix.'/'.$this->create_key($key).'.php'; }//End Function public function mkdir_p($dir,$dirmode=0755){ $path = explode('/',str_replace('\\','/',$dir)); $depth = count($path); for($i=$depth;$i>0;$i--){ if(file_exists(implode('/',array_slice($path,0,$i)))){ break; } } for($i;$i<$depth;$i++){ if($d= implode('/',array_slice($path,0,$i+1))){ if(!is_dir($d)) mkdir($d,$dirmode); } } return is_dir($dir); } }//End Class
Markdown
UTF-8
743
3.265625
3
[]
no_license
# Dishes Form A react.js form sending a POST request to the server with a created food type. This project was a recruitment task. ## How to use the project: Fill the input fields with data as suggested in placeholders. Write the name of your dish, the preparation time needed to cook it, select a dish type out of 3 (pizza, soup, sandwich) and choose from additional individual options. If the inputs are valid, the form will be submitted. ## Installation: Clone down this repository. You will need node and npm installed globally on your machine. Installation: npm install To Run Test Suite: npm test To Start Server: npm start ## To Visit App: https://imaginesolo.github.io/dishes-form/ ## Tools versions: npm 6.14.8 node.js v14.13.0
JavaScript
UTF-8
892
2.734375
3
[]
no_license
import Immutable from 'immutable'; export default function ImmutableCompare (nextProps,nextState) { const thisProps = this.props || {}, thisState = this.state || {}, is = Immutable.is; nextProps = nextProps || {}; nextState = nextState || {}; if (Object.keys(thisProps).length !== Object.keys(nextProps).length || Object.keys(thisState).length !== Object.keys(nextState).length) { return true; } for (const key in nextProps) { if ((thisProps[key] !== nextProps[key] || !is(Immutable.fromJS(thisProps[key]), Immutable.fromJS(nextProps[key])))&&typeof(thisProps[key])!="function") { return true; } } for (const key in nextState) { if (thisState[key] !== nextState[key] || !is(thisState[key], nextState[key])) { return true; } } return false; };
Java
UTF-8
397
1.734375
2
[]
no_license
package com.myself.security; public interface SecurityConstants { /** * 登录用户 */ public final static String LOGIN_USER = "user"; /** * 操作 */ public final static String OPERATION_SAVE = "save"; public final static String OPERATION_EDIT = "edit"; public final static String OPERATION_VIEW = "view"; public final static String OPERATION_DELETE = "delete"; }
C#
UTF-8
3,361
2.6875
3
[]
no_license
using LightCycleClone.GameObjects.World; using LightCycleClone.Util; using Microsoft.Xna.Framework; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace LightCycleClone.GameObjects.Character { public class Player : TileObject { public static List<PlayerAction> AvailableActions => EnumUtil.GetList<PlayerAction>(); public PlayerState State { get; set; } public Color Colour { get; set; } public Direction Direction { get { return _direction; } } private Direction _direction; public TileNode CurrentNode { get; set; } public Player(Point startPos, Direction initDir, Color color) { Pos = startPos; _direction = initDir; State = PlayerState.Alive; Colour = color; } public Player(Player rhs) { Guid = rhs.Id; Pos = rhs.Pos; _direction = rhs._direction; State = rhs.State; Colour = rhs.Colour; } public void Update() { if (State == PlayerState.Alive) { switch (_direction) { case Direction.North: Pos.Y--; break; case Direction.South: Pos.Y++; break; case Direction.East: Pos.X++; break; case Direction.West: Pos.X--; break; } } } public void SetAction(PlayerAction action) { switch (action) { case PlayerAction.NoAction: break; case PlayerAction.MoveUp: SetDirection(Direction.North); break; case PlayerAction.MoveDown: SetDirection(Direction.South); break; case PlayerAction.MoveLeft: SetDirection(Direction.West); break; case PlayerAction.MoveRight: SetDirection(Direction.East); break; } } private void SetDirection(Direction direction) { var valid = false; switch (direction) { case Direction.North: valid = (_direction != Direction.South); break; case Direction.South: valid = (_direction != Direction.North); break; case Direction.East: valid = (_direction != Direction.West); break; case Direction.West: valid = (_direction != Direction.East); break; } if (valid) { _direction = direction; } } public override void Dispose() { CurrentNode = null; base.Dispose(); } } }
Go
UTF-8
677
3.4375
3
[]
no_license
package main import ( "github.com/gogo/protobuf/proto" "log" "sort" ) type Person struct { Age *uint64 } func main() { persons := []*Person{ { Age: proto.Uint64(1), }, { Age: proto.Uint64(123), }, } mapper := make(map[int]*Person) mapper[1] = &Person{Age: proto.Uint64(1),} log.Printf("mapper 2: %v", mapper[2]) persons = append(persons, mapper[2]) for _, person := range persons { log.Printf("%v", *person.Age) } sort.Slice(persons, func(i, j int) bool { log.Printf("i: %v j: %v", i,j) name1 := *persons[i].Age name2 := *persons[j].Age return name1 < name2 }) for _, person := range persons { log.Printf("%v", *person.Age) } }
Java
UTF-8
96
1.710938
2
[]
no_license
package step8_03_atm3.copy1; public class Account1 { String number; int money; }
SQL
UTF-8
7,717
3.140625
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 4.6.6deb4 -- https://www.phpmyadmin.net/ -- -- Client : localhost:3306 -- Généré le : Jeu 28 Septembre 2017 à 11:11 -- Version du serveur : 5.7.19-0ubuntu0.17.04.1 -- Version de PHP : 7.0.22-0ubuntu0.17.04.1 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Base de données : `gstion_formation` -- -- -------------------------------------------------------- -- -- Structure de la table `ecf` -- CREATE TABLE `ecf` ( `id` int(11) NOT NULL, `nom` varchar(256) DEFAULT NULL, `id_module` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -------------------------------------------------------- -- -- Structure de la table `formation` -- CREATE TABLE `formation` ( `id` int(11) NOT NULL, `libelle` varchar(256) DEFAULT NULL, `description` text, `nbr_heures` int(11) DEFAULT NULL, `lieu` varchar(256) DEFAULT NULL, `date_debut` date DEFAULT NULL, `id_formateur` int(11) DEFAULT NULL, `codeFormation` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -------------------------------------------------------- -- -- Structure de la table `gestionECF` -- CREATE TABLE `gestionECF` ( `idStagiaire` int(11) NOT NULL, `idEcf` int(11) NOT NULL, `note` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -------------------------------------------------------- -- -- Structure de la table `gestionFormation` -- CREATE TABLE `gestionFormation` ( `idStagiaire` int(11) NOT NULL, `idFormation` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -------------------------------------------------------- -- -- Structure de la table `gestionModule` -- CREATE TABLE `gestionModule` ( `formation_id` int(11) NOT NULL, `module_id` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -------------------------------------------------------- -- -- Structure de la table `gestionSequence` -- CREATE TABLE `gestionSequence` ( `idModule` int(11) NOT NULL, `idSequence` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -------------------------------------------------------- -- -- Structure de la table `module` -- CREATE TABLE `module` ( `id` int(11) NOT NULL, `libelle` varchar(25) DEFAULT NULL, `description` text, `duree` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -------------------------------------------------------- -- -- Structure de la table `personnel` -- CREATE TABLE `personnel` ( `id` int(11) NOT NULL, `nom` varchar(255) NOT NULL, `prenom` varchar(255) NOT NULL, `user` varchar(255) NOT NULL, `MDP` varchar(255) DEFAULT NULL, `role` char(1) DEFAULT NULL, `email` varchar(255) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Contenu de la table `personnel` -- INSERT INTO `personnel` (`id`, `nom`, `prenom`, `user`, `MDP`, `role`, `email`) VALUES (1, 'Giraud', 'Alex', 'Alex Kidd', NULL, NULL, NULL); -- -------------------------------------------------------- -- -- Structure de la table `sequence` -- CREATE TABLE `sequence` ( `id` int(11) NOT NULL, `nom` varchar(255) NOT NULL, `description` text NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -------------------------------------------------------- -- -- Structure de la table `stagiaire` -- CREATE TABLE `stagiaire` ( `id` int(11) NOT NULL, `nom` varchar(256) DEFAULT NULL, `prenom` varchar(256) DEFAULT NULL, `adresse` varchar(256) DEFAULT NULL, `CP` int(11) DEFAULT NULL, `ville` varchar(256) DEFAULT NULL, `mail` varchar(256) DEFAULT NULL, `telephone` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Contenu de la table `stagiaire` -- INSERT INTO `stagiaire` (`id`, `nom`, `prenom`, `adresse`, `CP`, `ville`, `mail`, `telephone`) VALUES (2, 'Malezieux', 'James', 'Kerduraison', 22300, 'Ploumilliau', 'mail@mail.com', 769177283); -- -- Index pour les tables exportées -- -- -- Index pour la table `ecf` -- ALTER TABLE `ecf` ADD PRIMARY KEY (`id`), ADD KEY `id_stagiaire` (`id_module`); -- -- Index pour la table `formation` -- ALTER TABLE `formation` ADD PRIMARY KEY (`id`), ADD KEY `id_formateur` (`id_formateur`); -- -- Index pour la table `gestionECF` -- ALTER TABLE `gestionECF` ADD KEY `idStagiaire` (`idStagiaire`), ADD KEY `idEcf` (`idEcf`), ADD KEY `note` (`note`); -- -- Index pour la table `gestionFormation` -- ALTER TABLE `gestionFormation` ADD KEY `idStagiaire` (`idStagiaire`), ADD KEY `idFormation` (`idFormation`); -- -- Index pour la table `gestionModule` -- ALTER TABLE `gestionModule` ADD PRIMARY KEY (`formation_id`,`module_id`), ADD KEY `module_id` (`module_id`); -- -- Index pour la table `gestionSequence` -- ALTER TABLE `gestionSequence` ADD KEY `idModule` (`idModule`), ADD KEY `idSequence` (`idSequence`); -- -- Index pour la table `module` -- ALTER TABLE `module` ADD PRIMARY KEY (`id`); -- -- Index pour la table `personnel` -- ALTER TABLE `personnel` ADD PRIMARY KEY (`id`); -- -- Index pour la table `sequence` -- ALTER TABLE `sequence` ADD PRIMARY KEY (`id`); -- -- Index pour la table `stagiaire` -- ALTER TABLE `stagiaire` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT pour les tables exportées -- -- -- AUTO_INCREMENT pour la table `formation` -- ALTER TABLE `formation` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT pour la table `module` -- ALTER TABLE `module` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT pour la table `personnel` -- ALTER TABLE `personnel` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=2; -- -- AUTO_INCREMENT pour la table `sequence` -- ALTER TABLE `sequence` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT pour la table `stagiaire` -- ALTER TABLE `stagiaire` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=25; -- -- Contraintes pour les tables exportées -- -- -- Contraintes pour la table `ecf` -- ALTER TABLE `ecf` ADD CONSTRAINT `ecf_ibfk_1` FOREIGN KEY (`id_module`) REFERENCES `module` (`id`); -- -- Contraintes pour la table `formation` -- ALTER TABLE `formation` ADD CONSTRAINT `formation_ibfk_1` FOREIGN KEY (`id_formateur`) REFERENCES `personnel` (`id`); -- -- Contraintes pour la table `gestionECF` -- ALTER TABLE `gestionECF` ADD CONSTRAINT `gestionECF_ibfk_1` FOREIGN KEY (`idStagiaire`) REFERENCES `stagiaire` (`id`), ADD CONSTRAINT `gestionECF_ibfk_2` FOREIGN KEY (`idEcf`) REFERENCES `ecf` (`id`); -- -- Contraintes pour la table `gestionFormation` -- ALTER TABLE `gestionFormation` ADD CONSTRAINT `gestionFormation_ibfk_1` FOREIGN KEY (`idFormation`) REFERENCES `formation` (`id`), ADD CONSTRAINT `gestionFormation_ibfk_2` FOREIGN KEY (`idStagiaire`) REFERENCES `stagiaire` (`id`); -- -- Contraintes pour la table `gestionModule` -- ALTER TABLE `gestionModule` ADD CONSTRAINT `gestionModule_ibfk_1` FOREIGN KEY (`formation_id`) REFERENCES `formation` (`id`), ADD CONSTRAINT `gestionModule_ibfk_2` FOREIGN KEY (`module_id`) REFERENCES `module` (`id`); -- -- Contraintes pour la table `gestionSequence` -- ALTER TABLE `gestionSequence` ADD CONSTRAINT `gestionSequence_ibfk_1` FOREIGN KEY (`idModule`) REFERENCES `module` (`id`), ADD CONSTRAINT `gestionSequence_ibfk_2` FOREIGN KEY (`idSequence`) REFERENCES `sequence` (`id`); /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
Markdown
UTF-8
2,675
3.328125
3
[]
no_license
# NSDate 和測試的那些小事 純粹筆記一下,遇到的問題 <!-- more --> 最近在處理日期資料,寫了測試要驗證日期是否正確,於是就碰到兩的問題: - 要怎麼驗證 `NSDate` object? - 知道怎麼驗證了,怎麼時間就差這麼一些,測試沒過? # 怎麼驗證 `NSDate` 之前有寫過一篇有關於 XCTAssert 的文章 - [XCTest Assertions 及其種類]({{site.url}}/2014/07/10/xctest-assertions/) 有列出有哪些 XCTAssert 可以用,於是就要從這邊挑一個出來用。 上網找了找資料,其實只要取得 NSDate 物件的 timestamp 即可,再去對照處理的日期的 timestamp 是否符合預期即可。 timestamp 的型態是 doulble ,因此要比較他的精準度,就要使用 `XCTAssertEqualWithAccuracy` 了 ## XCTAssertEqualWithAccuracy 先複習一下, ``` objective-c XCTAssertEqualWithAccuracy XCTAssertEqualWithAccuracy(expression1, expression2, accuracy, format...) ``` - `expression1` 和 `expression2` 是兩個需要比較的對象 - `accuracy` 則是放比較的精準度 - `format...` 則是可以放測試沒過需要在 console 印出的文字 ## 那就來比吧 ``` objective-c XCTAssertEqualWithAccuracy(targetTimestamp, [checkedDate timeIntervalSince1970], 0.01); ``` - `targetTimestamp` 是個 double 變數,存放預期值 - `checkedDate` 則是需要被檢查的目標 NSDate 物件 - `0.01` 則是容許的誤差值 當時這樣跑下去,綠燈還亮不了 ... 繼續看下去 ... # 時區問題 在寫 date formatter 的時候,我的需求是要由字串轉成 NSDate object ,於是覺得很爽快地做完了, 測下去發現產出的 timestamp 轉換之後硬生生的多了八個小時。 後來又翻了翻文件,發現 `NSDateFormatter` 會自動幫你轉成手機的當地時間,我的時區在台北,是 GMT 的時間 +8 ,因此在這時候就需要把 date formatter 的時區設定好,或是在測試的時候需要加上時區的調整。 ## NSDateFormatter - Time Zone 如果時間要以 GMT 為準,就可以設定一下 date formatter 的時區, ``` dateFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"]; ``` - `dateFormatter` 是 NSDateFormatter 的 instance 這時候, 由這個物件產出來的日期,就和 GMT 一致了 # 參考資料 - [XCTest Assertions 及其種類]({{site.url}}/2014/07/10/xctest-assertions/) - [ios - XCTAssertEqual: How to compare NSDates? - Stack Overflow](http://stackoverflow.com/a/19777152) - [iphone - NSDateFormatter with default time zone gives different date than NSDate description method - Stack Overflow](http://stackoverflow.com/a/16719818)
JavaScript
UTF-8
204
2.78125
3
[]
no_license
/* Manejo de data */ // esta es una función de ejemplo // puedes ver como agregamos la función a nuestro objeto global window const example = () => { return 'example'; }; window.example = example;
Python
UTF-8
469
3.265625
3
[]
no_license
#!/usr/bin/env python # -*- coding:utf8 -*- class Animal(object): def run(self): print("动物跑......") class Dog(Animal): def run(self): print("狗狗跑.....") class Car(Animal): def run(self): print("汽车跑.....") if __name__ == '__main__': f1 = Animal() # 没有发生多态 f1.run() f2 = Dog() # 发生多态 f2.run() f3 = Car() # 发生多态 f3.run()
TypeScript
UTF-8
971
3.53125
4
[ "MIT" ]
permissive
// TODO unused. Delete? export class BitStream { public readonly data: Uint8Array; public readonly bitCount: number; public bitIndex: number = 0; public startBits: number = 0; constructor(data: Uint8Array) { this.data = data; this.bitCount = data.length*8; } public readByte(): number { const value = this.peekByte(); this.bitIndex += this.startBits + 8; return value; } public peekByte(ahead: number = 0): number { const bitIndex = this.bitIndex + ahead*(8 + this.startBits) + this.startBits; if (bitIndex + 8 > this.bitCount) { throw new Error("End of bit stream"); } const byteIndex = Math.floor(bitIndex/8); const bitOffset = bitIndex%8; let value = this.data[byteIndex] << bitOffset; if (bitOffset !== 0) { value |= this.data[byteIndex + 1] >> (8 - bitOffset); } return value; } }
Python
UTF-8
539
3.984375
4
[]
no_license
# sekwencja jest np. lista czy tez ciag znakow, krotka def przeciecie_sekwencji(S1, S2): S3 = [] for i in S1: if i in S2: S3.append(i) return S3 def suma_sekwencji(S1, S2): S3 = [] # wszystkie elementy pierwszej sekwencji for i in S1: if i not in S3: S3.append(i) for i in S2: if i not in S1 and i not in S3: S3.append(i) return S3 S1 = [1, 2, 2, 3, 3, 4, 5, 6, 7] S2 = [5, 6, 6, 7, 8, 836] print "Przeciecie sekwencji: " print przeciecie_sekwencji(S1, S2) print "Suma sekwencji: " print suma_sekwencji(S1, S2)
C++
UTF-8
850
3.828125
4
[]
no_license
//https://practice.geeksforgeeks.org/problems/check-if-tree-is-isomorphic/1 // Return True if the given trees are isomotphic. Else return False. bool isIsomorphicUtil(Node* root1,Node* root2) { if(!root1 && !root2) { return true; } if(!root1 || !root2) { return false; } if(root1->data != root2->data) { return false; } if((isIsomorphicUtil(root1->left,root2->right) &&isIsomorphicUtil(root1->right,root2->left)) ||(isIsomorphicUtil(root1->left,root2->left) && isIsomorphicUtil(root1->right,root2->right))) { return true; } else { return false; } } bool isIsomorphic(Node *root1,Node *root2) { if(root1==NULL && root2 == NULL) { return true; } return isIsomorphicUtil(root1,root2); }
C++
GB18030
3,886
3.421875
3
[]
no_license
#include<iostream> #include<stack> using namespace std; typedef char ElemType; struct ThreadNode{ ElemType data; int ltag,rtag; ThreadNode *lchild,*rchild; }; void CreateThreadNode(ThreadNode *&b,char *str){ stack<ThreadNode*> s; ThreadNode *p; b = NULL; int k,j = 0; char ch = str[j]; while(ch != '#'){ switch(ch){ case '(': s.push(p); k = 1; break; case ')': s.pop(); break; case ',': k = 2; break; default: p = new ThreadNode; p->data = ch; p->lchild = p->rchild = NULL; if(b == NULL) b = p; else switch(k){ case 1: s.top()->lchild = p;break; case 2: s.top()->rchild = p;break; } } j++; ch = str[j]; } } void DispThreadNode(ThreadNode *b){ if(b){ cout<<b->data; if((b->lchild != NULL) || (b->rchild != NULL)){ cout<<"("; DispThreadNode(b->lchild); if (b->rchild) cout<<","; DispThreadNode(b->rchild); cout<<")"; } } } ThreadNode *pre; //ȫֱ void Thread(ThreadNode *&p){ if (p){ Thread(p->lchild); // if (!p->lchild){ //ǰ p->lchild = pre; //ǰڵǰ p->ltag = 1; } else p->ltag = 0; if (!pre->rchild){ // pre->rchild = p; //ǰڵĺ pre->rtag = 1; } else pre->rtag = 0; pre = p; Thread(p->rchild); // } } // ThreadNode *CreateThread(ThreadNode *b){ ThreadNode *root; root = new ThreadNode; root->ltag = 0;root->rtag = 1; root->rchild = b; if (!b) root->lchild = root; else{ root->lchild = b; pre = root; //pre*pǰڵ, Thread(b); // pre->rchild = root; //,ָڵ pre->rtag = 1; root->rchild = pre; //ڵ } return root; } void InOrder(ThreadNode *tb){ if (tb->lchild && tb->ltag == 0) InOrder(tb->lchild); cout<<tb->data<<" "; if (tb->rchild && tb->rtag == 0) InOrder(tb->rchild); } //Ѱµһ ThreadNode *First(ThreadNode *current){ ThreadNode *p = current; while(p->ltag == 0) p = p->lchild; return p; } //Ѱҽµĺ̽ ThreadNode *Next(ThreadNode *current){ ThreadNode *p = current->rchild; if(current->rtag == 0) return First(p); else return p; } void iteratorInOrder(ThreadNode *tb){ ThreadNode *p = tb->lchild; while (p != tb){ while (p->ltag == 0) p = p->lchild; cout<<p->data<<" "; while (p->rtag == 1 && p->rchild != tb){ p = p->rchild; cout<<p->data<<" "; } p = p->rchild; } } /* void InOrder1(ThreadNode *root){ ThreadNode *p; if(root==NULL) return; //Ϊ,ղ while(p->ltag==0) //ĵһ㲢 p=p->lchild; cout<<p->data; while(p->rchild!=NULL) //Pں,η̽ { p=Next(p); cout<<p->data; } }*/ int main(){ ThreadNode *b,*tb; CreateThreadNode(b,"a(b(,c(d)))#"); cout<<":";DispThreadNode(b); tb=CreateThread(b); cout<<"\n:"; cout<<"\nݹ㷨:";InOrder(tb->lchild); cout<<"\nǵݹ㷨:";iteratorInOrder(tb); //InOrder1(tb); return 0; }
Python
UTF-8
1,490
2.75
3
[]
no_license
import sqlite3 import os import shutil conn=sqlite3.connect("Record_database.db") def re(): print('Creating database...') try: conn.execute("create table Record_TVL (name varchar(20) default '-', age varchar(10) default '-', file_no varchar(20) not null, doe varchar(20) default '-', sex varchar(10), diag varchar(30) default '-', phone varchar(20) default '-', occupation varchar(20) default'-')") conn.commit() except: print('Database exists') conn.execute('delete from Record_TVL') conn.commit() try: conn.execute("create table Record_KVP (name varchar(20) default '-', age varchar(10) default '-', file_no varchar(20) not null, doe varchar(20) default '-', sex varchar(10), diag varchar(30) default '-', phone varchar(20) default '-', occupation varchar(20) default'-')") conn.commit() except: conn.execute('delete from Record_KVP') print('Database exists') conn.commit() conn.close() print('Database created') def md(): print('Creating Directories...') if not os.path.exists('Case_files_KVP'): os.mkdir('Case_files_KVP') if not os.path.exists('Case_files_TVL'): os.mkdir('Case_files_TVL') def rd(): print('Removing directory...') try: shutil.rmtree('Case_files_KVP') shutil.rmtree('Case_files_TVL') except: print("Directoies doesn't exist...") md() rd() re()
Python
UTF-8
413
3.140625
3
[]
no_license
class Solution(object): def isHappy(self, n): """ :type n: int :rtype: bool """ from sets import Set nums = Set() while n not in nums: if n == 1: return True nums.add(n) s = str(n) n = 0 for i in s: n += int(i) * int(i) return False
C#
UTF-8
2,001
2.71875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace ffn_site.Models.Dal { public class ClubDal : IDal<Club> { private ffn_siteEntities bdd; public ClubDal() { bdd = new ffn_siteEntities(); } public int Add(Club o) { bdd.Club.Add(o); return bdd.SaveChanges(); } public int Delete(Club o) { bdd.Club.Remove(o); return bdd.SaveChanges(); } public int Delete(int id) { bdd.Club.Remove(Get(id)); return bdd.SaveChanges(); } public void Dispose() { bdd.Dispose(); } public Club Get(int id) { return bdd.Club.Where(c => c.id == id).FirstOrDefault(); } public Club Get(Club o) { return Get(o.id); } public List<Club> GetAll() { return bdd.Club.ToList(); } public int Update(Club o) { Club club = Get(o.id); if (club == null) return -1; else { if (o.nomClub != null && !"".Equals(o.nomClub)) club.nomClub = o.nomClub; if (o.adresseSiege != null && !"".Equals(o.adresseSiege)) club.adresseSiege = o.adresseSiege; if (o.cpSiege != null && !"".Equals(o.cpSiege)) club.cpSiege = o.cpSiege; if (o.villeSiege != null && !"".Equals(o.villeSiege)) club.villeSiege = o.villeSiege; if (o.siteWeb != null && !"".Equals(o.siteWeb)) club.siteWeb = o.siteWeb; return bdd.SaveChanges(); } } public int EntityExist(Club o) { Club club = bdd.Club .Where(c => c.idFederal == o.idFederal) .FirstOrDefault(); return (club == null) ? -1 : club.id; } } }
Ruby
UTF-8
1,854
2.890625
3
[ "MIT" ]
permissive
# read file name from the cli params file_name = ARGV[0] # Get contents of the file contents = IO.read(file_name) # List of all conversion passed to gsub, # @matcher: RegEx or String # @replacement: String conversions = [ # STUBS {matcher: /(\S+?).stubs\(\s*?(:.+?)\)/, replacement: 'allow(\1).to receive(\2)'}, # For Symbol {matcher: /(\S+?).stubs\((.+?)\)/, replacement: 'allow(\1).to receive_messages(\2)'}, # For Hash {matcher: /(\S+?).stub_chain\((.+?)\)/, replacement: 'allow(\1).to receive_message_chain(\2)'}, # For chained stubs # MOCKS {matcher: /(\S+?).expects\(\s*?(:.+?)\)/, replacement: 'expect(\1).to receive(\2)'}, # For Symbol {matcher: /(\S+?).expects\((.+?)\)/, replacement: 'expect(\1).to receive_messages(\2)'}, # For Hash # ANY INSTANCE {matcher: /(allow|expect)\((.*?)\.any_instance\)/, replacement: '\1_any_instance_of(\2)'}, # Fix any_instance for all cases # expect have_received .never {matcher: /expect\((.*?)\).to have_received(.*?)\.never/, replacement: 'expect(\1).to_not have_received\2'}, # SIMPLE REPLACEMENTS {matcher: '.returns', replacement: '.and_return'}, {matcher: '.raises', replacement: '.and_raise'}, {matcher: '.yields', replacement: '.and_yield'}, {matcher: '.at_least_once', replacement: '.at_least(:once)'}, {matcher: 'any_parameters', replacement: 'any_args'}, {matcher: 'stub_everything', replacement: 'spy'}, {matcher: /\.in_sequence\(.*?\)/, replacement: '.ordered'}, {matcher: /regexp_matches\((.*?)\)/, replacement: '\1'}, {matcher: /(mock|stubs|stub)\((.*?)\)/, replacement: 'double(\2)'}, ] # Apply all conversions conversions.each do |c| contents.gsub!(c[:matcher], c[:replacement]) end # ADD rspec_only: true contents.sub!(/(describe.+)\s(do)/, '\1, rspec_only: true \2') # Dump all changes to file IO.write(file_name, contents) puts "DONE!"
PHP
UTF-8
4,698
2.921875
3
[]
no_license
<?php namespace outputs; use GameOfLife\Board; use GameOfLife\outputs\Png; use Icecave\Isolator\Isolator; use PHPUnit\Framework\TestCase; use Ulrichsg\Getopt; class PngTest extends TestCase { public function testOutputWithoutColors() { $field = new Board(5, 5); $field->setBoardValue(2, 2, 1); $option = new Getopt(); $png = new Png(); $png->startOutput($option); $png->outputBoard($field); $picture = imagecreatefrompng("outPng/000.png"); $this->assertTrue($this->comparePicture($field, $picture)); } public function testCellColor() { $field = new Board(5, 5); $field->setBoardValue(2, 2, 1); $option = new Getopt(); $png = new Png(); $png->addOptions($option); $option->parse("--pngOutputBackgroundColor"); $isolator = $this->createMock(Isolator::class); $isolator->method("readline") ->willReturn("122") ->willReturn("122") ->willReturn("122"); $png->setIsolator($isolator); //expectColor("122", "122", "122"); $png->startOutput($option); $png->outputBoard($field); $picture = imagecreatefrompng("outPng/000.png"); $this->assertTrue($this->comparePicture($field, $picture, ["red" => 255, "green" => 255, "blue" => 255, "alpha" => 0], ["red" => 122, "green" => 122, "blue" => 122, "alpha" => 0])); } public function testBackgroundColor() { $field = new Board(5, 5); $field->setBoardValue(2, 2, 1); $option = new Getopt(); $png = new Png(); $png->addOptions($option); $option->parse("--pngOutputCellColor"); $isolator = $this->createMock(Isolator::class); $isolator->method("readline") ->willReturn("200") ->willReturn("200") ->willReturn("200"); $png->setIsolator($isolator); $png->startOutput($option); $png->outputBoard($field); $picture = imagecreatefrompng("outPng/000.png"); $this->assertTrue($this->comparePicture($field, $picture, ["red" => 200, "green" => 200, "blue" => 200, "alpha" => 0])); } public function testCellSizeBecauseKevinToldMeToDoSo() { $field = new Board(2, 2); $field->setBoardValue(0, 1, 1); $field->setBoardValue(1, 0, 1); $option = new Getopt(); $png = new Png(); $png->addOptions($option); $size = 4; //TODO: Resize only works with 2^x! Any other number won't work! $option->parse("--pngOutputSize " . $size); $png->startOutput($option); $png->outputBoard($field); $picture = imagecreatefrompng("outPng/000.png"); $counter = 0; $previousColor = imagecolorat($picture, 0 , 0); for($y = 0; $y < $field->width() * $size; $y++) { if (imagecolorat($picture, 0 , $y) == $previousColor) { $counter++; } else { $this->assertEquals($size, $counter); break; } } } /** * Compare Picture * The function uses the given parameters to create a new picture. * Afterward this picture be compared to another generated picture and will give a positive Unit-test result, if both of them are equal. * @param Board $board * @param $picture resource * @param $cellColor array defines the color for the cell, by using RGB code. * @param $backgroundColor array defines the backgroundcolor of the cell, by using RGB code. * @return bool */ private function comparePicture(Board $board, $picture, $cellColor = ["red" => 255, "green" => 255, "blue" => 255, "alpha" => 0], $backgroundColor = ["red" => 0, "green" => 0, "blue" => 0, "alpha" => 0]): bool { $isEqual = true; for ($y = 0; $y < $board->height(); $y++) { for ($x = 0; $x < $board->width(); $x++) { $pxlColor = imagecolorat($picture, $x, $y); $color = imagecolorsforindex($picture, $pxlColor); if ($board->boardValue($x, $y) == true) { if ($color != $cellColor) { $isEqual = false; } } else { if ($color != $backgroundColor) { $isEqual = false; } } } } return $isEqual; } }
Java
UTF-8
1,790
2.359375
2
[]
no_license
package pl.mmprogr.library.controller.book; import org.springframework.stereotype.Controller; import pl.mmprogr.library.model.book.Book; import pl.mmprogr.library.model.book.BookBuilder; import pl.mmprogr.library.model.user.User; import pl.mmprogr.library.service.book.BookService; import pl.mmprogr.library.view.BorrowBookView; import pl.mmprogr.library.view.FindBookView; import java.time.LocalDate; import java.util.List; import java.util.Optional; @Controller public class BookLendingController { private final BookController bookController; private final BookService bookService; public BookLendingController(BookController bookController, BookService bookService) { this.bookController = bookController; this.bookService = bookService; } public void borrowBook() { List<Optional<Book>>potentiallyBooksToBorrow = bookService.findByTitle(BorrowBookView.takeDataToFindBookByTitleToBorrow()); if (potentiallyBooksToBorrow == null || potentiallyBooksToBorrow.isEmpty()) { FindBookView.booksNotFound(); } else { for (Optional<Book> book : potentiallyBooksToBorrow) { Optional<Book> bookAvailableToLend = book.filter(b -> b.getLender() == null); if (bookAvailableToLend.isPresent()) { User user = BorrowBookView.takeUserDataToBorrowBook(); Book borrowedBook = new BookBuilder() .withAuthor(bookAvailableToLend.get().getAuthor()) .withIsbnNumber(bookAvailableToLend.get().getIsbnNumber()) .withTitle(bookAvailableToLend.get().getTitle()) .withDateOfLastRental(LocalDate.now()) .withLender(user) .build(); bookService.remove(bookAvailableToLend.get()); bookService.add(borrowedBook); bookController.updateFile(); return; } } BorrowBookView.noAvailableBookToBorrow(); } } }
Python
UTF-8
4,078
3.390625
3
[ "Apache-2.0" ]
permissive
import numpy as np class ValueLog(): """Implemements a key/value aggregating dictionary log with optional grouping/precision and custom aggregation modes""" def __init__(self): self.log_values = {} def log(self, key, val, agg="mean", scope="get", group=None, precision=None): """Logs a value Args: key: The key for this value, this will be the key in the resulting log dictionary val: The value to log agg: How to aggregate all the values received, should be the name of a valid numpy operation like mean/max/sum etc... scope: Scope over which to aggregate/reset the values for this key. Valid values are: get: Aggregate and reset each time get() is called None: Never reset (Aggregate all values received from the start) <number>: Aggregate the last <number> values received group: Optionally place this key in a sub-key called 'group'. Can set a nested group using '->', e.g. "training->general" precision: Precision to round the final value to after aggregation Note: agg/scope/precision must be the same for each value logged with the same key+group """ dest = self.log_values if group is not None: for subkey in group.split("->"): if subkey not in dest: dest[subkey] = {} dest = dest[subkey] if key not in dest: dest[key] = { "data": [], "scope": scope, "agg": agg, "precision": precision } else: assert(dest[key]['agg'] == agg) assert(dest[key]['precision'] == precision) assert(dest[key]['scope'] == scope) dest[key]['data'].append(val) scope = dest[key]['scope'] # If scope is a number, leave only that last amount in the history if isinstance(scope, int): dest[key]['data'] = dest[key]['data'][-int(scope):] def log_dict(self, source, agg="auto", group=None): """Logs values from a given dictionary in the same group/key structure """ for key, val in source.items(): if isinstance(val, dict): sub_group = key if group is None else group+"->"+key self.log_dict(val, agg=agg, group=sub_group) else: self.log(key, val, group=group, agg=agg) def _get_aggregator_for_key(self, key, agg_mode): if agg_mode == "auto": # 'auto' uses mean unless one of the supported modes is in # the key name (Example 'reward_max' will use max) supported_modes = ['min', 'mean', 'median', 'max', 'std', 'sum'] # Example auto-keys might be 'reward_max', or just 'max' mode = key.split("_")[-1] if mode not in supported_modes: agg_mode = "mean" else: agg_mode = mode return getattr(np, agg_mode) def _aggregate_log_values(self, source, dest): """Aggregates the log values recursively from source->dest""" remove = [] for key, item in source.items(): if "data" not in item: # Assume it's a sub-group dest[key] = {} self._aggregate_log_values(item, dest[key]) else: aggregator = self._get_aggregator_for_key(key, item['agg']) value = aggregator(item['data']) if item['precision'] is not None: value = round(value, item['precision']) dest[key] = value if item['scope'] == 'get': remove.append(key) for key in remove: del source[key] def get(self): res = {} self._aggregate_log_values(self.log_values, res) return res
Markdown
UTF-8
2,840
2.734375
3
[]
no_license
--- title: 'Comparison of four workflows for structural variants identification' date: '2022-01-28' slug: project-comparison-of-four-workflows-for-structural-variants-identification categories: - Open 2022 - Open Flexible Timeline tags: - 2022 thumbnailImagePosition: left thumbnailImage: https://github.com/CU-DSI-Scholars/site-source/blob/main/static/img/microbiome.png?raw=true --- Recent advances in genomic technologies have led to the identification of many novel disease-gene associations, enabling more precise diagnoses. Along with the technologies enabling rapid DNA sequencing, multiple computational approaches have been developed to identify structural variants (i.e. relatively large deletions and duplications of genomic sequences). These workflows can lead to the identification of different structural variants, raising the risk of missing disease-causing variants when using only one of those methods. Unfortunately, many of the variants identified by those workflows are artifacts (i.e. absent in the biological sample), raising concerns that time and effort will be wasted on those artifacts instead of analyzing the causative genetic variant. The goal of this project is to develop best practices to increase the chance to identify causative structural variants, while reducing the number of artifacts. We will use the raw data from whole-exome and whole-genome sequencing of patients with renal diseases. The students will be expected to (1) Compare the output of 4 different tools for identifying structural variants and visualize the differences (using R or Python) and (2) Identify the tool specific parameters that increases the specificity and sensitivity of each tool in differentiating true variants and artifacts. <!--more--> {{< alert success >}} Selected candidate(s) can receive a stipend directly from the faculty advisor. This is not a guarantee of payment, and the total amount is subject to available funding. {{< /alert >}} ## Faculty Advisor + Professor: [Ali Gharavi](http://columbiamedicine.org/cpmg/) + Center/Lab: Center for Precision Medicine and Genomics + Location: CUIMC + The mission of the Center for Precision Medicine and Genomics (CPMG) is to improve human health through high quality research, education and clinical care. ## Project Timeline + Earliest starting date: 3/1/2022 + End date: + Number of hours per week of research expected during Spring/Summer 2022: ~10 + Number of hours per week of research expected during Summer 2022: ~35 ## Candidate requirements + Skill sets: Fluent in at least one programing language (R, Python, Perl, Java), at least one course in statistics and knowledge in genetics. + Student eligibility: ~~freshman~~, ~~sophomore~~, junior, senior, master's + International students on F1 or J1 visa: **eligible** + Academic Credit Possible: Yes
JavaScript
UTF-8
1,338
2.671875
3
[]
no_license
const mongoose = require("mongoose"); const Schema = mongoose.Schema; const WorkoutSchema = new Schema({ day: { type: Date, default: Date.now }, exercises: [ { type: Schema.Types.ObjectId, ref: "Exercise" } ], totalDuration: { type: Number }, totalWeight: { type: Number }, totalDistance: { type: Number } }); WorkoutSchema.methods.addTotalDuration = (exercises) => { const totalDuration = exercises.reduce((accumulator, currentValue) => { accumulator = accumulator + currentValue.duration; return accumulator; }, 0); return totalDuration; }; WorkoutSchema.methods.addTotalWeight = (exercises) => { const totalWeight = exercises.reduce((accumulator, currentValue) => { if (currentValue.type === "resistance") { accumulator = accumulator + currentValue.weight; } else { accumulator = accumulator + 0; } return accumulator; }, 0); return totalWeight; }; WorkoutSchema.methods.addTotalDistance = (exercises) => { const totalDistance = exercises.reduce((accumulator, currentValue) => { if (currentValue.type === "resistance") { accumulator = accumulator + 0; } else { accumulator = accumulator + currentValue.distance; } return accumulator; }, 0); return totalDistance; }; const Workout = mongoose.model("Workout", WorkoutSchema); module.exports = Workout;
Markdown
UTF-8
1,027
4.21875
4
[]
no_license
## Reverse a Linked List (in Ruby!) ### Prompt ### Your task is to reverse a linked list using Ruby. *Examples:* Given the Linked List: ```3 -> 4 -> 6 -> 12 -> 33 -> 34 ``` return: ```34 -> 33 -> 12 -> 6 -> 4 -> 3``` Given the Linked List: ```0 -> 2 -> 5 -> 5 -> 6``` return: ```6 -> 5 -> 5 -> 2 -> 0``` ### Hints and Helpers ### Since the data structure we're working with doesn't yet exist in Ruby, we'll have to create it. In the starter code, you'll see that there is the definition for a Node: ```rb class Node attr_accessor :val, :next def initialize(val, next_node) @val = val @next = next_node end end ``` In addition, there is a helper function that allows you to print out a given linked list in a nice format. Feel free to check it out in the starter code. Think about how you would do this as a human. Make sure to pseudo-code and think out the process first before trying it in Ruby. You may use the starter code as a template with the Node class and helper function to start.
TypeScript
UTF-8
1,433
3.546875
4
[]
no_license
var nodeFetch = require('node-fetch'); // let fn: () => string = () => { // console.log('It has been 5 seconds'); // return 'test'; // } // const val: string = fn(); // setTimeout(fn, 5000); // // console.log(val); // // const afn = async () => { // // const res = await fetch('https://api.fungenerators.com'); // // const data = await res.json; // // console.log(data); // // } const api: string = 'https://api.github.com/repos/javascript-tutorial/en.javascript.info/commits'; const myAsyncFetch = async <T>(url: string): Promise<T> => { const response = await nodeFetch(url); const body = await response.json(); return body; } const asb = myAsyncFetch(api); setTimeout(() => console.log(asb), 1000) // // async function makeRequest(url: string): Promise<T> { // // const response = await fetch(url); // // const body = await response.json(); // // return body; // // } // //// fetch in JS // // const fetch = require('node-fetch'); // fetch(api) // .then(response => response.json()) // .then(body => console.log(body)) // .catch(error => console.log(error.messages)) // //// Promises // // const promise = new Promise((resolve, reject) => {}); // /* // A promise looks like this: // 1) takes a callbkack as a parameter // 2) The callback takes the resolve and reject parameters // 3) If true, it returnd the resolve, if false, it returns the reject // */
Markdown
UTF-8
1,750
2.78125
3
[ "Apache-2.0" ]
permissive
### 快速运行指南 想要使用 Cloud Kernel,您既可以运行预编译的二进制内核包,也可以从源码编译内核。请注意我们提供的默认内核配置文件是为阿里云 ECS 实例定制的版本,如果您想要将内核运行于非 ECS 平台上,您需要自行打开相关的内核模块开关并且重新编译内核。 ### 1 运行预编译二进制内核包(推荐) 首选方案是从 YUM 源安装: - 第一步,新建一个 YUM 仓库文件: ``` sudo vim /etc/yum.repos.d/alinux-2.1903-plus.repo ``` - 第二步,填入 repo 信息: ``` [plus] name=Alibaba Cloud Linux 2.1903 Plus Software Collections baseurl=http://mirrors.aliyun.com/alinux/2.1903/plus/x86_64/ enabled=1 gpgcheck=1 gpgkey=http://mirrors.aliyun.com/alinux/RPM-GPG-KEY-ALIYUN ``` - 第三步,安装内核: ``` sudo yum install -y kernel kernel-devel kernel-headers ``` - 第四步,重启并使用 Cloud Kernel. ### 2 从源码编译内核 - 第一步,从以下两种途径之一获取 Cloud Kernel 源码: - 从 [Releases](https://github.com/alibaba/cloud-kernel/releases) 页面获取最新的稳定版内核代码压缩包,并解压到当前目录; - 或者从项目 Git 树 Clone 代码: `git clone git@github.com:alibaba/cloud-kernel.git`. - 第二步,从 `configs` 分支获取[默认内核配置文件](https://github.com/alibaba/cloud-kernel/blob/configs/config-4.19.y-x86_64),重命名为 `.config`, 并复制到源码树的顶层目录下; - 第三步,通过下列命令编译并安装内核: ``` make oldconfig make -jN # N normally refers to the CPU core numbers on the system make modules -jN sudo make modules_install sudo make install ``` - 第四步,重启并使用 Cloud Kernel.
Swift
UTF-8
3,963
3.125
3
[]
no_license
//: [Previous](@previous) /*: A lot of times, the Mark 1 would grind to a halt soon after starting - and there was no user-friendly error message. Once, it was because a moth had flown into the machine - that gave us the term "bug", indicating an error on the code, and "debugging", correcting it. But most of the time, the bug was metaphorical - a wrongly flipped switch, a mispunched hole in the paper tape. */ import PlaygroundSupport import SpriteKit import AVFoundation class MarkIScene: SKScene { var bugsySprite: SKSpriteNode! var bugsyBaloonSprite: SKSpriteNode! var bugsyLabel: SKLabelNode! var bugWingsSound: AVAudioPlayer? var started = false override func didMove(to view: SKView) { let bugWingsSoundFile = URL(fileURLWithPath: Bundle.main.path(forResource: "bugWingsSound", ofType: "wav")!) do { bugWingsSound = try AVAudioPlayer(contentsOf: bugWingsSoundFile) } catch { print("error") } bugsySprite = childNode(withName: "//bugsySprite") as? SKSpriteNode bugsyBaloonSprite = childNode(withName: "//bugsyBaloonSprite") as? SKSpriteNode bugsyLabel = childNode(withName: "//bugsyLabel") as? SKLabelNode bugsySprite.name = "bugsy" bugsyLabel.text = "Oh, it's a bug...\nTake it off!" Timer.scheduledTimer(timeInterval: 7, target: self, selector: #selector(start), userInfo: nil, repeats: false) self.becomeFirstResponder() } @objc static override var supportsSecureCoding: Bool { // SKNode conforms to NSSecureCoding, so any subclass going // through the decoding process must support secure coding get { return true } } override var canBecomeFirstResponder: Bool { get { return true } } @objc func start() { started = true } override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) { for touch in touches { let location = touch.location(in: self) let touchedNode = nodes(at: location).first! if let name = touchedNode.name, name == "bugsy" { bugsyFly() } } } /*: Here we set the ladybug animation, making its textures change and moving it away from the screen. */ func bugsyFly() { let bugsyFlyTextures = [SKTexture(imageNamed: "bugsy_fly_1"), SKTexture(imageNamed: "bugsy_fly_2")] let bugsyTextureAnimation = SKAction.animate(with: bugsyFlyTextures, timePerFrame: 0.3) let bugsyFlyPosition = SKAction.sequence([.move(to: CGPoint(x: 916, y: 292), duration: 2), .move(to: CGPoint(x: 1240, y: 745), duration: 2)]) bugsySprite.xScale = -1 bugsySprite.run(.repeatForever(bugsyTextureAnimation)) bugsySprite.run(bugsyFlyPosition) { self.stopSound(self.bugWingsSound) self.bugsySprite.removeFromParent() } bugsyLabel.text = "Wait...Bugsy?!" bugsyBaloonSprite.run(.fadeIn(withDuration: 1)) playSound(bugWingsSound) } func playSound(_ sound: AVAudioPlayer?) { if let sound = sound { sound.prepareToPlay() sound.play() } } func stopSound(_ sound: AVAudioPlayer?) { if let sound = sound { sound.stop() } } } let sceneView = SKView(frame: CGRect(x:0 , y:0, width: 768, height: 1024)) if let scene = MarkIScene(fileNamed: "MarkIScene") { // Set the scale mode to scale to fit the window scene.scaleMode = .aspectFit // Present the scene sceneView.presentScene(scene) } PlaygroundSupport.PlaygroundPage.current.liveView = sceneView //: [Next](@next)
Python
UTF-8
389
3.765625
4
[]
no_license
def main(): numero = aux = int(input("Digite um número: ")) produto = numero while True: if numero != 0: numero -= 1 if numero != 0: produto *= numero elif produto == 0: produto = 1 elif numero == 0: break print(f'{aux} fatorial é {produto}.') if __name__ == '__main__': main()
Markdown
UTF-8
5,633
2.921875
3
[]
no_license
--- layout: post title: "Speaking Out Against Religion" date: 2007-01-01 21:51 comments: true sharing: true footer: true permalink: /2007/01/speaking-out-against-religion categories: [Religion] tags: [atheism, commentary, Religion] --- <p>One of the points that seems to come up a lot in atheist commentaries is the fact that religion holds some special place in our society that protects it from criticism. As <a href="http://www.samharris.org">Sam Harris</a> wrote in <a href="http://www.amazon.com/gp/product/0307265773?ie=UTF8&tag=brocklicom-20&linkCode=as2&camp=1789&creative=9325&creativeASIN=0307265773"><i>Letter to a Christian Nation</i></a>:</p> <blockquote>While believing strongly, without evidence, is considered a mark of madness or stupidity in any other area of our lives, faith in God still holds immense prestige in our society. Religion is the one area of our discourse where it is considered noble to pretend to be certain about things no human being could possibly be certain about.</blockquote> <p>It's true that discussing religion has long been considered impolite, and criticizing another person's religious beliefs is sometimes seen as cause for confrontation. The leap from religious criticism to religious intolerance isn't necessarily a difficault one to make.</p> <p>It's for that reason that I've always felt a little put off by Harris' writing. I enjoyed <i>Letter to a Christian Nation</i> when I read it a few months ago. Right now, my copy is probably sitting on my dad's pile of crap at home; when I was home for Christmas, I left it for him to read so he could get a sense of my stance on things (I included the disclaimer that Harris makes a much more aggressive argument than I do). It's true that I think belief in some higher deity, with absolutely no evidence, is a little ridiculous, but that's not really the way to make the argument. "I think you're core beliefs are ludicrous and you're just too ignorant to see it." You're not going to win any converts that way, for damn sure.</p> <p>However, this is pretty much the way Harris operates. Edge.org posted an article from him on Christmas: <a href="http://edge.org/3rd_culture/harris06/harris06_index.html">10 Myths - and 10 Truths - About Atheism</a>. Just before number 1, he offers this level-headed view of the situation:</p> <blockquote>Given that we know that atheists are often among the most intelligent and scientifically literate people in any society, it seems important to deflate the myths that prevent them from playing a larger role in our national discourse.</blockquote> <p>It's worth noting at this point that Myth #6 is "Atheists are arrogant."</p> <p>About a month before this article was published, Richard Dawkins addressed the issue on his website in <a href="http://richarddawkins.net/article,318,Im-an-atheist-BUT---,Richard-Dawkins">I'm An Atheist, BUT...</a></p> <blockquote><b>5. I'm an atheist, but I wish to dissociate myself from your intemperately strong language.</b></blockquote> <blockquote>Sam Harris and I have both received criticism of this kind... Yet if you look at the language we employ, it is no more strong or intemperate than anybody would use if criticizing a political or economic point of view: no stronger or more intemperate than any theatre critic, art critic or book critic when writing a negative review. Our language sounds strong and intemperate only because of the same weird convention I have already mentioned, that religious faith is uniquely privileged: above and beyond criticism.</blockquote> <blockquote>...Book critics or theatre critics can be derisively negative and earn delighted praise for the trenchant wit of their review. A politician may attack an opponent scathingly across the floor of the House and earn plaudits for his robust pugnacity. But let a critic of religion employ a fraction of the same direct forthrightness, and polite society will purse its lips and shake its head...</blockquote> <p>I think Dawkins is calling people like me the atheist equivalent of twice-a-year Catholics - the semi-devout who swell churches on Christmas and Easter, but don't feel guilty enough to attend mass every week.</p> <p>Expressing a negative opinion of a film maker's movie or an author's book is hardly on par with attacking someone's religious convictions. Dawkin's <a href="http://www.amazon.com/gp/product/0618680004?ie=UTF8&tag=brocklicom-20&linkCode=as2&camp=1789&creative=9325&creativeASIN=0618680004"><i>The God Delusion</i></a> has been on the New York Time's Best Seller list for 14 weeks now, so I'm hardly in a position to question his methods, but I can question the sustainability of them. Ideally, we will someday find ourselves in a society that values science over superstition and looks back fondly on the days of religious zealotry the same way we look back on the imaginary friends of our childhoods - how silly we were! - but this is not the way to get there.</p> <p>Maybe Harris and Dawkins are just interested in stirring up controversy so they can sell books. I don't care either way: at least they're bringing attention to the issue. However, I don't think that you can try to change someone's deeply-held beliefs about the world around them the same way you try to change their opinion about a movie or politics. It's true that religion holds a privileged, untouchable status in our society, but those are the rules one has to play by if one wants to do anything about it. Listing ten myths about atheism isn't going to change this country's perception of atheists if we just keep producing this self-righteous horseshit.</p>
C#
UTF-8
4,127
3.53125
4
[ "MIT" ]
permissive
using System; namespace SGL { /// <summary> /// Represent an ellipse defined by an origin point and two radii (along the X and Y axes). /// </summary> public class Ellipse : IEquatable<Ellipse> { /// <summary> /// The center of the ellipse. /// </summary> public Point Center { get => new Point(X, Y); set { X = value.X; Y = value.Y; } } /// <summary> /// The X-coordinate of the center of the ellipse. /// </summary> public double X { get; set; } /// <summary> /// The Y-coordinate of the center of the ellipse. /// </summary> public double Y { get; set; } /// <summary> /// The radius along the X-axis. /// </summary> public double RX { get; set; } /// <summary> /// The radius along the Y-axis. /// </summary> public double RY { get; set; } /// <summary> /// The area of the ellipse. /// </summary> public double Area => Math.PI * RX * RY; /// <summary> /// The outer perimeter of the ellipse. Synonymous with <see cref="Circumference"/>. /// </summary> public double Perimeter => Circumference; /// <summary> /// The outer perimeter of the ellipse. /// </summary> public double Circumference { get { if (Utils.Equals(RX, RY)) { return 2 * Math.PI * RX; } else { return CalculatePerimeter(RX, RY); } } } public Ellipse(double x, double y, double rx, double ry) { X = x; Y = y; RX = rx; RY = ry; } public Ellipse(double x, double y, double radius) { X = x; Y = y; RX = radius; RY = radius; } public Ellipse(Point p, double width, double height) { X = p.X; Y = p.Y; RX = width; RY = height; } public Ellipse(Point p, double radius) { X = p.X; Y = p.Y; RX = radius; RY = radius; } /// <summary> /// Checks whether the ellipse contains the point. /// </summary> public bool Contains(Point p) { return Math.Pow((X - p.X), 2) / (RX * RX) + Math.Pow((Y - p.Y), 2) / (RY * RY) <= 1; } public bool Equals(Ellipse other) { return Center == other.Center && RX == other.RX && RY == other.RY; } public override bool Equals(object obj) { return obj is Ellipse e && Equals(e); } public override int GetHashCode() { var hashCode = 1861411795; hashCode = hashCode * -1521134295 + base.GetHashCode(); hashCode = hashCode * -1521134295 + Center.GetHashCode(); hashCode = hashCode * -1521134295 + RX.GetHashCode(); hashCode = hashCode * -1521134295 + RY.GetHashCode(); return hashCode; } public override string ToString() { return Utils.Equals(RX, RY) ? $"Circle(Center = {Center}, Radius = {RX})" : $"Ellipse(Center = {Center}, RadiusX = {RX}, RadiusY = {RY})"; } public static bool operator ==(Ellipse a, Ellipse b) { return a.Equals(b); } public static bool operator !=(Ellipse a, Ellipse b) { return !a.Equals(b); } private static double CalculatePerimeter(double rx, double ry) { double diff = rx - ry; double sum = rx + ry; double h = diff * diff / (sum * sum); double p = Math.PI * sum * (1 + 0.25 * h + 0.015625 * h * h + 0.00390625 * h * h * h); return p; } } }
JavaScript
UTF-8
1,257
2.5625
3
[]
no_license
import React from 'react'; import PropTypes from 'prop-types'; import TimeStat from './component'; const onIntervalHOC = (propFunc, interval) => Component => class OnInterval extends React.Component { constructor(props) { super(props); this.state = propFunc(props); } componentWillMount() { this.interval = setInterval(this.update, interval); } componentWillReceiveProps(newProps) { this.update(newProps); } componentWillUnmount() { clearInterval(this.interval); } update = newProps => this.setState(propFunc(newProps || this.props)); render() { return ( <Component {...this.props} {...this.state}> {this.children} </Component> ); } }; const calculateDuration = props => ({ value: (props.value.getTime() - Math.floor(Date.now())) / 1000 }); const TimeStatContainer = ({ type, value }) => { const Component = type === 'duration' ? TimeStat : onIntervalHOC(calculateDuration, 1000)(TimeStat); return <Component value={value} />; }; TimeStatContainer.propTypes = { value: PropTypes.oneOfType([PropTypes.number, PropTypes.instanceOf(Date)]).isRequired, type: PropTypes.string.isRequired }; export default TimeStatContainer;
PHP
ISO-8859-1
1,006
2.734375
3
[]
no_license
<?php class Videos extends ModuloDB { public function Videos( $cod = '' ) { $this->tabela = "site_videos"; $this->tituloModulo = 'VDEOS'; $this->chave = 'VideoID'; $this->ModuloDB(); if ( $cod ) $this->configDb($cod); } function getCampos( $camposRequisitados = array('VideoID', 'Titulo', 'Descricao', 'Link', 'Ativo' ) ) { if (in_array('VideoID', $camposRequisitados)) $campos[] = new fId('VideoID',true); if (in_array('Titulo', $camposRequisitados)) $campos[] = new fChar('Titulo','Titulo:',true,200,200,true); if (in_array('Descricao', $camposRequisitados)) $campos[] = new fTexto('Descricao','Descrio:', false); if (in_array('Link', $camposRequisitados)) $campos[] = new fChar('Link','Link:',true,200,200,true); if (in_array('Ativo', $camposRequisitados)) $campos[] = new fSimNao('Ativo', 'Publicado:'); return $campos; } function getTableDefinition() { return $this->getCampos(); } }
C++
UTF-8
635
3.8125
4
[]
no_license
//// Happy number : sum of the digit with squrt iteratively. Return T/F whether sum is 1 / infinite loops. //// Tags : [math] //// [Easy] #include <iostream> using namespace std; // 01, my code recursive solution : time O(n), space O(1) bool isHappy(int n){ int sqrtsum = 0, next = n; while( next ){ int cur = next%10; sqrtsum += cur*cur; next = next/10; } // cout<<n<<" "<<sqrtsum<<endl; // range of [2,6] is infinte loops if( sqrtsum == 1 ) return 1; else if( sqrtsum > 6 ) return isHappy(sqrtsum); else return 0; } int main(){ int n=19; cout<<isHappy(n)<<endl; }
Java
UTF-8
2,630
3.140625
3
[]
no_license
import java.io.*; import java.util.*; public class Main { public static void solution(int[] arr, int vidx, int n, int k, int[] subsetSum, int conessf, ArrayList < ArrayList < Integer >> ans) { //write your code here if (vidx == arr.length) { if (conessf == k) { //if sum of each subset is equal or not for (int i = 0; i < subsetSum.length - 1; i++) { if (subsetSum[i] != subsetSum[i + 1]) { return; } } for (int i = 0; i < ans.size(); i++) { System.out.print(ans.get(i) + " "); } System.out.println(); } return; } int ce = arr[vidx]; for (int s = 0; s < k; s++) { //to combine with non-empty if (ans.get(s).size() > 0) { ans.get(s).add(ce); subsetSum[s] += ce; solution(arr, vidx + 1, n, k, subsetSum, conessf, ans); ans.get(s).remove(ans.get(s).size() - 1); subsetSum[s] -= ce; } //to add in first empty subset else { ans.get(s).add(ce); subsetSum[s] += ce; solution(arr, vidx + 1, n, k, subsetSum, conessf + 1, ans); ans.get(s).remove(ans.get(s).size() - 1); subsetSum[s] -= ce; break; } } } public static void main(String[] args) { Scanner scn = new Scanner(System.in); int n = scn.nextInt(); int[] arr = new int[n]; int sum = 0; for (int i = 0; i < arr.length; i++) { arr[i] = scn.nextInt(); sum += arr[i]; } int k = scn.nextInt(); // if k is equal to 1, then whole array is your answer if (k == 1) { System.out.print("["); for (int i = 0; i < arr.length; i++) { System.out.print(arr[i] + ", "); } System.out.println("]"); return; } //if there are more subsets than no. of elements in array or sum of all elements is not divisible by k if (k > n || sum % k != 0) { System.out.println("-1"); return; } int[] subsetSum = new int[k]; ArrayList < ArrayList < Integer >> ans = new ArrayList < > (); for (int i = 0; i < k; i++) { ans.add(new ArrayList < > ()); } solution(arr, 0, n, k, subsetSum, 0, ans); } }
Java
UTF-8
3,032
2.890625
3
[]
no_license
package fr.carbonit.treasuremap.data; import fr.carbonit.treasuremap.exception.MapFileException; import fr.carbonit.treasuremap.map.component.Component; import fr.carbonit.treasuremap.map.Map; import fr.carbonit.treasuremap.map.component.character.Moveable; import fr.carbonit.treasuremap.map.component.character.command.Command; import java.util.ArrayList; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; public class DataMapper { public static Map map(List<FileData> fileDataList) { /* All components without the adventurer */ List<FileData> filteredData = fileDataList.stream() .filter(data -> data.getType() != Type.A && data.getType() != Type.C) .collect(Collectors.toList()); List<Component> components = createComponents(filteredData); Moveable adventurer = createAdventurer(fileDataList); List<Command> commands = createCommands(fileDataList); return createMap(fileDataList, components, adventurer, commands); } private static FileData getAdventurerFileData(List<FileData> fileDataList) { Optional<FileData> optional = fileDataList.stream().filter(data -> data.getType() == Type.A).findFirst(); if(!optional.isPresent()) { throw new MapFileException("Didn't find any adventurer configuration in the input file"); } return optional.get(); } private static List<Command> createCommands(List<FileData> fileDataList) { return ComponentCreators.createCommands(getAdventurerFileData(fileDataList)); } private static Moveable createAdventurer(List<FileData> fileDataList) { return ComponentCreators.createAdventurer(getAdventurerFileData(fileDataList)); } private static List<Component> createComponents(List<FileData> fileDataList) { List<Component> componentList = new ArrayList<>(); for (FileData fileData : fileDataList) { switch (fileData.getType()) { case M: componentList.add( ComponentCreators.createMountain(fileData) ); break; case T: componentList.add( ComponentCreators.createTreasure(fileData) ); default: } } return componentList; } private static Map createMap(List<FileData> fileDataList, List<Component> components, Moveable adventurer, List<Command> commands) { Optional<FileData> optional = fileDataList.stream().filter(data -> data.getType() == Type.C).findAny(); if(!optional.isPresent()) { throw new MapFileException("Didn't find any map configuration in the input file"); } return ComponentCreators.createMap(optional.get(), components, adventurer, commands); } }
JavaScript
UTF-8
617
2.515625
3
[]
no_license
var jwt = require('jwt-simple'); var secret = 'ONSHOPCHANAKALK'; exports.createtoken = function(req,res) { var payload = { name: req.name, email:req.email,isseller:req.isseller, date:Date.now()}; var token = jwt.encode(payload, secret,'HS512'); return token; } exports.isvaliduser = function(req,res){ try{ var body = JSON.parse(req); var decode = jwt.decode(body.token, secret); if(body.email==decode.email){ return true; }else{ return false; } }catch(err){ return false } }
Markdown
UTF-8
4,699
3.5
4
[]
no_license
## Week Two - Module 2 Recap Fork or re-pull this respository. Answer the questions to the best of your ability. Try to answer them with limited amount of external research. These questions cover the majority of what we've learned this week (which is a TON - YOU are a web developer!!!). Note: When you're done, submit a PR. ### Week 2 Questions **At a high level, what is ActiveRecord? What does it do/allow you to do?** ActiveRecord is an ORM that allows you to do SQL operations on a Ruby object that models a record in your database. **Assume you have the following model:** ```ruby class Team << ActiveRecord::Base end ``` **What are some methods you can call on `Team`? If these methods aren't defined in the class, how do you have access to them?** .find, .all and .sum are two methods that you have access to. These are ActiveRecord methods that you have access to because Team is inheriting from the ActiveRecord base. **Assume that in your database, a team has the following attributes: "id", "name", owner_id". How would you find the name of a team with an id of 4? Assuming your class only included the code from question 2, how could you find the owner of the same team?** a) Team.find(4) b) Team.find_by(:owner_id = 4) **Assume that you added a line to your `Team` class as follows:** ```ruby class Team << ActiveRecord::Base belongs_to :owner end ``` **Now how would you find the owner of the team with an id of 4?** Team.find(4).owner **In a database that's holding students and teachers, what will be the relationship between students and teachers? Draw the schema diagram.** Teacher has many students | ID | Name | | -- |-------------| | 1 | Ms. Brown | | 2 | Mr. Baker | | 3 | Mr. Smith | Student belongs to a teacher | ID | Name | Teacher_id | | -- |----------|------------| | 1 | Lala | 1 | | 2 | Margaret | 1 | | 3 | Wilson | 3 | **Define foreign key, primary key, and schema.** A foreign key is a field on a table that references the id of a record on another table in order to access information on the second table vis a vi a SQL query. A primary key is a unique identifier, often a number, for a single record in a table. The schema is a blueprint of your entire database that defines all tables and their fields, including indexed fields and foreign keys. **Describe the relationship between a foreign key on one table and a primary key on another table.** Essentially, the foreign key on one table is the primary key of another table. In the team example, the teams table would have a foreign key of owner_id, and the owner table has a primary key of owner. But both keys point to the same owner record. **What are the parts of an HTTP response?** The head and the body, where the head contains key value pairs that format the response. And then the body, which actually contains all the HTML-formatted information that the user wants. ### Optional Questions **Name your five favorite ActiveRecord methods (i.e. methods your models inherit from ActiveRecord) and describe what they do.** * .select > allows you to say what information you want back from your query. One of my favs bc that's where the computation happens * .group > allows you to organize the info from your query. One of my favs bc I forget it, then putting it in saves the day * .join > allows you to query two (or more?) tables at once. One of my favs bc it is v. powerful. **Name your three favorite ActiveRecord rake tasks and describe what they do.** * rake db:setup > combines create, migrate and seed * rake db:test:prepare > creates test enviroment that reflects production enviroment **What two columns does `t.timestamps null: false` create in our database?** created_at and updated_at **In a database that's holding schools and teachers, what will be the relationship between schools and teachers?** A school will have many teachers, and a teacher will belong to a school. 5. In the same database, what will you need to do to create this relationship (draw a schema diagram)? 6. Give an example of when you might want to store information besides ids on a join table. 7. Describe and diagram the relationship between patients and doctors. 8. Describe and diagram the relationship between museums and original_paintings. 9. What could you see in your code that would make you think you might want to create a partial? ### Self Assessment: Choose One: * I was able to answer every question without relying on outside resources (I'm not sure that every answer is perfectly correct, but I think it's at least quite close.) Choose One: * I feel comfortable with the content presented this week
Java
UTF-8
8,153
2.28125
2
[]
no_license
package com.example.todoapp.Activities; import androidx.appcompat.app.AppCompatActivity; import androidx.fragment.app.DialogFragment; import android.app.AlarmManager; import android.app.DatePickerDialog; import android.app.TimePickerDialog; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.graphics.Typeface; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.DatePicker; import android.widget.EditText; import android.widget.TextView; import android.widget.TimePicker; import android.widget.Toast; import com.example.todoapp.Fragments.DatePickerFragment; import com.example.todoapp.Fragments.TimePickerFragment; import com.example.todoapp.Models.Task; import com.example.todoapp.Utils.DatabaseHelper; import com.example.todoapp.R; import com.example.todoapp.Utils.NotificationHelper; import java.text.DateFormat; import java.util.Calendar; public class NewTaskActivity extends AppCompatActivity implements TimePickerDialog.OnTimeSetListener, DatePickerDialog.OnDateSetListener { public TextView newTaskTitle, taskTitleLabel, taskDescLabel, taskDateLabel, taskTimeLabel, taskAlarmTimeLabel; public EditText taskTitle, taskDesc, taskDate, taskTime, taskAlarmTime; public Button btnCreate, btnCancel; public DatabaseHelper databaseHelper; public Calendar calendar; public String selectedDate; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_new_task); this._bindElements(); this._initTextFont(); this._bindEvents(); } @Override public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) { calendar.set(Calendar.YEAR, year); calendar.set(Calendar.MONTH, month); calendar.set(Calendar.DAY_OF_MONTH, dayOfMonth); _updateDateText(); } private void _updateDateText() { String dateText = DateFormat.getDateInstance(DateFormat.SHORT).format(calendar.getTime()); taskDate.setText(dateText); } @Override public void onTimeSet(TimePicker view, int hourOfDay, int minute) { calendar.set(Calendar.HOUR_OF_DAY, hourOfDay); calendar.set(Calendar.MINUTE, minute); calendar.set(Calendar.SECOND, 0); _updateTimeText(); } private void _updateTimeText() { String timeText = DateFormat.getTimeInstance(DateFormat.SHORT).format(calendar.getTime()); taskTime.setText(timeText); } private void _bindEvents() { taskDate.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { DialogFragment datePicker = new DatePickerFragment(); datePicker.show(getSupportFragmentManager(), DatePickerFragment.DATE_PICKER_TAG); } } }); taskDate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { DialogFragment datePicker = new DatePickerFragment(); datePicker.show(getSupportFragmentManager(), DatePickerFragment.DATE_PICKER_TAG); } }); taskTime.setOnFocusChangeListener(new View.OnFocusChangeListener() { @Override public void onFocusChange(View v, boolean hasFocus) { if (hasFocus) { DialogFragment timePicker = new TimePickerFragment(); timePicker.show(getSupportFragmentManager(), TimePickerFragment.TIME_PICKER_TAG); } } }); taskTime.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { DialogFragment timePicker = new TimePickerFragment(); timePicker.show(getSupportFragmentManager(), TimePickerFragment.TIME_PICKER_TAG); } }); btnCreate.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String title = taskTitle.getText().toString().trim(); String description = taskDesc.getText().toString().trim(); String date = taskDate.getText().toString().trim(); String time = taskTime.getText().toString().trim(); String alarmTimeText = taskAlarmTime.getText().toString().trim(); int alarmTime = 0; if (!alarmTimeText.isEmpty()) { alarmTime = Integer.parseInt(alarmTimeText); } if (title.isEmpty() || date.isEmpty() || time.isEmpty()) { Toast.makeText(NewTaskActivity.this, "Please fill in missing fields", Toast.LENGTH_SHORT).show(); return; } databaseHelper.QueryData("INSERT INTO TodoList VALUES (null, '"+ title +"', '" + description + "', '" + date + "', '" + time + "', " + alarmTime + ")"); Cursor data = databaseHelper.GetData("SELECT last_insert_rowid()"); if (data.moveToNext()) { int id = data.getInt(0); Task task = new Task(id, title, description, date, time, alarmTime); AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE); NotificationHelper.scheduleBroadcast(NewTaskActivity.this, alarmManager, task, calendar.getTimeInMillis() - alarmTime * 60 * 1000); Toast.makeText(NewTaskActivity.this, "Created new task successfully", Toast.LENGTH_SHORT).show(); } _backToMainActivity(); } }); btnCancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { _backToMainActivity(); } }); } private void _backToMainActivity() { finish(); } private void _initTextFont() { // import font Typeface MLight = Typeface.createFromAsset(getAssets(), "fonts/ML.ttf"); Typeface MMedium = Typeface.createFromAsset(getAssets(), "fonts/MM.ttf"); // customize font newTaskTitle.setTypeface(MMedium); taskTitleLabel.setTypeface(MLight); taskTitle.setTypeface(MMedium); taskDescLabel.setTypeface(MLight); taskDesc.setTypeface(MMedium); taskDateLabel.setTypeface(MLight); taskDate.setTypeface(MMedium); taskTimeLabel.setTypeface(MLight); taskTime.setTypeface(MMedium); taskAlarmTimeLabel.setTypeface(MLight); taskAlarmTime.setTypeface(MMedium); btnCreate.setTypeface(MMedium); btnCancel.setTypeface(MLight); } private void _bindElements() { newTaskTitle = findViewById(R.id.new_task_title); taskTitleLabel = findViewById(R.id.task_title_label); taskDescLabel = findViewById(R.id.task_desc_label); taskDateLabel = findViewById(R.id.task_date_label); taskTimeLabel = findViewById(R.id.task_time_label); taskAlarmTimeLabel = findViewById(R.id.task_alarm_time_label); taskTitle = findViewById(R.id.task_title); taskDesc = findViewById(R.id.task_desc); taskDate = findViewById(R.id.task_date); taskTime = findViewById(R.id.task_time); taskAlarmTime = findViewById(R.id.task_alarm_time); btnCreate = findViewById(R.id.btn_create); btnCancel = findViewById(R.id.btn_cancel); // init database databaseHelper = new DatabaseHelper(this, "TodoApp.sqlite", null, 1); databaseHelper.AssertTableTodoListExist(); // init date calendar = Calendar.getInstance(); // get date from intent Intent intent = getIntent(); selectedDate = intent.getStringExtra("date"); taskDate.setText(selectedDate); } }
C#
UTF-8
1,273
3.046875
3
[ "MIT" ]
permissive
using System; using Discord.Rest; using Discord.WebSocket; namespace Discord { /// <summary> /// Contains extension methods for abstracting <see cref="IRole"/> objects. /// </summary> internal static class RoleAbstractionExtensions { /// <summary> /// Converts an existing <see cref="IRole"/> to an abstracted <see cref="IRole"/> value. /// </summary> /// <param name="role">The existing <see cref="IRole"/> to be abstracted.</param> /// <exception cref="ArgumentNullException">Throws for <paramref name="role"/>.</exception> /// <returns>An <see cref="IRole"/> that abstracts <paramref name="role"/>.</returns> public static IRole Abstract(this IRole role) => role switch { null => throw new ArgumentNullException(nameof(role)), RestRole restRole => RestRoleAbstractionExtensions.Abstract(restRole) as IRole, SocketRole socketRole => SocketRoleAbstractionExtensions.Abstract(socketRole) as IRole, _ => throw new NotSupportedException($"Unable to abstract {nameof(IRole)} type {role.GetType().Name}") }; } }
Java
UTF-8
1,160
2.28125
2
[]
no_license
package org.vermeg.bookstore.service; import java.util.List; import javax.transaction.Transactional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.vermeg.bookstore.interfaces.AchatInterface; import org.vermeg.bookstore.model.Achat; @Service("achatService") public class AchatService { @Autowired AchatInterface achatInterface; @Transactional public List<Achat> getAllAchats(int orderid) { return achatInterface.getAllAchats(orderid); } @Transactional public Achat getAchat(int id) { return achatInterface.getAchat(id); } @Transactional public void addAchat(Achat livre) { achatInterface.addAchat(livre); } @Transactional public void updateAchat(Achat livre) { achatInterface.updateAchat(livre); } @Transactional public void deleteAchat(int id) { achatInterface.deleteAchat(id); } public double calculeTotal(List<Achat> listOfAchats) { double somme=0; int i=0; do { somme = somme+listOfAchats.get(i).getPrixpd(); i++; } while(i<listOfAchats.size()); return somme; } }
Python
UTF-8
553
3.5625
4
[]
no_license
""" Substring search input: string s, pattern p output: index i,j st. s[i,j]=p Test.py """ from BruteSearch import Solution Object=Solution() fp=open("test_data.txt") data=fp.readlines() Input=[] Output=[] for line in data: string,pattern,index=line.split(' ') Input.append([string,pattern]) Output.append(int(index)) for k in range(len(Input)): input_data=Input[k] #print(input_data) i=Object.findPattern(input_data[0],input_data[1]) if(i!=Output[k]): print("error") print(input_data) print("expected: ",Output[k], " Output: ",i)
Python
UTF-8
2,417
4.3125
4
[]
no_license
# https://leetcode-cn.com/problems/replace-words/ """ 在英语中,我们有一个叫做 词根(root)的概念,它可以跟着其他一些词组成另一个较长的单词——我们称这个词为 继承词(successor)。 例如,词根an,跟随着单词 other(其他),可以形成新的单词 another(另一个)。 现在,给定一个由许多词根组成的词典和一个句子。你需要将句子中的所有继承词用词根替换掉。 如果继承词有许多可以形成它的词根,则用最短的词根替换它。 你需要输出替换之后的句子。 示例 1: 输入: dict(词典) = ["cat", "bat", "rat"] sentence(句子) = "the cattle was rattled by the battery" 输出: "the cat was rat by the bat" """ ####使用内置函数startwith # 执行用时 :192 ms, 在所有 python3 提交中击败了58.46%的用户 # 内存消耗 :18.5 MB, 在所有 python3 提交中击败了30.61%的用户 """ class Solution: def replaceWords(self, dict: list, sentence: str) -> str: dict.sort() s = sentence.split(' ') for i, word in enumerate(s): for j in dict: if word.startswith(j): s[i] = j break return ' '.join(s) """ ###使用字典树 # 执行用时 :96 ms, 在所有 Python3 提交中击败了80.43%的用户 # 内存消耗 :27.8 MB, 在所有 Python3 提交中击败了18.37%的用户 class Solution: def replaceWords(self, dict: list, sentence: str) -> str: d = {} # 一定是需要一个额外的t字典的,如果不存在的话,那每次最后都是{“end”:True} for word in dict: t = d for c in word: if c not in t: t[c] = {} t = t[c] t["end"] = True def fnd(word: list): t = d for i, c in enumerate(word): if "end" in t: return word[:i] elif c in t: t = t[c] else: return word return " ".join(map(fnd, sentence.split(" "))) if __name__ == "__main__": dict = ["cat", "bat", "rat"] sentence = "the cattle was rattled by the battery" solution = Solution() result = solution.replaceWords(dict, sentence) print(result)
Python
UTF-8
34,406
3.015625
3
[ "LicenseRef-scancode-warranty-disclaimer", "MIT" ]
permissive
'''This module simulate a river-valley system based on user inputs. Usage: python3 riverbuilder <path.to.input.txt> <outputFolderName> path.to.input.txt -- Absolute or relative path to an input file that contains all parameters needed to build a river. outputFolderName -- Name of the folder that output files will be stored in. If the folder doesn't exist, then it will be created. Its overall mechanism is: 1. Parse inputs from input file. 2. Check and convert inputs. 3. Build a corresponding river. 4. Build a corresponding valley. ''' from .functions import * from .cChannel import Channel from .cValley import Valley from math import pi from decimal import Decimal import sys import csv import os import re import copy import traceback import numpy as np import matplotlib.pyplot as plt import matplotlib as mpl from datetime import datetime ALLOWFUN = set(["MASK", "SIN", "COS", "LINE", "PERLIN", "SINSQ", "COSSQ", "CNOIDAL", "STEP", "HIGHCURV"]) FUNPARANUM = {"SIN":4, "COS":4, 'SINSQ':4, 'COSSQ':4, "LINE":3, "PERLIN":4, "CNOIDAL":5, "STEP":5, "HIGHCURV": 5} XSHAPES = set(['AU', 'SU', 'EN']) ADDON = {'BEG':[], 'CD':[]} def defaultFunction(x): '''The default function for any function calculations, which returns a line without fluctuation.''' return x, np.array([0]*len(x)) def readTXTFunctionFile(nameId, paraDict, paraName, textName): try: f = open(textName, "r") except IOError: log = "Error! "+textName+" is not found in current folder:\n"+os.getcwd()+"\nProgram exits.\n" print(log) sys.exit() lines = f.readlines() funID = 0 funList = [] for line in lines: if line.startswith('#') or '=' not in line: continue [name, val] = line.strip().split('=') if name in paraDict: name = re.split('\d+', name)[0] name = name + '0' + str(nameId) + str(funID) funID += 1 paraDict[name] = val if not name.startswith('MASK'): funList.append(name) funList = '+'.join(funList) if paraName in paraDict: paraDict[paraName] = paraDict[paraName] + '+' + funList else: paraDict[paraName] = funList return paraDict def fileParser(fname): '''Parse a file, return a dictionary fname -- str: path to file Return: outdict -- dictionary, both key and value are string Exception: IOError -- program will exit. ''' outdict = {} try: f = open(fname, "r") except IOError: log = "Error! "+fname+" is not found in current folder:\n"+os.getcwd()+"\nProgram exits.\n" print(log) sys.exit() lines = f.readlines() addonSet = ADDON.keys() p = re.compile('[A-Z]+') nameID = 0 for line in lines: if line.startswith('#') or '=' not in line: continue [name, val] = line.strip().split('=') # check if it is an add-on: m = p.match(name) if m.group() is not None and m.group() in addonSet: ADDON[m.group()].append(val) continue if val.endswith('txt'): outdict = readTXTFunctionFile(nameID, outdict, name, val) nameID += 1 continue if name not in outdict: outdict[name] = val else: outdict[name] = outdict[name]+"+"+val return outdict #def fileParser(fname): # '''Parse a file, return a dictionary # # fname -- str: path to file # # Return: # outdict -- dictionary, both key and value are string # # Exception: # IOError -- program will exit. # ''' # outdict = {} # try: # f = open(fname, "r") # except IOError: # log = "Error! "+fname+" is not found in current folder:\n"+os.getcwd()+"\nProgram exits.\n" # print(log) # sys.exit() # # lines = f.readlines() # addonSet = ADDON.keys() # p = re.compile('[A-Z]+') # for line in lines: # if line.startswith('#') or '=' not in line: # continue # [name, val] = line.strip().split('=') # # check if it is an add-on: # m = p.match(name) # if m.group() is not None and m.group() in addonSet: # ADDON[m.group()].append(val) # continue # # if name not in outdict: # outdict[name] = val # else: # outdict[name] = outdict[name]+"+"+val # # return outdict # # def paraCheck(fdict, name, defaultVal, valType, sign=0): '''Check if the value for a key in a dictionary is valid, return updated dictionary fdict -- dictionary needs to be checked and updated name -- the key in fdict need to be checked defaultVal -- default value for name in fdict when checked failed valType -- str that indicate appropriate type of value for name in fdict sign -- -1, 0, or 1 represents whether value should be positive, real, or negative Return: fdict -- updated dictionary with correct value for name log -- str that is empty or alert information ''' log = "" if name not in fdict: fdict[name] = defaultVal log += 'Alert! '+name+' is not defined by user, use default value '+str(defaultVal)+' instead.\n' return fdict, log if valType == 'str': return fdict, log try: val = float(fdict[name]) except: log += "Alert! Can't not convert value for "+name+" to a number.\n Use default value "+defaultVal+" instead.\n" fdict[name] = defaultVal if valType == "int": fdict[name] = int(fdict[name]) elif valType == "float": fdict[name] = float(fdict[name]) if sign != 0 and fdict[name]*sign < 0: log += "Alert! The sign of value of "+name+" is incorrect. Change to the opposite.\n" fdict[name] = -1* fdict[name] return fdict, log def getfunParas(val, funDict): '''Parse parameter set string for a function, return a correct callable function. val -- parameter set string Constrains: This function should only be called when both name and val are in correct form. ''' val = val[1:-1].split(",") mask = val.pop().strip() if mask.startswith('MASK'): if mask in funDict: mask = funDict[mask] else: mask = ['ALL'] for i in range(len(val)): num = val[i] num = num.strip() exp = re.split(r'[/*+-]', num) if exp[0].strip() == '': exp[0] = 0 exp = [pi if x == "pi" else float(x) for x in exp] if len(exp) == 1: val[i] = float(exp[0]) continue if '+' in num: val[i] = exp[0] + exp[1] elif '-' in num: val[i] = exp[0] - exp[1] elif '*' in num: val[i] = exp[0] * exp[1] elif '/' in num: val[i] = exp[0] / exp[1] val.append(mask) return val def forgeFun(name, val): ''' name -- name of function ''' if name == "SIN": return lambda x: sin_v(x, *val) elif name == "COS": return lambda x: cos_v(x, *val) elif name == "SINSQ": return lambda x: sin_sq(x, *val) elif name == "COSSQ": return lambda x: cos_sq(x, *val) elif name == "LINE": return lambda x: line_v(x, *val) elif name == "PERLIN": return lambda x: perlin(x, *val) elif name == "CNOIDAL": return lambda x: cnoidal(x, *val) elif name == "STEP": return lambda x: step(x, *val) elif name == "HIGHCURV": return lambda x: highCurv(x, *val) def buildFunDict(fdict): '''Given a dictionary, extract and parse all allowed functions in it and return a new dictionary fdict -- dictionary that may contains allowed functions which are in str type. Return: funDict -- dictionary that contains allowed functions which values are callable functions. log -- str that record all successfully parsed functions and alert msg. Constrains: Need to defined allowFun and modify funValCheck and forgeFun when the code is changed. ''' log = "" p = re.compile('[A-Z]+') funDict = {} notMaskFuns = [] for name, val in fdict.items(): if not isinstance(val, str): continue name = name.strip() val = val.strip() m = p.match(name) if (val.startswith("(") and val.endswith(")") and m is not None and m.group() in ALLOWFUN): if m.group() == 'MASK': funDict[name] = val[1:-1].split(',') continue if not funValCheck(m.group(), val): log += "Can't parse function "+ name +'\n' continue notMaskFuns.append([name, m.group(), val]) for [name, funType, val] in notMaskFuns: funParas = getfunParas(val, funDict) funDict[name] = forgeFun(funType, funParas) log += "User defined funtions are:\n" for fun in funDict: log += fun+' '+fdict[fun]+'\n' return funDict, log def funValCheck(name, val): '''Check if parameter set string is correct for a function, return boolean name -- name of function val -- parameter set string in form (n1, n2, ...) ''' val = val[1:-1].split(",") if len(val) != FUNPARANUM[name]: return False val[-1] = val[-1].strip() if val[-1].startswith("MASK"): val.pop() for num in val: num = num.strip() p = re.compile("(\d+.?\d*|pi)") splitlist = re.split(r'[/*+-]', num) for i in range(len(splitlist)): part = splitlist[i] part = part.strip() if i == 0 and part == '': continue m = p.match(part) if not m: return False if m.span() != (0, len(part)): return False return True def printPara(name, fdict): '''Return a name value pair in dictionary in string form.''' return name+' is set to: '+str(fdict[name])+'\n' def inputCheck(fdict): '''Check keys and values in dictionary, return updated dictionaries that contains all important information to build river and valley. fdict -- dictionary need to be checked Return: fdict -- updated dictionary with correct key and value pairs funDict -- dictionary with values as callable functions log -- string format log ''' log = '' fdict, info = paraCheck(fdict, "Datum", 10, "float") log += info log += printPara("Datum", fdict) fdict, info = paraCheck(fdict, "Length", 1000, "float", 1) log += info log += printPara("Length", fdict) fdict, info = paraCheck(fdict, "X Resolution", 1, "float", 1) log += info log += printPara("X Resolution", fdict) fdict, info = paraCheck(fdict, "Channel XS Points", 21, "int", 1) log += info log += printPara("Channel XS Points", fdict) fdict, info = paraCheck(fdict, "Valley Slope (Sv)", 0.001, "float") log += info log += printPara("Valley Slope (Sv)", fdict) fdict, info = paraCheck(fdict, "Critical Shields Stress (t*50)", 0.06, "float") log += info log += printPara("Critical Shields Stress (t*50)", fdict) fdict, info = paraCheck(fdict, "Inner Channel Lateral Offset Minimum", 10, "float", 1) log += info log += printPara("Inner Channel Lateral Offset Minimum", fdict) fdict, info = paraCheck(fdict, "Inner Channel Depth Minimum", 0, "float", 0) log += info log += printPara("Inner Channel Depth Minimum", fdict) fdict, info = paraCheck(fdict, "Median Sediment Size (D50)", 0.01, "float", 1) log += info log += printPara("Median Sediment Size (D50)", fdict) fdict, info = paraCheck(fdict, "Left Valley Boundary Lateral Offset Minimum", 10, "float", 1) log += info log += printPara("Left Valley Boundary Lateral Offset Minimum", fdict) fdict, info = paraCheck(fdict, "Left Valley Boundary Height Offset", 20, "float", 1) log += info log += printPara("Left Valley Boundary Height Offset", fdict) fdict, info = paraCheck(fdict, "Right Valley Boundary Lateral Offset Minimum", 10, "float", 1) log += info log += printPara("Right Valley Boundary Lateral Offset Minimum", fdict) fdict, info = paraCheck(fdict, "Right Valley Boundary Height Offset", 20, "float", 1) log += info log += printPara("Right Valley Boundary Height Offset", fdict) fdict, info = paraCheck(fdict, "Inner Channel Average Bankfull Width", None, "float", 1) log += info log += printPara("Inner Channel Average Bankfull Width", fdict) fdict, info = paraCheck(fdict, "Inner Channel Average Bankfull Depth", None, "float", 1) log += info log += printPara("Inner Channel Average Bankfull Depth", fdict) fdict, info = paraCheck(fdict, "River Slope", None, "float", 1) log += info log += printPara("River Slope", fdict) fdict, info = paraCheck(fdict, "Smooth", 0, "int", 1) log += info log += printPara("River Slope", fdict) log += '' funDict, info = buildFunDict(fdict) log += info return fdict, funDict, log def funParser(funString, funDict, defaultFun): '''Parse a string of different functions, return a callable aggregate function. funString -- string in format "SIN1+COS2+LINE3" funDict -- dictionary with key as individual function name, and value as corresponding callable function Return: outFun -- callable aggregated function log -- string log ''' log = '' funs = funString.split("+") notIn = True highcurvFlag = False for i in range(len(funs)): fun = funs[i] if fun in funDict: notIn = False else: log += "Alert! Can't find function "+fun+" in user-defined functions. Ignore function "+fun+'.\n' #switch the high curv functions to the top if fun.startswith('HIGHCURV'): funs.pop(i) if highcurvFlag: log += "Error! Can only have one HIGHCURV function! Extra ones will be ignored!" continue funs.insert(0, fun) highcurvFlag = True if notIn: return defaultFun, log def outFun(x): outSum = 0 for fun in funs: if fun in funDict: x, out = funDict[fun](x) outSum += out return x, outSum return outFun, log def buildFun(name, fdict, funDict, fun): '''Return an appropriate callable function for a given name. name -- the thing that we want to assign a function fdict -- dictionary to look up what kind of functions are needed for name funDict -- dictionary with key as individual function name, and value as corresponding callable function fun -- default function if the check is failed Return: outFun -- callable function for name log -- string log ''' log = '' outFun = fun if name in fdict: outFun, info = funParser(fdict[name], funDict, outFun) log += info else: log += "Alert! Can't find function "+name+" in user-defined functions. Ignore function "+name+'.\n' return outFun, log def addLevels(pattern, fdict, funDict, default_fun,direction, obj): '''Add levels to river or valley in a given direction. pattern -- regex pattern that match the name of levels fdict -- dictionary that gives information of levels wanted to add funDict -- dictionary contain individaul function information default_fun -- default function if check or parse fails direction -- string "left" or "right" obj -- a Channel object or Valley object Return: obj -- an updated obj with levels added log -- string log ''' log = '' levels = [] for name, val in fdict.items(): m = pattern.match(name) if m: levels.append(name) levels.sort() for name in levels: funName = name[:-22] + "Function" fun, info = buildFun(funName, fdict, funDict, default_fun) log += info fdict, info = paraCheck(fdict, name, 10, "float", 1) log += info y_offset = fdict[name] hightName = name[:-22]+"Height Offset" fdict, info = paraCheck(fdict, hightName, 10, "float") log += info z_offset = fdict[hightName] thalweg = obj.getThalweg() if hasattr(obj, 'channel'): z_pre = thalweg else: orig_thalweg = thalweg+obj.channelUndulation thalweg_max = np.amax(orig_thalweg) z_pre = thalweg_max - obj.channelUndulation obj.setLevel(z_offset, z_pre, y_offset, direction, fun) if funName in fdict: log += "Creating "+name[:-22]+"with function: "+str(fdict[funName])+'\n' else: log += "Creating "+name[:-22]+"with constant width: "+str(fdict[name])+'\n' return obj, log def loopParameter(para, target, obj, buildfun, calfun): '''Rebuild the channel again and again until a parameter reach target value. para - parameter that will be modified every loop target - target value of the parameter minimum - minimum offset set for the parameter obj - channel or river buildfun - function that used to build the parameter, ex: channel.createInnerChannel calfun - function that used to calculate the parameter Return: obj - object with a target paraName log - string log ''' log = '' count = 0 decNum = abs(Decimal(str(target)).as_tuple().exponent) objTemp = copy.deepcopy(obj) objTemp = buildfun(objTemp, para) out = round(calfun(objTemp), decNum) sign = target - out increment = target - out flag = False while out != target and count < 100: para += increment if para <= 0 and flag: return -1, log elif para <= 0 and not flag: para = 0 flag = True else: flag = False objTemp = copy.deepcopy(obj) objTemp = buildfun(objTemp, para) out = round(calfun(objTemp), decNum) if sign * (target - out) < 0: para -= increment increment = increment/2 else: increment = target - out count += 1 if out != target: log = 'Looping reaches a limit of 100 times. Stop.\n' else: log = 'Loop '+str(count+1)+' times to get the ideal value.\n' print(log) return para, '' def buildChannel(fdict, funDict): '''Create a channel basing on information given in fdict and funDict. fdict -- dictionary contains parameter information for a channel funDict -- dictionary contains callable user defined functions Return: c -- channel that been built log -- string log ''' log = '' c = Channel(fdict["Length"], fdict["Inner Channel Lateral Offset Minimum"],\ fdict["Valley Slope (Sv)"], fdict["X Resolution"], fdict["Datum"]) nPoints = fdict['Channel XS Points'] c.setXShapePoints(nPoints) valleyfun, info = buildFun("Valley Centerline Function", fdict, funDict, defaultFunction) reshape=True fun, info = buildFun("Meandering Centerline Function", fdict, funDict, defaultFunction) log += info if valleyfun == defaultFunction: reshape = False log += 'Reshape not needed for river centerline.\n' if fdict['River Slope'] is not None: if fdict['River Slope'] >= fdict['Valley Slope (Sv)']: c.setCenterline(fun) log += 'Error! River Slope can not be bigger than Valley Slope!\n' print('Error! River Slope can not be bigger than Valley Slope!') else: print('') print('Start looping to get target river slope...') para = 1 rslope = fdict['River Slope'] count = 0 decNum = abs(Decimal(str(rslope)).as_tuple().exponent) channelTemp = copy.deepcopy(c) def centerlinefun(x): x, y = fun(x) return x, para*y channelTemp.setCenterline(centerlinefun) if reshape: print('reshape: Yes') channelTemp.shapeCenterline(valleyfun) out = channelTemp.getPipeSlope() increment = rslope/out while out != rslope and count < 100: para /= increment channelTemp = copy.deepcopy(c) channelTemp.setCenterline(centerlinefun) if reshape: channelTemp.shapeCenterline(valleyfun) out = round(channelTemp.getPipeSlope(), decNum) increment = rslope/out count += 1 if out != rslope: print('Looping reaches a limit of 100 times. Stop.') else: print('Loop '+str(count+1)+' times to get the ideal value.') c.setCenterline(centerlinefun) else: c.setCenterline(fun) if reshape: c.shapeCenterline(valleyfun) c.smoothCenterline(fdict['Smooth']) log += "Creating Meandering Center line with Function:"+fdict.get("Meandering Centerline Function", "None")+'\n' if fdict["Inner Channel Depth Minimum"] != 0: c.setHbfManual(fdict["Inner Channel Depth Minimum"]) log += "Use user defined Inner Channel Depth Minimum.\n" fun, info = buildFun("Centerline Curvature Function", fdict, funDict, None) log += info if fun: c.setCurvature(fun) log += "Use user defined Centerline Curvature Function:"+fdict["Centerline Curvature Function"]+'\n' leftfun, info = buildFun("Left Inner Bank Function", fdict, funDict, None) log += info rightfun, info = buildFun("Right Inner Bank Function", fdict, funDict, None) log += info thalfun, info = buildFun("Thalweg Elevation Function", fdict, funDict, defaultFunction) log += info print('') if fdict['Inner Channel Average Bankfull Width'] is not None: print('Start looping to get target Inner Channel Average Bankfull Width...') def loopFun(channel, para): channel.wbf_min = para channel.createInnerChannel(leftfun, rightfun, thalfun) return channel def calFun(channel): return channel.getAveWbf() para = fdict["Inner Channel Lateral Offset Minimum"] para, info = loopParameter(para, fdict['Inner Channel Average Bankfull Width'], c, loopFun, calFun) if para == -1: log += 'Cannot reach target Inner Channel Average Bankfull Width with current function settings. Please modify the functions.' else: log += info c.wbf_min = para if fdict['Inner Channel Average Bankfull Depth'] is not None: print('Start looping to get target Inner Channel Average Bankfull Depth...') def loopFun(channel, para): channel.hbf = para channel.createInnerChannel(leftfun, rightfun, thalfun) return channel def calFun(channel): return channel.getAveHbf() para = fdict["Inner Channel Depth Minimum"] para, info = loopParameter(para, fdict['Inner Channel Average Bankfull Depth'], c, loopFun, calFun) if para == -1: log += 'Cannot reach target Inner Channel Average Bankfull Depth with current function settings. Please modify the functions.' else: log += info c.hbf = para c.createInnerChannel(leftfun, rightfun, thalfun) log += "Creating Inner Channel Banks with left bank function: "+fdict.get("Left Inner Bank Function", "None")+'\n' log += " with right bank function: "+fdict.get("Right Inner Bank Function", "None")+'\n' log += " with thalweg elevation function: "+fdict.get("Thalweg Elevation Function", "None")+'\n' pattern = re.compile('L[\d]+ Outer Bank Lateral Offset Minimum') c, info = addLevels(pattern, fdict, funDict, None, 'left', c) log += info pattern = re.compile('R[\d]+ Outer Bank Lateral Offset Minimum') c, info = addLevels(pattern, fdict, funDict, None, 'right', c) log += info #################### Cross-Sectional Shape Calculation ################################ ckey = 'Cross-Sectional Shape' if ckey not in fdict: log += 'Alert! Cross-Sectional Shape not specified! Use asymmetric shape as default.\n' fdict[ckey] = 'AU' if fdict[ckey] not in XSHAPES: log += 'Alert! Cross-Sectional Shape value not recognizable! User input: '+ str(fdict[ckey])+'\nUse asymmetric shape as default.\n' fdict[ckey] = 'AU' if fdict[ckey] == 'AU': c.setXShape() elif fdict[ckey] == 'SU': copyCurvature = copy.copy(c.getDynamicCurv()) c.dynamicCurv = c.dynamicCurv*0 c.setXShape() else: fdict, info = paraCheck(fdict, "TZ(n)", 1, "int", 1) log += info log += printPara("TZ(n)", fdict) if fdict['TZ(n)'] > nPoints: log += 'Alert! TZ(n) value is not valid, set to Channel XS Points.\n' fdict['TZ(n)'] = nPoints c.setXShape(fdict['TZ(n)']) c.setTZ(fdict['TZ(n)']) #################### Bed Roughness ################################ if 'PBR' in fdict: log += 'Adding perlin roughness to bed.\n' fdict, info = paraCheck(fdict, "PBR", 5, "float") c.perlinThalweg(fdict['PBR']) return c, log def addBedElement(c, paras): log = '' paras = paras[1:-1] paras = paras.split(',') paras = [i.strip() for i in paras] if len(paras) != 4: log += "Number of parameters given to BEG doesn't equal to 4.\n" log += 'Given parameters should be in form: (val1, val2, val3, val4)\n' return log [num, size_mean, size_std, height] = paras try: num = int(num) size_mean = int(size_mean) size_std = int(size_std) height = float(height) except ValueError: log += "Cannot parsed given parameters in BEG.\n" return log c.addBoulders(num, size_mean, size_std, height) return log def addCheckDam(c, paras): log = '' paras = paras[1:-1] paras = paras.split(',') paras = [i.strip() for i in paras] if len(paras) != 3: log += "Number of parameters given to CD doesn't equal to 3.\n" log += 'Given parameters should be in form: (val1, val2, val3)\n' return log [loc, height, thickness] = paras try: loc = int(loc) height = int(height) thickness = int(thickness) except ValueError: log += "Cannot parsed given parameters in BEG.\n" return log c.addCheckDam(loc, height, thickness) return log def addChannelElements(c, addon): ADDONMETHOD = {'BEG': addBedElement, 'CD': addCheckDam} log = '' for key, values in ADDON.items(): if values != []: for value in values: log += ADDONMETHOD[key](c, value) return c, log def buildValley(fdict, funDict, channel): '''Create a valley basing on information given in fdict and funDict. fdict -- dictionary contains parameter information for a valley funDict -- dictionary contains callable user defined functions channel -- channel that will be passed to valley Return: valley -- valley that been built log -- string log ''' log = '' valley = Valley(channel) fun, info = buildFun("Valley Centerline Function", fdict, funDict, defaultFunction) log += info valley.setCenterline(fun) pattern = re.compile('(R[\d]+ Valley Breakline Lateral Offset Minimum)') valley, info = addLevels(pattern, fdict, funDict, None, 'right', valley) log += info pattern = re.compile('(L[\d]+ Valley Breakline Lateral Offset Minimum)') valley, info = addLevels(pattern, fdict, funDict, None, 'left', valley) log += info lboffset = fdict['Left Valley Boundary Lateral Offset Minimum'] lbheight = fdict['Left Valley Boundary Height Offset'] valley.setValleyBoundary(lbheight, lboffset, 'left', None) rboffset = fdict['Right Valley Boundary Lateral Offset Minimum'] rbheight = fdict['Right Valley Boundary Height Offset'] valley.setValleyBoundary(rbheight, rboffset, 'right', None) return valley, log def plotLevels(ax, xdict, ydict, dx, labelend, col): '''Plot levels to a figure. ax - the ax to draw to xdict - dictionary of values of x values of levels ydict - dictionary of values of y values of levels labelend - label added to each level, a string col - col of dots ''' for i in range(len(xdict['left'])): x = xdict['left'][i]*dx y = ydict['left'][i]*dx if labelend == 'V': ax.scatter(x, y, c='C'+str(col+i), marker='.', label='L'+labelend+str(i+1)) else: ax.scatter(x, y, c='C'+str(col+i), marker='.', label='L'+labelend+str(i)) for i in range(len(xdict['right'])): x = xdict['right'][i]*dx y = ydict['right'][i]*dx if labelend == 'V': ax.scatter(x, y, c='C'+str(col+i), marker='_', label='R'+labelend+str(i+1)) else: ax.scatter(x, y, c='C'+str(col+i), marker='_', label='R'+labelend+str(i)) ########################################################### def buildRiver(fname, outfolder, log): ''' It parse parameters in inputfile, then output to outputfolder. fname - inputfile name, end with '.txt'. outfolder - output folder name. log - additional information want to added to log file. ''' try: print("Start Parsing Inputs...") log += '\n' paraDict = fileParser(fname) paraDict, funDict, info = inputCheck(paraDict) log += info log += '\n' print("Start Creating River Channel...") t1 = datetime.now() channel, info = buildChannel(paraDict, funDict) log += info log += '\n' print("Start adding add-ons to Channel...") channel, info = addChannelElements(channel, ADDON) log += info log += '\n' t2 = datetime.now() print('It takes',round((t2-t1).total_seconds()),'seconds to build the channel.') print("Start Creating Valley...") t1 = datetime.now() valley, info = buildValley(paraDict, funDict, channel) log += info t2 = datetime.now() print('It takes',round((t2-t1).total_seconds()),'seconds to build the valley.') print('') #### Ploting #### if not os.path.exists(outfolder): os.mkdir(outfolder) valleyCol = max(len(channel.levels_x['left']), len(channel.levels_x['right'])) +1 fig, ax = plt.subplots(1, 1, figsize=[19.2, 14.4], dpi=400) ax.plot(channel.x_v*channel.dx, channel.y_center*channel.dx, 'k-', label='CL') plotLevels(ax, channel.levels_x, channel.levels_y, channel.dx, 'B', 1) plotLevels(ax, valley.levels_x, valley.levels_y, channel.dx, 'V', valleyCol) plt.title('SRV Planform') plt.xlabel('X (Distance Downstream)') plt.ylabel('Y') plt.legend() plt.savefig(outfolder+'/SRVlevels_xy') fig, ax = plt.subplots(1, 1, figsize=[19.2, 14.4], dpi=400) ax.plot(channel.x_v*channel.dx, channel.thalweg*channel.dx, 'k-', label='Thalweg') plotLevels(ax, channel.levels_x, channel.levels_z, channel.dx, 'B', 1) plotLevels(ax, valley.levels_x, valley.levels_z, channel.dx, 'V', valleyCol) plt.title('SRV Longitudianl Profile') plt.xlabel('X (Distance Downstream)') plt.ylabel('Z') plt.legend() plt.savefig(outfolder+'/SRVlevels_xz') fig, ax = plt.subplots(2, 1, sharex=True) fig.suptitle('River Centerline Slope & Curvature') fig.subplots_adjust(hspace=0) plt.subplot(211) plt.plot(channel.x_v*channel.dx, channel.getSlope(), 'tab:blue', label='slope') plt.xlabel('X') plt.ylabel('Y') plt.legend() plt.subplot(212) plt.scatter(channel.x_v*channel.dx, channel.getDynamicCurv(), c='tab:blue', s=1, label='dynamic curvature') plt.ylabel('Y') plt.legend() plt.savefig(outfolder+'/SRVcurvature') fig = channel.getXShapePlot() plt.savefig(outfolder+'/SRVinnerChannelXShape') fig = valley.getXShapePlot() plt.savefig(outfolder+'/SRVvalleyXShape') #### Output files #### valley.tocsv(outfolder+"/SRVtopo") print("Output files are saved to", os.getcwd()+'/'+outfolder) print(log) with open(os.getcwd()+'/'+outfolder+'/log.txt', 'w') as f: f.write(log) print(channel) with open(os.getcwd()+'/'+outfolder+'/SRVmetrics.txt', 'w') as f: f.write('River Channel Data:\n') f.write(channel.__str__()) f.write('\nValley Data:\n') f.write(valley.__str__()) out = [['X', 'S', 'C']] riverSlope = channel.getSlope() riverCurvature = channel.getDynamicCurv() riverx = channel.x_v*channel.dx out += [[riverx[i], riverSlope[i], riverCurvature[i]] for i in range(len(riverx))] with open(os.getcwd()+'/'+outfolder+'/SRVcenterline.csv', 'w') as cf: wt = csv.writer(cf, lineterminator='\n') wt.writerows(out) out = [['X', 'Z']] xz = valley.tolist_levelxz() out += [[xz[0][i]*valley.dx, xz[1][i]*valley.dx] for i in range(len(xz[0]))] with open(os.getcwd()+'/'+outfolder+'/SRVlevels_xz.csv', 'w') as cf: wt = csv.writer(cf, lineterminator='\n') wt.writerows(out) out = [['X', 'Y']] xz = valley.tolist_levelxy() out += [[xz[0][i]*valley.dx, xz[1][i]*valley.dx] for i in range(len(xz[0]))] with open(os.getcwd()+'/'+outfolder+'/SRVlevels_xy.csv', 'w') as cf: wt = csv.writer(cf, lineterminator='\n') wt.writerows(out) except Exception as err: print(log) traceback.print_exception(*sys.exc_info()) print(err)
Shell
UTF-8
1,519
3.1875
3
[]
no_license
#!/bin/bash set -e cd "${BUILD_PATH}" echo '-- Building espeak from source...' mkdir -p espeak pushd espeak cat <<eof > PKGBUILD # Maintainer: pkgname=espeak pkgver=1.48.04 pkgrel=1 pkgdesc="Text to Speech engine for good quality English, with support for other languages" arch=('armv6h') url="http://espeak.sourceforge.net/" license=('GPL') depends=('gcc-libs' 'portaudio') conflicts=("${pkgname}") provides=("${pkgname}") source=(http://downloads.sourceforge.net/sourceforge/\${pkgname}/\${pkgname}-\${pkgver}-source.zip) #md5sums=('281f96c90d1c973134ca1807373d9e67') md5sums=('cadd7482eaafe9239546bdc09fa244c3') build() { cd \${startdir}/src/\${pkgname}-\${pkgver}-source/src cp portaudio19.h portaudio.h # sed -i -e 's:#define FRAMES_PER_BUFFER 512:#define FRAMES_PER_BUFFER 2048:' \ # -e 's:paFramesPerBufferUnspecified:FRAMES_PER_BUFFER:' \ # -e 's:(double)0.1:(double)0.4:' \ # -e 's:double aLatency = deviceInfo->defaultLowOutputLatency:double aLatency = deviceInfo->defaultHighOutputLatency:' wave.cpp make all CXXFLAGS="$CXXFLAGS" } package() { cd \${startdir}/src/\${pkgname}-\${pkgver}-source/src make DESTDIR=\${pkgdir} install chmod 644 \${pkgdir}/usr/lib/libespeak.a install -m 755 speak /usr/bin cd \${startdir}/src/\${pkgname}-\${pkgver}-source install -Dm644 License.txt "\${pkgdir}/usr/share/licenses/\${pkgname}/LICENSE" } eof makepkg --asroot -i --noprogressbar --noconfirm popd echo '-- Finished building and installing espeak, tidying up...' set +e rm -rf espeak/ exit 0
Python
UTF-8
5,158
2.6875
3
[ "Apache-2.0", "BSD-3-Clause", "GPL-3.0-only" ]
permissive
# -*- coding: utf-8 -*- # Copyright 2019 United Kingdom Research and Innovation # Copyright 2019 The University of Manchester # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Authors: # CIL Developers, listed at: https://github.com/TomographicImaging/CIL/blob/master/NOTICE.txt from cil.optimisation.operators import LinearOperator from cil.framework import BlockGeometry, BlockDataContainer from cil.optimisation.operators import FiniteDifferenceOperator class SymmetrisedGradientOperator(LinearOperator): r'''Symmetrized Gradient Operator: E: V -> W V : range of the Gradient Operator W : range of the Symmetrized Gradient Example (2D): .. math:: v = (v1, v2) \\ Ev = 0.5 * ( \nabla\cdot v + (\nabla\cdot c)^{T} ) \\ \begin{matrix} \partial_{y} v1 & 0.5 * (\partial_{x} v1 + \partial_{y} v2) \\ 0.5 * (\partial_{x} v1 + \partial_{y} v2) & \partial_{x} v2 \end{matrix} ''' CORRELATION_SPACE = "Space" CORRELATION_SPACECHANNEL = "SpaceChannels" def __init__(self, domain_geometry, bnd_cond = 'Neumann', **kwargs): '''creator :param domain_geometry: domain of the operator :param bnd_cond: boundary condition, either :code:`Neumann` or :code:`Periodic`. :type bnd_cond: str, optional, default :code:`Neumann` :param correlation: :code:`SpaceChannel` or :code:`Channel` :type correlation: str, optional, default :code:`Channel` ''' self.bnd_cond = bnd_cond self.correlation = kwargs.get('correlation',SymmetrisedGradientOperator.CORRELATION_SPACE) tmp_gm = len(domain_geometry.geometries)*domain_geometry.geometries # Define FD operator. We need one geometry from the BlockGeometry of the domain self.FD = FiniteDifferenceOperator(domain_geometry.get_item(0), direction = 0, bnd_cond = self.bnd_cond) if domain_geometry.shape[0]==2: self.order_ind = [0,2,1,3] else: self.order_ind = [0,3,6,1,4,7,2,5,8] super(SymmetrisedGradientOperator, self).__init__( domain_geometry=domain_geometry, range_geometry=BlockGeometry(*tmp_gm)) def direct(self, x, out=None): '''Returns E(v)''' if out is None: tmp = [] for i in range(self.domain_geometry().shape[0]): for j in range(x.shape[0]): self.FD.direction = i tmp.append(self.FD.adjoint(x.get_item(j))) tmp1 = [tmp[i] for i in self.order_ind] res = [0.5 * sum(x) for x in zip(tmp, tmp1)] return BlockDataContainer(*res) else: ind = 0 for i in range(self.domain_geometry().shape[0]): for j in range(x.shape[0]): self.FD.direction = i self.FD.adjoint(x.get_item(j), out=out[ind]) ind+=1 out1 = BlockDataContainer(*[out[i] for i in self.order_ind]) out.fill( 0.5 * (out + out1) ) def adjoint(self, x, out=None): if out is None: tmp = [None]*self.domain_geometry().shape[0] i = 0 for k in range(self.domain_geometry().shape[0]): tmp1 = 0 for j in range(self.domain_geometry().shape[0]): self.FD.direction = j tmp1 += self.FD.direct(x[i]) i+=1 tmp[k] = tmp1 return BlockDataContainer(*tmp) else: tmp = self.domain_geometry().allocate() i = 0 for k in range(self.domain_geometry().shape[0]): tmp1 = 0 for j in range(self.domain_geometry().shape[0]): self.FD.direction = j self.FD.direct(x[i], out=tmp[j]) i+=1 tmp1+=tmp[j] out[k].fill(tmp1)
Python
UTF-8
1,657
2.859375
3
[]
no_license
import os import time import busio import digitalio import board import adafruit_mcp3xxx.mcp3008 as MCP from adafruit_mcp3xxx.analog_in import AnalogIn import RPi.GPIO as GPIO from bluedot import BlueDot from signal import pause spi = busio.SPI(clock=board.SCK, MISO=board.MISO, MOSI=board.MOSI) cs = digitalio.DigitalInOut(board.D22) mcp = MCP.MCP3008(spi,cs) bd = BlueDot() a = 1 def remapRange(value, leftMin, leftMax, rightMin, rightMax): leftSpan = leftMax - leftMin rightSpan = rightMax - rightMin valueScaled = int(value - leftMin)/ int(leftSpan) return int(rightMin + (valueScaled * rightSpan)) def dpad(pos): global a a = 0 def stop(): global a a = 1 def actuallyTurnOff(): print('stop') def run(): lastX = 0 lastY = 0 tolerance = 250 finalXPos = 0 finalYPos = 0 xChanged = False yChanged = False x = AnalogIn(mcp, MCP.P0) y = AnalogIn(mcp, MCP.P1) xValue = x.value yValue = y.value xAdjust = abs(xValue - lastX) yAdjust = abs(yValue - lastY) if xAdjust > tolerance: xChanged = True if yAdjust > tolerance: yChanged = True if xChanged: finalXPos = remapRange(xValue, 0, 65535, 0, 100) lastX = xValue if yChanged: finalYPos = remapRange(yValue, 0, 65535, 0, 100) lastY = yValue print('X: ', finalXPos) print('Y: ', finalYPos) time.sleep(.1) while True: bd.when_pressed = dpad bd.when_released = stop print('a: ', a) if a == 0: actuallyTurnOff() if a == 1: run()
Markdown
UTF-8
398
2.796875
3
[]
no_license
--- title: Quantity queries. date: 2015-06-03 21:35 UTC tags: - css - media queries --- I enjoyed [Heydon Pickering]'s well-written explanation of a clever technique for media-query-like "breakpoints" for, say, "[more than six paragraphs][article]," or "fewer than three elements." [article]: http://alistapart.com/article/quantity-queries-for-css [Heydon Pickering]: http://www.heydonworks.com/
Python
UTF-8
3,661
2.859375
3
[]
no_license
from PIL import Image from PIL import ImageOps from numpy import pi, mgrid, exp, square, zeros, ravel, dot, uint8 from itertools import product import math import numpy as np import random from scipy.ndimage import gaussian_filter import cv2 import matplotlib.pyplot as plt import matplotlib.image as mpimg from skimage import io, color #creating a gaussian random noise def add_noise(img): noise = np.zeros(img.shape, dtype=np.uint8) noise= np.random.normal(mean,std,Q42image.shape) new_img = img + noise return new_img #Gaussian Blur implementation def my_Gauss_filter(k_size,sigma): gaussian_filter = np.zeros((k_size, k_size), np.float32) m = k_size//2 n = k_size//2 sum=0.0 for x in range(-m, m+1): for y in range(-n, n+1): #applying the formula for 2-D Gaussian x1 = 2*np.pi*(sigma**2) x2 = np.exp(-(x**2 + y**2)/(2* sigma**2)) gaussian_filter[x+m, y+n] = (1/x1)*x2 sum+=gaussian_filter[x+m,y+n] gaussian_filter/=sum return gaussian_filter def apply_gaussian(): img = np.array(Image.open('gblur.jpg')) img_out = img.copy() gaussian_filter=my_Gauss_filter(5,5) gaussian_filter =np.flip(np.flip(gaussian_filter, 1), 0) # rotating the filter 180 degress for convolution height = img.shape[0] width = img.shape[1] for i in range(height-4): # avoiding corners for j in range(width-4): img_out[i][j]=np.sum(img[i:i+5,j:j+5]*gaussian_filter) return img_out if __name__=='__main__': #cropping the facial part of the picture Q4image=Image.open('pic2.jpg') Q4image_arr=np.array(Q4image) crop=Q4image_arr[0:2000,1200:3200,:] Q4_crop=Image.fromarray(crop) Q4_crop=Q4_crop.resize((256,256),Image.ANTIALIAS) Q4_crop.save('Q4_crop.jpg') image=Image.open('Q4_crop.jpg') image_gray = image.convert('L') image_gray.save('gray_image.jpg') image_gray=np.array(image_gray) #Plotting fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(20, 5)) axes[0].imshow(Q4_crop) axes[0].set_title(" Cropped Image ",fontsize=16) axes[1].imshow(image_gray) axes[1].set_title(" Croppped Image Greyscale ",fontsize=16) #using python's normal method to create a random gaussain with a spec mean and covariance mean=0 std=15 Q42image=np.array(image_gray) u=add_noise(image_gray) fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(20, 5)) axes[0].imshow(Q42image) axes[0].set_title(" Before Noise",fontsize=16) axes[1].imshow(u) axes[1].set_title(" After Noise",fontsize=16) u = u.astype(np.uint8) gblur=Image.fromarray(u) gblur.save('gblur.jpg') # plotting histogram for before and after adding fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(20, 5)) axes[0].hist(Q42image.flatten(),bins=256) axes[0].set_title("Histrogram Before Noise",fontsize=16) axes[1].hist(u.flatten(),bins=256) axes[1].set_title(" Histogram After Noise",fontsize=16) fig.savefig('Hist Noise.png') print("Histograms") smoothed_image = apply_gaussian() sm=Image.fromarray(smoothed_image) sm.save('gaussian output_3.jpg') fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(20, 5)) axes[0].imshow(gblur) axes[0].set_title(" After Noise",fontsize=16) axes[1].imshow(smoothed_image) axes[1].set_title(" Applying Gaussian Blur ",fontsize=16) #Checking with inbuilt Gaussian Blur blur = cv2.GaussianBlur(np.array(gblur),(5,5),1) Cimage= Image.fromarray(blur) fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(20, 5)) axes[0].imshow(gblur) axes[0].set_title(" Noise Image",fontsize=16) axes[1].imshow(blur) axes[1].set_title(" Inbuilt Gaussain",fontsize=16) plt.show()
Python
UTF-8
243
3.328125
3
[]
no_license
import turtle as t def koch(t, order, size): if order == 0: t.forward(size) else: for angle in [60, -120, 60, 0]: koch(t, order-1, size/3) t.left(angle) ordr = 1 siz = 100 kch = koch(t,ordr,siz)
C#
UTF-8
644
2.59375
3
[ "MIT" ]
permissive
using System.Collections; using System.Collections.Generic; using UnityEngine; class ChangePausedStateOnEvent : ActivateOnEvent { enum PauseType : byte { Pause, Unpause, TogglePause } [Header("Event Specifics")] [SerializeField] private PauseType m_pauseType; protected override void OnActivate() { switch (m_pauseType) { case PauseType.Pause: GameManager.IsPaused = true; break; case PauseType.Unpause: GameManager.IsPaused = false; break; case PauseType.TogglePause: GameManager.IsPaused = !GameManager.IsPaused; break; default: Debug.LogError("Unsupported pausetype"); break; } } }
C++
UTF-8
558
2.640625
3
[]
no_license
// Program to find nth Fibbonaci No // Link : https://practice.geeksforgeeks.org/problems/nth-fibonacci-number/0 #include<bits/stdc++.h> #define LL long long #define FOR(i,a,b) for(int i=(a);i<=(b);i++) #define elif else if #define FORA(x,arr) for(auto &x:arr) #define fastio ios_base::sync_with_stdio(false);cin.tie(NULL); #define pb push_back using namespace std; int main(){ int t; cin>>t; int n; LL arr[1000]; arr[0]=1; arr[1]=1; for(int i=2;i<1000;i++) arr[i]=(arr[i-1]+arr[i-2])%1000000007; while(t--){ cin>>n; cout<<arr[n-1]<<endl; } }
Markdown
UTF-8
2,464
3.953125
4
[ "MIT" ]
permissive
# Black Jack written in Python This is a simulation of a game of blackjack. It involves features such as choosing to pick up another card, deciding not to pick up a card and end your turn, (both using input). A winner is recognised and an ace being either a 1 or an 11 is there but doesn't work very well. I am hoping to simplify the code using functions and alter it so that the ace feature works properly. Here is an example of the code: ```bash python TheBlackjack.py Your first card is 8 of Spades Your second card is 4 of Clubs The total of the two is 12 stick (s) or twist (t)?t 10 of Spades Unlucky, you bust with 22 ------------------------------------------------------------------------------------------------- Player 2, now its your go! 5... 4... 3... 2... 1... Your first card is 2 of Spades Your second card is 11 of Diamonds The total of the two is 13 stick (s) or twist (t)?t 5 of Clubs 18 Would you like to stick (s) or twist (t)?s 18 Player 1 scored 22 but was bust. Player 2 scored 18 ``` When run, the code should randomise and print two random numbers and two random card suits. Next it should add up the two and print the current score. If you got an 11 and a 10 it will print ```"Wow, first time!"``` Then it will ask you whether you would like to stick or twist using: ``` stickortwist = raw_input("stick (s) or twist (t)?") ``` You should then type either "s" (meaning to stick and end your turn) or "t" (to twist and pick up another card) "s" will result in the end of your turn: ```print ("your final score is", finalscore)``` finalscore being your total score. If you input "t", it should randomise another card and output it. This should be added to the score and if it is over 21 it will be the end of the turn. This process is repeated until you pick to stick or the total is over 21. Then the code calculates who wins and prints it: ``` if player1score > 21: print "Player 1 scored",player1score, "but was bust." else: print "Player 1 scored",player1score if finalscore > 21: print "Player 2 scored",finalscore, "but was bust." else: print "Player 2 scored",finalscore if player1score < 21: if player1score > finalscore: print "Player 1 wins!" if finalscore < 21: if finalscore > player1score: print "Player 2 wins!" if finalscore > 21: if player1score > 21: print "You both lose!" elif player1score > 21: if finalscore > 21: print "You both lose!" ```
Python
UTF-8
159
3.40625
3
[]
no_license
theAnswer = 42 fortyTwo = ['life,', 'the universe,', 'and everything!'] if theAnswer == 42: print('The meaning of') for x in fortyTwo: print x
Java
UTF-8
3,445
2.453125
2
[]
no_license
package com.neusoft.abclife.productfactory.test; import java.io.IOException; import java.net.URI; import java.util.HashMap; import java.util.Map; import org.apache.http.HttpEntity; import org.apache.http.client.methods.CloseableHttpResponse; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.utils.URIBuilder; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import com.alibaba.fastjson.JSON; public class Client { // SOAP // public static void main(String[] args) { // CXFWebServiceControlerService controlerService = new // CXFWebServiceControlerService(); // CXFWebServiceControler cxfWebServiceControler = // controlerService.getCXFWebServiceControlerPort(); // String result = cxfWebServiceControler.run("calt.getInsurCode", // "{\"code\": \"2041\"}"); // System.out.println(result); // } // RESTful public static void main(String[] args) { String businessId = "calTest.getInsurCode"; Map<String, Object> params = new HashMap<String, Object>(); params.put("code", "2041"); getResult(businessId, params); } /* * */ static final String URL = "http://localhost:8080/framework/ws/common/service/"; public static String getResult(String businessId, Map<String, Object> params) { String url = ""; String result = ""; URI uri = null; // businessId 不为空 if (!businessId.isEmpty()) { url = URL + businessId; } else { try { throw new Exception("businessId 不能为空"); } catch (Exception e) { e.printStackTrace(); } } // params不为空 try { if (!params.isEmpty()) { String params2str = JSON.toJSONString(params); uri = new URIBuilder(url).setParameter("param", params2str) .build(); } else { String params2str = JSON .toJSONString(new HashMap<String, Object>()); uri = new URIBuilder(url).setParameter("param", params2str) .build(); } } catch (Exception e) { e.printStackTrace(); } // ==================== // 创建默认的httpClient实例 CloseableHttpClient httpClient = getHttpClient(); try { // 用get方法发送http请求 HttpGet get = new HttpGet(uri); // System.out.println("执行get请求:...."+get.getURI()); CloseableHttpResponse httpResponse = null; // 发送get请求 httpResponse = httpClient.execute(get); try { // response实体 HttpEntity entity = httpResponse.getEntity(); if (null != entity) { System.out.println("响应状态码:" + httpResponse.getStatusLine()); System.out .println("-------------------------------------------------"); System.out.println("响应内容:" + EntityUtils.toString(entity)); System.out .println("-------------------------------------------------"); } } finally { httpResponse.close(); } } catch (Exception e) { e.printStackTrace(); } finally { try { closeHttpClient(httpClient); } catch (IOException e) { e.printStackTrace(); } } return result; } /* * */ private static CloseableHttpClient getHttpClient() { return HttpClients.createDefault(); } private static void closeHttpClient(CloseableHttpClient client) throws IOException { if (client != null) { client.close(); } } }
C#
UTF-8
3,264
3.515625
4
[ "MIT" ]
permissive
using System; namespace ConsoleApp { class Program { static void Main(string[] args) { //setup vars string appName = "Number Guesser"; string appVersion = "1.0.0"; string appAuthor = "Shuonan"; //change text color Console.ForegroundColor = ConsoleColor.Cyan; //print info Console.WriteLine("{0}: Version{1} by {2}", appName, appVersion, appAuthor); //reset color Console.ResetColor(); //ask user name Console.WriteLine("What's your name?"); //get user name string userName = Console.ReadLine(); Console.WriteLine("Hello {0}, let's play a game.", userName); while (true) { //set answer //int answer = 6; //set a random answer Random random = new Random(); int answer = random.Next(1, 10); //init guess var int guess = 0; Console.WriteLine("Guess a number between 1 and 10."); // while the guess is not correct while (guess != answer) { //get user inout string userInput = Console.ReadLine(); //make sure user input a int if (!int.TryParse(userInput, out guess)) { //print error message PrintColorMessage(ConsoleColor.Red, "Please enter a number between 1 and 10!"); //keep going continue; } //convert str to int guess = Int32.Parse(userInput); //match guess to answer if (guess != answer) { //print error message PrintColorMessage(ConsoleColor.Red, "Wrong number, please try again!"); } } // print success message PrintColorMessage(ConsoleColor.Green, "You are CORRECT!!!"); //change text color //Console.ForegroundColor = ConsoleColor.Green; //print info //Console.WriteLine("You are CORRECT!!!"); //reset color //Console.ResetColor(); //ask to play again Console.WriteLine("Play again? [Y/N]"); //get user input string playAgain = Console.ReadLine().ToUpper(); if(playAgain == "Y") { continue; } else { return; } } } static void PrintColorMessage(ConsoleColor color, string message) { //change text color Console.ForegroundColor = color; //print info Console.WriteLine(message); //reset color Console.ResetColor(); } } }
C#
UTF-8
3,217
3.125
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.Windows.Forms; namespace Projekt { public partial class Form1 : Form { public Form1() { InitializeComponent(); listBox1.SelectedIndex = 0; listBox2.SelectedIndex = 0; textBox1.Text = Convert.ToString(hScrollBar1.Value); textBox2.Text = Convert.ToString(hScrollBar2.Value); } private void button1_Click(object sender, EventArgs e) { label2.Text = Convert.ToString(listBox1.SelectedIndex); } private void hScrollBar1_Scroll(object sender, ScrollEventArgs e) { textBox1.Text = Convert.ToString(hScrollBar1.Value); } private void hScrollBar2_Scroll(object sender, ScrollEventArgs e) { textBox2.Text = Convert.ToString(hScrollBar2.Value); } private void genetic() { textBox3.Text = ""; int selectedFunction = listBox1.SelectedIndex; int populationSize = hScrollBar2.Value; int iterationsNumber = hScrollBar1.Value; int selectedMethod = listBox2.SelectedIndex; double[,] result; GeneticAlgorithm geneticAlgorithm = new GeneticAlgorithm(selectedFunction, populationSize, iterationsNumber, selectedMethod); result = geneticAlgorithm.returnResult(); int l = result.GetLength(0); for (int i = 0; i < l; i++) { double x = result[i, 0]; double y = result[i, 1]; String text = ""; text += "Iteracja " + (i + 1) + ": "; text += "x = " + x + " "; text += "y = " + y + " "; string[] f = new string[4]; f[0] = "x^2y + 8x - xy^2 + 5y"; f[1] = "x^2y+xy^2-2x"; f[2] = "4x+2y^2+xy"; f[3] = "y^2+2xy^2+3x"; double functionResult; switch (listBox1.SelectedIndex) { case 0: functionResult = Math.Pow(x, 2) * y + 8 * x - x * Math.Pow(y, 2) + 5 * y; break; case 1: functionResult = Math.Pow(x, 2) * y + x * Math.Pow(y, 2) - 2 * x; break; case 2: functionResult = 4 * x + 2 * Math.Pow(y, 2) + x * y; break; case 3: functionResult = Math.Pow(y, 2) + 2 * x * Math.Pow(y, 2) + 3 * x; break; default: functionResult = 0; break; } text += f[listBox1.SelectedIndex] + " = " + functionResult + "\r\n"; textBox3.Text += text; } } private void button1_Click_1(object sender, EventArgs e) { genetic(); } } }
Java
UTF-8
423
1.914063
2
[]
no_license
package com.forumdev.demo.Service.ServiceInterface; import com.forumdev.demo.Model.Comment; import com.forumdev.demo.Model.Post; import java.util.List; public interface CommentServiceInterface { Comment save(Comment s); Comment editComment(Comment comment); void deleteComment(Comment comment); Integer nbComment(Post post); List<Comment> getComments(Post post); List<Comment> getAllComment(); }
Markdown
UTF-8
19,088
3.015625
3
[]
no_license
# 应用编程接口 ## API蓝本结构 |-practice_flask_blog |-app/ |- api |- __init__.py |- users.py |- posts.py |- comments.py |- authentication.py |- errors.py |- decorators.py 1. app/api/\_\_init__.py, 中创建蓝本 from flask import Blueprint api = Blueprint("api", \_\_name__) from . import authentication, posts, users, comments, errors 2. app/\_\_init__.py, 中注册api蓝本 def create_app(): &nbsp;&nbsp;&nbsp;&nbsp;... &nbsp;&nbsp;&nbsp;&nbsp;form .api import api as api_blueprint &nbsp;&nbsp;&nbsp;&nbsp;app.register_blueprint(api_blueprint, url_prefix="/api/v1") &nbsp;&nbsp;&nbsp;&nbsp;... 这里使用了版本控制, 就是api前缀后面的v1, 因为api与客户端是分开单独存在的, 互相不影响, 当一个改变后, 另一个更本不知道 每次同步API和客户端功能的时候, 可能会有同名端口的冲突, 这样, 使用不同时间段不同版本的api就可以解决向后兼容的问题. 3. 在所有的使用api蓝本的模块中引入 from . import api *注意* Flask会特殊对待末端带有斜线的路由. 如果客户端请求的URL的末端没有斜线, 而唯一匹配的路由有斜线, Flask会自动响应一个重定向, 转向末端带有斜线的URL. 反之则不会重定向. ## 区分普通页面与通过API请求所返回错误信息 app/main/errors.py @main.app_errorhandler(403) def forbidden(e): # 当接收到的MIME类型是json格式 并且 不包含html时 if request.accept_mimetypes.accept_json and not request.accept_mimetypes.accept_html: response = jsonify({"error": "forbidden"}) response.status_code = 403 return response return render_template("403.html"), 403 @main.app_errorhandler(404) def page_not_found(e): # 当接收到的MIME类型是json格式 并且 不包含html时 if request.accept_mimetypes.accept_json and not request.accept_mimetypes.accept_html: response = jsonify({"error": "not found"}) response.status_code = 404 return response return render_template('404.html'), 404 @main.app_errorhandler(500) def internal_server_error(e): # 当接收到的MIME类型是json格式 并且 不包含html时 if request.accept_mimetypes.accept_json and not request.accept_mimetypes.accept_html: response = jsonify({"error": "server error"}) response.status_code = 500 return response return render_template('500.html'), 500 新版错误处理程序检查Accept请求首部(解码为request.accept_mimetypes), 根据首部的值决定客户端期望接收的响应格式. 浏览器一般不限制响应格式, 但是API客户端通常会指定. 仅当客户端接受的格式列表中包含JSON但不包含HTML时, 才生成JSON响应. 其他状态码都由Web服务生成. app/api/errors.py from flask import jsonify from . import api from app.exceptions import ValidationError def bad_reequest(message): response = jsonify({"error": "bad request", "message": message}) response.status_code = 400 return response def unauthorized(message): response = jsonify({"error": "unauthorized", "message": message}) response.status_code = 401 return response def forbidden(message): response = jsonify({"error": "forbidden", "message": message}) response.status_code = 403 return response @api.errorhandler(ValidationError) def validateion_error(e): return bad_reequest(e.argv[0]) 在app中新建exceptions.py, 用于自定义的错误. app/exceptions.py class ValidationError(ValueError): pass 这里ValidationError用于在反向序列化中检查是否值是正确的, 如果不正确, 将会抛出这个错误. 这个错误在蓝本api中是注册到了errorhandler中, 没错, errorhandler可以接收Exception类, 只要抛出了指定类的异常, 就会调用被装饰的函数. 因为是在蓝本中注册的, 所以只有处理蓝本中的路由抛出错误才会调用. ## 验证用户身份 与普通Web应用一样, Web服务也需要保护信息, 确保未经授权的用户无法访问. 为此RIA必须询问用户的登录凭据, 并将其传递给服务器验证. REST式Web服务的特征之一是无状态, 即服务器在两次请求之间不能"记住"客户端的任何信息. 客户端必须要在发出的请求中包含所有必要的信息. 当前应用的登录功能是由flask-login的帮助下实现的, 数据存储在用户的会话中. 默认情况下, Flask会将会话保存在客户端的cookie中, 因此服务器没有保存任何用户相关的信息, 都转交给客户端保存. 这种实现方式看起来遵守了REST架构的无状态要求, 但在REST式Web服务中使用cookie有点不现实, 因为Web浏览器之外的客户端很难提供对cookie的支持. 因为REST架构基于HTTP协议, 所以发送凭据的最佳方式是使用HTTP身份验证, 基本验证和摘要验证都可以. 在HTTP身份验证中, 用户凭据包含在每个请求的Authorization首部中. ### 使用flask-httpauth验证用户 app/api/authentication.py from flask import g, jsonify from flask_httpauth import HTTPBasicAuth from . import api from .errors import unauthorized, forbidden from ..models import User auth = HTTPBasicAuth() @auth.verify_password def verify_password(email_or_token, password): """可以依据邮件地址或是令牌来验证用户""" if email_or_token == '': return False if password == '': g.current_user = User.verify_auth_token(email_or_token) g.token_used = True return g.current_user is not None user = User.query.filter_by(email=email_or_token).first() if not user: return False g.current_user = user g.token_used = False return user.verify_password(password) @auth.error_handler def auth_error(): """重新自定义了401, 为了让其与其他的报错格式一样""" return unauthorized('Invalid credentials') # 在请求所有的API之前, 都需要进行验证 @api.before_request @auth.login_required def before_request(): # 用户已经注册, 但还没有完成确认的用户将会被拒 if not g.current_user.is_anonymous and not g.current_user.confirmed: return forbidden('Unconfirmed account') @api.route('/tokens/', methods=['POST']) def get_token(): """生成身份验证令牌""" if g.current_user.is_anonymous or g.token_used: return unauthorized('Invalid credentials') return jsonify({'token': g.current_user.generate_auth_token(expiration=3600), 'expiration': 3600}) 与flask-login一样, flask-httpauth不对验证用户凭据所需的步骤做任何假设, 所需的信息在回调函数中提供. 在这里是`HTTPBasicAuth.verify_password装饰器`. 直接在蓝本中初始化了flask-httpauth的HTTPBasicAuth, 因为这种身份验证只在API中使用. `verify_password(email_or_token, password)` 参数可以是电子邮件, 也可以是身份验证令牌. 如果参数为空, 就假定为匿名用户. 如果密码为空, 就假定参数是令牌, 按照令牌的方式验证. 如果两个参数都不是空, 就假定使用常规的邮件地址和密码验证. 为了让视图函数能区分令牌验证和邮箱地址密码验证两种方法, 还添加了`g.token_used`. 使用了令牌, 那么其为True. `get_token()` 为了确保这个路由使用电子邮件地址和密码验证身份, 而不使用之前获取的令牌, 这里检查了g.token_used的值, 拒绝使用令牌验证身份. 这样做是为了防止用户绕过令牌过期机制, 使用旧令牌请求新令牌. ### 基于令牌的身份验证 每次请求, 客户端都要发送身份验证凭据, 为了避免频繁的暴露敏感信息, 可以使用一种基于令牌的身份验证方式. 客户端先发送一个包含登录凭据的请求, 通过身份验证后, 得到一个访问令牌. 这个令牌可以代替登录凭据对请求进行身份验证. app/models.py ... from itsdangerous import TimedJSONWebSignatureSerializer as Serializer ... class User(db.Model, UserMixin): ... def generate_auth_token(self, expiration): """生成用于API的令牌, 使用用户的id""" s = Serializer(current_app.config["SECRET_KEY"], expires_in=expiration) return s.dumps({"user's id token": self.id}).decode("U8") @staticmethod def verify_auth_token(token): """用于API的令牌验证, 通过解码的id获取到用户对象""" s = Serializer(current_app.config["SECRET_KEY"]) try: data = s.loads(token) except: return None return User.query.get(data["user's id token"]) > 流程 用户请求登录(携带邮箱, 密码) --> 服务器返回(登录成功, 返回令牌) --> 用户在做请求(携带令牌方式) --> 服务器返回(调用HTTPBasicAuth.verify_password装饰器下的验证函数, 该函数返回对错, 对则返回被请求的信息, 错则返回错误信息) ## 资源和Json的序列转换 app/models.py ... class User(db.Model, UserMixin): ... def to_json(self): json_user = { "url": url_for("api.get_user", id=self.id), "username": self.username, "member_since": self.member_since, "last_seen": self.last_seen, "posts_url": url_for("api.get_user_posts", id=self.id), "followd_posts_url": url_for("api.get_user_followed_posts", id=self.id), "post_count": self.posts.count() } return json_us class Post(db.Model): ... def to_json(self): json_post = { "url": url_for("api.get_post", id=self.id), "body": self.body, "body_html": self.body_html, "timestamp": self.timestamp, "author_url": url_for("api.get_user", id=self.author_id), "comments_url": url_for("api.get_post_comments", id=self.id), "comment_count": self.comments.count() } return json_post @staticmethod def from_json(json_post): body = json_post.get("body") # 无body内容抛出自定义的一个错误, 这个错误在蓝本errorhandler中注册了, 会自动捕获 if body is None or body =="": raise ValidationError("post does not have a body") return Post(body=body) db.event.listen(Post.body, "set", Post.on_changed_body `to_json()`方法用于将资源转换为Json格式数据, 为序列化. `from_json()`方法用于将Json格式转换为原资源格式, 为反序列化. 因为Post的来自用户的更改主要是body, 而body又有body_html字段, 但是body字段是绑定了set事件的, 所以只需要改变body字段即可. ## 实现资源的各个端点 实现对Post中的数据进行 增, 改, 查 app/api/posts.py from flask import g, jsonify, request, url_for, current_app from . import api from .errors import forbidden from .decorators import permission_required from .. import db from ..models import Permission, Post @api.route("/posts/", methods=["GET"]) def get_posts(): # 使用GET获取所有的post page = request.args.get("page", 1, type=int) pagination = Post.query.paginate(page, per_page=current_app.config["FLASKY_POSTS_PER_PAGE"], error_out=False) posts = pagination.items prev_page = None if pagination.has_prev: prev_page = url_for("api.get_posts", page=page-1) next_page = None if pagination.has_next: next_page = url_for("api.get_posts", page=page+1) return jsonify({ "posts": [post.to_json() for post in posts], "prev_url": prev_page, "next_url": next_page, "count": pagination.total, }) @api.route("/posts/<int:id>", methods=["GET"]) def get_post(id): # 使用GET获取指定id的post post = Post.query.get_or_404(id) return jsonify({"posts": post.to_json()}) @api.route("/posts/", methods=["POST"]) @permission_required(Permission.WRITE) def new_post(): # 使用POST新建post post = Post.from_json(request.json) post.author = g.current_user db.session.add(post) ad.session.commit() return jsonify(post.to_json(), 201, {"Location": url_for("api.get_post", id=post.id)}) @api.route("/posts/<int:id>", methods=["PUT"]) @permission_required(Permission.WRITE) def edit_post(id): # 使用PUT更改post post = Post.query.get_or_404(id) # 用户是否是原作者, 用户是否是管理员. if g.current_user != post.author and not g.current_user.can(Permission.ADMIN): return forbidden("Insuficient permissions") post.body = request.json.get("body", post.body) # 让原post的body如果有新的提交变为新的, 否则还是原来的. db.session.add(post) db.session.commit() return jsonify(post.to_json()) ### 针对api中的权限验证 app/api/decorators.py from flask import g from .errors import forbidden from ..models import Permission import functools def permission_required(permission): def decorator(f): @functools.wraps(f) def decorated_function(*args, **kwargs): if not g.current_user.can(permission): return forbidden("Insufficient permissions") return f(*args, **kwargs) return decorated_function return decorator REST不同于基于会话的请求, 其是无状态的, 所以没法像原来一样, 使用flask_login中的current_user获取cookie中的用户, 这里使用在flask.g中的current_user变量来获取当前的用户. ## 完善所有接口 + GET /users/\<int:id> 返回一个用户 + GET /users/\<int:id>/posts 返回一个用户发布的所有博客文章 + GET /users/\<int:id>/timeline 返回一个用户所关注用户发布的所有文章 + GET /posts/ 返回所有博客文章 + POST /posts/ 创建一篇博客文章 + GET /posts/\<int:id> 返回一篇博客文章 + PUT /posts/\<int:id> 修改一篇博客文章 + GET /posts/\<int:id>/comments/ 返回一篇博客文章的评论 + POST /posts/\<int:id>/comments/ 在一篇博客文章中添加一条评论 + GET /comments/ 返回所有评论 + GET /comments/\<int:id> 返回一条评论 [接口的详细实现](./07.1应用编程接口_更多.md) ## 补充 ### 内容协商 #### 服务端驱动型内容协商机制 在服务端驱动型协商机制或者主动协商机制中,浏览器(或者其他任何类型的用户代理)会随同 URL 发送一系列的消息头。这些消息头描述了用户倾向的选择。服务器则以此为线索,通过内部算法来选择最佳方案提供给客户端。相关算法与具体的服务器相关,并没有在规范中进行规定。 HTTP/1.1 规范指定了一系列的标准消息头用于启动服务端驱动型内容协商 (Accept、Accept-Charset、 Accept-Encoding、Accept-Language)。 _Accept 首部_ Accept 首部列举了用户代理希望接收的媒体资源的 MIME 类型。 _Accept-CH 首部_ 该实验性首部 Accept-CH 列出了服务器可以用来选择合适响应的配置数据。 _Accept-Charset 首部_ Accept-Charset首部用于告知服务器该客户代理可以理解何种形式的字符编码。 _Accept-Encoding 首部_ Accept-Encoding 首部明确说明了(接收端)可以接受的内容编码形式(所支持的压缩算法)。 _Accept-Language 首部_ Accept-Language 首部用来提示用户期望获得的自然语言的优先顺序。 _User-Agent 首部_ User-Agent 首部可以用来识别发送请求的浏览器。该字符串中包含有用空格间隔的产品标记符及注释的清单。 _Vary 响应首部_ 与前面列举的 Accept-* 形式的由客户端发送的首部相反,Vary 首部是由服务器在响应中发送的。它标示了服务器在服务端驱动型内容协商阶段所使用的首部清单。这个首部是必要的,它可以用来通知缓存服务器决策的依据,这样它可以进行复现,使得缓存服务器在预防将错误内容提供给用户方面发挥作用。 #### 代理驱动型内容协商机制 服务端驱动型内容协商机制由于一些缺点而为人诟病——它在规模化方面存在问题。在协商机制中,每一个特性需要对应一个首部。如果想要使用屏幕大小、分辨率或者其他方面的特性,就需要创建一个新的首部。而且在每一次请求中都必须发送这些首部。在首部很少的时候,这并不是问题,但是随着数量的增多,消息体的体积会导致性能的下降。带有精确信息的首部发送的越多,信息熵就会越大,也就准许了更多 HTTP 指纹识别行为,以及与此相关的隐私问题的发生。 在这种协商机制中,当面临不明确的请求时,服务器会返回一个页面,其中包含了可供选择的资源的链接。资源呈现给用户,由用户做出选择。 #### 多用途互联网邮件扩展 MIME 多用途互联网邮件扩展(MIME,Multipurpose Internet Mail Extensions)是一个互联网标准,它扩展了电子邮件标准,使其能够支持: + 非ASCII字符文本; + 非文本格式附件(二进制、声音、图像等); + 由多部分(multiple parts)组成的消息体; + 包含非ASCII字符的头信息(Header information)。 MIME headers MIME是通过标准化电子邮件报文的头部的附加域(fields)而实现的;这些头部的附加域,描述新的报文类型的内容和组织形式。 MIME版本(MIME-Version),这个头部域在邮件消息的报文用一个版本号码来指明消息遵从的MIME规范的版本。目前版本是1.0。 MIME-Version: 1.0 内容类型(Content-Type),这个头部领域用于指定消息的类型。一般以下面的形式出现。 `Content-Type: [type]/[subtype]; parameter` 内容传输编码(Content-Transfer-Encoding),这个区域使指定ASCII以外的字符编码方式成为可能。形式如下: `Content-Transfer-Encoding: [mechanism]` 其中,mechanism的值可以指定为“7bit”,“8bit”,“binary”,“quoted-printable”,“base64”。
Python
UTF-8
2,103
3.671875
4
[]
no_license
#linear fitting.py #生成服从一维正态分布的随机数(离散值),使用最小二乘法进行曲线拟合,并梯度下降法求取极值。 #导入2d图形库 matplotlib 数学函数库numpy mah import numpy as np import matplotlib.pyplot as plt import math #生成20个待测试的服从标准正态分布随机数并且打印在图像上 X = np.arange(-5, 5, 0.1) Z = [1/math.sqrt(2*math.pi)*math.exp(-x**2/2) for x in X] Y = np.array([np.random.normal(z,0.9) for z in Z]) plt.plot(X,Y,'ro') plt.show() """ 1 f(x)= −−exp(−(x−μ)2/2σ2) √2πσ """ # 求解多项式的正则方程组 # 生成系数矩阵A def gen_coefficient_matrix(X, Y): N = len(X) m = 9 A = [] # 计算每一个方程的系数 for i in range(m): a = [] # 计算当前方程中的每一个系数 for j in range(m): a.append(sum(X ** (i+j))) A.append(a) return A # 计算方程组的右端向量b def gen_right_vector(X, Y): N = len(X) m = 9 b = [] for i in range(m): b.append(sum(X**i * Y)) return b A = gen_coefficient_matrix(X, Y) b = gen_right_vector(X, Y) a0, a1, a2 ,a3,a4,a5,a6,a7,a8= np.linalg.solve(A, b) # 生成拟合曲线的绘制点 _X = np.arange(-5, 5, 0.01) _Y = np.array([a0 + a1*x + a2*x**2 + a3*x**3 + a4*x**4 + a5*x**5 + a6*x**6+a7*x**7 +a8*x**8 for x in _X]) plt.plot( _X, _Y, 'b', linewidth=2) plt.show() ''' def dj(theta): return (a1+2*a2*theta+3*a3*theta**2+4*a4*theta**3+5*a5*theta**4+6*a6*theta**5)#这里返回theta对应的导数,而函数求导是手动进行的 def j(theta): return (a0 + a1*theta + a2*theta**2 + a3*theta**3 + a4*theta**4 + a5*theta**5 + a6*theta**6 ) eta=0.1#这个是学习率 theta=0.0#第一个点 episilon=1e-8 while True: gradient=dj(theta) last_theta=theta theta-=gradient*eta#对theta进行更新 if abs(j(theta)-j(last_theta)<episilon):#如果小于一个阈值,那么就退出 break print(theta) print(j(theta)) '''
SQL
UTF-8
86
2.59375
3
[]
no_license
SELECT DISTINCT ShipCity FROM Orders WHERE DATEDIFF(DAY, OrderDate , ShippedDate) > 10
SQL
UTF-8
2,901
3.90625
4
[ "MIT" ]
permissive
set serveroutput on declare v_stno BARORDER.studentno%type:='&Enter_Student_Number'; --STUDENT NUMBER v_rmno BARORDER.delivertoroom%type:=&Enter_Room_Number; --ROOM NUMBER v_itemname ORDERITEM.itemname%type:='&Enter_Item_Name'; --ITEM NAME v_quantity ORDERITEM.quantity%type:=&Enter_Item_Quantity; --ITEM QUANTITY v_total number(6,2); --USED FOR CALCULATING TOTAL OF ORDER --CURSOR TO DISPLAY ORDER CURSOR DETAILS IS SELECT ItemName, Quantity, ItemCost FROM BARORDER JOIN ORDERITEM USING (Studentno, Orderdate) JOIN MenuItem USING (ItemName) WHERE StudentNo LIKE v_stno AND OrderDate LIKE TO_DATE(TO_CHAR(SYSDATE),'YYYY-MM-DD'); CUR_DETAILS DETAILS%ROWTYPE; begin --CHECK STUDENT NUMBER ENTERED IF Check_Student(v_stno) THEN --CHECK ROOM NUMBER ENTERED IF Check_Room(v_rmno) THEN --CHECK MENU ITEM NAME ENTERED IF Check_Menu_Item(v_itemname) THEN --CHECK QUANTITY > 0 IF v_quantity > 0 THEN --CALL PROCEDURE TO ADD THE ITEM add_item(v_stno, v_rmno, v_itemname, v_quantity); --PRINT ORDER TOTAL TO SCREEN SELECT SUM(ITEMCOST*QUANTITY) into v_total FROM BARORDER JOIN ORDERITEM USING (studentno, orderdate) JOIN MENUITEM USING (ItemName) WHERE StudentNo LIKE v_stno AND OrderDate LIKE TO_DATE(TO_CHAR(SYSDATE),'YYYY-MM-DD'); --GET CURSOR DETAILS --OPEN CURSOR OPEN DETAILS; --DISPLAY ORDER HEADER dbms_output.put_line('Your Order:'); dbms_output.put_line('----------------------------------------------'); --START LOOP LOOP --TAKE DETAILS INTO INITIALISED CURSOR FETCH DETAILS INTO CUR_DETAILS; --BREAK FROM LOOP IF NO MORE DATA IS FOUND EXIT WHEN DETAILS%NOTFOUND; DBMS_OUTPUT.PUT_LINE( 'Item: '||CUR_DETAILS.ItemName||' , Quantity: '||CUR_DETAILS.Quantity||' , Cost: '||CUR_DETAILS.ItemCost*CUR_DETAILS.Quantity||''); END LOOP; --CLOSE CURSOR CLOSE DETAILS; --DISPLAY TOTAL dbms_output.put_line('----------------------------------------------'); dbms_output.put_line('Order total is: '||v_total||' euro.'); ELSE dbms_output.put_line('Please enter a quantity greater than 0'); END IF; ELSE dbms_output.put_line('Item does not exist'); END IF; ELSE dbms_output.put_line('Room does not exist'); END IF; ELSE dbms_output.put_line('Student does not exist'); END IF; exception when others then dbms_output.put_line('Error occurred '||SQLCODE||' meaning '||SQLERRM); end;
Java
UTF-8
455
2.046875
2
[ "MIT" ]
permissive
package com.packt.modern.api.aop; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * @author : github.com/sharmasourabh * @project : Chapter02 - Modern API Development with Spring and Spring Boot * @created : 10/20/2020, Tuesday **/ @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface TimeMonitor { }
Python
UTF-8
3,812
2.8125
3
[]
no_license
import socket import sys import time import urllib.parse as urlparse from http.server import BaseHTTPRequestHandler, HTTPServer HOST_NAME = 'localhost' PORT_NUMBER = 9000 def loadMap(): board = open(sys.argv[2],"r") spaces = board.read().split("\n") Matrix = [["_" for x in range(10)] for y in range(10)] for y in range(0,9): for x in range(0,9): if(list(spaces[x])[y] != "_"): Matrix[x][y] = list(spaces[x])[y] return Matrix def buildOpponent(): Matrix = [["_" for x in range(10)] for y in range(10)] return Matrix print("own board:") loadedMap = loadMap() print(loadedMap) print("opponent board:") opponentMap = buildOpponent() print(opponentMap) def checkHit(board, x, y): currentBoard = board returnedVal = [0] isHit = 0 if(currentBoard[x][y] != "_" and currentBoard[x][y] != "M"): isHit = 1 returnedVal = [isHit, currentBoard[x][y]] ship = checkSunk(board, currentBoard[x][y], x, y) if(ship != 1): print("Ship Sunk") returnedVal = [isHit, currentBoard[x][y], ship] elif(currentBoard[x][y] == "M"): returnedVal = [isHit, "M"] else: currentBoard[x][y] = "M" if(isHit == 1): print("Hit") else: opponentMap[x][y] = "M" print("Miss") loadedMap = currentBoard return returnedVal def checkSunk(board, typeShip, xCoord, yCoord): board[xCoord][yCoord] = "X" opponentMap[xCoord][yCoord] = "X" isFound = typeShip for x in range(0,9): for y in range(0,9): if(board[x][y] == typeShip): print("x: " + str(x) + " y: " + str(y)) print(board[x][y] + " EQUALS " + typeShip) isFound = 1 return isFound def checkOutBounds(x,y): if(x > 9 or x < 0 or y > 9 or y < 0): return 1 else: return 0 def checkMalformed(x,y): if(x is None or y is None): return 1 else: return 0 def reformatMap(inputMap): rtnStr = "" for x in range(0,9): rtnStr += (''.join(inputMap[x])) + "\n" return rtnStr class BattleShipServer(BaseHTTPRequestHandler): def do_GET(self): print(self.client_address) self.send_response(200); self.send_header("hit", "done") self.end_headers() newMap = "" if(self.path == "/own_board.html"): newMap = reformatMap(loadedMap) if(self.path == "/opponent_board.html"): newMap = reformatMap(opponentMap) self.wfile.write(bytes(newMap,"utf-8")) def do_POST(self): parsed = urlparse.urlparse(self.path) x = urlparse.parse_qs(parsed.query)['x'] y = urlparse.parse_qs(parsed.query)['y'] if(checkOutBounds(int(x[0]),int(y[0]))==1): self.send_response(404) self.end_headers() elif(checkMalformed(x,y)): self.send_response(400) self.end_headers() else: shot = checkHit(loadedMap, int(x[0]), int(y[0])) if(len(shot) > 1): if((shot[1] == "X" or shot[1] == "M") and len(shot) < 3): self.send_response(410) self.end_headers() else: self.send_response(200); self.send_header("hit",str(shot[0])) if(len(shot) > 2): self.send_header("sunk", shot[2]) self.end_headers() else: self.send_response(200); self.send_header("hit",str(shot[0])) self.end_headers() httpd = HTTPServer((HOST_NAME, PORT_NUMBER), BattleShipServer) try: httpd.serve_forever() except KeyboardInterrupt: pass httpd.server_close()
Python
UTF-8
309
3.4375
3
[ "MIT" ]
permissive
from random import * seed() x = [] for i in range(0, 10): x.append(randint(0, 100)) def inorder(x): i = 0 j = len(x) while i + 1 < j: if x[i] > x[i + 1]: return False i += 1 return True def bogo(x): while not inorder(x): shuffle(x) return x
C
UTF-8
434
2.859375
3
[]
no_license
/* item.h: header file for the Item CS411 Lab #:4 Name: Kevin Sahr Date: February 21, 2017 */ #ifndef ITEM_H #define ITEM_H #define MAX_ITEM_NAME_LEN 30 typedef struct { int id; char name[MAX_ITEM_NAME_LEN + 1]; float price; } Item; /*** Item function prototypes ***/ Item* createItem(int id, const char* name, float price); void printItem(Item* item); void destroyItem(Item** item); #endif /* ITEM_H */
JavaScript
UTF-8
8,766
2.734375
3
[ "MIT" ]
permissive
$(document).ready(function(){ // Reattach the reply form as last element of the article the user want's to answer // and update the form action URL so the answer is really associated with that message. // We also hide the answer link and focus the textarea for the message. Note that first // all answer links are shown again. This is to prevent other answer links from vanishing // when this form is moved to another article. $('ul.actions > li.new.message > a').show().click(function(){ var article = $(this).parents('article'); var newsgroup = window.location.pathname.split('/')[1]; var message_number = parseInt(article.attr('data-number'), 10); $('form.message').hide().detach().appendTo(article).show(). attr('action', '/' + newsgroup + '/' + message_number); $('article > ul.actions > li.new.message').show(); $(this).parents('li.new.message').hide(); $('textarea#message_body').focus(); return false; }); // The cancel button hides the form and shows the reply link again $('form.message button.cancel').click(function(){ $(this).parents('article').eq(0). find('> form.message').hide().end(). find('> ul.actions > li.new.message').show().end(); return false; }); // Validates the form and shows the proper error messages. If the form data is // invalid `false` is returned. $('form.message').bind('validate', function(){ var form = $(this); $('ul.error, ul.error > li').hide(); if ( $.trim(form.find('#message_body').val()) == "" ){ form.find('ul.error, ul.error > li#message_body_error').show(); var offset = form.find('ul.error').offset(); window.scrollTo(0, offset.top); return false; } return true; }); // Triggers the "validate" event to check if the form content is valid. If so the current post // text is converted to markdown (with a background request to the server) and show it in // the preview article. $('form.message button.preview').click(function(){ if ( ! $(this).parents('form').triggerHandler('validate') ) return false; $.post(window.location.pathname, {'preview_text': $('textarea').val()}, function(data){ var offset = $('article#post-preview'). find('> div').html(data).end(). show().offset(); window.scrollTo(0, offset.top); $('button.preview').removeClass('recommended'); $('button.create').addClass('recommended'); }); return false; }); // Triggers the "validate" event to check if the form content is valid. If it's not abort the form // submission. $('form.message').submit(function(){ if ( ! $(this).triggerHandler('validate') ) return false; }); // Create a confirmation dialog. If the user confirms that he want's to delete the message // kick of background request. Otherwise just destroy the confirmation dialog. $('ul.actions > li.destroy.message > a').show().click(function(){ var article = $(this).parents('article').eq(0); var newsgroup_and_topic_number = window.location.pathname.split('/'); var newsgroup = newsgroup_and_topic_number[1]; var topic_number = parseInt(newsgroup_and_topic_number[2], 10); var message_number = parseInt(article.attr('data-number'), 10); var confirmation_form = $('<div class="confirmation"><form>' + '<p>' + locale.delete_dialog.question + '</p>' + '<p><button>' + locale.delete_dialog.yes + '</button><button>' + locale.delete_dialog.no + '</button></p>' + '</form></div>').appendTo(article).find('> form'); confirmation_form.css({ top: (article.innerHeight() - confirmation_form.height()) / 2 + 'px', left: (article.innerWidth() - confirmation_form.width()) / 2 + 'px' }); confirmation_form.find('button'). eq(0).click(function(){ // Send DELETE request to delete the message $.ajax('/' + newsgroup + '/' + message_number, { type: 'DELETE', context: this, complete: function(request){ if (request.status == 204 || request.status == 404) { // In case of 204 the message has been deleted successfully. 404 means the message // is already deleted. In both case reload the page to show the updated information. // If we just deleted the root message of the topic load the newgroup topic list. if (topic_number == message_number) window.location.href = window.location.protocol + '//' + window.location.host + '/' + newsgroup; else window.location.reload(); } else { // 422 happend… I'm lazy now, just hide the confirmation form and show an alert box // with the error message. $(this).parents('div.confirmation').remove(); alert(request.responseText); } } }); return false; }).end(). eq(1).click(function(){ // Remove confirmation dialog $(this).parents('div.confirmation').remove(); return false; }).end(); return false; }); // Mange the attachment list. Allow to remove all but the last file input field in the list and // create a new empty file input after the user chose a file for one. $('form.message dl a').live('click', function(){ var dd_element = $(this).parent(); if ( dd_element.next().length == 1 ) dd_element.remove(); else $(this).siblings('input[type="file"]').val(''); return false; }); $('form.message dl input[type="file"]').live('change', function(){ var dd_element = $(this).parent(); if ( dd_element.next().length == 0 ) dd_element.clone(false).find('input[type="file"]').replaceWith('<input name="attachments[]" type="file" />').end().insertAfter(dd_element); return false; }); // Collapse the block quotes of the previous messages. It's somewhat nice that mail clients do that // but in a forum it's just visual clutter since the previous post is displayed right above the current // one. $('article > p + blockquote').each(function(){ // Ignore blockquotes with less than 3 paragraphs or blockquotes. Seems to be a good rule of // thumb to leave small quotes in tact but yet catch the big message quotes. if ( $(this).find('> p, > blockquote').length >= 3 ) $(this).prev('p').addClass('quote-guardian collapsed').attr('title', locale.show_quote); }); $('p.quote-guardian').live('click', function(){ if ( $(this).toggleClass('collapsed').hasClass('collapsed') ) $(this).attr('title', locale.show_quote); else $(this).attr('title', locale.hide_quote); return false; }) // Add links that collapse all replies to a message ("reply guardians"). The main work is done by the // style sheet that uses different styles for collapsed reply lists. We only toggle the `collapsed` class // here. $('article + ul').each(function(){ var reply_count = $(this).find('article').length; var title = locale.hide_replies.replace('%s', reply_count); $(this).prepend('<li class="reply-guardian" title="' + title + '"><a href="#">' + title + '</a></li>'); }); $('li.reply-guardian').live('click', function(){ var reply_list = $(this).parent('ul'); var reply_count = reply_list.find('article').length; if ( reply_list.toggleClass('collapsed').hasClass('collapsed') ) var title = locale.show_replies.replace('%s', reply_count); else var title = locale.hide_replies.replace('%s', reply_count); $(this).attr('title', title).find('a').text(title); return false; }) $('ul.actions > li.new.subscription > a').live('click', function(){ var article = $(this).closest('article'); var message_id = article.data('id'); console.log(message_id); $(this).closest('li').addClass('in_progress'); $.ajax('/your/subscriptions', { type: 'POST', contentType: 'text/plain', data: message_id, context: this, complete: function(request){ $(this).closest('li').removeClass('in_progress failed'); if (request.status == 201) { $(this).closest('li').addClass('disabled'); $(this).closest('ul').find('li.destroy.subscription').removeClass('disabled'); } else { $(this).closest('li').addClass('failed'); $(this).text(locale.subscribe_failed); } } }); return false; }); $('ul.actions > li.destroy.subscription > a').live('click', function(){ var article = $(this).closest('article'); var message_id = article.data('id'); $(this).closest('li').addClass('in_progress'); $.ajax('/your/subscriptions/' + encodeURIComponent(message_id), { type: 'DELETE', context: this, complete: function(request){ $(this).closest('li').removeClass('in_progress failed'); if (request.status == 204) { $(this).closest('li').addClass('disabled'); $(this).closest('ul').find('li.new.subscription').removeClass('disabled'); } else { $(this).closest('li').addClass('failed'); $(this).text(locale.unsubscribe_failed); } } }); return false; }); });
Java
UTF-8
53,411
2.078125
2
[]
no_license
package com.huazhu.application.cms.wechat.event.entity; import java.util.ArrayList; import java.util.Date; import java.util.List; public class CustomerInfoExample { protected String orderByClause; protected boolean distinct; protected List<Criteria> oredCriteria; public CustomerInfoExample() { oredCriteria = new ArrayList<Criteria>(); } public void setOrderByClause(String orderByClause) { this.orderByClause = orderByClause; } public String getOrderByClause() { return orderByClause; } public void setDistinct(boolean distinct) { this.distinct = distinct; } public boolean isDistinct() { return distinct; } public List<Criteria> getOredCriteria() { return oredCriteria; } public void or(Criteria criteria) { oredCriteria.add(criteria); } public Criteria or() { Criteria criteria = createCriteriaInternal(); oredCriteria.add(criteria); return criteria; } public Criteria createCriteria() { Criteria criteria = createCriteriaInternal(); if (oredCriteria.size() == 0) { oredCriteria.add(criteria); } return criteria; } protected Criteria createCriteriaInternal() { Criteria criteria = new Criteria(); return criteria; } public void clear() { oredCriteria.clear(); orderByClause = null; distinct = false; } protected abstract static class GeneratedCriteria { protected List<Criterion> criteria; protected GeneratedCriteria() { super(); criteria = new ArrayList<Criterion>(); } public boolean isValid() { return criteria.size() > 0; } public List<Criterion> getAllCriteria() { return criteria; } public List<Criterion> getCriteria() { return criteria; } protected void addCriterion(String condition) { if (condition == null) { throw new RuntimeException("Value for condition cannot be null"); } criteria.add(new Criterion(condition)); } protected void addCriterion(String condition, Object value, String property) { if (value == null) { throw new RuntimeException("Value for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value)); } protected void addCriterion(String condition, Object value1, Object value2, String property) { if (value1 == null || value2 == null) { throw new RuntimeException("Between values for " + property + " cannot be null"); } criteria.add(new Criterion(condition, value1, value2)); } public Criteria andRowIdIsNull() { addCriterion("row_id is null"); return (Criteria) this; } public Criteria andRowIdIsNotNull() { addCriterion("row_id is not null"); return (Criteria) this; } public Criteria andRowIdEqualTo(Long value) { addCriterion("row_id =", value, "rowId"); return (Criteria) this; } public Criteria andRowIdNotEqualTo(Long value) { addCriterion("row_id <>", value, "rowId"); return (Criteria) this; } public Criteria andRowIdGreaterThan(Long value) { addCriterion("row_id >", value, "rowId"); return (Criteria) this; } public Criteria andRowIdGreaterThanOrEqualTo(Long value) { addCriterion("row_id >=", value, "rowId"); return (Criteria) this; } public Criteria andRowIdLessThan(Long value) { addCriterion("row_id <", value, "rowId"); return (Criteria) this; } public Criteria andRowIdLessThanOrEqualTo(Long value) { addCriterion("row_id <=", value, "rowId"); return (Criteria) this; } public Criteria andRowIdIn(List<Long> values) { addCriterion("row_id in", values, "rowId"); return (Criteria) this; } public Criteria andRowIdNotIn(List<Long> values) { addCriterion("row_id not in", values, "rowId"); return (Criteria) this; } public Criteria andRowIdBetween(Long value1, Long value2) { addCriterion("row_id between", value1, value2, "rowId"); return (Criteria) this; } public Criteria andRowIdNotBetween(Long value1, Long value2) { addCriterion("row_id not between", value1, value2, "rowId"); return (Criteria) this; } public Criteria andCusNameIsNull() { addCriterion("cus_name is null"); return (Criteria) this; } public Criteria andCusNameIsNotNull() { addCriterion("cus_name is not null"); return (Criteria) this; } public Criteria andCusNameEqualTo(String value) { addCriterion("cus_name =", value, "cusName"); return (Criteria) this; } public Criteria andCusNameNotEqualTo(String value) { addCriterion("cus_name <>", value, "cusName"); return (Criteria) this; } public Criteria andCusNameGreaterThan(String value) { addCriterion("cus_name >", value, "cusName"); return (Criteria) this; } public Criteria andCusNameGreaterThanOrEqualTo(String value) { addCriterion("cus_name >=", value, "cusName"); return (Criteria) this; } public Criteria andCusNameLessThan(String value) { addCriterion("cus_name <", value, "cusName"); return (Criteria) this; } public Criteria andCusNameLessThanOrEqualTo(String value) { addCriterion("cus_name <=", value, "cusName"); return (Criteria) this; } public Criteria andCusNameLike(String value) { addCriterion("cus_name like", value, "cusName"); return (Criteria) this; } public Criteria andCusNameNotLike(String value) { addCriterion("cus_name not like", value, "cusName"); return (Criteria) this; } public Criteria andCusNameIn(List<String> values) { addCriterion("cus_name in", values, "cusName"); return (Criteria) this; } public Criteria andCusNameNotIn(List<String> values) { addCriterion("cus_name not in", values, "cusName"); return (Criteria) this; } public Criteria andCusNameBetween(String value1, String value2) { addCriterion("cus_name between", value1, value2, "cusName"); return (Criteria) this; } public Criteria andCusNameNotBetween(String value1, String value2) { addCriterion("cus_name not between", value1, value2, "cusName"); return (Criteria) this; } public Criteria andHotelIdIsNull() { addCriterion("hotel_id is null"); return (Criteria) this; } public Criteria andHotelIdIsNotNull() { addCriterion("hotel_id is not null"); return (Criteria) this; } public Criteria andHotelIdEqualTo(Long value) { addCriterion("hotel_id =", value, "hotelId"); return (Criteria) this; } public Criteria andHotelIdNotEqualTo(Long value) { addCriterion("hotel_id <>", value, "hotelId"); return (Criteria) this; } public Criteria andHotelIdGreaterThan(Long value) { addCriterion("hotel_id >", value, "hotelId"); return (Criteria) this; } public Criteria andHotelIdGreaterThanOrEqualTo(Long value) { addCriterion("hotel_id >=", value, "hotelId"); return (Criteria) this; } public Criteria andHotelIdLessThan(Long value) { addCriterion("hotel_id <", value, "hotelId"); return (Criteria) this; } public Criteria andHotelIdLessThanOrEqualTo(Long value) { addCriterion("hotel_id <=", value, "hotelId"); return (Criteria) this; } public Criteria andHotelIdIn(List<Long> values) { addCriterion("hotel_id in", values, "hotelId"); return (Criteria) this; } public Criteria andHotelIdNotIn(List<Long> values) { addCriterion("hotel_id not in", values, "hotelId"); return (Criteria) this; } public Criteria andHotelIdBetween(Long value1, Long value2) { addCriterion("hotel_id between", value1, value2, "hotelId"); return (Criteria) this; } public Criteria andHotelIdNotBetween(Long value1, Long value2) { addCriterion("hotel_id not between", value1, value2, "hotelId"); return (Criteria) this; } public Criteria andCusSexIsNull() { addCriterion("cus_sex is null"); return (Criteria) this; } public Criteria andCusSexIsNotNull() { addCriterion("cus_sex is not null"); return (Criteria) this; } public Criteria andCusSexEqualTo(Byte value) { addCriterion("cus_sex =", value, "cusSex"); return (Criteria) this; } public Criteria andCusSexNotEqualTo(Byte value) { addCriterion("cus_sex <>", value, "cusSex"); return (Criteria) this; } public Criteria andCusSexGreaterThan(Byte value) { addCriterion("cus_sex >", value, "cusSex"); return (Criteria) this; } public Criteria andCusSexGreaterThanOrEqualTo(Byte value) { addCriterion("cus_sex >=", value, "cusSex"); return (Criteria) this; } public Criteria andCusSexLessThan(Byte value) { addCriterion("cus_sex <", value, "cusSex"); return (Criteria) this; } public Criteria andCusSexLessThanOrEqualTo(Byte value) { addCriterion("cus_sex <=", value, "cusSex"); return (Criteria) this; } public Criteria andCusSexIn(List<Byte> values) { addCriterion("cus_sex in", values, "cusSex"); return (Criteria) this; } public Criteria andCusSexNotIn(List<Byte> values) { addCriterion("cus_sex not in", values, "cusSex"); return (Criteria) this; } public Criteria andCusSexBetween(Byte value1, Byte value2) { addCriterion("cus_sex between", value1, value2, "cusSex"); return (Criteria) this; } public Criteria andCusSexNotBetween(Byte value1, Byte value2) { addCriterion("cus_sex not between", value1, value2, "cusSex"); return (Criteria) this; } public Criteria andCountryIsNull() { addCriterion("country is null"); return (Criteria) this; } public Criteria andCountryIsNotNull() { addCriterion("country is not null"); return (Criteria) this; } public Criteria andCountryEqualTo(String value) { addCriterion("country =", value, "country"); return (Criteria) this; } public Criteria andCountryNotEqualTo(String value) { addCriterion("country <>", value, "country"); return (Criteria) this; } public Criteria andCountryGreaterThan(String value) { addCriterion("country >", value, "country"); return (Criteria) this; } public Criteria andCountryGreaterThanOrEqualTo(String value) { addCriterion("country >=", value, "country"); return (Criteria) this; } public Criteria andCountryLessThan(String value) { addCriterion("country <", value, "country"); return (Criteria) this; } public Criteria andCountryLessThanOrEqualTo(String value) { addCriterion("country <=", value, "country"); return (Criteria) this; } public Criteria andCountryLike(String value) { addCriterion("country like", value, "country"); return (Criteria) this; } public Criteria andCountryNotLike(String value) { addCriterion("country not like", value, "country"); return (Criteria) this; } public Criteria andCountryIn(List<String> values) { addCriterion("country in", values, "country"); return (Criteria) this; } public Criteria andCountryNotIn(List<String> values) { addCriterion("country not in", values, "country"); return (Criteria) this; } public Criteria andCountryBetween(String value1, String value2) { addCriterion("country between", value1, value2, "country"); return (Criteria) this; } public Criteria andCountryNotBetween(String value1, String value2) { addCriterion("country not between", value1, value2, "country"); return (Criteria) this; } public Criteria andCusSignIsNull() { addCriterion("cus_sign is null"); return (Criteria) this; } public Criteria andCusSignIsNotNull() { addCriterion("cus_sign is not null"); return (Criteria) this; } public Criteria andCusSignEqualTo(String value) { addCriterion("cus_sign =", value, "cusSign"); return (Criteria) this; } public Criteria andCusSignNotEqualTo(String value) { addCriterion("cus_sign <>", value, "cusSign"); return (Criteria) this; } public Criteria andCusSignGreaterThan(String value) { addCriterion("cus_sign >", value, "cusSign"); return (Criteria) this; } public Criteria andCusSignGreaterThanOrEqualTo(String value) { addCriterion("cus_sign >=", value, "cusSign"); return (Criteria) this; } public Criteria andCusSignLessThan(String value) { addCriterion("cus_sign <", value, "cusSign"); return (Criteria) this; } public Criteria andCusSignLessThanOrEqualTo(String value) { addCriterion("cus_sign <=", value, "cusSign"); return (Criteria) this; } public Criteria andCusSignLike(String value) { addCriterion("cus_sign like", value, "cusSign"); return (Criteria) this; } public Criteria andCusSignNotLike(String value) { addCriterion("cus_sign not like", value, "cusSign"); return (Criteria) this; } public Criteria andCusSignIn(List<String> values) { addCriterion("cus_sign in", values, "cusSign"); return (Criteria) this; } public Criteria andCusSignNotIn(List<String> values) { addCriterion("cus_sign not in", values, "cusSign"); return (Criteria) this; } public Criteria andCusSignBetween(String value1, String value2) { addCriterion("cus_sign between", value1, value2, "cusSign"); return (Criteria) this; } public Criteria andCusSignNotBetween(String value1, String value2) { addCriterion("cus_sign not between", value1, value2, "cusSign"); return (Criteria) this; } public Criteria andCusPhotoIsNull() { addCriterion("cus_photo is null"); return (Criteria) this; } public Criteria andCusPhotoIsNotNull() { addCriterion("cus_photo is not null"); return (Criteria) this; } public Criteria andCusPhotoEqualTo(String value) { addCriterion("cus_photo =", value, "cusPhoto"); return (Criteria) this; } public Criteria andCusPhotoNotEqualTo(String value) { addCriterion("cus_photo <>", value, "cusPhoto"); return (Criteria) this; } public Criteria andCusPhotoGreaterThan(String value) { addCriterion("cus_photo >", value, "cusPhoto"); return (Criteria) this; } public Criteria andCusPhotoGreaterThanOrEqualTo(String value) { addCriterion("cus_photo >=", value, "cusPhoto"); return (Criteria) this; } public Criteria andCusPhotoLessThan(String value) { addCriterion("cus_photo <", value, "cusPhoto"); return (Criteria) this; } public Criteria andCusPhotoLessThanOrEqualTo(String value) { addCriterion("cus_photo <=", value, "cusPhoto"); return (Criteria) this; } public Criteria andCusPhotoLike(String value) { addCriterion("cus_photo like", value, "cusPhoto"); return (Criteria) this; } public Criteria andCusPhotoNotLike(String value) { addCriterion("cus_photo not like", value, "cusPhoto"); return (Criteria) this; } public Criteria andCusPhotoIn(List<String> values) { addCriterion("cus_photo in", values, "cusPhoto"); return (Criteria) this; } public Criteria andCusPhotoNotIn(List<String> values) { addCriterion("cus_photo not in", values, "cusPhoto"); return (Criteria) this; } public Criteria andCusPhotoBetween(String value1, String value2) { addCriterion("cus_photo between", value1, value2, "cusPhoto"); return (Criteria) this; } public Criteria andCusPhotoNotBetween(String value1, String value2) { addCriterion("cus_photo not between", value1, value2, "cusPhoto"); return (Criteria) this; } public Criteria andCusOpenIdIsNull() { addCriterion("cus_open_id is null"); return (Criteria) this; } public Criteria andCusOpenIdIsNotNull() { addCriterion("cus_open_id is not null"); return (Criteria) this; } public Criteria andCusOpenIdEqualTo(String value) { addCriterion("cus_open_id =", value, "cusOpenId"); return (Criteria) this; } public Criteria andCusOpenIdNotEqualTo(String value) { addCriterion("cus_open_id <>", value, "cusOpenId"); return (Criteria) this; } public Criteria andCusOpenIdGreaterThan(String value) { addCriterion("cus_open_id >", value, "cusOpenId"); return (Criteria) this; } public Criteria andCusOpenIdGreaterThanOrEqualTo(String value) { addCriterion("cus_open_id >=", value, "cusOpenId"); return (Criteria) this; } public Criteria andCusOpenIdLessThan(String value) { addCriterion("cus_open_id <", value, "cusOpenId"); return (Criteria) this; } public Criteria andCusOpenIdLessThanOrEqualTo(String value) { addCriterion("cus_open_id <=", value, "cusOpenId"); return (Criteria) this; } public Criteria andCusOpenIdLike(String value) { addCriterion("cus_open_id like", value, "cusOpenId"); return (Criteria) this; } public Criteria andCusOpenIdNotLike(String value) { addCriterion("cus_open_id not like", value, "cusOpenId"); return (Criteria) this; } public Criteria andCusOpenIdIn(List<String> values) { addCriterion("cus_open_id in", values, "cusOpenId"); return (Criteria) this; } public Criteria andCusOpenIdNotIn(List<String> values) { addCriterion("cus_open_id not in", values, "cusOpenId"); return (Criteria) this; } public Criteria andCusOpenIdBetween(String value1, String value2) { addCriterion("cus_open_id between", value1, value2, "cusOpenId"); return (Criteria) this; } public Criteria andCusOpenIdNotBetween(String value1, String value2) { addCriterion("cus_open_id not between", value1, value2, "cusOpenId"); return (Criteria) this; } public Criteria andCreateDateIsNull() { addCriterion("create_date is null"); return (Criteria) this; } public Criteria andCreateDateIsNotNull() { addCriterion("create_date is not null"); return (Criteria) this; } public Criteria andCreateDateEqualTo(Date value) { addCriterion("create_date =", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateNotEqualTo(Date value) { addCriterion("create_date <>", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateGreaterThan(Date value) { addCriterion("create_date >", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateGreaterThanOrEqualTo(Date value) { addCriterion("create_date >=", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateLessThan(Date value) { addCriterion("create_date <", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateLessThanOrEqualTo(Date value) { addCriterion("create_date <=", value, "createDate"); return (Criteria) this; } public Criteria andCreateDateIn(List<Date> values) { addCriterion("create_date in", values, "createDate"); return (Criteria) this; } public Criteria andCreateDateNotIn(List<Date> values) { addCriterion("create_date not in", values, "createDate"); return (Criteria) this; } public Criteria andCreateDateBetween(Date value1, Date value2) { addCriterion("create_date between", value1, value2, "createDate"); return (Criteria) this; } public Criteria andCreateDateNotBetween(Date value1, Date value2) { addCriterion("create_date not between", value1, value2, "createDate"); return (Criteria) this; } public Criteria andCreateUserIsNull() { addCriterion("create_user is null"); return (Criteria) this; } public Criteria andCreateUserIsNotNull() { addCriterion("create_user is not null"); return (Criteria) this; } public Criteria andCreateUserEqualTo(Long value) { addCriterion("create_user =", value, "createUser"); return (Criteria) this; } public Criteria andCreateUserNotEqualTo(Long value) { addCriterion("create_user <>", value, "createUser"); return (Criteria) this; } public Criteria andCreateUserGreaterThan(Long value) { addCriterion("create_user >", value, "createUser"); return (Criteria) this; } public Criteria andCreateUserGreaterThanOrEqualTo(Long value) { addCriterion("create_user >=", value, "createUser"); return (Criteria) this; } public Criteria andCreateUserLessThan(Long value) { addCriterion("create_user <", value, "createUser"); return (Criteria) this; } public Criteria andCreateUserLessThanOrEqualTo(Long value) { addCriterion("create_user <=", value, "createUser"); return (Criteria) this; } public Criteria andCreateUserIn(List<Long> values) { addCriterion("create_user in", values, "createUser"); return (Criteria) this; } public Criteria andCreateUserNotIn(List<Long> values) { addCriterion("create_user not in", values, "createUser"); return (Criteria) this; } public Criteria andCreateUserBetween(Long value1, Long value2) { addCriterion("create_user between", value1, value2, "createUser"); return (Criteria) this; } public Criteria andCreateUserNotBetween(Long value1, Long value2) { addCriterion("create_user not between", value1, value2, "createUser"); return (Criteria) this; } public Criteria andLastUpdateDateIsNull() { addCriterion("last_update_date is null"); return (Criteria) this; } public Criteria andLastUpdateDateIsNotNull() { addCriterion("last_update_date is not null"); return (Criteria) this; } public Criteria andLastUpdateDateEqualTo(Date value) { addCriterion("last_update_date =", value, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateNotEqualTo(Date value) { addCriterion("last_update_date <>", value, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateGreaterThan(Date value) { addCriterion("last_update_date >", value, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateGreaterThanOrEqualTo(Date value) { addCriterion("last_update_date >=", value, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateLessThan(Date value) { addCriterion("last_update_date <", value, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateLessThanOrEqualTo(Date value) { addCriterion("last_update_date <=", value, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateIn(List<Date> values) { addCriterion("last_update_date in", values, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateNotIn(List<Date> values) { addCriterion("last_update_date not in", values, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateBetween(Date value1, Date value2) { addCriterion("last_update_date between", value1, value2, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateDateNotBetween(Date value1, Date value2) { addCriterion("last_update_date not between", value1, value2, "lastUpdateDate"); return (Criteria) this; } public Criteria andLastUpdateUserIsNull() { addCriterion("last_update_user is null"); return (Criteria) this; } public Criteria andLastUpdateUserIsNotNull() { addCriterion("last_update_user is not null"); return (Criteria) this; } public Criteria andLastUpdateUserEqualTo(Long value) { addCriterion("last_update_user =", value, "lastUpdateUser"); return (Criteria) this; } public Criteria andLastUpdateUserNotEqualTo(Long value) { addCriterion("last_update_user <>", value, "lastUpdateUser"); return (Criteria) this; } public Criteria andLastUpdateUserGreaterThan(Long value) { addCriterion("last_update_user >", value, "lastUpdateUser"); return (Criteria) this; } public Criteria andLastUpdateUserGreaterThanOrEqualTo(Long value) { addCriterion("last_update_user >=", value, "lastUpdateUser"); return (Criteria) this; } public Criteria andLastUpdateUserLessThan(Long value) { addCriterion("last_update_user <", value, "lastUpdateUser"); return (Criteria) this; } public Criteria andLastUpdateUserLessThanOrEqualTo(Long value) { addCriterion("last_update_user <=", value, "lastUpdateUser"); return (Criteria) this; } public Criteria andLastUpdateUserIn(List<Long> values) { addCriterion("last_update_user in", values, "lastUpdateUser"); return (Criteria) this; } public Criteria andLastUpdateUserNotIn(List<Long> values) { addCriterion("last_update_user not in", values, "lastUpdateUser"); return (Criteria) this; } public Criteria andLastUpdateUserBetween(Long value1, Long value2) { addCriterion("last_update_user between", value1, value2, "lastUpdateUser"); return (Criteria) this; } public Criteria andLastUpdateUserNotBetween(Long value1, Long value2) { addCriterion("last_update_user not between", value1, value2, "lastUpdateUser"); return (Criteria) this; } public Criteria andActiveFlagIsNull() { addCriterion("active_flag is null"); return (Criteria) this; } public Criteria andActiveFlagIsNotNull() { addCriterion("active_flag is not null"); return (Criteria) this; } public Criteria andActiveFlagEqualTo(Byte value) { addCriterion("active_flag =", value, "activeFlag"); return (Criteria) this; } public Criteria andActiveFlagNotEqualTo(Byte value) { addCriterion("active_flag <>", value, "activeFlag"); return (Criteria) this; } public Criteria andActiveFlagGreaterThan(Byte value) { addCriterion("active_flag >", value, "activeFlag"); return (Criteria) this; } public Criteria andActiveFlagGreaterThanOrEqualTo(Byte value) { addCriterion("active_flag >=", value, "activeFlag"); return (Criteria) this; } public Criteria andActiveFlagLessThan(Byte value) { addCriterion("active_flag <", value, "activeFlag"); return (Criteria) this; } public Criteria andActiveFlagLessThanOrEqualTo(Byte value) { addCriterion("active_flag <=", value, "activeFlag"); return (Criteria) this; } public Criteria andActiveFlagIn(List<Byte> values) { addCriterion("active_flag in", values, "activeFlag"); return (Criteria) this; } public Criteria andActiveFlagNotIn(List<Byte> values) { addCriterion("active_flag not in", values, "activeFlag"); return (Criteria) this; } public Criteria andActiveFlagBetween(Byte value1, Byte value2) { addCriterion("active_flag between", value1, value2, "activeFlag"); return (Criteria) this; } public Criteria andActiveFlagNotBetween(Byte value1, Byte value2) { addCriterion("active_flag not between", value1, value2, "activeFlag"); return (Criteria) this; } public Criteria andFollowDateIsNull() { addCriterion("follow_date is null"); return (Criteria) this; } public Criteria andFollowDateIsNotNull() { addCriterion("follow_date is not null"); return (Criteria) this; } public Criteria andFollowDateEqualTo(Date value) { addCriterion("follow_date =", value, "followDate"); return (Criteria) this; } public Criteria andFollowDateNotEqualTo(Date value) { addCriterion("follow_date <>", value, "followDate"); return (Criteria) this; } public Criteria andFollowDateGreaterThan(Date value) { addCriterion("follow_date >", value, "followDate"); return (Criteria) this; } public Criteria andFollowDateGreaterThanOrEqualTo(Date value) { addCriterion("follow_date >=", value, "followDate"); return (Criteria) this; } public Criteria andFollowDateLessThan(Date value) { addCriterion("follow_date <", value, "followDate"); return (Criteria) this; } public Criteria andFollowDateLessThanOrEqualTo(Date value) { addCriterion("follow_date <=", value, "followDate"); return (Criteria) this; } public Criteria andFollowDateIn(List<Date> values) { addCriterion("follow_date in", values, "followDate"); return (Criteria) this; } public Criteria andFollowDateNotIn(List<Date> values) { addCriterion("follow_date not in", values, "followDate"); return (Criteria) this; } public Criteria andFollowDateBetween(Date value1, Date value2) { addCriterion("follow_date between", value1, value2, "followDate"); return (Criteria) this; } public Criteria andFollowDateNotBetween(Date value1, Date value2) { addCriterion("follow_date not between", value1, value2, "followDate"); return (Criteria) this; } public Criteria andProvinceIsNull() { addCriterion("province is null"); return (Criteria) this; } public Criteria andProvinceIsNotNull() { addCriterion("province is not null"); return (Criteria) this; } public Criteria andProvinceEqualTo(String value) { addCriterion("province =", value, "province"); return (Criteria) this; } public Criteria andProvinceNotEqualTo(String value) { addCriterion("province <>", value, "province"); return (Criteria) this; } public Criteria andProvinceGreaterThan(String value) { addCriterion("province >", value, "province"); return (Criteria) this; } public Criteria andProvinceGreaterThanOrEqualTo(String value) { addCriterion("province >=", value, "province"); return (Criteria) this; } public Criteria andProvinceLessThan(String value) { addCriterion("province <", value, "province"); return (Criteria) this; } public Criteria andProvinceLessThanOrEqualTo(String value) { addCriterion("province <=", value, "province"); return (Criteria) this; } public Criteria andProvinceLike(String value) { addCriterion("province like", value, "province"); return (Criteria) this; } public Criteria andProvinceNotLike(String value) { addCriterion("province not like", value, "province"); return (Criteria) this; } public Criteria andProvinceIn(List<String> values) { addCriterion("province in", values, "province"); return (Criteria) this; } public Criteria andProvinceNotIn(List<String> values) { addCriterion("province not in", values, "province"); return (Criteria) this; } public Criteria andProvinceBetween(String value1, String value2) { addCriterion("province between", value1, value2, "province"); return (Criteria) this; } public Criteria andProvinceNotBetween(String value1, String value2) { addCriterion("province not between", value1, value2, "province"); return (Criteria) this; } public Criteria andCityIsNull() { addCriterion("city is null"); return (Criteria) this; } public Criteria andCityIsNotNull() { addCriterion("city is not null"); return (Criteria) this; } public Criteria andCityEqualTo(String value) { addCriterion("city =", value, "city"); return (Criteria) this; } public Criteria andCityNotEqualTo(String value) { addCriterion("city <>", value, "city"); return (Criteria) this; } public Criteria andCityGreaterThan(String value) { addCriterion("city >", value, "city"); return (Criteria) this; } public Criteria andCityGreaterThanOrEqualTo(String value) { addCriterion("city >=", value, "city"); return (Criteria) this; } public Criteria andCityLessThan(String value) { addCriterion("city <", value, "city"); return (Criteria) this; } public Criteria andCityLessThanOrEqualTo(String value) { addCriterion("city <=", value, "city"); return (Criteria) this; } public Criteria andCityLike(String value) { addCriterion("city like", value, "city"); return (Criteria) this; } public Criteria andCityNotLike(String value) { addCriterion("city not like", value, "city"); return (Criteria) this; } public Criteria andCityIn(List<String> values) { addCriterion("city in", values, "city"); return (Criteria) this; } public Criteria andCityNotIn(List<String> values) { addCriterion("city not in", values, "city"); return (Criteria) this; } public Criteria andCityBetween(String value1, String value2) { addCriterion("city between", value1, value2, "city"); return (Criteria) this; } public Criteria andCityNotBetween(String value1, String value2) { addCriterion("city not between", value1, value2, "city"); return (Criteria) this; } public Criteria andLanguageIsNull() { addCriterion("language is null"); return (Criteria) this; } public Criteria andLanguageIsNotNull() { addCriterion("language is not null"); return (Criteria) this; } public Criteria andLanguageEqualTo(String value) { addCriterion("language =", value, "language"); return (Criteria) this; } public Criteria andLanguageNotEqualTo(String value) { addCriterion("language <>", value, "language"); return (Criteria) this; } public Criteria andLanguageGreaterThan(String value) { addCriterion("language >", value, "language"); return (Criteria) this; } public Criteria andLanguageGreaterThanOrEqualTo(String value) { addCriterion("language >=", value, "language"); return (Criteria) this; } public Criteria andLanguageLessThan(String value) { addCriterion("language <", value, "language"); return (Criteria) this; } public Criteria andLanguageLessThanOrEqualTo(String value) { addCriterion("language <=", value, "language"); return (Criteria) this; } public Criteria andLanguageLike(String value) { addCriterion("language like", value, "language"); return (Criteria) this; } public Criteria andLanguageNotLike(String value) { addCriterion("language not like", value, "language"); return (Criteria) this; } public Criteria andLanguageIn(List<String> values) { addCriterion("language in", values, "language"); return (Criteria) this; } public Criteria andLanguageNotIn(List<String> values) { addCriterion("language not in", values, "language"); return (Criteria) this; } public Criteria andLanguageBetween(String value1, String value2) { addCriterion("language between", value1, value2, "language"); return (Criteria) this; } public Criteria andLanguageNotBetween(String value1, String value2) { addCriterion("language not between", value1, value2, "language"); return (Criteria) this; } public Criteria andSurveyAgeIsNull() { addCriterion("survey_age is null"); return (Criteria) this; } public Criteria andSurveyAgeIsNotNull() { addCriterion("survey_age is not null"); return (Criteria) this; } public Criteria andSurveyAgeEqualTo(String value) { addCriterion("survey_age =", value, "surveyAge"); return (Criteria) this; } public Criteria andSurveyAgeNotEqualTo(String value) { addCriterion("survey_age <>", value, "surveyAge"); return (Criteria) this; } public Criteria andSurveyAgeGreaterThan(String value) { addCriterion("survey_age >", value, "surveyAge"); return (Criteria) this; } public Criteria andSurveyAgeGreaterThanOrEqualTo(String value) { addCriterion("survey_age >=", value, "surveyAge"); return (Criteria) this; } public Criteria andSurveyAgeLessThan(String value) { addCriterion("survey_age <", value, "surveyAge"); return (Criteria) this; } public Criteria andSurveyAgeLessThanOrEqualTo(String value) { addCriterion("survey_age <=", value, "surveyAge"); return (Criteria) this; } public Criteria andSurveyAgeLike(String value) { addCriterion("survey_age like", value, "surveyAge"); return (Criteria) this; } public Criteria andSurveyAgeNotLike(String value) { addCriterion("survey_age not like", value, "surveyAge"); return (Criteria) this; } public Criteria andSurveyAgeIn(List<String> values) { addCriterion("survey_age in", values, "surveyAge"); return (Criteria) this; } public Criteria andSurveyAgeNotIn(List<String> values) { addCriterion("survey_age not in", values, "surveyAge"); return (Criteria) this; } public Criteria andSurveyAgeBetween(String value1, String value2) { addCriterion("survey_age between", value1, value2, "surveyAge"); return (Criteria) this; } public Criteria andSurveyAgeNotBetween(String value1, String value2) { addCriterion("survey_age not between", value1, value2, "surveyAge"); return (Criteria) this; } public Criteria andAbroadDestinationIsNull() { addCriterion("abroad_destination is null"); return (Criteria) this; } public Criteria andAbroadDestinationIsNotNull() { addCriterion("abroad_destination is not null"); return (Criteria) this; } public Criteria andAbroadDestinationEqualTo(String value) { addCriterion("abroad_destination =", value, "abroadDestination"); return (Criteria) this; } public Criteria andAbroadDestinationNotEqualTo(String value) { addCriterion("abroad_destination <>", value, "abroadDestination"); return (Criteria) this; } public Criteria andAbroadDestinationGreaterThan(String value) { addCriterion("abroad_destination >", value, "abroadDestination"); return (Criteria) this; } public Criteria andAbroadDestinationGreaterThanOrEqualTo(String value) { addCriterion("abroad_destination >=", value, "abroadDestination"); return (Criteria) this; } public Criteria andAbroadDestinationLessThan(String value) { addCriterion("abroad_destination <", value, "abroadDestination"); return (Criteria) this; } public Criteria andAbroadDestinationLessThanOrEqualTo(String value) { addCriterion("abroad_destination <=", value, "abroadDestination"); return (Criteria) this; } public Criteria andAbroadDestinationLike(String value) { addCriterion("abroad_destination like", value, "abroadDestination"); return (Criteria) this; } public Criteria andAbroadDestinationNotLike(String value) { addCriterion("abroad_destination not like", value, "abroadDestination"); return (Criteria) this; } public Criteria andAbroadDestinationIn(List<String> values) { addCriterion("abroad_destination in", values, "abroadDestination"); return (Criteria) this; } public Criteria andAbroadDestinationNotIn(List<String> values) { addCriterion("abroad_destination not in", values, "abroadDestination"); return (Criteria) this; } public Criteria andAbroadDestinationBetween(String value1, String value2) { addCriterion("abroad_destination between", value1, value2, "abroadDestination"); return (Criteria) this; } public Criteria andAbroadDestinationNotBetween(String value1, String value2) { addCriterion("abroad_destination not between", value1, value2, "abroadDestination"); return (Criteria) this; } public Criteria andDomesticDestinationIsNull() { addCriterion("domestic_destination is null"); return (Criteria) this; } public Criteria andDomesticDestinationIsNotNull() { addCriterion("domestic_destination is not null"); return (Criteria) this; } public Criteria andDomesticDestinationEqualTo(String value) { addCriterion("domestic_destination =", value, "domesticDestination"); return (Criteria) this; } public Criteria andDomesticDestinationNotEqualTo(String value) { addCriterion("domestic_destination <>", value, "domesticDestination"); return (Criteria) this; } public Criteria andDomesticDestinationGreaterThan(String value) { addCriterion("domestic_destination >", value, "domesticDestination"); return (Criteria) this; } public Criteria andDomesticDestinationGreaterThanOrEqualTo(String value) { addCriterion("domestic_destination >=", value, "domesticDestination"); return (Criteria) this; } public Criteria andDomesticDestinationLessThan(String value) { addCriterion("domestic_destination <", value, "domesticDestination"); return (Criteria) this; } public Criteria andDomesticDestinationLessThanOrEqualTo(String value) { addCriterion("domestic_destination <=", value, "domesticDestination"); return (Criteria) this; } public Criteria andDomesticDestinationLike(String value) { addCriterion("domestic_destination like", value, "domesticDestination"); return (Criteria) this; } public Criteria andDomesticDestinationNotLike(String value) { addCriterion("domestic_destination not like", value, "domesticDestination"); return (Criteria) this; } public Criteria andDomesticDestinationIn(List<String> values) { addCriterion("domestic_destination in", values, "domesticDestination"); return (Criteria) this; } public Criteria andDomesticDestinationNotIn(List<String> values) { addCriterion("domestic_destination not in", values, "domesticDestination"); return (Criteria) this; } public Criteria andDomesticDestinationBetween(String value1, String value2) { addCriterion("domestic_destination between", value1, value2, "domesticDestination"); return (Criteria) this; } public Criteria andDomesticDestinationNotBetween(String value1, String value2) { addCriterion("domestic_destination not between", value1, value2, "domesticDestination"); return (Criteria) this; } public Criteria andActivityIsNull() { addCriterion("activity is null"); return (Criteria) this; } public Criteria andActivityIsNotNull() { addCriterion("activity is not null"); return (Criteria) this; } public Criteria andActivityEqualTo(String value) { addCriterion("activity =", value, "activity"); return (Criteria) this; } public Criteria andActivityNotEqualTo(String value) { addCriterion("activity <>", value, "activity"); return (Criteria) this; } public Criteria andActivityGreaterThan(String value) { addCriterion("activity >", value, "activity"); return (Criteria) this; } public Criteria andActivityGreaterThanOrEqualTo(String value) { addCriterion("activity >=", value, "activity"); return (Criteria) this; } public Criteria andActivityLessThan(String value) { addCriterion("activity <", value, "activity"); return (Criteria) this; } public Criteria andActivityLessThanOrEqualTo(String value) { addCriterion("activity <=", value, "activity"); return (Criteria) this; } public Criteria andActivityLike(String value) { addCriterion("activity like", value, "activity"); return (Criteria) this; } public Criteria andActivityNotLike(String value) { addCriterion("activity not like", value, "activity"); return (Criteria) this; } public Criteria andActivityIn(List<String> values) { addCriterion("activity in", values, "activity"); return (Criteria) this; } public Criteria andActivityNotIn(List<String> values) { addCriterion("activity not in", values, "activity"); return (Criteria) this; } public Criteria andActivityBetween(String value1, String value2) { addCriterion("activity between", value1, value2, "activity"); return (Criteria) this; } public Criteria andActivityNotBetween(String value1, String value2) { addCriterion("activity not between", value1, value2, "activity"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; } public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
C#
UTF-8
1,889
3.046875
3
[]
no_license
using System; using NetworkCommsDotNet; using NetworkCommsDotNet.Connections; using NetworkCommsDotNet.Connections.TCP; using Protocol; using System.Threading; namespace Client { class Client { Network net; Display print; public void Connect() { net = new Network(); print = new Display(); ConnectionInfo connInfo = new ConnectionInfo("127.0.0.1", 2222); Connection newTCPConn = TCPConnection.GetConnection(connInfo); newTCPConn.AppendIncomingPacketHandler<Network>("Network", PrintIncomingMessage); newTCPConn.AppendShutdownHandler(OnConnectionClosed); Thread.Sleep(100); while (true) ; } private void OnConnectionClosed(Connection connection) { Console.WriteLine("Connection closed!"); Environment.Exit(0); } private void OnConnectionEstablished(Connection connection) { Console.WriteLine("Connection established!"); } private void PrintIncomingMessage(PacketHeader header, Connection connection, Network receive) { print.setNet(receive); if (receive.State == 0) print.display(); //print msg else if (receive.State == 1) Console.WriteLine(" " + receive.message + Tools.ENTER); //print game + msg + get input from user else if (receive.State >= 2) { net = receive; if (receive.State == 2) print.display(); if (receive.State == 3) { print.display_contract(); Console.WriteLine(Tools.ENTER); } print.check_and_send(connection); } } } }
Python
UTF-8
316
3.234375
3
[ "MIT" ]
permissive
from math import factorial instr = [1.00e+06, 6.00e+07, 3.60e+09, 8.64e+10, 2.59e+12, 3.15e+13, 3.15e+15] def fctorial(instr): number = [] for i in instr: n = 0 f = 1 while f <= int(i): f = factorial(n) n += 1 number.append(n-2) return number
Java
UTF-8
5,593
2.34375
2
[]
no_license
package cn.hehe9.persistent.dao; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import cn.hehe9.persistent.entity.Video; import cn.hehe9.persistent.mapper.VideoMapper; @Service @Transactional(propagation = Propagation.SUPPORTS, rollbackFor = Exception.class) public class VideoDao { @Resource private VideoMapper videoMapper; /** * 查询视频列表: 仅查询简要的数据 */ public List<Video> listBrief(int page, int count) { Map<String, Object> params = new HashMap<String, Object>(); int offset = (page - 1) * count; params.put("offset", offset); params.put("count", count); return videoMapper.findBriefBy(params); } /** * 查询视频列表: 排除大数据量的字段 */ public List<Video> listExceptBigData(Integer sourceId, int page, int count) { Map<String, Object> params = new HashMap<String, Object>(); int offset = (page - 1) * count; params.put("sourceId", sourceId); params.put("offset", offset); params.put("count", count); return videoMapper.findExceptBigDataBy(params); } /** * 查询视频列表: 排除大数据量的字段 */ public List<Video> listExceptBigData(Integer sourceId, String name) { Map<String, Object> params = new HashMap<String, Object>(); params.put("sourceId", sourceId); if (StringUtils.isNotBlank(name)) { params.put("name", name); } params.put("offset", 0); params.put("count", Integer.MAX_VALUE); return videoMapper.findExceptBigDataBy(params); } /** * 查询视频列表: 查询视频的所有的数据 */ public List<Video> list(int page, int count) { Map<String, Object> params = new HashMap<String, Object>(); int offset = (page - 1) * count; params.put("offset", offset); params.put("count", count); return videoMapper.findBy(params); } /** * 根据名称, 查询简要信息 * @param name * @return */ public List<Video> searchBriefByName(Integer sourceId, String name) { return findBriefBy(sourceId, null, name, null); } /** * 根据名称, 查询简要信息 * @param name * @return */ public List<Video> searchBriefByName(String name) { return findBriefBy(null, null, name, null); } /** * 根据条件, 查询简要信息 * @param name * @return */ public List<Video> findBriefByListPageUrl(Integer sourceId, String listPageUrl) { return findBriefBy(sourceId, null, null, listPageUrl, 1, Integer.MAX_VALUE); } /** * 根据条件, 查询简要信息 * @param name * @return */ public List<Video> findBriefBy(Integer sourceId, String firstChar, String name, String listPageUrl) { return findBriefBy(sourceId, firstChar, name, listPageUrl, 1, Integer.MAX_VALUE); } /** * 根据条件, 查询简要信息 * @param name 名称 * @param page 查询页码 * @param count 查询数量 * @return */ public List<Video> findBriefBy(Integer sourceId, String firstChar, String name, String listPageUrl, int page, int count) { Map<String, Object> params = new HashMap<String, Object>(); params.put("sourceId", sourceId); if (StringUtils.isNotBlank(firstChar)) { params.put("firstChar", firstChar); } if (StringUtils.isNotBlank(name)) { params.put("name", name); } if (StringUtils.isNotBlank(listPageUrl)) { params.put("listPageUrl", listPageUrl); } int offset = (page - 1) * count; params.put("offset", offset); params.put("count", count); return videoMapper.findBriefBy(params); } /** * 根据条件, 查询视频信息 * * @param videoId 视频id * @return 视频信息 */ public Video findById(Integer videoId) { return videoMapper.selectByPrimaryKey(videoId); } @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class) public int save(Video video) { video.setCreateTime(new Date()); return videoMapper.insertSelective(video); } @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class) public int udpate(Video video) { return videoMapper.updateByPrimaryKeySelective(video); } public Integer countBy(String firstChar, String name) { Map<String, Object> params = new HashMap<String, Object>(1); if (StringUtils.isNotBlank(firstChar)) { params.put("firstChar", firstChar); } if (StringUtils.isNotBlank(name)) { params.put("name", name); } return videoMapper.countBy(params); } /** * 按首字母分组查询记录 * @param countPerFirstChar 每组字母查询前多少条记录 * @return 视频列表 */ public List<Video> listBriefGroupByFirstChar(int countPerFirstChar) { Map<String, Object> params = new HashMap<String, Object>(); params.put("countPerFirstChar", countPerFirstChar); return videoMapper.listBriefGroupByFirstChar(params); } public int deleteById(Integer id) { return videoMapper.deleteByPrimaryKey(id); } public int updateRank(Integer sourceId, int rank) { Map<String, Object> params = new HashMap<String, Object>(); params.put("sourceId", sourceId); params.put("rank", rank); return videoMapper.updateRank(params); } public List<Video> listNoEpisodeVideos() { return videoMapper.listNoEpisodeVideos(); } public int delete(List<Integer> videoIds) { Map<String, Object> params = new HashMap<String, Object>(); params.put("videoIds", videoIds); return videoMapper.delete(params); } }
Java
UTF-8
9,717
1.96875
2
[]
no_license
package com.example.todolist.Main.Today; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import androidx.appcompat.app.AlertDialog; import androidx.fragment.app.Fragment; import androidx.lifecycle.ViewModelProvider; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.Toast; import com.example.todolist.Di.ViewModelFactory; import com.example.todolist.Main.GroupsViewModel; import com.example.todolist.Model.Entities.Groups; import com.example.todolist.Model.Entities.Tasks; import com.example.todolist.Model.Repositories.GroupsRepository; import com.example.todolist.R; import com.example.todolist.entry.EntryActivity; import com.example.todolist.tasks.TasksActivity; import com.example.todolist.tasks.TasksAdapter; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import dagger.android.support.AndroidSupportInjection; import io.reactivex.CompletableObserver; import io.reactivex.SingleObserver; import io.reactivex.android.schedulers.AndroidSchedulers; import io.reactivex.annotations.NonNull; import io.reactivex.disposables.Disposable; import io.reactivex.schedulers.Schedulers; public class TodayFragment extends Fragment implements TodayGroupsAdapter.OnItemClicked { private View rootView; private RecyclerView recyclerView; private TodayGroupsAdapter todayGroupsAdapter; private LinearLayout emptyStateToday; @Inject public GroupsRepository groupsRepository; private GroupsViewModel groupsViewModel; private Disposable disposable; private String groupLabel; @Inject public ViewModelFactory viewModelFactory_new; // @Inject // public ViewModelFactory viewModelFactory; public static TodayFragment newInstance(String text) { TodayFragment f = new TodayFragment(); Bundle b = new Bundle(); b.putString("msg", text); f.setArguments(b); return f; } // @Override // public void onCreate(Bundle savedInstanceState) { // super.onCreate(savedInstanceState); // if (getArguments() != null) { // mParam1 = getArguments().getString(ARG_PARAM1); // mParam2 = getArguments().getString(ARG_PARAM2); // } // } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { // Inflate the layout for this fragment rootView = inflater.inflate(R.layout.fragment_today, container, false); AndroidSupportInjection.inject(this); initialize(); // checkFirstTime(); showTodayGroups(); return rootView; } private void initialize() { recyclerView = rootView.findViewById(R.id.rc_GroupListToday); emptyStateToday = rootView.findViewById(R.id.emptyStateToday); // groupsViewModel = new ViewModelProvider(this, new GroupsViewModelFactory(groupsRepository, 1)).get(GroupsViewModel.class); groupsViewModel = new ViewModelProvider(this, viewModelFactory_new).get(GroupsViewModel.class); } private void showTodayGroups() { // GroupsViewModel groupsViewModel = new ViewModelProvider(this, new GroupsViewModelFactory(groupsRepository, 1)).get(GroupsViewModel.class); groupsViewModel.getGroupsToday().observe(getViewLifecycleOwner(), t -> { if (t.size() < 1) { emptyStateToday.setVisibility(View.VISIBLE); } else { emptyStateToday.setVisibility(View.GONE); } RecyclerView.LayoutManager mLayoutManager = new GridLayoutManager(rootView.getContext(), 2); recyclerView.setLayoutManager(mLayoutManager); // recyclerView.setLayoutManager(new LinearLayoutManager(rootView.getContext(), RecyclerView.VERTICAL, false)); todayGroupsAdapter = new TodayGroupsAdapter(t); recyclerView.setAdapter(todayGroupsAdapter); todayGroupsAdapter.setOnClick(this); }); // groupsViewModel.getError().observe(getViewLifecycleOwner(), e -> { // Toast.makeText(rootView.getContext(), "Failed Sync Your Groups!!!", Toast.LENGTH_LONG).show(); // }); } private void checkInternet() { groupsViewModel.isInternetWorking().subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new SingleObserver<Boolean>() { @Override public void onSubscribe(@NonNull Disposable d) { disposable = d; } @Override public void onSuccess(@NonNull Boolean aBoolean) { Intent intent = new Intent(rootView.getContext(), EntryActivity.class); startActivity(intent); getActivity().finish(); } @Override public void onError(@NonNull Throwable e) { } }); } private void deleteGroup(Groups groups) { Groups groups1 = new Groups(groups.getId(), groups.getIcon(), groups.getLabel(), groups.getCategory(), groups.isSynced(), true, groups.isUpdated(), groups.getDonePercent(), groups.getTasksCount()); groupsViewModel.updateGroup(groups1).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new CompletableObserver() { @Override public void onSubscribe(@NonNull Disposable d) { // compositeDisposable.add(d); } @Override public void onComplete() { groupLabel = groups.getLabel(); getTasks(groups.getId()); } @Override public void onError(@NonNull Throwable e) { Toast.makeText(rootView.getContext(), "Deleted unsuccessfully!!", Toast.LENGTH_SHORT).show(); Log.e("TAG", "onError: ", e); } }); } private void getTasks(int gpId){ groupsViewModel.getTasks(gpId).observe(getViewLifecycleOwner(), this::deleteTasks); } private void deleteTasks(List<Tasks> tasksList){ int counter = 0; while (counter < tasksList.size()){ tasksList.get(counter).setDeleted(true); groupsViewModel.setScheduleNotification(groupLabel, tasksList.get(counter).getContent(), R.drawable.ic_github, tasksList.get(counter).getDate(), tasksList.get(counter).isRepeatTask(), tasksList.get(counter).getId(), true); counter++; } groupsViewModel.updateTask2(tasksList).subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread()).subscribe(new CompletableObserver() { @Override public void onSubscribe(@NonNull Disposable d) { } @Override public void onComplete() { Toast.makeText(rootView.getContext(), "Deleted successfully", Toast.LENGTH_SHORT).show(); } @Override public void onError(@NonNull Throwable e) { } }); } private void dialog(Groups groups) { new AlertDialog.Builder(rootView.getContext()) .setTitle("Delete group") .setMessage("Are you sure you want to delete this group?") // Specifying a listener allows you to take an action before dismissing the dialog. // The dialog is automatically dismissed when a dialog button is clicked. .setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { // Continue with delete operation deleteGroup(groups); } }) // .setNeutralButton("Edit task", new DialogInterface.OnClickListener() { // @Override // public void onClick(DialogInterface dialogInterface, int i) { // Intent intent = new Intent(this, AddTaskActivity) // } // }) // A null listener allows the button to dismiss the dialog and take no further action. .setNegativeButton(android.R.string.no, null) // .setIcon(android.R.drawable.ic_dialog_alert) .show(); } private void checkFirstTime(){ // boolean s = groupsViewModel.saveDataSharedPreferences("first_time", "test"); // Log.e("TAG", "checkFirstTime: " + s ); String result = groupsViewModel.getDataSharedPreferences("first_time"); if (result != null) checkInternet(); // SharedPreferences sharedPref = rootView.getContext().getSharedPreferences("user", Context.MODE_PRIVATE); // sharedPref.getString("key", null); } @Override public void onDestroy() { super.onDestroy(); // disposable.dispose(); } @Override public void onItemClick(Groups groups) { Intent intent = new Intent(rootView.getContext(), TasksActivity.class); intent.putExtra("groupId",groups.getId()); intent.putExtra("groupLabel",groups.getLabel()); intent.putExtra("groupCategory","Day"); rootView.getContext().startActivity(intent); } @Override public void onItemLongClick(Groups groups) { dialog(groups); // Toast.makeText(rootView.getContext(), groups.getLabel(), Toast.LENGTH_SHORT).show(); } }
C++
UTF-8
4,924
2.53125
3
[ "MIT" ]
permissive
#include <vector> #include <iterator> #include <algorithm> template<typename T> void readoutART(Layer<T> layer, int numEpisode, std::vector< std::vector<double> >& output) { output.resize(layer.x.size()); for(unsigned int i=0; i<layer.x.size();i++) { output[i].resize(layer.weight[i][numEpisode].size()/2); for(unsigned int j=0; j<layer.weight[i][numEpisode].size()/2; j++) { output[i][j] = layer.weight[i][numEpisode][j]; } } } bool near_zero(double i) { return (i < 0.000001); } void readout(Layer<int> layer_obj, Layer<int> layer_obj2, Layer<int> layer1, Layer<double> layer2, int numEpisode, std::vector<Episode> episode) { std::vector< std::vector<double> > output1; std::vector< std::vector<double> > output_obj; std::vector< std::vector<double> > output_obj2; std::vector< std::vector<double> > normalized_oy; std::vector< std::vector<double> > ix(episode[numEpisode].numEvent); std::vector< std::vector<double> > bx(episode[numEpisode].numEvent); std::vector< std::vector<double> > oy(episode[numEpisode].numEvent); std::vector< std::vector<double> > temp(episode[numEpisode].numEvent); int L = 0; int E = 0; readoutART(layer2, numEpisode, normalized_oy); // Weight readout process.. for(auto& i:normalized_oy[0]) { if(near_zero(i)) i = 0; } for(int i=0; i<episode[numEpisode].numEvent; i++) { ix[i].resize(normalized_oy[0].size(),0); bx[i].resize(normalized_oy[0].size(),0); oy[i].resize(normalized_oy[0].size(),0); temp[i].resize(normalized_oy[0].size(),0); if(i == 0) { // De-normalization .. for(unsigned int j=0; j<normalized_oy[0].size(); j++) oy[i][j] = int(normalized_oy[0][j]*std::pow(10,max_position_num[numEpisode])); } else oy[i] = bx[i-1]; L = std::distance(oy[i].begin(), std::max_element(oy[i].begin(), oy[i].end())); for(int k=0; k<episode[numEpisode].numEvent; k++) { if(std::abs(iw*std::pow((bw*ow),k) - oy[i][L]) < 0.001) { E = k; break; } else if(iw*std::pow((bw*ow),k) > oy[i][L]) { E = k-1; break; } else if(k == (episode[numEpisode].numEvent-1)) E = k; } ix[i][L] = 1; bx[i] = oy[i]; bx[i][L] = oy[i][L] - iw*std::pow((bw*ow),E)*ix[i][L]; readoutART(layer1, std::distance(ix[i].begin(), std::max_element(ix[i].begin(), ix[i].end())), output1); readoutART(layer_obj, std::distance(output1[1].begin(), std::max_element(output1[1].begin(), output1[1].end())), output_obj); readoutART(layer_obj2, std::distance(output1[2].begin(), std::max_element(output1[2].begin(), output1[2].end())), output_obj2); std::stringstream ss; std::cout << "Event " << i << " : " << std::endl; ss << ACTION[std::distance(output1[0].begin(), std::max_element(output1[0].begin(), output1[0].end()))] << " "; if(!near_zero(*std::max_element(output_obj[4].begin(), output_obj[4].end()))) ss << OBJECT_PREPOSITION[std::distance(output_obj[4].begin(), std::max_element(output_obj[4].begin(), output_obj[4].end()))] << " "; if(!near_zero(*std::max_element(output_obj[1].begin(), output_obj[1].end()))) ss << OBJECT_COLOR[std::distance(output_obj[1].begin(), std::max_element(output_obj[1].begin(), output_obj[1].end()))] << " "; if(!near_zero(*std::max_element(output_obj[2].begin(), output_obj[2].end()))) ss << OBJECT_SHAPE[std::distance(output_obj[2].begin(), std::max_element(output_obj[2].begin(), output_obj[2].end()))] << " "; if(!near_zero(*std::max_element(output_obj[3].begin(), output_obj[3].end()))) ss << OBJECT_TYPE[std::distance(output_obj[3].begin(), std::max_element(output_obj[3].begin(), output_obj[3].end()))] << " "; if(!near_zero(*std::max_element(output_obj[0].begin(), output_obj[0].end()))) ss << OBJECT[std::distance(output_obj[0].begin(), std::max_element(output_obj[0].begin(), output_obj[0].end()))] << " "; if(!near_zero(*std::max_element(output_obj2[4].begin(), output_obj2[4].end()))) ss << OBJECT_PREPOSITION[std::distance(output_obj2[4].begin(), std::max_element(output_obj2[4].begin(), output_obj2[4].end()))] << " "; if(!near_zero(*std::max_element(output_obj2[1].begin(), output_obj2[1].end()))) ss << OBJECT_COLOR[std::distance(output_obj2[1].begin(), std::max_element(output_obj2[1].begin(), output_obj2[1].end()))] << " "; if(!near_zero(*std::max_element(output_obj2[2].begin(), output_obj2[2].end()))) ss << OBJECT_SHAPE[std::distance(output_obj2[2].begin(), std::max_element(output_obj2[2].begin(), output_obj2[2].end()))] << " "; if(!near_zero(*std::max_element(output_obj2[3].begin(), output_obj2[3].end()))) ss << OBJECT_TYPE[std::distance(output_obj2[3].begin(), std::max_element(output_obj2[3].begin(), output_obj2[3].end()))] << " "; if(!near_zero(*std::max_element(output_obj2[0].begin(), output_obj2[0].end()))) ss << OBJECT[std::distance(output_obj2[0].begin(), std::max_element(output_obj2[0].begin(), output_obj2[0].end()))]; std::cout << ss.str() << std::endl; } }
PHP
UTF-8
378
3.03125
3
[]
no_license
<?php namespace App; class Logger { public static function message($context, $message = '') { if (is_string($context)) { $message = $context; $context = null; } if (strpos($message, "\n") !== false) { $message .= "\n" . $message; } echo date('[Y-m-d H:i:s]') . (is_object($context) ? (' [' . $context->getId() . ']') : '') . ' ' . $message . "\n"; } }
Java
UTF-8
6,455
1.664063
2
[ "MIT", "Apache-2.0" ]
permissive
/** * Copyright 2018-2019 Amazon.com, * Inc. or its affiliates. All Rights Reserved. * * SPDX-License-Identifier: Apache-2.0 */ package com.apollographql.apollo.internal.cache.normalized; import com.apollographql.apollo.api.GraphqlFragment; import com.apollographql.apollo.api.Operation; import com.apollographql.apollo.api.Response; import com.apollographql.apollo.api.ResponseFieldMapper; import com.apollographql.apollo.cache.CacheHeaders; import com.apollographql.apollo.cache.normalized.ApolloStore; import com.apollographql.apollo.cache.normalized.GraphQLStoreOperation; import com.apollographql.apollo.cache.normalized.CacheKey; import com.apollographql.apollo.cache.normalized.CacheKeyResolver; import com.apollographql.apollo.cache.normalized.NormalizedCache; import com.apollographql.apollo.cache.normalized.Record; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.Map; import java.util.Set; import java.util.UUID; import javax.annotation.Nonnull; import javax.annotation.Nullable; /** * An alternative to {@link RealAppSyncStore} for when a no-operation cache is needed. */ public final class NoOpApolloStore implements ApolloStore, ReadableStore, WriteableStore { @Override public Set<String> merge(@Nonnull Collection<Record> recordCollection, @Nonnull CacheHeaders cacheHeaders) { return Collections.emptySet(); } @Override public Set<String> merge(Record record, @Nonnull CacheHeaders cacheHeaders) { return Collections.emptySet(); } @Nullable @Override public Record read(@Nonnull String key, @Nonnull CacheHeaders cacheHeaders) { return null; } @Override public Collection<Record> read(@Nonnull Collection<String> keys, @Nonnull CacheHeaders cacheHeaders) { return Collections.emptySet(); } @Override public void subscribe(RecordChangeSubscriber subscriber) { } @Override public void unsubscribe(RecordChangeSubscriber subscriber) { } @Override public void publish(Set<String> keys) { } @Nonnull @Override public GraphQLStoreOperation<Boolean> clearAll() { return GraphQLStoreOperation.emptyOperation(Boolean.FALSE); } @Nonnull @Override public GraphQLStoreOperation<Boolean> remove(@Nonnull CacheKey cacheKey) { return GraphQLStoreOperation.emptyOperation(Boolean.FALSE); } @Nonnull @Override public GraphQLStoreOperation<Integer> remove(@Nonnull List<CacheKey> cacheKeys) { return GraphQLStoreOperation.emptyOperation(0); } @Override public ResponseNormalizer<Map<String, Object>> networkResponseNormalizer() { //noinspection unchecked return ResponseNormalizer.NO_OP_NORMALIZER; } @Override public ResponseNormalizer<Record> cacheResponseNormalizer() { //noinspection unchecked return ResponseNormalizer.NO_OP_NORMALIZER; } @Override public <R> R readTransaction(Transaction<ReadableStore, R> transaction) { return transaction.execute(this); } @Override public <R> R writeTransaction(Transaction<WriteableStore, R> transaction) { return transaction.execute(this); } @Override public NormalizedCache normalizedCache() { return null; } @Override public CacheKeyResolver cacheKeyResolver() { return null; } @Nonnull @Override public <D extends Operation.Data, T, V extends Operation.Variables> GraphQLStoreOperation<T> read( @Nonnull Operation<D, T, V> operation) { return GraphQLStoreOperation.emptyOperation(null); } @Nonnull @Override public <D extends Operation.Data, T, V extends Operation.Variables> GraphQLStoreOperation<Response<T>> read( @Nonnull Operation<D, T, V> operation, @Nonnull ResponseFieldMapper<D> responseFieldMapper, @Nonnull ResponseNormalizer<Record> responseNormalizer, @Nonnull CacheHeaders cacheHeaders) { return GraphQLStoreOperation.emptyOperation(Response.<T>builder(operation).build()); } @Nonnull @Override public <F extends GraphqlFragment> GraphQLStoreOperation<F> read(@Nonnull ResponseFieldMapper<F> fieldMapper, @Nonnull CacheKey cacheKey, @Nonnull Operation.Variables variables) { return GraphQLStoreOperation.emptyOperation(null); } @Nonnull @Override public <D extends Operation.Data, T, V extends Operation.Variables> GraphQLStoreOperation<Set<String>> write( @Nonnull Operation<D, T, V> operation, @Nonnull D operationData) { return GraphQLStoreOperation.emptyOperation(Collections.<String>emptySet()); } @Nonnull @Override public <D extends Operation.Data, T, V extends Operation.Variables> GraphQLStoreOperation<Boolean> writeAndPublish( @Nonnull Operation<D, T, V> operation, @Nonnull D operationData) { return GraphQLStoreOperation.emptyOperation(Boolean.FALSE); } @Nonnull @Override public GraphQLStoreOperation<Set<String>> write(@Nonnull GraphqlFragment fragment, @Nonnull CacheKey cacheKey, @Nonnull Operation.Variables variables) { return GraphQLStoreOperation.emptyOperation(Collections.<String>emptySet()); } @Nonnull @Override public GraphQLStoreOperation<Boolean> writeAndPublish(@Nonnull GraphqlFragment fragment, @Nonnull CacheKey cacheKey, @Nonnull Operation.Variables variables) { return GraphQLStoreOperation.emptyOperation(Boolean.FALSE); } @Nonnull @Override public <D extends Operation.Data, T, V extends Operation.Variables> GraphQLStoreOperation<Set<String>> writeOptimisticUpdates(@Nonnull Operation<D, T, V> operation, @Nonnull D operationData, @Nonnull UUID mutationId) { return GraphQLStoreOperation.emptyOperation(Collections.<String>emptySet()); } @Nonnull @Override public <D extends Operation.Data, T, V extends Operation.Variables> GraphQLStoreOperation<Boolean> writeOptimisticUpdatesAndPublish(@Nonnull Operation<D, T, V> operation, @Nonnull D operationData, @Nonnull UUID mutationId) { return GraphQLStoreOperation.emptyOperation(Boolean.FALSE); } @Nonnull @Override public GraphQLStoreOperation<Boolean> rollbackOptimisticUpdatesAndPublish(@Nonnull UUID mutationId) { return GraphQLStoreOperation.emptyOperation(Boolean.FALSE); } @Nonnull @Override public GraphQLStoreOperation<Set<String>> rollbackOptimisticUpdates(@Nonnull UUID mutationId) { return GraphQLStoreOperation.emptyOperation(Collections.<String>emptySet()); } }
Java
UTF-8
6,948
2.046875
2
[]
no_license
/* * Created by JFormDesigner on Wed Mar 15 14:12:19 MSK 2017 */ package client.reporter; import java.awt.*; import java.awt.event.*; import java.io.IOException; import java.util.*; import java.util.List; import javax.swing.*; import javax.swing.border.EmptyBorder; import client.component.WaitingDialog; import client.component.suggestion.SuggestionComboBox; import client.net.*; import client.reporter.component.renderer.ActionListRenderer; import report.enums.EForm; import report.exceptions.ExcelReportException; import report.reporter.managers.BuildManager; import server.protocol2.*; import server.protocol2.reporter.*; /** * @author Maksim */ public class QuotaReportFrame extends JFrame implements NetListener<Request, Response> { // JFormDesigner - Variables declaration - DO NOT MODIFY //GEN-BEGIN:variables private SuggestionComboBox<RAction> actionComboBox; private JButton showButton; // JFormDesigner - End of variables declaration //GEN-END:variables private WaitingDialog waitingDialog; public QuotaReportFrame(Window owner, List<RAction> allActionList, List<RActionEvent> allActionEventList) { initComponents(); Set<Long> actionIdSet = new HashSet<>(); for (RActionEvent actionEvent : allActionEventList) { if (actionEvent.isQuota()) { actionIdSet.add(actionEvent.getActionId()); } } for (RAction action : allActionList) { if (actionIdSet.contains(action.getId())) { actionComboBox.addItem(action);//на первой итерации вызывается actionComboBoxItemStateChanged } } ActionListRenderer actionListRenderer = new ActionListRenderer(70); actionListRenderer.setShowOrganizer(Env.user.getUserType() != UserType.ORGANIZER); actionComboBox.setRenderer(actionListRenderer); actionComboBox.setElementToStringConverter(actionListRenderer); showButton.setIcon(Env.excelIcon); pack(); setLocationRelativeTo(owner); } @Override public void setVisible(boolean b) { super.setVisible(b); if (b) { int state = getExtendedState(); if ((state & ICONIFIED) != 0) setExtendedState(state & ~ICONIFIED); } } private void actionComboBoxItemStateChanged(ItemEvent e) { if (e.getStateChange() == ItemEvent.SELECTED) { showButton.setEnabled(true); } } private void showButtonActionPerformed() { RAction action = actionComboBox.getItemAt(actionComboBox.getSelectedIndex()); if (action == null) return; BuildManager.setAction(action); BuildManager.setActionEventQuotaMap(null); waitingDialog = new WaitingDialog(this, Dialog.ModalityType.DOCUMENT_MODAL); Env.net.create("GET_REPORT_SALE_INFO", new Request(new Object[]{action.getId(), null, null}), this).start(); } private void initComponents() { // JFormDesigner - Component initialization - DO NOT MODIFY //GEN-BEGIN:initComponents JPanel panel1 = new JPanel(); JLabel label1 = new JLabel(); actionComboBox = new SuggestionComboBox<>(); JPanel panel3 = new JPanel(); showButton = new JButton(); //======== this ======== setIconImages(Env.frameIcons); setTitle("\u041e\u0442\u0447\u0435\u0442 \u043f\u043e \u043f\u0440\u043e\u0434\u0430\u0436\u0430\u043c"); Container contentPane = getContentPane(); contentPane.setLayout(new BorderLayout()); //======== panel1 ======== { panel1.setBorder(new EmptyBorder(5, 5, 5, 5)); panel1.setLayout(new GridBagLayout()); ((GridBagLayout)panel1.getLayout()).columnWidths = new int[] {0, 0}; ((GridBagLayout)panel1.getLayout()).rowHeights = new int[] {0, 0, 0}; ((GridBagLayout)panel1.getLayout()).columnWeights = new double[] {1.0, 1.0E-4}; ((GridBagLayout)panel1.getLayout()).rowWeights = new double[] {0.0, 0.0, 1.0E-4}; //---- label1 ---- label1.setText("\u041f\u0440\u0435\u0434\u0441\u0442\u0430\u0432\u043b\u0435\u043d\u0438\u0435:"); panel1.add(label1, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 5, 0), 0, 0)); //---- actionComboBox ---- actionComboBox.setMaximumRowCount(18); actionComboBox.addItemListener(new ItemListener() { @Override public void itemStateChanged(ItemEvent e) { actionComboBoxItemStateChanged(e); } }); panel1.add(actionComboBox, new GridBagConstraints(0, 1, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0)); } contentPane.add(panel1, BorderLayout.NORTH); //======== panel3 ======== { panel3.setBorder(new EmptyBorder(5, 5, 5, 5)); panel3.setLayout(new GridBagLayout()); ((GridBagLayout)panel3.getLayout()).columnWidths = new int[] {0, 0}; ((GridBagLayout)panel3.getLayout()).rowHeights = new int[] {0, 0}; ((GridBagLayout)panel3.getLayout()).columnWeights = new double[] {0.0, 1.0E-4}; ((GridBagLayout)panel3.getLayout()).rowWeights = new double[] {0.0, 1.0E-4}; //---- showButton ---- showButton.setText("\u041f\u043e\u043a\u0430\u0437\u0430\u0442\u044c \u043e\u0442\u0447\u0435\u0442"); showButton.setEnabled(false); showButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { showButtonActionPerformed(); } }); panel3.add(showButton, new GridBagConstraints(0, 0, 1, 1, 0.0, 0.0, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(0, 0, 0, 0), 0, 0)); } contentPane.add(panel3, BorderLayout.SOUTH); // JFormDesigner - End of component initialization //GEN-END:initComponents } @Override public void netState(NetEvent<Request, Response> event, Network.State state) { if (state == Network.State.STARTED) waitingDialog.setVisible(true); if (state == Network.State.FINISHED) waitingDialog.setVisible(false); } @Override public void netResult(NetResultEvent<Request, Response> result) { if (!result.getResponse().isSuccess()) { JOptionPane.showMessageDialog(this, result.getResponse().getErrorForUser(), "Ошибка", JOptionPane.ERROR_MESSAGE); return; } ReportSaleInfo reportSaleInfo = (ReportSaleInfo) result.getResponse().getData(); BuildManager.setReportSaleInfo(reportSaleInfo); try { BuildManager.build(EForm.FORM_9); } catch (IOException | ExcelReportException e) { JOptionPane.showMessageDialog(this, "Не удалось открыть файл: " + e.getMessage(), "Ошибка", JOptionPane.ERROR_MESSAGE); } } @Override public void netError(NetErrorEvent<Request, Response> error) { JOptionPane.showMessageDialog(this, "Ошибка соединения с сервером. Не удалось загрузить данные", "Ошибка", JOptionPane.ERROR_MESSAGE); } }
Java
UTF-8
1,984
2.296875
2
[]
no_license
package booking; import java.io.IOException; import java.sql.SQLException; import java.text.SimpleDateFormat; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; @WebServlet("/Addbooking") public class Addbooking extends HttpServlet { private static final long serialVersionUID = 1L; public Addbooking() { super(); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { SimpleDateFormat format = new SimpleDateFormat ("yyyy-mm-dd"); java.util.Date date_checkin = null; java.util.Date date_checkout = null; try { date_checkin = (java.util.Date) format.parse(request.getParameter("date_checkin")); date_checkout = (java.util.Date) format.parse(request.getParameter("date_checkout")); } catch (java.text.ParseException e) { e.printStackTrace(); } java.sql.Date sqldate1 = new java.sql.Date(date_checkin.getTime()); java.sql.Date sqldate2 = new java.sql.Date(date_checkout.getTime()); Booking iv = new Booking(); iv.setGuest_id(Integer.parseInt(request.getParameter("guest_id"))); iv.setRoom_id(Integer.parseInt(request.getParameter("room_id"))); iv.setBed_no(Integer.parseInt(request.getParameter("bed"))); iv.setDate_checkin(sqldate1); iv.setDate_checkout(sqldate2); BookingModel im = new BookingModel(); try { im.addBooking(iv); } catch (SQLException | ClassNotFoundException e) { e.printStackTrace(); } HttpSession session = request.getSession(); session.setAttribute("success", "Success"); response.sendRedirect("records.jsp"); } }
C#
UTF-8
935
2.75
3
[ "MIT" ]
permissive
using System; using System.Linq; using System.Linq.Expressions; using AMKsGear.Architecture; namespace AMKsGear.Core.Linq { public static class QueryableExtensions { #region OrderByEx public static IOrderedQueryable<TEntity> OrderByEx<TEntity, TKey>( this IQueryable<TEntity> queryable, Expression<Func<TEntity, TKey>> selector, SortingOrder order) { return order == SortingOrder.Descending ? queryable.OrderByDescending(selector) : queryable.OrderBy(selector); } #endregion //public static Task<List<TElement>> ToListAsync<TElement>(this IQueryable<TElement> queryable) //{ return Task.Run(() => queryable.ToList()); } //public static Task<TElement[]> ToArrayAsync<TElement>(this IQueryable<TElement> queryable) //{ return Task.Run(() => queryable.ToArray()); } } }
TypeScript
UTF-8
2,967
2.71875
3
[]
no_license
import { Request, Response } from 'express'; import pool from '../database' class SeccionesController{ public async list (req: Request, res: Response): Promise<void>{ const Secciones = await pool.query('SELECT * FROM Secciones') res.json(Secciones); } public async getOne (req: Request, res: Response): Promise<any>{ const { id } = req.params; const usuario = await pool.query('SELECT * FROM Secciones WHERE IdSeccion = ?', [id]); if(usuario.length > 0){ res.json(usuario[0]) }else{ res.status(404).json({Text: "La seccion no existe"}) } } public async create (req: Request, res: Response): Promise<any>{ const IdSeccion = JSON.stringify(req.body.IdSeccion); var usuarios = (await pool.query( 'SELECT * FROM Secciones WHERE IdSeccion = ' + IdSeccion )); if(usuarios.length == 0){ await pool.query('INSERT INTO Secciones set ?', [req.body]) res.json({Text: 'seccion ' + IdSeccion + ' Creada'}); }else{ res.status(404).json({Text: "La seccion ya existe"}) } } public async update (req: Request, res: Response): Promise<any>{ const { id } = req.params; const usuario = await pool.query('SELECT * FROM Secciones WHERE IdSeccion = ?', [id]); if(usuario.length > 0){ await pool.query('UPDATE Secciones set ? WHERE IdSeccion = ?', [req.body, id]) res.json({Text: "La seccion fue actualizada"}) }else{ res.status(404).json({Text: "La seccion no existe"}) } } public async delete (req: Request, res: Response): Promise<any>{ const { id } = req.params; const usuario = await pool.query('SELECT * FROM Secciones WHERE IdSeccion = ?', [id]); if(usuario.length > 0){ await pool.query('DELETE FROM Secciones WHERE IdSeccion = ?', [id]) res.json({Text: 'seccion ' + id + ' Eliminada'}); }else{ res.status(404).json({Text: "La seccion no existe"}) } } public async getCurso (req: Request, res: Response): Promise<any>{ const { id } = req.params; const usuario = await pool.query('SELECT * FROM Secciones WHERE CodigoCurso = ?', [id]); if(usuario.length > 0){ res.json(usuario) }else{ res.status(404).json({Text: "No existen secciones"}) } } public async getCatedratico (req: Request, res: Response): Promise<any>{ const { id } = req.params; const usuario = await pool.query('SELECT * FROM Secciones WHERE IdSCatedratico = ?', [id]); if(usuario.length > 0){ res.json(usuario) }else{ res.status(404).json({Text: "No existen secciones"}) } } } const seccionesController = new SeccionesController(); export default seccionesController;
Markdown
UTF-8
2,093
4.28125
4
[ "MIT" ]
permissive
--- layout: post permalink: lc0919 --- ## 919. Complete Binary Tree Inserter 完全二叉树是一种二叉树,其中除了可能的最后一层外,每一层都被完全填满,并且所有节点都尽可能靠左。 设计一种算法,将新节点插入到完整的二叉树中,并在插入后保持完整。 实现 CBTInserter 类: CBTInserter(TreeNode root) 用完整二叉树的根初始化数据结构。 int insert(int v) 将 TreeNode 插入到值为 Node.val == val 的树中,使树保持完整,并返回插入的 TreeNode 的父节点的值。 TreeNode get_root() 返回树的根节点。 BFS ```java /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class CBTInserter { TreeNode root ; public CBTInserter(TreeNode root) { this.root=root; return; } public int insert(int val) { Queue<TreeNode> queue = new LinkedList<>(); queue.add(root); TreeNode newNode = new TreeNode(val); while(!queue.isEmpty()){ int len =queue.size(); for(int i=0;i<len;i++){ TreeNode Node = queue.poll(); if(Node.left==null){ Node.left=newNode; return Node.val; }else queue.add(Node.left); if(Node.right==null){ Node.right=newNode; return Node.val; }else queue.add(Node.right); } } return -1; } public TreeNode get_root() { return root; } } /** * Your CBTInserter object will be instantiated and called as such: * CBTInserter obj = new CBTInserter(root); * int param_1 = obj.insert(val); * TreeNode param_2 = obj.get_root(); */ ```
Python
UTF-8
7,538
2.734375
3
[]
no_license
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Feb 13 19:37:13 2019 @author: lz """ import time import multiprocessing import click import universal_functions as uf class mp: """ Multiprocess object, can know which processes are running and which are waiting. func = function to multiprocess mp_arg = the only argument to iterate in multiprocess fixed_arg = other args in function that is fixed in all process pool_size = how many processes to open timeout = how long to wait for a job until you call it failed job_names = jobs names in a list of strings with the same length as mp_arg flushtime = seconds you want the program to report status and fill in new jobs, should << than your job running time kwarg = other fixed key word args to function each iteration After creating object, call run() method to start the jobs """ def __init__(self, func, mp_arg, *fixed_arg, pool_size=None, timeout=None, job_names=[], flushtime=5, **kwarg): self.func = func if isinstance(mp_arg, list): self.mp_arg = mp_arg else: raise ValueError('mp_arg must be a list') if isinstance(pool_size, int): self.mp_arg = mp_arg else: raise ValueError('must be an integer') if isinstance(job_names, list): if job_names and len(job_names) == len(mp_arg): self.job_names = job_names else: self.job_names = [] else: raise ValueError('job_names must be a list') if not pool_size: self.pool_size = multiprocessing.cpu_count() else: self.pool_size = pool_size self.timeout = timeout self.fixed_arg = fixed_arg self.kwarg = kwarg self.res = [] self._completed = set() self._failed = set() self.flushtime = flushtime self.jobs = None def __str__(self): return (f'A self built multiprocess object. ' f'Jobs completed {list(self._completed)} ' f'Jobs failed {list(self._failed)} ' ) def __repr__(self): return 'A self built multiprocess object.' def completed(self): return list(self._completed) def failed(self): return list(self._failed) def status(self): """Returns a list, first value how many completed, second how many failed""" return [len(self._completed), len(self._failed)] def run(self): _job_indices = {x for x in range(len(self.mp_arg))} _running = set() p = multiprocessing.Pool(self.pool_size) uf.info(f' Number of jobs {len(_job_indices)}', True) uf.info(f'Pool size is {self.pool_size}', True) _jobs = [] time.sleep(3) _slots_remain = self.pool_size _submitted = set() _timer = time.perf_counter() with click.progressbar(length=len(self.mp_arg)) as bar: while _job_indices != set(): _slot_count = 0 try: _slots_remain = self.pool_size - [job.ready() for job in _jobs].count(False) except: pass try: for i in _job_indices: if _slot_count < _slots_remain: _args = tuple([self.mp_arg[i]] + list(self.fixed_arg)) _jobs += [p.apply_async(self.func, args=_args, kwds=self.kwarg)] _submitted.add(i) _slot_count += 1 except: pass for index, job in enumerate(_jobs): if job.ready(): self._completed.add(index) else: _running.add(index) _job_indices -= _submitted try: time_last_flush except: time_last_flush = self.flushtime if time.time() - time_last_flush < self.flushtime + 0.1: pass else: print_run = [f'{index}{self.job_names[index] if self.job_names else ""}' for index in list(_running)] print_completed = [f'{index}{self.job_names[index] if self.job_names else ""}' for index in list(self._completed)] print_waiting = [f'{index}{self.job_names[index] if self.job_names else ""}' for index in list(_job_indices)] uf.info(f'jobs running: {print_run if len(print_run) <= 15 else len(print_run)}', True) uf.info(f'jobs completed: {print_completed if len(print_completed) <= 15 else len(print_completed)}', True) uf.info(f'jobs waiting: {print_waiting if len(print_waiting) <= 15 else len(print_waiting)}', True) uf.info(f'number waiting: {len(_job_indices)}', True) bar.update(len(self._completed)) print("") time_last_flush = time.time() _running = set() # behavior after all jobs submitted while len(self._completed) != len(self.mp_arg): for index, job in enumerate(_jobs): if job.ready(): self._completed.add(index) else: _running.add(index) try: time_last_flush except: time_last_flush = self.flushtime if time.time() - time_last_flush < self.flushtime + 0.1: pass else: print_run = [f'{index}{self.job_names[index] if self.job_names else ""}' for index in list(_running)] print_completed = [f'{index}{self.job_names[index] if self.job_names else ""}' for index in list(self._completed)] uf.info(f'jobs running: {print_run if len(print_run) <= 15 else len(print_run)}', True) uf.info(f'jobs completed: {print_completed if len(print_completed) <= 15 else len(print_completed)}', True) time_last_flush = time.time() _running = set() bar.update(len(self._completed)) print("") time.sleep(self.flushtime) if self.timeout and time.perf_counter() - _timer > self.timeout: break # Try to get results for i, job in enumerate(_jobs): # uf.info("im here 1") try: # uf.info("i here 2") self.res.append(job.get(timeout=1)) except: uf.info(f'Job {i} waited too long, time out', True) self.res.append("Fail") self._failed.add(i) if all([job.ready() and job.successful() for job in _jobs]): uf.info('All jobs are done running', True) elif all([job.ready() for job in _jobs]): uf.info('All jobs have been run but some failed', True) self.jobs = _jobs ########### test code # mylist = [chr(x) for x in range(ord('a'), ord('k'))] # # # def dummy(x): # try: # uf.info('processing ' + str(x)) # finally: # time.sleep(10) # # # aaa = mp(dummy, mylist) # aaa.run() # # bbb = mp(max, mylist, 'b', 'c') # bbb.run() # bbb.res
Python
UTF-8
1,027
3.21875
3
[]
no_license
# coding=utf-8 # 플로이드 풀이 def solution(n, m, price): INF = int(1e9) graph = [[INF] * n for _ in range(n)] for i in range(m): a, b, c = price[i] graph[a - 1][b - 1] = min(graph[a - 1][b - 1], c) # print(graph) # 시작 도시와 도착 도시가 같은 경우 for i in range(n): graph[i][i] = 0 # print(graph) # 플로이드 점화식 D(ab) = min(D(ab), D(a(ak)+a(kb))) for k in range(n): for i in range(n): for j in range(n): graph[i][j] = min(graph[i][k] + graph[k][j], graph[i][j]) # print(graph) # 이동할 수 없는 경우 for i in range(n): for j in range(n): if graph[i][j] == INF: graph[i][j] = 0 for i in range(n): print(graph[i]) solution(5, 14, [[1, 2, 2], [1, 3, 3], [1, 4, 1], [1, 5, 10], [2, 4, 2], [3, 4, 1], [3, 5, 1], [4, 5, 3], [3, 5, 10], [3, 1, 8], [1, 4, 2], [5, 1, 7], [3, 4, 2], [5, 2, 4]])