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,110
3.0625
3
[ "MIT" ]
permissive
/* Copyright (c) 2011 Andrée Ekroth * See the file LICENSE.txt for copying permission. */ #ifndef KKE_ARGPARSER_HPP #define KKE_ARGPARSER_HPP #include "IO/Argument.hpp" #include "Interface/INoncopyable.hpp" #include "Utilities/FNV1aHash.hpp" #include "Utilities/Singleton.hpp" #include <string> #include <unordered_map> #define ArgHasher(x) KKE_FNV1AHASH(x) namespace kke { typedef FNV1aHash::Hash ArgumentID; /** * @brief Run-time hash **/ inline ArgumentID ArgHasherRT(const char* str) { return FNV1aHash::hash_rt(str); } /** * @brief Run-time hash **/ inline ArgumentID ArgHasherRT(const std::string& str) { return FNV1aHash::hash_rt(str.c_str()); } /** * @brief Registers arguments to an integer, and parses them. **/ class ArgParser : public Singleton<ArgParser> { friend class Singleton<ArgParser>; public: /** * @brief Process the arguments. * @return bool **/ bool Process(int argc, char **argv); const Argument* GetArgument(const ArgumentID& id); /** * @brief If argument has been registered. * @return bool **/ bool Registered(const ArgumentID& id); /** * @brief If registered argument has been parsed. * @return bool **/ bool Exist(const ArgumentID& id); /** * @brief Return argument index. * @return int **/ int ValidArgument(const std::string &arg) const; /** * @brief Register a argument. * * @param id Unique argument ID. * @param type Type of argument. * @param lName Long name of argument. (--<lName>) * @param sName Short name of argument. (-<sName>) Defaults to std::string(). * @param info Description of argument. Defaults to "No description.". * @return bool **/ bool Register(const ArgumentID& id, ArgumentType type, const std::string &lName, const std::string &sName = std::string(), const std::string &info = "No description."); void CaseSense(bool value); private: ArgParser(); ~ArgParser(); private: typedef std::unordered_map<ArgumentID, Argument> ArgMap; ArgMap argMap; bool caseSense; }; } #endif // KKE_ARGPARSER_HPP
C
UTF-8
408
3.09375
3
[]
no_license
#include <stdio.h> #include <stdlib.h> #include <string.h> void main() { int nums[] = {-1,0,1,2,-1,-4}; int numsSize = sizeof(nums)/sizeof(nums[0]); int** ret = NULL; int retSize = 0; int i; ret = threeSum(&(nums[0]),numsSize,&retSize); if(ret){ for(i = 0; i < retSize; i++){ printf("ret[%d] = %d\t%d\t%d\n",i,ret[i][0],ret[i][1],ret[i][2]); } }else{ printf("error ret = %d\n",ret); } }
Markdown
UTF-8
1,732
2.578125
3
[]
no_license
# Secret Task Force - Wireframe (IECSE) > Developer : S Sitaraman (a.k.a hackerbone), Team ID : 57744 (Solo) - Designed a responsive Cartel themed minimalist website for the given prompt. The website is hosted currently on netlify. [Site Link](https://stf-hackerbone.netlify.app/) - Frameworks and Software used : ReactJS, Sass (Scss), Figma - The webpage was created using custom CSS, no bootstrap and is mobile responsive (Yup iPhone 5/SE as well) - One of the things I found was that only on iPhones the view port is a bit zoomed, tried to use meta tags for that but did not work. It works perfectly on iPhones if the screen is pinched to zoom out. This issue occurs in iPhones only since the `100vh` height includes the URL Bar and the bottom navs in browsers like chrome/safari etc. ## Here are some snapshots of the website #### Landing page ![Landing Page](/images/landing.png) #### Access page ![Access Page](/images/accesspage.png) #### Dashboard page ![Dashboard Page](/images/dashboard.png) #### Social Media Users page ![Users Page](/images/users.png) #### Social Media Users - Specific page ![User Specific Page](/images/user-specific.png) #### Social Media Posts page ![Posts Page](/images/posts.png) #### Social Media Posts - Specific page ![Post Specific Page](/images/post-specific.png) #### Stocks page ![Stocks Page](/images/stocks.png) #### Stock - Specific page ![Stock Specific Page](/images/stock-specific.png) #### Institutions page ![Institutions Page](/images/institutions.png) #### Institution - Specific page ![Institutions Specific Page](/images/institution-specific.png) #### Mobile Version ![Mobile Responsive](/images/mobile.png) #### 404 Page ![404 Page](/images/404.png)
Java
UTF-8
376
2.59375
3
[]
no_license
package com.xuke.unit.api.stringdemo; public class StringApiDemo { public static void main(String[] args) { byte[] bt= {97,98,99,100}; String str=new String(bt); System.out.println(str); //int offset, int length String str2=new String(bt,0,2); System.out.println(str2); String str3=new String(new char[]{'a','3','y'}); System.out.println(str3); } }
Java
UTF-8
181
1.664063
2
[]
no_license
package com.yourplace.custom.reservation.service; import com.yourplace.custom.reservation.vo.ReviewVO; public interface ClickedReviewService { void clickedReview(ReviewVO vo); }
Python
UTF-8
4,521
2.6875
3
[ "MIT" ]
permissive
import re import os from pymongo import MongoClient from tqdm import tqdm import datetime MongoUrl = "xxx" # 清洗库 res_kb_process = "xxxx" res_kb_process_expert = "xxxx" dir_path = os.path.dirname(__file__) class ExperienceExtractor(object): def __init__(self): self.load_experience_position() def load_experience_position(self): with open(os.path.join(dir_path,"experience_position.txt"),"r") as fr: datas = fr.readlines() datas = list(map(lambda x:x.strip(), datas)) self.experience_positions = datas def split_sentence(self,sentences): '''根据时间戳将单句分句''' sentences = sentences.replace("(","(").replace(")",")").replace(u"\xa0"," ") sentences = re.sub("[~~]","-",sentences) sentences = re.sub(" {3,}"," ", sentences) # 时间后置 # like 曾任东北大学学科建设处处长(1999-2005),现任东北大学研究院院长(2011-至今) if re.findall("(\d{4}", sentences): return re.split("[,,]", sentences) res = re.finditer("[1-2]{1}\d{3}",sentences) time_index = [r.span()[0] for r in res] split_sentences = [] if len(time_index) < 1: return [sentences] elif len(time_index) == 1: start = time_index[0] return [sentences[start:]] else: cur_index = 1 time_index.append(len(sentences)) while cur_index < len(time_index): candidate_sentence = sentences[time_index[cur_index-1]:time_index[cur_index]].strip() # 判断是否合并时间点为时间段 if len(candidate_sentence)<=10 and "-" in candidate_sentence: # 溢出判断 if cur_index + 1 >= len(time_index): break sentence = sentences[time_index[cur_index-1]:time_index[cur_index+1]] cur_index += 2 sentence = sentence.strip(",").strip("个人简历").strip() split_sentences.append(sentence) else: candidate_sentence = candidate_sentence.strip("个人简历").strip(",").strip() split_sentences.append(candidate_sentence) cur_index += 1 return split_sentences def gen_text(self, data): resume = "" if data["resume"] or data["raw_edu_experience"] or data["raw_work_experience"]: if "根据数据搜索表明" not in data["resume"]: resume += data["resume"] + "。" if data["raw_work_experience"]: resume += data["raw_work_experience"] + "。" if data["raw_edu_experience"]: resume += data["raw_edu_experience"] + "。" return resume def extract(self, resume): extract_with_time = [] extract_res = [] resume_list = [] # 简介描述为空或纯英文,暂不做抽取 if (not resume) or (not re.findall("[\u4e00-\u9fa5]",resume)): return [] # 中文个人经历抽取 # 分句 syn_split_list = re.split("[;;。]", resume) for s in syn_split_list: s_split = self.split_sentence(s) s_split = list(filter(lambda x:len(x)>0, s_split)) if s_split: resume_list.extend(s_split) resume_list = list(filter(lambda x:len(x)>0, resume_list)) # 经历抽取排序 for sentence in resume_list: year_list = re.findall("\d{4}", sentence) # 过滤掉出生年月的时间 if len(year_list)==1 and ("出生" in sentence or "生于" in sentence or "年生" in sentence or "月生" in sentence): continue if year_list: for pos in self.experience_positions: if pos in sentence and [year_list[0],sentence] not in extract_with_time: extract_with_time.append([year_list[0], sentence]) break if extract_with_time: _sorted = sorted(extract_with_time, key=lambda x:x[0]) extract_res = [i[1] for i in _sorted] return extract_res
Shell
UTF-8
1,163
3.078125
3
[]
no_license
### VI mode ### bindkey -v #bindkey '^R' history-incremental-search-backward #bindkey '^P' up-history #bindkey '^N' down-history #bindkey '^w' backward-kill-word #bindkey '^a' beginning-of-line #bindkey '^e' end-of-line bindkey "^Q" push-line ### Zsh options ### setopt promptsubst setopt append_history setopt share_history setopt hist_expire_dups_first HISTSIZE=100000 SAVEHIST=80000 ### Aliases ### alias h="history" alias s="search" alias vi="vim" alias calc="noglob awk_calc" ### Functions ### search() { open "http://google.com/search?q=`echo $@ | sed 's/ /+/g'`" ; } wiki() { open "http://en.wikipedia.org/wiki/`echo $@ | sed 's/ /_/g'`" ; } function comma() { if [ -z $1 ]; then local replace="," else local replace="$1" fi xargs | tr " " "$replace" } function motd() { fortune -s | sed $'s/\t/ /g' | awk 'BEGIN{RS=""; FS="\n"} {max=0; for (i=1;i<=NF;i++) { if (length($i) > max) { max = length($i); } } h=""; for(i=0;i<max+4;i++) { h=sprintf("%s-", h); } printf("%s\n", h); for(i=1;i<=NF;i++) { printf("| %-*s |\n", max, $i); } printf("%s\n", h); }' } function awk_calc() { awk "BEGIN {print $*}" ; }
Ruby
UTF-8
1,377
3.359375
3
[ "MIT" ]
permissive
# SYNOPSIS # Provides a set of position sizing methods featuring # - Kelly criteria # - Optimal F # - Secure F # - Fractional F # - Percent (from available margin). # # First release: Cássio Jandir Pagnoncelli (cassiopagnoncelli@gmail.com) # Licence: MIT. # class PositionSizing attr_accessor :account # Reference to Account. # Point to Account object so that calculations can be performed. def initialize(account_ref) account = account_ref end # Calculates the ammount of equity to allocate into `instrument'. # `value' ranges from 0 up to 1, where # 0 stands for the minimum allocation possible (minimum lot size) # 1 stands for the maximum allocation possible not immediately meeting # margin call. def percent(instrument, value) end # Calculates the Kelly's criteria. def kelly(instrument) end # Calculates the Optimal F, Secure F, and Fractional F criteria. # # Optimal F is a slightly Kelly's criteria variation considering profit # factor instead of profit and loss. # # Secure F takes the second derivative instead of first providing a point # where growth acceleration is null. # # Fractional F combines Optimal F (`percent'==1) and Secure F (`percent'==0) # where `percent' tweaks their mixture. # def optimal_f(instrument) end def secure_f(instrument) end def fractional_f(instrument, value) end end
Python
UTF-8
745
2.625
3
[]
no_license
from benchopt import BaseObjective import numpy as np class Objective(BaseObjective): name = "Total Variation" parameters = { 'reg': [.1], 'lmbd': [1., 0.01] } def __init__(self, reg=.1, lmbd=.1): self.lmbd = lmbd self.reg = reg def set_data(self, X, y): self.X, self.y = X, y self.lmbd = self.reg * self._get_lambda_max() def compute(self, beta): diff = self.y - self.X.dot(beta) diff_beta = np.diff(beta) l1 = sum(abs(diff_beta)) return .5 * diff.dot(diff) + self.lmbd * l1 def _get_lambda_max(self): return abs(self.X.T.dot(self.y)).max() def to_dict(self): return dict(X=self.X, y=self.y, lmbd=self.lmbd)
Markdown
UTF-8
2,111
3.203125
3
[]
no_license
Cinch is a Javascript source transformation tool. It allows you to write asynchronous, non-blocking code in a clean, synchronous form. Cinch modules use the extension `.js_` and contain regular Javascript syntax, with one bonus. The Cinch engine will transform any function whose name ends in an underscore into asynchronous form. The new function will have the same name (minus the underscore) and an extra callback parameter. Inside a transformed function, you can call any asynchronous function (whether converted or hand-coded) as if it was synchronous by appending an underscore to its name. You can mix such function calls with language constructs like `while`, `for`, `try`/`catch`, `throw`, and `return`, and they'll work as you hope. Cinch is 100% compatible with regular Javascript code. Transformed functions and regular functions can coexist in the same module and call each other freely. Example ------- var fs = require('fs'); fileLength(__filename, function(err, length) { if (err) throw err; console.log('I am ' + length + ' bytes long'); }); function fileLength_(path) { return fs.readFile_(path).length; }; Since `fileLength_()` ends with an underscore, Cinch will convert it into the following: function fileLength(path, callback) { fs.readFile(path, function(err, result) { if (err) { return callback(err); }; return callback(null, result.length); }); }; Running Cinch code ------------------ npm install cinch node-cinch myfile.js_ As `.js_` modules are loaded, Cinch will save pure-Javascript versions with the `.js` extension. These are regular modules and can be used without Cinch present. API --- `cinch.registerExtension()` Hooks into `require()` functionality to allow `.js_` modules to be loaded. `cinch.transform(source)` Transforms a single script and returns the pure-JS version. History ------- Cinch started as a fork of the excellent [Streamline.js] [1] and turned into a full rewrite. [1]: https://github.com/Sage/streamlinejs
Python
UTF-8
1,365
3.21875
3
[]
no_license
import hub rollcorrection = 5 # Compensate for 0 position not being O pitchcorrection = 5 # Compensate for 0 position not being O pitchmotor= hub.port.E rollmotor= hub.port.F # Normalizes PWM values. For positive values # - clips values close to 0 to 0 # - clips small values to a minimum PWM value that makes the motor move # - clips large values to a maximum value allowed for PWM def normalize(val) : if val < -3 : val -= 25 if val<-100 : val=-100 elif val > +3 : val += 25 if val>+100 : val=+100 else : val = 0 return int(val) def rolllevel(): roll1= hub.motion.accelerometer()[1]/10 # approx ship roll in degrees (port down is positive) roll2= rollmotor.motor.get()[2] - rollcorrection # approx platform roll in degrees duty = normalize( (roll1 - roll2) * 0.6 ) rollmotor.pwm(duty) def pitchlevel(): pitch1= hub.motion.accelerometer()[0]/10 # approx ship pitch in degrees (back up is positive) pitch2= pitchcorrection - pitchmotor.motor.get()[2] # approx platform pitch in degrees duty = normalize( (pitch2 - pitch1) * 0.8 ) pitchmotor.pwm(duty) def main(): hub.sound.beep(440, 200) print("SeaTransferPlatform") hub.sound.beep(880, 200) while True: roll = rolllevel() pitch = pitchlevel() main()
Java
UTF-8
677
1.9375
2
[]
no_license
package com.ixonos.skillnet.logic.dao.impl; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Repository; import com.ixonos.skillnet.logic.bean.GroupMember; import com.ixonos.skillnet.logic.dao.GroupMemberDAO; /** * * @author magurja */ @Repository("groupMemberDAO") public class GroupMemberDAOImpl extends GenericDAOImpl<GroupMember> implements GroupMemberDAO { @Autowired public GroupMemberDAOImpl(final @Qualifier("sessionFactory") SessionFactory sessionFactory) { setSessionFactory(sessionFactory); } }
Markdown
UTF-8
741
2.5625
3
[]
no_license
# EasyFinance This is Web server of Easy Finance , an individual finacial management application. Easy finance is my graduation project, it includes a Web application and an iOS Application. - Platform: Web & iOS - Programming Languages: Java, JavaScript, Objective-C - Supported Languagues: English. - Features - Manage account book easily. - Create a report with graph. - Record any you want. - Use your money wisely. - URL: http://easy.fczm.pw ![EasyFinance](https://raw.githubusercontent.com/lm2343635/EasyFinance/master/screenshot/easyfinance.png) You can see the demo here: http://easy.fczm.pw. Demo account is tom@126.com with password 123. Source code of iOS application is here: https://github.com/lm2343635/AccountManagement
C++
UTF-8
797
3.265625
3
[]
no_license
#pragma once using namespace std; #include <string> #include <iostream> class Student { public: Student(int, string, float); void display(); protected: int num; string name; float score; }; Student::Student(int n,string nam,float s) { num = n; name = nam; score = s; } void Student::display() { cout << "student num:" << num << "\nname:" << name << "\nscore:" << score << "\n\n"; } class Graduate : public Student { public: Graduate(int ,string ,float ,float); private: float pay; void display(); }; void Graduate::display() { cout << "Graduate num:" << num << "\nname:" << name << "\nscore:" << score << "\npay=" << pay << endl; } Graduate::Graduate(int n,string nam,float s,float p):Student(n,nam,s),pay(p) { } class Student { public: Student(); ~Student(); };
JavaScript
UTF-8
1,172
2.765625
3
[]
no_license
require('../spec.helper') describe("BMICalculator metric", function() { let calculator; let person; beforeEach(function() { person = new Person({weight: 90, height: 186}); calculator = new BMICalculator(); }); it ("calculates BMI for a person using metric method", function() { calculator.metric_bmi(person); expect(person.bmiValue).to.equal(26.01); }); it ("sets BMI message for a person using metric method", () => { calculator.metric_bmi(person); expect(person.bmiMessage).to.equal('Overweight'); }); }); describe("BMICalculator imperial", function() { let calculator; let person; beforeEach(function() { person = new Person({weight: 200, height: 72}); calculator = new BMICalculator(); }); it ("calculates BMI for a person using metric method", function() { calculator.imperial_bmi(person); expect(person.bmiValue).to.equal(27.12); }); it ("sets BMI message for a person using metric method", () => { calculator.imperial_bmi(person); expect(person.bmiMessage).to.equal('Overweight'); }); });
Java
UTF-8
951
2.546875
3
[]
no_license
package com.altunsoy.customer; import lombok.Setter; @Setter public class CustomerService { private CustomerRepository customerRepository; private NotifiCationService notifiCationService; public CustomerRepository getMusteriRepository() { return customerRepository; } public void deletecustomer(Integer musteriId) { customerRepository.delete(musteriId); } public void saveCustomer(Customer customer) { customerRepository.save(customer); notifiCationService.sendMailforNewRegistry(customer); } public Customer handleNewCustomer(String customerName, String email) { Customer customer = new Customer(customerName,email); giveWelcomeGifts(customer); customerRepository.save(customer); notifiCationService.sendWelcomeNotification(customerName,email); return customer; } private void giveWelcomeGifts(Customer customer) { customer.addGift(new Gift("welcome1")); customer.addGift(new Gift("welcome2")); } }
JavaScript
UTF-8
1,215
2.609375
3
[]
no_license
var matches = "msMatchesSelector" in Element.prototype ? "msMatchesSelector" : "webkitMatchesSelector" in Element.prototype ? "webkitMatchesSelector" : "matches"; var util = module.exports = { wait(duration, callback) { setTimeout(callback, duration || 400); }, addClass(element, name) { element.className += " " + name; }, removeClass(element, name) { var re = new RegExp(name, "g"); element.className = element.className.replace(re, ""); }, qsa(s, element) { return Array.prototype.slice.call((element || document).querySelectorAll(s)); }, closest(element, f) { if (typeof f == "function") { while (element && !f(element) && element !== document.documentElement) { element = element.parentElement; } } else { while (element && !element[matches](f) && element !== document.documentElement) { element = element.parentElement; } } if (element == document.documentElement) return null; return element; }, delegate(element, event, selector, fn) { element.addEventListener(event, function(e) { var closest = util.closest(e.target, selector); if (closest) { fn(e); } }); } };
Java
UTF-8
1,307
2.40625
2
[ "Apache-2.0" ]
permissive
/* Copyright 2019 Fausto Spoto (fausto.spoto@univr.it) Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package it.univr.bcel; import org.apache.bcel.generic.ObjectType; /** * An uninitialized object type created by a {@code new} instruction * at a given offset inside the code, or passed as receiver to a constructor. */ public interface UninitializedObjectType { /** * Returns the type of the variable, as it will be after initialization. */ ObjectType onceInitialized(); /** * Yields the offset of the {@code new} instruction that created the object, * inside the code of the same method or constructor * whose type are being inferred. This may be -1, meaning that this * is the uninitialized object passed as receiver to a constructor. * * @return the offset */ int getOffset(); }
Python
UTF-8
1,875
3.078125
3
[]
no_license
# Actualizar registro o fila existente.OK import fdb import numpy as np import pandas as pd from tkinter import * def actualizar(id,nom): con = fdb.connect( dsn='localhost:C:/data/FILM.FDB', user='SYSDBA', password='udelas') cursor = con.cursor() #OJO: todo el query debe estar contenido entre doble comillas, y las variables string entre comillas simples. try: query="UPDATE CATEGORY SET NAME = '"+ nom +"' WHERE CATEGORY_ID ="+ str(id) print(query) cursor.execute(query) con.commit() except: con.rollback() print("Error") cursor.close() con.close() def proc_actualizar(root,id): dialogo = Toplevel(root) dialogo.title("Actualizar datos.") dialogo.geometry("1200x750+0+00") dialogo.resizable(FALSE,FALSE) Button(dialogo,text="Cerrar",bg="green", command=dialogo.destroy,anchor="s").pack(side=BOTTOM, padx=20, pady=20) dialogo.grab_set() # esta instrucción igual que la siguiente, obligan que primero se cierre esta ventana para que se pueda cerrar la anterior. dialogo.transient(master=root) lblCatId=Label(dialogo,text="CatId:",font=("Agency FB",14)).place(x=10,y=50) entradaCatId=StringVar(dialogo) entradaCatId.set(id) txtCatId= Entry(dialogo,textvariable=entradaCatId,font=("Agency FB",14),width=10,state='readonly').place(x=80, y =60) lblName=Label(dialogo,text="Name:",font=("Agency FB",14)).place(x=10,y=90) entradaName=StringVar(dialogo) txtName= Entry(dialogo,textvariable=entradaName,font=("Agency FB",14),width=10).place(x=80, y =100) btActualizar=Button(dialogo,text="Actualizar Registro",relief="solid",fg="blue",height=2,width=20,font=('Helvetica', '8'),bg="yellow",command=lambda:actualizar(entradaCatId.get(),entradaName.get())) btActualizar.place (x=10, y=150)
Markdown
UTF-8
13,961
2.96875
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
# Options Strategy Structure !!! Links - **[List of Strategies](index.md)** - **[Strategy Design (workflow of a strategy)](../pyalgotrad/structure.md)** ## 1. Initial steps i. Create a new strategy file with a unique file name. eg: strategy_```<developer_initials>```_options_ema_crossover.py !!!Note * Add the initials of your name after the word strategy in the strategy file name so that it becomes easier to identify the developer who developed the strategy and also helps with a unique strategy name. * Make sure that the file name is in lowercase and that each word is separated with an underscore '_' as shown above. ii. Create a class with the same name as the file name, and make sure the first letter of each word is in uppercase and the initials should be in uppercase as well. eg: For the above strategy name the class name would be: Strategy```<developer_initials>```OptionsEMACrossover(StrategyOptionsBaseV2) !!! Note * If the class name includes indicator names like EMA, SMA, and VWAP the name should be in uppercase in the class name but not in the file name. * Every strategy class is a child class of the StrategyBase. --- ## 2. Init method This method gets called only once when the strategy is started. i. Strategy info: In the __init__ method add the ```super().__init__(*args, **kwargs)``` and add the below lines. ``` VERSION = strategy_version CLIENT = client_name STRATEGY_TYPE = 'OPTIONS' self.logger.info(f'\n{"#" * 40}\nSTRATEGY VERSION: {VERSION}\n{"#" * 40}') self.logger.debug(f'\n{"#" * 60}\nSTRATEGY TYPE: {STRATEGY_TYPE} | CLIENT: {CLIENT}\n{"#" * 60}') ``` * VERSION: This is the strategy version, the initial version is 3.3.1 as and when there are fixes/updates/changes in the strategy the version should be updated to 3.3.2, and so on. * CLIENT: Name of the client. * STRATEGY_TYPE: Whether the strategy is a FUTURES strategy or an OPTIONS strategy. We print this information in the next line, so whenever we run the strategy this information is displayed in the logs. We save the parameter string in the parameter_string variable and check if the length of the parameter_string matches the number of parameters in the strategy's YAML file. eg: ``` parameter_string = '\n(1) FRESH_ORDER_CANDLE \n(1) START_TIME_HOURS \n(1) START_TIME_MINUTES \n(1) END_TIME_HOURS \n(1) END_TIME_MINUTES \n(1) \n(1) STRIKES_DIRECTION_CE' '\n(1) STRIKES_DIRECTION_PE \n(1) NO_OF_STRIKES_AWAY_CE \n(1) NO_OF_STRIKES_AWAY_PE \n(1) EMA_PERIOD_ONE \n(1) EMA_PERIOD_TWO' '\n(1) TARGET_PERCENTAGE \n(1) STOPLOSS_PERCENTAGE \n(1) STOPLOSS_RANGE \n(1) STOPLOSS_ORDER_COUNT_ALLOWED' check_argument(self.strategy_parameters, 'extern_function', lambda x: len(x) >= 15, err_message=f'Need 15 parameters for this strategy: {parameter_string}') ``` * parameter_string: This string contains all the strategy parameters as shown above. * We check if the number of parameters matches those in the strategy YAML file. !!! Note * The parameter names and the number of parameters may change for different strategies. ii. Parameter creation: Next, we assign the parameter values to the class variables of the same name as the parameters but in the lowercase format as shown below: eg: ``` self.fresh_order_candle = self.strategy_parameters['FRESH_ORDER_CANDLE'] self.start_time_hours = self.strategy_parameters['START_TIME_HOURS'] self.start_time_minutes = self.strategy_parameters['START_TIME_MINUTES'] self.end_time_hours = self.strategy_parameters['END_TIME_HOURS'] self.end_time_minutes = self.strategy_parameters['END_TIME_MINUTES'] self.no_of_strikes_away_ce = self.strategy_parameters['NO_OF_STRIKES_AWAY_CE'] self.no_of_strikes_away_p = self.strategy_parameters['NO_OF_STRIKES_AWAY_PE'] self._strike_direction_ce = self.strategy_parameters['STRIKES_DIRECTION_CE'] self._strike_direction_pe = self.strategy_parameters['STRIKES_DIRECTION_PE'] self.ema_period_one = self.strategy_parameters['EMA_PERIOD_ONE'] self.ema_period_two = self.strategy_parameters['EMA_PERIOD_TWO'] self.target_percentage = self.strategy_parameters['TARGET_PERCENTAGE'] self.stoploss_percentage = self.strategy_parameters['STOPLOSS_PERCENTAGE'] self.stoploss_range = self.strategy_parameters['STOPLOSS_RANGE'] self.stoploss_order_count_allowed = self.strategy_parameters['STOPLOSS_ORDER_COUNT_ALLOWED'] ``` iii. Parameter validation We validate each parameter's value according to the strategy requirement. The following methods can be used to validate the parameter values: * check_argument: Checks a single parameter passed in it. Syntax: check_argument(value to be checked, 'extern_function', validating condition or method, error_message) eg: check_argument(self.strategy_parameters, 'extern_function', lambda x: len(x) >= 11, err_message=f'Need 11 parameters for this strategy: {parameter_string}') * check_argument_bulk: Checks multiple parameters passed in a list Syntax: check_argument_bulk(list of values to be checked, 'extern_function', validating condition or method, error_message) eg: is_nonnegative_int_arg_list = [self.start_time_hours, self.start_time_minutes, self.end_time_hours, self.end_time_minutes] check_argument_bulk(is_nonnegative_int_arg_list, 'extern_function', is_nonnegative_int, 'Value should be >=0') * is_nonnegative_int: Checks whether the value is greater than or equal to zero. * is_positive_int_or_float: Checks whether the value is greater than zero and is an integer or a float value. * is_positive_int: Checks whether the value is greater than zero and is an integer value. * is_nonnegative_int_or_float: Checks whether the value is greater than or equal to zero and is an integer or a float value. No of the strikes values are validated as follows: ``` no_of_strikes_list = [(self.no_of_strikes_away_ce, 'NO_OF_STRIKES_AWAY_CE'), (self.no_of_strikes_away_pe, 'NO_OF_STRIKES_AWAY_PE')] for no_of_strikes, text in no_of_strikes_list: check_argument(no_of_strikes, 'extern_function', lambda x: 0 <= x <= 50 and isinstance(x, int), err_message=f'{text} should be an integer with possible values between 0 to 50') ``` Strike direction values are validated as follows: ``` strikes_direction_list = [(self._strike_direction_ce, 'STRIKE_DIRECTION_CE'), (self._strike_direction_pe, 'STRIKE_DIRECTION_PE')] for strike_direction, text in strikes_direction_list: check_argument(strike_direction, 'extern_function', lambda x: x in [0, 1, 2] and isinstance(x, int), err_message=f'{text} should be an integer with possible values - 0: ITM or 1: ATM or 2: OTM') ``` Once all the parameters are validated we calculate the actual value of the strike direction from the strike direction values given in the strategy YAML file. We define the below dictionary for ```strike_direction```. ``` strike_direction_map = {0: OptionsStrikeDirection.ITM.value, 1: OptionsStrikeDirection.ATM.value, 2: OptionsStrikeDirection.OTM.value} ``` Then we create new variables for strike direction that save the value as ATM, ITM, and OTM based on the YAML parameter value. ``` self.strike_direction_ce = strike_direction_map[self._strike_direction_ce] self.strike_direction_pe = strike_direction_map[self._strike_direction_pe] ``` iv. Start time and End time creation: Add the below code to calculate the strategy start time and end time, from the start time and end time parameters in the strategy YAML file. ``` try: self.candle_start_time = time(hour=self.start_time_hours, minute=self.start_time_minutes) except ValueError: self.logger.fatal('Error converting start hours and minutes... EXITING') raise SystemExit try: self.candle_end_time = time(hour=self.end_time_hours, minute=self.end_time_minutes) except ValueError: self.logger.fatal('Error converting end time hours and minutes... EXITING') raise SystemExit ``` v. Strategy variables: We create our own strategy variables other than the strategy parameter variables which will be used throughout the strategy. eg: self.main_order = None # We save the entry order in this variable self.stoploss_order = None # We save the corresponding stoploss exit order of the entry order in this variable We initialize the variables with a None value. !!! Note There could be more strategy variables required as per the strategy requirement. --- ## 3. Initialize method Unlike the ```init method```, this method gets called every day at the beginning of the day once the strategy is started. Here the strategy variables that were initialized as None are again defined as dictionaries/lists except for the ```self.order_tag_manager```. Create a reference for ```OrderTagManager``` as shown below: ```self.order_tag_manager = OrderTagManager``` --- ## 4. OrderTagManager The ```self.order_tag_manager``` is used to store/remove the entry/exit orders. The ```self.order_tag_manager``` has the following methods: **i. add_order**: * Stores the order object for the given tags. eg: ```self.order_tag_manager.add_order(_order, tags=[base_inst_str, entry_key])``` Here the ```_order``` is the order object stored inside the ```OrderTagManager``` for the tags ```base_inst_str``` and ```entry_key```. **ii. get_orders**: * Retrieve the order(s) for the given tags. eg: ```self.order_tag_manager.get_orders(tags=[base_inst_str, BrokerExistingOrderPositionConstants.ENTER, entry_key], ignore_errors=True)``` Here the order object retrieved from the ```OrderTagManager``` for the tags ```base_inst_str, BrokerExistingOrderPositionConstants.ENTER``` and ```entry_key``` **iii. remove_tags**: * Removes the tags stored in the ```OrderTagManager``` along with the orders related stored in that tag eg: ```self.order_tag_manager.remove_tags(tags=entry_key)``` Here the ```entry_key``` tag is removed from the ```OrderTagManager```. !!! Note When the tag is removed the order objects stored in that tag are also removed but the same order objects would still be present in order tags. **iv. remove_order**: * Remove the order(s) from the ```OrderTagManager``` for the given tag(s). eg: ```self.order_tag_manager.remove_order(main_order)``` Here the ```main_order``` order object is removed from the ```OrderTagManager```. !!! Note The order object will be removed from all the tags ta **v. get_internals**: * Returns the values i.e. both the entry and exit orders stored inside the tags list. --- ## 5. Child instruments calculation i. Fetch the LTP of the base instrument (instrument in the YAML). ```ltp = self.broker.get_ltp(self.underlying_instrument)``` ii. Get the ATM ITM and OTM lists of the child instrument based on the LTP: ```self.options_instruments_set_up_local(self.underlying_instrument, tradingsymbol_suffix, ltp)``` iii. Select a child instrument from the lists of ATM, ITM, and OTM based on the strike direction and no of strikes given for the child instrument. ```child_instrument = self.get_child_instrument_details(self.underlying_instrument, tradingsymbol_suffix, strike_direction, no_of_strikes)``` --- ## 6. Entry Methods **i. strategy_select_instruments_for_entry:** * In this method we process each instrument in the instruments bucket, if there is some entry condition to be checked then we create a ```get_entry_decision``` method that calculates the entry condition like a crossover or compares the latest value of the OHLC data or indicator data. * When the order has to be placed we add the ```instrument``` to ```selectd_instruments_bucket``` and additional data related to the instrument that will be required while placing to the ```sideband_info```. This information is passed to the ```strategy_enter_position``` method **ii. strategy_enter_position:** * Here is where we actually place the entry order for which we calculate the quantity for the order to be placed. If the order is placed successfully we save the order in a class variable such that we can access the order object via the variable in the exit methods. --- ## 7. Exit Methods **i. strategy_select_instruments_for_exit:** * This method is called before the entry methods because in the case of delivery strategy we want to resume and exit previous day orders before we can place new entry orders. * Here we place stoploss exit orders, target exit orders, and check for exit conditions for the open entry orders. --- ## 8. Other common methods There are other methods that are used in the strategy: **i. check_and_place_stoploss_order:** This method is called in the ```strategy_select_instruments_for_exit``` when our entry order is open, and we want to place a stoploss exit order for the same. **ii. set_all_none:** This method is called in the ```strategy_exit_position``` when our entry order has exited, and we want to remove the order object from the ```self.main_order``` variable. **iii. options_instruments_set_up_local** This method is called in the ```strategy_select_instruments_for_entry``` to fetch the ATM, ITM, and OTM lists of the child instruments based on the LTP of the base instrument. **iv. get_child_instrument_details** This method is called in the ```strategy_select_instruments_for_entry``` to fetch a single child instrument based on the no of strikes and strike direction. --- ## 9. Cleanup i. Add comments and docstrings wherever possible to improve code readability. ii. Once the strategy is completed perform O-I-L on the strategy code and remove unwanted imports, variables, and methods before delivering the code.** --- To know more about a strategy from our given template, simply **check the first line of comment** in the code of that specific strategy. You can even access them [here](https://algobulls.github.io/pyalgotrading/) in `Strategies` Section
SQL
UTF-8
5,556
4.3125
4
[]
no_license
-- @@ 생성시 제약조건 설정 -- emp02 테이블 생성 DROP TABLE IF EXISTS emp02; CREATE TABLE emp02 ( empno decimal(4,0) , eanme nvarchar(15) , sal decimal(7,2) , comm decimal(7,2) , job nvarchar(4) , deptno decimal(2,0) ); -- emp03 테이블 생성 -- empno 에 not null 조건 설정. -- ename 에 not null 조건 설정. DROP TABLE IF EXISTS emp03; CREATE TABLE emp03 ( empno decimal(4,0) NOT NULL , eanme nvarchar(15) NOT NULL , sal decimal(7,2) , comm decimal(7,2) , job nvarchar(4) , deptno decimal(2,0) ); -- emp03 테이블 생성 -- empno 에 not null 조건 설정. -- ename 에 not null 조건 설정. -- sal 에 check 조건 설정 500~ 5000 사이만 허용되게 만든다. -- comm 에 default 조건 설정 DROP TABLE IF EXISTS emp04; CREATE TABLE emp04 ( empno decimal(4,0) NOT NULL , ename nvarchar(15) NOT NULL , sal decimal(7,2) -- myslq 에서는 안됌 check (50 <= sal AND sal <= 5000) , comm decimal(7,2) default 100 , job nvarchar(4) , deptno decimal(2,0) ); -- 데이터 insert 테스트 -- 모든 값을 nulll 채워서 insert 해라 -->>> 불가능(not null 조건 떄문임) INSERT INTO emp03 VALUES (null, null, null, null, null, null); -- empno 에 10, ename에 abcd를 insert 해라, INSERT INTO emp03(ename) VALUES (10); INSERT INTO emp04(empno, ename) VALUES (10, 'abcd'); -- @@@@@@@@@@@@@ -- QQQ1 emp02 테이블 수정 -- @@@@@@@@@@@@@ -- empno 에 not null 조건 설정. ALTER TABLE emp02 MODIFY empno decimal(4,0) NOT NULL ; -- ename 에 not null 조건 설정. ALTER TABLE emp02 MODIFY ename varchar(15) NOT NULL ; -- sal 에 check 조건 설정 ALTER TABLE emp02 MODIFY sal decimal(7,2) Check (50 <= sal AND sal <= 5000) ; -- comm 에 default 조건 설정 ALTER TABLE emp02 MODIFY comm decimal(7,2) default 123; -- empno 에 primary key 조건 설정. ALTER TABLE emp02 MODIFY comm decimal(7,2) default 123; -- empno 와 ename 에 primary key 조건 설정. -- @@@@@@@@@@@@@ -- 문제. emp05 테이블 생성과 제약 조건 변경. -- emp02 테이블을 복제하여 emp05 테이블 만드시오. DROP TABLE IF EXISTS emp05; CREATE TABLE emp05 SELECT * FROm emp02 -- emp05 테이블 컬럼에 alter를 이용하여 제약 조건을 추가하시오. -- empno 에 not null 조건 설정. -- ename 에 not null 조건 설정. -- comm 에 default 조건 설정. default 값을 10을 사용. ALTER TABLE emp05 MODIFY empno decimal(4,0) NOT NULL; ALTER TABLE emp05 MODIFY ename varchar(15) NOT NULL ; ALTER TABLE emp05 MODIFY comm decimal(7,2) default 10; -- @@@@@@@@@@@@@ -- primary key 설정 DROP TABLE IF EXISTS emp06; CREATE TABLE emp06 ( empno decimal(4,0) NOT NULL PRIMARY KEY , ename nvarchar(15) NOT NULL , sal decimal(7,2) , comm decimal(7,2) default 100 , job nvarchar(4) , deptno decimal(2,0) ); -- primary key 설정 ( 2개 설정 3(개 이상도 가능하다)) DROP TABLE IF EXISTS emp07; CREATE TABLE emp07 ( empno decimal(4,0) NOT NULL , ename nvarchar(15) NOT NULL , sal decimal(7,2) , comm decimal(7,2) default 100 , job nvarchar(4) , deptno decimal(2,0) , PRIMARY KEY( empno, ename) ); DROP TABLE IF EXISTS emp08; CREATE TABLE emp08 ( empno decimal(4,0) NOT NULL , ename nvarchar(15) NOT NULL , sal decimal(7,2) , comm decimal(7,2) default 100 , job nvarchar(4) , deptno decimal(2,0) , UNIQUE KEY( empno, ename) ); -- @@@@@@@@@@@@@ -- emp02 테이블 수정 -- @@@@@@@@@@@@@ -- empno 에 not null 조건 설정. -- ename 에 not null 조건 설정. -- sal 에 check 조건 설정 -- comm 에 default 조건 설정 -- empno 와 ename 에 primary key 조건 설정. -- empno 와 deptno 에 unique key 조건 설정 --@@@@@@@@@@@@@ -- emp02 테이블 수정 --@@@@@@@@@@@@@ -- empno 에 not null 조건 설정. -- ename 에 not null 조건 설정. -- sal 에 check 조건 설정 -- comm 에 default 조건 설정 -- empno 와 ename 에 primary key 조건 설정. -- empno 와 deptno 에 unique 조건 설정 -- deptno 에 foreign key 조건 설정. --@@@@@@@@@@@@@@@@ -- table created 된 후에 제약 조건 추가하기 --@@@@@@@@@@@@@@@@ -- empno에 primary key 추가 -- deptno에 foreign key 추가 -- job에 unique 추가 --@@@@@@@@@@@@@@@@ -- table created 된 후에 제약 조건 수정하기 -- 컬럼 타입 과 제약 조건 변경 --@@@@@@@@@@@@@@@@ -- 데이터 타입 바꾸기 -- ename을 varchar(20) 에서 char(100) 수정하기 -- 제약 조건 변경 -- emp02.ename 을 null 조건으로 바꾸기 -- 제약 조건 변경 -- emp02.ename 을 not null 조건으로 바꾸기 -- @@@@@@@@@@@@@@@@ -- table created 된 후에 제약 조건 삭제하기 -- @@@@@@@@@@@@@@@@ -- emp02에서 primary key 조건 삭제하기 -- emp02에서 foreign key 조건 삭제하기 -- emp02에서 unique 조건 삭제하기 -- emp02에서 check 조건 삭제하기 --###################### -- 미션 10. ERD를 이용해서 DB를 구축하시오 --###################### -- @@ 생성시 제약조건 설정 -- emp02 테이블 수정 -- empno 에 not null 조건 설정. -- ename 에 not null 조건 설정. -- EMP02 에 데이터 삽입. -- @@@@@@@@@@@@@ -- emp02 테이블 수정 -- @@@@@@@@@@@@@ -- empno 에 not null 조건 설정. -- ename 에 not null 조건 설정. -- sal 에 check 조건 설정 -- comm 에 default 조건 설정 -- @@@@@@@@@@@@@ -- EMP02 에 데이터 삽입. -- @@@@@@@@@@@@@ -- comm 에 100 입력됨. -- sal 위배 -- sal 만족
Shell
UTF-8
1,090
3.546875
4
[]
no_license
# make docker audit information date +"%Y-%m-%d_%H-%M-%S" > $DOCKER_DIR/01_BUILD_DATE.var echo $BASE_IMAGE > $DOCKER_DIR/02_BASE_IMAGE.var echo $IMAGE_NAME > $DOCKER_DIR/03_IMAGE_NAME.var echo $IMAGE_VERSION > $DOCKER_DIR/04_IMAGE_VERSION.var echo $GIT_COMMIT > $DOCKER_DIR/05_GIT_COMMIT.var #add docker info to a history file echo -e '\n\n' >> $DOCKER_HISTORY cat $DOCKER_DIR/*.var >> $DOCKER_HISTORY #add docker info for this image to a file for R echo "" > $DOCKER_INFO echo "################################" >> $DOCKER_INFO echo "# DOCKER BUILD INFORMATION" >> $DOCKER_INFO echo -e "################################\n" >> $DOCKER_INFO echo "This is docker image: ${IMAGE_NAME}:${IMAGE_VERSION}" >> $DOCKER_INFO echo "Built from git commit: ${GIT_COMMIT}" >> $DOCKER_INFO echo "See https://github.com/chapmandu2/datasci_docker/tree/${GIT_COMMIT} for Dockerfile code" >> $DOCKER_INFO echo "See $DOCKER_HISTORY for provenance of this environment." >> $DOCKER_INFO echo "See $DOCKER_DIR for more information" >> $DOCKER_INFO echo -e "\n################################" >> $DOCKER_INFO
Java
UTF-8
294
1.890625
2
[ "Apache-2.0" ]
permissive
package ai.labs.lifecycle; import ai.labs.memory.IConversationMemory; /** * @author ginccc */ public interface ILifecycleManager { void executeLifecycle(final IConversationMemory conversationMemory) throws LifecycleException; void addLifecycleTask(ILifecycleTask lifecycleTask); }
Python
UTF-8
898
3.078125
3
[]
no_license
import os import re import random import time def insertionSort(dataArray, numToAdd): dataArray.append(numToAdd) counter = (len(dataArray)-1) if counter <= 0: return dataArray else: while dataArray[counter] < dataArray[counter-1] and counter > 0: tempValStore = dataArray[counter] dataArray[counter] = dataArray[counter-1] dataArray[counter-1] = tempValStore counter = counter-1 return dataArray size = 10 result = 0.0 while result < 30: sortedList = [] start = time.time() for i in range (1,size): insertionSort(sortedList,random.randint(1,10000)) end = time.time() result = end - start resultFile = open('./insertTime.txt',"a+") resultFile.write("%s " % size) resultFile.write("%s " % result) resultFile.write("\n") resultFile.close() size = size + 1000
Shell
UTF-8
825
3.09375
3
[]
no_license
#!/bin/sh gcc nwrites_to_crash.c -o nwrites_to_crash #set_crash sets n_writes_to_crash ./ nwrites_to_crash 4 cd test #For each of the following commands, nwrites_to_crash decrements by 1 #But all commands are executed normally echo 'hello' >> hello.txt echo 'hi' > color.txt ln world.txt copy_of_world.txt ln -s hello.txt symlink_to_hello #Anything following this line should silently fail ln world.txt sym.txt rm copy_of_world.txt echo 'red blue green' >> color.txt unlink symlink_to_hello cd .. #Restore the OSPFS system so that we can use the file system normally ./nwrites_to_crash -1 cd test #Now if you try to access things added or removed during the incorrect #sym.txt does not exist ln sym.txt sym2.txt #cd copy_of_world.txt still exists cat copy_of_world.txt #Only contains 'hi' cat color.txt
Java
UTF-8
3,090
2.4375
2
[ "Apache-2.0" ]
permissive
package ru.intertrust.cm.core.business.api.dto.impl; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import ru.intertrust.cm.core.model.FatalException; import static org.junit.Assert.assertEquals; /** * @author vmatsukevich * Date: 9/18/13 * Time: 11:29 AM */ public class RdbmsIdTest { @Rule public ExpectedException expectedException = ExpectedException.none(); @Test public void testSetFromStringRepresentation() throws Exception { String stringRepresentation = "0042000000001023"; RdbmsId rdbmsId = new RdbmsId(); rdbmsId.setFromStringRepresentation(stringRepresentation); assertEquals(42, rdbmsId.getTypeId()); assertEquals(1023, rdbmsId.getId()); } @Test public void testSetFromStringRepresentationNullString() throws Exception { expectedException.expect(NullPointerException.class); RdbmsId rdbmsId = new RdbmsId(); rdbmsId.setFromStringRepresentation(null); } @Test public void testSetFromStringRepresentationInvalidLength() throws Exception { String stringRepresentation = "1234"; expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage("Invalid id string representation '" + stringRepresentation + "'. Must be " + "exactly " + RdbmsId.MAX_ID_LENGTH + " characters long"); RdbmsId rdbmsId = new RdbmsId(); rdbmsId.setFromStringRepresentation(stringRepresentation); } @Test public void testSetFromStringRepresentationWithLetters() throws Exception { String stringRepresentation = "00420000000a1023"; expectedException.expect(IllegalArgumentException.class); expectedException.expectMessage(stringRepresentation + " can't be parsed"); RdbmsId rdbmsId = new RdbmsId(); rdbmsId.setFromStringRepresentation(stringRepresentation); } @Test public void testGenerateStringRepresentation() throws Exception { RdbmsId rdbmsId = new RdbmsId(42, 1023); String stringRepresentation = rdbmsId.generateStringRepresentation(); assertEquals("0042000000001023", stringRepresentation); } @Test public void testGenerateStringRepresentationInvalidTypeIdLength() throws Exception { RdbmsId rdbmsId = new RdbmsId(42222, 1023); expectedException.expect(FatalException.class); expectedException.expectMessage("Domain Object type id '" + 42222 +"' exceeds " + RdbmsId.MAX_DO_TYPE_ID_LENGTH + " digits length."); rdbmsId.generateStringRepresentation(); } @Test public void testGenerateStringRepresentationInvalidIdLength() throws Exception { RdbmsId rdbmsId = new RdbmsId(42, 1023111111111L); expectedException.expect(FatalException.class); expectedException.expectMessage("Domain Object id '" + 1023111111111L +"' exceeds " + RdbmsId.MAX_DO_ID_LENGTH + " digits length."); rdbmsId.generateStringRepresentation(); } }
Python
UTF-8
1,788
2.84375
3
[ "MIT" ]
permissive
import matplotlib.pyplot as plt import torch import numpy as np def valid(data): if data is None: return False if data.x is None: return False if data.x.shape[1] == 0: return False return True def generate_histc(dataset): ini_val = np.float64(0.0) num_pairs = [] pos = [] neg = [] while ini_val<=1.0: kk = ((((ini_val <= dataset.K) & (dataset.K < ini_val+0.01)) if ini_val < 1.0 else (dataset.K==1.0)).nonzero()) total_nums = kk.shape[0] pos_num = np.sum([bool(m.y == n.y) for m,n in zip(dataset.dataset[kk[:,0]], dataset.dataset[kk[:,1]])]) pos.append(np.round(pos_num/total_nums,3)) neg.append(np.round((total_nums - pos_num)/total_nums,3)) num_pairs.append(total_nums) ini_val = np.round(ini_val+ np.float64(0.01),3) num_pairs_percentage = np.array(num_pairs) / (dataset.K.shape[0] * dataset.K.shape[0]) * 100 return num_pairs_percentage,pos,neg def draw_histc(dataset): npp,pos,neg = generate_histc(dataset) X = np.linspace(0,1,101,endpoint=True) plt.figure(figsize=(10.24,4.8)) a1 = plt.subplot(1, 2, 1) a1.plot(X,npp,color="blue",linewidth=2.5,linestyle="-",label="% Number of graph pairs") a1.set_xticks(np.arange(0,1.1,0.1)) a1.legend(loc='upper right') a1.set_xlabel("Pairs Similarity") a1.set_ylabel("% of numbers of pairs") a2 = plt.subplot(1, 2, 2) a2.set_xticks(np.arange(0, 1.1, 0.1)) a2.plot(X,pos,color="red",linewidth=2.5,linestyle="-",label="Matching Pairs") a2.plot(X,neg,color="green",linewidth=2.5,linestyle="-",label="Un-matching Pairs") a2.legend(loc='upper left') a2.set_xlabel("Pairs Similarity") a2.set_ylabel("% of numbers of pairs") plt.show() print(1)
Python
UTF-8
607
2.828125
3
[]
no_license
import argparse # 处理命令行 parser = argparse.ArgumentParser() parser.add_argument("-n", dest="n", type=int, help="Number of events") parser.add_argument("-g", "--geo", dest="geo", type=str, help="Geometry file") parser.add_argument("-o", "--output", dest="opt", type=str, help="Output file") args = parser.parse_args() import h5py as h5 # 读入几何文件 with h5.File(args.geo, "r") as geo: print("TODO: Deal with geometry file") # 输出 with h5.File(args.opt, "w") as opt: # 循环模拟 for i in range(args.n): print("TODO: Event", i) print("TODO: Write opt file")
Java
UTF-8
486
3.40625
3
[]
no_license
package javawork; import java.util.*; public class ex15 { public static void main(String[] args) { /* Write a program to calculate the sum of the digits of a 3-digit number. Number : 132 Output : 6*/ Scanner sc = new Scanner(System.in); System.out.println("Enter a 3 digit no"); int n = sc.nextInt(); int res=0; while(n>0) { res = res + n%10; n/=10; } System.out.println(res); } }
Java
UTF-8
3,407
1.875
2
[]
no_license
package com.girfa.apps.wifitalkie.helper; import java.lang.reflect.Method; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.net.wifi.WifiManager; import android.provider.Settings; import android.support.v4.content.LocalBroadcastManager; import com.girfa.apps.wifitalkie.model.Command; public abstract class Broadcast extends BroadcastReceiver { private static final String WIFI_AP_STATE_CHANGED = "android.net.wifi.WIFI_AP_STATE_CHANGED"; private Context ctx; private LocalBroadcastManager lbm; private Class<?> me; private Command last; private WifiManager wm; public Broadcast(Context context, Class<?> dest) { ctx = context; lbm = LocalBroadcastManager.getInstance(context); me = dest; wm = (WifiManager) ctx.getSystemService(Context.WIFI_SERVICE); } public void register() { IntentFilter filter = new IntentFilter(); filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION); filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION); filter.addAction(WIFI_AP_STATE_CHANGED); ctx.registerReceiver(this, filter); lbm.registerReceiver(this, new IntentFilter(Broadcast.class.getName())); } public void unregister() { lbm.unregisterReceiver(this); ctx.unregisterReceiver(this); } public void send(Command cmd, Intent intent) { if (Command._WIFI_TURN_ON.equals(cmd)) { wm.setWifiEnabled(true); return; } else if (Command._WIFI_CONNECT.equals(cmd)) { ctx.startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS)); return; } if (intent == null) { intent = new Intent(); } intent.setAction(Broadcast.class.getName()); intent.putExtra(Broadcast.class.getName(), me.getName()); intent.putExtra(Command.class.getName(), cmd.id); lbm.sendBroadcast(intent); } public abstract void onReceive(Command cmd, Intent intent); @Override public void onReceive(Context context, Intent intent) { if (me.getName().equals( intent.getStringExtra(Broadcast.class.getName()))) return; Command cmd = Command.valueOf(intent.getIntExtra( Command.class.getName(), 0)); String action = intent.getAction(); if (Command._WIFI_STATUS.equals(cmd) || WifiManager.NETWORK_STATE_CHANGED_ACTION.equals(action) || WifiManager.WIFI_STATE_CHANGED_ACTION.equals(action) || WIFI_AP_STATE_CHANGED.equals(action)) { NetworkInfo ni = ((ConnectivityManager) ctx .getSystemService(Context.CONNECTIVITY_SERVICE)) .getNetworkInfo(ConnectivityManager.TYPE_WIFI); if (wm.isWifiEnabled()) { if (ni.isConnected()) { cmd = Command._WIFI_ON_CONNECTED; } else { cmd = Command._WIFI_ON_DISCONNECTED; } } else { cmd = Command._WIFI_OFF; for (Method method : wm.getClass().getDeclaredMethods()) { if (method.getName().equals("isWifiApEnabled")) { try { if ((Boolean) method.invoke(wm)) { cmd = Command._WIFI_ON_CONNECTED; } } catch (Exception e) { e.printStackTrace(); } } } } Config.write(ctx).wifi(Command._WIFI_ON_CONNECTED.equals(cmd)); if (cmd.equals(last)) { return; } else { last = cmd; } } onReceive(cmd, intent); } }
Java
UTF-8
3,725
2.53125
3
[]
no_license
package com.learning.springreactive.inventory_reactive; import java.util.Arrays; import java.util.List; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.data.mongo.DataMongoTest; import org.springframework.test.context.junit4.SpringRunner; import com.learning.springreactive.inventory_reactive.documents.InventoryItem; import com.learning.springreactive.inventory_reactive.repositories.InventoryItemRepository; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; @RunWith(SpringRunner.class) @DataMongoTest public class BasicMpongoOperationTest extends BaseTest{ @Autowired private InventoryItemRepository repository; private List<InventoryItem> items = Arrays.asList(new InventoryItem("sita-ram", "jai sita ram"), new InventoryItem("radhe-krishna", "jai radhe krishna"), new InventoryItem("ABC","radhe-krishna", "jai radhe krishna")//this time id will not be auto generated ); @Before public void setup() { //remove exisitng data and insert new data everytime -> saves data corruption repository.deleteAll() .thenMany(Flux.fromIterable(items)) .flatMap(repository::save) .doOnNext(item -> System.out.println("Created Item "+item)) .blockLast() ; } @Test public void findAllItem() { //empty case StepVerifier.create(repository.findAll().log()) .expectSubscription() .expectNextCount(3) .verifyComplete(); ; } @Test public void findById() { String expectedID = "ABC"; StepVerifier.create(repository.findById(expectedID).log()) .expectSubscription() .expectNextMatches(item -> item.getId().equals(expectedID)) .verifyComplete() ; ; } @Test public void findByDescriptionContains() { String expectedDescriptionContains = "jai"; StepVerifier.create(repository.findByDescriptionContains(expectedDescriptionContains).log()) .expectSubscription() //all returned items must contain expected string in descriptionm .expectNextMatches(item -> item.getDescription().contains(expectedDescriptionContains)) //since we are returning bounded items on complete even will not be fiered .thenCancel() .verify() ; } @Test public void testInsert() { InventoryItem item = new InventoryItem("fake", "fake-king", "fake baba se bacho"); Mono<InventoryItem> itemMono = Mono.just(item) .flatMap(i -> repository.save(i)) .then(repository.findById(item.getId())) .log() ; StepVerifier.create(itemMono) .expectNextMatches(a -> a.getId().equals(item.getId())) .verifyComplete() ; } @Test public void testUpdate() { String expectedID = "ABC"; String updatedName = "radhe-krishna-updated"; Mono<InventoryItem> updatedMono = repository.findById(expectedID) .map(item -> {item.setName(updatedName); return item;}) .flatMap(repository::save ).then(repository.findById(expectedID)); ; StepVerifier.create(updatedMono) .expectSubscription() .expectNextMatches(item -> item.getId().equals(expectedID) && updatedName.equals(item.getName())) .verifyComplete() ; } @Test public void testDelete() { String expectedID = "ABC"; Mono<InventoryItem> monoRemoved = repository.findById(expectedID) .flatMap(repository::delete) .then(repository.findById(expectedID)) .log() ; //stepverifier is blocking aleady StepVerifier.create(monoRemoved) .expectSubscription() .expectNextCount(0) .verifyComplete(); } }
Python
UTF-8
745
3.46875
3
[ "MIT" ]
permissive
# Max Consecutive Ones # https://leetcode.com/explore/learn/card/fun-with-arrays/521/introduction/3238 class Solution: def findMaxConsecutiveOnes(self, nums): start_pos = 0 end_pos = 0 max_len = 0 pos = 0 while (pos < len(nums)): if nums[pos] == 1: # 窗口伸长 l = end_pos - start_pos + 1 max_len = max(max_len, l) end_pos = end_pos + 1 elif nums[pos] == 0: # 窗口移动 start_pos = pos + 1 end_pos = start_pos pos = pos + 1 return max_len if __name__ == "__main__": s = Solution() print(s.findMaxConsecutiveOnes([1,0,1,1,0,1]))
Java
UTF-8
961
2.234375
2
[ "Apache-2.0" ]
permissive
package service; import java.io.IOException; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import io.web.LoadFile; /** * Servlet implementation class UploadDish */ public class UploadDish extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response) */ protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub List<String> paths = new ArrayList<String>(); LoadFile lf = new LoadFile(); lf.setUrl("E:\\workspace\\congregation\\src\\main\\webapp\\images\\dish\\"); lf.setExt(".jpg"); paths.addAll(lf.run(request, response)); } }
Java
UTF-8
982
2.1875
2
[]
no_license
package com.example.ranggarizky.nami.model; /** * Created by ranggarizky on 1/30/2017. */ public class Kartu { private String xl,telkomsel,ooredo,axis,tri,other; public void setAxis(String axis) { this.axis = axis; } public void setOoredo(String ooredo) { this.ooredo = ooredo; } public void setOther(String other) { this.other = other; } public void setTelkomsel(String telkomsel) { this.telkomsel = telkomsel; } public void setTri(String tri) { this.tri = tri; } public void setXl(String xl) { this.xl = xl; } public String getAxis() { return axis; } public String getOoredo() { return ooredo; } public String getOther() { return other; } public String getTelkomsel() { return telkomsel; } public String getTri() { return tri; } public String getXl() { return xl; } }
PHP
UTF-8
7,199
2.734375
3
[]
no_license
<?php $m_inspection = new controllerClass(); // instantiate in controllerClass object $inspection_validation = array('plqinsp_date', 5, 'date', 'plqinsp_comments', 5, 'comments', 'fkvendor_id', 2, 'vendor', 'fkplaqueinspectiontype_id', 2, 'inspection type'); $result = $m_inspection->getPlaqueByID($_GET['id']); // read plaque record $row = mysql_fetch_array($result); // plaque data ?> <p> Plaque Receipient: &nbsp; <?php echo $row['plq_recipient']; ?></p> <?php // want attributes for plaqueinspectionClass $inspection_vars = $m_inspection->getInspection(); // attributes // if submit button add or update plaque inspection record if(isset($_POST['submit_app'])) { // if submit button $post_vars = $_POST; // field values entered on form if ($post_vars['pkplaqueinspection_id']=='new') { // if a new plq inspection // create plaque inspection record echo "adding ..."; // validate data if(validateData($inspection_validation, $post_vars)) { // data is valid, create inspection record $result=$m_inspection->createInspection($post_vars); $result=$m_inspection->updatePlaque($post_vars); if($result) { ?> <p> Your Inspection has been added. If you would like to see a listing click <a href="index.php?page=plaque_listing">here</a>.</p> <?php } } else { // validation error ?> <p> <?php echo '<font style="color:red;">'.$err_mess.'</font>'; ?> </p> <?php displayPlaqueInspection($post_vars); } } else { echo "updating ..."; // validate data if(validateData($inspection_validation, $post_vars)) { // data is valid, update inspection record $result=$m_inspection->updateInspection($post_vars); $result=$m_inspection->updatePlaque($post_vars); if($result) { ?> <p> Your Inspection has been updated. If you would like to see a listing click <a href="index.php?page=plaque_listing">here</a>.</p> <?php } } else { // validation error ?> <p> <?php echo '<font style="color:red;">'.$err_mess.'</font>'; ?> </p> <?php displayPlaqueInspection($post_vars); } } } else { if(isset($_GET['id'])) { // if plaque id is set in url // read plaque record passed in url // extract plaque record data $plqresult = $m_inspection->getPlaqueByID($_GET['id']); $plqrow = mysql_fetch_array($plqresult); // determine if there is existing plaque inspection record // attempt to retrieve plaque inspection record // using plaque id and current year $today = getdate(); // current date from system $result = $m_inspection->getInspectionByPlqIdYear($_GET['id'], $today['year']); $rowcount = mysql_num_rows($result); // number of records retrieved if ($rowcount > 0) { // if plq inspection record exists // retrieve plaque inspection data // append plaque inspection data to plaque data // want all data accessible when populating form while ($row = mysql_fetch_array($result)) { $row = array_merge($row, $plqrow); displayPlaqueInspection($row); // populate form } } else { // otherwise // no plaque inspection data // display blank form - plaque inspection data // form includes plaque inspection required field from plaque record // include plaque inspection attributes with plaque attributes $row = array_merge($inspection_vars, $plqrow); displayPlaqueInspection($row); } } } ?> <?php /*----------------------------------- display inspection form -----------------------------------*/ // display plaque inspection form (tblplaqueinspection) // include plaque inspection required field from plaque record (tblplaque) // if no plaque inspection record - display form with no date // if plaque inpsection record - display form poulated with data from record function displayPlaqueInspection($vars) { ?> <form name="Inspection" method="post" action="" > <!--index.php?action=applicant--> <fieldset> <legend> Plaque Inspection </legend> <table> <tr> <td> Inspection Date: <br /> <div> <input onclick='ds_sh(this);' name="plqinsp_date" readonly='readonly' style='cursor: text' value="<?php echo $vars['plqinsp_date']; ?>" /> </div> </td> <td> Done By: <br /> <?php displayVendor($vars['fkvendor_id']); ?> </td> <td> Inspection Required: <br /> <input type="radio" name="plq_inspect_reqd" value="Y" <?php if($vars['plq_inspect_reqd']=='Y') echo 'checked'; ?> /> Yes <input type="radio" name="plq_inspect_reqd" value="N" <?php if($vars['plq_inspect_reqd']=='N') echo 'checked'; ?> /> No </td> </tr> <tr> <td> Inspection Action: <br /> <input type="text" name="plqinsp_action" value="<?php echo $vars['plqinsp_action']; ?>" /> </td> <td> Inspection Type: <br /> <?php displayInspectType($vars['fkplaqueinspectiontype_id']); ?> </td> </tr> <tr> <td colspan="2"> Inspection Comments: <br /> <textarea name="plqinsp_comments" cols="40" rows="6"><?php echo $vars['plqinsp_comments']; ?></textarea> </td> </tr> </table> </fieldset> <input type="hidden" name="pkplaqueinspection_id" value="<?php if ($vars['pkplaqueinspection_id']=='') { echo 'new'; } else { echo $vars['pkplaqueinspection_id']; }?>" /> <input type="hidden" name="pkplaque_id" value="<?php echo $vars['pkplaque_id']; ?>" /> <input class="btton" type="submit" value="Submit" name="submit_app" /> </form> <?php } /*----------------------------------- display vendors -----------------------------------*/ // display drop down list containing vendors (file tblvendor) // populate drop down list entries with vendor id and vendor name function displayVendor($fkvendor_id) { $m_vendor = new controllerClass(); // instantiate new controller object $results = $m_vendor->getAllVendors(); // retrieve all records ?> <select name="fkvendor_id"> <option value="0"> Choose a Vendor... </option> <?php while($row=mysql_fetch_array($results)) { // for all records in vendor table ?> <option value="<?php echo $row['pkvendor_id']; ?>"<?php if($row['pkvendor_id'] == $fkvendor_id) echo "selected"; ?>><?php echo $row['vendor_name']; ?></option> <?php } ?> </select> <?php } /*------------------------------ display plaque inspection type ------------------------------*/ // display drop down list containing plaque inspection type (file tblplaqueinspectiontype) // populate drop down list entries with id and name function displayInspectType($fkplaqueinspectiontype_id) { $m_plqinspecttype = new controllerClass(); // instantiate new controller object $result = $m_plqinspecttype->getInspectionTypes(); // retrieve all records ?> <select name="fkplaqueinspectiontype_id"> <option value="0"> Choose Inspection Type ... </option> <?php while($row=mysql_fetch_array($result)) { // for all records in vendor table ?> <option value="<?php echo $row['id']; ?>"<?php if($row['id'] == $fkplaqueinspectiontype_id) echo "selected"; ?>> <?php echo $row['name']; ?> </option> <?php } ?> </select> <?php } ?>
JavaScript
UTF-8
752
2.96875
3
[]
no_license
//Obtener los elementos de la clase .close let links = document.querySelectorAll(".close"); //Recorrerlos links.forEach(function(link) { //Agregar un evento click a cada uno de ellos - case sensitive link.addEventListener("click", function(ev) { ev.preventDefault(); let content = document.querySelector('.content'); //Quitarle las clases de animación que ya tiene content.classList.remove("animate__pulse"); content.classList.remove("animate__animated"); //agregar las clases de animación que ya tiene content.classList.add("animate__fadeOutUp"); content.classList.add("animate__animated"); setTimeout(function() { window.history.go(-1); }, 600); setInterval return false; }); });
Markdown
UTF-8
544
2.78125
3
[]
no_license
# Food Recipe Web-scraper This project was created to develop a solution to a constant problem I've had: You have certain ingredients available in your pantry, but you're unsure as to what you can make. The food recipe web-scraper (currently) takes in a single ingredient and returns the top 20 recipes from [allrecipes](https://www.allrecipes.com/). It's still a work-in-progress, but will eventually pull data from various recipe websites, such as the [Food Network](https://www.foodnetwork.com/). Documentation is not yet fully completed.
C++
UTF-8
1,874
2.59375
3
[]
no_license
/* * CLProgramManager.cpp * * Created on: Apr 27, 2011 * Author: tychi */ #include "CLProgramManager.h" #include "Buffer/IntermediateResultBuffersManager.h" #include <boost/foreach.hpp> namespace Flewnit { CLProgramManager::CLProgramManager( bool useCacheUsingOpenCLImplementation) : mIntermediateResultBuffersManager(new IntermediateResultBuffersManager()), mUseCacheUsingOpenCLImplementation(useCacheUsingOpenCLImplementation) { // TODO Auto-generated constructor stub } CLProgramManager::~CLProgramManager() { delete mIntermediateResultBuffersManager; //DON't delete CLPrograms, as they are "owned" by SimResManager; } void CLProgramManager::registerCLProgram(CLProgram* clProgram)throw(SimulatorException) { //no validation, as only CLProgram::registerToCLPRogramManager() can call this, which in turn is only //callable by CLProgram* base class; if(mCLPrograms.find(clProgram->getName()) != mCLPrograms.end()) { throw(SimulatorException( String("CLProgramManager::registerCLProgram(): CLProgram with specified name ") + clProgram->getName() + String(" already exists!") )); } mCLPrograms[ clProgram->getName() ] = clProgram; } CLProgram* CLProgramManager::getProgram(String name)throw(SimulatorException) { if(mCLPrograms.find(name) == mCLPrograms.end()) { throw(SimulatorException( String("CLProgramManager::getProgram(): CLProgram with specified name ") + name + String(" doesn't exist!") )); } return mCLPrograms[name]; } void CLProgramManager::buildProgramsAndCreateKernels() { mIntermediateResultBuffersManager->allocBuffers(); //BOOST_FOREACH(CLProgram* clProgram, mCLPrograms) BOOST_FOREACH(CLProgramMap::value_type stringProgPair, mCLPrograms) { stringProgPair.second->build(); stringProgPair.second->createKernels(); // clProgram->build(); // clProgram->createKernels(); } } }
Java
UTF-8
16,647
1.804688
2
[]
no_license
package com.helloyuyu.routerwrapper.compiler; import android.support.annotation.NonNull; import com.alibaba.android.arouter.facade.annotation.Autowired; import com.alibaba.android.arouter.facade.annotation.Route; import com.squareup.javapoet.ClassName; import com.squareup.javapoet.CodeBlock; import com.squareup.javapoet.JavaFile; import com.squareup.javapoet.MethodSpec; import com.squareup.javapoet.ParameterSpec; import com.squareup.javapoet.TypeName; import com.squareup.javapoet.TypeSpec; import com.helloyuyu.routerwrapper.compiler.feature.TypeTransformer; import com.helloyuyu.routerwrapper.compiler.utils.CollectionUtils; import com.helloyuyu.routerwrapper.compiler.utils.Logger; import com.helloyuyu.routerwrapper.compiler.utils.RouteTypes; import com.helloyuyu.routerwrapper.compiler.utils.StringUtils; import com.helloyuyu.routerwrapper.compiler.utils.SubsetUtils; import com.helloyuyu.routerwrapper.compiler.utils.TypeUtils; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.annotation.processing.Filer; import javax.lang.model.element.Element; import javax.lang.model.element.Modifier; import javax.lang.model.element.PackageElement; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; import javax.lang.model.util.Elements; import javax.lang.model.util.Types; import static com.helloyuyu.routerwrapper.compiler.Constants.FACADE_PACKAGE; import static com.helloyuyu.routerwrapper.compiler.Constants.BUILDER_CLASS_NAME_PREFIX; import static com.helloyuyu.routerwrapper.compiler.Constants.POSTCARD_SIMPLE_CLASS_NAME; /** * 构建文件输出 * * @author xjs * @date 2018/1/13 */ public class RouterWrapperClassGenerator { private Logger logger; private Types typeUtils; private String outputPackage; private Elements elementUtils; private TypeTransformer typeTransformer; private Map<TypeElement, List<Element>> elementListMap; private static final String ROUTER_WRAPPER_NAME = "Navigator"; public RouterWrapperClassGenerator(String outputPackage, Types typeUtils, Logger logger, TypeTransformer typeTransformer, @NonNull Map<TypeElement, List<Element>> elementListMap, Elements elementUtils) { this.outputPackage = outputPackage; this.typeUtils = typeUtils; this.logger = logger; this.typeTransformer = typeTransformer; this.elementListMap = elementListMap; this.elementUtils = elementUtils; } public void write(Filer filer) throws IOException { for (JavaFile javaFile : createClasses()) { javaFile.writeTo(filer); } } /** * 构建生成文件 * * @return ; */ private Set<JavaFile> createClasses() { Set<JavaFile> javaFiles = new HashSet<>(); List<MethodSpec> routeMethodSpecList = new LinkedList<>(); Map<String, Integer> duplicationNameMap = new HashMap<>(elementListMap.size()); for (Map.Entry<TypeElement, List<Element>> entry : elementListMap.entrySet()) { //重名加前缀 _mx x为重复的次数 String methodNamePrefix = ""; TypeElement classElement = entry.getKey(); String className = classElement.getSimpleName().toString(); if (duplicationNameMap.containsKey(className)) { int times = duplicationNameMap.get(className) + 1; methodNamePrefix = String.format("_m%1$s", times); duplicationNameMap.put(className, times); } else { duplicationNameMap.put(className, 1); } //如果Route注解的是Activity添加方法,如果是其他类(也只支持Fragment参数注入)则创建JavaFile if (isActivitySubclass(classElement)) { routeMethodSpecList.addAll(getActivitySubclassMethodSpecs(classElement, entry.getValue(), methodNamePrefix)); } else { javaFiles.add(createInjectFragmentJavaFile(classElement, entry.getValue())); } } TypeSpec routerServerClassTypeSpec = TypeSpec .classBuilder(ROUTER_WRAPPER_NAME) .addMethods(routeMethodSpecList) .addJavadoc("模块路由表") .addModifiers(Modifier.PUBLIC) .build(); javaFiles.add(JavaFile.builder(outputPackage, routerServerClassTypeSpec).build()); return javaFiles; } /** * 创建 作为参数注入的 fragment 的文件 * * @return ; */ private JavaFile createInjectFragmentJavaFile(TypeElement classElement, List<Element> fieldElement) { List<MethodSpec> builderMethod = getClassBuilderMethodSpecs(classElement, fieldElement); //构造函数 MethodSpec constructor = MethodSpec.constructorBuilder() .addModifiers(Modifier.PRIVATE) .build(); //类名 TypeSpec classTypeSpec = TypeSpec .classBuilder(BUILDER_CLASS_NAME_PREFIX + classElement.getSimpleName()) .addModifiers(Modifier.PUBLIC) .addMethods(builderMethod) .addMethod(constructor) .build(); return JavaFile.builder(getClassElementPackageName(classElement), classTypeSpec) .build(); } /** * 构建 activity 子类的方法 * * @param typeElement ; * @param fieldElement ; * @return ; */ private List<MethodSpec> getActivitySubclassMethodSpecs(TypeElement typeElement, List<Element> fieldElement, String methodNamePrefix) { if (fieldElement.isEmpty()) { MethodSpec methodSpec = createRouteActivityStaticMethod(typeElement, fieldElement, methodNamePrefix, ""); return Collections.singletonList(methodSpec); } List<List<Element>> possibleCombinations = getParamsPossibleCombinations(fieldElement); List<MethodSpec> methodSpecList = new ArrayList<>(possibleCombinations.size()); for (int i = 0; i < possibleCombinations.size(); i++) { String methodNameSuffix = i == 0 ? "" : String.valueOf(i); MethodSpec methodSpec = createRouteActivityStaticMethod(typeElement, possibleCombinations.get(i), methodNamePrefix, methodNameSuffix); methodSpecList.add(methodSpec); } return methodSpecList; } /** * ARouter 现在只是fragment支持参数注入 * * @param typeElement ; * @param fieldElement ; * @return ; */ private List<MethodSpec> getClassBuilderMethodSpecs(TypeElement typeElement, List<Element> fieldElement) { if (fieldElement.isEmpty()) { MethodSpec methodSpec = createClassStaticBuilderMethod(typeElement, fieldElement, ""); return Collections.singletonList(methodSpec); } List<List<Element>> possibleCombinations = getParamsPossibleCombinations(fieldElement); List<MethodSpec> methodSpecList = new ArrayList<>(possibleCombinations.size()); for (int i = 0; i < possibleCombinations.size(); i++) { String methodNameSuffix = i == 0 ? "" : String.valueOf(i); MethodSpec methodSpec = createClassStaticBuilderMethod(typeElement, possibleCombinations.get(i), methodNameSuffix); methodSpecList.add(methodSpec); } return methodSpecList; } /** * 获取注入参数所有可能组合情况 * * @param fieldElementList route 类中所有依赖注入的参数element * @return 注入参数所有可能组合情况 */ private List<List<Element>> getParamsPossibleCombinations(List<Element> fieldElementList) { List<Element> choosableElements = new ArrayList<>(); for (int i = 0; i < fieldElementList.size(); i++) { Element element = fieldElementList.get(i); Autowired autowired = element.getAnnotation(Autowired.class); if (!autowired.required()) { fieldElementList.remove(i); i--; choosableElements.add(element); } } List<List<Element>> resultList = new ArrayList<>(2 ^ choosableElements.size()); resultList.add(fieldElementList); if (CollectionUtils.isNotEmpty(choosableElements)) { Set<int[]> combinationSet = SubsetUtils.recursionGetCombination(0, choosableElements.size() - 1); if (CollectionUtils.isNotEmpty(combinationSet)) { for (int[] positionArray : combinationSet) { List<Element> elements = new ArrayList<>(fieldElementList.size() + positionArray.length); elements.addAll(fieldElementList); for (int index : positionArray) { elements.add(choosableElements.get(index)); } resultList.add(elements); } } } return resultList; } /** * @param classElement activity class element * @param elements parameter element * @param methodNameSuffix 方法名后缀为了避免可选参数类型重复 * @param methodNamePrefix 方法名前缀避免类名重复 * @return ; */ private MethodSpec createRouteActivityStaticMethod(@NonNull TypeElement classElement, List<Element> elements, String methodNamePrefix, String methodNameSuffix) { List<ParameterSpec> parameterSpecList = new ArrayList<>(); String routePath = classElement.getAnnotation(Route.class).path(); //ARouter.getInstance().build("/path") ClassName aRouter = ClassName.get(Constants.AROUTER_LAUNCHER_PACKAGE, Constants.AROUTER_SIMPLE_CLASS_NAME); CodeBlock.Builder arouterParamCodeBlockBuilder = CodeBlock.builder().add( "return $T.getInstance().build($S)", aRouter, routePath); // 注释文档 CodeBlock.Builder javaDocBuilder = createClassJavaDoc(classElement); for (Element element : elements) { String parameterName = replaceStartWith_m_Field(element.getSimpleName().toString()); ParameterSpec parameterSpec = ParameterSpec.builder(TypeName.get(element.asType()) , parameterName) .build(); parameterSpecList.add(parameterSpec); //.withXxx("key",value) arouterParamCodeBlockBuilder.add(".with$N($S,$N)" , typeTransformer.transform(element) , getParamKey(element) , parameterName); javaDocBuilder.add(createFieldJavaDoc((VariableElement) element)); } arouterParamCodeBlockBuilder.add(";"); String methodName; if (StringUtils.isNotEmpty(methodNamePrefix)) { methodName = methodNamePrefix + classElement.getSimpleName().toString() + methodNameSuffix; } else { methodName = StringUtils.firstCharacterToLow(classElement.getSimpleName().toString()) + methodNameSuffix; } return MethodSpec.methodBuilder(methodName) .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .addParameters(parameterSpecList) .addJavadoc(javaDocBuilder.build()) .addCode(arouterParamCodeBlockBuilder.build()) .returns(ClassName.get(FACADE_PACKAGE, POSTCARD_SIMPLE_CLASS_NAME)) .build(); } private MethodSpec createClassStaticBuilderMethod(@NonNull TypeElement classElement, @NonNull List<Element> elements, String builderMethodNameSuffix) { List<ParameterSpec> parameterSpecList = new ArrayList<>(); String routePath = classElement.getAnnotation(Route.class).path(); // ARouter.getInstance() ClassName aRouter = ClassName.get(Constants.AROUTER_LAUNCHER_PACKAGE, Constants.AROUTER_SIMPLE_CLASS_NAME); CodeBlock.Builder paramCodeBlockBuilder = CodeBlock.builder().add( "$T.getInstance().build($S)", aRouter, routePath); for (Element element : elements) { String parameterName = replaceStartWith_m_Field(element.getSimpleName().toString()); // (XXX xxx) ParameterSpec parameterSpec = ParameterSpec.builder(TypeName.get(element.asType()) , parameterName) .build(); parameterSpecList.add(parameterSpec); //.withXxx("key",value) paramCodeBlockBuilder.add(".with$N($S,$N)" , typeTransformer.transform(element) , getParamKey(element) , parameterName); } //.navigation 方法; paramCodeBlockBuilder.add(".navigation();"); // return ARouter.getInstance().build("path").navigation(代码; ClassName classType = ClassName.bestGuess(classElement.getQualifiedName().toString()); CodeBlock returnCodes = CodeBlock.builder() .add("return ($T)", classType) .add(paramCodeBlockBuilder.build()) .build(); return MethodSpec.methodBuilder("builder" + builderMethodNameSuffix) .addModifiers(Modifier.PUBLIC, Modifier.STATIC) .addParameters(parameterSpecList) .addCode(returnCodes) .returns(ClassName.bestGuess(classElement.getQualifiedName().toString())) .build(); } private CodeBlock.Builder createClassJavaDoc(TypeElement typeElement) { Route route = typeElement.getAnnotation(Route.class); String routeDesc = route.name(); String classJavaDoc = elementUtils.getDocComment(typeElement); if (classJavaDoc == null) { classJavaDoc = "/***/"; } String linkDoc = String.format("{@link %1$s}", typeElement.getQualifiedName().toString()); return CodeBlock.builder().add("路由描述: $N\n\n$N\n$N\n", routeDesc, classJavaDoc, linkDoc); } /** * 获取被{@code Autowired}注解的字段注释 * * @param element field * @return ; */ private CodeBlock createFieldJavaDoc(VariableElement element) { Autowired autowired = element.getAnnotation(Autowired.class); String paramDesc = autowired.desc(); if ("No desc.".equals(paramDesc)) { paramDesc = elementUtils.getDocComment(element); if (paramDesc == null || "".equals(paramDesc)) { paramDesc = element.getSimpleName().toString(); } } return CodeBlock.of("@param $N $N\n", element.getSimpleName(), paramDesc); } /** * 判断是否继承Activity * android.app.Activity 或者 android.support.v7.app.AppCompatActivity * * @param element ; * @return ; */ private boolean isActivitySubclass(@NonNull TypeElement element) { return TypeUtils.recursionIsImplements(element, ClassName.bestGuess(RouteTypes.ACTIVITY.getClassName()), typeUtils) || TypeUtils.recursionIsImplements(element, ClassName.bestGuess(RouteTypes.SUPPORT_ACTIVITY.getClassName()), typeUtils); } private String replaceStartWith_m_Field(String fieldName) { //匹配 类似于 mUserName这样的 String regex = "^m[A-Z]"; Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(fieldName); if (matcher.find()) { return StringUtils.firstCharacterToLow(fieldName.substring(1)); } return fieldName; } /** * 获取 ARouter.getInstance().withString("key","value") 中的key * * @param element field element * @return ; */ private String getParamKey(Element element) { Autowired autowired = element.getAnnotation(Autowired.class); if (StringUtils.isNotEmpty(autowired.name())) { return autowired.name(); } else { VariableElement variableElement = (VariableElement) element; return variableElement.getSimpleName().toString(); } } private static String getClassElementPackageName(TypeElement classElement) { return ((PackageElement) classElement.getEnclosingElement()).getQualifiedName().toString(); } }
Markdown
UTF-8
494
2.671875
3
[]
no_license
#Bongo Dashboard Use Nodejs to create a simple Real Time Dashboard. Convert HTTP POST in to a socket event sent to browser. ![Dashboard ScreenShot](/public/landing.png) ##Events Emulator Run Order emulator ``` node run order_example.js ``` ##Server Run Dashboard Server ``` node run app.js ``` ##Mongo DB You need to run a Mongo DB in order to save events. ``` mongod `` **Events are only sent to the user after saving to DB** ##Browser Open Browser and go to ``` http://localhost:3000 ```
C++
UTF-8
3,133
3.296875
3
[]
no_license
#ifndef BOARDMANAGER_H #define BOARDMANAGER_H #include "board.h" #include "../file/filemanager.h" #include "../file/boarddata.h" /** \brief Class managing the board and communicating with UI. */ class BoardManager { public: /** \brief Standard constructor returning new BoardManager object. */ BoardManager(); /** \brief Standard destructor deleting the BoardManager object. */ ~BoardManager(); /** \brief Makes all the fields of the board dead. * \return void */ void clearBoard(); /** \brief Reverts dead fields of the board to alive and vice-versa. * \return void */ void revertBoard(); /** \brief Reverts single field of the board to alive and vice-versa. * \param h int Vertical position of field. * \param w int Horizontal position of field. * \return void */ void revertField(int h, int w); /** \brief Sets random dead/alive value to every field of the board. * \return void */ void randomizeBoard(); /** \brief Changes height of the board. * \param height int New height of the board. * \return void */ void changeBoardHeight(int height); /** \brief Changes width of the board. * \param width int New width of the board. * \return void */ void changeBoardWidth(int width); /** \brief Updates the board based on the current state. * \return void */ void updateBoard(); /** \brief Reads board from .txt file (if in appropriate format) and updates the board. * \param path std::string Path to the source file. * \return bool True if read successfully, false if not. */ bool readBoardFromFile(std::string path); /** \brief Saves board to .txt file. * \param path std::string Path to the .txt file. * \return void */ void saveBoardToFile(std::string path); /** \brief Returns height of the board. * \return int Height of the board. */ int getHeight(); /** \brief Returns width of the board. * \return int Width of the board. */ int getWidth(); /** \brief Checks if field is alive. * \param h int Vertical position of field. * \param w int Horizontal position of field. * \return bool True if alive, false if dead. */ bool getIsFieldAlive(int h, int w); /** \brief Sets neighborhood type of the game. * \param neighborhoodType int Type of neighborhood (Moore/von Neumann) based on a static dictionary. * \return void */ void setNeighborhoodType(int neighborhoodType); private: Board *board; int neighborhoodType; FileManager *fileManager; /** \brief Converts BoardData object and saves it as the internal Board object. * \param boardData BoardData* Object to be converted. * \return void */ void setBoardWithBoardData(BoardData *boardData); /** \brief Converts internal Board object to BoardData object. * \return BoardData* Board in a convenient format to save/read from .txt file. */ BoardData *setBoardDataWithBoard(); }; #endif // BOARDMANAGER_H
PHP
UTF-8
2,920
2.8125
3
[]
no_license
<?php class Image extends fActiveRecord { protected $file; protected function configure() { // } public function genId(){ // Generate random UUIDs until it is unique while(1) { $uuid = ''; while (strlen($uuid) < CI_UUID_LENGTH){ $uuid .= substr(CI_UUID_CHARS, rand(0,strlen(CI_UUID_CHARS)-1), 1); } try { $tmp = new Image($uuid); } catch (fNotFoundException $e) { $this->setId($uuid); break; } } } public function getIp(){ return inet_ntop(parent::getIp()); } public function storeFile($file){ $this->file = $file; if (!$this->getId()) $this->genId(); $file_path = str_replace(CI_UPLOAD_DIR, '', $file->getPath()); if ($file->getMimeType() == "image/svg+xml") { $this->setType('svg'); $this->setWidth(0); $this->setHeight(0); } else { $this->setType($file->getType()); $this->setWidth($file->getWidth()); $this->setHeight($file->getHeight()); } $this->processImage(); $this->setFileName($file_path); $this->setIp(inet_pton($_SERVER['REMOTE_ADDR'])); $this->setTime(time()); $this->store(); } protected function processImage(){ $this->orientImage(); $thumb = $this->file->duplicate(CI_UPLOAD_DIR.'thumb/'); if ($this->getType() == 'svg') { // TODO: Make png thumbnail? } else { $thumb->resize(CI_THUMBNAIL_WIDTH, 0); $thumb->saveChanges(); } } protected function orientImage() { $file_path = CI_UPLOAD_DIR . $this->getFileName(); $exif = @exif_read_data($file_path); if ($exif === false) return false; $orientation = intval(@$exif['Orientation']); if (!in_array($orientation, array(3, 6, 8))) return false; switch ($orientation) { case 3: $this->file->rotate(180); break; case 6: $this->file->rotate(270); break; case 8: $this->file->rotate(90); break; default: return false; } $this->file->saveChanges(); return true; } protected function orientImage2() { $file_path = CI_UPLOAD_DIR . $this->getFileName(); $exif = @exif_read_data($file_path); if ($exif === false) return false; $orientation = intval(@$exif['Orientation']); if (!in_array($orientation, array(3, 6, 8))) return false; $image = @imagecreatefromjpeg($file_path); switch ($orientation) { case 3: $image = @imagerotate($image, 180, 0); break; case 6: $image = @imagerotate($image, 270, 0); break; case 8: $image = @imagerotate($image, 90, 0); break; default: return false; } $success = imagejpeg($image, $file_path); // Free up memory (imagedestroy does not delete files): @imagedestroy($image); return $success; } public function delete( $force_cascade=FALSE ){ // Delete all related files unlink(CI_UPLOAD_DIR . $this->getFileName()); unlink(CI_UPLOAD_DIR .'thumb/'. $this->getFileName()); parent::delete($force_cascade); } }
C#
UTF-8
2,885
2.609375
3
[]
no_license
using System; using System.Reflection; using NTools.Logging.Log4Net; namespace NTools.Core.Reflection { /// <summary> /// Abstract base class for member access by reflection. /// </summary> [Serializable] public abstract class MemberReflector { private static readonly ITraceLog s_log = TraceLogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); public static BindingFlags AllInstanceDeclared = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.DeclaredOnly; public static BindingFlags PrivateInstanceDeclared = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.DeclaredOnly; public static BindingFlags AllStaticDeclared = BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly; public static BindingFlags AllDeclared = BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly; private readonly Type m_type; private readonly string m_memberName; private readonly BindingFlags m_bindingFlags; private MemberInfo m_memberInfo; #region Konstruktor / Cleanup /// <summary> /// Initialisiert eine neue Instanz der class <see cref="MemberReflector"/>. /// </summary> /// <param name="type">The type.</param> /// <param name="memberName">Name of the member.</param> /// <param name="bindingFlags">The binding flags.</param> protected MemberReflector(Type type, string memberName, BindingFlags bindingFlags) { #region Checks if (type == null) { throw new ArgumentNullException("type"); } if (String.IsNullOrEmpty(memberName)) { throw new ArgumentNullException("memberName"); } #endregion m_type = type; m_memberName = memberName; m_bindingFlags = bindingFlags; } /// <summary> /// Initialisiert eine neue Instanz der class <see cref="MemberReflector"/>. /// </summary> /// <param name="memberInfo">The member info.</param> protected MemberReflector(MemberInfo memberInfo) { #region Checks if (memberInfo == null) { throw new ArgumentNullException("memberInfo"); } #endregion m_memberInfo = memberInfo; } #endregion #region Properties /// <summary> /// Gets the type. /// </summary> /// <value>The type.</value> public Type Type { get { return m_type; } } /// <summary> /// Gets the name. /// </summary> /// <value>The name.</value> public string Name { get { return m_memberName; } } /// <summary> /// Gets the binding flags. /// </summary> /// <value>The binding flags.</value> public BindingFlags BindingFlags { get { return m_bindingFlags; } } /// <summary> /// Gets or sets the info. /// </summary> /// <value>The info.</value> public MemberInfo Info { get { return m_memberInfo; } set { m_memberInfo = value; } } #endregion } }
Java
UTF-8
2,128
2.125
2
[]
no_license
package net.wit.entity; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; import javax.persistence.CollectionTable; import javax.persistence.Column; import javax.persistence.ElementCollection; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.ManyToMany; import javax.persistence.SequenceGenerator; import javax.persistence.Table; import org.hibernate.validator.constraints.Length; import org.hibernate.validator.constraints.NotEmpty; /** * Entity - 角色 * @author 降魔战队 * @date 2017/2/13 19:00:18 */ @Entity @Table(name = "wx_role") @SequenceGenerator(name = "sequenceGenerator", sequenceName = "wx_role_sequence") public class Role extends BaseEntity { private static final long serialVersionUID = 49L; /** 名称 */ @NotEmpty @Length(max = 200) @Column(columnDefinition="varchar(255) not null comment '名称'") private String name; /** 是否内置 */ @Column(columnDefinition="bit not null comment '是否内置'") private Boolean isSystem; /** 描述 */ @Length(max = 200) @Column(columnDefinition="varchar(255) comment '描述'") private String description; /** 权限 */ @ElementCollection @CollectionTable(name = "wx_role_authority") private List<String> authorities = new ArrayList<String>(); /** 管理员 */ @ManyToMany(mappedBy = "roles", fetch = FetchType.LAZY) private Set<Admin> admins = new HashSet<Admin>(); public String getName() { return name; } public void setName(String name) { this.name = name; } public Boolean getIsSystem() { return isSystem; } public void setIsSystem(Boolean system) { isSystem = system; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public List<String> getAuthorities() { return authorities; } public void setAuthorities(List<String> authorities) { this.authorities = authorities; } public Set<Admin> getAdmins() { return admins; } public void setAdmins(Set<Admin> admins) { this.admins = admins; } }
Java
UHC
993
3.84375
4
[]
no_license
package workbook.StepA; import java.util.Scanner; public class A7_GigaToByte { private int gigabytes; private int megabytes; private int kilobytes; private long bytes; /** **/ public A7_GigaToByte() { input(); } /** **/ public void printResult() { System.out.println("ԷϽ 뷮"); System.out.println(getMega() + " ްƮ,"); System.out.println(getKilo() + " ųιƮ,"); System.out.println(getBytes() + " Ʈ Դϴ."); } /** Է **/ void input() { Scanner sc = new Scanner(System.in); System.out.print(" 뷮 ⰡƮ Էϼ. "); gigabytes = sc.nextInt(); } /** **/ int getMega() { megabytes = gigabytes * 1024; return megabytes; } int getKilo() { kilobytes = megabytes * 1024; return kilobytes; } long getBytes() { bytes = (long) kilobytes * 1024; return bytes; } }
Python
UTF-8
466
3.5
4
[]
no_license
from turtle import * def draw_square(): i = 0 j = 9 iteration = 1 while(iteration < j): for iteration in range(1, j): while (i < 4): forward(30) right(90) i += 1 forward(30) i = 0 j -= 1 iteration = 1 backward(30 * j) if(j != 1): left(90) forward(30) right(90) # draw_square() # input()
Java
UTF-8
801
1.859375
2
[]
no_license
package com.internexa.dynamics.steps; import com.internexa.dynamics.pageObjects.LoginDynamicsPage; import net.thucydides.core.annotations.Step; public class LoginDynamicsSteps { LoginDynamicsPage loginDynamicsPage; @Step public void login_dynamics(String strUsuario, String strPass) { //Paso Comun Admin-otrosUsarios loginDynamicsPage.open(); loginDynamicsPage.inputUsuario(strUsuario); //Solo admin loginDynamicsPage.btnsiguiente(); //Otros Usuarios loginDynamicsPage.btnCuentaProfesionaloEducativa(); // loginDynamicsPage.inputPass(strPass); loginDynamicsPage.btnIniciar(); loginDynamicsPage.btnMantenerSecion(); //loginDynamicsPage.btnMsjeCorreo(); //loginDynamicsPage.chkActivo(); //loginDynamicsPage.btnContinuar(); } }
Markdown
UTF-8
801
3.09375
3
[]
no_license
# mongoose-transaction256 package for mongoose transaction (based on mongoose transaction) Use ```npm install mongoose-transaction256``` to install package then ``` const transaction = require('mongoose-transaction256'); const ModelName1 = require('./models/x'); // ModelName is your model for example : User, Restaurants, Employees , ... const ModelName2 = require('./models/y'); const one = new ModelName1({x : 1, y : 1}); const two = new ModelName2({x : 2, y : 2}); transaction(async session => { // session is required parameter for this callback function await one.save({session}); await two.save({session}); }) .then(console.log('success')) .catch(console.log('fail')) ``` you can use this for many other mongoose operation but you should use **session** as a parameter
Java
UTF-8
1,761
2.5625
3
[ "Apache-2.0" ]
permissive
package dev.jpestana.mifitanalyzer.DataImporter.Entities; import javax.persistence.*; import java.sql.Date; import java.sql.Timestamp; import java.util.Objects; @Entity @Table(name = "activityminute") public class ActivityMinute { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id") private Integer id; @Column(name = "date") private Date date; @Column(name = "time") private Timestamp time; @Column(name = "steps") private Integer steps; public ActivityMinute() {} public ActivityMinute(Date date, Timestamp time, Integer steps) { this.date = date; this.time = time; this.steps = steps; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } public Timestamp getTime() { return time; } public void setLastSyncTime(Timestamp time) { this.time = time; } public Integer getSteps() { return steps; } public void setSteps(Integer steps) { this.steps = steps; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ActivityMinute activity = (ActivityMinute) o; return Objects.equals(id, activity.id) && Objects.equals(date, activity.date) && Objects.equals(time, activity.time) && Objects.equals(steps, activity.steps); } @Override public int hashCode() { return Objects.hash(id, date, time, steps); } }
C++
UTF-8
592
2.625
3
[]
no_license
#include<iostream> #include<cstdio> #include<cstring> #include<vector> #include<algorithm> using namespace std; int main() { int n; cin>>n; long long a; vector<long long> v; for(int i=1;i<=n;i++) { scanf("%lld",&a); v.push_back(a); } int ans=0; for(int i=1;i<v.size();) { /*cout<<v[i-1]<<' '<<v[i]<<' '<<v.size()<<':';for(int j=0;j<v.size();j++) { cout<<' '<<v[j]; }cout<<endl;*/ if(v[i]-v[i-1]==1) { v.erase(v.begin()+i); ans++; } else if(v[i-1]-v[i]==1) { v.erase(v.begin()+(i-1)); ans++; } else i++; } cout<<ans<<endl; return 0; }
Java
UTF-8
12,390
3.09375
3
[]
no_license
package University; import java.util.ArrayList; import java.util.Scanner; public class Student extends User { private String nric; ArrayList<Marks> mark = new ArrayList<>(); /** * Creates a student based on various attributes **/ public Student(int studId, String studFName, String studLName, String studEmail, String studPhoneNo, String studFaculty, String nric) { super(studId, studFName, studLName, studEmail, studPhoneNo, studFaculty); this.nric = nric; } /** * Student register for a course * @param course all courses * @param courseCount total number of courses * @return details of course that the student registered for */ public String[] regCourse(ArrayList<Course> course, int courseCount) { String[] ar = new String[5]; ar[0]="0"; int i; boolean valid = true; Scanner sc = new Scanner(System.in); System.out.println("Enter Course ID: "); int courseChoice = sc.nextInt(); int totalSlots; for(i=0;i<courseCount;i++) { if(course.get(i).lecGrp.size()==1) totalSlots = course.get(i).lecGrp.get(0).studIds.size(); else totalSlots = course.get(i).lecGrp.get(0).studIds.size()+course.get(i).lecGrp.get(1).studIds.size(); if(course.get(i).getCourseId()==courseChoice) { if(course.get(i).getSlots() > totalSlots) { for(int b=0; b<course.get(i).lecGrp.size(); b++) { for(int a=0;a<course.get(i).lecGrp.get(b).studIds.size();a++) { if(course.get(i).lecGrp.get(b).studIds.size()>0) { if(id == course.get(i).lecGrp.get(b).studIds.get(a)) { System.out.println("You are already registered for this course."); valid = false; break; } } } } if(valid) { System.out.println("======================================="); System.out.println("Group No: Slots Available:"); System.out.println("_______________________________________"); for(int x=0;x<course.get(i).lecGrp.size();x++) System.out.println("Lecture Group " + (x+1) + ":" + " " + (course.get(i).lecGrp.get(x).getSlots() - course.get(i).lecGrp.get(x).studIds.size()) + "/" + course.get(i).lecGrp.get(x).getSlots()); System.out.println("_______________________________________"); if(course.get(i).tutGrp.size()==0) System.out.println("No tutorial group for this course. "); else { for(int y=0;y<course.get(i).tutGrp.size();y++) System.out.println("Tutorial Group " + (y+1) + ":" + " " + (course.get(i).tutGrp.get(y).getSlots() - course.get(i).tutGrp.get(y).studIds.size()) + "/" + course.get(i).tutGrp.get(y).getSlots()); } System.out.println("_______________________________________"); if(course.get(i).labGrp.size()==0) System.out.println("No lab group for this course. "); else { for(int z=0;z<course.get(i).labGrp.size();z++) System.out.println("Lab Group " + (z+1) + ":" + " " + (course.get(i).labGrp.get(z).getSlots() - course.get(i).labGrp.get(z).studIds.size()) + "/" + course.get(i).labGrp.get(z).getSlots()); } System.out.println("======================================="); System.out.println("Please enter lecture group of your choice: "); int lecgrpChoice = sc.nextInt(); if(lecgrpChoice>course.get(i).getLec() || lecgrpChoice<1) { System.out.println("Please enter a valid group."); break; } else if(course.get(i).lecGrp.get(lecgrpChoice-1).studIds.size()>=course.get(i).lecGrp.get(lecgrpChoice-1).getSlots()) { System.out.println("No more vacancies."); break; } else { if(course.get(i).tutGrp.size()>0 && course.get(i).labGrp.size()>0) { System.out.println("Please enter tutorial group of your choice: "); int tutgrpChoice = sc.nextInt(); if(tutgrpChoice>course.get(i).getTut() || tutgrpChoice<1) { System.out.println("Please enter a valid group."); break; } else if(course.get(i).tutGrp.get(tutgrpChoice-1).studIds.size()>=course.get(i).tutGrp.get(tutgrpChoice-1).getSlots()) { System.out.println("No more vacancies."); break; } else { System.out.println("Please enter lab group of your choice: "); int labgrpChoice = sc.nextInt(); if(labgrpChoice>course.get(i).getLab() || labgrpChoice<1) { System.out.println("Please enter a valid group."); break; } else if(course.get(i).labGrp.get(labgrpChoice-1).studIds.size()>=course.get(i).labGrp.get(labgrpChoice-1).getSlots()) { System.out.println("No more vacancies."); break; } else { int x = course.get(i).lecGrp.get(lecgrpChoice-1).studIds.size(); course.get(i).lecGrp.get(lecgrpChoice-1).studIds.add(x, id); int y = course.get(i).tutGrp.get(tutgrpChoice-1).studIds.size(); course.get(i).tutGrp.get(tutgrpChoice-1).studIds.add(y, id); int z = course.get(i).labGrp.get(labgrpChoice-1).studIds.size(); course.get(i).labGrp.get(labgrpChoice-1).studIds.add(z, id); ar[0] = "1"; ar[1] = String.valueOf(i); ar[2] = String.valueOf(lecgrpChoice); ar[3] = String.valueOf(tutgrpChoice); ar[4] = String.valueOf(labgrpChoice); System.out.println("Course registered."); break; } } } else if(course.get(i).labGrp.size()==0 && course.get(i).tutGrp.size()>0) { System.out.println("Please enter tutorial group of your choice: "); int tutgrpChoice = sc.nextInt(); if(tutgrpChoice>course.get(i).getTut() || tutgrpChoice<1) { System.out.println("Please enter a valid group."); break; } else if(course.get(i).tutGrp.get(tutgrpChoice-1).studIds.size()>=course.get(i).tutGrp.get(tutgrpChoice-1).getSlots()) { System.out.println("No more vacancies."); break; } else { int x = course.get(i).lecGrp.get(lecgrpChoice-1).studIds.size(); course.get(i).lecGrp.get(lecgrpChoice-1).studIds.add(x, id); int y = course.get(i).tutGrp.get(tutgrpChoice-1).studIds.size(); course.get(i).tutGrp.get(tutgrpChoice-1).studIds.add(y, id); ar[0] = "1"; ar[1] = String.valueOf(i); ar[2] = String.valueOf(lecgrpChoice); ar[3] = String.valueOf(tutgrpChoice); ar[4] = String.valueOf(0); System.out.println("Course registered."); break; } } else if(course.get(i).labGrp.size()>0 && course.get(i).tutGrp.size()==0) { System.out.println("Please enter lab group of your choice: "); int labgrpChoice = sc.nextInt(); if(labgrpChoice>course.get(i).getLab() || labgrpChoice<1) { System.out.println("Please enter a valid group."); break; } else if(course.get(i).labGrp.get(labgrpChoice-1).studIds.size()>=course.get(i).labGrp.get(labgrpChoice-1).getSlots()) { System.out.println("No more vacancies."); break; } else { int x = course.get(i).lecGrp.get(lecgrpChoice-1).studIds.size(); course.get(i).lecGrp.get(lecgrpChoice-1).studIds.add(x, id); int z = course.get(i).labGrp.get(labgrpChoice-1).studIds.size(); course.get(i).labGrp.get(labgrpChoice-1).studIds.add(z, id); ar[0] = "1"; ar[1] = String.valueOf(i); ar[2] = String.valueOf(lecgrpChoice); ar[3] = String.valueOf(0); ar[4] = String.valueOf(labgrpChoice); System.out.println("Course registered."); break; } } else { int x = course.get(i).lecGrp.get(lecgrpChoice-1).studIds.size(); course.get(i).lecGrp.get(lecgrpChoice-1).studIds.add(x, id); ar[0] = "1"; ar[1] = String.valueOf(i); ar[2] = String.valueOf(lecgrpChoice); ar[3] = String.valueOf(0); ar[4] = String.valueOf(0); System.out.println("Course registered."); break; } } } } else System.out.println("No more vacancies. "); } } if(courseChoice>courseCount) System.out.println("Please enter a valid Course ID."); System.out.println("================================================="); return ar; } /** * Check the availability for a particular course * @param course all courses * @param courseCount total number of courses */ public void checkAvail(ArrayList<Course> course, int courseCount) { int i; System.out.println("Enter Course ID."); Scanner sc = new Scanner(System.in); int courseChoice = sc.nextInt(); for(i=0;i<courseCount;i++) { if(course.get(i).getCourseId()==courseChoice) { System.out.println("1. Tutorial group availability"); System.out.println("2. Lab group availability"); System.out.println("Enter your choice: "); int tutlabChoice = sc.nextInt(); switch (tutlabChoice) { case 1: System.out.println("Number of tutorial groups for this course: " + course.get(i).getTut()); System.out.println("Enter a tutorial group: "); int tutChoice = sc.nextInt(); if(tutChoice>course.get(i).getTut() || tutChoice<1) System.out.println("Please enter a valid tutorial group."); else System.out.println("Slots left: " + (course.get(i).tutGrp.get(tutChoice-1).getSlots() - course.get(i).tutGrp.get(tutChoice-1).studIds.size()) + "/" + course.get(i).tutGrp.get(tutChoice-1).getSlots()); break; case 2: System.out.println("Number of lab groups for this course: " + course.get(i).getLab()); System.out.println("Enter a lab group: "); int labChoice = sc.nextInt(); if(labChoice>course.get(i).getLab() || labChoice<1) System.out.println("Please enter a valid lab group."); else System.out.println("Slots left: " + (course.get(i).labGrp.get(labChoice-1).getSlots() - course.get(i).labGrp.get(labChoice-1).studIds.size()) + "/" + course.get(i).labGrp.get(labChoice-1).getSlots()); break; default: System.out.println("Please enter 1 or 2."); break; } break; } } if(i>=courseCount) System.out.println("Please enter a valid Course ID."); System.out.println("================================================="); } /** * Print student transcript * @param course all courses * @param courseCount total number of courses * @param marks all marks */ public void printTranscript(ArrayList<Course> course, int courseCount, ArrayList<Marks> marks) { int k; System.out.println("Name: " + fName + " " + lName); System.out.println("Student ID: " + id); System.out.println("Faculty: " + faculty); for(int i=0; i<courseCount; i++) { for(int l=0; l<course.get(i).lecGrp.size();l++) { for(int j=0; j<course.get(i).lecGrp.get(l).studIds.size();j++) { if(id == course.get(i).lecGrp.get(l).studIds.get(j)) { for(k=0; k<marks.size(); k++) { if(course.get(i).getCourseId()==marks.get(k).getCourseId()) break; } System.out.println("============================================================="); System.out.println("Course: " + course.get(i).getCourseName()); System.out.println("Exam Mark: " + marks.get(k).getExam()); System.out.println("Exam Percentage: " + course.get(i).exam.getPercentage()+"%"); System.out.println("Coursework Mark: " + marks.get(k).getCoursework()); System.out.println("Coursework Percentage: " + (100-course.get(i).exam.getPercentage()+"%")); marks.get(k).calcOverall(); marks.get(k).calcGradesO(); System.out.println("Total: " + marks.get(k).getOverall()); System.out.println("Grade: " + marks.get(k).getGradeO()); } } } } System.out.println("================================================="); } public String getName() { return (fName + " " + lName); } public String getNRIC() { return nric; } public void setNRIC(String nric) { this.nric = nric; } }
Python
UTF-8
8,691
2.96875
3
[ "Apache-2.0" ]
permissive
from __future__ import division import abc import collections import math import sys import numpy as np import tensorflow as tf EpsDelta = collections.namedtuple("EpsDelta", ["spent_eps", "spent_delta"]) class MomentsAccountant(object): """Privacy accountant which keeps track of moments of privacy loss. Note: The constructor of this class creates tf.Variables that must be initialized with tf.global_variables_initializer() or similar calls. MomentsAccountant accumulates the high moments of the privacy loss. It requires a method for computing differenital moments of the noise (See below for the definition). So every specific accountant should subclass this class by implementing _differential_moments method. Denote by X_i the random variable of privacy loss at the i-th step. Consider two databases D, D' which differ by one item. X_i takes value log Pr[M(D')==x]/Pr[M(D)==x] with probability Pr[M(D)==x]. In MomentsAccountant, we keep track of y_i(L) = log E[exp(L X_i)] for some large enough L. To compute the final privacy spending, we apply Chernoff bound (assuming the random noise added at each step is independent) to bound the total privacy loss Z = sum X_i as follows: Pr[Z > e] = Pr[exp(L Z) > exp(L e)] < E[exp(L Z)] / exp(L e) = Prod_i E[exp(L X_i)] / exp(L e) = exp(sum_i log E[exp(L X_i)]) / exp(L e) = exp(sum_i y_i(L) - L e) Hence the mechanism is (e, d)-differentially private for d = exp(sum_i y_i(L) - L e). We require d < 1, i.e. e > sum_i y_i(L) / L. We maintain y_i(L) for several L to compute the best d for any give e (normally should be the lowest L such that 2 * sum_i y_i(L) / L < e. We further assume that at each step, the mechanism operates on a random sample with sampling probability q = batch_size / total_examples. Then E[exp(L X)] = E[(Pr[M(D)==x / Pr[M(D')==x])^L] By distinguishign two cases of wether D < D' or D' < D, we have that E[exp(L X)] <= max (I1, I2) where I1 = (1-q) E ((1-q) + q P(X+1) / P(X))^L + q E ((1-q) + q P(X) / P(X-1))^L I2 = E (P(X) / ((1-q) + q P(X+1)))^L In order to compute I1 and I2, one can consider to 1. use an asymptotic bound, which recovers the advance composition theorem; 2. use the closed formula (like GaussianMomentsAccountant); 3. use numerical integration or random sample estimation. Dependent on the distribution, we can often obtain a tigher estimation on the moments and hence a more accurate estimation of the privacy loss than obtained using generic composition theorems. """ #__metaclass__ = abc.ABCMeta def __init__(self, total_examples=5040, moment_orders=1): """Initialize a MomentsAccountant. Args: total_examples: total number of examples. moment_orders: the order of moments to keep. """ assert total_examples > 0 self._total_examples = total_examples self._moment_orders = (moment_orders if isinstance(moment_orders, (list, tuple)) else range(1, moment_orders + 1)) self._max_moment_order = max(self._moment_orders) assert self._max_moment_order < 100, "The moment order is too large." self._log_moments = [tf.Variable(np.float64(0.0), trainable=False, name=("log_moments-%d" % moment_order)) for moment_order in self._moment_orders] def _compute_log_moment(self, num_examples=5040): """Compute high moment of privacy loss. Args: sigma: the noise sigma, in the multiples of the sensitivity. q: the sampling ratio. moment_order: the order of moment. Returns: log E[exp(moment_order * X)] """ q = tf.cast(num_examples, tf.float64) * 1.0 / self._total_examples mu_1, sigma_1 = 0, 4 # mean and standard deviation s_1 = np.random.normal(mu_1, sigma_1, 1000) mu_2, sigma_2 = 1, 4 # mean and standard deviation s_2 = np.random.normal(mu_2, sigma_2, 1000) s = (1-q)*s_1 + q*s_2 moment_1 =[0]*len(self._log_moments) moment_2 = [0]*len(self._log_moments) log_moment = [0] * len(self._log_moments) for i in range(len(self._log_moments)): for j in range(len(s_1)): moment_1[i] += ((s_1[j]/s[j])**self._moment_orders[i])/len(s_1) moment_2[i] += ((s[j] / s_1[j]) ** self._moment_orders[i]) / len(s_1) for i in range(len(self._log_moments)): log_moment[i] = math.log(abs(max(moment_1[i],moment_2[i]))) return log_moment def accumulate_privacy_spending(self, sigma=1, num_examples=5040): """Accumulate privacy spending. In particular, accounts for privacy spending when we assume there are num_examples, and we are releasing the vector (sum_{i=1}^{num_examples} x_i) + Normal(0, stddev=l2norm_bound*sigma) where l2norm_bound is the maximum l2_norm of each example x_i, and the num_examples have been randomly selected out of a pool of self.total_examples. Args: unused_eps_delta: EpsDelta pair which can be tensors. Unused in this accountant. sigma: the noise sigma, in the multiples of the sensitivity (that is, if the l2norm sensitivity is k, then the caller must have added Gaussian noise with stddev=k*sigma to the result of the query). num_examples: the number of examples involved. Returns: a TensorFlow operation for updating the privacy spending. """ q = tf.cast(num_examples, tf.float64) * 1.0 / self._total_examples moments_accum_ops = [] for i in range(len(self._log_moments)): moment = self._compute_log_moment() moments_accum_ops.append(tf.compat.v1.assign_add(self._log_moments[i], moment[i])) #print(moments_accum_ops) return tf.group(*moments_accum_ops) def _compute_delta(self, log_moments, eps): """Compute delta for given log_moments and eps. Args: log_moments: the log moments of privacy loss, in the form of pairs of (moment_order, log_moment) eps: the target epsilon. Returns: delta """ min_delta = 1.0 for moment_order, log_moment in log_moments: if math.isinf(log_moment) or math.isnan(log_moment): sys.stderr.write("The %d-th order is inf or Nan\n" % moment_order) continue if log_moment < moment_order * eps: min_delta = min(min_delta, math.exp(log_moment - moment_order * eps)) return min_delta def _compute_eps(self, log_moments, delta=1e-5): min_eps = float("inf") eps = [] for i in range(len(log_moments)): if math.isinf(log_moments[i]) or math.isnan(log_moments[i]): sys.stderr.write("The %d-th order is inf or Nan\n" % self._moment_orders[i]) continue min_eps = min(min_eps, (log_moments[i] - math.log(delta)) / self._moment_orders[i]) eps.append((log_moments[i] - math.log(delta)) / self._moment_orders[i]) order = eps.index(min(eps)) return min_eps,order def get_privacy_spent(self, target_eps=None, target_deltas=None): """Compute privacy spending in (e, d)-DP form for a single or list of eps. Args: target_eps: a list of target epsilon's for which we would like to compute corresponding delta value. target_deltas: a list of target deltas for which we would like to compute the corresponding eps value. Caller must specify either target_eps or target_delta. Returns: A list of EpsDelta pairs. """ assert (target_eps is None) ^ (target_deltas is None) eps_deltas = [] log_moments = self._log_moments log_moments_with_order = zip(self._moment_orders, log_moments) if target_eps is not None: for eps in target_eps: eps_deltas.append( EpsDelta(eps, self._compute_delta(log_moments_with_order, eps))) else: assert target_deltas for delta in target_deltas: eps_deltas.append( EpsDelta(self._compute_eps(log_moments_with_order, delta), delta)) return eps_deltas if __name__ == '__main__': accountant = MomentsAccountant() accountant.accumulate_privacy_spending() log_mo = accountant._compute_log_moment() eps = accountant._compute_eps(log_mo) print(eps)
Java
UTF-8
631
1.992188
2
[ "Apache-2.0" ]
permissive
package com.algorand.auction.rest.request; import java.math.BigDecimal; public class PlaceBidRequest { private String token; private BigDecimal amount; private int auctionId; public BigDecimal getAmount() { return amount; } public void setAmount(BigDecimal amount) { this.amount = amount; } public int getAuctionId() { return auctionId; } public void setAuctionId(int auctionId) { this.auctionId = auctionId; } public String getToken() { return token; } public void setToken(String token) { this.token = token; } }
PHP
UTF-8
1,181
2.515625
3
[ "MIT" ]
permissive
<?php /* |-------------------------------------------------------------------------- | Web Routes |-------------------------------------------------------------------------- | | Here is where you can register web routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | contains the "web" middleware group. Now create something great! | foreach ($video->comments as $coment { // code... echo $comment->body; } $videos=video::all(); foreach ($videos as $video) { // code... echo $video->title; echo $video->user->email.'<br/>'; echo "<hr/>"; } */ Use App\Video; Route::get('/',function() { return view ('welcome'); }); Auth::routes(); Route::get('/home', 'HomeController@index')->name('home'); //Rutes del controlador de Videos Route::get('/crear-video', array ( 'as'=>'createVideo', 'middleware'=>'auth', 'uses' =>'VideoController@createVideo' )); Route::post('/guardar-video', array ( 'as'=>'saveVideo', 'middleware'=>'auth', 'uses' =>'VideoController@saveVideo' )); Route::get('/miniatura/{filename}', array( 'as' => 'imageVideo', 'uses'=>'VideoController@displayImage' ));
Python
UTF-8
1,621
2.59375
3
[]
no_license
from ptpython import * from fake_useragent import UserAgent from selenium import webdriver from bs4 import BeautifulSoup as BS import requests import pandas as pd df = pd.read_excel('Final_Table.xlsx') url_1 = 'https://www.google.com/search?q=' url_2 = 'https://www.firmenwissen.de/index.html' ua = UserAgent() headers = {'User-Agent':str(ua.chrome)} Com_address1 = [] com_list = ['Maler Jäggle GmbH'] keyword = 'site:www.unternehmen24.info/Firmeninformationen/ ' driver = webdriver.Chrome('chromedriver_win32/chromedriver') driver.get(url_1) #for company in regNumber: for company in df.Beschreibung[1:]: inputElement = driver.find_element_by_name("q") inputElement.clear() inputElement.send_keys(keyword+company) inputElement.submit() try: results = driver.find_elements_by_css_selector('div.bkWMgd') link = results[0].find_element_by_tag_name("a") href = link.get_attribute("href") driver.get(href) companyInfor = driver.find_element_by_xpath('/html/body/div[7]/div[2]/div[1]').text companyIndex = df.Beschreibung[df.Beschreibung==company].index.tolist() regNumber = df.loc[companyIndex[0], 'Firma/Name'].split()[-2:] regNumber = regNumber[0] + ' ' + regNumber[1] if regNumber in companyInfor: address = driver.find_element_by_xpath('/html/body/div[7]/div[2]/div[1]/div[1]/table/tbody/tr[2]/td[3]').text print(address) driver.get(url_1) else: driver.get(url_2) except: driver.get(url_1)
SQL
UTF-8
2,289
3.53125
4
[]
no_license
CREATE TABLE IF NOT EXISTS `db_dev_doctor_labelling`.`user` ( `id` BIGINT NOT NULL AUTO_INCREMENT, `email` VARCHAR(255) NULL DEFAULT NULL, `name` VARCHAR(255) NULL DEFAULT NULL, `password` VARCHAR(255) NULL DEFAULT NULL, PRIMARY KEY (`id`)) ENGINE = InnoDB AUTO_INCREMENT = 2 DEFAULT CHARACTER SET = utf8 COLLATE = utf8_general_ci; CREATE TABLE IF NOT EXISTS `db_dev_doctor_labelling`.`profile` ( `id` BIGINT NOT NULL AUTO_INCREMENT, `name` VARCHAR(255) NULL DEFAULT NULL, PRIMARY KEY (`id`)) ENGINE = InnoDB AUTO_INCREMENT = 2 DEFAULT CHARACTER SET = utf8 COLLATE = utf8_general_ci; CREATE TABLE IF NOT EXISTS `db_dev_doctor_labelling`.`user_profiles` ( `user_id` BIGINT NOT NULL, `profiles_id` BIGINT NOT NULL, INDEX `FK7bauo77qnjbrc8yjqwrlc8o5k` (`profiles_id` ASC) VISIBLE, INDEX `FK4np1ktrt8iwtncc4otmhfd6yn` (`user_id` ASC) VISIBLE, CONSTRAINT `FK4np1ktrt8iwtncc4otmhfd6yn` FOREIGN KEY (`user_id`) REFERENCES `db_dev_doctor_labelling`.`user` (`id`), CONSTRAINT `FK7bauo77qnjbrc8yjqwrlc8o5k` FOREIGN KEY (`profiles_id`) REFERENCES `db_dev_doctor_labelling`.`profile` (`id`)) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8 COLLATE = utf8_general_ci; CREATE TABLE IF NOT EXISTS `db_dev_doctor_labelling`.`cases` ( `id` BIGINT NOT NULL AUTO_INCREMENT, `date_create` DATETIME NULL DEFAULT NULL, `electronic_health_record` TEXT NULL DEFAULT NULL, `state` VARCHAR(255) NULL DEFAULT NULL, `time_to_label` DATETIME NULL DEFAULT NULL, `doctor_id` BIGINT NULL DEFAULT NULL, `time_in_minutes_to_label` BIGINT NULL DEFAULT NULL, PRIMARY KEY (`id`), INDEX `FK3xctv7vqucw0q1nv8ni2eoii1` (`doctor_id` ASC) VISIBLE, CONSTRAINT `FK3xctv7vqucw0q1nv8ni2eoii1` FOREIGN KEY (`doctor_id`) REFERENCES `db_dev_doctor_labelling`.`user` (`id`)) ENGINE = InnoDB AUTO_INCREMENT = 4 DEFAULT CHARACTER SET = utf8 COLLATE = utf8_general_ci; CREATE TABLE IF NOT EXISTS `db_dev_doctor_labelling`.`cases_label` ( `case_id` BIGINT NOT NULL, `label_id` VARCHAR(255) NULL DEFAULT NULL, INDEX `FK5p7bes35n0qk69s9m5c7m4dpu` (`case_id` ASC) VISIBLE, CONSTRAINT `FK5p7bes35n0qk69s9m5c7m4dpu` FOREIGN KEY (`case_id`) REFERENCES `db_dev_doctor_labelling`.`cases` (`id`)) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8 COLLATE = utf8_general_ci
JavaScript
UTF-8
1,258
2.84375
3
[]
no_license
import { YoutubeApi } from './YoutubeApi.js'; import { Card } from './Card.js'; import { Section } from './Section.js'; import { searchForm, elementsList, input, keywordElem } from './constants.js'; //создание экземпляра класса YoutubeApi export const youtubeApi = new YoutubeApi ({ baseUrl: 'https://www.googleapis.com/youtube/v3/search', headers: { Accept: 'application/json', 'Content-Type': 'application/json' } }) //создание карточки const createCardFunction = (data) => { const card = new Card({data, }, '.cards__template') const element = card.generateCard() cardsList.addItem(element) } //создание экземпляра класса для отрисовки карточек на странице const cardsList = new Section ({ renderer: (data => { createCardFunction(data) }) }, elementsList) const handleSearchVideos = (keyword) => { youtubeApi.getVideos(keyword) .then((res) => { cardsList.emptyContainer() cardsList.renderItems(res.items) }) .catch((err) => console.log(err)) } searchForm.addEventListener('submit', (e) => { e.preventDefault() const keyword = input.value handleSearchVideos(keyword) keywordElem.textContent = keyword })
Markdown
UTF-8
10,729
2.84375
3
[]
no_license
title: PyCharm - HotKeys! --- body: *** ###Работа с закладками: | | |---------------------------------------------------------------------------------------| |Поставить или снять закладку |**F11** | |Аналогично с присвоением буквы или цифры |**Ctrl + F11** | |Переход к закладке (удаление — клавишей Delete) |**Shift + F11** | |Быстрый переход к закладке с присвоенным числом |**Ctrl + Число**| *** ###Редактирование: | | |---------------------------------------------------------------------------------------| |Отменить последнее действие |**Ctrl + Z**| |Отменить последнюю отмену действия |**Ctrl + Shift + Z**| |Расширенная вставка из буфера обмена (с историей) |**Ctrl + Shift + V**| |Инкрементальное выделение выражения |**Ctrl (+ Shift) + W**| |Перемещение между словами |**Ctrl + влево/вправо**| |Прокрутка кода без изменения позиции курсора |**Ctrl + вверх/вниз**| |Переход в начало/конец файла |**Ctrl + Home/End**| |Удаление строки, отличие в том, где потом окажется курсор |**Shift + Del (Ctrl + Y)**| |Удалить от текущей позиции до конца слова |**Ctrl + Del**| |Удалить от текущей позиции до начала слова |**Ctrl + Backspace**| |Дублировать текущую строку |**Ctrl + D**| |Увеличить / уменьшить текущий отступ |**Tab / Shift + Tab**| |Выравнивание отступов в коде |**Ctrl + Alt + I**| |Приведение кода в соответствие Code-Style |**Ctrl + Alt + L**| |Закомментировать/раскомментировать текущую строку |**Ctrl + /**| |Закомментировать/раскомментировать выделенный код |**Ctrl + Shift + /**| |Фолдинг, свернуть/развернуть |**Ctrl + -/+**| |Фолдинг, свернуть/развернуть все |**Ctrl + Shift + -/+**| |Сделать текущий скоуп сворачиваемым и свернуть его |**Ctrl + Shift + .**| |Сделать текущий скоуп несворачиваемым |**Ctrl + .**| |Замена в тексте |**Ctrl + R**| |Замена во всех файлах |**Ctrl + Shift + R**| *** ###Работа с окнами, вкладками: | | |---------------------------------------------------------------------------------------| |Перемещение между вкладками |**Alt + влево/вправо**| |Закрыть вкладку |**Ctrl + F4**| |Открытие/закрытие окон Project, Structure, Changes и тд |**Altl + число**| |Переключение между вкладками и окнами |**Ctrl + Tab**| |Закрыть активное окно |**Shift + Esс**| |Открыть последнее закрытое окно |**F12**| |Zoom, если он был вами настроен |**Ctrl + колесико мыши**| *** ###Работа с поиском: | | |---------------------------------------------------------------------------------------| |Быстрый поиск по всему проекту |**Дважды Shift**| |Быстрый поиск по настройкам, действиям и тд |**Ctr + Shift + A**| |Перейти к следующему/предыдущему методу |**Alt + вниз/вверх**| |Перемещение к началу и концу текущего скоупа |**Ctrl + [ и Ctrl + ]**| |Поиск в файле |**Ctrl + F**| |Поиск по всем файлам (переход — F4) |**Ctr + Shift + F**| |Искать слово под курсором |**Ctrl + F3**| |Искать вперед/назад |**F3 / Shift + F3**| |Переход к строке или строке:номеру_символа |**Ctrl + G**| |Список методов с переходом к их объявлению |**Ctrl + F12**| |Список недавно открытых файлов с переходом к ним |**Ctrl + E**| |Список недавно измененных файлов с переходом к ним |**Ctrl + Shift + E**| |Иерархия наследования текущего класса и переход по ней |**Ctrl + H**| |Иерархия вызовов выбранного метода |**Ctrl + Alt + H**| |Поиска класса по имени и переход к нему |**Ctrl + N**| |Поиск файла по имени и переход к нему |**Ctrl + Shift + N**| |Перейти к объявлению переменной, класса, метода |**Ctrl + B**| |Перейти к реализации |**Ctrl + Alt + B**| |Определить тип и перейти к его реализации |**Ctrl + Shift + B**| |Перемещение назад по стеку поиска |**Shift + Alt + влево**| |Перемещение вперед по стеку поиска |**Shift + Alt + вправо**| |Переход к следующей / предыдущей ошибке |**F2 / Shift + F2**| |Найти все места, где используется метод / переменная |**Shift + Alt + 7**| |Как предыдущий пункт, только во всплывающем окне |**Ctrl + Alt + 7**| *** ###Генерация кода и рефакторинг: | | |---------------------------------------------------------------------------------------| |Полный автокомплит |**Ctrl + Space**| |Автокомплит с фильтрацией по подходящему типу |**Ctrl + Shift + Space**| |Простой автокомплит по словам, встречающимся в проекте |**Alt + /**| |Реализовать интерфейс |**Ctrl + I**| |Переопределить метод родительского класса |**Ctrl + O**| |Генерация шаблонного кода (обход по итератору и тд) |**Ctrl + J**| |Обернуть выделенный код в один из шаблонов |**Ctrl + Alt + J**| |Генератор кода — сеттеров, зависимостей в pom.xml и тд |**Alt + Insert**| |Переименование переменной, класса и тд во всем коде |**Shift + F6**| |Изменение сигнатуры метода во всем коде |**Ctrl + F6**| |Перемещение метода, класса или пакета |**F6**| |Создать копию класса, файла или каталога |**F5**| |Создать копию класса в том же пакете |**Shift + F5**| |Безопасное удаление класса, метода или атрибута |**Alt + Delete**| |Выделение метода |**Ctrl + Alt + M**| |Выделение переменной |**Ctrl + Alt + V**| |Выделение атрибута |**Ctrl + Alt + F**| |Выделение константы (public final static) |**Ctrl + Alt + C**| |Выделение аргумента метода |**Ctrl + Alt + P**| |Инлайнинг метода, переменной, аргумента или константы |**Ctrl + Alt + N**| |Оптимизация импортов |**Ctrl + Alt + O**| ***
Python
UTF-8
1,877
3.140625
3
[ "BSD-3-Clause" ]
permissive
"""Univariate repeated measures ANOVA Rutherford (2001) Examples, cross-checked results: factorial anova Independent Measures (p. 53): SS df MS MS(denom) df(denom) F p ------------------------------------------------------------------------- A 432.00 1 432.00 9.05 42 47.75*** < .001 B 672.00 2 336.00 9.05 42 37.14*** < .001 A x B 224.00 2 112.00 9.05 42 12.38*** < .001 ------------------------------------------------------------------------- Total 1708.00 47 Repeated Measure (p. 86): SS df MS MS(denom) df(denom) F p ------------------------------------------------------------------------- A 432.00 1 432.00 10.76 7 40.14*** < .001 B 672.00 2 336.00 11.50 14 29.22*** < .001 A x B 224.00 2 112.00 6.55 14 17.11*** < .001 ------------------------------------------------------------------------- Total 1708.00 47 """ import numpy as np from eelbrain import * Y = np.array([ 7, 3, 6, 6, 5, 8, 6, 7, 7, 11, 9, 11, 10, 10, 11, 11, 8, 14, 10, 11, 12, 10, 11, 12, 16, 7, 11, 9, 10, 11, 8, 8, 16, 10, 13, 10, 10, 14, 11, 12, 24, 29, 10, 22, 25, 28, 22, 24]) A = Factor([1, 0], repeat=3 * 8, name='A') B = Factor(range(3), tile=2, repeat=8, name='B') # Independent Measures: subject = Factor(range(8 * 6), name='subject', random=True) print(test.anova(Y, A * B + subject(A % B), title="Independent Measures:")) # Repeated Measure: subject = Factor(range(8), tile=6, name='subject', random=True) print(test.anova(Y, A * B * subject, title="Repeated Measure:"))
Java
UTF-8
509
1.9375
2
[]
no_license
package com.floatinvoice.business.dao; import com.floatinvoice.messages.BaseMsg; import com.floatinvoice.messages.RegistrationStep2CorpDtlsMsg; import com.floatinvoice.messages.RegistrationStep3UserPersonalDtlsMsg; public interface RegistrationDao { BaseMsg registerSignInInfo(String userEmail, String password, String confirmedPassword, int regCode); BaseMsg registerOrgInfo(RegistrationStep2CorpDtlsMsg msg); BaseMsg registerUserBankInfo (RegistrationStep3UserPersonalDtlsMsg msg); }
Java
UTF-8
2,200
2.453125
2
[]
no_license
package ajax.jquery.autocomplete; import java.io.IOException; import java.util.List; 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 ajax.model.dao.AjaxDAO; /** * Servlet implementation class JqueryAjaxAutoCompleteServlet */ @WebServlet("/jquery/autoComplete") public class JqueryAjaxAutoCompleteServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public JqueryAjaxAutoCompleteServlet() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //1.인코딩 request.setCharacterEncoding("utf-8"); response.setContentType("text/csv; charset=utf-8"); //2.파라미터핸들링 String srchName = request.getParameter("srchName"); System.out.println("srchName="+srchName); //유효성 검사 if(srchName.trim().isEmpty()) return; //3.업무로직 List<String> nameList = new AjaxDAO().selectByName(srchName); //csv 작업 StringBuilder csv = new StringBuilder(); if(nameList!=null && !nameList.isEmpty()){ for(int i=0; i< nameList.size(); i++){ if(i!=0) csv.append(","); csv.append(nameList.get(i)); } } //4.view단 처리: csv형태로 전송 response.getWriter().append(csv); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub doGet(request, response); } }
TypeScript
UTF-8
3,117
2.546875
3
[ "MIT" ]
permissive
import * as GamesConfig from './games.config.json'; import {Module} from '../../libs/module'; import Game2048 from './2048/2048.game'; import BlockrainGame from "./blockrain/blockrain.game"; import TowerGame from './tower/tower.game'; import * as $ from 'jquery'; import template from './games.template.html'; export default class GamesModule extends Module { protected events = { 'games.prev': {control: 'up', title: 'بازی قبلی', icon: 'up'}, 'games.next': {control: 'down', title: 'بازی بعدی', icon: 'bottom'}, 'games.enter': {control: 'enter', title: 'انتخاب', icon: 'enter'}, }; constructor(config?, layoutInstance?, moduleType?: string) { super(config, layoutInstance, moduleType); const self = this; this.events = this.prepareControls(); this.render(GamesConfig, () => { self.registerKeyboardInputs(); }); return this; } reInit() { this.layoutInstance.prepareUnloadModule(this); this.registerKeyboardInputs(); this.render(GamesConfig); } render(games, callback?) { this.templateHelper.render(template, {items: games}, this.$el, 'html', () => { if (typeof callback === 'function') callback(games); }); } setActive(which: string): void { const $current = $('.game-items').find('li.active').length ? $('.game-items li.active') : $('.game-items li:first'); let $el; this.templateHelper.removeClass('active', $current); if (which === 'next') { if ($current.next().length) { $el = $current.next(); } else { $el = $current.parents('ul:first').find('li:first'); } } else { if ($current.prev().length) { $el = $current.prev(); } else { $el = $current.parents('ul:first').find('li:last'); } } this.templateHelper.addClass('active', $el); } loadGame() { const $current = $('.game-items li.active'); if ($current.length < 1) { return false; } const game = $current.attr('data-game').toString(); let gameObject: any = null; switch (game) { case '2048': gameObject = Game2048; break; case 'blockrain': gameObject = BlockrainGame; break; case 'tower': gameObject = TowerGame; } new gameObject(this); this.input.removeEvent('back,backspace', {key: 'module.exit'}); } registerKeyboardInputs() { const self = this; this.input.addEvent('up', false, this.events['games.prev'], () => { self.setActive('prev'); }); this.input.addEvent('down', false, this.events['games.next'], () => { self.setActive('next'); }); this.input.addEvent('enter', false, this.events['games.enter'], () => { self.loadGame(); }); } }
C++
UTF-8
223
2.78125
3
[]
no_license
#pragma once template <class Pred, class It> size_t CountIf(It first, const It last, Pred const & pred) { size_t result = 0; for (; first != last; ++first) { if (pred(*first)) { ++result; } } return result; }
Python
UTF-8
297
4.125
4
[]
no_license
# To take input from user we use input() function name = input("Enter your name: ") print("Hello "+name) # input(Always takes input as a string) age=input("Enter your age: ") # This age is in String print("Your age is "+age) # Agr age int mn huta tou ye concatenate ni huta
Java
UTF-8
620
2.90625
3
[]
no_license
import java.io.*; /****************************************************** The main class used to test LexemeGenerator. ******************************************************/ class main { public static void main(String[] args) throws IOException { File f = null; if(args.length <1) { System.err.println("Usage: main <source_code_file>"); System.exit(1); } else { f = new File(args[0]); if(!f.exists()) { throw new IOException("Source file does not exist."); } } LexemeGenerator lg = new LexemeGenerator(f); Parser p = new Parser(lg); p.output(System.out); } }
C++
UTF-8
2,881
3.59375
4
[]
no_license
#include<iostream> #include<vector> #include<map> #include<math.h> using namespace std; class Apothecary{ public: vector<int> balance(int W){ //// (1) check about how many objects are needed to measure the weight // proposition: // x can be represented just by {i_1, ..., i_n} // s.t \sum_{i=1}^{n-1}3^i < x <= \sum_{i=1}^{n}3^i int sum=0, N=0; while(sum < W){ sum += (int)pow(3, N++); } //// (2) create dictionary // key: \sum_{i=0}^{n}(3^i * \delta(bits[i]=1)) // s.t. \delta takes 1 if given condition would satisfied, or takes 0. // value: a condition of bits map<int,int> dict; for(int i=0; i < (1 << N); ++i){ int sum = 0; for(int j=0; j<=N; ++j){ if( i & (1 << j) ){ sum += pow(3, j); } } dict[ sum ] = i; } //// (3) balance the apothecary // these two variables represent the presences of items using N-bits (from right) int pLeft = 0, pRight = 0; // these two variables represent the weight of a side, respectivily int wLeft = W, wRight = 0; // using reverse_iterator, // scan dictionary from the recode having largest key to the one having smallest key map<int,int>::reverse_iterator i = dict.rbegin(); while( wLeft != wRight ){ if( wLeft < wRight ){ // proceeeding until left side has more weight than right side for(; i->first + wLeft >= wRight && i != dict.rend(); ++i){} i--; // ##### why can we know that the bits used by i->first haven't used yet ?? ##### wLeft += i->first; pLeft |= i->second; }else{ for(; i->first + wRight >= wLeft && i != dict.rend(); ++i){} i--; // ##### why can we know that the bits used by i->first haven't used yet ?? ##### wRight += i->first; pRight |= i->second; } } //// (3) create a vector representing items vector<int> items; for(int i=N-1; i>=0; --i){ if( pLeft & (1<<i) ){ items.push_back( -(int)pow(3,i) ); } } for(int i=0; i<N; ++i){ if( pRight & (1<<i) ){ items.push_back( (int)pow(3,i) ); } } return items; }; }; int main(){ Apothecary ap = Apothecary(); for(int i=0; i<100; ++i){ vector<int> items = ap.balance(i); printf("%d:\t", i); int right=0, left=i; for(int j=0; j<items.size(); ++j){ printf("%d, ", items[j]); if(items[j]>0){ right += items[j]; }else{ left -= items[j]; } } printf("\t::%d=%d\n", left, right); } }
C#
UTF-8
538
2.796875
3
[]
no_license
using BooleanRegisterUtilityAPI.BoolParsingToken.LogicBlock; namespace BooleanRegisterUtilityAPI { public class LessDuoLogic : DoubleLogicBlock { public LessDuoLogic(LogicBlock left, LogicBlock right) : base(left, right) { } public override bool ComputedBoolean(bool vl, bool vr) { return BoolOperationLogic.ALessB(vl, vr); } public override string ToString() { return string.Format(" ( {0} < {1} ) ", m_left, m_right); } } }
Python
UTF-8
3,544
3.09375
3
[]
no_license
class Constellation(): def __init__(self): pass def __str__(self): returnStr = f""" Name : {self.GetName()}\n IAU Abbriviation : {self.GetIAU()}\n Right ascension start in time : {self.GetRAStartTime()}\n Right ascension end in time : {self.GetRAEndTime()}\n Right ascension start in degree : {self.GetRAStartDeg()}\n Right ascension end in degree : {self.GetRAEndDeg()}\n Declination start : {self.GetDeclinationStart()}\n Declination end : {self.GetDeclinationEnd()}\n Genitive : {self.GetGenitive()}\n Meaning : {self.GetMeaning()}\n Brightest Star : {self.GetBrightestStar()}\n """ return returnStr #------------------------------------------------------------- __name = None def SetName(self, name): self.__name = name def GetName(self): return self.__name #------------------------------------------------------------- __IAU_Abbreviation = None def SetIAU(self, IAU): self.__IAU_Abbreviation = IAU def GetIAU(self): return self.__IAU_Abbreviation #------------------------------------------------------------- __rightAscensionStartInTime = None def SetRAStartTime(self, raStartTime): self.__rightAscensionStartInTime = raStartTime def GetRAStartTime(self): return self.__rightAscensionStartInTime #------------------------------------------------------------- __rightAscensionEndInTime = None def SetRAEndTime(self, raEndTime): self.__rightAscensionEndInTime = raEndTime def GetRAEndTime(self): return self.__rightAscensionEndInTime #------------------------------------------------------------- __rightAscensionStartInDegree = None def SetRAStartDeg(self, raStartDeg): self.__rightAscensionStartInDegree = raStartDeg def GetRAStartDeg(self): return self.__rightAscensionStartInDegree #------------------------------------------------------------- __rightAscensionEndInDegree = None def SetRAEndDeg(self, raEndDeg): self.__rightAscensionEndInDegree = raEndDeg def GetRAEndDeg(self): return self.__rightAscensionEndInDegree #------------------------------------------------------------- __declinationStart = None def SetDeclinationStart(self, decStart): self.__declinationStart = decStart def GetDeclinationStart(self): return self.__declinationStart #------------------------------------------------------------- __declinationEnd = None def SetDeclinationEnd(self, decEnd): self.__declinationEnd = decEnd def GetDeclinationEnd(self): return self.__declinationEnd #------------------------------------------------------------- __genitive = None def SetGenitive(self, gen): self.__genitive = gen def GetGenitive(self): return self.__genitive #------------------------------------------------------------- __meaning = None def SetMeaning(self, meaning): self.__meaning = meaning def GetMeaning(self): return self.__meaning #------------------------------------------------------------- __brightestStar = None def SetBrightestStar(self, brStar): self.__brightestStar = brStar def GetBrightestStar(self): return self.__brightestStar
Java
UTF-8
3,910
2.15625
2
[]
no_license
package tech.qijin.cell.im.test; import org.junit.Assert; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import tech.qijin.cell.im.base.*; import tech.qijin.cell.im.base.MessageSendBo; import tech.qijin.cell.im.db.model.ImMessage; import tech.qijin.cell.im.service.CellImMessageService; import tech.qijin.util4j.lang.exception.ValidateException; import tech.qijin.util4j.utils.DateUtil; import java.util.List; /** * @author michealyang * @date 2019-12-16 * @relax: 开始眼保健操 ←_← ↓_↓ →_→ ↑_↑ */ public class CellImMessageServiceTest extends BaseTest { @Autowired private CellImMessageService cellImMessageService; public static long uid = 233333; public static long peerUid = 666666; @Test public void testSendMessage() { MessageSendBo messageSendBo = getMessageSendBo(MsgType.TEXT); ImMessage imMessage = cellImMessageService.sendMessage(messageSendBo); log.info("imMessage={}", imMessage); } /** * 测试禁止发送消息的场景 */ @Test(expected = ValidateException.class) public void testSendMessageForbidden() { MessageSendBo messageSendBo = getMessageSendBo(MsgType.TEXT); ImMessage imMessage = cellImMessageService.sendMessage(messageSendBo); log.info("imMessage={}", imMessage); } /** * 测试假发的逻辑 */ @Test() public void testSendMessageSilent() { MessageSendBo messageSendBo = getMessageSendBo(MsgType.TEXT); messageSendBo.setSilent(true); ImMessage imMessage = cellImMessageService.sendMessage(messageSendBo); Assert.assertNotNull(imMessage); Assert.assertEquals((long) imMessage.getStatus(), 1L); log.info("imMessage={}", imMessage); } @Test public void testListHistoryMessage() { List<CellImMessageBo> imMessages = cellImMessageService.listMessageHistory(uid, peerUid, 1590334661329000001L, 40); log.info("imMessages={}", imMessages); } @Test public void testListUnreadMessage() { List<CellImMessageBo> imMessages = cellImMessageService.listMessageNew(uid, peerUid, 1590334661329000001L, 20); log.info("messageBOs={}", imMessages); } @Test public void testDelMessage() { // 先发送一条消息,再删除 MessageSendBo messageSendBo = getMessageSendBo(MsgType.TEXT); ImMessage imMessage = cellImMessageService.sendMessage(messageSendBo); Assert.assertNotNull(imMessage); log.info("imMessage={}", imMessage); boolean res = cellImMessageService.delMessage(uid, peerUid, imMessage.getMsgId()); Assert.assertTrue(res); } @Test public void testDelMessage2() { // 先发送一条消息,再删除 MessageSendBo messageSendBo = getMessageSendBo(MsgType.TEXT); ImMessage imMessage = cellImMessageService.sendMessage(messageSendBo); Assert.assertNotNull(imMessage); log.info("imMessage={}", imMessage); boolean res = cellImMessageService.delMessage(uid, peerUid, imMessage.getMsgId()); Assert.assertTrue(res); res = cellImMessageService.delMessage(peerUid, uid, imMessage.getMsgId()); Assert.assertTrue(res); } private MessageSendBo getMessageSendBo(MsgType msgType) { return MessageSendBo.builder() .uid(uid) .toUid(peerUid) .msgType(msgType) .content(getContent(msgType)) .build(); } private AbstractContent getContent(MsgType msgType) { switch (msgType) { case TEXT: default: ContentText contentText = new ContentText(); contentText.setText(DateUtil.formatStr(DateUtil.now(), DateUtil.YYYYMMDDHHMMSS)); return contentText; } } }
Java
UTF-8
387
1.890625
2
[]
no_license
package com.dao; import org.springframework.data.domain.Page; import org.springframework.data.domain.Pageable; import org.springframework.data.jpa.repository.JpaRepository; import com.entity.Note; public interface NoteDao extends JpaRepository<Note, Integer> { public Note findById(Integer id); public Page<Note> findAllByCategoryName(String categoryName, Pageable pageable); }
Shell
UTF-8
314
2.515625
3
[ "MIT" ]
permissive
# -*- mode: sh -*- # vim: set ft=sh: function zpwrFasdFList(){ fasd -f |& perl -lne 'for (reverse <>){do{($_=$2)=~s@$ENV{HOME}@~@;print} if m{^\s*(\S+)\s+(\S+)\s*$}}' | eval "$ZPWR_FZF -m --no-sort --border $FZF_CTRL_T_OPTS" | perl -pe 's@^([~]*)([^~].*)$@$1"$2"@;s@\s+@ @g;' } zpwrFasdFList "$@"
Java
UTF-8
9,575
2.171875
2
[]
no_license
package com.yunda.jcbm.webservice; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import org.apache.log4j.Logger; import org.springframework.stereotype.Service; import com.yunda.frame.util.ExceptionUtil; import com.yunda.frame.util.JSONUtil; import com.yunda.frame.util.StringUtil; import com.yunda.jcbm.jcgx.entity.JcgxBuild; import com.yunda.jcbm.jcgx.entity.JcxtflFault; import com.yunda.jcbm.jcgx.manager.JcgxBuildQueryManager; import com.yunda.jcbm.jcgx.manager.JcxtflFaultManager; import com.yunda.jcbm.jcxtfl.entity.JcxtflBuild; /** * <li>标题:机车检修管理信息系统 * <li>说明:机车组成 * <li>http://localhost:8080/CoreFrame/ydservices/JcgxBuildService?wsdl * <li>创建人: 何东 * <li>创建日期: 2016-5-19 上午11:10:16 * <li>修改人: * <li>修改日期: * <li>修改内容: * <li>版权: Copyright (c) 2008 运达科技公司 */ @Service(value="jcgxBuildWS") public class JcgxBuildService implements IJcgxBuildService { /** 日志工具 */ private Logger logger = Logger.getLogger(getClass().getName()); /** 机车构型查询业务类 */ @Resource private JcgxBuildQueryManager jcgxBuildQueryManager; /** 分类编码故障现象业务类 */ @Resource private JcxtflFaultManager jcxtflFaultManager; /** * <li>方法名:通过分类编码获取故障现象数据 * <li>@param jsonObject json对象参数 * <li>@return * <li>返回类型:String * <li>说明: * <li>创建人:何东 * <li>创建日期:2016-5-16 * <li>修改人: * <li>修改日期: */ public String getFlbmFault(String jsonObject) throws Exception { List<Map<String, Object>> faultList = new ArrayList<Map<String,Object>>(); Map<String, Object> map = new HashMap<String, Object>(); String treeStr = ""; try { String searchJson = StringUtil.nvlTrim(jsonObject, "{}"); JcxtflFault entity = JSONUtil.read(searchJson, JcxtflFault.class); if (entity != null) { faultList = jcgxBuildQueryManager.getFlbmFault(entity); } }catch (RuntimeException e) { ExceptionUtil.process(e, logger); map.put("flag", false); map.put("message", "操作失败!"); } finally{ if (map.get("flag") != null && !(Boolean)map.get("flag")) { treeStr = JSONUtil.write(map); } else { treeStr = JSONUtil.write(faultList); } } return treeStr; } /** * <li>方法名:根据车型及机车构型主键获取下级树节点列表 * <li>@param jsonObject json对象参数 * <li>@return * <li>返回类型:String * <li>说明: * <li>创建人:何东 * <li>创建日期:2016-5-16 * <li>修改人: * <li>修改日期: */ public String getJcgxBuildTree(String jsonObject) throws Exception { List<Map<String, Object>> children = new ArrayList<Map<String,Object>>(); Map<String, Object> map = new HashMap<String, Object>(); String treeStr = ""; try { String searchJson = StringUtil.nvlTrim(jsonObject, "{}"); JcgxBuild entity = JSONUtil.read(searchJson, JcgxBuild.class); //JcgxBuild entity = entities.length > 0 ? entities[0] : null; // 取第一条提票信息 if (entity != null) { String fjdID = entity.getFjdID(); String sycx = entity.getSycx(); String useType = entity.getUseType(); children = jcgxBuildQueryManager.getJcgxBuildTree(fjdID, sycx, useType); } }catch (RuntimeException e) { ExceptionUtil.process(e, logger); map.put("flag", false); map.put("message", "操作失败!"); } finally{ if (map.get("flag") != null && !(Boolean)map.get("flag")) { treeStr = JSONUtil.write(map); } else { treeStr = JSONUtil.write(children); } } return treeStr; } /** * <li>方法名:保存分类编码的故障现象 * <li>@param jsonObject json对象参数 * <li>@return * <li>返回类型:String * <li>说明: * <li>创建人:何东 * <li>创建日期:2016-5-16 * <li>修改人: * <li>修改日期: */ public String saveFlbmFault(String jsonObject) throws Exception { Map<String, Object> map = new HashMap<String, Object>(); String treeStr = ""; try { String searchJson = StringUtil.nvlTrim(jsonObject, "{}"); JcxtflFault[] entitys = JSONUtil.read(searchJson, JcxtflFault[].class); if (entitys != null && entitys.length > 0) { map = jcxtflFaultManager.saveFlbmFault(entitys); } }catch (RuntimeException e) { ExceptionUtil.process(e, logger); map.put("flag", false); map.put("message", "操作失败!"); } finally{ if (map.get("success") != null && (Boolean)map.get("success")) { map.put("flag", true); map.put("message", "操作成功!"); } else { map.put("flag", false); map.put("message", map.get("errMsg")); } map.remove("errMsg"); map.remove("success"); treeStr = JSONUtil.write(map); } return treeStr; } /** * <li>说明:根据车型及机车构型获取机车组成列表 * <li>创建人:张迪 * <li>创建日期:2016-9-9 * <li>修改人: * <li>修改日期: * <li>修改内容: * @param jsonObject json对象参数 * @return 分类名称树节点列表 * @throws Exception */ public String getJczcmcBuildTree(String jsonObject) throws Exception { List<Map<String, Object>> children = new ArrayList<Map<String,Object>>(); Map<String, Object> map = new HashMap<String, Object>(); String treeStr = ""; try { String searchJson = StringUtil.nvlTrim(jsonObject, "{}"); JcxtflBuild entity = JSONUtil.read(searchJson, JcxtflBuild.class); if (entity != null) { children = jcgxBuildQueryManager.getJczcmcBuildTreeAll(entity); } }catch (RuntimeException e) { ExceptionUtil.process(e, logger); map.put("flag", false); map.put("message", "操作失败!"); } finally{ if (map.get("flag") != null && !(Boolean)map.get("flag")) { treeStr = JSONUtil.write(map); } else { treeStr = JSONUtil.write(children); } } return treeStr; } /** * <li>说明:获取上级部件分类简称 * <li>创建人:张迪 * <li>创建日期:2016-9-9 * <li>修改人: * <li>修改日期: * <li>修改内容: * @param jsonObject json对象参数 * @return 上级部件分类简称 * @throws Exception */ public String getSjbjList(String jsonObject) throws Exception { List<Map<String, Object>> sjbjList = new ArrayList<Map<String,Object>>(); Map<String, Object> map = new HashMap<String, Object>(); String treeStr = ""; try { String searchJson = StringUtil.nvlTrim(jsonObject, "{}"); JcgxBuild entity = JSONUtil.read(searchJson, JcgxBuild.class); sjbjList = jcgxBuildQueryManager.getSjbjList(entity); }catch (RuntimeException e) { ExceptionUtil.process(e, logger); map.put("flag", false); map.put("message", "操作失败!"); } finally{ if (map.get("flag") != null && !(Boolean)map.get("flag")) { treeStr = JSONUtil.write(map); } else { treeStr = JSONUtil.write(sjbjList); } } return treeStr; } /** * <li>说明:获取所选部件位置分类简称 * <li>创建人:张迪 * <li>创建日期:2016-9-10 * <li>修改人: * <li>修改日期: * <li>修改内容: * @param jsonObject json对象参数 * @return 部件分类简称 * @throws Exception */ public String getBjwzList(String jsonObject) throws Exception { List<Map<String, Object>> sjbjList = new ArrayList<Map<String,Object>>(); Map<String, Object> map = new HashMap<String, Object>(); String treeStr = ""; try { String searchJson = StringUtil.nvlTrim(jsonObject, "{}"); JcgxBuild[] entityList = JSONUtil.read(searchJson, JcgxBuild[].class); sjbjList = jcgxBuildQueryManager.getBjwzList(entityList); }catch (RuntimeException e) { ExceptionUtil.process(e, logger); map.put("flag", false); map.put("message", "操作失败!"); } finally{ if (map.get("flag") != null && !(Boolean)map.get("flag")) { treeStr = JSONUtil.write(map); } else { treeStr = JSONUtil.write(sjbjList); } } return treeStr; } }
Markdown
UTF-8
1,780
4.03125
4
[]
no_license
# 797. All Paths From Source to Target #### [link](https://leetcode.com/problems/all-paths-from-source-to-target/) #### Description Given a directed, acyclic graph of `N` nodes. Find all possible paths from node `0` to node `N-1`, and return them in any order. The graph is given as follows: the nodes are 0, 1, ..., graph.length - 1. graph[i] is a list of all nodes j for which the edge (i, j) exists. #### Example: ``` Input: [[1,2], [3], [3], []] Output: [[0,1,3],[0,2,3]] Explanation: The graph looks like this: 0--->1 | | v v 2--->3 There are two paths: 0 -> 1 -> 3 and 0 -> 2 -> 3. ``` #### Note: * The number of nodes in the graph will be in the range `[2, 15]` * You can print different paths in any order, but you should keep the order of nodes inside one path. ## DFS ```java class Solution { public List<List<Integer>> allPathsSourceTarget(int[][] graph) { if(graph == null || graph.length == 0){ return new ArrayList<>(); } List<List<Integer>> ans = new ArrayList<>(); List<Integer> tmp = new ArrayList<>(); tmp.add(0); dfs(ans, tmp, graph, 0); return ans; } private void dfs(List<List<Integer>> ans, List<Integer> tmp, int[][] graph, int now){ if(now == graph.length - 1){ ans.add(new ArrayList<>(tmp)); return; } for(int next : graph[now]){ tmp.add(next); dfs(ans, tmp, graph, next); tmp.remove(tmp.size() - 1); } } } ``` ### Time complexity * O(n * 2^n) * for each path from source to destination, at most we can choose each node to appear or not ### Space complexity * O(n * 2^n) ### Remark * acyclic graph, no need to keep track of visit array
JavaScript
UTF-8
932
2.96875
3
[]
no_license
import React, {Component} from 'react'; class Counter extends Component { state = { count: 0 }; increaseHandler = () => { const count = this.state.count + 1; console.log("increasing count") this.setState ({ count }) } decreaseHandler = () => { const count = this.state.count -1; console.log("decreasing count") this.setState ({ count }) } render() { return ( <div className="container"> <div className="row"> <div className="Counter col-6 text-right"> <h4>Counter: {this.state.count}</h4> <button onClick={this.increaseHandler}>incrementing</button> <button onClick={this.decreaseHandler}>decrementing</button> </div> </div> </div> ) } } export default Counter;
C++
UTF-8
458
3.078125
3
[]
no_license
#include<stdio.h> #include<iostream> using namespace std; void pr(int o,int n) { if(n<=o) { cout<<n<<" "; pr(o,n+5); } } void print(int o,int n) { if(n<=0) { pr(o,n); return; } cout<<n<<" "; print(o,n-5); } int main() { int t; cin>>t; for(int x=0;x<t;x++) { int n; cin>>n; cout<<n<<" "; print(n,n-5); cout<<endl; } return 0; }
Java
UTF-8
3,596
2.40625
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2010 , 2014 Thorsten Frank (accounting@tfsw.de). * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package de.tfsw.accounting.model; import java.io.Serializable; import java.math.BigDecimal; import java.util.HashMap; import java.util.List; import java.util.Map; import de.tfsw.accounting.util.CalculationUtil; import de.tfsw.accounting.util.TimeFrame; /** * A container for paid invoices within a specific time period. * * <p>This is a non-persistent entity.</p> * * @author thorsten frank */ public class Revenue implements Serializable { /** * */ private static final long serialVersionUID = -9220047923401626299L; private TimeFrame timeFrame; private List<Invoice> invoices; private Map<Invoice, Price> invoiceRevenues; private Price regularRevenue; private Price otherRevenue; private Price totalRevenue; /** * @return the timeFrame */ public TimeFrame getTimeFrame() { return timeFrame; } /** * @param timeFrame the timeFrame to set */ public void setTimeFrame(TimeFrame timeFrame) { this.timeFrame = timeFrame; } /** * @return the invoices */ public List<Invoice> getInvoices() { return invoices; } /** * @param invoices the invoices to set */ public void setInvoices(List<Invoice> invoices) { this.invoices = invoices; this.invoiceRevenues = new HashMap<Invoice, Price>(); updateTotals(); } /** * */ private void updateTotals() { BigDecimal revenueGross = BigDecimal.ZERO; BigDecimal revenueNet = BigDecimal.ZERO; BigDecimal revenueTax = BigDecimal.ZERO; for (Invoice invoice : invoices) { final Price price = CalculationUtil.calculateRevenue(invoice); invoiceRevenues.put(invoice, price); revenueNet = revenueNet.add(price.getNet()); revenueGross = revenueGross.add(price.getGross()); if (price.getTax() != null) { revenueTax = revenueTax.add(price.getTax()); } } this.regularRevenue = new Price(revenueNet, revenueTax, revenueGross); this.totalRevenue = new Price(revenueNet, revenueTax, revenueGross); } /** * @return total revenue for the period */ public Price getTotalRevenue() { return totalRevenue; } /** * * @return total net revenue */ public BigDecimal getRevenueNet() { return totalRevenue.getNet(); } /** * @return the revenueTax */ public BigDecimal getRevenueTax() { return totalRevenue.getTax(); } /** * @return the revenueGross */ public BigDecimal getRevenueGross() { return totalRevenue.getGross(); } /** * * @return */ public Price getRegularRevenue() { return regularRevenue; } /** * * @return */ public Price getOtherRevenue() { return otherRevenue; } /** * @return the invoiceRevenues */ public Map<Invoice, Price> getInvoiceRevenues() { return invoiceRevenues; } }
C++
UTF-8
1,100
3.015625
3
[]
no_license
#include <stdio.h> #include <avr/io.h> #define StepPin 22 #define DirPin 24 #define Slp 26 int stepset=0; int stepspd = 1000; void setup() { pinMode(StepPin,OUTPUT); pinMode(DirPin,OUTPUT); pinMode(Slp,OUTPUT); digitalWrite(Slp,LOW); } void loop() { A_clockwise(); delay(1000); clockwise(); delay(1000); } void A_clockwise() { digitalWrite(Slp,HIGH); //turns on driver digitalWrite(DirPin,HIGH); for(stepset=0;stepset<200;stepset++) { digitalWrite(StepPin,HIGH); //initialize step delayMicroseconds(stepspd); //step speed digitalWrite(StepPin,LOW); delayMicroseconds(stepspd); } digitalWrite(Slp,LOW); //turns off driver } void clockwise() { digitalWrite(Slp,HIGH); //turns on driver digitalWrite(DirPin,LOW); for(stepset=0;stepset<200;stepset++) { digitalWrite(StepPin,HIGH); delayMicroseconds(stepspd); digitalWrite(StepPin,LOW); delayMicroseconds(stepspd); } digitalWrite(Slp,LOW); //turns off driver }
JavaScript
UTF-8
466
2.859375
3
[]
no_license
var colisoes = 0; var passos_no_tempo = 10000; function setup() { createCanvas(windowWidth,200); background(55); bloco1 = new Bloco(100,0,1,50); //posi x, vel, massa, lado bloco2 = new Bloco(300,-2/passos_no_tempo,1,100); } function draw() { background(55); for(var i = 0; i<passos_no_tempo; i++){ bloco1.atualiza(); bloco2.atualiza(); bloco1.colide(bloco2); bloco1.colide_parede(); } bloco1.mostra(); bloco2.mostra(); }
Python
UTF-8
4,427
3.390625
3
[]
no_license
import os # the program will first ask for password and username pass_word= input("Enter your password : ") user_name= input("Enter your username : ") #then take the password and username intered and check if they are available #the program will display the invail text if they are not correct until user enters correct cridentials reads = open("user.txt","r+") read_lines = reads.readlines() index =0 for line in read_lines : index+=1 if line : # if the password is correct it will display the task of the login user esle it will ask you to enter correct details if user_name in line : break else : if index == len(read_lines) : # helps in to check each line in the file print("invaild username or password!!! || try again\n") pass_word= input("Enter your password : ") user_name= input("Enter your username : ") read_lines = reads.readlines() for line in read_lines : if pass_word in line : break #if the user login is the admin the program will display the admin menu else if its not the admin the program displays the user menu #below is the admin menu if user_name == "admin" : print("\nPlease select one of the following options :") print("r - register user") print("a - add task") print("va - view all tasks") print("vm - view my tasks") print("s - to view statisticts") print("exit") print("\n") #the else code below displays the user maenu else : print("\nPlease select one of the following options :") print("a - add task") print("vm - view my tasks") print("exit") print("\n") reads.close() charactor = input() charactor = charactor.lower() write_in = open("user.txt",'a') #if the user enters *r* the program will allow them to register a new user if charactor == "r" : if pass_word != "admin" : print("you are not urthurised in this section") else : username = input("enter new username : ") password = input("enter new password : ") confirm = input("please confirm your password : ") if password == confirm : write_in.write(str(username)+" , "+str(password)) print("user successfuly registered !!!") write_in.close() # if the user enters *a* the program will allow them to add a task if charactor == "a" : username = input("\nEnter the username of the person the task is assigned to : ") tittle = input("\nEnter title of the task : ") description = input("\nDescription of a task : ") date = input("\nEnter the date today :") task_complete= input("\nIs the task completed? :") write_in = open("tasks.txt","a") write_in.write("\n"+str(username)+", "+str(tittle)+", "+str(description)+", "+str(date)+", No ") write_in.close() print("Task sucessfuly added!!!") # if the user enters va then the program will print out all the task in the file if charactor == "va" : task_file = open("tasks.txt","r") for line in task_file : if line : username,tittle,description,date,task_complete = line.split(",") print(""" Assigned to : {} Task tittle : {} Task description : {} Date Assigned : {} Task completed? : {} """.format(username,tittle,description,date,task_complete)) task_file.close() # if the user enters vm then the program will print out only the task of the loggedin user if charactor == "vm" : task_file = open("tasks.txt","r") for line in task_file : username,tittle,description,date,task_complete = line.split(",") if user_name == username : print(f""" Assigned to : {username}. Task tittle : {tittle}. Task description : {description}. Date Assigned : {date} Task completed? : {task_complete} """) task_file.close() #if they enters *s* the program will display a statistics if charactor == "s" : task_file = open("tasks.txt","r") counter = 0 for i in task_file : if i : counter +=1 print("Number Of Tasks") print(counter) task_file = open("user.txt","r") lenth = 0 for i in task_file : if i : lenth +=1 print("\nNumber Of Users") print(lenth) if charactor == "exit" : print("u have exited your program Bye !!! Bye!!!") quit() os.system("pause")
Python
UTF-8
2,128
2.734375
3
[]
no_license
from django.core.management.base import BaseCommand, CommandError # import the necessary packages # from picamera.array import PiRGBArray # from picamera import PiCamera import picamera import picamera.array import time import cv2 import imutils import numpy as np class Command(BaseCommand): help = 'Start capturing images' def handle(self, **options): # initialize the camera and grab a reference to the raw camera capture with picamera.PiCamera() as camera: # camera.resolution = (2592, 1944) res = (2592, 1936) camera.resolution = res # camera.resolution = (2000, 1500) # camera.resolution = (1280, 720) # camera.resolution = (720, 540) camera.start_preview() time.sleep(2) with picamera.array.PiRGBArray(camera, size=res) as stream: camera.capture(stream, format='bgr') # At this point the image is available as stream.array frame = stream.array frame = imutils.rotate(frame, angle=180) cv2.imshow("frame", frame) cv2.waitKey(0); # camera = PiCamera() # camera.resolution = (640, 480) # camera.framerate = 32 # rawCapture = PiRGBArray(camera, size=(640, 480)) # # # allow the camera to warmup # time.sleep(0.1) # # # capture frames from the camera # for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True): # # grab the raw NumPy array representing the image, then initialize the timestamp # # and occupied/unoccupied text # image = frame.array # # # show the frame # cv2.imshow("Frame", image) # key = cv2.waitKey(1) & 0xFF # # # clear the stream in preparation for the next frame # rawCapture.truncate(0) # # # if the `q` key was pressed, break from the loop # if key == ord("q"): # break
SQL
UTF-8
8,839
3.140625
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 4.9.1 -- https://www.phpmyadmin.net/ -- -- Host: localhost -- Generation Time: Nov 28, 2019 at 03:22 AM -- Server version: 10.4.8-MariaDB -- PHP Version: 7.3.11 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; 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 */; -- -- Database: `hackathon_bjc` -- -- -------------------------------------------------------- -- -- Table structure for table `bjc_nilai_jawaban` -- CREATE TABLE `bjc_nilai_jawaban` ( `id_nilai` int(11) NOT NULL, `id_pertanyaan` varchar(5) NOT NULL, `jawaban` varchar(100) NOT NULL, `skor` int(10) NOT NULL, `active` varchar(10) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `bjc_nilai_jawaban` -- INSERT INTO `bjc_nilai_jawaban` (`id_nilai`, `id_pertanyaan`, `jawaban`, `skor`, `active`) VALUES (1, '1', 'Tentu saja, mengapa tidak', 30, '1'), (2, '1', 'Ya untuk mendapatkan skor yang lebih tinggi', 10, '1'), (3, '1', 'Saya tidak tahu itu tergantung pada pertanyaan', 20, '1'), (4, '1', 'Mungkin tidak saya tidak bisa berhenti berbohong', 0, '1'), (5, '2', 'Agak, saya tertangkap berbohong sesekali', 10, '1'), (6, '2', 'Ya, sesekali', 20, '1'), (7, '2', 'Selalu, saya berbohong seolah anda tidak akan pernah membayangkan', 0, '1'), (8, '2', 'Mereka percaya padaku karena aku jujur', 30, '1'), (9, '3', 'Saya tidak ingat kapan terakhir kalinya', 30, '1'), (10, '3', 'Saya nyaris tidak berbohong', 20, '1'), (12, '3', 'Saya sering berbohong saat pamitan pergi keluar', 0, '1'), (13, '3', 'Terkadang saya berlagak sakit agar terbebas dari pekerjaan rumah', 10, '1'); -- -------------------------------------------------------- -- -- Table structure for table `bjc_pekerjaan` -- CREATE TABLE `bjc_pekerjaan` ( `id_pekerjaan` int(11) NOT NULL, `id_user` varchar(2) NOT NULL, `nama` varchar(50) NOT NULL, `lokasi` varchar(50) NOT NULL, `isi` text NOT NULL, `active` varchar(50) NOT NULL, `date_created` datetime NOT NULL, `status_pengupload` timestamp NOT NULL DEFAULT current_timestamp() ON UPDATE current_timestamp(), `gambar` tinyblob NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -------------------------------------------------------- -- -- Table structure for table `bjc_pertanyaan` -- CREATE TABLE `bjc_pertanyaan` ( `id_pertanyaan` int(11) NOT NULL, `pertanyaan` text NOT NULL, `active` varchar(1) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -- Dumping data for table `bjc_pertanyaan` -- INSERT INTO `bjc_pertanyaan` (`id_pertanyaan`, `pertanyaan`, `active`) VALUES (1, 'Apakah anda akan jujur menjawab pertanyaan selanjutnya?', '1'), (2, 'Apakah orang lain biasa mempercayai anda?', '1'), (3, 'Seberapa sering anda berbohong kepada kedua orang tua anda?', '1'), (4, 'Bagaimana perasaanmu ketika berbohong?', '1'), (5, 'Kapan anda akan berbohong?', '1'), (6, 'Apa taktik berbohong anda?', '1'), (7, 'Anda dalam kesulitan untuk sesuatu yang tidak anda lakukan. Apa yang kamu kerjakan?', '1'), (8, 'Permainan kartu mana yang akan kamu mainkan?', '1'), (9, 'Pilih kutipan:', '1'), (10, 'Jadi, apakah anda berbohong di kuiz ini?', '1'); -- -------------------------------------------------------- -- -- Table structure for table `bjc_perusahaan` -- CREATE TABLE `bjc_perusahaan` ( `id_perusahaan` int(11) NOT NULL, `alamat` varchar(50) NOT NULL, `deskripsi` text NOT NULL, `gambar` tinyblob NOT NULL, `active` varchar(50) NOT NULL, `date_created` datetime NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -------------------------------------------------------- -- -- Table structure for table `bjc_skill` -- CREATE TABLE `bjc_skill` ( `id_skill` int(10) NOT NULL, `id_user` int(10) NOT NULL, `nama_skill` varchar(20) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -------------------------------------------------------- -- -- Table structure for table `bjc_skor` -- CREATE TABLE `bjc_skor` ( `id_skor` int(11) NOT NULL, `id_pertanyaan` varchar(100) NOT NULL, `id_nilai` varchar(100) NOT NULL, `id_user` varchar(100) NOT NULL, `skor` int(10) NOT NULL, `active` varchar(10) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4; -- -------------------------------------------------------- -- -- Table structure for table `bjc_user` -- CREATE TABLE `bjc_user` ( `id` int(255) NOT NULL, `username` varchar(255) NOT NULL, `nama` varchar(100) NOT NULL, `email` varchar(255) NOT NULL, `jenis_kelamin` varchar(11) NOT NULL, `gambar` varchar(255) NOT NULL, `password` varchar(255) NOT NULL, `role_id` int(1) NOT NULL, `is_active` int(1) NOT NULL, `date_created` varchar(100) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `bjc_user` -- INSERT INTO `bjc_user` (`id`, `username`, `nama`, `email`, `jenis_kelamin`, `gambar`, `password`, `role_id`, `is_active`, `date_created`) VALUES (1, 'adminsuper', 'Admin Super', 'sisadaadm19@gmail.com', 'Laki-Laki', 'defaullt.jpg', '$2y$10$TAt8D4KuiBEA12DAJGS9Y.5o2Dhcri4B/QmWZ.iXMGQURLuwOZPIC', 1, 1, '1571059932'), (2, 'admin', 'Admin', 'joko.riyadi97@gmail.com', 'Perempuan', 'default.jpg', '$2y$10$7ts46nrNe5Ggft06KBwjSuzziscyw1YhEwG.CzAZ57q1fmWKrHxm.', 2, 1, '1571059932'), (3, 'jokorey', 'joko riyadi', 'joko.riyadi9@gmail.com', 'Laki-Laki', 'default.jpg', '$2y$10$fGRsejnw4/hy8m5axgpme..zwCMSAZDyzuRmgiuK.8cd8ioYA38A2', 1, 1, '1571059932'), (6, 'riya', 'riya', 'riya@gmail.com', 'Perempuan', 'default.jpg', '$2y$10$.Bd.4zGaDs6Xwv8UyS2TGe.XrqYSdA.QWN/oGcAWRgq14PUq825oi', 1, 1, '1571060266'); -- -------------------------------------------------------- -- -- Table structure for table `bjc_user_role` -- CREATE TABLE `bjc_user_role` ( `id` int(100) NOT NULL, `role` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Dumping data for table `bjc_user_role` -- INSERT INTO `bjc_user_role` (`id`, `role`) VALUES (1, 'admin Super'), (2, 'admin'); -- -------------------------------------------------------- -- -- Table structure for table `bjc_user_token` -- CREATE TABLE `bjc_user_token` ( `id` int(100) NOT NULL, `email` varchar(128) NOT NULL, `token` varchar(128) NOT NULL, `date_created` int(100) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Indexes for dumped tables -- -- -- Indexes for table `bjc_nilai_jawaban` -- ALTER TABLE `bjc_nilai_jawaban` ADD PRIMARY KEY (`id_nilai`); -- -- Indexes for table `bjc_pekerjaan` -- ALTER TABLE `bjc_pekerjaan` ADD PRIMARY KEY (`id_pekerjaan`); -- -- Indexes for table `bjc_pertanyaan` -- ALTER TABLE `bjc_pertanyaan` ADD PRIMARY KEY (`id_pertanyaan`); -- -- Indexes for table `bjc_perusahaan` -- ALTER TABLE `bjc_perusahaan` ADD PRIMARY KEY (`id_perusahaan`); -- -- Indexes for table `bjc_skill` -- ALTER TABLE `bjc_skill` ADD PRIMARY KEY (`id_skill`); -- -- Indexes for table `bjc_skor` -- ALTER TABLE `bjc_skor` ADD PRIMARY KEY (`id_skor`); -- -- Indexes for table `bjc_user` -- ALTER TABLE `bjc_user` ADD PRIMARY KEY (`id`); -- -- Indexes for table `bjc_user_role` -- ALTER TABLE `bjc_user_role` ADD PRIMARY KEY (`id`); -- -- Indexes for table `bjc_user_token` -- ALTER TABLE `bjc_user_token` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `bjc_nilai_jawaban` -- ALTER TABLE `bjc_nilai_jawaban` MODIFY `id_nilai` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=14; -- -- AUTO_INCREMENT for table `bjc_pekerjaan` -- ALTER TABLE `bjc_pekerjaan` MODIFY `id_pekerjaan` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `bjc_pertanyaan` -- ALTER TABLE `bjc_pertanyaan` MODIFY `id_pertanyaan` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=11; -- -- AUTO_INCREMENT for table `bjc_perusahaan` -- ALTER TABLE `bjc_perusahaan` MODIFY `id_perusahaan` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `bjc_skill` -- ALTER TABLE `bjc_skill` MODIFY `id_skill` int(10) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `bjc_skor` -- ALTER TABLE `bjc_skor` MODIFY `id_skor` int(11) NOT NULL AUTO_INCREMENT; -- -- AUTO_INCREMENT for table `bjc_user` -- ALTER TABLE `bjc_user` MODIFY `id` int(255) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7; -- -- AUTO_INCREMENT for table `bjc_user_role` -- ALTER TABLE `bjc_user_role` MODIFY `id` int(100) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; -- -- AUTO_INCREMENT for table `bjc_user_token` -- ALTER TABLE `bjc_user_token` MODIFY `id` int(100) NOT NULL AUTO_INCREMENT; COMMIT; /*!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 */;
SQL
UTF-8
1,720
4.0625
4
[]
no_license
SELECT name FROM world WHERE population > (SELECT population FROM world WHERE name='Russia') SELECT name FROM world WHERE continent = 'Europe' AND gdp / population > (SELECT gdp/population FROM world WHERE name = 'United Kingdom') SELECT name, continent FROM world WHERE continent IN(SELECT continent FROM world WHERE name IN('Argentina', 'Australia')) ORDER BY name SELECT name, population FROM world WHERE population > (SELECT population FROM world WHERE name = 'Canada') AND population < (SELECT population FROM world WHERE name = 'Poland') SELECT name, CONCAT(ROUND((population / (SELECT population FROM world WHERE name='Germany') * 100)),'%') FROM world WHERE continent = 'Europe' SELECT name FROM world WHERE gdp > ALL(SELECT gdp FROM world WHERE continent ='Europe' AND gdp > 0) SELECT continent, name, area FROM world x WHERE area >= ALL(SELECT area FROM world y WHERE y.continent = x.continent AND area>0) SELECT continent,name FROM world x WHERE name = (SELECT name FROM world y WHERE x.continent = y.continent ORDER BY name LIMIT 1) GROUP BY continent,name SELECT name,continent, population FROM world x WHERE 25000000 >= ALL(SELECT population FROM world y WHERE x.continent = y.continent) GROUP BY continent,name, population SELECT name, continent FROM world x WHERE population > ALL(SELECT 3 * population FROM world y WHERE x.continent = y.continent AND NOT x.name = y.name) GROUP BY continent,name,population
Java
UTF-8
619
2.40625
2
[ "MIT" ]
permissive
package com.noxception.midisense.interpreter.rrobjects; import com.noxception.midisense.config.dataclass.RequestObject; import java.util.UUID; public class ProcessFileRequest extends RequestObject { /** ATTRIBUTE */ private final UUID fileDesignator; //unique identifier for file /** * CONSTRUCTOR * @param fileDesignator used to identify file */ public ProcessFileRequest(UUID fileDesignator) { this.fileDesignator = fileDesignator; } /** GET Method * @return fileDesignator */ public UUID getFileDesignator() { return fileDesignator; } }
Rust
UTF-8
505
3.046875
3
[ "Apache-2.0", "MIT" ]
permissive
use tranche::BasedTranche; fn do_test<T>(slice: &impl AsRef<[T]>) { let mut tranche = BasedTranche::new(slice); assert_eq!(tranche.offset(), 0); tranche.take_first().unwrap(); assert_eq!(tranche.offset(), 1); tranche.take_front(2).unwrap(); assert_eq!(tranche.offset(), 3); } #[test] fn test_bytes() { do_test(&[1u8, 2, 3, 4, 5, 6]); } #[test] fn test_words() { do_test(&[1usize, 2, 3, 4, 5, 6]); } #[test] fn test_units() { do_test(&[(), (), (), (), (), ()]); }
C++
UTF-8
7,873
4.03125
4
[]
no_license
//Justin Foster - CS303 Lab 3 //Implementing these functions using a premade stack + queue implemented with vectors #include<iostream> #include<vector> #include<string> using namespace std; //Stack implementation class my_Stack { private: int size; int back; vector<int> vec; public: my_Stack() { size = 0; back = -1; vec.reserve(30); } void push(int data) { vec.push_back(data); back++; size++; } void pop() { back--; size--; } int top() { return vec[back]; } void printStack() { int counter = 0; while (counter <= back) { cout << vec[counter] << " "; counter++; } cout << endl; } int Size() { return size; } bool empty() { if (size == 0) return true; else return false; } }; //Queue implementation class my_Queue { public: my_Queue(); void enqueue(int data); void dequeue(); int getFront(); int getBack(); void printQueue(); int Size(); bool empty(); private: int size, back, front; vector<int> vec; }; my_Queue::my_Queue() { size = 0; back = -1; front = -1; vec.reserve(30); } void my_Queue::enqueue(int data) { vec.push_back(data); back = (back + 1) % 30; size++; if (front == -1) front = 0; } void my_Queue::dequeue() { front = (front + 1) % 30; size--; } int my_Queue::getFront() { return vec[front]; } int my_Queue::getBack() { return vec[back]; } void my_Queue::printQueue() { int counter = front; while (counter <= back) { cout << vec[counter] << " "; counter = (counter + 1) % 30; } cout << endl; } int my_Queue::Size() { return size; } bool my_Queue::empty() { if (size == 0) return true; else return false; } int main() { cout << "Lab 3 Menu:" << endl; char userVar = ' '; while (userVar != 'q') { cout << "(1) - Palindrome Check. " << endl; cout << "(2) - Convert binary to decimal. " << endl; cout << "(3) - Post-Fix Equation solver. " << endl; cout << "(4) - Parenthesis Balancer. " << endl; cout << "(5) - Insert value into middle of a queue. " << endl; cout << "(Q) - Quit the program. " << endl; cin >> userVar; if (userVar == '1') { //Question 1 - Check if string is a palindrome //Using a stack to push the characters of the string onto the stack one at a time //Pop the values back off and compare to original string to check for a match my_Stack myStack; string palindrome; string palin2; cout << "Enter a word for a palindrome check. " << endl; ws(cin); getline(cin, palindrome); int size = palindrome.size(); char x; for (int i = 0; i < size; i++) { x = palindrome[i]; myStack.push(x); } for (int i = 0; i < size; i++) { char temp; temp = myStack.top(); myStack.pop(); palin2 += temp; } if (palindrome == palin2) cout << palindrome << " is a palindrome!" << endl; else { cout << palindrome << " is not a palindrome." << endl; } } //Question 2 - Convert to Binary -------------------------------------------- if (userVar == '2') { cout << "Question 2..." << endl; int start; int counter = 0; string binary; my_Stack myStack1; cout << "Enter your decimal number to convert to binary." << endl; cin >> start; int initHold = start; //holds the inital decimal number while (start != 0) { if (start % 2 == 1) myStack1.push('1'); if (start % 2 == 0) myStack1.push('0'); start /= 2; counter++; } for (int i = 0; i < counter; i++) { char temp; temp = myStack1.top(); binary += temp; myStack1.pop(); } cout << initHold << " in binary is: " << binary << endl; } //Question 3 - Calculate the value of a post-fix equation //Read in the equation character by character and push onto stack //Once an operator is found, pop last two integer values off of the stack and apply operator //*** Can only work with single digit integers currently if (userVar == '3') { my_Stack postStack; string equation; cout << "Enter the post-fix equation." << endl; ws(cin); getline(cin, equation); for (int i = 0; i < equation.length(); i++) { char topVal = ' '; char secVal = ' '; if (isdigit(equation[i])) postStack.push(equation[i]); else { switch (equation[i]) { case '+' : topVal = postStack.top(); postStack.pop(); secVal = postStack.top(); postStack.pop(); postStack.push(secVal + topVal); break; case '/': topVal = postStack.top(); postStack.pop(); secVal = postStack.top(); postStack.pop(); postStack.push(secVal / topVal); break; case '*': topVal = postStack.top(); postStack.pop(); secVal = postStack.top(); postStack.pop(); postStack.push(topVal * secVal); break; case '-': topVal = postStack.top(); postStack.pop(); secVal = postStack.top(); postStack.pop(); postStack.push(topVal - secVal); break; } } } cout << "Final result is: " << postStack.top() << endl; } //Question 4 - Check the balance of a parenthesis //Have program parse string to find any brackets, if bracket is found push onto stack //Once the ending bracket is found, pop the stack and check if it matches the bracket //If not matching, unbalanced parenthesis if (userVar == '4') { my_Stack parenStack; string parenth; char tempStore; //variable used to store the value of the top of the stack cout << "Enter your equation." << endl; cin >> parenth; const int size = parenth.size(); for (int i = 0; i < size; i++) { if (parenth[i] == '(' || parenth[i] == '{' || parenth[i] == '[') parenStack.push(parenth[i]); switch (parenth[i]) { case ')': tempStore = parenStack.top(); parenStack.pop(); if (tempStore == '(') cout << "() brackets are balanced." << endl; else { cout << "() brackets are not balanced. " << endl; } break; case '}': tempStore = parenStack.top(); parenStack.pop(); if (tempStore == '{') cout << "{} brackets are balanced." << endl; else { cout << "{} brackets are not balanced. " << endl; } break; case ']': tempStore = parenStack.top(); parenStack.pop(); if (tempStore == '[') cout << "[] brackets are balanced." << endl; else { cout << "[] brackets are not balanced. " << endl; } break; } } } //Question 5 - Insert a value in the middle of a queue. //Logic - Need to find size of queue, divide by two to find the middle. //Enqueue the front of the initQueue to a new tempQueue until the middle is reached //At the middle value enqueue the userVar then proceed to enqueue the initQueue's values //Print the new tempQueue with the value added to the middle if (userVar == '5') { my_Queue initQueue; my_Queue tempQueue; initQueue.enqueue(1); initQueue.enqueue(2); initQueue.enqueue(3); initQueue.enqueue(4); initQueue.enqueue(5); initQueue.enqueue(6); cout << "Current queue values: "; initQueue.printQueue(); int userVar; cout << "What is the value you would like to insert?" << endl; cin >> userVar; int size = initQueue.Size(); int insertSize = size / 2; for (int i = 0; i < size; i++) { //Enqeueues the user values at the middle of the queue //then enqueues the following value that it "replaced" if (i == insertSize) { tempQueue.enqueue(userVar); tempQueue.enqueue(initQueue.getFront()); initQueue.dequeue(); } else if (i != insertSize) { tempQueue.enqueue(initQueue.getFront()); initQueue.dequeue(); } } cout << "New queue with value " << userVar << " added: "; tempQueue.printQueue(); } if (userVar == 'Q' || userVar == 'q') break; } return 0; }
Java
UTF-8
1,931
2.9375
3
[]
no_license
package it.uniclam.db; import com.mysql.jdbc.Connection; import com.mysql.jdbc.Statement; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.SQLException; /** * Connessione DB con JDBC driver * */ public class DBUtility { public static final String DRIVERNAME = "com.mysql.jdbc.Driver"; // public static final String USER = "sql11171626"; //public static final String PASSWORD = "ipSx2liyxJ"; //public static final String URL = "jdbc:mysql://sql11.freesqldatabase.com:3306/sql11171626"; public static final String USER = "root"; public static final String PASSWORD = "root"; public static final String URL="jdbc:mysql://localhost/hego"; static { try { Class.forName(DRIVERNAME); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * Effettua la connessione al database * @return Connection */ public static Connection getDBConnection() { Connection dbConnection = null; try { dbConnection = (Connection) DriverManager.getConnection(URL, USER, PASSWORD); return dbConnection; } catch (SQLException e) { System.out.println(e.getMessage()); } return dbConnection; } /** * Ottiene un PreparedStatement * @param sql String * @return PreparedStatement * @throws SQLException */ public static PreparedStatement getPreparedStatement(String sql) throws SQLException { return getDBConnection().prepareStatement(sql); } /** * Ottiene uno Statement * @return Statement * @throws SQLException */ public static Statement getStatement() throws SQLException { return (Statement) getDBConnection().createStatement(); } }
Java
UTF-8
9,571
1.726563
2
[]
no_license
package com.agnet.leteApp.fragments.main.sales; import android.annotation.SuppressLint; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.LinearLayout; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import androidx.annotation.Nullable; import androidx.fragment.app.Fragment; import androidx.fragment.app.FragmentActivity; import androidx.recyclerview.widget.GridLayoutManager; import androidx.recyclerview.widget.LinearLayoutManager; import androidx.recyclerview.widget.RecyclerView; import com.agnet.leteApp.R; import com.agnet.leteApp.application.mSingleton; import com.agnet.leteApp.fragments.main.ProjectFragment; import com.agnet.leteApp.fragments.main.adapters.CategoryAdapter; import com.agnet.leteApp.fragments.main.adapters.ProductsAdapter; import com.agnet.leteApp.helpers.DatabaseHandler; import com.agnet.leteApp.helpers.FragmentHelper; import com.agnet.leteApp.models.Category; import com.agnet.leteApp.models.ResponseData; import com.agnet.leteApp.models.User; import com.agnet.leteApp.service.Endpoint; import com.android.volley.NetworkResponse; import com.android.volley.Request; import com.android.volley.RetryPolicy; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.facebook.shimmer.ShimmerFrameLayout; import com.google.gson.Gson; import java.util.HashMap; import java.util.List; import java.util.Map; public class ProductsFragment extends Fragment { private FragmentActivity _c; private RecyclerView _productsList, _categorytList; private LinearLayoutManager _productsLayoutManager, _categoryLayoutManager; private String Token; private SharedPreferences.Editor _editor; private SharedPreferences _preferences; private Gson _gson; private ShimmerFrameLayout _shimmerLoader; private User _user; private DatabaseHandler _dbHandler; @SuppressLint("RestrictedApi") @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_products, container, false); _c = getActivity(); _preferences = getActivity().getSharedPreferences("SharedData", Context.MODE_PRIVATE); _editor = _preferences.edit(); _gson = new Gson(); _dbHandler = new DatabaseHandler(_c); TextView username = view.findViewById(R.id.user_name); _categorytList= view.findViewById(R.id.category_list); _productsList= view.findViewById(R.id.product_list); _shimmerLoader = view.findViewById(R.id.shimmer_view_container); LinearLayout userAcc = view.findViewById(R.id.view_user_account_btn); TextView totalQnty = view.findViewById(R.id.total_qnty); RelativeLayout openCartBtn = view.findViewById(R.id.open_cart); try { _user = _gson.fromJson(_preferences.getString("User", null), User.class); Token = _preferences.getString("TOKEN", null); String projectName = _preferences.getString("PROJECT_NAME", null); username.setText(projectName); int clientId = _preferences.getInt("CLIENT_ID", 0); getCategories(clientId); totalQnty.setText(""+_dbHandler.getTotalQnty()); } catch (NullPointerException e) { } _categoryLayoutManager= new LinearLayoutManager(_c, RecyclerView.HORIZONTAL, false); _categorytList.setLayoutManager(_categoryLayoutManager); _productsLayoutManager = new GridLayoutManager(_c, 2); _productsList.setLayoutManager(_productsLayoutManager); openCartBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { new FragmentHelper(_c).replaceWithbackStack(new CartFragment(),"CartFragment", R.id.fragment_placeholder); } }); return view; } @Override public void onPause() { super.onPause(); _shimmerLoader.setVisibility(View.GONE); _shimmerLoader.stopShimmerAnimation(); } @Override public void onActivityCreated(@Nullable Bundle savedInstanceState) { super.onActivityCreated(savedInstanceState); getView().setFocusableInTouchMode(true); getView().requestFocus(); getView().setOnKeyListener((v, keyCode, event) -> { if (event.getAction() == KeyEvent.ACTION_DOWN) { if (keyCode == KeyEvent.KEYCODE_BACK) { new FragmentHelper(_c).replaceWithbackStack(new ProjectFragment(),"ProjectFragment", R.id.fragment_placeholder); return true; } } return false; }); } public void getCategories(int id) { Log.d("CLIENT_ID", ""+id); _shimmerLoader.setVisibility(View.VISIBLE); _shimmerLoader.startShimmerAnimation(); Endpoint.setUrl("categories/client/"+id); String url = Endpoint.getUrl(); StringRequest postRequest = new StringRequest(Request.Method.GET, url, response -> { ResponseData res = _gson.fromJson(response, ResponseData.class); List<Category> categories = res.getCategories(); CategoryAdapter productsAdapter = new CategoryAdapter(_c,categories, this); _categorytList.setAdapter(productsAdapter); _shimmerLoader.setVisibility(View.GONE); _shimmerLoader.stopShimmerAnimation(); getProducts(categories.get(0).getId()); }, error -> { error.printStackTrace(); _shimmerLoader.setVisibility(View.GONE); _shimmerLoader.stopShimmerAnimation(); NetworkResponse response = error.networkResponse; String errorMsg = ""; if (response != null && response.data != null) { String errorString = new String(response.data); Log.i("log error", errorString); //TODO: display errors based on the message from the server Toast.makeText(_c, "Kuna tatizo, angalia mtandao alafu jaribu tena", Toast.LENGTH_SHORT).show(); } } ) { @Override public Map<String, String> getHeaders() { Map<String, String> params = new HashMap<String, String>(); params.put("Authorization", "Bearer " + "" + Token); return params; } }; mSingleton.getInstance(_c).addToRequestQueue(postRequest); postRequest.setRetryPolicy(new RetryPolicy() { @Override public int getCurrentTimeout() { return 50000; } @Override public int getCurrentRetryCount() { return 50000; } @Override public void retry(VolleyError error) throws VolleyError { } }); } public void getProducts(int cid) { Endpoint.setUrl("products/category/"+cid); String url = Endpoint.getUrl(); StringRequest postRequest = new StringRequest(Request.Method.GET, url, response -> { ResponseData res = _gson.fromJson(response, ResponseData.class); ProductsAdapter productsAdapter = new ProductsAdapter(_c,res.getProducts(), this); _productsList.setAdapter(productsAdapter); // Log.d("RESPONSEHERE", _gson.toJson(res.getProducts().get(0).getPrice())); }, error -> { error.printStackTrace(); _shimmerLoader.setVisibility(View.GONE); _shimmerLoader.stopShimmerAnimation(); NetworkResponse response = error.networkResponse; String errorMsg = ""; if (response != null && response.data != null) { String errorString = new String(response.data); Log.i("log error", errorString); //TODO: display errors based on the message from the server Toast.makeText(_c, "Kuna tatizo, angalia mtandao alafu jaribu tena", Toast.LENGTH_SHORT).show(); } } ) { @Override public Map<String, String> getHeaders() { Map<String, String> params = new HashMap<String, String>(); params.put("Authorization", "Bearer " + "" + Token); return params; } }; mSingleton.getInstance(_c).addToRequestQueue(postRequest); postRequest.setRetryPolicy(new RetryPolicy() { @Override public int getCurrentTimeout() { return 50000; } @Override public int getCurrentRetryCount() { return 50000; } @Override public void retry(VolleyError error) throws VolleyError { } }); } }
Java
UTF-8
5,042
1.914063
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2018 Hippo B.V. (http://www.onehippo.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.onehippo.forge.servlet.decorators.common; import com.google.common.base.Strings; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import java.util.regex.Pattern; public final class DecoratorConfiguration { public static final DecoratorConfiguration INVALID = new DecoratorConfiguration(); private boolean valid; private boolean enabled; private String hostHeader; private String contextPath; private Pattern hostPattern; private DecoratorConfiguration() { } public String getContextPath() { return contextPath; } public void setContextPath(final String contextPath) { this.contextPath = contextPath; } public boolean isValid() { return valid; } public String getHostHeader() { return hostHeader; } public boolean isEnabled() { return enabled; } public Pattern getHostPattern() { return hostPattern; } public boolean disabled() { return !enabled; } public boolean invalid() { return !valid; } public static final class Builder { private static final Logger log = LoggerFactory.getLogger(Builder.class); private final Map<String, String> mappings = new HashMap<>(); private String hostHeader; private boolean enabled; private Builder() { } public static Builder start() { return new Builder(); } public Builder hostHeader(final String hostHeader) { this.hostHeader = hostHeader; return this; } public Builder hosts(final Map<String, String> hosts) { if (hosts != null) { mappings.putAll(hosts); } return this; } public Builder enabled(final boolean enabled) { this.enabled = enabled; return this; } public Set<DecoratorConfiguration> build() { final Set<DecoratorConfiguration> objects = new HashSet<>(); final Map<Pattern, String> patterns = parseHostPatterns(mappings);; for (Map.Entry<Pattern, String> entry : patterns.entrySet()) { final Pattern host = entry.getKey(); final String contextPath = entry.getValue(); final DecoratorConfiguration config = new DecoratorConfiguration(); config.enabled = enabled; config.hostHeader = hostHeader; config.contextPath = contextPath; config.hostPattern = host; validate(config); objects.add(config); } return ImmutableSet.copyOf(objects); } private void validate(final DecoratorConfiguration config) { config.valid = config.contextPath != null && config.hostPattern !=null; } private Map<Pattern, String> parseHostPatterns(final Map<String, String> hosts) { if (hosts == null) { throw new IllegalStateException("No host names provided"); } final Map<Pattern, String> patterns = new HashMap<>(); for (Map.Entry<String, String> entry : hosts.entrySet()) { String host = entry.getKey(); if (Strings.isNullOrEmpty(host)) { log.warn("Skipping empty host value"); continue; } try { final Pattern pattern = Pattern.compile(host); patterns.put(pattern, entry.getValue()); } catch (Exception e) { log.error("Invalid host value {}", host); log.error("Error compiling host pattern: ", e); } } return ImmutableMap.copyOf(patterns); } } @Override public String toString() { return "FilterConfiguration{" + "valid=" + valid + ", enabled=" + enabled + ", hostHeader='" + hostHeader + '\'' + ", contextPath='" + contextPath + '\'' + ", hostPattern=" + hostPattern + '}'; } }
JavaScript
UTF-8
775
3.90625
4
[]
no_license
/** * Shifts an encryped Caesar cipher back to decode it. * Takes in a numeric value to shift the str parameter to the left by, * wrapping around for any ascii value below 65. * * @param {Number} shift - A number to shift the cipher by * @param {String} str - A string parameter * @returns {String} - Returns a decoded string */ function caesarShiftCipher (shift, str) { let message = ''; for (let i = 0; i < str.length; i++) { if (str.charCodeAt(i) < 65 || str.charCodeAt(i) > 90) { message += str[i]; } else { let asciiChar = str.charCodeAt(i) - shift; if (asciiChar < 65) { message += String.fromCharCode(asciiChar + 26); } else { message += String.fromCharCode(asciiChar); } } } return message; }
Java
UTF-8
401
1.859375
2
[]
no_license
package yuweixiang.first.dal.daointerface; import yuweixiang.first.dal.dataobject.OrderFeeDO; public interface OrderFeeDOMapper { int deleteByPrimaryKey(Long id); int insert(OrderFeeDO record); int insertSelective(OrderFeeDO record); OrderFeeDO selectByPrimaryKey(Long id); int updateByPrimaryKeySelective(OrderFeeDO record); int updateByPrimaryKey(OrderFeeDO record); }
C++
UTF-8
4,893
3.28125
3
[]
no_license
// // SingleLinkedList.cpp // DoubleLinkedListImpl // // Created by Sumanth Sai on 9/30/16. // Copyright © 2016 Sumanth Sai. All rights reserved. // #include <iostream> #include "SingleLinkedList.h" using namespace std; //This Method appends data to the list void LinkedList::append(int item){ str = new SingleNode(); str->data=item; if(start == NULL){ start = str; str->link = NULL; tvs = str; } else{ while(tvs->link != NULL){ tvs = tvs->link; } tvs->link = str; str->link = NULL; } } //This Method prints the list void LinkedList::print(SingleNode* head){ SingleNode* trav = head; int counter =0; while(trav!=NULL){ if(counter%4 == 0){ cout<<"\n"; } counter++; cout<<trav->data<<" "; trav=trav->link; } cout << endl; } //This Method reverse the list SingleNode* LinkedList::reverse(SingleNode* head){ SingleNode* prev=NULL; SingleNode* current= head; SingleNode* next =NULL; while(current !=NULL){ next = current->link; current->link = prev; prev = current; current= next; } start = prev; return start; } void LinkedList::printlist(SingleNode* SingleNode){ int counter =0; while(SingleNode!= NULL){ if(counter%4 ==0){ cout<<"\n"; } counter++; std::cout<<SingleNode->data<<" "; SingleNode=SingleNode->link; } std::cout << std::endl; } //This Method Splits the list to two lists void LinkedList::split(SingleNode* head,SingleNode* *front,SingleNode* *back){ SingleNode* fast; SingleNode* slow; if(head == NULL || head->link == NULL){ *front = head; *back = NULL; } else{ slow = head; fast = head->link; while(fast !=NULL){ fast=fast->link; if(fast != NULL){ slow = slow->link; fast= fast->link; } } *front = head; *back= slow->link; slow->link = NULL; } } //This Method merges two lists after sorting SingleNode* LinkedList::MergeAfterSort(SingleNode* a,SingleNode* b){ SingleNode* result = NULL; if(a == NULL){ return b; } else if(b == NULL){ return a; } if(a->data <= b->data){ result = a; result->link = MergeAfterSort(a->link, b); } else{ result = b; result->link = MergeAfterSort(a, b->link); } return result; } //This Method sort the list void LinkedList::sort1(SingleNode* *headref){ SingleNode* head = *headref; SingleNode* a = NULL; SingleNode* b = NULL; //cout<<head->data<<endl; if((head == NULL) || (head->link == NULL)){ return; } split(head, &a, &b); sort1(&a); sort1(&b); *headref = MergeAfterSort(a,b); } //This Method merges two lists void LinkedList::merge(SingleNode* a,SingleNode* b){ if(a == NULL|| b== NULL ){ return; } while(a->link != NULL){ a= a->link; } a->link =b; } //This Method executes the first problem statement(Team of four) void LinkedList::teamoffoursort(SingleNode* head){ SingleNode* fast; SingleNode* slow; SingleNode* slow2; int count=0; if(head == NULL){ return; } slow = head; fast = head->link; if(fast == NULL){ merge(spm,slow); return; } while(fast->link !=NULL && count <2){ count +=1; fast=fast->link; if(fast->link != NULL){ count +=1; fast= fast->link; } } if(fast != NULL){ slow2 = fast->link; } if(fast != NULL){ fast->link = NULL; } sort1(&slow); if((spm == NULL) || (spm->link == NULL)){ spm = slow; start = slow; } else{ merge(spm, slow); } slow = slow2; teamoffoursort(slow); } //This Method splits the list into half and shuffles them void LinkedList::shuffle(SingleNode* r){ SingleNode* p = NULL; SingleNode* q = NULL; split(r, &p, &q); cout<<"** first half **" << endl; printlist(p); cout <<"\n"; cout <<"** second half **"<< endl; printlist(q); cout <<"\n"; SingleNode* p_c=p, *q_c=q; SingleNode* p_n,*q_n; while(p_c != NULL && q_c != NULL){ p_n = p_c->link; q_n = q_c->link; q_c->link = p_n; p_c->link = q_c; p_c =p_n; q_c = q_n; } q = q_c; }
JavaScript
UTF-8
1,418
2.734375
3
[]
no_license
'use strict' const cheerio = require('cheerio') const writeFile = require('fs') const request = require('request') const parseGameInfo = (title) => { let atIndex = title.indexOf(' at ') let boxIndex = title.indexOf('Box Score') let hocIndex = title.indexOf('Hockey') return { date : title.substring(boxIndex+12,hocIndex-2), home : title.substring(atIndex+3,boxIndex), away : title.substring(0,atIndex) } } module.exports.scrapeGameStats = (html) => { let player = '' let data = '' let playerId = '' const rawhtml = cheerio.load(html); const title = rawhtml('head > title').text().replace('|','') const gameInfo = parseGameInfo(title); rawhtml('tr').map(index => { let tr = rawhtml('tr')[index] let team = tr.parent.parent.parent.attribs.id.substring(4,7) let dataType = rawhtml(tr).attr('class') ? rawhtml(tr).attr('class') : 'general' tr.children.forEach((element,i) => { if(rawhtml(element).attr('data-stat')==='player') { player = rawhtml(element).text() playerId = rawhtml(element).find('a').attr('href') } else if (rawhtml(element).attr('data-stat')){ let row = title.concat('|',gameInfo.date,'|',gameInfo.home,'|',gameInfo.away,'|',dataType,'|',playerId,'|',team,'|',player,'|', rawhtml(element).attr('data-stat'),'|', rawhtml(element).html()) data += row + '\n' } }) }) return data }
Python
UTF-8
245
3.0625
3
[ "MIT" ]
permissive
import openpyxl class Excel: def __init__(self, file_path): wb = openpyxl.load_workbook('file_path') self.sheet = wb.get_sheet_by_name('Лист1') def get_value(self, position): return self.sheet[position].value
PHP
UTF-8
1,012
2.90625
3
[]
no_license
<?php namespace SsoSdk; /** * soap header验证需要的信息载体 * * @author jiang <mylampblog@163.com> */ abstract class AbstractSoapHeaderInfo { /** * soap header所需要的参数 * * @var array */ public $headerUser; /** * soap header所需要的参数 * * @var array */ public $headerPassword; /** * soap header所需要的参数 * * @var array */ public $headerToken; /** * 设置soap header所需要的参数 * * @param array $headerUser * @access public */ abstract public function setHeaderUser($headerUser); /** * 设置soap header所需要的参数 * * @param array $headerUser * @access public */ abstract public function setHeaderPassword($headerPassword); /** * 设置soap header所需要的参数 * * @param array $headerUser * @access public */ abstract public function setHeaderToken($headerToken); }
JavaScript
UTF-8
1,418
2.734375
3
[]
no_license
import React from 'react' import { Cell } from 'fixed-data-table' export default class StatCell extends React.Component { constructor() { super() this.timer = null this.state = { className: '' } } componentWillReceiveProps(nextProps) { if (nextProps.value > this.props.value) { this.showPositiveTicker() } if (nextProps.value < this.props.value) { this.showNegativeTicker() } } componentWillUnmount() { clearTimeout(this.timer) } showPositiveTicker() { const positiveColor = this.props.colorblind ? 'blue-ticker' : 'green-ticker' this.flashTicker(positiveColor) } showNegativeTicker() { this.flashTicker('red-ticker') } flashTicker(colorClassName) { this.setState({ className: `ticker ${colorClassName}` }) this.timer = setTimeout(() => { this.setState({ className: '' }) }, 1500) } render() { const { value, colorblind } = this.props let color = 'black' if (typeof value === 'number') { const positiveColor = colorblind ? '#3a77d8' : '#1daa16' color = value > 0 ? positiveColor : '#eb2c2c' } // eslint-disable-next-line eqeqeq if (value == '0.00') { color = 'black' } return ( <Cell className={this.state.className} {...this.props.cellProps}> <span style={{ color }}> {value} </span> </Cell> ) } }
C++
UTF-8
692
2.625
3
[]
no_license
// // Filter.hpp // // // Created by Martino Milani on 26.05.19. // #ifndef Filter_h #define Filter_h #include <pybind11/pybind11.h> #include <pybind11/numpy.h> #include <iostream> namespace py = pybind11; class Filter{ // Abstract base class from which all filters have to inherit to obey the API. // Furthermore, it implements a simple static method as factory, in order to be easily // ported to Python public: Filter(int n): nthreads(n){}; virtual ~Filter() = default; virtual py::array_t<double> operator()(py::array_t<double>& data) = 0; static std::unique_ptr<Filter> factory(std::string filter_name); protected: int nthreads; }; #endif /* Filter_h */
Python
UTF-8
11,710
2.5625
3
[ "Apache-2.0" ]
permissive
# This code is part of Qiskit. # # (C) Copyright IBM 2021. # # This code is licensed under the Apache License, Version 2.0. You may # obtain a copy of this license in the LICENSE.txt file in the root directory # of this source tree or at http://www.apache.org/licenses/LICENSE-2.0. # # Any modifications or derivative works of this code must retain this # copyright notice, and modified files need to carry a notice indicating # that they have been altered from the originals. """Rabi amplitude experiment.""" from typing import List, Optional import numpy as np from qiskit import QuantumCircuit from qiskit.circuit import Gate, Parameter from qiskit.qobj.utils import MeasLevel from qiskit.providers import Backend import qiskit.pulse as pulse from qiskit_experiments.framework import BaseExperiment, Options from qiskit_experiments.curve_analysis import ParameterRepr, OscillationAnalysis from qiskit_experiments.exceptions import CalibrationError class Rabi(BaseExperiment): """An experiment that scans the amplitude of a pulse to calibrate rotations between 0 and 1. # section: overview The circuits that are run have a custom rabi gate with the pulse schedule attached to it through the calibrations. The circuits are of the form: .. parsed-literal:: ┌───────────┐ ░ ┌─┐ q_0: ┤ Rabi(amp) ├─░─┤M├ └───────────┘ ░ └╥┘ measure: 1/═════════════════╩═ 0 If the user provides his own schedule for the Rabi then it must have one free parameter, i.e. the amplitude that will be scanned, and a drive channel which matches the qubit. # section: tutorial :doc:`/tutorials/calibrating_armonk` See also `Qiskit Textbook <https://qiskit.org/textbook/ch-quantum-hardware/\ calibrating-qubits-pulse.html>`_ for the pulse level programming of Rabi experiment. """ __analysis_class__ = OscillationAnalysis __rabi_gate_name__ = "Rabi" @classmethod def _default_run_options(cls) -> Options: """Default option values for the experiment :meth:`run` method.""" options = super()._default_run_options() options.meas_level = MeasLevel.KERNELED options.meas_return = "single" return options @classmethod def _default_experiment_options(cls) -> Options: """Default values for the pulse if no schedule is given. Users can set a schedule by doing .. code-block:: rabi.set_experiment_options(schedule=rabi_schedule) Experiment Options: duration (int): The duration of the default Gaussian pulse. sigma (float): The standard deviation of the default Gaussian pulse. amplitudes (iterable): The list of amplitude values to scan. schedule (ScheduleBlock): The schedule for the Rabi pulse that overrides the default. """ options = super()._default_experiment_options() options.duration = 160 options.sigma = 40 options.amplitudes = np.linspace(-0.95, 0.95, 51) options.schedule = None return options @classmethod def _default_analysis_options(cls) -> Options: """Default analysis options.""" options = super()._default_analysis_options() options.result_parameters = [ParameterRepr("freq", "rabi_rate")] options.xlabel = "Amplitude" options.ylabel = "Signal (arb. units)" options.normalization = True return options def __init__(self, qubit: int): """Initialize a Rabi experiment on the given qubit. The parameters of the Gaussian Rabi pulse can be specified at run-time. The rabi pulse has the following parameters: - duration: The duration of the rabi pulse in samples, the default is 160 samples. - sigma: The standard deviation of the pulse, the default is duration 40. - amplitudes: The amplitude that are scanned in the experiment, default is np.linspace(-0.95, 0.95, 51) Args: qubit: The qubit on which to run the Rabi experiment. """ super().__init__([qubit]) def _template_circuit(self, amp_param) -> QuantumCircuit: """Return the template quantum circuit.""" gate = Gate(name=self.__rabi_gate_name__, num_qubits=1, params=[amp_param]) circuit = QuantumCircuit(1) circuit.append(gate, (0,)) circuit.measure_active() return circuit def _default_gate_schedule(self, backend: Optional[Backend] = None): """Create the default schedule for the Rabi gate.""" amp = Parameter("amp") with pulse.build(backend=backend, name="rabi") as default_schedule: pulse.play( pulse.Gaussian( duration=self.experiment_options.duration, amp=amp, sigma=self.experiment_options.sigma, ), pulse.DriveChannel(self.physical_qubits[0]), ) return default_schedule def circuits(self, backend: Optional[Backend] = None) -> List[QuantumCircuit]: """Create the circuits for the Rabi experiment. Args: backend: A backend object. Returns: A list of circuits with a rabi gate with an attached schedule. Each schedule will have a different value of the scanned amplitude. Raises: CalibrationError: - If the user-provided schedule does not contain a channel with an index that matches the qubit on which to run the Rabi experiment. - If the user provided schedule has more than one free parameter. """ schedule = self.experiment_options.get("schedule", None) if schedule is None: schedule = self._default_gate_schedule(backend=backend) else: if self.physical_qubits[0] not in set(ch.index for ch in schedule.channels): raise CalibrationError( f"User provided schedule {schedule.name} does not contain a channel " "for the qubit on which to run Rabi." ) if len(schedule.parameters) != 1: raise CalibrationError("Schedule in Rabi must have exactly one free parameter.") param = next(iter(schedule.parameters)) # Create template circuit circuit = self._template_circuit(param) circuit.add_calibration( self.__rabi_gate_name__, (self.physical_qubits[0],), schedule, params=[param] ) # Create the circuits to run circs = [] for amp in self.experiment_options.amplitudes: amp = np.round(amp, decimals=6) assigned_circ = circuit.assign_parameters({param: amp}, inplace=False) assigned_circ.metadata = { "experiment_type": self._type, "qubits": (self.physical_qubits[0],), "xval": amp, "unit": "arb. unit", "amplitude": amp, "schedule": str(schedule), } if backend: assigned_circ.metadata["dt"] = getattr(backend.configuration(), "dt", "n.a.") circs.append(assigned_circ) return circs class EFRabi(Rabi): """An experiment that scans the amplitude of a pulse to calibrate rotations between 1 and 2. # section: overview This experiment is a subclass of the :class:`Rabi` experiment but takes place between the first and second excited state. An initial X gate used to populate the first excited state. The Rabi pulse is then applied on the 1 <-> 2 transition (sometimes also labeled the e <-> f transition) which implies that frequency shift instructions are used. The necessary frequency shift (typically the qubit anharmonicity) should be specified through the experiment options. The circuits are of the form: .. parsed-literal:: ┌───┐┌───────────┐ ░ ┌─┐ q_0: ┤ X ├┤ Rabi(amp) ├─░─┤M├ └───┘└───────────┘ ░ └╥┘ measure: 1/══════════════════════╩═ 0 # section: example Users can set a schedule by doing .. code-block:: ef_rabi.set_experiment_options(schedule=rabi_schedule) """ @classmethod def _default_experiment_options(cls) -> Options: """Default values for the pulse if no schedule is given. Experiment Options: frequency_shift (float): The frequency by which the 1 to 2 transition is detuned from the 0 to 1 transition. """ options = super()._default_experiment_options() options.frequency_shift = None return options @classmethod def _default_analysis_options(cls) -> Options: """Default analysis options.""" options = super()._default_analysis_options() options.result_parameters = [ParameterRepr("freq", "rabi_rate_12")] return options def _default_gate_schedule(self, backend: Optional[Backend] = None): """Create the default schedule for the EFRabi gate with a frequency shift to the 1-2 transition.""" if self.experiment_options.frequency_shift is None: try: anharm, _ = backend.properties().qubit_property(self.physical_qubits[0])[ "anharmonicity" ] self.set_experiment_options(frequency_shift=anharm) except KeyError as key_err: raise CalibrationError( f"The backend {backend} does not provide an anharmonicity for qubit " f"{self.physical_qubits[0]}. Use EFRabi.set_experiment_options(frequency_shift=" f"anharmonicity) to manually set the correct frequency for the 1-2 transition." ) from key_err except AttributeError as att_err: raise CalibrationError( "When creating the default schedule without passing a backend, the frequency needs " "to be set manually through EFRabi.set_experiment_options(frequency_shift=..)." ) from att_err amp = Parameter("amp") with pulse.build(backend=backend, name=self.__rabi_gate_name__) as default_schedule: with pulse.frequency_offset( self.experiment_options.frequency_shift, pulse.DriveChannel(self.physical_qubits[0]), ): pulse.play( pulse.Gaussian( duration=self.experiment_options.duration, amp=amp, sigma=self.experiment_options.sigma, ), pulse.DriveChannel(self.physical_qubits[0]), ) return default_schedule def _template_circuit(self, amp_param) -> QuantumCircuit: """Return the template quantum circuit.""" circuit = QuantumCircuit(1) circuit.x(0) circuit.append(Gate(name=self.__rabi_gate_name__, num_qubits=1, params=[amp_param]), (0,)) circuit.measure_active() return circuit
Markdown
UTF-8
2,800
3.359375
3
[]
no_license
# dynamic_calendar A calendar that allows scheduling of dynamic events - Python3 Modules Used: functools in 'models/events.py' - line 6, 20-30, 65, 75-79 datetime in 'models/events.py' - line 6, 20-30, 65, 75-79, 138-234 flask in server.py - line 8-243 pymongo - line 10-11, 53-67, etc. bson - line 77, 115, 120, 145, 151, etc. os - line 10 Name and Location of Custom Class: /models/events.py: Dynamic_Event and Static_Event Name and Location of Decorators: I used the @total_ordering decorator from functools in /models/events.py In addition, I used the @app.route and @app.errorhandler decorators from flask in server.py Project Features: Login Page / Signup Page - username/password -javascript ajax requests to the server's api -response based on database request from the server To-do-list + calendar view -creation, modification, and deletion of static and dynamic items -done using ajax requests to the server -some server-side validation implemented -server then queries/modifies the database in response -automatic sorting of events -inserts dynamic events into the list of static events -Jinja used for utilizing python objects within html -Bootstrap grid used to keep everything ordered into rows and columns -cdn used for jquery and bootstrap on the frontend -Updates are not dynamic. Due to "Notes on Dynamic Additions" below, I did not implement dynamic additions/edits to the page. Therefore, one must reload to see changes made. Git The entire project was created utilizing git version control https://github.com/crestwood204/dynamic_calendar However, the project on github does not contain the env.sh file, so you would need to source your own MONGODB_URI to get this to work after cloning the repository. How to launch / operate the project: -Open terminal and navigate to the dynamic_calendar directory -source env.sh -export FLASK_APP=server.py -flask run -Open web browser and go to localhost:5000 (Designed for Google Chrome) -Create an account and login -Once logged in, click on the plus signs to add static vs dynamic events -Reload the page to see changes. Notes on Dynamic Additions: Dynamic calendar additions only consider the hour (rounded up for the event's end time) If date has passed, it is not added to the calendar Dynamic additions are done on the backend to utilize python, but in practice, they should be done on the front end so that the page does not need to be reloaded in order to see changes. (This would also present a heavy load on the server as non-trivial computations are done)
TypeScript
UTF-8
511
2.796875
3
[]
no_license
export enum StatusEnum { Correct = 'Correct', Wrong = 'Wrong', AlmostCorrect = 'AlmostCorrect', } export interface IGameState { grid: GridType noise: string[] solution: string[] size: number } export interface INavigationState { currentPage: string } export interface IStoreState { game: IGameState navigation: INavigationState } export interface IGridItem { column: number letter: string row: number status?: StatusEnum updatedAt: Date } export type GridType = IGridItem[][]
Java
UTF-8
7,134
2.6875
3
[]
no_license
package fmi.informatics.gui; import java.awt.BorderLayout; import java.awt.Color; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.ComponentAdapter; import java.awt.event.ComponentEvent; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.beans.PropertyChangeEvent; import java.beans.PropertyChangeListener; import java.io.FileReader; import java.util.ArrayList; import java.util.Arrays; import javax.swing.JButton; import javax.swing.JDialog; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JOptionPane; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.JTextField; import javax.swing.SortOrder; import fmi.informatics.comparators.StudentComparator; import fmi.informatics.enums.EType; import fmi.informatics.extending.Student; import jdk.internal.platform.Container; public abstract class copyCustomDialog extends JFrame { public static Student[] students; JTable table; copyStudentDataModel copystudentDataModel; public static void main(String[] args) { students = FileReader.readPeople(); initializeData(); copyStudentData gui = new copyStudentData(); gui.createAndShowGUI(); } public static void initializeData() { if (!FileReader.isFileExists()) { FileReader.createPersonFile(); } } public void createAndShowGUI() { JFrame frame = new JFrame("Таблица с данни за студенти"); frame.setSize(800, 450); JLabel label = new JLabel("Списък с потребители", JLabel.CENTER); frame.getContentPane().setBackground(Color.lightGray); copystudentDataModel = new copyStudentDataModel(students); table = new JTable(copystudentDataModel); table.setBackground(Color.orange); JScrollPane scrollPane = new JScrollPane(table); JButton buttonSortAscending = new JButton("Сортирай по възходящ ред"); JButton buttonSortDescending = new JButton("Сортирай по низходящ ред"); JButton buttonFilter = new JButton("Филтрирай"); JPanel buttonsPanel = new JPanel(); buttonsPanel.add(buttonSortAscending); buttonsPanel.add(buttonFilter); buttonsPanel.add(buttonSortDescending); Container container = frame.getContentPane(); container.setLayout(new BorderLayout()); container.add(label, BorderLayout.NORTH); container.add(scrollPane, BorderLayout.CENTER); container.add(buttonsPanel, BorderLayout.SOUTH); final JDialog filterDialog = new copyCustomDialog(getFilterText(), this, EType.FILTER,SortOrder.ASCENDING); // Добавяме listener към бутона за сортиране // Добавяме диалог final JDialog sortDialogAscending = new copyCustomDialog(getSortText(), this,EType.SORT,SortOrder.ASCENDING); buttonSortAscending.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { sortDialogAscending.pack(); sortDialogAscending.setVisible(true); } }); final JDialog sortDialogDescending = new copyCustomDialog(getSortText(), this,EType.SORT,SortOrder.DESCENDING); // Добавяме listener към бутона за сортиране buttonSortDescending.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { sortDialogDescending.pack() ;sortDialogDescending.setVisible(true); } } ); buttonFilter.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { filterDialog.pack(); filterDialog.setVisible(true); } }); frame.setVisible(true); } public void filterTable ( String lastName , JTable table, Student[] students){ this.copystudentDataModel = new copyStudentDataModel(filterData(students,lastName)); table.setModel(this.copystudentDataModel); table.repaint(); } public static Student[] filterData (Student[]students,String lastName){ ArrayList<Student> filteredData = new ArrayList<>(); for (int i = 0; i < students.length; i++) { if (lastName.equals(students[i].getlastName())) { filteredData.add(students[i]); } } Student[] filteredDataArray = new Student[filteredData.size()]; filteredDataArray = filteredData.toArray(filteredDataArray); return filteredDataArray; } public void sortTable ( int intValue, JTable table, Student[]students,SortOrder order){ StudentComparator comparator = null; switch (intValue) { case 1: comparator = new FirstNameComp(); checkIfDescending( order, comparator); break; case 2: comparator = new SecondNameComp(); checkIfDescending( order, comparator); break; case 3: comparator = new LastNameComparator(); checkIfDescending( order, comparator); break; } if (comparator == null) { Arrays.sort(students); } else { Arrays.sort(students, comparator); } copystudentDataModel = new copyStudentDataModel(students); table.setModel(copystudentDataModel); table.repaint(); } private static void checkIfDescending(SortOrder order,StudentComparator comparator){ if (order.equals(SortOrder.DESCENDING)){ comparator.setSortOrder(SortOrder.DESCENDING); } } private static String getSortText () { return "Моля, въведете цифрата на колоната, по която искате да сортирате: \n" + " 1 - Име \n" + " 2 - Презиме \n" + " 3 - Фамилия \n"; } // TODO Добавяме текст, който да се визуализира в диалога за филтриране private static String getFilterText () { return "Моля, въведете фамилията на студентд\n" ; } }