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
989
2.65625
3
[]
no_license
#pragma once #include <BasicFormater.hpp> #include <UITextField.hpp> #include <UITextInput.hpp> #include <optional> #include <Renderer.hpp> //debug #include <string> class UserInputView { public: UITextInput& get() { return userInputBuffer; } std::optional<UITextField> popInput() { if(not hasUnconsumedUserInput()) return{}; UITextField userInput; userInput.setText(userInputBuffer.getBuffer().data()); reset(); return {userInput}; } // debug std::string getInput() { return std::string(userInputBuffer.getBuffer().data()); } void display(Renderer& renderer) { renderer.submit(userInputBuffer, BasicFormater::any); } private: bool hasUnconsumedUserInput() { return userInputBuffer.getInputPendingFlag(); } void reset() { userInputBuffer = UITextInput(); userInputBuffer.getInputPendingFlag() = false; } private: UITextInput userInputBuffer; };
C#
UTF-8
2,929
2.53125
3
[]
no_license
using OutlierProtege.Database; using OutlierProtege.Models; using System.Data.Entity; using System.Data.Entity.Infrastructure; using System.Linq; using System.Net; using System.Threading.Tasks; using System.Web.Http; using System.Web.Http.Description; namespace OutlierProtege.Controllers.Api { public class SourcesController : ApiController { private ProtegeContext db = new ProtegeContext(); // GET: api/Sources public IQueryable<Source> GetSources() { return db.Sources; } // GET: api/Sources/5 [ResponseType(typeof(Source))] public async Task<IHttpActionResult> GetSource(int id) { Source source = await db.Sources.FindAsync(id); if (source == null) { return NotFound(); } return Ok(source); } // PUT: api/Sources/5 [ResponseType(typeof(void))] public async Task<IHttpActionResult> PutSource(int id, Source source) { if (!ModelState.IsValid) { return BadRequest(ModelState); } if (id != source.Id) { return BadRequest(); } db.Entry(source).State = EntityState.Modified; try { await db.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!SourceExists(id)) { return NotFound(); } else { throw; } } return StatusCode(HttpStatusCode.NoContent); } // POST: api/Sources [ResponseType(typeof(Source))] public async Task<IHttpActionResult> PostSource(Source source) { if (!ModelState.IsValid) { return BadRequest(ModelState); } db.Sources.Add(source); await db.SaveChangesAsync(); return CreatedAtRoute("DefaultApi", new { id = source.Id }, source); } // DELETE: api/Sources/5 [ResponseType(typeof(Source))] public async Task<IHttpActionResult> DeleteSource(int id) { Source source = await db.Sources.FindAsync(id); if (source == null) { return NotFound(); } db.Sources.Remove(source); await db.SaveChangesAsync(); return Ok(source); } protected override void Dispose(bool disposing) { if (disposing) { db.Dispose(); } base.Dispose(disposing); } private bool SourceExists(int id) { return db.Sources.Count(e => e.Id == id) > 0; } } }
Markdown
UTF-8
3,683
3.0625
3
[]
no_license
# sql * 表操作: drop table tableName; 删除表 create table tableName(clomnkey...) engine=InnoDB; // 创建表,并指定工作引擎 alter table add clomnKey; 新增表字段 alter table drop clomnKey; 删除表字段 rename table a to b; 重命名表 show index from table; 查看索引 show columns from tabel; 查看表信息 * mysql配置文件: /etc/my.cnf * 触发器: 1. 语法: ``` create trigger triggerName alter | before(定义触发器执行时间) insert | update | delete (定义触发的动作) on table (定义触发的表) for each row begin sql语句; end; ``` * insert: 1. insert low_priority into table 降低数据插入执行优先级,降低等待处理select的性能,同样适用于update和delete操作 2. insert into table(clonm) values(value),(value); 优于多条insert语句插入 3. insert into table(clonm) select (clomn) from oldTable; insert select将oldTable中的数据导入到table中 * update: 1. 更新语法: update table set clomnKey_1 = '1', clomnKey_2 = '2' where id = 1; 注意过滤条件where省略会导致更新全表 2. update ignore table; 多行更新时,忽略出现更新错误的行 3. update中可使用子查询的结果来更新字段的值 * delete: 1. delete语法: delete from table where id = 1; 注意过滤条件where省略会导致删除全表数据 2. truncate table; 删除表内容操作,比delete快;过程:删除表,然后创建新表,delete是逐条删除数据 * 字符集校对: 1. show character set; 查看所支持的字符集完整列表 2. show collation; 查看所支持校对的完成列表 3. show variables like 'character%'; 查看使用的字符集 4 show variables like 'collation%' 查看使用的校对 5. 在创建表时指定字符集及校对: create table table() default character set hebrew collation hebrew_general_ci; * 访问控制: 1. 创建新用户: create user username identified by 'password'; 2. 修改用户名: rename user username to newName 或使用 update user set username = 'newName' where username='username'; 3. 删除用户及相关权限: drop user username; 4. 查看用户权限: show grants for username; 5. 权限授予: grants select on table.*(所要授予的具体权限) to username; grants all 授予所有权限 grants database.* 授予指定数据库的所有权限 grants database.tabel.* 授予指定表的所有权限 6. 撤销权限: revoke select on table.*(所要授予的具体权限) from username; revoke all 取消所有授权... 7. 修改密码:set password for username = password('newpassword'); * 数据备份: 1. mysqldump 2. mysqlhotcopy 3. backup table 或 select into outfie, 使用restore table来恢复数据 * mysql慢查询(在my.ini中配置): 1. slow_query_log = on; 可以捕获执行时间超过一定数值的SQL语句 2. long_query_time = 1; 当SQL语句执行时间超过此数值时,就会被记录到日志中,建议设置为1或者更短 3. slow_query_log_file; 慢查询记录日志的文件名 4. log_queries_not_using_indexes=on; 可以捕获到所有未使用索引的SQL语句,尽管这个SQL语句有可能执行得挺快 面试sql: 1. 查询人数最多的部门ID ``` select dept as ID from people where dept in (select dept from people group by dept having count(*) >= All(select count(*) from people group by dept)); ``` 2. 表复制 ``` inset into table1(name, sex) select name, sex from table; ```
Java
UTF-8
556
3.109375
3
[]
no_license
import java.util.HashSet; import java.util.Set; class Solution { public int maxNonOverlapping(int[] nums, int target) { Set<Integer> sums = new HashSet<>(); sums.add(0); int result = 0; int sum = 0; for (int num : nums) { sum += num; if (sums.contains(sum - target)) { ++result; sums.clear(); sums.add(0); sum = 0; } else { sums.add(sum); } } return result; } }
Python
UTF-8
4,548
3.15625
3
[]
no_license
""" class implementation of a 2D rotation class creator: Peter Mackenzie-Helnwein date: Oct 29, 2019 revised: April 5, 2020 """ # import libraries import sys import numpy as np # the element master class from Element import * # class definition class PlateElement(Element): """ !class: PlateElement this is still the linear element variables: self.C ... material stiffness tensor self.A ... element area self.g1 ... covariant base vector 1 self.g2 ... covariant base vector 2 self.B1 ... kinematic matrix for node 1 self.B2 ... kinematic matrix for node 2 self.B3 ... kinematic matrix for node 3 inherited variables: self.nnode ......... number of nodes per element self.ndof .......... number of degrees of freedom per node self.X = (X1,X2) ... tuple of nodal position vectors (as np.array) self.U ............. array of nodal displacement vectors self.force ......... internal forces at nodes self.stiffness ..... the stiffness matrix overloaded methods: def init(self) ....... element specific initialization steps compute(self) ...... does the actual computation inherited methods: __init__(self, X, params) setDisp(self, U) ... U is an array of nodal displacement vectors getFe(self) ........ return the internal force vector as array of nodal vectors getKe(self) ........ return the stiffness matrix as array of nodal matrices getFeAsMatrix(self) .. return the internal force vector as nx1 matrix getKeAsMatrix(self) .. return the stiffness matrix as nxn matrix """ def init(self): X1 = self.X[0] X2 = self.X[1] X3 = self.X[2] self.stress = np.zeros(3) if not 'E' in self.params.keys(): self.params['E'] = 1.0 if not 'nu' in self.params.keys(): self.params['nu'] = 0.0 E = self.params['E'] nu = self.params['nu'] self.C = np.array([[1.,nu,0.], [nu,1.,0.], [0.,0.,(1-nu)/2.]]) * E/(1.-nu*nu) # compute base vectors self.g1 = X1 - X3 self.g2 = X2 - X3 # compute metric G = np.array([[np.dot(self.g1,self.g1),np.dot(self.g1,self.g2)], [np.dot(self.g2,self.g1),np.dot(self.g2,self.g2)]]) # compute jacobian and area J = np.sqrt( np.linalg.det(G) ) self.A = J/2. # compute dual base vectors H = np.linalg.inv(G) h1 = H[0][0] * self.g1 + H[0][1] * self.g2 h2 = H[1][0] * self.g1 + H[1][1] * self.g2 self.B1 = np.array([[h1[0],0.0],[0.0,h1[1]],[h1[1],h1[0]]]) self.B2 = np.array([[h2[0],0.0],[0.0,h2[1]],[h2[1],h2[0]]]) self.B3 = -(self.B1 + self.B2) def compute(self): U1 = self.U[0] U2 = self.U[1] U3 = self.U[2] strain = self.B1 @ (U1 - U3) strain += self.B2 @ (U2 - U3) stress = self.C @ strain self.force = ( stress @ self.B1 * self.A, stress @ self.B2 * self.A, stress @ self.B3 * self.A ) K11 = self.B1.T @ self.C @ self.B1 * self.A K12 = self.B1.T @ self.C @ self.B2 * self.A K13 = self.B1.T @ self.C @ self.B3 * self.A K22 = self.B2.T @ self.C @ self.B2 * self.A K23 = self.B2.T @ self.C @ self.B3 * self.A K33 = self.B3.T @ self.C @ self.B3 * self.A self.stiffness = ( (K11 ,K12 ,K13), (K12.T,K22 ,K23), (K13.T,K23.T,K33) ) # defining main execution procedure def main(): # create a demo element X1 = np.array([0.,0.]) X2 = np.array([1.,0.]) X3 = np.array([0.,1.]) e = PlateElement((X1,X2,X3)) # undeformed state print('U = ',e.U) print('---') print('Fe = ',e.getFe()) print('Kte = \n',e.getKe()) print('---') print('Fe = ',e.getFeAsMatrix()) print('Kte = \n',e.getKeAsMatrix()) # now set some displacement and check out changes e.setDisp((np.array([0.0,0.0]),np.array([0.1,0.0]),np.array([0.0,0.0]))) print('=======') print('U = ',e.U) print('---') print('Fe = ',e.getFe()) print('Kte = \n',e.getKe()) print('---') print('Fe = ',e.getFeAsMatrix()) print('Kte = \n',e.getKeAsMatrix()) # main execution **************************************** if __name__ == "__main__": main() sys.exit(0)
JavaScript
UTF-8
4,490
2.609375
3
[]
no_license
// create our angular app and inject ngAnimate and ui-router // ============================================================================= angular.module('formApp', ['ngAnimate', 'ngMessages', 'ui.router']) // configuring our routes // ============================================================================= .config(function ($stateProvider, $urlRouterProvider) { $stateProvider .state('form', { url: '/form', templateUrl: 'form.html', controller: 'formController' }) // nested states .state('form.profile', { url: '/profile', templateUrl: 'form-profile.html' }) .state('form.interests', { url: '/interests', templateUrl: 'form-interests.html' }) .state('form.summary', { url: '/summary', templateUrl: 'form-summary.html' }); $urlRouterProvider.otherwise('/form/profile'); }) .value('formSteps', [ {uiSref: 'form.profile', valid: false}, {uiSref: 'form.interests', valid: false}, {uiSref: 'form.summary', valid: false} ]) .run([ '$rootScope', '$state', 'formSteps', function ($rootScope, $state, formSteps) { // Register listener to watch route changes $rootScope.$on('$stateChangeStart', function (event, toState, toParams, fromState, fromParams) { var canGoToStep = false; // only go to next if previous is valid var toStateIndex = _.findIndex(formSteps, function (formStep) { return formStep.uiSref === toState.name; }); console.log('toStateIndex', toStateIndex) if (toStateIndex === 0) { canGoToStep = true; } else { canGoToStep = formSteps[toStateIndex - 1].valid; } console.log('canGoToStep', toState.name, canGoToStep); // Stop state changing if the previous state is invalid if (! canGoToStep) { // Abort going to step event.preventDefault(); } }); } ]) // our controller for the form // ============================================================================= .controller('formController', function ($scope, $state, $stateParams, formSteps) { // we will store all of our form data in this object $scope.formData = {}; $scope.formStepSubmitted = false; var nextState = function (currentState) { switch (currentState) { case 'form.profile': return 'form.interests'; break; case 'form.interests': return 'form.summary'; break; default: alert('Did not match any switch'); } }; var updateValidityOfCurrentStep = function (updatedValidity) { var currentStateIndex = _.findIndex(formSteps, function (formStep) { return formStep.uiSref === $state.current.name; }); formSteps[currentStateIndex].valid = updatedValidity; }; $scope.goToNextSection = function (isFormValid) { console.log('isFormValid ', isFormValid) // set to true to show all error messages (if there are any) $scope.formStepSubmitted = true; if (isFormValid) { // reset this for next form $scope.formStepSubmitted = false; // mark the step as valid so we can navigate to it via the links updateValidityOfCurrentStep(true /*valid */); $state.go(nextState($state.current.name)); } else { // mark the step as valid so we can navigate to it via the links updateValidityOfCurrentStep(false /*not valid */); } }; $scope.discount = function() { return $scope.formData.interests !== 'later' ? 'You get a 7% discount, congrats!' : 'No discount, sorry'; }; $scope.processForm = function () { alert('awesome!'); }; });
Java
UTF-8
1,017
3.6875
4
[]
no_license
package info; import infoInterface.IInfo; /** * 一个最基本的Info类型, * 包含一个成员变量container来存储实际的信息。 */ public class InfoWithContainer implements IInfo{ /** * 存储信息的对象, * 之所以创建这么一个对象是为了使得多个Info对象能够操作同一个信息 */ public Object container; /** * @param container 信息的承载体,可以是任何对象。 */ public InfoWithContainer(Object container){ this.container = container; } /** * 默认构造方法, * 内部信息全部为null。 */ public InfoWithContainer(){ //Empty Body } /** * 获取当前Info对象中的信息承载体。 * @return 包含信息的Object对象。 */ @Override public Object getContainer() { return container; } /** * 设置当前Info对象中的信息承载体。 * @param container 包含信息的Object对象。 */ @Override public void setContainer(Object container) { this.container = container; } }
Java
UTF-8
3,368
3.390625
3
[]
no_license
package payloadGeneration.hashTable; import java.io.*; import java.util.*; public class HashTableMain { public static class HashOrder implements Comparator<String>{ public HashOrder() { } public int compare(String str1, String str2) { int hash1 = str1.hashCode(); int hash2 = str2.hashCode(); return hash1-hash2; } } public static void HTmain(String[] args) { /* * size of table * length of payload * file for payload */ //TODO make flags to add the ability to choose these fields. int size = 1024; int maxLength = 100; String filename = "./payload.csv"; boolean naive = false; HashOrder order = new HashOrder(); int index = 0; for(String arg: args) { if (arg.contains("--size")) { size = Integer.parseInt(args[index+1]); } if(arg.contains("--length")) { maxLength = Integer.parseInt(args[index+1]); } if(arg.contains("--file")) { filename = args[index+1]; } if (arg.contains("--naive")) { naive = true; } index++; } if (naive) { specificNaiveHashGeneration(size, maxLength, filename, order); } else { concurrentAndDesignedHashGeneration(size, maxLength, filename, order); } } private static void concurrentAndDesignedHashGeneration(int size, int maxLength, String filename, HashOrder order) { Hashtable table = new Hashtable(size, maxLength); int elementLength = 15; int length; Random rand = new Random(); String[] array; int iterations = 0; String element; while (true){ // If iterations > size*maxLength we've reached an infinite loop. iterations++; /* * Sets the length of our string */ length = rand.nextInt(elementLength-5) + 5; element = RandomMessage.getNextMessage(length); try { table.add(element); } catch (IndexOutOfBoundsException e) { array = table.getArray(element); break; } if(iterations > size*maxLength) { System.out.println("The program got stuck in an infinite loop."); System.exit(0); } } Arrays.sort(array, order); try{ PrintWriter out = new PrintWriter(filename); for (int i = 0; i < maxLength; i++) { out.print(array[i]); if (i< (maxLength -1)) { out.print(","); } } out.close(); }catch(FileNotFoundException e) { System.out.println("Something was wrong with the file"); } } public static void specificNaiveHashGeneration(int size, int maxLength, String filename, HashOrder order) { int elementLength = 15; int length; Random rand = new Random(); String element; ArrayList<String> list = new ArrayList<String>(maxLength); length = rand.nextInt(elementLength-5) + 5; element = RandomMessage.getNextMessage(length); int hash = element.hashCode(); while (list.size() < maxLength) { length = rand.nextInt(elementLength-5) + 5; element = RandomMessage.getNextMessage(length); if (hash == element.hashCode()) { list.add(element); } } String[] array = (String[])list.toArray(); Arrays.sort(array, order); try{ PrintWriter out = new PrintWriter(filename); for (int i = 0; i < maxLength; i++) { out.print(array[i]); if (i< (maxLength -1)) { out.print(","); } } out.close(); }catch(FileNotFoundException e) { System.out.println("Something was wrong with the file"); } } }
Python
UTF-8
2,468
2.53125
3
[ "MIT" ]
permissive
#!/usr/bin/env python import argparse import os import socket import gym import numpy as np import gym_uds_pb2 import utils class Environment: def __init__(self, env_id, sock): self.env = gym.make(env_id) self.sock = sock self.sock.settimeout(1) def run(self): while True: request = utils.recv_message(self.sock, gym_uds_pb2.Request) if request.type == gym_uds_pb2.Request.DONE: break elif request.type == gym_uds_pb2.Request.RESET: self.reset() elif request.type == gym_uds_pb2.Request.STEP: self.step() elif request.type == gym_uds_pb2.Request.SAMPLE: self.sample() def reset(self): observation = self.env.reset() observation_pb = gym_uds_pb2.Observation(data=observation.ravel(), shape=observation.shape) utils.send_message(self.sock, gym_uds_pb2.State(observation=observation_pb, reward=0.0, done=False)) def step(self): action = utils.recv_message(self.sock, gym_uds_pb2.Action) observation, reward, done, _ = self.env.step(action.value) assert type(observation) is np.ndarray observation_pb = gym_uds_pb2.Observation(data=observation.ravel(), shape=observation.shape) utils.send_message(self.sock, gym_uds_pb2.State(observation=observation_pb, reward=reward, done=done)) def sample(self): action = self.env.action_space.sample() utils.send_message(self.sock, gym_uds_pb2.Action(value=action)) if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('id', help='the id of the gym environment to simulate') parser.add_argument( 'filepath', nargs='?', default='/tmp/gym-uds-socket', help='a unique filepath where the socket will bind') args = parser.parse_args() try: os.remove(args.filepath) except FileNotFoundError: pass sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) sock.bind(args.filepath) sock.listen() while True: try: conn, _ = sock.accept() env = Environment(args.id, conn) env.run() except BrokenPipeError: pass except socket.timeout: print('socket.timeout!') pass finally: try: del env except NameError: pass
C++
UTF-8
9,215
2.609375
3
[]
no_license
// // jnidictionry.cpp // vntoeic // // Created by dai nguyen on 5/15/17. // Copyright © 2017 dai nguyen. All rights reserved. // #include <stdio.h> #include "jni.h" #include "model.cpp" #include "SqliteDictionary.hpp" #include <iostream> #include <string> #include <vector> using namespace std; // select all dictionary which similar name_ extern "C"{ JNIEXPORT jobjectArray JNICALL Java_sqlite_SqliteDictionary_searchSimilar(JNIEnv * env , jobject object , jstring name_){ const char *name = env->GetStringUTFChars(name_, 0); // TODO env->ReleaseStringUTFChars(name_, name); SqliteDictionary sqlite; vector<Dictionary>result =sqlite.searchAll(name); jclass cl = env -> FindClass("model/Dictionary"); jmethodID methodId = env -> GetMethodID(cl,"<init>", "(ILjava/lang/String;Ljava/lang/String;)V"); jclass clcv = env -> FindClass("model/Convert"); jmethodID methodId1 = env -> GetStaticMethodID(clcv, "convertCStringToJniSafeString", "([B)Ljava/lang/String;"); jobjectArray arr = env->NewObjectArray((int)result.size(), cl, NULL); for (int i =0;i<result.size();i++){ jbyteArray array = env->NewByteArray(strlen(result[i].getName())); env->SetByteArrayRegion(array,0,strlen(result[i].getName()),(jbyte*)result[i].getName()); jstring str = (jstring)env->CallStaticObjectMethod(clcv, methodId1, array); jbyteArray array1 = env->NewByteArray(strlen(result[i].getContent())); env->SetByteArrayRegion(array1,0,strlen(result[i].getContent()),(jbyte*)result[i].getContent()); jstring str1 = (jstring)env->CallStaticObjectMethod(clcv, methodId1, array1); jobject ob = env->NewObject(cl, methodId,result[i].getId(),str,str1); env->SetObjectArrayElement(arr, i, ob); } return arr; } } // select dictionary with id extern "C"{ JNIEXPORT jobject JNICALL Java_sqlite_SqliteDictionary_searchId(JNIEnv * env , jobject object , jint id_){ int id = (int)id_; SqliteDictionary sqlite; Dictionary *diction = sqlite.searchId(id); jclass cl = env -> FindClass("model/Dictionary"); jmethodID methodId = env -> GetMethodID(cl,"<init>", "(ILjava/lang/String;Ljava/lang/String;)V"); jclass clcv = env -> FindClass("model/Convert"); jmethodID methodId1 = env -> GetStaticMethodID(clcv, "convertCStringToJniSafeString", "([B)Ljava/lang/String;"); if(diction!=NULL){ jbyteArray array = env->NewByteArray(strlen(diction->getName())); env->SetByteArrayRegion(array,0,strlen(diction->getName()),(jbyte*)diction->getName()); jstring str = (jstring)env->CallStaticObjectMethod(clcv, methodId1, array); jbyteArray array1 = env->NewByteArray(strlen(diction->getContent())); env->SetByteArrayRegion(array1,0,strlen(diction->getContent()),(jbyte*)diction->getContent()); jstring str1 = (jstring)env->CallStaticObjectMethod(clcv, methodId1, array1); jobject ob = env->NewObject(cl, methodId,diction->getId(),str,str1); return ob; } else return NULL; } } // extern "C"{ JNIEXPORT jobject JNICALL Java_sqlite_SqliteDictionary_searchHistory(JNIEnv * env , jobject object ){ SqliteDictionary sqlite; vector<Dictionary>result = sqlite.searchHistory(); jclass cl = env -> FindClass("model/Dictionary"); jmethodID methodId = env -> GetMethodID(cl,"<init>", "(ILjava/lang/String;Ljava/lang/String;)V"); jclass clcv = env -> FindClass("model/Convert"); jmethodID methodId1 = env -> GetStaticMethodID(clcv, "convertCStringToJniSafeString", "([B)Ljava/lang/String;"); jobjectArray arr = env->NewObjectArray((int)result.size(), cl, NULL); for(int i=0;i<result.size();i++){ Dictionary diction = result.at(i); jbyteArray array = env->NewByteArray(strlen(diction.getName())); env->SetByteArrayRegion(array,0,strlen(diction.getName()),(jbyte*)diction.getName()); jstring str = (jstring)env->CallStaticObjectMethod(clcv, methodId1, array); env->DeleteLocalRef(array); jbyteArray array1 = env->NewByteArray(strlen(diction.getContent())); env->SetByteArrayRegion(array1,0,strlen(diction.getContent()),(jbyte*)diction.getContent()); jstring str1 = (jstring)env->CallStaticObjectMethod(clcv, methodId1, array1); env->DeleteLocalRef(array1); jobject ob = env->NewObject(cl, methodId,diction.getId(),str,str1); env->SetObjectArrayElement(arr, i, ob); env->DeleteLocalRef(str); env->DeleteLocalRef(str1); env->DeleteLocalRef(ob); } return arr; } } // select all favorite extern "C"{ JNIEXPORT jobjectArray JNICALL Java_sqlite_SqliteDictionary_searchFavorite(JNIEnv * env , jobject object ){ SqliteDictionary sqlite; vector<DictionaryFavorite>result =sqlite.searchFavorite(); jclass cl = env -> FindClass("model/DictionaryFavorite"); jmethodID methodId = env -> GetMethodID(cl,"<init>", "(ILjava/lang/String;Ljava/lang/String;)V"); jclass clcv = env -> FindClass("model/Convert"); jmethodID methodId1 = env -> GetStaticMethodID(clcv, "convertCStringToJniSafeString", "([B)Ljava/lang/String;"); jobjectArray arr = env->NewObjectArray((int)result.size(), cl, NULL); for (int i =0;i<result.size();i++){ jbyteArray array = env->NewByteArray(strlen(result[i].getTime())); env->SetByteArrayRegion(array,0,strlen(result[i].getTime()),(jbyte*)result[i].getTime()); jstring str = (jstring)env->CallStaticObjectMethod(clcv, methodId1, array); jbyteArray array1 = env->NewByteArray(strlen(result[i].getMeaning())); env->SetByteArrayRegion(array1,0,strlen(result[i].getMeaning()),(jbyte*)result[i].getMeaning()); jstring str1 = (jstring)env->CallStaticObjectMethod(clcv, methodId1, array1); jobject ob = env->NewObject(cl, methodId,result[i].getId(),str,str1); env->SetObjectArrayElement(arr, i, ob); } return arr; } } // insert favovite extern "C"{ JNIEXPORT void JNICALL Java_sqlite_SqliteDictionary_insertFavorite(JNIEnv * env, jobject object , jobject data){ jclass cl = env-> FindClass("model/DictionaryFavorite"); jmethodID getid = env->GetMethodID(cl,"getId","()I"); jmethodID gettime = env->GetMethodID(cl,"getTime","()Ljava/lang/String;"); jmethodID getmeaning = env->GetMethodID(cl,"getMeaning","()Ljava/lang/String;"); jstring time_ = (jstring)env->CallObjectMethod(data , gettime ,0); const char *time = env->GetStringUTFChars(time_, 0); jstring meaning_ =(jstring)env->CallObjectMethod(data , getmeaning ,0); const char *meaning = env->GetStringUTFChars(meaning_, 0); jint id_ = (jint)env->CallIntMethod(data,getid); int id =(int)id_; DictionaryFavorite dicfavorite(id,time, meaning); SqliteDictionary sqlite; sqlite.insertFavorite(dicfavorite); } } extern "C"{ JNIEXPORT void JNICALL Java_sqlite_SqliteDictionary_updateHistory(JNIEnv * env, jobject object , jint id, jint his){ SqliteDictionary sqlite; sqlite.updateHistory((int)id,(int)his); } } extern "C"{ JNIEXPORT jboolean JNICALL Java_sqlite_SqliteDictionary_checkFavorite(JNIEnv * env, jobject object , jint id){ SqliteDictionary sqlite; bool b =sqlite.checkFavorite((int)id); return (jboolean)b; } } extern "C"{ JNIEXPORT jobject JNICALL Java_sqlite_SqliteDictionary_searchFavoriteDictionary(JNIEnv * env, jobject object , jint id1){ SqliteDictionary sqlite; int id =(int)id1; DictionaryFavorite *dic =sqlite.searchFavoriteDictionary(id); if(dic==NULL)return NULL; jclass cl = env -> FindClass("model/DictionaryFavorite"); jmethodID methodId = env -> GetMethodID(cl,"<init>", "(ILjava/lang/String;Ljava/lang/String;)V"); jclass clcv = env -> FindClass("model/Convert"); jmethodID methodId1 = env -> GetStaticMethodID(clcv, "convertCStringToJniSafeString", "([B)Ljava/lang/String;"); jbyteArray array = env->NewByteArray(strlen(dic->getTime())); env->SetByteArrayRegion(array,0,strlen(dic->getTime()),(jbyte*)dic->getTime()); jstring str = (jstring)env->CallStaticObjectMethod(clcv, methodId1, array); jbyteArray array1 = env->NewByteArray(strlen(dic->getMeaning())); env->SetByteArrayRegion(array1,0,strlen(dic->getMeaning()),(jbyte*)dic->getMeaning()); jstring str1 = (jstring)env->CallStaticObjectMethod(clcv, methodId1, array1); jobject ob = env->NewObject(cl, methodId,dic->getId(),str,str1); return ob; } }
Java
UTF-8
77
2.046875
2
[]
no_license
package code.microsystem; public interface Vehical { void move(); }
C++
UTF-8
7,107
3.421875
3
[ "MIT" ]
permissive
#include <iostream> #include <vector> #include <string> #include <stack> #include <utility> #include <cstdio> const int ALPHABET = 128; struct Node { // Bounds of a substring that correspont to the edge from parent int start; int end; int suff_link; std::vector<int> children; Node(int start, int end): children(ALPHABET, -1), start(start), end(end), suff_link(-1) {} bool has_child(char trans) const; void add_child(char trans, int node) ; int get_child(char trans) const; }; class SuffixTree { // Tree nodes std::vector<Node> nodes; // String itself std::string str; int i; // Current position is the tree int active_node; int active_edge; int active_len; int remainder; int need_suff_link; // Suplimental functions Node& active(); char active_edge_char(); void build_tree(); void add_leaf_to_node(); void split_edge(); void jump_to_the_next_location(); void add_suff_link(int to); bool do_we_overshoot(); int get_edge_length(int node); int add_leaf(int start); int add_node(int start, int end); public: SuffixTree(const std::string &str); SuffixTree(std::string &&str); // Outside interface const Node& get_node(int node) const; int node_count() const; }; void Node::add_child(char trans, int node) { children[trans] = node; } int Node::get_child(char trans) const { return children[trans]; } bool Node::has_child(char trans) const { return children[trans] != -1; } int SuffixTree::node_count() const { return nodes.size(); } const Node& SuffixTree::get_node(int node) const { return nodes[node]; } int SuffixTree::get_edge_length(int node) { // -1 = end, so real end is current suffix length if (nodes[node].end == -1) { return i - nodes[node].start + 1; } return nodes[node].end - nodes[node].start; } // Checks if active len overshoots active edge and chops it if it does overshoot bool SuffixTree::do_we_overshoot() { int next = active().get_child(active_edge_char()); int edge_len = get_edge_length(next); if (active_len >= edge_len) { active_len -= edge_len; active_edge += edge_len; active_node = next; return true; } return false; } // Add pending suffix link to current edge void SuffixTree::add_suff_link(int to) { if (need_suff_link != -1) { nodes[need_suff_link].suff_link = to; } need_suff_link = to; } int SuffixTree::add_leaf(int start) { nodes.emplace_back(start, -1); return nodes.size() - 1; } int SuffixTree::add_node(int start, int end) { nodes.emplace_back(start, end); return nodes.size() - 1; } char SuffixTree::active_edge_char() { return str[active_edge]; } Node& SuffixTree::active() { return nodes[active_node]; } // Jmp to the next point of insertion void SuffixTree::jump_to_the_next_location() { --remainder; if (active_node == 0 && active_len > 0) { active_edge = i - remainder + 1; --active_len; } else { if (active().suff_link == -1) { active_node = 0; } else { active_node = active().suff_link; } } } // Add leaf node to active node void SuffixTree::add_leaf_to_node() { int new_node = add_leaf(i); active().add_child(active_edge_char(), new_node); add_suff_link(active_node); } // Split active edge and add a leaf to it void SuffixTree::split_edge() { int next = active().get_child(active_edge_char()); int split = add_node(nodes[next].start, nodes[next].start + active_len); active().add_child(active_edge_char(), split); // Add leaf node int leaf = add_leaf(i); nodes[split].add_child(str[i], leaf); // Add second half of the edge nodes[next].start += active_len; nodes[split].add_child(str[nodes[next].start], next); // Add pending suffix link add_suff_link(split); } void SuffixTree::build_tree() { i = 0; remainder = 0; active_node = 0; active_len = 0; active_edge = 0; // Add root add_node(0, 0); // Go through the string for (; i < str.size(); ++i) { need_suff_link = -1; ++remainder; while (remainder > 0) { // WE ARE IN A NODE if (active_len == 0) { // We want to go to the edge with current symbol active_edge = i; if (!active().has_child(str[i])) { // No such edge? Create one! add_leaf_to_node(); jump_to_the_next_location(); continue; } } // WE ARE ALONG AN EDGE // 1. If we overshoot, chop down active edge until we have a valid value if (do_we_overshoot()) { continue; } int next = active().get_child(active_edge_char()); // 2. Can we go further on the same edge? if (str[nodes[next].start + active_len] == str[i]) { // 3. Yes! Then go there and move to the next symbol without inserting anything ++active_len; add_suff_link(active_node); break; } // 4. No! Split the edge split_edge(); jump_to_the_next_location(); } } } SuffixTree::SuffixTree(std::string &&str): str(str) { build_tree(); } SuffixTree::SuffixTree(const std::string &str): str(str) { build_tree(); } void output_two_tree(const std::string &str1, const std::string &str2) { SuffixTree tree(str1 + str2); printf("%d\n", tree.node_count()); // Store pairs (parent, node) std::stack<std::pair<int, int>> dfs; dfs.push(std::make_pair(-1, 0)); int iteration = 0; while (!dfs.empty()) { auto current = dfs.top(); dfs.pop(); const Node& node = tree.get_node(current.second); // Pre order if (current.first != -1) { printf("%d ", current.first); if (node.start < str1.size()) { printf("0 %d ", node.start); if (node.end == -1) { printf("%d\n", str1.size()); } else { printf("%d\n", node.end); } } else { printf("1 %d ", node.start - str1.size()); if (node.end == -1) { printf("%d\n", str2.size()); } else { printf("%d\n", node.end - str1.size()); } } } // Continue descend for (int i = ALPHABET - 1; i >= 0; --i) { if (node.has_child(i)) { dfs.push(std::make_pair(iteration, node.get_child(i))); } } ++iteration; } } int main() { // Input std::string str1, str2; std::cin >> str1 >> str2; // Output output_two_tree(str1, str2); return 0; }
Markdown
UTF-8
1,406
2.828125
3
[]
no_license
# Packer Templates This is a repository of available Packer templates. One day, hopefully, there will be a website that makes it easier to discover these templates, but for now a central repository helps quite a bit. If you want to contribute a template, please make a pull request! Note that these templates are not guaranteed to work. In fact, many rely on external resources (URLs) that may change and cause them to fail. We don't actively check to verify that every template works, although we do verify it works prior to merging it. So, if a template isn't working, it is probably *very* close to working and only a small external change affected it. ## Template Features The templates all adhere to the following features: - Templates from ISO must install a bare-bones OS - Provisioners such as Chef, Puppet, etc. are _not_ installed into templates from ISOs. - VirtualBox/VMware guest tools _are_ installed into the machine, if applicable. - Templates are not configured with any Vagrant-specific things, though the intention is for them to be able to work with Vagrant. - Different builders are split into separate template files, rather than a single template file with multiple builders. This makes it easier for others to use only the pieces they want. If you plan on submitting a template, please adhere to the above rules, which are quite simple. Thanks!
PHP
UTF-8
4,431
2.59375
3
[ "MIT" ]
permissive
<?php use Fuel\Core\DB; /** * Any query in Model Version * * @package Model * @created 2017-10-22 * @version 1.0 * @author AnhMH */ class Model_Atvn_Product extends Model_Abstract { /** @var array $_properties field of table */ protected static $_properties = array( 'id', 'aff_link', 'brand', 'category_id', 'category_name', 'description', 'discount', 'image', 'link', 'name', 'price', 'product_category', 'short_desc', 'disable', 'created', 'is_hot' ); protected static $_observers = array( 'Orm\Observer_CreatedAt' => array( 'events' => array('before_insert'), 'mysql_timestamp' => false, ), 'Orm\Observer_UpdatedAt' => array( 'events' => array('before_update'), 'mysql_timestamp' => false, ), ); /** @var array $_table_name name of table */ protected static $_table_name = 'atvn_products'; /** * import data from batch * * @author AnhMH * @param array $param Input data * @return array|bool Detail Admin or false if error */ public static function import() { $data = \Lib\AccessTrade::getTopProducts(); $updateField = array(); $addUpdateData = array(); $time = time(); foreach (self::$_properties as $val) { $updateField[$val] = DB::expr("VALUES({$val})"); } if (!empty($data['data'])) { foreach ($data['data'] as $val) { $tmp = array( 'id' => $val['product_id'], 'aff_link' => $val['aff_link'], 'brand' => !empty($val['brand']) ? $val['brand'] : '', 'category_id' => !empty($val['category_id']) ? $val['category_id'] : '', 'category_name' => !empty($val['category_name']) ? $val['category_name'] : '', 'description' => !empty($val['desc']) ? $val['desc'] : '', 'discount' => !empty($val['discount']) ? $val['discount'] : '', 'image' => !empty($val['image']) ? $val['image'] : '', 'link' => !empty($val['link']) ? $val['link'] : '', 'name' => !empty($val['name']) ? $val['name'] : '', 'price' => !empty($val['price']) ? $val['price'] : '', 'product_category' => !empty($val['product_category']) ? $val['product_category'] : '', 'short_desc' => !empty($val['short_desc']) ? $val['short_desc'] : '', 'created' => $time ); $addUpdateData[] = $tmp; } self::batchInsert(self::$_table_name, $addUpdateData, $updateField); } return true; } /** * Get all * @author AnhMH * @param array $param Input data * @return array|bool Detail Product or false if error */ public static function get_all($param) { // Query $query = DB::select( self::$_table_name.'.*' ) ->from(self::$_table_name) ; // Filter if (!empty($param['from_front'])) { $query->where(self::$_table_name . '.price', '>', 0); $query->where(self::$_table_name . '.disable', 0); } // Pagination if (!empty($param['page']) && $param['limit']) { $offset = ($param['page'] - 1) * $param['limit']; $query->limit($param['limit'])->offset($offset); } // Sort if (!empty($param['sort'])) { if (!self::checkSort($param['sort'])) { self::errorParamInvalid('sort'); return false; } $sortExplode = explode('-', $param['sort']); if ($sortExplode[0] == 'created') { $sortExplode[0] = self::$_table_name . '.created'; } $query->order_by($sortExplode[0], $sortExplode[1]); } else { $query->order_by(self::$_table_name . '.is_hot', 'DESC'); $query->order_by(self::$_table_name . '.created', 'DESC'); } // Get data $data = $query->execute()->as_array(); return $data; } }
Java
UTF-8
81
1.742188
2
[]
no_license
package com.msus.GameOfLifeView; public enum Actions { STEP,START,STOP; }
C
UTF-8
1,162
3.71875
4
[]
no_license
#include <stdio.h> typedef struct { int c[20]; int front; int rear; }queue; void enqueue(queue *q,int n) { if (q->rear==20) printf("Queue Full\n"); else { int i,j,t; q->c[(q->rear)++]=n; for (i=0;i<q->rear-1;i++) { for (j=0;j<q->rear-i-1;j++) { if (q->c[j]>q->c[j+1]) { t=q->c[j]; q->c[j]=q->c[j+1]; q->c[j+1]=t; } } } } } int dequeue(queue *q) { if (q->front==q->rear) { printf("Queue Empty"); return -1; } else return q->c[--(q->rear)]; } void display(queue *q) { int i; for (i=q->front;i<q->rear;i++) printf("%d\t",q->c[i]); printf("\n"); } int main() { int z=0,k,e; queue q; q.front=0; q.rear=0; while (z==0) { printf("1. Enqueue \t4. Dequeue \t5. Display \t6. Exit\n"); scanf("%d",&k); switch(k) { case 1: { scanf("%d",&e); enqueue(&q,e); break; } case 2: { break; } case 3: { break; } case 4: { printf ("%d\n",dequeue(&q)); break; } case 5: { display(&q); break; } case 6: { z=1; } } } }
SQL
UTF-8
381
2.671875
3
[]
no_license
QUERYVALIDACAO select 1 from sys.sysreferences r join sys.sysobjects o on (o.id = r.constid and o.type = 'F') where r.fkeyid = object_id('INFM_ITEMPROCESSO') and o.name = 'FK_INFM_ITEMPROCESSO_INFM_PROCESSO' BANCODEDADOS IGERENCE alter table INFM_ITEMPROCESSO add constraint FK_INFM_ITEMPROCESSO_INFM_PROCESSO foreign key (IDPROCESSO) references INFM_PROCESSO (IDPROCESSO)
Java
UTF-8
453
2.015625
2
[]
no_license
package com.cangli.tech.intersect.internet; import android.os.Build; /** * Created by Alienware on 2016/8/10. */ public class DeviceId { private String DEVICE_ID; public DeviceId(){ generateDeviceId(); } private void generateDeviceId() { DEVICE_ID = new String(); String SerialNumber = Build.SERIAL; DEVICE_ID = SerialNumber; } public String getDeviceId(){ return DEVICE_ID; } }
Java
UTF-8
641
3.59375
4
[]
no_license
package arthmetic; import java.util.Scanner; public class Threechar { /** *题目描述 * 给定一个英文字符串,请写一段代码找出这个字符串中首先出现三次的那个英文字符(需要区分大小写)。 * 输入描述: * 输入数据一个字符串,包括字母,数字等。 * 输出描述: * 输出首先出现三次的那个英文字符 * */ public static void main(String[] args) { Scanner in = new Scanner(System.in); while(in.hasNext()){ String datastr = in.nextLine(); String[] data = datastr.split(" "); } } }
Java
UTF-8
1,064
4.15625
4
[]
no_license
package com.algorithm.dynamic_programming; public class IntegerBreak { /** * 给定一个正整数 n,将其拆分为至少两个正整数的和,并使这些整数的乘积最大化。 返回你可以获得的最大乘积。 * * 例如,给定 n = 2,返回1(2 = 1 + 1);给定 n = 10,返回36(10 = 3 + 3 + 4)。 * * 注意:你可以假设 n 不小于2且不大于58。 */ public static void main(String[] args) { int n = 10; System.out.println(integerBreak(n)); } private static int integerBreak(int n) { int array[] = new int[n + 1]; array[0] = 0; array[1] = 1; for (int i = 2; i <= n; i++) { for (int j = 1; j <= i - j; j++) { int tmp = Math.max(array[j], j) * Math.max(array[i - j], i - j); array[i] = Math.max(tmp, array[i]); // array[i] = Math.max(Math.max(Math.max(array[j], j) * array[i - j], j * (i - j)), array[i]); } } return array[n]; } }
JavaScript
UTF-8
481
3.171875
3
[]
no_license
const RIGHT_WALL = 220; const FALL_SPEED = 0.5; class FallingObject { constructor(img, canvasContext, itemType) { this.img = img; this.canvasContext = canvasContext; this.itemType = itemType; this.posX = Math.floor(Math.random() * RIGHT_WALL); this.posY = 0; } updatePos() { this.canvasContext.drawImage(this.img, this.posX,this.posY, 25,25); if (this.posY <= 120) { this.posY += FALL_SPEED; } } } module.exports = FallingObject;
Python
UTF-8
781
2.796875
3
[]
no_license
from flask import Flask, render_template, request, redirect, url_for import os app = Flask(__name__) # view function # represents a html page # single forward slash --> root url @app.route('/') def hello(): return "Hello World" @app.route('/about-our-company') def about(): return "About Me" @app.route('/catalog') def show_catalog(): return render_template('catalog.template.html') @app.route('/greeting/<name>') def greet(name): return "Hello " + name @app.route('/add/<n1>/<n2>') def add(n1, n2): r = int(n1) + int(n2) return render_template('results.template.html', result=r) # "magic code" -- boilerplate if __name__ == '__main__': app.run(host=os.environ.get('IP'), port=int(os.environ.get('PORT')), debug=True)
JavaScript
UTF-8
348
3.515625
4
[]
no_license
'use strict'; // function now(){ // return 21; // } // // function later(){ // console.log(`meaning of life is ${answer*2}`); // } // // let answer = now(); // setTimeout(later,10); //NOW we set up an action for LATER console.log('A'); setTimeout(function fc(){ console.log('C'); },100); // console.log(`B ${fc.name}`); console.log(`B `);
C#
UTF-8
3,226
2.96875
3
[]
no_license
using System; using System.Linq; namespace TeamEeyore.SpaceShip { class HelpMenu { static byte curX = (byte)(Console.WindowWidth - 10); static byte curY = 0; static byte tempX = curX; static byte tempY = curY; public static void Help() { Page1(); ChangePage(); } static void Page1() { #region PrintShips for (int i = 0; i < 9; i++) { MainMenu.Print(curX, curY, "#", ConsoleColor.Green); if (i == 0 || i == 8) { for (byte j = 0; j < 5; j++) { MainMenu.Print(curX, j, "#", ConsoleColor.Green); } } curX++; if (i == 8) { curY = 5; curX = tempX; for (int g = 0; g < 9; g++) { MainMenu.Print(curX, curY, "#", ConsoleColor.Green); curX++; } } } Console.WriteLine(); MainMenu.Print(Console.WindowWidth - 7, 2, "|=0=|", ConsoleColor.Red); curX = 0; curY = (byte)(Console.WindowHeight - 7); for (int i = 0; i < 11; i++) { MainMenu.Print(curX, curY, "#", ConsoleColor.Green); if (i == 0 || i == 10) { for (int j = curY; j < curY + 5; j++) { MainMenu.Print(curX, j, "#", ConsoleColor.Green); } } curX++; if (i == 10) { curX = 0; for (int g = 0; g < 11; g++) { MainMenu.Print(curX, curY + 5, "#", ConsoleColor.Green); curX++; } } } MainMenu.Print(2, Console.WindowHeight - 4, "|==0==|", ConsoleColor.Red); #endregion MainMenu.Print(Console.WindowWidth - 36, 2, "This is your Spaceship -->", ConsoleColor.Cyan); MainMenu.Print(13, Console.WindowHeight - 4, "<-- These are your enemies", ConsoleColor.Cyan); MainMenu.Print(Console.WindowWidth - 15, Console.WindowHeight - 5, "--> Move Left", ConsoleColor.Cyan); MainMenu.Print(Console.WindowWidth - 15, Console.WindowHeight - 4, "<-- Move Right", ConsoleColor.Cyan); MainMenu.Print(Console.WindowWidth - 15, Console.WindowHeight - 3, " F Shoot", ConsoleColor.Cyan); MainMenu.Print(0, 0, "\"SPACESHIP\" HELP CONTENT:", ConsoleColor.Cyan); MainMenu.Print(0, 1, "(press b to go back)", ConsoleColor.Cyan); } static void ChangePage() { ConsoleKeyInfo key = Console.ReadKey(true); while (key.Key != ConsoleKey.B) { key = Console.ReadKey(); } Console.Clear(); MainMenu.Main(); } } }
Markdown
UTF-8
2,567
2.921875
3
[ "MIT" ]
permissive
# 软件项目管理 - 综述 ## 介绍 本文主要描述以下几个方面: - [产出物](#产出物) - [角色和他们的职责](#角色和他们的职责) - [项目管理流程](#项目管理流程) ## 产出物 一个项目的会产出什么? ### 发布的内容 - 用户手册 负责人: `Information Developer` - Installers 负责人: `DevOps Developer` ### 规范文档 规范文档应该有公司一个技术委员会来负责。 - 项目流程定义 负责人: `Project Manager` - 文档规范 - 代码规范 ### 内部 - 需求文档 负责人: `Product Manager` - 设计文档 负责人: 任何人 - 测试用例 负责人: `Tester` - 源代码 负责人: `Developer`, `Tester`, `DevOps Developer` - 项目开发计划 负责人: `Developer` - 项目测试计划 负责人: `Tester` - 项目开发运营计划 负责人: `DevOps Developer` - 项目文档计划 负责人: `Information Developer` - 项目架构设计文档 负责人: `Architect` ### 项目执行结果 - 项目计划执行结果 负责人: `Project Manager` - 测试结果 负责人: `Tester` ### 资产 - 团队人员列表 负责人: `Project Manager` - 服务器 负责人: `DevOps Developer` ## 角色和他们的职责 这里,我们使用一个逻辑的角色模型,来描述一个团队的组成和成员的职责。 在真实世界里,一个人可以扮演多个角色,当然,一个角色也可以被多个人共同承担。 - Project Manager 负责项目流程的运作。 - Product Manager 负责产品的需求定义。 - Architect 负责产品的技术架构。 - Developer 负责开发产品 - Tester 负责测试产品 - DevOps Developer 负责开发中的运维工作。 - Information Developer 负责产品的文档编辑 ### 项目经理的职责 - 负责建立与外界的沟通渠道 - 负责收集项目进度信息 - 负责收集项目的指数信息 ### 架构师的职责 - [建立软件的框架](guidelines/Architecture.md) - 负责编辑代码规范 - 负责开发环境配置流程 - 负责代码版本控制流程 - 管理软件每个版本的依赖环境信息 - 管理软件每个版本的第三方组件版本信息 ## 项目管理流程 1. [流程:项目流程](processes/Process%20Project.md) 2. [流程:项目的估算](processes/Process%20Estimation.md) 3. [流程:Feature管理](processes/Process%20Feature%20Management.md) 4. [流程:Defect管理](processes/Process%20Defect%20Management.md) 5. [流程:产品版本管理](processes/Process%20Product%20Versions.md)
Markdown
UTF-8
5,053
3.0625
3
[ "CC-BY-SA-4.0", "CC-BY-SA-3.0", "MIT" ]
permissive
# Azure App Services and Subdomain Takeovers ## Introduction Azure Web Apps enables you to build and host web applications in the programming language of your choice without managing infrastructure. It offers auto-scaling and high availability, supports both Windows and Linux, and enables automated deployments from GitHub, Azure DevOps, or any Git repo. ## What are we going to cover? We will look at how we can - Identify a domain belonging to a target that is vulnerable to a subdomain takeover - Use the information we collect to create an Azure App Service to take over the subdomain **Please note:** This chapter requires the existence of CNAMES that do not point to anything (dangling CNAMES). Best to read through this chapter as we will not be able to create CNAMES for everyone trying is exercise outisde a classroom setting. Take a look at the references at the bottom of this page for a real world example. ## Steps to Identify a vulnerable subdomain The following steps can be used to identify a subdomain that is potentially vulnerable to a subdomain takeover 1. Our target domain is `galaxybutter.co`. 2. While doing reconnaissance, a sub domain was discovered, `users.galaxybutter.co` 3. Browse to this sub domain at `https://users.galaxybutter.co` and notice the error 4. Perform a DNS A query to identify the IP address of this sub domain using `dig A users.galaxybutter.co`. Notice the NXDOMAIN response. This means that there is no such domain. 5. Perform a DNS CNAME lookup using `dig CNAME users.galaxybutter.co` 6. The CNAME points to an Azure App Service that was probably deprecated/removed 7. An attacker can now create an Azure App service with the same name and host phishing content, resulting in a sub domain takeover ## Steps to create an App Service We will work in groups for this. ### Steps to hijack the sub domain This is essentially two steps from here 1. Configure the App Service name to point to the subdomain 2. Add custom content to the site to show its been taken over ### Creat an App Service and point it to the missing CNAME 1. In the Azure Portal, click on `All Services` and search for `App Services`. 2. Click on `Add` and select the most basic app from the Web window that opens. 3. Click on `Create`. 4. Provide the App name as `XXXXXXXXXX`. Replace `XXXXXXXXXX` with your team name. The App will be hosted at `XXXXXXXXXX.azurewebsites.net` 5. Select Runtime Stack as PHP 7.3. Any stack could be chosen here, but since our objective is to show subdomain takeover, it doesn't really matter for this Proof of Concept. 6. Under `Sku and size` select `Dev/Test > F1` 7. Click `Create`. If you receive an error, check the raw message's bottom most json body. ![Create App Service](images/create-web-app-service.png) 6. Once the App Service is created, go to its dashboard and under `Overview` click on `Browse` to see the deployment. #### Add a custom domain to the App Service 1. In the dashboard, scroll down to find `Custom domains` 2. Click on `Add hostname` and type `XXXXXXXXXX.galaxybutter.co`. Replace `XXXXXXXXXX` with your team name. 3. Click on `Validate` 4. Click on `Add hostname` to complete the configuration 5. Reload `https://XXXXXXXXXX.galaxybutter.co` and check if the takeover is complete. #### Show custom content 1. A deployment of a web application in the Azure App Service is beyond the scope of this training, however to show a Proof of Concept, we can simply update the index page shown when you browse to `https://XXXXXXXXXX.galaxybutter.co` 2. In the dashboard of the App Service, scroll down and click on `SSH`. Click on Go to launch the SSH shell for the App Service container. 3. Navigate to the `/var/www/html` folder and run the following command to create a simple file containing our text `echo Subdomain takeover example. > index.html` ![App Service Container SSH](images/app-service-shell-edit-html.png) 4. Reload the sub domain URL to see your message. ![Final sub domain takeover](images/subdomain-takeover-final.png) ## Finding Subdomain takeover at scale using FDNS Dataset (DEMO) Forward DNS dataset is published as part of Project Sonar. This data is created by extracting domain names from a number of sources and then sending DNS queries for each domain. The data format is a gzip-compressed JSON file. We can parse the dataset to find sub-domains for a given domain. The project also publishes CNAME records they have enumerated across the Internet. We can use this CNAME dataset to identify potential subdomain takeover issues across the Internet. https://opendata.rapid7.com/sonar.fdns_v2/ **Find Azure Websites using FDNS dataset** cat CNAME-DATASET-NAME | pigz -dc | grep -E "\.azurewebsites\.com" **Find AWS S3 based applications using FDNS dataset** cat CNAME-DATASET-NAME | pigz -dc | grep -E "\.s3\.amazonaws\.com" ## Additional References - [Can I take over](https://github.com/EdOverflow/can-i-take-over-xyz) - [Subdomain Takeover: Starbucks points to Azure](https://0xpatrik.com/subdomain-takeover-starbucks/)
C
UTF-8
35,020
2.703125
3
[ "BSD-2-Clause", "BSD-2-Clause-Patent" ]
permissive
/* * (C) Copyright 2016-2022 Intel Corporation. * * SPDX-License-Identifier: BSD-2-Clause-Patent */ /** * This file is part of cart, it implements the hash table functions. */ #define D_LOGFAC DD_FAC(mem) #include <pthread.h> #include <gurt/common.h> #include <gurt/list.h> #include <gurt/hash.h> enum d_hash_lru { D_HASH_LRU_TAIL = -1, D_HASH_LRU_NONE = 0, D_HASH_LRU_HEAD = 1, }; /****************************************************************************** * Hash functions / supporting routines ******************************************************************************/ /* * Each thread has CF_UUID_MAX number of thread-local buffers for UUID strings. * Each debug message can have at most this many CP_UUIDs. * * CF_UUID prints the first eight characters of the string representation. */ #define CF_UUID_MAX 8 #define CF_UUID "%.8s" #define D_UUID_STR_SIZE 37 /* 36 + 1 for '\0' */ static __thread char thread_uuid_str_buf[CF_UUID_MAX][D_UUID_STR_SIZE]; static __thread int thread_uuid_str_buf_idx; static char * CP_UUID(const void *uuid) { char *buf = thread_uuid_str_buf[thread_uuid_str_buf_idx]; uuid_unparse_lower(uuid, buf); thread_uuid_str_buf_idx = (thread_uuid_str_buf_idx + 1) % CF_UUID_MAX; return buf; } uint64_t d_hash_mix64(uint64_t key) { key = (~key) + (key << 21); key = key ^ (key >> 24); key = (key + (key << 3)) + (key << 8); key = key ^ (key >> 14); key = (key + (key << 2)) + (key << 4); key = key ^ (key >> 28); key = key + (key << 31); return key; } /** Robert Jenkins' 96 bit Mix Function */ uint32_t d_hash_mix96(uint32_t a, uint32_t b, uint32_t c) { a = a - b; a = a - c; a = a ^ (c >> 13); b = b - c; b = b - a; b = b ^ (a << 8); c = c - a; c = c - b; c = c ^ (b >> 13); a = a - b; a = a - c; a = a ^ (c >> 12); b = b - c; b = b - a; b = b ^ (a << 16); c = c - a; c = c - b; c = c ^ (b >> 5); a = a - b; a = a - c; a = a ^ (c >> 3); b = b - c; b = b - a; b = b ^ (a << 10); c = c - a; c = c - b; c = c ^ (b >> 15); return c; } /** consistent hash search */ unsigned int d_hash_srch_u64(uint64_t *hashes, unsigned int nhashes, uint64_t value) { int high = nhashes - 1; int low = 0; int i; for (i = high / 2; high - low > 1; i = (low + high) / 2) { if (value >= hashes[i]) low = i; else /* value < hashes[i] */ high = i; } return value >= hashes[high] ? high : low; } /* The djb2 string hash function, hash a string to a uint32_t value */ uint32_t d_hash_string_u32(const char *string, unsigned int len) { uint32_t result = 5381; const unsigned char *p; p = (const unsigned char *) string; for (; len > 0; len--) { result = (result << 5) + result + *p; ++p; } return result; } /** * Murmur hash * see https://sites.google.com/site/murmurhash */ #define MUR_PRIME 0xc6a4a7935bd1e995 #define MUR_ROTATE 47 uint64_t d_hash_murmur64(const unsigned char *key, unsigned int key_len, unsigned int seed) { const uint64_t *addr = (const uint64_t *)key; int loop = key_len >> 3; /* divided by sizeof uint64 */ int rest = key_len & ((1 << 3) - 1); int i; uint64_t mur; mur = seed ^ (key_len * MUR_PRIME); for (i = 0; i < loop; i++) { uint64_t k = addr[i]; k *= MUR_PRIME; k ^= k >> MUR_ROTATE; k *= MUR_PRIME; mur ^= k; mur *= MUR_PRIME; } key = (const unsigned char *)&addr[i]; switch (rest) { case 7: mur ^= (uint64_t)key[6] << 48; case 6: mur ^= (uint64_t)key[5] << 40; case 5: mur ^= (uint64_t)key[4] << 32; case 4: mur ^= (uint64_t)key[3] << 24; case 3: mur ^= (uint64_t)key[2] << 16; case 2: mur ^= (uint64_t)key[1] << 8; case 1: mur ^= (uint64_t)key[0]; mur *= MUR_PRIME; }; mur ^= mur >> MUR_ROTATE; mur *= MUR_PRIME; mur ^= mur >> MUR_ROTATE; return mur; } /** * Jump Consistent Hash Algorithm that provides a bucket location * for the given key. This algorithm hashes a minimal (1/n) number * of keys to a new bucket when extending the number of buckets. * * \param[in] key A unique key representing the object that * will be placed in the bucket. * \param[in] num_buckets The total number of buckets the hashing * algorithm can choose from. * * \return Returns an index ranging from 0 to * num_buckets representing the bucket * the given key hashes to. */ uint32_t d_hash_jump(uint64_t key, uint32_t num_buckets) { int64_t z = -1; int64_t y = 0; while (y < num_buckets) { z = y; key = key * 2862933555777941757ULL + 1; y = (z + 1) * ((double)(1LL << 31) / ((double)((key >> 33) + 1))); } return z; } /****************************************************************************** * Generic Hash Table functions / data structures ******************************************************************************/ /** * Lock the hash table * * Note: if hash table is using rwlock, it only takes read lock for * reference-only operations and caller should protect refcount. * see D_HASH_FT_RWLOCK for the details. */ static inline void ch_bucket_lock(struct d_hash_table *htable, uint32_t idx, bool read_only) { union d_hash_lock *lock; if (htable->ht_feats & D_HASH_FT_NOLOCK) return; lock = (htable->ht_feats & D_HASH_FT_GLOCK) ? &htable->ht_lock : &htable->ht_locks[idx]; if (htable->ht_feats & D_HASH_FT_MUTEX) { D_MUTEX_LOCK(&lock->mutex); } else if (htable->ht_feats & D_HASH_FT_RWLOCK) { if (read_only) D_RWLOCK_RDLOCK(&lock->rwlock); else D_RWLOCK_WRLOCK(&lock->rwlock); } else { D_SPIN_LOCK(&lock->spin); } } /** unlock the hash table */ static inline void ch_bucket_unlock(struct d_hash_table *htable, uint32_t idx, bool read_only) { union d_hash_lock *lock; if (htable->ht_feats & D_HASH_FT_NOLOCK) return; lock = (htable->ht_feats & D_HASH_FT_GLOCK) ? &htable->ht_lock : &htable->ht_locks[idx]; if (htable->ht_feats & D_HASH_FT_MUTEX) D_MUTEX_UNLOCK(&lock->mutex); else if (htable->ht_feats & D_HASH_FT_RWLOCK) D_RWLOCK_UNLOCK(&lock->rwlock); else D_SPIN_UNLOCK(&lock->spin); } /** * wrappers for member functions. */ static inline bool ch_key_cmp(struct d_hash_table *htable, d_list_t *link, const void *key, unsigned int ksize) { return htable->ht_ops->hop_key_cmp(htable, link, key, ksize); } static inline void ch_key_init(struct d_hash_table *htable, d_list_t *link, void *arg) { htable->ht_ops->hop_key_init(htable, link, arg); } /** * Convert key to hash bucket id. * * It calls DJB2 hash if no customized hash function is provided. */ static inline uint32_t ch_key_hash(struct d_hash_table *htable, const void *key, unsigned int ksize) { uint32_t idx; if (htable->ht_ops->hop_key_hash) idx = htable->ht_ops->hop_key_hash(htable, key, ksize); else idx = d_hash_string_u32((const char *)key, ksize); return idx & ((1U << htable->ht_bits) - 1); } static inline uint32_t ch_rec_hash(struct d_hash_table *htable, d_list_t *link) { uint32_t idx = 0; if (htable->ht_ops->hop_rec_hash) idx = htable->ht_ops->hop_rec_hash(htable, link); else D_ASSERT(htable->ht_feats & (D_HASH_FT_NOLOCK | D_HASH_FT_GLOCK)); return idx & ((1U << htable->ht_bits) - 1); } static inline void ch_rec_addref(struct d_hash_table *htable, d_list_t *link) { if (htable->ht_ops->hop_rec_addref) htable->ht_ops->hop_rec_addref(htable, link); } static inline bool ch_rec_decref(struct d_hash_table *htable, d_list_t *link) { return htable->ht_ops->hop_rec_decref ? htable->ht_ops->hop_rec_decref(htable, link) : false; } static inline void ch_rec_free(struct d_hash_table *htable, d_list_t *link) { if (htable->ht_ops->hop_rec_free) htable->ht_ops->hop_rec_free(htable, link); } static inline void ch_rec_insert(struct d_hash_table *htable, struct d_hash_bucket *bucket, d_list_t *link) { d_list_add(link, &bucket->hb_head); #if D_HASH_DEBUG htable->ht_nr++; if (htable->ht_nr > htable->ht_nr_max) htable->ht_nr_max = htable->ht_nr; if (htable->ht_ops->hop_rec_hash) { bucket->hb_dep++; if (bucket->hb_dep > htable->ht_dep_max) { htable->ht_dep_max = bucket->hb_dep; D_DEBUG(DB_TRACE, "Max depth %d/%d/%d\n", htable->ht_dep_max, htable->ht_nr, htable->ht_nr_max); } } #endif } /** * Insert the record into the hash table and take refcount on it if * "ephemeral" is not set. */ static inline void ch_rec_insert_addref(struct d_hash_table *htable, struct d_hash_bucket *bucket, d_list_t *link) { if (!(htable->ht_feats & D_HASH_FT_EPHEMERAL)) ch_rec_addref(htable, link); ch_rec_insert(htable, bucket, link); } static inline void ch_rec_delete(struct d_hash_table *htable, d_list_t *link) { d_list_del_init(link); #if D_HASH_DEBUG htable->ht_nr--; if (htable->ht_ops->hop_rec_hash) { struct d_hash_bucket *bucket; bucket = &htable->ht_buckets[ch_rec_hash(htable, link)]; bucket->hb_dep--; } #endif } /** * Delete the record from the hash table, it also releases refcount of it if * "ephemeral" is not set. */ static inline bool ch_rec_del_decref(struct d_hash_table *htable, d_list_t *link) { bool zombie = false; ch_rec_delete(htable, link); if (!(htable->ht_feats & D_HASH_FT_EPHEMERAL)) zombie = ch_rec_decref(htable, link); return zombie; } static inline d_list_t * ch_rec_find(struct d_hash_table *htable, struct d_hash_bucket *bucket, const void *key, unsigned int ksize, enum d_hash_lru lru) { d_list_t *link; bool lru_enabled = (htable->ht_feats & D_HASH_FT_LRU) && (lru != D_HASH_LRU_NONE); d_list_for_each(link, &bucket->hb_head) { if (ch_key_cmp(htable, link, key, ksize)) { if (lru_enabled) { if (lru == D_HASH_LRU_HEAD && link != bucket->hb_head.next) d_list_move(link, &bucket->hb_head); else if (lru == D_HASH_LRU_TAIL && link != bucket->hb_head.prev) d_list_move_tail(link, &bucket->hb_head); } return link; } } return NULL; } bool d_hash_rec_unlinked(d_list_t *link) { return d_list_empty(link); } d_list_t * d_hash_rec_find(struct d_hash_table *htable, const void *key, unsigned int ksize) { struct d_hash_bucket *bucket; d_list_t *link; uint32_t idx; bool is_lru = (htable->ht_feats & D_HASH_FT_LRU); D_ASSERT(key != NULL && ksize != 0); idx = ch_key_hash(htable, key, ksize); bucket = &htable->ht_buckets[idx]; ch_bucket_lock(htable, idx, !is_lru); link = ch_rec_find(htable, bucket, key, ksize, D_HASH_LRU_HEAD); if (link != NULL) ch_rec_addref(htable, link); ch_bucket_unlock(htable, idx, !is_lru); return link; } int d_hash_rec_insert(struct d_hash_table *htable, const void *key, unsigned int ksize, d_list_t *link, bool exclusive) { struct d_hash_bucket *bucket; d_list_t *tmp; uint32_t idx; int rc = 0; D_ASSERT(key != NULL && ksize != 0); idx = ch_key_hash(htable, key, ksize); bucket = &htable->ht_buckets[idx]; ch_bucket_lock(htable, idx, false); if (exclusive) { tmp = ch_rec_find(htable, bucket, key, ksize, D_HASH_LRU_NONE); if (tmp) { D_DEBUG(DB_TRACE, "Dup key detected\n"); D_GOTO(out_unlock, rc = -DER_EXIST); } } ch_rec_insert_addref(htable, bucket, link); out_unlock: ch_bucket_unlock(htable, idx, false); return rc; } d_list_t * d_hash_rec_find_insert(struct d_hash_table *htable, const void *key, unsigned int ksize, d_list_t *link) { struct d_hash_bucket *bucket; d_list_t *tmp; uint32_t idx; D_ASSERT(key != NULL && ksize != 0); idx = ch_key_hash(htable, key, ksize); bucket = &htable->ht_buckets[idx]; ch_bucket_lock(htable, idx, false); tmp = ch_rec_find(htable, bucket, key, ksize, D_HASH_LRU_HEAD); if (tmp) { ch_rec_addref(htable, tmp); link = tmp; D_GOTO(out_unlock, 0); } ch_rec_insert_addref(htable, bucket, link); out_unlock: ch_bucket_unlock(htable, idx, false); return link; } int d_hash_rec_insert_anonym(struct d_hash_table *htable, d_list_t *link, void *arg) { struct d_hash_bucket *bucket; uint32_t idx; uint32_t nr = 1U << htable->ht_bits; bool need_lock = !(htable->ht_feats & D_HASH_FT_NOLOCK); bool need_keyinit_lock; if (htable->ht_ops->hop_key_init == NULL) return -DER_INVAL; need_keyinit_lock = !(htable->ht_feats & D_HASH_FT_NO_KEYINIT_LOCK); if (need_lock && need_keyinit_lock) { /* Lock all buckets because of unknown key yet */ for (idx = 0; idx < nr; idx++) { ch_bucket_lock(htable, idx, false); if (htable->ht_feats & D_HASH_FT_GLOCK) break; } } /* has no key, hash table should have provided key generator */ ch_key_init(htable, link, arg); idx = ch_rec_hash(htable, link); bucket = &htable->ht_buckets[idx]; if (need_lock && !need_keyinit_lock) ch_bucket_lock(htable, idx, false); ch_rec_insert_addref(htable, bucket, link); if (need_lock) { if (!need_keyinit_lock) { ch_bucket_unlock(htable, idx, false); } else { for (idx = 0; idx < nr; idx++) { ch_bucket_unlock(htable, idx, false); if (htable->ht_feats & D_HASH_FT_GLOCK) break; } } } return 0; } bool d_hash_rec_delete(struct d_hash_table *htable, const void *key, unsigned int ksize) { struct d_hash_bucket *bucket; d_list_t *link; uint32_t idx; bool deleted = false; bool zombie = false; D_ASSERT(key != NULL && ksize != 0); idx = ch_key_hash(htable, key, ksize); bucket = &htable->ht_buckets[idx]; ch_bucket_lock(htable, idx, false); link = ch_rec_find(htable, bucket, key, ksize, D_HASH_LRU_NONE); if (link != NULL) { zombie = ch_rec_del_decref(htable, link); deleted = true; } ch_bucket_unlock(htable, idx, false); if (zombie) ch_rec_free(htable, link); return deleted; } bool d_hash_rec_delete_at(struct d_hash_table *htable, d_list_t *link) { uint32_t idx = 0; bool deleted = false; bool zombie = false; bool need_lock = !(htable->ht_feats & D_HASH_FT_NOLOCK); if (need_lock) { idx = ch_rec_hash(htable, link); ch_bucket_lock(htable, idx, false); } if (!d_list_empty(link)) { zombie = ch_rec_del_decref(htable, link); deleted = true; } if (need_lock) ch_bucket_unlock(htable, idx, false); if (zombie) ch_rec_free(htable, link); return deleted; } bool d_hash_rec_evict(struct d_hash_table *htable, const void *key, unsigned int ksize) { struct d_hash_bucket *bucket; d_list_t *link; uint32_t idx; if (!(htable->ht_feats & D_HASH_FT_LRU)) return false; D_ASSERT(key != NULL && ksize != 0); idx = ch_key_hash(htable, key, ksize); bucket = &htable->ht_buckets[idx]; ch_bucket_lock(htable, idx, false); link = ch_rec_find(htable, bucket, key, ksize, D_HASH_LRU_TAIL); ch_bucket_unlock(htable, idx, false); return link != NULL; } bool d_hash_rec_evict_at(struct d_hash_table *htable, d_list_t *link) { struct d_hash_bucket *bucket; uint32_t idx; bool evicted = false; if (!(htable->ht_feats & D_HASH_FT_LRU)) return false; idx = ch_rec_hash(htable, link); bucket = &htable->ht_buckets[idx]; ch_bucket_lock(htable, idx, false); if (link != bucket->hb_head.prev) { d_list_move_tail(link, &bucket->hb_head); evicted = true; } ch_bucket_unlock(htable, idx, false); return evicted; } void d_hash_rec_addref(struct d_hash_table *htable, d_list_t *link) { uint32_t idx = 0; bool need_lock = !(htable->ht_feats & D_HASH_FT_NOLOCK); if (need_lock) { idx = ch_rec_hash(htable, link); ch_bucket_lock(htable, idx, true); } ch_rec_addref(htable, link); if (need_lock) ch_bucket_unlock(htable, idx, true); } void d_hash_rec_decref(struct d_hash_table *htable, d_list_t *link) { uint32_t idx = 0; bool need_lock = !(htable->ht_feats & D_HASH_FT_NOLOCK); bool ephemeral = (htable->ht_feats & D_HASH_FT_EPHEMERAL); bool zombie; if (need_lock) { idx = ch_rec_hash(htable, link); ch_bucket_lock(htable, idx, !ephemeral); } zombie = ch_rec_decref(htable, link); if (zombie && ephemeral && !d_list_empty(link)) ch_rec_delete(htable, link); D_ASSERT(!zombie || d_list_empty(link)); if (need_lock) ch_bucket_unlock(htable, idx, !ephemeral); if (zombie) ch_rec_free(htable, link); } int d_hash_rec_ndecref(struct d_hash_table *htable, int count, d_list_t *link) { uint32_t idx = 0; bool need_lock = !(htable->ht_feats & D_HASH_FT_NOLOCK); bool ephemeral = (htable->ht_feats & D_HASH_FT_EPHEMERAL); bool zombie = false; int rc = 0; if (need_lock) { idx = ch_rec_hash(htable, link); ch_bucket_lock(htable, idx, !ephemeral); } if (htable->ht_ops->hop_rec_ndecref) { rc = htable->ht_ops->hop_rec_ndecref(htable, link, count); if (rc >= 1) { zombie = true; rc = 0; } } else { do { zombie = ch_rec_decref(htable, link); } while (--count && !zombie); if (count != 0) rc = -DER_INVAL; } if (rc == 0) { if (zombie && ephemeral && !d_list_empty(link)) ch_rec_delete(htable, link); D_ASSERT(!zombie || d_list_empty(link)); } if (need_lock) ch_bucket_unlock(htable, idx, !ephemeral); if (zombie) ch_rec_free(htable, link); return rc; } /* Find an entry in the hash table. * * As d_hash_table_traverse() does not support removal from the callback * function save a pointer in *arg and return 1 to terminate the traverse. * This way we can iterate over the entries in the hash table and delete every * one. */ static inline int d_hash_find_single(d_list_t *link, void *arg) { d_list_t **p = arg; *p = link; return 1; } d_list_t * d_hash_rec_first(struct d_hash_table *htable) { d_list_t *link = NULL; int rc; rc = d_hash_table_traverse(htable, d_hash_find_single, &link); if (rc < 0) return NULL; return link; } int d_hash_table_create_inplace(uint32_t feats, uint32_t bits, void *priv, d_hash_table_ops_t *hops, struct d_hash_table *htable) { uint32_t nr = (1 << bits); uint32_t i; int rc = 0; D_ASSERT(hops != NULL); D_ASSERT(hops->hop_key_cmp != NULL); htable->ht_feats = feats; htable->ht_bits = bits; htable->ht_ops = hops; htable->ht_priv = priv; if (hops->hop_rec_hash == NULL && !(feats & D_HASH_FT_NOLOCK)) { htable->ht_feats |= D_HASH_FT_GLOCK; D_WARN("The d_hash_table_ops_t->hop_rec_hash() callback is " "not provided!\nTherefore the whole hash table locking " "will be used for backward compatibility.\n"); } D_ALLOC_ARRAY(htable->ht_buckets, nr); if (htable->ht_buckets == NULL) D_GOTO(out, rc = -DER_NOMEM); for (i = 0; i < nr; i++) D_INIT_LIST_HEAD(&htable->ht_buckets[i].hb_head); if (htable->ht_feats & D_HASH_FT_NOLOCK) D_GOTO(out, rc = 0); if (htable->ht_feats & D_HASH_FT_GLOCK) { if (htable->ht_feats & D_HASH_FT_MUTEX) rc = D_MUTEX_INIT(&htable->ht_lock.mutex, NULL); else if (htable->ht_feats & D_HASH_FT_RWLOCK) rc = D_RWLOCK_INIT(&htable->ht_lock.rwlock, NULL); else rc = D_SPIN_INIT(&htable->ht_lock.spin, PTHREAD_PROCESS_PRIVATE); if (rc) D_GOTO(free_buckets, rc); } else { D_ALLOC_ARRAY(htable->ht_locks, nr); if (htable->ht_locks == NULL) D_GOTO(free_buckets, rc = -DER_NOMEM); for (i = 0; i < nr; i++) { if (htable->ht_feats & D_HASH_FT_MUTEX) rc = D_MUTEX_INIT(&htable->ht_locks[i].mutex, NULL); else if (htable->ht_feats & D_HASH_FT_RWLOCK) rc = D_RWLOCK_INIT(&htable->ht_locks[i].rwlock, NULL); else rc = D_SPIN_INIT(&htable->ht_locks[i].spin, PTHREAD_PROCESS_PRIVATE); if (rc) D_GOTO(free_locks, rc); } } D_GOTO(out, rc = 0); free_locks: while (i > 0) { i--; /* last successful */ if (htable->ht_feats & D_HASH_FT_MUTEX) D_MUTEX_DESTROY(&htable->ht_locks[i].mutex); else if (htable->ht_feats & D_HASH_FT_RWLOCK) D_RWLOCK_DESTROY(&htable->ht_locks[i].rwlock); else D_SPIN_DESTROY(&htable->ht_locks[i].spin); } D_FREE(htable->ht_locks); free_buckets: D_FREE(htable->ht_buckets); out: return rc; } int d_hash_table_create(uint32_t feats, uint32_t bits, void *priv, d_hash_table_ops_t *hops, struct d_hash_table **htable_pp) { struct d_hash_table *htable; int rc; D_ALLOC_PTR(htable); if (htable == NULL) D_GOTO(out, rc = -DER_NOMEM); rc = d_hash_table_create_inplace(feats, bits, priv, hops, htable); if (rc) D_FREE(htable); out: *htable_pp = htable; return rc; } int d_hash_table_traverse(struct d_hash_table *htable, d_hash_traverse_cb_t cb, void *arg) { struct d_hash_bucket *bucket; d_list_t *link; uint32_t nr = 1U << htable->ht_bits; uint32_t idx; int rc = 0; if (htable->ht_buckets == NULL) { D_ERROR("d_hash_table %p not initialized (NULL buckets).\n", htable); D_GOTO(out, rc = -DER_UNINIT); } if (cb == NULL) { D_ERROR("invalid parameter, NULL cb.\n"); D_GOTO(out, rc = -DER_INVAL); } for (idx = 0; idx < nr && !rc; idx++) { bucket = &htable->ht_buckets[idx]; ch_bucket_lock(htable, idx, true); d_list_for_each(link, &bucket->hb_head) { rc = cb(link, arg); if (rc) break; } ch_bucket_unlock(htable, idx, true); } out: return rc; } static bool d_hash_table_is_empty(struct d_hash_table *htable) { uint32_t nr = 1U << htable->ht_bits; uint32_t idx; bool is_empty = true; if (htable->ht_buckets == NULL) { D_ERROR("d_hash_table %p not initialized (NULL buckets).\n", htable); D_GOTO(out, 0); } for (idx = 0; idx < nr && is_empty; idx++) { ch_bucket_lock(htable, idx, true); is_empty = d_list_empty(&htable->ht_buckets[idx].hb_head); ch_bucket_unlock(htable, idx, true); } out: return is_empty; } int d_hash_table_destroy_inplace(struct d_hash_table *htable, bool force) { struct d_hash_bucket *bucket; uint32_t nr = 1U << htable->ht_bits; uint32_t i; int rc = 0; for (i = 0; i < nr; i++) { bucket = &htable->ht_buckets[i]; while (!d_list_empty(&bucket->hb_head)) { if (!force) { D_DEBUG(DB_TRACE, "Warning, non-empty hash\n"); D_GOTO(out, rc = -DER_BUSY); } d_hash_rec_delete_at(htable, bucket->hb_head.next); } } if (htable->ht_feats & D_HASH_FT_NOLOCK) D_GOTO(free_buckets, rc = 0); if (htable->ht_feats & D_HASH_FT_GLOCK) { if (htable->ht_feats & D_HASH_FT_MUTEX) D_MUTEX_DESTROY(&htable->ht_lock.mutex); else if (htable->ht_feats & D_HASH_FT_RWLOCK) D_RWLOCK_DESTROY(&htable->ht_lock.rwlock); else D_SPIN_DESTROY(&htable->ht_lock.spin); } else { for (i = 0; i < nr; i++) { if (htable->ht_feats & D_HASH_FT_MUTEX) D_MUTEX_DESTROY(&htable->ht_locks[i].mutex); else if (htable->ht_feats & D_HASH_FT_RWLOCK) D_RWLOCK_DESTROY(&htable->ht_locks[i].rwlock); else D_SPIN_DESTROY(&htable->ht_locks[i].spin); } D_FREE(htable->ht_locks); } free_buckets: D_FREE(htable->ht_buckets); memset(htable, 0, sizeof(*htable)); out: return rc; } int d_hash_table_destroy(struct d_hash_table *htable, bool force) { int rc = d_hash_table_destroy_inplace(htable, force); if (!rc) D_FREE(htable); return rc; } void d_hash_table_debug(struct d_hash_table *htable) { #if D_HASH_DEBUG D_DEBUG(DB_TRACE, "max nr: %d, cur nr: %d, max_dep: %d\n", htable->ht_nr_max, htable->ht_nr, htable->ht_dep_max); #endif } /****************************************************************************** * DAOS Handle Hash Table Wrapper * * Note: These functions are not thread-safe because reference counting * operations are not internally lock-protected. The user must add their own * locking. ******************************************************************************/ struct d_hhash { ATOMIC uint64_t ch_cookie; struct d_hash_table ch_htable; /* server-side uses D_HTYPE_PTR handle */ bool ch_ptrtype; }; static inline struct d_rlink* link2rlink(d_list_t *link) { D_ASSERT(link != NULL); return container_of(link, struct d_rlink, rl_link); } static void rl_op_addref(struct d_rlink *rlink) { atomic_fetch_add_relaxed(&rlink->rl_ref, 1); } static bool rl_op_decref(struct d_rlink *rlink) { uint32_t oldref; oldref = atomic_fetch_sub_relaxed(&rlink->rl_ref, 1); D_ASSERT(oldref > 0); return oldref == 1; } static void rl_op_init(struct d_rlink *rlink) { D_INIT_LIST_HEAD(&rlink->rl_link); rlink->rl_initialized = 1; atomic_store_relaxed(&rlink->rl_ref, 1); /* for caller */ } static bool rl_op_empty(struct d_rlink *rlink) { bool is_unlinked; if (!rlink->rl_initialized) return true; is_unlinked = (atomic_load_relaxed(&rlink->rl_ref) == 0); if (is_unlinked) D_ASSERT(d_hash_rec_unlinked(&rlink->rl_link)); return is_unlinked; } static inline struct d_hlink * link2hlink(d_list_t *link) { struct d_rlink *rlink = link2rlink(link); return container_of(rlink, struct d_hlink, hl_link); } static void hh_op_key_init(struct d_hash_table *htable, d_list_t *link, void *arg) { struct d_hhash *hhash; struct d_hlink *hlink = link2hlink(link); int type = *(int *)arg; uint64_t cookie; hhash = container_of(htable, struct d_hhash, ch_htable); cookie = atomic_fetch_add_relaxed(&hhash->ch_cookie, 1); hlink->hl_key = (cookie << D_HTYPE_BITS) | (type & D_HTYPE_MASK); } static uint32_t hh_op_key_hash(struct d_hash_table *htable, const void *key, unsigned int ksize) { D_ASSERT(ksize == sizeof(uint64_t)); return (uint32_t)(*(const uint64_t *)key >> D_HTYPE_BITS); } static bool hh_op_key_cmp(struct d_hash_table *htable, d_list_t *link, const void *key, unsigned int ksize) { struct d_hlink *hlink = link2hlink(link); D_ASSERT(ksize == sizeof(uint64_t)); return hlink->hl_key == *(uint64_t *)key; } static uint32_t hh_op_rec_hash(struct d_hash_table *htable, d_list_t *link) { struct d_hlink *hlink = link2hlink(link); return (uint32_t)(hlink->hl_key >> D_HTYPE_BITS); } static void hh_op_rec_addref(struct d_hash_table *htable, d_list_t *link) { rl_op_addref(link2rlink(link)); } static bool hh_op_rec_decref(struct d_hash_table *htable, d_list_t *link) { return rl_op_decref(link2rlink(link)); } static void hh_op_rec_free(struct d_hash_table *htable, d_list_t *link) { struct d_hlink *hlink = link2hlink(link); if (hlink->hl_ops != NULL && hlink->hl_ops->hop_free != NULL) hlink->hl_ops->hop_free(hlink); } static d_hash_table_ops_t hh_ops = { .hop_key_init = hh_op_key_init, .hop_key_hash = hh_op_key_hash, .hop_key_cmp = hh_op_key_cmp, .hop_rec_hash = hh_op_rec_hash, .hop_rec_addref = hh_op_rec_addref, .hop_rec_decref = hh_op_rec_decref, .hop_rec_free = hh_op_rec_free, }; int d_hhash_create(uint32_t feats, uint32_t bits, struct d_hhash **hhash_pp) { struct d_hhash *hhash; int rc = 0; D_ALLOC_PTR(hhash); if (hhash == NULL) D_GOTO(out, rc = -DER_NOMEM); rc = d_hash_table_create_inplace(feats, bits, NULL, &hh_ops, &hhash->ch_htable); if (rc) { D_FREE(hhash); D_GOTO(out, rc); } atomic_store_relaxed(&hhash->ch_cookie, 1); hhash->ch_ptrtype = false; out: *hhash_pp = hhash; return rc; } void d_hhash_destroy(struct d_hhash *hhash) { d_hash_table_debug(&hhash->ch_htable); d_hash_table_destroy_inplace(&hhash->ch_htable, true); D_FREE(hhash); } int d_hhash_set_ptrtype(struct d_hhash *hhash) { if (!d_hash_table_is_empty(&hhash->ch_htable) && hhash->ch_ptrtype == false) { D_ERROR("d_hash_table %p not empty with non-ptr objects.\n", &hhash->ch_htable); return -DER_ALREADY; } hhash->ch_ptrtype = true; return 0; } bool d_hhash_is_ptrtype(struct d_hhash *hhash) { return hhash->ch_ptrtype; } void d_hhash_hlink_init(struct d_hlink *hlink, struct d_hlink_ops *hl_ops) { hlink->hl_ops = hl_ops; rl_op_init(&hlink->hl_link); } bool d_uhash_link_empty(struct d_ulink *ulink) { return rl_op_empty(&ulink->ul_link); } void d_hhash_link_insert(struct d_hhash *hhash, struct d_hlink *hlink, int type) { D_ASSERT(hlink->hl_link.rl_initialized); /* check if handle type fits in allocated bits */ D_ASSERTF(type < (1 << D_HTYPE_BITS), "Type (%d) does not fit in D_HTYPE_BITS (%d)\n", type, D_HTYPE_BITS); if (d_hhash_is_ptrtype(hhash)) { uint64_t ptr_key = (uintptr_t)hlink; D_ASSERTF(type == D_HTYPE_PTR, "direct/ptr-based htable can " "only contain D_HTYPE_PTR type entries"); D_ASSERTF(d_hhash_key_isptr(ptr_key), "hlink ptr %p is invalid " "D_HTYPE_PTR type", hlink); hlink->hl_key = ptr_key; ch_rec_addref(&hhash->ch_htable, &hlink->hl_link.rl_link); } else { D_ASSERTF(type != D_HTYPE_PTR, "PTR type key being inserted " "in a non ptr-based htable.\n"); d_hash_rec_insert_anonym(&hhash->ch_htable, &hlink->hl_link.rl_link, (void *)&type); } } static inline struct d_hlink* d_hlink_find(struct d_hash_table *htable, const void *key, unsigned int ksize) { d_list_t *link = d_hash_rec_find(htable, key, ksize); return link ? link2hlink(link) : NULL; } bool d_hhash_key_isptr(uint64_t key) { return ((key & 0x1) == 0); } struct d_hlink * d_hhash_link_lookup(struct d_hhash *hhash, uint64_t key) { if (d_hhash_key_isptr(key)) { struct d_hlink *hlink = (struct d_hlink *)key; if (hlink == NULL) { D_ERROR("NULL PTR type key.\n"); return NULL; } if (!d_hhash_is_ptrtype(hhash)) { D_ERROR("invalid PTR type key being lookup in a " "non ptr-based htable.\n"); return NULL; } if (hlink->hl_key != key) { D_ERROR("invalid PTR type key.\n"); return NULL; } d_hash_rec_addref(&hhash->ch_htable, &hlink->hl_link.rl_link); return hlink; } else { return d_hlink_find(&hhash->ch_htable, (void *)&key, sizeof(key)); } } bool d_hhash_link_delete(struct d_hhash *hhash, struct d_hlink *hlink) { if (d_hhash_key_isptr(hlink->hl_key)) { if (!d_hhash_is_ptrtype(hhash)) { D_ERROR("invalid PTR type key being lookup in a " "non ptr-based htable.\n"); return false; } d_hhash_link_putref(hhash, hlink); return true; } else { return d_hash_rec_delete_at(&hhash->ch_htable, &hlink->hl_link.rl_link); } } void d_hhash_link_getref(struct d_hhash *hhash, struct d_hlink *hlink) { ch_rec_addref(&hhash->ch_htable, &hlink->hl_link.rl_link); } void d_hhash_link_putref(struct d_hhash *hhash, struct d_hlink *hlink) { /* handle hash table should not use D_HASH_FT_EPHEMERAL */ D_ASSERT(!(hhash->ch_htable.ht_feats & D_HASH_FT_EPHEMERAL)); if (ch_rec_decref(&hhash->ch_htable, &hlink->hl_link.rl_link)) ch_rec_free(&hhash->ch_htable, &hlink->hl_link.rl_link); } bool d_hhash_link_empty(struct d_hlink *hlink) { return rl_op_empty(&hlink->hl_link); } void d_hhash_link_key(struct d_hlink *hlink, uint64_t *key) { *key = hlink->hl_key; } int d_hhash_key_type(uint64_t key) { return d_hhash_key_isptr(key) ? D_HTYPE_PTR : key & D_HTYPE_MASK; } /****************************************************************************** * UUID Hash Table Wrapper * Key: UUID * Value: generic pointer * * Note: These functions are not thread-safe because reference counting * operations are not internally lock-protected. The user must add their own * locking. ******************************************************************************/ struct d_uhash_bundle { struct d_uuid *key; /* additional args for comparison function */ void *cmp_args; }; static inline struct d_ulink * link2ulink(d_list_t *link) { struct d_rlink *rlink = link2rlink(link); return container_of(rlink, struct d_ulink, ul_link); } static void uh_op_rec_addref(struct d_hash_table *htable, d_list_t *link) { struct d_ulink *ulink = link2ulink(link); rl_op_addref(&ulink->ul_link); } static bool uh_op_rec_decref(struct d_hash_table *htable, d_list_t *link) { struct d_ulink *ulink = link2ulink(link); return rl_op_decref(&ulink->ul_link); } static uint32_t uh_op_key_hash(struct d_hash_table *htable, const void *key, unsigned int ksize) { struct d_uhash_bundle *uhbund = (struct d_uhash_bundle *)key; struct d_uuid *lkey = uhbund->key; uint32_t *retp = (uint32_t *)lkey->uuid; D_ASSERT(ksize == sizeof(struct d_uhash_bundle)); D_DEBUG(DB_TRACE, "uuid_key: "CF_UUID"\n", CP_UUID(lkey->uuid)); return *retp; } static uint32_t uh_op_rec_hash(struct d_hash_table *htable, d_list_t *link) { struct d_ulink *ulink = link2ulink(link); uint32_t *retp = (uint32_t *)ulink->ul_uuid.uuid; return *retp; } static bool uh_op_key_cmp(struct d_hash_table *htable, d_list_t *link, const void *key, unsigned int ksize) { struct d_ulink *ulink = link2ulink(link); struct d_uhash_bundle *uhbund = (struct d_uhash_bundle *)key; struct d_uuid *lkey = (struct d_uuid *)uhbund->key; bool res; D_ASSERT(ksize == sizeof(struct d_uhash_bundle)); D_DEBUG(DB_TRACE, "Link key, Key:"CF_UUID","CF_UUID"\n", CP_UUID(lkey->uuid), CP_UUID(ulink->ul_uuid.uuid)); res = ((uuid_compare(ulink->ul_uuid.uuid, lkey->uuid)) == 0); if (res && ulink->ul_ops != NULL && ulink->ul_ops->uop_cmp != NULL) res = ulink->ul_ops->uop_cmp(ulink, uhbund->cmp_args); return res; } static void uh_op_rec_free(struct d_hash_table *htable, d_list_t *link) { struct d_ulink *ulink = link2ulink(link); if (ulink->ul_ops != NULL && ulink->ul_ops->uop_free != NULL) ulink->ul_ops->uop_free(ulink); } static d_hash_table_ops_t uh_ops = { .hop_key_hash = uh_op_key_hash, .hop_key_cmp = uh_op_key_cmp, .hop_rec_hash = uh_op_rec_hash, .hop_rec_addref = uh_op_rec_addref, .hop_rec_decref = uh_op_rec_decref, .hop_rec_free = uh_op_rec_free, }; int d_uhash_create(uint32_t feats, uint32_t bits, struct d_hash_table **htable_pp) { return d_hash_table_create(feats, bits, NULL, &uh_ops, htable_pp); } void d_uhash_destroy(struct d_hash_table *htable) { d_hash_table_debug(htable); d_hash_table_destroy(htable, true); } void d_uhash_ulink_init(struct d_ulink *ulink, struct d_ulink_ops *ul_ops) { ulink->ul_ops = ul_ops; rl_op_init(&ulink->ul_link); } static inline struct d_ulink* d_ulink_find(struct d_hash_table *htable, void *key, unsigned int ksize) { d_list_t *link = d_hash_rec_find(htable, key, ksize); return link ? link2ulink(link) : NULL; } struct d_ulink* d_uhash_link_lookup(struct d_hash_table *htable, struct d_uuid *key, void *cmp_args) { struct d_uhash_bundle uhbund; uhbund.key = key; uhbund.cmp_args = cmp_args; return d_ulink_find(htable, (void *)&uhbund, sizeof(uhbund)); } void d_uhash_link_addref(struct d_hash_table *htable, struct d_ulink *ulink) { d_hash_rec_addref(htable, &ulink->ul_link.rl_link); } void d_uhash_link_putref(struct d_hash_table *htable, struct d_ulink *ulink) { d_hash_rec_decref(htable, &ulink->ul_link.rl_link); } int d_uhash_link_insert(struct d_hash_table *htable, struct d_uuid *key, void *cmp_args, struct d_ulink *ulink) { struct d_uhash_bundle uhbund; int rc = 0; D_ASSERT(ulink->ul_link.rl_initialized); uuid_copy(ulink->ul_uuid.uuid, key->uuid); uhbund.key = key; uhbund.cmp_args = cmp_args; rc = d_hash_rec_insert(htable, (void *)&uhbund, sizeof(uhbund), &ulink->ul_link.rl_link, true); if (rc) D_ERROR("Error Inserting handle in UUID in-memory hash: "DF_RC"\n", DP_RC(rc)); return rc; } bool d_uhash_link_last_ref(struct d_ulink *ulink) { return atomic_load_relaxed(&ulink->ul_link.rl_ref) == 1; } void d_uhash_link_delete(struct d_hash_table *htable, struct d_ulink *ulink) { d_hash_rec_delete_at(htable, &ulink->ul_link.rl_link); }
C++
UTF-8
1,262
2.703125
3
[ "BSD-3-Clause" ]
permissive
/* * Copyright Regents of the University of Minnesota, 2017. This software is released under the following license: http://opensource.org/licenses/ * Source code originally developed at the University of Minnesota Interactive Visualization Lab (http://ivlab.cs.umn.edu). * * Code author(s): * Dan Orban (dtorban) */ #ifndef FUNCTION_H_ #define FUNCTION_H_ #include "AnyItem/AnyItem.h" #include <string> namespace any_fw { class Function { public: virtual ~Function() {} const std::string& getName() const { return name; } virtual const any::AnyItem& getParameters() const { return parameters; } any::AnyItem operator()() { return (*this)(parameters); } virtual any::AnyItem operator()(const any::AnyItem& parameters) = 0; friend std::ostream& operator<<(std::ostream& stream, const Function& item); protected: Function(const std::string& name) : name(name) {} std::string name; any::AnyItem parameters; }; inline std::ostream& operator<<(std::ostream& out, const Function& method) { out << method.getName() << "("; if (method.getParameters().isValue()) { out << "\""; } out << method.getParameters(); if (method.getParameters().isValue()) { out << "\""; } out << ");"; return out; } } /* namespace any_fw */ #endif /* FUNCTION_H_ */
Python
UTF-8
1,284
2.5625
3
[]
no_license
from celery import Celery import time from urllib.request import urlopen import uuid app = Celery('tasks', broker='redis://35.165.238.44', backend='redis://35.165.238.44') @app.task def check_input_file(file_path): return file_path @app.task def move_input_file(file_path_start, file_path_end): return (file_path_start, file_path_end) @app.task def word_count_python(infile='readme.txt'): start = time.time() with open(infile) as reader: word_count = 0 for line in reader: word_count += len(line.split()) time.sleep(5) return (word_count, time.time() - start) @app.task def a001_get_file(file_url): start = time.time() ret = get_from_url(file_url) if not ret['status'] == 0: return ('a001 - error downloading url', time.time() - start) else: return (ret['file'], time.time() - start) def get_from_url(url, prefix=None): file_name = get_unique_file_name(prefix) response = urlopen(url) CHUNK = 16 * 1024 with open(file_name, 'wb') as f: while True: chunk = response.read(CHUNK) if not chunk: break f.write(chunk) return {'file':file_name, 'status':0} def get_unique_file_name(prefix=None): if prefix and type(prefix) == str: return prefix + str(uuid.uuid4()) else: return str(uuid.uuid4())
Markdown
UTF-8
1,084
2.578125
3
[ "MIT" ]
permissive
+++ # A Skills section created with the Featurette widget. widget = "featurette" # See https://sourcethemes.com/academic/docs/page-builder/ headless = true # This file represents a page section. active = true # Activate this widget? true/false weight = 30 # Order that this section will appear. title = "Skills" subtitle = "" # Showcase personal skills or business features. # # Add/remove as many `[[feature]]` blocks below as you like. # # For available icons, see: https://sourcethemes.com/academic/docs/widgets/#icons [[feature]] icon = "chart-area" icon_pack = "fas" name = "Visualizations" description = "Representing data using effective graphs, plots, and other special visualizations" [[feature]] icon = "chart-line" icon_pack = "fas" name = "Learning Analytics" description = "Extracting trends from learner data using analytical tools to improve learning" [[feature]] icon = "hospital" icon_pack = "fas" name = "Cancer Imaging" description = "Probing the tumour microenvironment with MRI techniques to investigate drug effect" +++
PHP
UTF-8
5,349
2.71875
3
[]
no_license
<?php class Categories { // constructor public function __construct() {} // get list of categories public static function get_categories($id_parent=0) { return self::list_categories($id_parent); } private function list_categories($id_parent) { global $mysqli; $current_datetime = date('Y-m-d H:i:s'); if (!$result = $mysqli->query('SELECT category.id, category_description.name, category.featured, (SELECT COUNT(c.id) FROM category AS c WHERE c.id_parent = category.id AND c.active = 1 AND c.start_date <= "'.$current_datetime.'" AND (c.end_date = "0000-00-00 00:00:00" OR c.end_date > "'.$current_datetime.'")) AS total_child FROM category INNER JOIN category_description ON (category.id = category_description.id_category AND category_description.language_code = "'.$_SESSION['customer']['language'].'") WHERE category.active = 1 AND category.start_date <= "'.$current_datetime.'" AND (category.end_date = "0000-00-00 00:00:00" OR category.end_date > "'.$current_datetime.'") AND category.id_parent = "'.$id_parent.'" ORDER BY category.sort_order ASC')) throw new Exception('An error occured while trying to get list of categories.'."\r\n\r\n".$mysqli->error); $categories = array(); $current_alias=''; if ($result->num_rows) { if (!$stmt_total_products = $mysqli->prepare('SELECT COUNT(t.id) AS total FROM ((SELECT product.id, product_image_variant.id AS id_product_image_variant FROM product_category INNER JOIN product ON (product_category.id_product = product.id) INNER JOIN product_image_variant ON (product.id = product_image_variant.id_product AND product_image_variant.displayed_in_listing = 1) WHERE product_category.id_category = ? AND product.active = 1 AND product.display_in_catalog = 1 AND product.date_displayed <= "'.$current_datetime.'" AND product.has_variants = 1) UNION (SELECT product.id, 0 AS id_product_image_variant FROM product_category INNER JOIN product ON (product_category.id_product = product.id) WHERE product_category.id_category = ? AND product.active = 1 AND product.display_in_catalog = 1 AND product.date_displayed <= "'.$current_datetime.'")) AS t')) throw new Exception('An error occured while trying to prepare get total products statement.'."\r\n\r\n".$mysqli->error); while ($row = $result->fetch_assoc()) { if (!$stmt_total_products->bind_param("ii", $row['id'], $row['id'])) throw new Exception('An error occured while trying to bind params to get total products statement.'."\r\n\r\n".$mysqli->error); /* Execute the statement */ if (!$stmt_total_products->execute()) throw new Exception('An error occured while trying to get total products.'."\r\n\r\n".$mysqli->error); /* store result */ $stmt_total_products->store_result(); /* bind result variables */ $stmt_total_products->bind_result($total_products); $stmt_total_products->fetch(); $categories[] = array( 'id' => $row['id'], 'name' => htmlspecialchars($row['name']), 'url' => self::get_url($row['id']), 'featured' => $row['featured'], 'childs' => $row['total_child'] ? self::list_categories($row['id']):array(), 'total_products' => $total_products, ); } $stmt_total_products->close(); } $result->free(); return $categories; } public static function get_url($id,$language_code='') { global $mysqli, $products, $url_prefix; $language_code = !empty($language_code) ? $language_code:$_SESSION['customer']['language']; $array = array(); if (!$stmt_get_alias = $mysqli->prepare('SELECT category.id_parent, category_description.alias FROM category INNER JOIN category_description ON (category.id = category_description.id_category AND category_description.language_code = "'.$mysqli->escape_string($language_code).'") WHERE category.id = ? LIMIT 1')) throw new Exception('An error occured while trying to prepare get category alias statement.'."\r\n\r\n".$mysqli->error); do { if (!$stmt_get_alias->bind_param("i", $id)) throw new Exception('An error occured while trying to bind params to get category alias statement.'."\r\n\r\n".$mysqli->error); /* Execute the statement */ if (!$stmt_get_alias->execute()) throw new Exception('An error occured while trying to get category alias statement.'."\r\n\r\n".$mysqli->error); /* store result */ $stmt_get_alias->store_result(); /* bind result variables */ $stmt_get_alias->bind_result($id, $alias); $stmt_get_alias->fetch(); if ($alias) array_unshift($array,$alias); } while ($id); $stmt_get_alias->close(); /*$querystr = $_SERVER['QUERY_STRING']; $querystr = preg_replace('/_lang=([a-z]{2})&?/i','',$querystr); $querystr = preg_replace('/alias=([a-z0-9-_]+)&?/i','',$querystr);*/ if (is_object($products) && sizeof($filters = $products->get_filters_array())) { $querystr = http_build_query($filters); } return '/'.$language_code.'/catalog'.(sizeof($array) ? '/'.implode('/',$array):'').($querystr ? '?'.$querystr:''); } }
Shell
UTF-8
1,274
2.84375
3
[]
no_license
#!/bin/bash set -e jekyll build if [ ! -d _jack1 ]; then git clone --recursive git@github.com:jackaudio/jack1 _jack1 fi # if [ ! -d _jack2 ]; then # git clone --recursive git@github.com:jackaudio/jack2 _jack2 # fi pushd _jack1 if [ ! -f configure ]; then ./autogen.sh fi if [ ! -f Makefile ]; then ./configure \ --enable-force-install \ --prefix=/usr \ --disable-alsa \ --disable-firewire fi rm -rf doc/reference doc/reference.doxygen git pull && git submodule update && make -j 4 popd # pushd _jack2 # if [ ! -d build ]; then # ./waf configure \ # -o build \ # --alsa=no \ # --firewire=no \ # --iio=no \ # --portaudio=no \ # --winmme=no \ # --celt=no \ # --opus=no \ # --samplerate=no \ # --sndfile=no \ # --readline=no \ # --systemd=no \ # --db=no \ # --doxygen=yes \ # --htmldir=/api # fi # rm -rf tmp-install # git pull && ./waf build -j4 && ./waf install --destdir=$(pwd)/tmp-install # popd rm -rf _site/api mv _jack1/doc/reference/html _site/api git add _site git commit -a -m "Update static pages" && git push || echo "nothing to commit" ssh -A jackaudio.org bash <<EOF set -e cd ~/sites/jackaudio git pull EOF
JavaScript
UTF-8
2,857
4.375
4
[]
no_license
// What is the return value of the below code sample? Provide a sentence or two of explanation. typeof( 15 ); //Return type is "number". All types of numerical values are //Return type is "Number". All objects that represent numbers are of type "Number" // What is the return value of the below code sample? Provide a sentence or two of explanation. typeof( "hello" ); //Return type is String //Return type is "String". This object is a String object. // What is the return value of the below code sample? Provide a sentence or two of explanation. typeof( [ "dog", "cat", "horse" ] ); //This is type "Object". An array is a object and not one of the primitive data types. // What is the return value of the below code sample? Provide a sentence or two of explanation. typeof( NaN ); //Return value of this is "Number". Even though it is not a number it is a numeric type and something that results from operations with actual numbers. // What is the return value of the below code sample? Provide a sentence or two of explanation. "hamburger" + "s"; //This operation concatenates an "s" to "hamburger" // What is the return value of the below code sample? Provide a sentence or two of explanation. "hamburgers" - "s"; //You can't use the "-" operand on Strings so it returns "Nan" // What is the return value of the below code sample? Provide a sentence or two of explanation. "johnny" + 5; //Using forced conversions this turns 5 into a string and concatenates it to "johnny" to get "johnny5" // What is the return value of the below code sample? Provide a sentence or two of explanation. 99 * "luftbaloons"; //This returns "Nan" because you can't perform an arithmetic operations on a string. // What will the contents of the below array be after the below code sample is executed. var numbers = [ 2, 4, 6, 8 ]; numbers.pop(); numbers.push( 10 ); numbers.unshift( 3 ); //[3, 2, 4, 6, 10] // What is the return value of the below code sample? var morse = [ "dot", "pause", "dot" ]; var moreMorse = morse.join( " dash " ); moreMorse.split( " " ); //This returns [dot, dash, pause, dash, dot]. The join method command adds dash between the string values in the morse array and turns it in to a string. The split method divdes the morMorse string be the space //delimiter and puts it into an array. // What will the contents of the below array be after the below code sample is executed. var bands = []; var beatles = [ "Paul", "John", "George", "Pete" ]; var stones = [ "Brian", "Mick", "Keith", "Ronnie", "Charlie" ]; bands.push( beatles ); bands.unshift( stones ); bands[ bands.length - 1 ].pop(); bands[0].shift(); bands[1][3] = "Ringo"; //The push and unshift methods add the beatles and stones array tothe bands array. The bands array now has two arrays in it. The next line removes the last element from the second array in the bands array.
C#
UTF-8
3,364
2.53125
3
[]
no_license
using RevivalWebSite.Models; using System; using System.Collections.Generic; using System.Data.Entity; using System.Linq; using System.Web; namespace RevivalWebSite.DAL { public class RevivalDbInitializer : DropCreateDatabaseIfModelChanges<RevivalContext> { protected override void Seed(RevivalContext context) { //new List<Address> { // new Address { City = "New York", StreetAdress = "1232 Zarichna" }, // new Address {City = "Atlanta", StreetAdress = "1234 Nicolus Street" }, // new Address {City = "New York", StreetAdress = "1211 Zarichna" }, // new Address {City = "Atlanta", StreetAdress = "1 Iphone Street" }, // new Address {City = "Chattanooga", StreetAdress = "14049 Scenic Hwy" }, // new Address {City = "Atlanta", StreetAdress = "1 Mehico Street" }, // new Address {City = "Chattanooga", StreetAdress = "34 Scenic Hwy" } //}.ForEach(address => context.Addresses.Add(address)); //context.SaveChanges(); //new List<Child> //{ // new Child { Name = "Vanya", Age = 21, Sex = true, FamilyID = 1}, // new Child { Name = "Luke", Age = 15, Sex = true, FamilyID = 1}, // new Child { Name = "Vanya", Age = 21, Sex = true, FamilyID = 2}, // new Child { Name = "Samy", Age = 11, Sex = false, FamilyID = 3}, // new Child { Name = "Nick", Age = 13, Sex = true, FamilyID = 3}, // new Child { Name = "Anna", Age = 11, Sex = false, FamilyID = 4}, // new Child { Name = "Emely", Age = 15, Sex = false, FamilyID = 5}, // new Child { Name = "Mary", Age = 12, Sex = false, FamilyID = 5} //}.ForEach(child => context.Children.Add(child)); //context.SaveChanges(); //new List<Parent> //{ // new Parent {Name = "Ivan Tymophiyovich", PhoneNumber = "096-8537-455" }, // new Parent {Name = "Bananchick", PhoneNumber = "096-8137-455" }, // new Parent {Name = "Ivan Mickhaylo", PhoneNumber = "096-8537-455" }, // new Parent {Name = "Ivan Prokopchuck", PhoneNumber = "026-8537-455" }, // new Parent {Name = "Natalia Ivanivna", PhoneNumber = "093-8537-455" }, // new Parent {Name = "Vera Petrovna", PhoneNumber = "094-8537-455" }, // new Parent {Name = "Bananchick Volodimirovich", PhoneNumber = "094-8111-453" } //}.ForEach(parent => context.Parents.Add(parent)); //context.SaveChanges(); //new List<Family> //{ // new Family { FName= "Korniychuck", AddressID = 1, ParentID = 1 }, // new Family { FName= "Tan", AddressID = 2, ParentID = 2 }, // new Family { FName= "Krisno", AddressID = 3, ParentID = 3 }, // new Family { FName= "Lanska", AddressID = 4, ParentID = 4 }, // new Family { FName= "Zelinskiy", AddressID = 5, ParentID = 5 }, // new Family { FName= "Tsvigaylo", AddressID = 6, ParentID = 6 }, // new Family { FName= "Marks", AddressID = 7, ParentID = 7 }, //}.ForEach(family => context.Families.Add(family)); //context.SaveChanges(); // base.Seed(context); } } }
Python
UTF-8
4,431
2.59375
3
[]
no_license
''' Created on 04 Oct. 2018, last edited 23 Oct. 2018 Module to simplify interfacing with the processing scripts @author: James Moran [jpmoran.pac@gmail.com] ''' from . import file_io_thermal from . import process_image as process_image_file # Must be aliased, as the function matches the filename from server.messages import message import asyncio import sys import numpy import base64 async def process_image(connection, path_to_save, simulation_select, process_select, frames_to_process = -1, frame_start = -1): '''Encapsulates the processing methods implemented. Returns a 3D numpy array containing the processed image, with [0, y, x]. Note that the first dimension only ever has a length of one. Connection is the address of the object encapsulating the request event from the app. Path_to_save is the directory to save the file .png to. Simulation_select chooses which folder to search for files (in theory each folder contains a different simulation, but in the actual application this could store the .ris files output by the camera). Frames_to_process is the total number of frames that should be processed out of the total. Frame_start is which frame to start from. ''' print('Reading file...') try: thermogram = file_io_thermal.open_file('/home/pi/scans/png/' + simulation_select + '/') except: print('Unable to load file!') # The app hasn't implemented an error code that can be read from the server, so # we hack an error message by sending back a .png with the error written on it. # Load the error image scanImg = open('/home/pi/error/error.png', 'rb') scan = base64.b64encode(scanImg.read()) scanImg.close() await connection.send(message('scan_progress', {'percent': 100})) # Send the error image await connection.send(message('scan_complete', {'base64EncodedString': scan.decode('utf-8')})) return await connection.send(message('scan_progress', {'percent': 10})) print('Selecting process...') # Select the processing method based on the case statement # Python doesn't have real switch..case :( method = 0 if process_select == "PPT Static": # The app directly sends the names from the combo box method = 0 if process_select == "PPT Dynamic": method = 1 if process_select == "Image Subtraction Static": method = 2 if process_select == "Image Subtraction Dynamic": method = 3 if process_select == "TSR Static": method = 4 if process_select == "TSR Dynamic": method = 5 print('Processing image...') try: phasemap = process_image_file.process_image(thermogram, method_select = method, frame_start = frame_start, frames_to_process = frames_to_process, xStartSkip = 0, xEndSkip = 0, yStartSkip = 0, yEndSkip = 0) except: print('Unable to process file!') scanImg = open('/home/pi/error/error.png', 'rb') scan = base64.b64encode(scanImg.read()) scanImg.close() await connection.send(message('scan_progress', {'percent': 100})) await connection.send(message('scan_complete', {'base64EncodedString': scan.decode('utf-8')})) return await connection.send(message('scan_progress', {'percent': 90})) print('Saving phasemap to .png...') if phasemap.shape[0] == 1: #Check if there is only one thermogram if not file_io_thermal.save_png(phasemap, path_to_save + '.png'): print('Failed to save .png :(') else: #Save first thermogram if more than one was produced if not file_io_thermal.save_png(phasemap[0,:,:], path_to_save + '.png'): print('Failed to save.png :(') # Open the .png that was saved and code it in base 64 to send back scanImg = open(path_to_save + '.png', 'rb') scan = base64.b64encode(scanImg.read()) scanImg.close() await connection.send(message('scan_progress', {'percent': 100})) await connection.send(message('scan_complete', {'base64EncodedString': scan.decode('utf-8')})) print("Done! Process Complete.")
Ruby
UTF-8
1,417
3.75
4
[]
no_license
############################################ # # Class Bob # class Bob def hey(input) respond(input) end private def respond(input) Response.new(input).respond end end ############################################ # # Class Response # class Response attr_reader :input SENTENCE_SUFFIXES = ['.', '!'] def initialize(input) self.input = input end def respond generate_response end private def input=(text) @input = sanitize_input(text) end def sanitize_input(text) result = text.chomp unless text.nil? result = '' if result.nil? || is_number_only_string?(result) result end def is_number_only_string?(text) text =~ /^\d+$/ end def generate_response if is_sentence? 'Whatever.' elsif is_yelling? 'Woah, chill out!' elsif is_question? 'Sure.' elsif is_silence? 'Fine. Be that way.' else 'Sure.' end end def is_sentence? input.end_with? *SENTENCE_SUFFIXES unless is_silence? || is_yelling? end def is_yelling? input == input.upcase unless is_silence? end def is_question? input.end_with? '?' unless is_silence? end def is_silence? is_blank? end def is_blank? input.nil? || is_empty_string? end def is_empty_string? input == '' end end
JavaScript
UTF-8
1,081
2.796875
3
[ "MIT" ]
permissive
define(['jquery','helper'],function($,helper){ //北美 var usBox = { init: function(){ this.$element = $('#beimei') this.$container = this.$element.find('.container') this.start() }, start: function(){ var _this = this this.getData(function(data){ _this.render(data) }) }, getData: function(callback){ //获取数据 var _this = this //加载状态 _this.$element.find('.loading').show() $.ajax({ url:'https://api.douban.com//v2/movie/us_box', type:'GET', dataType: 'jsonp' }).done(function(ret){ console.log(ret) callback&&callback(ret) }).fail(function(){ console.log('数据异常') }).always(function(){ _this.$container.find('.loading').hide() }) }, render: function(data){ //渲染 var _this = this data.subjects.forEach(function(movie){ _this.$container.append(helper.createNode(movie.subject)) }) } } return usBox })
C++
UTF-8
675
3.125
3
[]
no_license
/************************** GameItem ***************************** ** The GameItem class represents items in the game the player can ** collect and use. There is a special type, known as food that the ** player can consume. This is defined by isEdible bool variable. *********************************************************************/ #ifndef GAMEITEM_HPP #define GAMEITEM_HPP #include <string> class GameItem { private: std::string itemName; int healthRecoverPt; bool isEdible; public: GameItem(std::string setName, int setRecoverHP, bool setEdible); std::string getItemName(); int getHealthRecoverPt(); bool getIsEdible(); }; #endif
JavaScript
UTF-8
1,022
2.625
3
[]
no_license
import { Command, Option, InvalidOptionArgumentError } from 'commander/esm.mjs'; function checkInt(value) { if (isNaN(+value)) { throw new InvalidOptionArgumentError('Shift value must be a number.'); } return +value; } export default () => { const program = new Command(); program .addHelpText('before', 'This utility will encode or decode your input using Caesar ciphering algorithm') .addOption(new Option('-a, --action <encode|decode>', 'an action encode/decode') .choices(['encode', 'decode']) .makeOptionMandatory(true) ) .addOption(new Option('-s, --shift <number>', 'A shift of the Caesar cipher') .makeOptionMandatory(true) .argParser(checkInt) ) .option('-i, --input [filename]', 'An input file. If omitted gets input from stdin') .option('-o, --output [filename]', 'An output file. If omitted puts result to stdout') .addHelpText('afterAll', '\nCreated by Odintsov Fedor at 9 May 2021'); program.parse(process.argv); return program.opts(); }
Swift
UTF-8
3,226
2.53125
3
[]
no_license
// // Keychain.swift // Combine-MVVM // // Created by Glenn Posadas on 4/30/21. // Copyright © 2021 clarknt. All rights reserved. // import Foundation public enum KeychainKey: String { case userId = "KEY_USER_ID" } // Arguments for the keychain queries private let kSecClassValue = NSString(format: kSecClass) private let kSecAttrAccountValue = NSString(format: kSecAttrAccount) private let kSecValueDataValue = NSString(format: kSecValueData) private let kSecClassGenericPasswordValue = NSString(format: kSecClassGenericPassword) private let kSecAttrServiceValue = NSString(format: kSecAttrService) private let kSecMatchLimitValue = NSString(format: kSecMatchLimit) private let kSecReturnDataValue = NSString(format: kSecReturnData) private let kSecMatchLimitOneValue = NSString(format: kSecMatchLimitOne) open class Keychain { /** * Internal methods for querying the keychain. */ private class func getKeychainQuery(service: KeychainKey, country: String = "US") -> NSMutableDictionary { let serviceStr = service.rawValue + country return NSMutableDictionary(dictionary: [kSecClass: kSecClassGenericPassword, kSecAttrService: serviceStr, kSecAttrAccount: serviceStr, kSecAttrAccessible: kSecAttrAccessibleAfterFirstUnlock]) } open class func save(service: KeychainKey, data: Any, country: String = "US") { // Instantiate a new default keychain query let keychainQuery: NSMutableDictionary = getKeychainQuery(service: service, country: country) // Delete any existing items SecItemDelete(keychainQuery as CFDictionary) keychainQuery.setObject(NSKeyedArchiver.archivedData(withRootObject: data), forKey: kSecValueData as! NSCopying) // Add the new keychain item SecItemAdd(keychainQuery as CFDictionary, nil) } open class func delete(service: KeychainKey, country: String = "US") { // Instantiate a new default keychain query let keychainQuery: NSMutableDictionary = getKeychainQuery(service: service, country: country) // Delete any existing items SecItemDelete(keychainQuery as CFDictionary) } open class func deleteAllData() { let secItemClasses = [kSecClassGenericPassword, kSecClassInternetPassword, kSecClassCertificate, kSecClassKey, kSecClassIdentity] for secItemClass in secItemClasses { let dictionary = [kSecClass as String: secItemClass] SecItemDelete(dictionary as CFDictionary) } } open class func load(service: KeychainKey, country: String = "US") -> Any? { let keychainQuery: NSMutableDictionary = getKeychainQuery(service: service, country: country) keychainQuery.setObject(kCFBooleanTrue as Any, forKey: kSecReturnData as! NSCopying) keychainQuery.setObject(kSecMatchLimitOne, forKey: kSecMatchLimit as! NSCopying) var keyData: AnyObject? var contentsOfKeychain: Any? = nil if SecItemCopyMatching(keychainQuery, &keyData) == noErr { if let retrievedData = keyData as? NSData { contentsOfKeychain = NSKeyedUnarchiver.unarchiveObject(with: retrievedData as Data) } } return contentsOfKeychain } }
C++
UTF-8
854
2.609375
3
[]
no_license
#pragma once #include "../defines.h" #include "vector.h" class Bsdf { public: HOST_DEVICE virtual Vec3f sample(Vec3f n, float u[2]) = 0; HOST_DEVICE virtual float f(Vec3f n, Vec3f wi) = 0; HOST_DEVICE virtual float pdf(Vec3f n, Vec3f wi) = 0; }; using BsdfPtr = Bsdf *; class NullBsdf : public Bsdf { public: HOST_DEVICE NullBsdf() {} HOST_DEVICE virtual Vec3f sample(Vec3f n, float u[2]) override; HOST_DEVICE virtual float f(Vec3f n, Vec3f wi) override; HOST_DEVICE virtual float pdf(Vec3f n, Vec3f wi) override; }; class DiffuseBsdf : public Bsdf { public: HOST_DEVICE DiffuseBsdf(float albedo) : albedo(albedo) {} HOST_DEVICE virtual Vec3f sample(Vec3f n, float u[2]) override; HOST_DEVICE virtual float f(Vec3f n, Vec3f wi) override; HOST_DEVICE virtual float pdf(Vec3f n, Vec3f wi) override; private: float albedo; };
Java
UTF-8
520
2.28125
2
[]
no_license
package com.example.interseptor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class SimpleWebController { private static final Logger log = LoggerFactory.getLogger(SimpleWebController.class); @RequestMapping("/hello") public String hello(){ log.info("Welcome to access RequestMapping: /hello!"); return "Hello World!"; } }
Java
UTF-8
1,996
2.046875
2
[]
no_license
package com.xuqm.frame.ui.fragment; import android.view.View; import com.xuqm.base.adapter.BasePagedAdapter; import com.xuqm.base.common.LogHelper; import com.xuqm.base.common.ToolsHelper; import com.xuqm.base.ui.BaseListAppBarFragment; import com.xuqm.frame.R; import com.xuqm.frame.model.AD; import com.xuqm.frame.model.Article; import com.xuqm.frame.ui.adapter.BannerImageAdapter; import com.xuqm.frame.ui.adapter.CommonArticleAdapter; import com.xuqm.frame.viewmodel.HomeListViewModel; import com.youth.banner.Banner; import com.youth.banner.indicator.CircleIndicator; import com.youth.banner.listener.OnBannerListener; import java.util.ArrayList; public class HomeFragment extends BaseListAppBarFragment<Article, HomeListViewModel> { @Override public BasePagedAdapter<Article> adapter() { return new CommonArticleAdapter(); } private ArrayList<AD> list = new ArrayList<>(); private BannerImageAdapter bannerImageAdapter; private Banner banner; @Override protected int getAppBarView() { return R.layout.user_item_user_title; } @Override protected void initView() { super.initView(); banner = getActivity().findViewById(R.id.banner); bannerImageAdapter = new BannerImageAdapter(list); banner.setAdapter(bannerImageAdapter) .setIndicator(new CircleIndicator(mContext)) .setIndicatorNormalColorRes(R.color.dark_gray) .setIndicatorSelectedColorRes(R.color.blue) .setOnBannerListener((OnBannerListener<AD>) (data, position) -> LogHelper.e("=====>点击了" + data + position)); } @Override protected void initData() { super.initData(); getViewModel().adLiveData.observe(this, banner::setDatas); getViewModel().get(); } @Override public void itemClicked(View view, Article item, int position) { ToolsHelper.snack(getBinding().baseRefreshLayout, item.toString()); } }
Python
UTF-8
642
2.890625
3
[ "MIT" ]
permissive
import numpy as np class Relu(object): def __call__(self, a): return np.maximum(0, a) def gradient(self, a): return np.heaviside(a, 0) class Tanh(object): def __call__(self,x): return np.tanh(x) def gradient(self, x): return 1.0 - np.tanh(x)**2 class Sigmoid(object): def __call__(self, a): output = 1 / (1 + np.exp(-a)) self._ouptut = output return output def gradient(self, Y): output = self(Y) return output * (1 - output) class Identity(object): def __call__(self, a): return a def gradient(self, a): return np.ones_like(a)
Swift
UTF-8
713
2.625
3
[ "MIT" ]
permissive
// // P00Test.swift // NintyNineTests // // Created by Gordon Tucker on 11/14/18. // Copyright © 2018 Gordon Tucker. All rights reserved. // import XCTest import NintyNine class P00Test: XCTestCase { func testConvienceInit() { let list = List(1, 2, 3) XCTAssertEqual(1, list.value) XCTAssertEqual(2, list.nextItem?.value) XCTAssertEqual(3, list.nextItem?.nextItem?.value) } func testInit() { let list = List([1, 2, 3]) XCTAssertEqual(1, list?.value) XCTAssertEqual(2, list?.nextItem?.value) XCTAssertEqual(3, list?.nextItem?.nextItem?.value) } func testInit_empty() { XCTAssertNil(List([])) } }
Python
UTF-8
693
3.75
4
[]
no_license
# Представлен список чисел. Необходимо вывести элементы исходного списка, # значения которых больше предыдущего элемента. Элементы, удовлетворяющие # условию, оформить в виде списка. Для формирования списка использовать генератор. import random list_numbers = [round(random.random() * 10, 5) for i in range(random.randint(0, 10))] print(list_numbers) items_more_than = [list_numbers[i] for i in range(1, len(list_numbers)) if list_numbers[i] > list_numbers[i - 1]] print(items_more_than)
TypeScript
UTF-8
1,834
2.515625
3
[]
no_license
import axios, { AxiosPromise, AxiosResponse } from "axios"; import { io } from "../.."; import { FunctionRequest } from "../../types"; const db = require('../../../db') const infoDataClients = async () => { const response: AxiosResponse = await axios.get('http://localhost:3030/clients') return io.emit('clients', response.data) } interface DefineModels { select: FunctionRequest, update: FunctionRequest, delete: FunctionRequest, insert: FunctionRequest } export const Models: DefineModels = { async select (req, res, _, table) { let response = await db(table).select('*').where(req.query).catch(() => []) if (table === 'clients') { response = response.map(client => { let year = new Date().getFullYear() - new Date(client.date_of_birth).getFullYear(); if ((new Date().getMonth() + 1) <= (new Date(client.date_of_birth).getMonth() + 1) && (new Date().getDate()) < (new Date(client.date_of_birth).getDate())) year-- client.age = year return client }) } return res.status(200).json(response) }, async update (req, res, _, table) { await db(table).update(req.body).where(req.params).catch(erro => erro) await infoDataClients() return res.status(204).send() }, async delete (req, res, _, table) { const response = await db(table).delete().where(req.params).catch(erro => ({ error: true, message: erro })) if (response.error) return res.status(400).json(response) return res.status(204).send() }, async insert (req, res, _, table) { const response = await db(table).insert(req.body, 'id').catch(erro => ({ error: true, message: erro })) if (response.error) return res.status(404).json(response) if (table === 'clients') await infoDataClients() return res.status(200).json({ id: response[0] }) } }
Python
UTF-8
111
3.0625
3
[]
no_license
numbers = (10,20,10,20,30,40,60,70) n = set(numbers) print("Tuple after removing all duplicates: ", tuple(n))
Java
UTF-8
2,228
2.953125
3
[]
no_license
package logic; import business.AdministradorBusiness; import business.NombresDeArchivosBusiness; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JList; /** * Clase que permite llevar un control de los administradores y encuestas * creadas en el sistema * * @author adriansb3105 */ public class ListasServidor implements Runnable { private JList<String> listaAdmins; private JList<String> listaEncuestas; private AdministradorBusiness administradorBusiness; private NombresDeArchivosBusiness nombresDeArchivosBusiness; public ListasServidor(JList listaAdmins, JList listaEncuestas) { this.listaAdmins = listaAdmins; this.listaEncuestas = listaEncuestas; } @Override public void run() { while (true) { iniciar(); try { Thread.sleep(3000); } catch (InterruptedException ex) { Logger.getLogger(ListasServidor.class.getName()).log(Level.SEVERE, null, ex); } } } /** * Metodo que atraves del hilo me actualiza la lista de administradores y la * encuestas creadas cada cinco seguntos */ private void iniciar() { this.administradorBusiness = new AdministradorBusiness(); this.nombresDeArchivosBusiness = new NombresDeArchivosBusiness(); String nombresAdmins[] = new String[(this.administradorBusiness.getNombresAdministradores().length) + (1)]; nombresAdmins[0] = "Administradores"; for (int i = 0; i < this.administradorBusiness.getNombresAdministradores().length; i++) { nombresAdmins[i + 1] = this.administradorBusiness.getNombresAdministradores()[i]; } String[] nombresEncuestas = new String[this.nombresDeArchivosBusiness.getNombresDeEncuestas().size() + 1]; nombresEncuestas[0] = "Encuestas"; for (int i = 0; i < this.nombresDeArchivosBusiness.getNombresDeEncuestas().size(); i++) { nombresEncuestas[i + 1] = this.nombresDeArchivosBusiness.getNombresDeEncuestas().get(i); } this.listaAdmins.setListData(nombresAdmins); this.listaEncuestas.setListData(nombresEncuestas); } }
C++
UTF-8
668
2.609375
3
[]
no_license
//https://codeforces.com/contest/1474/problem/A #include<bits/stdc++.h> using namespace std; int main() { int t;cin>>t; while(t--) { int n;cin>>n; string b; cin>>b; int prev; if(b[0]=='1'){cout<<1;prev=2;} else if(b[0]=='0'){cout<<1;prev=1;} for(int i=1;i<n;i++) { prev=prev-(b[i]-'0'); if(prev==2 || prev<0) {cout<<1; prev=1+(b[i]-'0');} else { int one = 1; int ans = prev^one; cout<<ans; prev=ans+(b[i]-'0'); } } cout<<"\n"; } }
Java
UTF-8
1,285
3.609375
4
[]
no_license
package cn.laoma.thread2.t2_003; import lombok.SneakyThrows; import java.util.ArrayList; import java.util.List; import java.util.concurrent.locks.ReentrantLock; /** * @program: ThreadDemos * @description: 可重入锁比synchronized厉害的点 * 可以设置公平锁和非公平锁 * 公平锁:线程先进入等待队列FIFO执行。 * 非公平锁:就是抢锁 * @author: 老马 * @create: 2021-01-26 20:53 **/ public class Lock_05ReentrantLock { //观察true和false的区别;默认为false private ReentrantLock lock = new ReentrantLock(true); @SneakyThrows public void show() { for (int i = 0; i < 100; i++) { lock.lock(); try { System.out.println(Thread.currentThread().getName()+"得到了锁"); } catch (Exception e) { e.printStackTrace(); }finally { lock.unlock(); } } } @SneakyThrows public static void main(String[] args) { Lock_05ReentrantLock locktest = new Lock_05ReentrantLock(); List<Thread> threads = new ArrayList<>(); threads.add(new Thread(locktest::show, "t1")); threads.add(new Thread(locktest::show, "t2")); threads.forEach(t -> t.start()); } }
Java
UTF-8
579
2.421875
2
[]
no_license
package org.ternlang.compile; import junit.framework.TestCase; public class PackageTest extends TestCase { public void testPackage() throws Exception { // create a package object for java.lang package Package pack1 = Package.getPackage("java.lang"); Package pack2 = Package.getPackage("java.lang.reflect"); Package pack3 = Package.getPackage("java.util.regex"); // get the fully qualified name for this package System.out.println(pack1); System.out.println(pack2); System.out.println(pack3); } }
Java
UTF-8
2,468
2.078125
2
[]
no_license
package com.ex.controller.core_controller.CoremutualReferringController; import com.ex.service.MerchantElectService; import com.ex.util.JsonView; import com.ex.util.PageRequest; import com.ex.vo.MerchantCoreVo; import com.github.pagehelper.PageInfo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.HashMap; import java.util.Map; @RestController @RequestMapping("/CoreMutualReferring") public class CoremutualReferringController { @Autowired private MerchantElectService merchantElectService; /** * 运营后台互推 * @param page * @return */ @RequestMapping("selectAllMerchant") public JsonView selectAllMerchant(PageRequest page){ JsonView jsonView = new JsonView(); try{ PageInfo<MerchantCoreVo> merchantCoreVoPageInfo = merchantElectService.selectAllMerchant(page); jsonView.setCode(JsonView.SUCCESS); jsonView.setMessage("查询成功"); jsonView.setData(merchantCoreVoPageInfo); }catch(Exception e){ e.printStackTrace(); jsonView.setCode(JsonView.ERROR); jsonView.setMessage("查询失败"); } return jsonView; } /** * 修改商家之间互推关系 */ public JsonView updateMerchant(Long merchantId,Long BeMerchantId,int state){ JsonView jsonView = new JsonView(); Map termMap = new HashMap<String, Object>(); try{ if(merchantId!=null){ termMap.put("merchantId",merchantId); if(BeMerchantId!=null){ termMap.put("BeMerchantId",BeMerchantId); termMap.put("state",state); int i = merchantElectService.updateMerchantElect(termMap); if(i>0){ jsonView.setCode(JsonView.SUCCESS); jsonView.setMessage("修改成功"); }else { jsonView.setCode(JsonView.SUCCESS); jsonView.setMessage("修改失败"); } } } }catch (Exception e) { e.printStackTrace(); jsonView.setMessage("查询异常"); jsonView.setCode(JsonView.ERROR); } return jsonView; } }
JavaScript
UTF-8
49,389
2.78125
3
[]
no_license
describe("The 6502 CPU", function(){ var regPC = 0, regA = 0, regX = 1, regY = 2, regP = 3, regSP = 4; var INTERRUPT_NONE = 0, INTERRUPT_IRQ = 1, INTERRUPT_NMI = 2, INTERRUPT_RESET = 3; var cpu = new NEScript.CPU(); describe("with basic functionality", function(){ it("can report its internal state", function(){ var dmp = cpu.dumpRegs(); expect(dmp.hasOwnProperty('A')).toBeTruthy(); expect(dmp.hasOwnProperty('PC')).toBeTruthy(); }) cpu._regs[regA] = 1; cpu._regPC[regPC] = 1; cpu._mainMemory.writeByte(0xFF, 0xAB); it("can completely reset itself", function(){ cpu.totalReset(); var dmp = cpu.dumpRegs(); expect(dmp.A).toEqual(0); expect(dmp.X).toEqual(0); expect(dmp.Y).toEqual(0); expect(dmp.P).toEqual(0); expect(dmp.SP).toEqual(0xFF); expect(dmp.PC).toEqual(0); expect(cpu._mainMemory.readByte(0xFF)).toEqual(0); }) it("can transfer its flags to a single byte", function(){ cpu.totalReset(); cpu.flagC = true; cpu.flagN = true; expect(cpu.flagsToP()).toEqual(0xA1); cpu.totalReset(); cpu.flagN = true; cpu.flagV = true; expect(cpu.flagsToP()).toEqual(0xE0); }) it("can set its flags according to a given byte", function(){ cpu.totalReset(); cpu.pToFlags(0x81) expect(cpu.flagN).toEqual(true); expect(cpu.flagC).toEqual(true); expect(cpu.flagB).toEqual(false); expect(cpu.flagV).toEqual(false); cpu.totalReset(); cpu.pToFlags(0xC0) expect(cpu.flagN).toEqual(true); expect(cpu.flagC).toEqual(false); expect(cpu.flagB).toEqual(false); expect(cpu.flagV).toEqual(true); }) describe("with basic stack operations", function(){ it("pushes a byte", function(){ cpu.totalReset(); cpu.pushByte(0xAB); expect(cpu._regs[regSP]).toEqual(0xFE); expect(cpu.readByte(0x1FF)).toEqual(0xAB); }) it("pops a byte", function(){ var tmp = cpu.popByte(); expect(tmp).toEqual(0xAB); expect(cpu._regs[regSP]).toEqual(0xFF); }) it("pushes a word", function(){ cpu.totalReset(); cpu.pushWord(0xFACE); expect(cpu._regs[regSP]).toEqual(0xFD); expect(cpu.readWord(0x1FE)).toEqual(0xFACE); }) it("pops a word", function(){ var tmp = cpu.popWord(); expect(tmp).toEqual(0xFACE); expect(cpu._regs[regSP]).toEqual(0xFF); }) it("wraps around the stack", function(){ cpu.totalReset(); cpu._regs[regSP] = 0; cpu.pushByte(0xAB); expect(cpu._regs[regSP]).toEqual(0xFF); expect(cpu.readByte(0x100)).toEqual(0xAB); cpu.totalReset(); cpu._regs[regSP] = 0; cpu.pushWord(0xFACE); expect(cpu._regs[regSP]).toEqual(0xFE); expect(cpu.readByte(0x100)).toEqual(0xFA); expect(cpu.readByte(0x1FF)).toEqual(0xCE); var tmp = cpu.popWord(); expect(tmp).toEqual(0xFACE); expect(cpu._regs[regSP]).toEqual(0x00); }) }) it("handles interrupts", function(){ cpu.totalReset(); cpu.pToFlags(0x80); cpu._regPC[regPC] = 0x1234; cpu.writeWord(0xFFFA, 0xFACE); cpu.writeWord(0xFFFC, 0xABCD); cpu.writeWord(0xFFFE, 0xBEAD); cpu.postInterrupt(INTERRUPT_IRQ); expect(cpu._regInterrupt).toEqual(INTERRUPT_IRQ); var tmp = cpu.handleInterrupt() expect(tmp).toEqual(7) expect(cpu._regInterrupt).toEqual(INTERRUPT_NONE); expect(cpu.flagI).toEqual(true); expect(cpu._regPC[regPC]).toEqual(0xBEAD); expect(cpu.popByte()).toEqual(0x80); expect(cpu.popWord()).toEqual(0x1234); //Ignore IRQ when flagI is set. cpu.postInterrupt(INTERRUPT_IRQ); expect(cpu._regInterrupt).toEqual(INTERRUPT_NONE); cpu.postInterrupt(INTERRUPT_NMI); cpu.handleInterrupt(); expect(cpu._regPC[regPC]).toEqual(0xFACE); cpu.postInterrupt(INTERRUPT_RESET); cpu.handleInterrupt(); expect(cpu._regPC[regPC]).toEqual(0xABCD); }) }) describe("with opcode parser", function(){ beforeEach(function(){ cpu.totalReset(); }) //Helper functions for testing opcode behavior //Note the first test for each opcode group will be the most verbose, //since it will test all behaviors of the ALU proc. To test these for each opcode //in the group would be redundant. function _opTest(opcode, expectedCycles, expectedVals){ var tmp = cpu.execute(opcode), dmp = cpu.dumpRegs(); expect(tmp).toEqual(expectedCycles); for (var key in expectedVals){ if (expectedVals[key] === true){ expect(dmp[key]).toBeTruthy(); } else if (expectedVals[key] === false){ expect(dmp[key]).toBeFalsy(); } else { expect(dmp[key]).toEqual(expectedVals[key]); } } } describe("executes ADC", function(){ //First test I wrote, so it's a little longer :) it("in immediate mode", function(){ cpu.writeWord(0, 0x0101); cpu.writeWord(2, 0x0202); cpu.writeWord(4, 0xFFFF); cpu.writeWord(6, 0xFFFF); cpu._regs[regX] = 1; cpu._regs[regY] = 2; _opTest(0x69, 2, {A: 1, flagC: false}); _opTest(0x69, 2, {A: 3, flagC: false}); _opTest(0x69, 2, {A: 2, flagC: true}); _opTest(0x69, 2, {A: 2, flagC: true, flagZ: false, flagV: false, flagN: false}); cpu.totalReset(); _opTest(0x69, 2, {A: 0, flagC: false, flagZ: true, flagV: false}); cpu.writeWord(2, 0xFFFF); _opTest(0x69, 2, {A: 0xFF, flagC: false, flagZ: false, flagV: false, flagN: true}); cpu.totalReset(); //Should trigger overflow cpu.writeByte(1, 126); cpu._regs[regA] = 126; _opTest(0x69, 2, {A: 252, flagC: false, flagZ: false, flagV: true}); cpu.totalReset(); cpu.writeByte(1, 64); cpu._regs[regA] = 65; _opTest(0x69, 2, {flagV: true}); }) it("in zero page mode", function(){ cpu.totalReset(); cpu.writeWord(2, 0xABAB); cpu.writeByte(0xAB, 0xCD); _opTest(0x65, 3, {A: 0, flagZ: true}); _opTest(0x65, 3, {A: 0xCD}) }) it("in zero page indexed x mode", function(){ cpu.totalReset(); cpu.writeByte(0xAF, 0xBE); cpu.writeByte(1, 0xAD); cpu._regs[regX] = 2; _opTest(0x75, 4, {A: 0xBE}) }) it("in absolute mode", function(){ cpu.totalReset(); cpu.writeByte(0xBEAD, 0x12); cpu.writeWord(1, 0xBEAD); _opTest(0x6D, 4, {A: 0x12}); }) it("in absolute indexed x mode", function(){ cpu.totalReset(); cpu.writeByte(0xFACE, 0x34); cpu.writeWord(1, 0xFACB); cpu._regs[regX] = 3; _opTest(0x7D, 4, {A: 0x34}); //Add extra cycle when adding x reg goes to next page cpu.totalReset(); cpu.writeByte(0x4103, 0x56); cpu.writeWord(1, 0x40FE); cpu._regs[regX] = 5; _opTest(0x7D, 5, {A: 0x56}); }) it("in absolute indexed y mode", function(){ cpu.totalReset(); cpu.writeByte(0x1201, 0x78); cpu.writeWord(1, 0x11FA); cpu._regs[regY] = 7; _opTest(0x79, 5, {A: 0x78}); cpu.totalReset(); cpu.writeByte(0x1727, 0xF0); cpu.writeWord(1, 0x1701); cpu._regs[regY] = 0x26; _opTest(0x79, 4, {A: 0xF0}); }) it("in indirect indexed x mode", function(){ cpu.totalReset(); cpu.writeByte(0xBADA, 0x15); cpu.writeWord(0x76, 0xBADA); cpu.writeByte(1, 0x72); cpu._regs[regX] = 4; _opTest(0x61, 6, {A: 0x15}); }) it("in indirect indexed y mode", function(){ cpu.totalReset(); cpu.writeByte(0xCADA, 0x47); cpu.writeWord(0xBA, 0xCAD7); cpu.writeByte(1, 0xBA); cpu._regs[regY] = 3; _opTest(0x71, 5, {A: 0x47}); //Expect extra cycle for page cross cpu.totalReset(); cpu.writeByte(0x4302, 0xF2); cpu.writeWord(0x6D, 0x42FA); cpu.writeByte(1, 0x6D); cpu._regs[regY] = 8; _opTest(0x71, 6, {A: 0xF2}); }) }) describe("executes AND", function(){ it("in immediate mode", function(){ cpu._regs[regA] = 0xFF; cpu.writeByte(1, 0xF0); _opTest(0x29, 2, {A: 0xF0, flagN: true, flagZ: false}); cpu.writeByte(3, 0xF); _opTest(0x29, 2, {A: 0, flagN: false, flagZ: true}); }) it("in zero page mode", function(){ cpu.totalReset(); cpu._regs[regA] = 0xFF; cpu.writeByte(0x54, 0xF); cpu.writeByte(1, 0x54); _opTest(0x25, 3, {A: 0xF}); }) it("in zero page indexed x mode", function(){ cpu.totalReset(); cpu._regs[regA] = 0xFF; cpu.writeByte(0xDC, 1); cpu.writeByte(1, 0xD0); cpu._regs[regX] = 0xC; _opTest(0x35, 4, {A: 1}); }) it("in absolute mode", function(){ cpu.totalReset(); cpu._regs[regA] = 0xFF; cpu.writeByte(0xABCD, 0x2); cpu.writeWord(1, 0xABCD); _opTest(0x2D, 4, {A: 2}); }) it("in absolute indexed x mode", function(){ cpu.totalReset(); cpu._regs[regA] = 0xFF; cpu.writeByte(0xFD03, 0x4); cpu.writeWord(1, 0xFCFE); cpu._regs[regX] = 5; _opTest(0x3D, 5, {A: 4}); }) it("in absolute indexed y mode", function(){ cpu.totalReset(); cpu._regs[regA] = 0xFF; cpu.writeByte(0x0345, 0x8); cpu.writeWord(1, 0x0342); cpu._regs[regY] = 3; _opTest(0x39, 4, {A: 8}); }) it("in indirect indexed x mode", function(){ cpu.totalReset(); cpu._regs[regA] = 0xFF; cpu.writeByte(0xBADA, 0x15); cpu.writeWord(0x76, 0xBADA); cpu.writeByte(1, 0x72); cpu._regs[regX] = 4; _opTest(0x21, 6, {A: 0x15}); }) it("in indirect indexed y mode", function(){ cpu.totalReset(); cpu._regs[regA] = 0xCA; cpu.writeByte(0xCADA, 0xF); cpu.writeWord(0xBA, 0xCAD7); cpu.writeByte(1, 0xBA); cpu._regs[regY] = 3; _opTest(0x31, 5, {A: 0xA}); //Expect extra cycle for page cross cpu.totalReset(); cpu._regs[regA] = 0xFF; cpu.writeByte(0x4302, 0xF2); cpu.writeWord(0x6D, 0x42FA); cpu.writeByte(1, 0x6D); cpu._regs[regY] = 8; _opTest(0x31, 6, {A: 0xF2}); }) }) describe("executes ASL", function(){ it("in accumulator mode", function(){ cpu._regs[regA] = 0x80; _opTest(0x0A, 2, {A: 0, flagN: false, flagZ: true, flagC: true}); cpu._regs[regA] = 0x01; _opTest(0x0A, 2, {A: 2, flagN: false, flagZ: false, flagC: false}); cpu._regs[regA] = 0xC0; //11000000b _opTest(0x0A, 2, {A: 0x80, flagN: true, flagZ: false, flagC: true}); }) it("in zero page mode", function(){ cpu.totalReset(); cpu.writeByte(0xCB, 0x40); cpu.writeByte(1, 0xCB); var tmp = cpu.execute(0x06); expect(tmp).toEqual(5); expect(cpu.readByte(0xCB)).toEqual(0x80); }) it("in zero page indexed x mode", function(){ cpu.totalReset(); cpu.writeByte(0x89, 0x2); cpu.writeByte(1, 0x82); cpu._regs[regX] = 0x7; var tmp = cpu.execute(0x16); expect(tmp).toEqual(6); expect(cpu.readByte(0x89)).toEqual(4); }) it("in absolute mode", function(){ cpu.totalReset(); cpu.writeByte(0xFEDC, 0x4); cpu.writeWord(1, 0xFEDC); var tmp = cpu.execute(0x0E); expect(tmp).toEqual(6); expect(cpu.readByte(0xFEDC)).toEqual(0x8); }) it("in absolute indexed x mode", function(){ cpu.totalReset(); cpu.writeByte(0xFEDC, 0x2); cpu.writeWord(1, 0xFEDA); cpu._regs[regX] = 0x2; var tmp = cpu.execute(0x1E); expect(tmp).toEqual(7); expect(cpu.readByte(0xFEDC)).toEqual(0x4); }) }) describe("executes BCC", function(){ it("in relative mode", function(){ cpu.writeByte(1, 30); cpu.flagC = true; _opTest(0x90, 2, {PC: 2}); //Take branch, no page cross cpu.totalReset(); cpu.writeByte(1, 30); cpu.flagC = false; _opTest(0x90, 3, {PC: 32}); //Branch w/page cross forward cpu.totalReset(); cpu.writeByte(253, 6); cpu.flagC = false; cpu._regPC[regPC] = 252; _opTest(0x90, 4, {PC: 260}); //Branch w/page cross backward cpu.totalReset(); cpu.writeByte(0x3303, 250) //-6 cpu.flagC = false; cpu._regPC[regPC] = 0x3302; _opTest(0x90, 4, {PC: 0x32FE}); }) }) //The rest of the branch opcodes are identical //in the branching implementation except for the condition //tested, so the tests are much simpler describe("executes BCS", function(){ it("in relative mode", function(){ cpu.writeByte(1, 30); cpu.flagC = false; _opTest(0xB0, 2, {PC: 2}); cpu.totalReset(); cpu.writeByte(1, 30); cpu.flagC = true; _opTest(0xB0, 3, {PC: 32}); }) }) describe("executes BEQ", function(){ it("in relative mode", function(){ cpu.totalReset(); cpu.writeByte(1, 30); cpu.flagZ = false; _opTest(0xF0, 2, {PC: 2}); cpu.totalReset(); cpu.writeByte(253, 6); cpu.flagZ = true; cpu._regPC[regPC] = 252; _opTest(0xF0, 4, {PC: 260}); }) }) describe("executes BIT", function(){ it("in zero page mode", function(){ cpu._regs[regA] = 1; cpu.writeByte(20, 1) cpu.writeByte(1, 20); _opTest(0x24, 3, {flagN: false, flagV: false, flagZ: false}); cpu.totalReset(); cpu.writeByte(1, 1); _opTest(0x24, 3, {flagN: false, flagV: false, flagZ: true}); cpu.totalReset(); cpu.writeByte(30, 0xFF); cpu.writeByte(1, 30); _opTest(0x24, 3, {flagN: true, flagV: true, flagZ: true}); cpu.totalReset(); cpu.writeByte(0xFA, 0x40); cpu.writeByte(1, 0xFA); cpu._regs[regA] = 0xFF; _opTest(0x24, 3, {flagN: false, flagV: true, flagZ: false}); cpu.totalReset(); cpu.writeByte(0x80, 0x80); cpu.writeByte(1, 0x80); _opTest(0x24, 3, {flagN: true, flagV: false, flagZ: true}); }) it("in absolute mode", function(){ cpu.totalReset(); cpu._regs[regA] = 1; cpu.writeByte(0xFACE, 1) cpu.writeWord(1, 0xFACE); _opTest(0x2C, 4, {flagN: false, flagV: false, flagZ: false}); }) }) describe("executes BMI", function(){ it("in relative mode", function(){ cpu.totalReset(); cpu.writeByte(1, 30); cpu.flagN = false; _opTest(0x30, 2, {PC: 2}); cpu.totalReset(); cpu.writeByte(253, 6); cpu.flagN = true; cpu._regPC[regPC] = 252; _opTest(0x30, 4, {PC: 260}); }) }) describe("executes BNE", function(){ it("in relative mode", function(){ cpu.writeByte(1, 30); cpu.flagZ = true; _opTest(0xD0, 2, {PC: 2}); cpu.totalReset(); cpu.writeByte(1, 30); cpu.flagZ = false; _opTest(0xD0, 3, {PC: 32}); cpu.totalReset(); cpu.writeByte(253, 6); cpu.flagZ = false; cpu._regPC[regPC] = 252; _opTest(0xD0, 4, {PC: 260}); cpu.totalReset(); cpu.writeByte(0x3303, 250) //-6 cpu.flagZ = false; cpu._regPC[regPC] = 0x3302; _opTest(0xD0, 4, {PC: 0x32FE}); }) }) describe("executes BPL", function(){ it("in relative mode", function(){ cpu.totalReset(); cpu.writeByte(1, 30); cpu.flagN = true; _opTest(0x10, 2, {PC: 2}); cpu.totalReset(); cpu.writeByte(253, 6); cpu.flagN = false; cpu._regPC[regPC] = 252; _opTest(0x10, 4, {PC: 260}); }) }) describe("executes BRK", function(){ it("in imlplied mode", function(){ cpu.writeWord(0xFFFE, 0xABCD); _opTest(0x00, 7, {PC: 0xABCD, flagI: true, SP: 0xFC}) expect(cpu.readByte(0x1FD)).toEqual(0x30); expect(cpu.readWord(0x1FE)).toEqual(2); }) }) describe("executes BVC", function(){ it("in relative mode", function(){ cpu.totalReset(); cpu.writeByte(1, 30); cpu.flagV = true; _opTest(0x50, 2, {PC: 2}); cpu.totalReset(); cpu.writeByte(253, 6); cpu.flagV = false; cpu._regPC[regPC] = 252; _opTest(0x50, 4, {PC: 260}); }) }) describe("executes BVS", function(){ it("in relative mode", function(){ cpu.totalReset(); cpu.writeByte(1, 30); cpu.flagV = false; _opTest(0x70, 2, {PC: 2}); cpu.totalReset(); cpu.writeByte(253, 6); cpu.flagV = true; cpu._regPC[regPC] = 252; _opTest(0x70, 4, {PC: 260}); }) }) describe("executes CLC", function(){ it("in implied mode", function(){ cpu.pToFlags(0xFF); _opTest(0x18, 2, {flagC: false}); }) }) describe("executes CLD", function(){ it("in implied mode", function(){ cpu.pToFlags(0xFF); _opTest(0xD8, 2, {flagD: false}); }) }) describe("executes CLI", function(){ it("in implied mode", function(){ cpu.pToFlags(0xFF); _opTest(0x58, 2, {flagI: false}); }) }) describe("executes CLV", function(){ it("in implied mode", function(){ cpu.pToFlags(0xFF); _opTest(0xB8, 2, {flagV: false}); }) }) describe("executes CMP", function(){ it("in immediate mode", function(){ cpu.writeByte(1, 0x0); _opTest(0xC9, 2, {flagN: false, flagZ: true, flagC: true}); cpu.writeByte(3, 0x27); _opTest(0xC9, 2, {flagN: true, flagZ: false, flagC: false}); cpu.writeByte(5, 0x4); cpu._regs[regA] = 0xFF; _opTest(0xC9, 2, {flagN: true, flagZ: false, flagC: true}); cpu.writeByte(7, 0xFA); cpu._regs[regA] = 0xFA; _opTest(0xC9, 2, {flagN: false, flagZ: true, flagC: true}); }) it("in zero page mode", function(){ cpu.totalReset(); cpu.writeByte(0xCD, 0x1); cpu.writeByte(1, 0xCD); cpu._regs[regA] = 1; _opTest(0xC5, 3, {flagN: false, flagZ: true, flagC: true}); }) it("in zero page indexed x mode", function(){ cpu.totalReset(); cpu.writeByte(0xCD, 0x1); cpu.writeByte(1, 0xCA); cpu._regs[regA] = 1; cpu._regs[regX] = 3; _opTest(0xD5, 4, {flagN: false, flagZ: true, flagC: true}); }) it("in absolute mode", function(){ cpu.totalReset(); cpu.writeByte(0xFACE, 0x1); cpu.writeWord(1, 0xFACE); cpu._regs[regA] = 1; _opTest(0xCD, 4, {flagN: false, flagZ: true, flagC: true}); }) it("in absolute indexed x mode", function(){ cpu.totalReset(); cpu.writeByte(0xFACE, 0x1); cpu.writeWord(1, 0xFACB); cpu._regs[regA] = 1; cpu._regs[regX] = 3; _opTest(0xDD, 4, {flagN: false, flagZ: true, flagC: true}); }) it("in absolute indexed y mode", function(){ cpu.totalReset(); cpu.writeByte(0xFACE, 0x1); cpu.writeWord(1, 0xFACB); cpu._regs[regA] = 1; cpu._regs[regY] = 3; _opTest(0xD9, 4, {flagN: false, flagZ: true, flagC: true}); }) it("in indirect indexed x mode", function(){ cpu.totalReset(); cpu.writeByte(0xFACE, 0x1); cpu.writeWord(0x72, 0xFACE); cpu.writeWord(1, 0x70); cpu._regs[regA] = 1; cpu._regs[regX] = 2; _opTest(0xC1, 6, {flagN: false, flagZ: true, flagC: true}); }) it("in indirect indexed y mode", function(){ cpu.totalReset(); cpu.writeByte(0xFACE, 0x1); cpu.writeWord(0x72, 0xFACA); cpu.writeWord(1, 0x72); cpu._regs[regA] = 1; cpu._regs[regY] = 4; _opTest(0xD1, 5, {flagN: false, flagZ: true, flagC: true}); }) }) describe("executes CPX", function(){ it("in immediate mode", function(){ cpu.writeByte(1, 0x0); _opTest(0xE0, 2, {flagN: false, flagZ: true, flagC: true}); cpu.writeByte(3, 0x27); _opTest(0xE0, 2, {flagN: true, flagZ: false, flagC: false}); cpu.writeByte(5, 0x4); cpu._regs[regX] = 0xFF; _opTest(0xE0, 2, {flagN: true, flagZ: false, flagC: true}); cpu.writeByte(7, 0xFA); cpu._regs[regX] = 0xFA; _opTest(0xE0, 2, {flagN: false, flagZ: true, flagC: true}); }) it("in zero page mode", function(){ cpu.totalReset(); cpu.writeByte(0xCD, 0x1); cpu.writeByte(1, 0xCD); cpu._regs[regX] = 1; _opTest(0xE4, 3, {flagN: false, flagZ: true, flagC: true}); }) it("in absolute mode", function(){ cpu.totalReset(); cpu.writeByte(0xFACE, 0x1); cpu.writeWord(1, 0xFACE); cpu._regs[regX] = 1; _opTest(0xEC, 4, {flagN: false, flagZ: true, flagC: true}); }) }) describe("executes CPY", function(){ it("in immediate mode", function(){ cpu.writeByte(1, 0x0); _opTest(0xC0, 2, {flagN: false, flagZ: true, flagC: true}); }) it("in zero page mode", function(){ cpu.totalReset(); cpu.writeByte(0xCD, 0x1); cpu.writeByte(1, 0xCD); cpu._regs[regY] = 1; _opTest(0xC4, 3, {flagN: false, flagZ: true, flagC: true}); }) it("in absolute mode", function(){ cpu.totalReset(); cpu.writeByte(0xFACE, 0x1); cpu.writeWord(1, 0xFACE); cpu._regs[regY] = 1; _opTest(0xCC, 4, {flagN: false, flagZ: true, flagC: true}); }) }) describe("executes DEC", function(){ it("in zero page mode", function(){ cpu.writeByte(0x70, 0x3); cpu.writeByte(1, 0x70); _opTest(0xC6, 5, {flagN: false, flagZ: false}); expect(cpu.readByte(0x70)).toEqual(2); cpu.totalReset(); cpu.writeByte(0x70, 0x1); cpu.writeByte(1, 0x70); _opTest(0xC6, 5, {flagN: false, flagZ: true}); expect(cpu.readByte(0x70)).toEqual(0); cpu.totalReset(); cpu.writeByte(0x70, 0x0); cpu.writeByte(1, 0x70); _opTest(0xC6, 5, {flagN: true, flagZ: false}); expect(cpu.readByte(0x70)).toEqual(255); }) it("in zero page indexed x mode", function(){ cpu.totalReset(); cpu.writeByte(0x70, 3); cpu.writeByte(1, 0x6E); cpu._regs[regX] = 2; _opTest(0xD6, 6, {flagN: false, flagZ: false}); expect(cpu.readByte(0x70)).toEqual(2); }) it("in absolute mode", function(){ cpu.totalReset(); cpu.writeByte(0xFACE, 3); cpu.writeWord(1, 0xFACE); cpu.flagZ = true; _opTest(0xCE, 6, {flagN: false, flagZ: false}); expect(cpu.readByte(0xFACE)).toEqual(2); }) it("in absolute indexed x mode", function(){ cpu.totalReset(); cpu.writeByte(0xFACE, 3); cpu.writeWord(1, 0xFACD); cpu._regs[regX] = 1; _opTest(0xDE, 7, {flagN: false, flagZ: false}); expect(cpu.readByte(0xFACE)).toEqual(2); }) }) describe("executes DEX", function(){ it("in implied mode", function(){ cpu._regs[regX] = 3; _opTest(0xCA, 2, {flagN: false, flagZ: false, X: 2}); cpu.totalReset(); cpu._regs[regX] = 1; _opTest(0xCA, 2, {flagN: false, flagZ: true, X: 0}); cpu.totalReset(); cpu._regs[regX] = 0; _opTest(0xCA, 2, {flagN: true, flagZ: false, X: 255}); }) }) describe("executes DEY", function(){ it("in implied mode", function(){ cpu._regs[regY] = 3; _opTest(0x88, 2, {flagN: false, flagZ: false, Y: 2}); cpu.totalReset(); cpu._regs[regY] = 1; _opTest(0x88, 2, {flagN: false, flagZ: true, Y: 0}); cpu.totalReset(); cpu._regs[regY] = 0; _opTest(0x88, 2, {flagN: true, flagZ: false, Y: 255}); }) }) describe("executes EOR", function(){ it("in immediate mode", function(){ cpu.writeByte(1, 0xFF); _opTest(0x49, 2, {A: 0xFF, flagN: true, flagZ: false}); cpu.totalReset() _opTest(0x49, 2, {A: 0, flagN: false, flagZ: true}); }) it("in zero page mode", function(){ cpu.totalReset(); cpu.writeByte(0x70, 0xFF); cpu.writeByte(1, 0x70); _opTest(0x45, 3, {A: 0xFF, flagN: true, flagZ: false}); }) it("in zero page indexed x mode", function(){ cpu.totalReset(); cpu.writeByte(0x70, 0xFF); cpu.writeByte(1, 0x6F); cpu._regs[regX] = 1; _opTest(0x55, 4, {A: 0xFF, flagN: true, flagZ: false}); }) it("in absolute mode", function(){ cpu.totalReset(); cpu.writeByte(0xFACE, 0xFF); cpu.writeWord(1, 0xFACE); _opTest(0x4D, 4, {A: 0xFF, flagN: true, flagZ: false}); }) it("in absolute indexed x mode", function(){ cpu.totalReset(); cpu.writeByte(0xF100, 0xFF); cpu.writeWord(1, 0xF0FF); cpu._regs[regX] = 1; _opTest(0x5D, 5, {A: 0xFF, flagN: true, flagZ: false}); }) it("in absolute indexed y mode", function(){ cpu.totalReset(); cpu.writeByte(0xFACE, 0xFF); cpu.writeWord(1, 0xFACD); cpu._regs[regY] = 1; _opTest(0x59, 4, {A: 0xFF, flagN: true, flagZ: false}); }) it("in indirect indexed x mode", function(){ cpu.totalReset(); cpu.writeByte(0xFACE, 0xFF); cpu.writeWord(0x70, 0xFACE); cpu.writeWord(1, 0x6C); cpu._regs[regX] = 4; _opTest(0x41, 6, {A: 0xFF, flagN: true, flagZ: false}); }) it("in indirect indexed y mode", function(){ cpu.totalReset(); cpu.writeByte(0xF100, 0xFF); cpu.writeWord(0x70, 0xF0FF) cpu.writeByte(1, 0x70); cpu._regs[regY] = 1; _opTest(0x51, 6, {A: 0xFF, flagN: true, flagZ: false}); }) }) describe("executes INC", function(){ it("in zero page mode", function(){ cpu.writeByte(0x70, 0x3); cpu.writeByte(1, 0x70); _opTest(0xE6, 5, {flagN: false, flagZ: false}); expect(cpu.readByte(0x70)).toEqual(4); cpu.totalReset(); cpu.writeByte(0x70, 0xFF); cpu.writeByte(1, 0x70); _opTest(0xE6, 5, {flagN: false, flagZ: true}); expect(cpu.readByte(0x70)).toEqual(0); cpu.totalReset(); cpu.writeByte(0x70, 0xFE); cpu.writeByte(1, 0x70); _opTest(0xE6, 5, {flagN: true, flagZ: false}); expect(cpu.readByte(0x70)).toEqual(255); }) it("in zero page indexed x mode", function(){ cpu.totalReset(); cpu.writeByte(0x70, 3); cpu.writeByte(1, 0x6E); cpu._regs[regX] = 2; _opTest(0xF6, 6, {flagN: false, flagZ: false}); expect(cpu.readByte(0x70)).toEqual(4); }) it("in absolute mode", function(){ cpu.totalReset(); cpu.writeByte(0xFACE, 3); cpu.writeWord(1, 0xFACE); cpu.flagZ = true; _opTest(0xEE, 6, {flagN: false, flagZ: false}); expect(cpu.readByte(0xFACE)).toEqual(4); }) it("in absolute indexed x mode", function(){ cpu.totalReset(); cpu.writeByte(0xFACE, 3); cpu.writeWord(1, 0xFACD); cpu._regs[regX] = 1; _opTest(0xFE, 7, {flagN: false, flagZ: false}); expect(cpu.readByte(0xFACE)).toEqual(4); }) }) describe("executes INX", function(){ it("in implied mode", function(){ cpu._regs[regX] = 3; _opTest(0xE8, 2, {flagN: false, flagZ: false, X: 4}); cpu.totalReset(); cpu._regs[regX] = 255; _opTest(0xE8, 2, {flagN: false, flagZ: true, X: 0}); cpu.totalReset(); cpu._regs[regX] = 254; _opTest(0xE8, 2, {flagN: true, flagZ: false, X: 255}); }) }) describe("executes INY", function(){ it("in implied mode", function(){ cpu._regs[regY] = 3; _opTest(0xC8, 2, {flagN: false, flagZ: false, Y: 4}); cpu.totalReset(); cpu._regs[regY] = 255; _opTest(0xC8, 2, {flagN: false, flagZ: true, Y: 0}); cpu.totalReset(); cpu._regs[regY] = 254; _opTest(0xC8, 2, {flagN: true, flagZ: false, Y: 255}); }) }) describe("executes JMP", function(){ it("in absolute mode", function(){ cpu.writeWord(1, 0xFACE) _opTest(0x4C, 3, {PC: 0xFACE}); }) it("in indirect mode", function(){ cpu.totalReset(); cpu.writeWord(0xFACE, 0xBEAD); cpu.writeWord(1, 0xFACE); _opTest(0x6C, 5, {PC: 0xBEAD}); }) }) describe("executes JSR", function(){ it("in absolute mode", function(){ cpu._regPC[regPC] = 0xCEAD; cpu.writeWord(0xCEAE, 0xFACE); _opTest(0x20, 6, {PC: 0xFACE}); expect(cpu.popWord()).toEqual(0xCEAF); }) }) describe("executes LDA", function(){ it("in immediate mode", function(){ cpu.writeByte(1, 0x02); _opTest(0xA9, 2, {A: 0x02, flagN: false, flagZ: false}); cpu.writeByte(3, 0x0); _opTest(0xA9, 2, {A: 0, flagN: false, flagZ: true}); cpu.writeByte(5, 0xA5); _opTest(0xA9, 2, {A: 0xA5, flagN: true, flagZ: false}) }) it("in zero page mode", function(){ cpu.totalReset(); cpu.writeByte(0x70, 0xAB); cpu.writeByte(1, 0x70); _opTest(0xA5, 3, {A: 0xAB, flagN: true, flagZ: false}); }) it("in zero page indexed x mode", function(){ cpu.totalReset(); cpu.writeByte(0x70, 0xCD); cpu.writeByte(1, 0x6F); cpu._regs[regX] = 1; _opTest(0xB5, 4, {A: 0xCD, flagN: true, flagZ: false}); }) it("in absolute mode", function(){ cpu.totalReset(); cpu.writeByte(0xFACE, 0xFD); cpu.writeWord(1, 0xFACE); _opTest(0xAD, 4, {A: 0xFD, flagN: true, flagZ: false}); }) it("in absolute indexed x mode", function(){ cpu.totalReset(); cpu.writeByte(0xF100, 0xFE); cpu.writeWord(1, 0xF0FF); cpu._regs[regX] = 1; _opTest(0xBD, 5, {A: 0xFE, flagN: true, flagZ: false}); }) it("in absolute indexed y mode", function(){ cpu.totalReset(); cpu.writeByte(0xFACE, 0xFF); cpu.writeWord(1, 0xFACD); cpu._regs[regY] = 1; _opTest(0xB9, 4, {A: 0xFF, flagN: true, flagZ: false}); }) it("in indirect indexed x mode", function(){ cpu.totalReset(); cpu.writeByte(0xFACE, 0xAF); cpu.writeWord(0x70, 0xFACE); cpu.writeWord(1, 0x6C); cpu._regs[regX] = 4; _opTest(0xA1, 6, {A: 0xAF, flagN: true, flagZ: false}); }) it("in indirect indexed y mode", function(){ cpu.totalReset(); cpu.writeByte(0xF100, 0xBF); cpu.writeWord(0x70, 0xF0FF) cpu.writeByte(1, 0x70); cpu._regs[regY] = 1; _opTest(0xB1, 6, {A: 0xBF, flagN: true, flagZ: false}); }) }) describe("executes LDX", function(){ it("in immediate mode", function(){ cpu.writeByte(1, 0x02); _opTest(0xA2, 2, {X: 0x02, flagN: false, flagZ: false}); cpu.writeByte(3, 0x0); _opTest(0xA2, 2, {X: 0, flagN: false, flagZ: true}); cpu.writeByte(5, 0xA5); _opTest(0xA2, 2, {X: 0xA5, flagN: true, flagZ: false}) }) it("in zero page mode", function(){ cpu.totalReset(); cpu.writeByte(0x70, 0xAB); cpu.writeByte(1, 0x70); _opTest(0xA6, 3, {X: 0xAB, flagN: true, flagZ: false}); }) it("in zero page indexed y mode", function(){ cpu.totalReset(); cpu.writeByte(0x70, 0xCD); cpu.writeByte(1, 0x6F); cpu._regs[regY] = 1; _opTest(0xB6, 4, {X: 0xCD, flagN: true, flagZ: false}); }) it("in absolute mode", function(){ cpu.totalReset(); cpu.writeByte(0xFACE, 0xFD); cpu.writeWord(1, 0xFACE); _opTest(0xAE, 4, {X: 0xFD, flagN: true, flagZ: false}); }) it("in absolute indexed y mode", function(){ cpu.totalReset(); cpu.writeByte(0xF100, 0xFE); cpu.writeWord(1, 0xF0FF); cpu._regs[regY] = 1; _opTest(0xBE, 5, {X: 0xFE, flagN: true, flagZ: false}); }) }) describe("executes LDY", function(){ it("in immediate mode", function(){ cpu.writeByte(1, 0x02); _opTest(0xA0, 2, {Y: 0x02, flagN: false, flagZ: false}); cpu.writeByte(3, 0x0); _opTest(0xA0, 2, {Y: 0, flagN: false, flagZ: true}); cpu.writeByte(5, 0xA5); _opTest(0xA0, 2, {Y: 0xA5, flagN: true, flagZ: false}) }) it("in zero page mode", function(){ cpu.totalReset(); cpu.writeByte(0x70, 0xAB); cpu.writeByte(1, 0x70); _opTest(0xA4, 3, {Y: 0xAB, flagN: true, flagZ: false}); }) it("in zero page indexed x mode", function(){ cpu.totalReset(); cpu.writeByte(0x70, 0xCD); cpu.writeByte(1, 0x6F); cpu._regs[regX] = 1; _opTest(0xB4, 4, {Y: 0xCD, flagN: true, flagZ: false}); }) it("in absolute mode", function(){ cpu.totalReset(); cpu.writeByte(0xFACE, 0xFD); cpu.writeWord(1, 0xFACE); _opTest(0xAC, 4, {Y: 0xFD, flagN: true, flagZ: false}); }) it("in absolute indexed x mode", function(){ cpu.totalReset(); cpu.writeByte(0xF100, 0xFE); cpu.writeWord(1, 0xF0FF); cpu._regs[regX] = 1; _opTest(0xBC, 5, {Y: 0xFE, flagN: true, flagZ: false}); }) }) describe("executes LSR", function(){ it("in accumulator mode", function(){ cpu._regs[regA] = 0x80; _opTest(0x4A, 2, {A: 0x40, flagN: false, flagZ: false, flagC: false}); cpu._regs[regA] = 0x01; _opTest(0x4A, 2, {A: 0x00, flagN: false, flagZ: true, flagC: true}); cpu._regs[regA] = 0x03; _opTest(0x4A, 2, {A: 0x01, flagN: false, flagZ: false, flagC: true}); }) it("in zero page mode", function(){ cpu.totalReset(); cpu.writeByte(0x80, 0x40); cpu.writeByte(1, 0x80); _opTest(0x46, 5, {flagN: false, flagZ: false, flagC: false}); expect(cpu.readByte(0x80)).toEqual(0x20); }) it("in zero page indexed x mode", function(){ cpu.totalReset(); cpu.writeByte(0xFD, 0x20); cpu.writeByte(1, 0xFB); cpu._regs[regX] = 2; _opTest(0x56, 6, {}); expect(cpu.readByte(0xFD)).toEqual(0x10); }) it("in absolute mode", function(){ cpu.totalReset(); cpu.writeByte(0xFACE, 0x80); cpu.writeWord(1, 0xFACE); _opTest(0x4E, 6, {}); expect(cpu.readByte(0xFACE)).toEqual(0x40); }) it("in absolute indexed x mode", function(){ cpu.totalReset(); cpu.writeByte(0xABCD, 0x40); cpu.writeWord(1, 0xABC9); cpu._regs[regX] = 4; _opTest(0x5E, 7, {}); expect(cpu.readByte(0xABCD)).toEqual(0x20); }) }) describe("executes NOP", function(){ it("in implied mode", function(){ _opTest(0xEA, 2, {}); }) }) describe("executes ORA", function(){ it("in immediate mode", function(){ cpu.writeByte(1, 1); cpu._regs[regA] = 0x80; _opTest(0x09, 2, {A: 0x81, flagN: true, flagZ: false}); cpu.writeByte(3, 0); cpu._regs[regA] = 0; _opTest(0x09, 2, {A: 0, flagN: false, flagZ: true}); cpu.writeByte(5, 2); cpu._regs[regA] = 1; _opTest(0x09, 2, {A: 3, flagN: false, flagZ: false}); }) it("in zero page mode", function(){ cpu.writeByte(0x70, 0x02); cpu.writeByte(1, 0x70); cpu._regs[regA] = 0x80; _opTest(0x05, 3, {A: 0x82}); }) it("in zero page indexed x mode", function(){ cpu.totalReset(); cpu.writeByte(0x70, 2); cpu.writeByte(1, 0x6F); cpu._regs[regX] = 1; cpu._regs[regA] = 0x80; _opTest(0x15, 4, {A: 0x82, flagN: true, flagZ: false}); }) it("in absolute mode", function(){ cpu.totalReset(); cpu.writeByte(0xFACE, 2); cpu.writeWord(1, 0xFACE); cpu._regs[regA] = 0x80; _opTest(0x0D, 4, {A: 0x82, flagN: true, flagZ: false}); }) it("in absolute indexed x mode", function(){ cpu.totalReset(); cpu.writeByte(0xF100, 0x02); cpu.writeWord(1, 0xF0FF); cpu._regs[regX] = 1; cpu._regs[regA] = 0x80; _opTest(0x1D, 5, {A: 0x82, flagN: true, flagZ: false}); }) it("in absolute indexed y mode", function(){ cpu.totalReset(); cpu.writeByte(0xFACE, 0x02); cpu.writeWord(1, 0xFACD); cpu._regs[regY] = 1; cpu._regs[regA] = 0x80; _opTest(0x19, 4, {A: 0x82, flagN: true, flagZ: false}); }) it("in indirect indexed x mode", function(){ cpu.totalReset(); cpu.writeByte(0xFACE, 0x02); cpu.writeWord(0x70, 0xFACE); cpu.writeWord(1, 0x6C); cpu._regs[regX] = 4; cpu._regs[regA] = 0x80; _opTest(0x01, 6, {A: 0x82, flagN: true, flagZ: false}); }) it("in indirect indexed y mode", function(){ cpu.totalReset(); cpu.writeByte(0xF100, 0x02); cpu.writeWord(0x70, 0xF0FF) cpu.writeByte(1, 0x70); cpu._regs[regY] = 1; cpu._regs[regA] = 0x80; _opTest(0x11, 6, {A: 0x82, flagN: true, flagZ: false}); }) }) describe("executes PHA", function(){ it("in implied mode", function(){ cpu._regs[regA] = 0xBA; _opTest(0x48, 3, {A: 0xBA}); expect(cpu.popByte()).toEqual(0xBA); }) }) describe("executes PHP", function(){ it("in implied mode", function(){ cpu.flagC = true; cpu.flagZ = true; cpu.flagN = true; _opTest(0x08, 3, {}); //Were the flags combined and pushed correctly? expect(cpu.popByte()).toEqual(0xB3); }) }) describe("executes PLA", function(){ it("in implied mode", function(){ cpu._regs[regA] = 0xBA; cpu.execute(0x48); cpu._regs[regA] = 0x00; _opTest(0x68, 4, {A: 0xBA, flagN: true, flagZ: false}); }) }) describe("executes PLP", function(){ it("in implied mode", function(){ cpu.flagC = true; cpu.flagZ = true; cpu.flagN = true; cpu.execute(0x08); cpu.flagC = false; cpu.flagZ = false; cpu.flagN = false; _opTest(0x28, 4, {}); expect(cpu.flagC).toEqual(true); expect(cpu.flagZ).toEqual(true); expect(cpu.flagN).toEqual(true); }) }) describe("executes ROL", function(){ it("in accumulator mode", function(){ cpu._regs[regA] = 0x01; _opTest(0x2A, 2, {A: 0x02, flagN: false, flagZ: false, flagC: false}); cpu._regs[regA] = 0x80; _opTest(0x2A, 2, {A: 0x00, flagN: false, flagZ: true, flagC: true}); cpu._regs[regA] = 0x40; cpu.flagC = true; _opTest(0x2A, 2, {A: 0x81, flagN: true, flagZ: false, flagC: false}); }) it("in zero page mode", function(){ cpu.totalReset(); cpu.writeByte(0x80, 0x20); cpu.writeByte(1, 0x80); _opTest(0x26, 5, {flagN: false, flagZ: false, flagC: false}); expect(cpu.readByte(0x80)).toEqual(0x40); }) it("in zero page indexed x mode", function(){ cpu.totalReset(); cpu.writeByte(0xFD, 0x20); cpu.writeByte(1, 0xFB); cpu._regs[regX] = 2; _opTest(0x36, 6, {}); expect(cpu.readByte(0xFD)).toEqual(0x40); }) it("in absolute mode", function(){ cpu.totalReset(); cpu.writeByte(0xFACE, 0x20); cpu.writeWord(1, 0xFACE); _opTest(0x2E, 6, {}); expect(cpu.readByte(0xFACE)).toEqual(0x40); }) it("in absolute indexed x mode", function(){ cpu.totalReset(); cpu.writeByte(0xABCD, 0x20); cpu.writeWord(1, 0xABC9); cpu._regs[regX] = 4; _opTest(0x3E, 7, {}); expect(cpu.readByte(0xABCD)).toEqual(0x40); }) }) describe("executes ROR", function(){ it("in accumulator mode", function(){ cpu._regs[regA] = 0x80; _opTest(0x6A, 2, {A: 0x40, flagN: false, flagZ: false, flagC: false}); cpu._regs[regA] = 0x01; _opTest(0x6A, 2, {A: 0x00, flagN: false, flagZ: true, flagC: true}); cpu._regs[regA] = 0x02; cpu.flagC = true; _opTest(0x6A, 2, {A: 0x81, flagN: true, flagZ: false, flagC: false}); }) it("in zero page mode", function(){ cpu.totalReset(); cpu.writeByte(0x80, 0x20); cpu.writeByte(1, 0x80); _opTest(0x66, 5, {flagN: false, flagZ: false, flagC: false}); expect(cpu.readByte(0x80)).toEqual(0x10); }) it("in zero page indexed x mode", function(){ cpu.totalReset(); cpu.writeByte(0xFD, 0x20); cpu.writeByte(1, 0xFB); cpu._regs[regX] = 2; _opTest(0x76, 6, {}); expect(cpu.readByte(0xFD)).toEqual(0x10); }) it("in absolute mode", function(){ cpu.totalReset(); cpu.writeByte(0xFACE, 0x20); cpu.writeWord(1, 0xFACE); _opTest(0x6E, 6, {}); expect(cpu.readByte(0xFACE)).toEqual(0x10); }) it("in absolute indexed x mode", function(){ cpu.totalReset(); cpu.writeByte(0xABCD, 0x20); cpu.writeWord(1, 0xABC9); cpu._regs[regX] = 4; _opTest(0x7E, 7, {}); expect(cpu.readByte(0xABCD)).toEqual(0x10); }) }) describe("executes RTI", function(){ it("in implied mode", function(){ cpu.flagC = true; cpu.flagZ = true; cpu._regPC[regPC] = 0xFACE; cpu.postInterrupt(INTERRUPT_IRQ); cpu.handleInterrupt(); cpu.flagZ = false; cpu._regPC[regPC] = 0xABCD; _opTest(0x40, 6, { PC: 0xFACE, flagI: false, flagC: true, flagZ: true, }) }) }) describe("executes RTS", function(){ it("in implied mode", function(){ cpu.flagC = true; cpu.flagZ = true; cpu._regPC[regPC] = 0xCEAD; cpu.writeWord(0xCEAE, 0xFACE); cpu.execute(0x20); cpu.flagZ = false; cpu._regPC[regPC] = 0xABCD; _opTest(0x60, 6, { PC: 0xCEB0, flagC: true, flagZ: false, }) }) }) describe("executes SBC", function(){ it("in immediate mode", function(){ cpu.writeByte(1, 2); cpu._regs[regA] = 3; cpu.flagC = true; _opTest(0xE9, 2, {A: 1, flagN: false, flagZ: false, flagC: true, flagV: false}); cpu.totalReset(); cpu.writeByte(1, 3); cpu._regs[regA] = 5; cpu.flagC = true; _opTest(0xE9, 2, {A: 2, flagN: false, flagZ: false, flagC: true, flagV: false}); cpu.totalReset(); cpu.writeByte(1, 6); cpu._regs[regA] = 5; cpu.flagC = true; _opTest(0xE9, 2, {A: 255, flagN: true, flagZ: false, flagC: false, flagV: false}); //Making sure overflow is being set correctly... cpu.totalReset(); cpu.writeByte(1, -1); cpu._regs[regA] = 127; cpu.flagC = true; _opTest(0xE9, 2, {A: 128, flagV: true}); cpu.totalReset(); cpu.writeByte(1, 1); cpu._regs[regA] = -128; cpu.flagC = true; _opTest(0xE9, 2, {A: 127, flagV: true, flagC: true}); cpu.totalReset(); cpu.writeByte(1, 1); cpu._regs[regA] = -128; cpu.flagC = true; _opTest(0xE9, 2, {A: 127, flagV: true}); cpu.totalReset(); cpu.writeByte(1, 1); cpu._regs[regA] = 0; cpu.flagC = true; _opTest(0xE9, 2, {A: 255, flagV: false}); cpu.totalReset(); cpu.writeByte(1, 64); cpu._regs[regA] = -64; //cpu.flagC = true; _opTest(0xE9, 2, {A: 127, flagV: true}); }) it("in zero page mode", function(){ cpu.writeByte(0xAB, 4); cpu.writeByte(1, 0xAB); cpu._regs[regA] = 5; cpu.flagC = true; _opTest(0xE5, 3, {A: 1}); }) it("in zero page indexed x mode", function(){ cpu.writeByte(0xAB, 4); cpu.writeByte(1, 0xA9); cpu._regs[regA] = 5; cpu._regs[regX] = 2; cpu.flagC = true; _opTest(0xF5, 4, {A: 1}); }) it("in absolute mode", function(){ cpu.writeByte(0xFACE, 4); cpu.writeWord(1, 0xFACE); cpu._regs[regA] = 5; cpu.flagC = true; _opTest(0xED, 4, {A: 1}); }) it("in absolute indexed x mode", function(){ cpu.writeByte(0xA101, 4); cpu.writeWord(1, 0xA0FE); cpu._regs[regX] = 3; cpu._regs[regA] = 5; cpu.flagC = true; _opTest(0xFD, 5, {A: 1}); }) it("in absolute indexed y mode", function(){ cpu.writeByte(0xA101, 4); cpu.writeWord(1, 0xA0FE); cpu._regs[regY] = 3; cpu._regs[regA] = 5; cpu.flagC = true; _opTest(0xF9, 5, {A: 1}); }) it("in indirect indexed x mode", function(){ cpu.writeByte(0xA101, 4); cpu.writeWord(0xAB, 0xA101); cpu.writeByte(1, 0xA8); cpu._regs[regX] = 3; cpu._regs[regA] = 5; cpu.flagC = true; _opTest(0xE1, 6, {A: 1}); }) it("in indirect indexed y mode", function(){ cpu.writeByte(0xA101, 4); cpu.writeWord(0xAB, 0xA0FE); cpu.writeWord(1, 0xAB); cpu._regs[regY] = 3; cpu._regs[regA] = 5; cpu.flagC = true; _opTest(0xF1, 6, {A: 1}); }) }) describe("executes SEC", function(){ it("in implied mode", function(){ _opTest(0x38, 2, {flagC: true}); }) }) describe("executes SED", function(){ it("in implied mode", function(){ _opTest(0xF8, 2, {flagD: true}); }) }) describe("executes SEI", function(){ it("in implied mode", function(){ _opTest(0x78, 2, {flagI: true}); }) }) describe("executes STA", function(){ it("in zero page mode", function(){ cpu.writeByte(1, 0x21); cpu._regs[regA] = 0xAB; _opTest(0x85, 3, {}); expect(cpu.readByte(0x21)).toEqual(0xAB); }) it("in zero page indexed x mode", function(){ cpu.totalReset(); cpu.writeByte(1, 0x21); cpu._regs[regA] = 0xAB; cpu._regs[regX] = 3 _opTest(0x95, 4, {}); expect(cpu.readByte(0x24)).toEqual(0xAB); }) it("in absolute mode", function(){ cpu.totalReset(); cpu.writeWord(1, 0xFACE); cpu._regs[regA] = 0xAB; _opTest(0x8D, 4, {}); expect(cpu.readByte(0xFACE)).toEqual(0xAB); }) it("in absolute indexed x mode", function(){ cpu.totalReset(); cpu.writeWord(1, 0xFACC); cpu._regs[regA] = 0xAB; cpu._regs[regX] = 2; _opTest(0x9D, 5, {}); expect(cpu.readByte(0xFACE)).toEqual(0xAB); }) it("in absolute indexed y mode", function(){ cpu.totalReset(); cpu.writeWord(1, 0xFACC); cpu._regs[regA] = 0xAB; cpu._regs[regY] = 2; _opTest(0x99, 5, {}); expect(cpu.readByte(0xFACE)).toEqual(0xAB); }) it("in indirect indexed x mode", function(){ cpu.totalReset(); cpu.writeWord(0x12, 0xFACE) cpu.writeByte(1, 0x10); cpu._regs[regA] = 0xAB; cpu._regs[regX] = 2; _opTest(0x81, 6, {}); expect(cpu.readByte(0xFACE)).toEqual(0xAB); }) it("in indirect indexed y mode", function(){ cpu.totalReset(); cpu.writeWord(0x12, 0xFACC) cpu.writeByte(1, 0x12); cpu._regs[regA] = 0xAB; cpu._regs[regY] = 2; _opTest(0x91, 6, {}); expect(cpu.readByte(0xFACE)).toEqual(0xAB); }) }) describe("executes STX", function(){ it("in zero page mode", function(){ cpu.writeByte(1, 0x21); cpu._regs[regX] = 0xAB; _opTest(0x86, 3, {}); expect(cpu.readByte(0x21)).toEqual(0xAB); }) it("in zero page indexed y mode", function(){ cpu.totalReset(); cpu.writeByte(1, 0x21); cpu._regs[regX] = 0xAB; cpu._regs[regY] = 3 _opTest(0x96, 4, {}); expect(cpu.readByte(0x24)).toEqual(0xAB); }) it("in absolute mode", function(){ cpu.totalReset(); cpu.writeWord(1, 0xFACE); cpu._regs[regX] = 0xAB; _opTest(0x8E, 4, {}); expect(cpu.readByte(0xFACE)).toEqual(0xAB); }) }) describe("executes STY", function(){ it("in zero page mode", function(){ cpu.writeByte(1, 0x21); cpu._regs[regY] = 0xAB; _opTest(0x84, 3, {}); expect(cpu.readByte(0x21)).toEqual(0xAB); }) it("in zero page indexed y mode", function(){ cpu.totalReset(); cpu.writeByte(1, 0x21); cpu._regs[regY] = 0xAB; cpu._regs[regX] = 3 _opTest(0x94, 4, {}); expect(cpu.readByte(0x24)).toEqual(0xAB); }) it("in absolute mode", function(){ cpu.totalReset(); cpu.writeWord(1, 0xFACE); cpu._regs[regY] = 0xAB; _opTest(0x8C, 4, {}); expect(cpu.readByte(0xFACE)).toEqual(0xAB); }) }) describe("executes TAX", function(){ it("in implied mode",function(){ cpu._regs[regA] = 0xCD; _opTest(0xAA, 2, {A: 0xCD, X: 0xCD, flagN: true, flagZ: false}); cpu._regs[regA] = 0x00; _opTest(0xAA, 2, {A: 0x00, X: 0x00, flagN: false, flagZ: true}); cpu._regs[regA] = 0x04; _opTest(0xAA, 2, {A: 0x04, X: 0x04, flagN: false, flagZ: false}); }) }) describe("executes TAY", function(){ it("in implied mode",function(){ cpu._regs[regA] = 0xCD; _opTest(0xA8, 2, {A: 0xCD, Y: 0xCD, flagN: true, flagZ: false}); cpu._regs[regA] = 0x00; _opTest(0xA8, 2, {A: 0x00, Y: 0x00, flagN: false, flagZ: true}); cpu._regs[regA] = 0x04; _opTest(0xA8, 2, {A: 0x04, Y: 0x04, flagN: false, flagZ: false}); }) }) describe("executes TSX", function(){ it("in implied mode",function(){ cpu._regs[regSP] = 0xCD; _opTest(0xBA, 2, {SP: 0xCD, X: 0xCD, flagN: true, flagZ: false}); cpu._regs[regSP] = 0x00; _opTest(0xBA, 2, {SP: 0x00, X: 0x00, flagN: false, flagZ: true}); cpu._regs[regSP] = 0x04; _opTest(0xBA, 2, {SP: 0x04, X: 0x04, flagN: false, flagZ: false}); }) }) describe("executes TXA", function(){ it("in implied mode",function(){ cpu._regs[regX] = 0xCD; _opTest(0x8A, 2, {X: 0xCD, A: 0xCD, flagN: true, flagZ: false}); cpu._regs[regX] = 0x00; _opTest(0x8A, 2, {X: 0x00, A: 0x00, flagN: false, flagZ: true}); cpu._regs[regX] = 0x04; _opTest(0x8A, 2, {X: 0x04, A: 0x04, flagN: false, flagZ: false}); }) }) describe("executes TXS", function(){ it("in implied mode",function(){ cpu._regs[regX] = 0xCD; _opTest(0x9A, 2, {X: 0xCD, SP: 0xCD, flagN: false, flagZ: false}); cpu._regs[regX] = 0x00; _opTest(0x9A, 2, {X: 0x00, SP: 0x00, flagN: false, flagZ: false}); cpu._regs[regX] = 0x04; _opTest(0x9A, 2, {X: 0x04, SP: 0x04, flagN: false, flagZ: false}); }) }) describe("executes TYA", function(){ it("in implied mode",function(){ cpu._regs[regY] = 0xCD; _opTest(0x98, 2, {Y: 0xCD, A: 0xCD, flagN: true, flagZ: false}); cpu._regs[regY] = 0x00; _opTest(0x98, 2, {Y: 0x00, A: 0x00, flagN: false, flagZ: true}); cpu._regs[regY] = 0x04; _opTest(0x98, 2, {Y: 0x04, A: 0x04, flagN: false, flagZ: false}); }) }) // describe("throws an error when given an illegal opcode", function(){ // it("reports the illegal opcode", function(){ // var badOp = cpu.execute.bind(cpu, 0xAB); // expect(badOp).toThrowError(/0xab/); // }) // }) }) cpu.totalReset(); describe("correctly emulates the mirroring of specific address ranges", function(){ it("mirrors $0000 to $07FF at $0800 to $0FFF, $1000 to $17FF, and $18FF to $1FFF", function(){ cpu.writeByte(0x0017, 0xAB); expect(cpu.readByte(0x0017)).toEqual(0xAB); expect(cpu.readByte(0x0817)).toEqual(0xAB); expect(cpu.readByte(0x1017)).toEqual(0xAB); expect(cpu.readByte(0x1817)).toEqual(0xAB); cpu.writeByte(0x1234, 0xCD); expect(cpu.readByte(0x0234)).toEqual(0xCD); expect(cpu.readByte(0x0A34)).toEqual(0xCD); expect(cpu.readByte(0x1234)).toEqual(0xCD); expect(cpu.readByte(0x1A34)).toEqual(0xCD); }) cpu.totalReset(); it("mirrors $2000 to $2007 every 8 bytes until $4000", function(){ cpu.writeByte(0x2001, 0xAB); for(var tmpAddr = 0x2001; tmpAddr < 0x4000; tmpAddr += 8){ expect(cpu.readByte(tmpAddr)).toEqual(0xAB); } cpu.writeByte(0x3018, 0xCD); for(var tmpAddr = 0x2000; tmpAddr < 0x4000; tmpAddr += 8){ expect(cpu.readByte(tmpAddr)).toEqual(0xCD); } }) it("correctly handles a word at a mirrored region's boundary", function(){ cpu.totalReset(); cpu.writeWord(0x07FF, 0xFACE); expect(cpu.readWord(0x07FF)).toEqual(0xFACE); expect(cpu.readWord(0x17FF)).toEqual(0xFACE); expect(cpu.readByte(0x07FF)).toEqual(0xCE); expect(cpu.readByte(0x0000)).toEqual(0xFA); // cpu.totalReset(); // cpu.writeWord(0x2027, 0xFACE); // expect(cpu.readWord(0x2027)).toEqual(0xFACE); // expect(cpu.readWord(0x3027)).toEqual(0xFACE); // expect(cpu.readByte(0x2027)).toEqual(0xCE); // expect(cpu.readByte(0x2020)).toEqual(0xFA); }) }) })
C#
UTF-8
1,952
3.078125
3
[ "MIT" ]
permissive
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Text; namespace Bearded.TD.Game.Generation.Semantic.Fitness; static partial class FitnessFunction { public static FitnessFunction<T> From<T>(params FitnessFunction<T>[] functions) { return new CompositeFitnessFunction<T>(functions); } private sealed class CompositeFitnessFunction<T> : FitnessFunction<T> { private readonly ImmutableArray<FitnessFunction<T>> functions; public override string Name => "Composite Fitness"; public CompositeFitnessFunction(IEnumerable<FitnessFunction<T>> functions) { this.functions = functions.ToImmutableArray(); } public override Fitness<T> FitnessOf(T instance) { var components = functions.Select(f => f.FitnessOf(instance)).ToImmutableArray(); return new CompositeFitness<T>(this, components.Sum(c => c.Value), components); } } private sealed record CompositeFitness<T>( FitnessFunction<T> Function, double Value, ImmutableArray<Fitness<T>> Components) : Fitness<T>(Function, Value) { // ReSharper disable once StaticMemberInGenericType private static readonly char[] newLines = {'\r', '\n'}; public override string ToString() { var stringBuilder = new StringBuilder(); stringBuilder.AppendLine($"{Function.Name}: {Value}"); foreach (var component in Components) { var componentLines = component.ToString() ?? ""; foreach (var line in componentLines.Split(newLines, StringSplitOptions.RemoveEmptyEntries)) { stringBuilder.Append(" "); stringBuilder.AppendLine(line); } } return stringBuilder.ToString(); } } }
Ruby
UTF-8
220
3.171875
3
[]
no_license
require "movie" class RegularMovie < Movie def price(days_rented) amount = 2 if days_rented > 2 amount += (days_rented - 2) * 1.5 end amount end def points(days_rented) 1 end end
Java
UTF-8
1,544
3.421875
3
[]
no_license
package com.javarush.task.task30.task3009; import java.math.BigInteger; import java.util.*; /* Палиндром? */ public class Solution { public static void main(String[] args) { System.out.println(getRadix("112")); //expected output: [3, 27, 13, 15] System.out.println(getRadix("123")); //expected output: [6] System.out.println(getRadix("5321")); //expected output: [] System.out.println(getRadix("1A")); //expected output: [] } private static Set<Integer> getRadix(String number) { HashSet<Integer> set = new HashSet<>(); try { int max = maxIntNew(number) +1; String str = ""; for (int i = 2; i <= 36; i++) { str = Integer.toString(Integer.valueOf(number), i); if(isPalindrom(str)) { set.add(i); } } } catch (NumberFormatException e) { } return set; } private static boolean isPalindrom(String str) { char[] charArray = str.toCharArray(); for (int i = 0; i < charArray.length/2; i++) { if(charArray[i] != charArray[charArray.length-1-i]) return false; } return true; } private static int maxIntNew(String str) { char[] charArray = str.toCharArray(); int max = 0; for (int i = 0; i < charArray.length; i++) { if(charArray[i]-48 > max) max = charArray[i]-48; } return max; } }
Markdown
UTF-8
8,056
2.9375
3
[]
no_license
# Configure Pydantic schemas and User model Now it is time to get more serious stuff. We need proper User model, proper Pydantic schemas and simple endpoint to test our work. I have adopted, changed the code from [Designing a robust User Model](https://www.jeffastor.com/blog/designing-a-robust-user-model-in-a-fastapi-app) Let's get started. First of all let's update our User model with extra columns: ```python from backend.app.main import db class User(db.Model): __tablename__ = "users" id = db.Column(db.BigInteger(), primary_key=True) username = db.Column(db.Unicode(), unique=True, nullable=False) email = db.Column(db.String(), unique=True, nullable=False) email_verified = db.Column(db.Boolean(), nullable=True, server_default="True") salt = db.Column(db.Unicode(), nullable=False) password = db.Column(db.Unicode(), nullable=False) is_active = db.Column(db.Boolean(), nullable=False, server_default="True") is_superuser = db.Column(db.Boolean(), nullable=False, server_default="False") created_at = db.Column(db.DateTime(), nullable=False) updated_at = db.Column(db.DateTime(), nullable=False) ``` Create migration file: ```shell ❯ poetry run alembic revision --autogenerate -m 'update users table' INFO [alembic.runtime.migration] Context impl PostgresqlImpl. INFO [alembic.runtime.migration] Will assume transactional DDL. INFO [alembic.ddl.postgresql] Detected sequence named 'users_id_seq' as owned by integer column 'users(id)', assuming SERIAL and omitting INFO [alembic.autogenerate.compare] Detected removed table 'users' Generating /home/shako/REPOS/Learning_FastAPI/Djackets/backend/migrations/versions/0508f9ca0879_update_users_table.py ... done ``` Run the migration: ```shell poetry run alembic upgrade head INFO [alembic.runtime.migration] Context impl PostgresqlImpl. INFO [alembic.runtime.migration] Will assume transactional DDL. INFO [alembic.runtime.migration] Running upgrade 43774c187998 -> 0508f9ca0879, update users table ``` Next lets define our shared schemas in `app/schemas.py` file: ```python # Define core Pydantic schemas here from typing import Optional from datetime import datetime from pydantic import BaseModel, validator class CoreModel(BaseModel): """ Any common logic to be shared by all models goes here """ pass class DateTimeModelMixin(BaseModel): created_at: Optional[datetime] updated_at: Optional[datetime] @validator("created_at", "updated_at", pre=True, always=True) def default_datetime(cls, value: datetime) -> datetime: return value or datetime.now() class IDModelMixin(BaseModel): id: int ``` Our plan here is to have something code and shared Pydantic models to be used in different schemas. `DateTimeModelMixin` has 2 two properties which will be populated automatically. Basically, we are going to add `created_at` and `updated_at` with `datetime.now()`. Now it is time to add our User schemas: ```python import string from pydantic import EmailStr, constr, validator from backend.app.schemas import CoreModel, DateTimeModelMixin, IDModelMixin from typing import Optional # simple check for valid username def validate_username(username: str) -> str: allowed = string.ascii_letters + string.digits + "-" + "_" assert all(char in allowed for char in username), "Invalid characters in username." assert len(username) >= 3, "Username must be 3 characters or more." return username class UserBase(CoreModel): """ Leaving off password and salt from base model """ email: Optional[EmailStr] username: Optional[str] email_verified: bool = False is_active: bool = True is_superuser: bool = False class UserCreate(CoreModel): """ Email, username, and password are required for registering a new user """ email: EmailStr password: constr(min_length=7, max_length=100) username: str @validator("username", pre=True) def username_is_valid(cls, username: str) -> str: return validate_username(username) class UserInDB(IDModelMixin, DateTimeModelMixin, UserBase): """ Add in id, created_at, updated_at, and user's password and salt """ password: constr(min_length=7, max_length=100) salt: str class UserPublic(DateTimeModelMixin, UserBase): pass # TODO: UserUpdate for profile update can be here # TODO: UserPasswordUpdate for password update can be here ``` Why we need `UserPublic`? It is basically for response model, we do not want to return password, salt, etc back to the user. Now let's add our first view(or controller) to test. I am going to remove `v1.py` file from `users/api/` and add `controller.py` instead: ```python from fastapi import APIRouter, status, Body from fastapi.responses import JSONResponse from ..schemas import UserCreate, UserInDB, UserPublic router = APIRouter() @router.post( "/create", tags=["user registration"], description="Register the User", response_model=UserPublic, ) async def user_create(user: UserCreate): return user ``` What we have so far? We have indicated that we want as input `UserCreate` model which is from Pydantic, we also have `response_model` which is a neat thing to indicate what the frontend side will get back after sending POST request to our endpoint. Wait, we need to register our router. Open the `app/main.py` file and update: ```python import sys from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from .core.config import settings from .database import db sys.path.append('..') # fixing parent folder import error from backend.users.api.controller import router as user_router def get_application(): _app = FastAPI(title=settings.PROJECT_NAME) _app.add_middleware( CORSMiddleware, allow_origins=[str(origin) for origin in settings.BACKEND_CORS_ORIGINS], allow_credentials=True, allow_methods=["*"], allow_headers=["*"], ) db.init_app(_app) _app.include_router(user_router, prefix='/users') # this is the new added return _app app = get_application() ``` Fire up the server: ```shell ❯ fastapi run INFO: Uvicorn running on http://127.0.0.1:8000 (Press CTRL+C to quit) INFO: Started reloader process [1322] using statreload INFO: Started server process [1325] INFO: Waiting for application startup. INFO: Application startup complete. ``` You can go to `http://127.0.0.1:8000/docs` and see our new endpoint and even test it there. For simplicity I am going to run cURL here: ```shell curl -X POST http://127.0.0.1:8000/users/create -d '{"email": "example@gmail.com", "password": "123456789", "username": "example"}' | jq { "email": "example@gmail.com", "username": "example", "email_verified": false, "is_active": true, "is_superuser": false, "created_at": "2021-05-14T16:15:36.070429", "updated_at": "2021-05-14T16:15:36.070445" } ``` As you see the request data is what we have defined in `UserCreate` schema, and the response data was automatically populated for us from `UserPublic` schema. That is it for now. So we have setup the User model, User schemas and we have our simple endpoint for just returning back the UserPublic data. But It is fully functional and even the validation is in place: ```shell curl -X POST http://127.0.0.1:8000/users/create -d '{"email": "example@gmail.com", "password": "12345", "username": "example"}' | jq { "detail": [ { "loc": [ "body", "password" ], "msg": "ensure this value has at least 7 characters", "type": "value_error.any_str.min_length", "ctx": { "limit_value": 7 } } ] } ``` Great the next thing is to improve our User registration and to add password salt/hashing. The code changes for this episode -> [episode-4](https://github.com/ShahriyarR/ecommerce-nuxtjs-fastapi-backend/tree/episode-4) ### NEXT -> [Configure User registration - password hashing](./ecommerce-configure-user-registration)
JavaScript
UTF-8
1,300
2.625
3
[]
no_license
import {createSlice} from "@reduxjs/toolkit"; const slice = createSlice({ name: 'degree', initialState: { degrees: [ {id: 1, name: 'Junior', bonus: 10}, {id: 2, name: 'Middle', bonus: 15}, {id: 3, name: 'Senior', bonus: 30} ] }, reducers: { addDegree: (state, action) => { state.degrees.push({id: state.degrees.length + 1, name: action.payload.name, bonus: action.payload.bonus}) }, editDegree: (state, action) => { state.degrees.map(item => { if (item.id === action.payload.id) { item.name = action.payload.name item.bonus = action.payload.bonus } return item }) }, deleteDegree: (state, action) => { state.degrees.map((item, index) => { if (item.id === action.payload) { state.degrees.splice(index, 1) } return item }) }, searchDegree: (state, action) => { state.degrees.filter(item => item.name === action.payload) } } }) export const {addDegree, editDegree, deleteDegree, searchDegree} = slice.actions export default slice.reducer
TypeScript
UTF-8
278
2.90625
3
[]
no_license
export class Meeting { title: string; speaker: string; date: Date; active: boolean; constructor({title = '', speaker = '', date = new Date(), active = true}) { this.title = title; this.speaker = speaker; this.date = date; this.active = active; } }
Python
UTF-8
1,876
3.359375
3
[]
no_license
from selenium import webdriver from collections import namedtuple from pprint import pprint class Cult: def __init__(self, driver): self.driver = driver self.url = 'http://www.cultcampinas.com.br' self.box = 'eventbox' #class self.type ='typeEventBox'#class self.title_box = 'titleEventBox'#titulo self.date = 'dateEvent'#class self.place='placeEvent'#class self.hour = 'hourEvent'#class self.descr='descEventBox'#class self.event = namedtuple('Event','title type date place hour descr') def navigate(self): self.driver.get(self.url) def _get_boxes(self): return self.driver.find_elements.by_class_name(self.box) def _get_title(self): return self.box.find_element_by_class_name(self.title_box) def _get_type(self,box): return self.box.find_element_by_class_name(self.type) def _get_date(self, box): return self.box.find_element_by_class_name(self.date) def _get_descr(self, box): return self.box.find_element_by_class_name(self.descr) def _get_hour(self, box): return self.box.find_element_by_class_name(self.hour) ''' def get_all_data(self): boxes = self._get_boxs() for box in boxes: print(box)''' #exibindo o titulo def get_all_data(self): boxes = self._get_boxes() for box in boxes: yield self.event(self._get_title(box).text, self._get_type(box).text, self._get_date(box).text, self._get_place(box).text, self._get_hour(box).text, self._get_descr(box).text) ff= webdriver.Firefox() c = Cult(ff) c.navigate() #c.get_all_data() for event in c.get_all_data(): print(event)
C
UTF-8
1,977
2.671875
3
[]
no_license
#include"oddEven.decl.h" int numelements; CProxy_Main mainproxy; CProxy_Worker workerarray; class myMsg: public CMessage_myMsg { public: int val; }; class Main: public CBase_Main { public: Main(CkArgMsg* msg) { if(msg->argc !=2 ) { CkExit(); } numelements = atoi(msg->argv[1]); mainproxy = thisProxy; workerarray = CProxy_Worker::ckNew(numelements); workerarray.run(); } void done (CkReductionMsg* msg) { for(int i = 0 ; i < numelements; i++) { workerarray(i).dump(); } CkExit(); } }; class Worker: public CBase_Worker { public: int val; CthThread t; Worker() { srand(thisIndex); val = ((double) rand()/RAND_MAX) * 100; CkPrintf("Initial: [%d]: val : %d\n", thisIndex, val); } void dump() { CkPrintf("Final: [%d]: val : %d\n", thisIndex, val); } Worker(CkMigrateMessage* msg) {} void barrier() { contribute (CkCallback(CkReductionTarget(Worker, barrierH), workerarray)); t = CthSelf(); CthSuspend(); } void barrierH() { CthAwaken(t); } void run() { for (int i = 0 ; i < numelements; i++) { if(thisIndex % 2 == 0 && thisIndex != numelements -1 ) { myMsg* m = workerarray[thisIndex + 1].sendSmaller(val); val = m->val; delete m; } barrier(); if (thisIndex % 2 == 1 && thisIndex != numelements -1 ) { myMsg* m = workerarray[thisIndex + 1].sendSmaller(val); val = m->val; delete m; } barrier(); } contribute(CkCallback(CkIndex_Main::done(NULL), mainproxy)); } myMsg* sendSmaller(int leftVal) { myMsg* msg = new myMsg(); if(leftVal > val) { msg->val = val; val = leftVal; } else { msg->val = leftVal; } return msg; } }; #include"oddEven.def.h"
Java
UTF-8
25,912
1.898438
2
[ "Apache-2.0" ]
permissive
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.glaf.core.util; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.jar.JarEntry; import java.util.jar.JarOutputStream; import java.util.zip.DataFormatException; import java.util.zip.Deflater; import java.util.zip.Inflater; import java.util.zip.ZipEntry; import java.util.zip.ZipInputStream; import java.util.zip.ZipOutputStream; import org.apache.commons.io.IOUtils; import org.apache.commons.lang3.StringUtils; import org.apache.commons.compress.archivers.ArchiveEntry; import org.apache.commons.compress.archivers.zip.Zip64Mode; import org.apache.commons.compress.archivers.zip.ZipArchiveEntry; import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream; import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.glaf.core.config.BaseConfiguration; import com.glaf.core.config.Configuration; public class ZipUtils { private static final Logger logger = LoggerFactory.getLogger(ZipUtils.class); protected static Configuration conf = BaseConfiguration.create(); private static String sp = System.getProperty("file.separator"); private static byte buf[] = new byte[256]; private static int len; private static int BUFFER = 8192; public static byte[] compress(byte[] data) throws IOException { long startTime = System.currentTimeMillis(); Deflater deflater = new Deflater(1); deflater.setInput(data); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length); deflater.finish(); byte[] buffer = new byte[1024]; while (!deflater.finished()) { int count = deflater.deflate(buffer); // returns the generated code... index outputStream.write(buffer, 0, count); } outputStream.close(); byte[] output = outputStream.toByteArray(); logger.debug("Original: " + data.length + " bytes. " + "Compressed: " + output.length + " byte. Time: " + (System.currentTimeMillis() - startTime)); return output; } private static void compressDirectoryToZipfile(String rootDir, String sourceDir, ZipOutputStream out) throws IOException { File[] files = new File(sourceDir).listFiles(); if (files == null) return; for (File sourceFile : files) { if (sourceFile.isDirectory()) { compressDirectoryToZipfile(rootDir, sourceDir + normDir(sourceFile.getName()), out); } else { ZipEntry entry = new ZipEntry( normDir(StringUtils.isEmpty(rootDir) ? sourceDir : sourceDir.replace(rootDir, "")) + sourceFile.getName()); entry.setTime(sourceFile.lastModified()); out.putNextEntry(entry); FileInputStream in = new FileInputStream(sourceDir + sourceFile.getName()); try { IOUtils.copy(in, out); } finally { com.glaf.core.util.IOUtils.closeStream(in); } } } } /** * * 把文件压缩成zip格式 * * @param files * 需要压缩的文件 * * @param zipFilePath * 压缩后的zip文件路径 ,如"/var/data/aa.zip"; */ public static void compressFile(File[] files, String zipFilePath) { if (files != null && files.length > 0) { if (isEndsWithZip(zipFilePath)) { ZipArchiveOutputStream zaos = null; try { File zipFile = new File(zipFilePath); zaos = new ZipArchiveOutputStream(zipFile); // Use Zip64 extensions for all entries where they are // required zaos.setUseZip64(Zip64Mode.AsNeeded); for (File file : files) { if (file != null) { ZipArchiveEntry zipArchiveEntry = new ZipArchiveEntry(file, file.getName()); zaos.putArchiveEntry(zipArchiveEntry); InputStream is = null; try { is = new BufferedInputStream(new FileInputStream(file)); byte[] buffer = new byte[BUFFER]; int len = -1; while ((len = is.read(buffer)) != -1) { zaos.write(buffer, 0, len); } // Writes all necessary data for this entry. zaos.closeArchiveEntry(); } catch (Exception e) { throw new RuntimeException(e); } finally { com.glaf.core.util.IOUtils.closeStream(is); } } } zaos.finish(); } catch (Exception e) { throw new RuntimeException(e); } finally { com.glaf.core.util.IOUtils.closeStream(zaos); } } } } public static void compressZipFile(String sourceDir, String zipFilename) throws IOException { if (!validateZipFilename(zipFilename)) { throw new RuntimeException("Zipfile must end with .zip"); } ZipOutputStream zipFile = null; try { zipFile = new ZipOutputStream(new FileOutputStream(zipFilename)); compressDirectoryToZipfile(normDir(new File(sourceDir).getParent()), normDir(sourceDir), zipFile); } finally { com.glaf.core.util.IOUtils.closeStream(zipFile); } } public static String convertEncoding(String s) { String s1 = s; try { s1 = new String(s.getBytes("UTF-8"), "GBK"); } catch (Exception exception) { } return s1; } public static byte[] decompress(byte[] data) throws IOException, DataFormatException { long startTime = System.currentTimeMillis(); Inflater inflater = new Inflater(); inflater.setInput(data); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length); byte[] buffer = new byte[1024]; while (!inflater.finished()) { int count = inflater.inflate(buffer); outputStream.write(buffer, 0, count); } outputStream.close(); byte[] output = outputStream.toByteArray(); logger.debug("Original: " + data.length + " bytes. " + "Decompressed: " + output.length + " bytes. Time: " + (System.currentTimeMillis() - startTime)); return output; } /** * * 把zip文件解压到指定的文件夹 * * @param zipFilePath * zip文件路径, 如 "/var/data/aa.zip" * * @param saveFileDir * 解压后的文件存放路径, 如"/var/test/" */ public static void decompressZip(String zipFilePath, String saveFileDir) { if (isEndsWithZip(zipFilePath)) { File file = new File(zipFilePath); if (file.exists() && file.isFile()) { InputStream inputStream = null; ZipArchiveInputStream zais = null; try { inputStream = new FileInputStream(file); zais = new ZipArchiveInputStream(inputStream); ArchiveEntry archiveEntry = null; while ((archiveEntry = zais.getNextEntry()) != null) { String entryFileName = archiveEntry.getName(); String entryFilePath = saveFileDir + entryFileName; byte[] content = new byte[(int) archiveEntry.getSize()]; zais.read(content); OutputStream os = null; try { File entryFile = new File(entryFilePath); os = new BufferedOutputStream(new FileOutputStream(entryFile)); os.write(content); } catch (IOException e) { throw new IOException(e); } finally { com.glaf.core.util.IOUtils.closeStream(os); } } } catch (Exception e) { throw new RuntimeException(e); } finally { com.glaf.core.util.IOUtils.closeStream(zais); com.glaf.core.util.IOUtils.closeStream(inputStream); } } } } public static void decompressZipfileToDirectory(String zipFileName, File outputFolder) throws IOException { ZipInputStream zipInputStream = null; try { zipInputStream = new ZipInputStream(new FileInputStream(zipFileName)); ZipEntry zipEntry = null; while ((zipEntry = zipInputStream.getNextEntry()) != null) { logger.info("decompressing " + zipEntry.getName() + " is directory:" + zipEntry.isDirectory() + " available: " + zipInputStream.available()); File temp = new File(outputFolder, zipEntry.getName()); if (zipEntry.isDirectory()) { temp.mkdirs(); } else { temp.getParentFile().mkdirs(); temp.createNewFile(); temp.setLastModified(zipEntry.getTime()); FileOutputStream outputStream = new FileOutputStream(temp); try { IOUtils.copy(zipInputStream, outputStream); } finally { com.glaf.core.util.IOUtils.closeStream(outputStream); } } } } finally { com.glaf.core.util.IOUtils.closeStream(zipInputStream); } } public static byte[] genZipBytes(Map<String, byte[]> dataMap) { byte[] bytes = null; byte[] data = null; ByteArrayInputStream bais = null; ByteArrayOutputStream baos = null; BufferedOutputStream bos = null; JarOutputStream jos = null; try { baos = new ByteArrayOutputStream(); bos = new BufferedOutputStream(baos); jos = new JarOutputStream(bos); if (dataMap != null) { Set<Entry<String, byte[]>> entrySet = dataMap.entrySet(); for (Entry<String, byte[]> entry : entrySet) { String name = entry.getKey(); data = entry.getValue(); if (name != null && data != null) { bais = new ByteArrayInputStream(data); BufferedInputStream bis = new BufferedInputStream(bais); JarEntry jarEntry = new JarEntry(name); jos.putNextEntry(jarEntry); while ((len = bis.read(buf)) >= 0) { jos.write(buf, 0, len); } bis.close(); jos.closeEntry(); } } } jos.flush(); com.glaf.core.util.IOUtils.closeStream(jos); bos.flush(); com.glaf.core.util.IOUtils.closeStream(bos); bytes = baos.toByteArray(); com.glaf.core.util.IOUtils.closeStream(bais); com.glaf.core.util.IOUtils.closeStream(baos); return bytes; } catch (Exception ex) { throw new RuntimeException(ex); } finally { data = null; com.glaf.core.util.IOUtils.closeStream(jos); com.glaf.core.util.IOUtils.closeStream(bos); com.glaf.core.util.IOUtils.closeStream(bais); com.glaf.core.util.IOUtils.closeStream(baos); } } public static byte[] getBytes(byte[] bytes, String name) { InputStream inputStream = null; try { inputStream = new ByteArrayInputStream(bytes); return getBytes(inputStream, name); } catch (Exception ex) { throw new RuntimeException(ex); } finally { com.glaf.core.util.IOUtils.closeStream(inputStream); } } public static byte[] getBytes(InputStream inputStream, String name) { byte[] bytes = null; ZipInputStream zipInputStream = null; try { zipInputStream = new ZipInputStream(inputStream); ZipEntry zipEntry = zipInputStream.getNextEntry(); while (zipEntry != null) { String entryName = zipEntry.getName(); if (entryName.equalsIgnoreCase(name)) { bytes = FileUtils.getBytes(zipInputStream); if (bytes != null) { break; } } zipEntry = zipInputStream.getNextEntry(); } return bytes; } catch (Exception ex) { throw new RuntimeException(ex); } finally { com.glaf.core.util.IOUtils.closeStream(zipInputStream); } } public static byte[] getBytes(ZipInputStream zipInputStream, String name) { byte[] bytes = null; try { ZipEntry zipEntry = zipInputStream.getNextEntry(); while (zipEntry != null) { String entryName = zipEntry.getName(); if (entryName.equalsIgnoreCase(name)) { bytes = FileUtils.getBytes(zipInputStream); if (bytes != null) { break; } } zipEntry = zipInputStream.getNextEntry(); } return bytes; } catch (Exception ex) { throw new RuntimeException(ex); } } public static byte[] getZipBytes(Map<String, InputStream> dataMap) { byte[] bytes = null; ByteArrayOutputStream baos = null; BufferedOutputStream bos = null; JarOutputStream jos = null; try { baos = new ByteArrayOutputStream(); bos = new BufferedOutputStream(baos); jos = new JarOutputStream(bos); if (dataMap != null) { Set<Entry<String, InputStream>> entrySet = dataMap.entrySet(); for (Entry<String, InputStream> entry : entrySet) { String name = entry.getKey(); InputStream inputStream = entry.getValue(); if (name != null && inputStream != null) { BufferedInputStream bis = new BufferedInputStream(inputStream); JarEntry jarEntry = new JarEntry(name); jos.putNextEntry(jarEntry); while ((len = bis.read(buf)) >= 0) { jos.write(buf, 0, len); } bis.close(); jos.closeEntry(); } } } jos.flush(); com.glaf.core.util.IOUtils.closeStream(jos); bos.flush(); com.glaf.core.util.IOUtils.closeStream(bos); bytes = baos.toByteArray(); com.glaf.core.util.IOUtils.closeStream(baos); return bytes; } catch (Exception ex) { throw new RuntimeException(ex); } finally { com.glaf.core.util.IOUtils.closeStream(jos); com.glaf.core.util.IOUtils.closeStream(bos); com.glaf.core.util.IOUtils.closeStream(baos); } } public static Map<String, byte[]> getZipBytesMap(ZipInputStream zipInputStream) { Map<String, byte[]> zipMap = new java.util.HashMap<String, byte[]>(); java.util.zip.ZipEntry zipEntry = null; ByteArrayOutputStream baos = null; BufferedOutputStream bos = null; byte tmpByte[] = null; try { while ((zipEntry = zipInputStream.getNextEntry()) != null) { tmpByte = new byte[BUFFER]; baos = new ByteArrayOutputStream(); bos = new BufferedOutputStream(baos, BUFFER); int i = 0; while ((i = zipInputStream.read(tmpByte, 0, BUFFER)) != -1) { bos.write(tmpByte, 0, i); } bos.flush(); byte[] bytes = baos.toByteArray(); com.glaf.core.util.IOUtils.closeStream(baos); com.glaf.core.util.IOUtils.closeStream(baos); zipMap.put(zipEntry.getName(), bytes); } } catch (Exception ex) { throw new RuntimeException(ex); } finally { com.glaf.core.util.IOUtils.closeStream(baos); com.glaf.core.util.IOUtils.closeStream(baos); } return zipMap; } public static Map<String, byte[]> getZipBytesMap(ZipInputStream zipInputStream, List<String> includes) { Map<String, byte[]> zipMap = new java.util.HashMap<String, byte[]>(); java.util.zip.ZipEntry zipEntry = null; ByteArrayOutputStream baos = null; BufferedOutputStream bos = null; byte tmpByte[] = null; try { while ((zipEntry = zipInputStream.getNextEntry()) != null) { String name = zipEntry.getName(); String ext = FileUtils.getFileExt(name); if (includes.contains(ext) || includes.contains(ext.toLowerCase())) { tmpByte = new byte[BUFFER]; baos = new ByteArrayOutputStream(); bos = new BufferedOutputStream(baos, BUFFER); int i = 0; while ((i = zipInputStream.read(tmpByte, 0, BUFFER)) != -1) { bos.write(tmpByte, 0, i); } bos.flush(); byte[] bytes = baos.toByteArray(); com.glaf.core.util.IOUtils.closeStream(baos); com.glaf.core.util.IOUtils.closeStream(baos); zipMap.put(zipEntry.getName(), bytes); } } } catch (Exception ex) { throw new RuntimeException(ex); } finally { com.glaf.core.util.IOUtils.closeStream(baos); com.glaf.core.util.IOUtils.closeStream(baos); } return zipMap; } /** * * 判断文件名是否以.zip为后缀 * * @param fileName * 需要判断的文件名 * * @return */ public static boolean isEndsWithZip(String fileName) { boolean flag = false; if (fileName != null && !"".equals(fileName.trim())) { if (fileName.toLowerCase().endsWith(".zip")) { flag = true; } } return flag; } public static void makeZip(File dir, File zipFile) throws IOException, FileNotFoundException { JarOutputStream jos = new JarOutputStream(new FileOutputStream(zipFile)); String as[] = dir.list(); if (as != null) { for (int i = 0; i < as.length; i++) recurseFiles(jos, new File(dir, as[i]), ""); } jos.close(); } private static String normDir(String dirName) { if (!StringUtils.isEmpty(dirName) && !dirName.endsWith(File.separator)) { dirName = dirName + File.separator; } return dirName; } private static void recurseFiles(JarOutputStream jos, File file, String s) throws IOException, FileNotFoundException { if (file.isDirectory()) { s = s + file.getName() + "/"; jos.putNextEntry(new JarEntry(s)); String as[] = file.list(); if (as != null) { for (int i = 0; i < as.length; i++) recurseFiles(jos, new File(file, as[i]), s); } } else { if (file.getName().endsWith("MANIFEST.MF") || file.getName().endsWith("META-INF/MANIFEST.MF")) { return; } JarEntry jarentry = new JarEntry(s + file.getName()); FileInputStream fileinputstream = new FileInputStream(file); BufferedInputStream bufferedinputstream = new BufferedInputStream(fileinputstream); jos.putNextEntry(jarentry); while ((len = bufferedinputstream.read(buf)) >= 0) { jos.write(buf, 0, len); } bufferedinputstream.close(); jos.closeEntry(); } } public static byte[] toZipBytes(Map<String, byte[]> zipMap) { byte[] bytes = null; InputStream inputStream = null; BufferedInputStream bis = null; ByteArrayOutputStream baos = null; BufferedOutputStream bos = null; JarOutputStream jos = null; try { baos = new ByteArrayOutputStream(); bos = new BufferedOutputStream(baos); jos = new JarOutputStream(bos); if (zipMap != null) { Set<Entry<String, byte[]>> entrySet = zipMap.entrySet(); for (Entry<String, byte[]> entry : entrySet) { String name = entry.getKey(); byte[] x_bytes = entry.getValue(); inputStream = new ByteArrayInputStream(x_bytes); if (name != null && inputStream != null) { bis = new BufferedInputStream(inputStream); JarEntry jarEntry = new JarEntry(name); jos.putNextEntry(jarEntry); while ((len = bis.read(buf)) >= 0) { jos.write(buf, 0, len); } com.glaf.core.util.IOUtils.closeStream(bis); jos.closeEntry(); } com.glaf.core.util.IOUtils.closeStream(inputStream); } } jos.flush(); jos.close(); bytes = baos.toByteArray(); com.glaf.core.util.IOUtils.closeStream(baos); com.glaf.core.util.IOUtils.closeStream(bos); return bytes; } catch (Exception ex) { throw new RuntimeException(ex); } finally { com.glaf.core.util.IOUtils.closeStream(inputStream); com.glaf.core.util.IOUtils.closeStream(baos); com.glaf.core.util.IOUtils.closeStream(bos); } } public static void unzip(File zipFile) { FileInputStream fileInputStream = null; ZipInputStream zipInputStream = null; FileOutputStream fileoutputstream = null; BufferedOutputStream bufferedoutputstream = null; try { fileInputStream = new FileInputStream(zipFile); zipInputStream = new ZipInputStream(fileInputStream); java.util.zip.ZipEntry zipEntry; while ((zipEntry = zipInputStream.getNextEntry()) != null) { byte abyte0[] = new byte[BUFFER]; fileoutputstream = new FileOutputStream(zipEntry.getName()); bufferedoutputstream = new BufferedOutputStream(fileoutputstream, BUFFER); int i; while ((i = zipInputStream.read(abyte0, 0, BUFFER)) != -1) { bufferedoutputstream.write(abyte0, 0, i); } bufferedoutputstream.flush(); com.glaf.core.util.IOUtils.closeStream(fileoutputstream); com.glaf.core.util.IOUtils.closeStream(bufferedoutputstream); } } catch (Exception ex) { throw new RuntimeException(ex); } finally { com.glaf.core.util.IOUtils.closeStream(fileInputStream); com.glaf.core.util.IOUtils.closeStream(zipInputStream); com.glaf.core.util.IOUtils.closeStream(fileoutputstream); com.glaf.core.util.IOUtils.closeStream(bufferedoutputstream); } } public static void unzip(File zipFile, String dir) throws Exception { File file = new File(dir); FileUtils.mkdirsWithExistsCheck(file); FileInputStream fileInputStream = null; ZipInputStream zipInputStream = null; FileOutputStream fileoutputstream = null; BufferedOutputStream bufferedoutputstream = null; try { fileInputStream = new FileInputStream(zipFile); zipInputStream = new ZipInputStream(fileInputStream); fileInputStream = new FileInputStream(zipFile); zipInputStream = new ZipInputStream(fileInputStream); java.util.zip.ZipEntry zipEntry; while ((zipEntry = zipInputStream.getNextEntry()) != null) { boolean isDirectory = zipEntry.isDirectory(); byte abyte0[] = new byte[BUFFER]; String s1 = zipEntry.getName(); s1 = convertEncoding(s1); String s2 = dir + "/" + s1; s2 = FileUtils.getJavaFileSystemPath(s2); if (s2.indexOf('/') != -1 || isDirectory) { String s4 = s2.substring(0, s2.lastIndexOf('/')); File file2 = new File(s4); FileUtils.mkdirsWithExistsCheck(file2); } if (isDirectory) { continue; } fileoutputstream = new FileOutputStream(s2); bufferedoutputstream = new BufferedOutputStream(fileoutputstream, BUFFER); int i = 0; while ((i = zipInputStream.read(abyte0, 0, BUFFER)) != -1) { bufferedoutputstream.write(abyte0, 0, i); } bufferedoutputstream.flush(); com.glaf.core.util.IOUtils.closeStream(fileoutputstream); com.glaf.core.util.IOUtils.closeStream(bufferedoutputstream); } } catch (Exception ex) { throw new RuntimeException(ex); } finally { com.glaf.core.util.IOUtils.closeStream(fileInputStream); com.glaf.core.util.IOUtils.closeStream(zipInputStream); com.glaf.core.util.IOUtils.closeStream(fileoutputstream); com.glaf.core.util.IOUtils.closeStream(bufferedoutputstream); } } public static void unzip(java.io.InputStream inputStream, String dir) throws Exception { File file = new File(dir); FileUtils.mkdirsWithExistsCheck(file); ZipInputStream zipInputStream = null; FileOutputStream fileoutputstream = null; BufferedOutputStream bufferedoutputstream = null; try { zipInputStream = new ZipInputStream(inputStream); java.util.zip.ZipEntry zipEntry; while ((zipEntry = zipInputStream.getNextEntry()) != null) { boolean isDirectory = zipEntry.isDirectory(); byte abyte0[] = new byte[BUFFER]; String s1 = zipEntry.getName(); s1 = convertEncoding(s1); String s2 = dir + sp + s1; s2 = FileUtils.getJavaFileSystemPath(s2); if (s2.indexOf('/') != -1 || isDirectory) { String s4 = s2.substring(0, s2.lastIndexOf('/')); File file2 = new File(s4); FileUtils.mkdirsWithExistsCheck(file2); } if (isDirectory) { continue; } fileoutputstream = new FileOutputStream(s2); bufferedoutputstream = new BufferedOutputStream(fileoutputstream, BUFFER); int i = 0; while ((i = zipInputStream.read(abyte0, 0, BUFFER)) != -1) { bufferedoutputstream.write(abyte0, 0, i); } bufferedoutputstream.flush(); com.glaf.core.util.IOUtils.closeStream(fileoutputstream); com.glaf.core.util.IOUtils.closeStream(bufferedoutputstream); } } catch (Exception ex) { throw new RuntimeException(ex); } finally { com.glaf.core.util.IOUtils.closeStream(zipInputStream); com.glaf.core.util.IOUtils.closeStream(fileoutputstream); com.glaf.core.util.IOUtils.closeStream(bufferedoutputstream); } } public static void unzip(java.io.InputStream inputStream, String path, List<String> excludes) throws Exception { File file = new File(path); FileUtils.mkdirsWithExistsCheck(file); ZipInputStream zipInputStream = null; FileOutputStream fileoutputstream = null; BufferedOutputStream bufferedoutputstream = null; try { zipInputStream = new ZipInputStream(inputStream); java.util.zip.ZipEntry zipEntry; while ((zipEntry = zipInputStream.getNextEntry()) != null) { boolean isDirectory = zipEntry.isDirectory(); byte abyte0[] = new byte[BUFFER]; String s1 = zipEntry.getName(); String ext = FileUtils.getFileExt(s1); if (excludes.contains(ext) || excludes.contains(ext.toLowerCase())) { continue; } s1 = convertEncoding(s1); String s2 = path + sp + s1; s2 = FileUtils.getJavaFileSystemPath(s2); if (s2.indexOf('/') != -1 || isDirectory) { String s4 = s2.substring(0, s2.lastIndexOf('/')); File file2 = new File(s4); FileUtils.mkdirsWithExistsCheck(file2); } if (isDirectory) { continue; } fileoutputstream = new FileOutputStream(s2); bufferedoutputstream = new BufferedOutputStream(fileoutputstream, BUFFER); int i = 0; while ((i = zipInputStream.read(abyte0, 0, BUFFER)) != -1) { bufferedoutputstream.write(abyte0, 0, i); } bufferedoutputstream.flush(); com.glaf.core.util.IOUtils.closeStream(fileoutputstream); com.glaf.core.util.IOUtils.closeStream(bufferedoutputstream); } } catch (Exception ex) { throw new RuntimeException(ex); } finally { com.glaf.core.util.IOUtils.closeStream(zipInputStream); com.glaf.core.util.IOUtils.closeStream(fileoutputstream); com.glaf.core.util.IOUtils.closeStream(bufferedoutputstream); } } private static boolean validateZipFilename(String filename) { if (!StringUtils.isEmpty(filename) && filename.trim().toLowerCase().endsWith(".zip")) { return true; } return false; } private ZipUtils() { } }
SQL
UTF-8
177
2.890625
3
[]
no_license
SELECT Citizenship, Alignment, COUNT(*) AS `Frequency` FROM Heros WHERE Citizenship != "" AND Alignment != "" GROUP BY Citizenship, Alignment ORDER BY Frequency DESC
Java
UTF-8
4,927
3.109375
3
[ "Apache-2.0" ]
permissive
package lang.celadon; import squidpony.squidmath.CrossHash; import java.util.Objects; /** * Indirection cell; has a name that may be used to look it up, and any Object for a value. * Created by Tommy Ettinger on 8/20/2017. */ public class Cel { public String title; public Object ref; public Cel() { title = null; ref = null; } public Cel(Object ref) { this.title = (ref == null) ? "null" : ref.toString(); this.ref = ref; } public Cel(String title, Object ref) { this.title = title; this.ref = ref; } public static boolean isNumeric(Cel o) { return o != null && o.ref != null && ((o.ref instanceof Number) || (o.ref instanceof Boolean)); } public static boolean isFloating(Cel o) { return o != null && o.ref != null && ((o.ref instanceof Double) || (o.ref instanceof Float)); } @Override public String toString() { if(ref == null) return title == null ? "null" : title + " = UNBOUND"; if(ref instanceof Syntax) { switch ((Syntax)ref) { case SYMBOL: return title; case GAP: return ":"; case NOW: return "@"; case ACCESS: return "."; case EMPTY: return "()"; case OPEN_PARENTHESIS: return "("; case CLOSE_PARENTHESIS: return ")"; case OPEN_BRACKET: return "["; case CLOSE_BRACKET: return "]"; case OPEN_BRACE: return "{"; case CLOSE_BRACE: return "}"; } } if(ref instanceof CharSequence) return "'" + ref + "'"; if(ref instanceof Character) return "`" + ref + "`"; if(ref instanceof Procedural) return title; return ref.toString(); } @Override public boolean equals(Object o) { if (this == o) return true; if(ref != null) { if (o == null) return false; if (getClass() == o.getClass()) { Cel item = (Cel) o; return ref.equals(item.ref); } else return ref.getClass() == o.getClass() && ref.equals(o); } else return o == null || (o.getClass() == getClass() && ((Cel)o).ref == null); } @Override public int hashCode() { return ref != null ? ref.hashCode() : 0; } public static class HasherByName implements CrossHash.IHasher { @Override public int hash(Object data) { return data == null || !(data instanceof Cel) ? 0 : CrossHash.hash(((Cel)data).title); } @Override public boolean areEqual(Object left, Object right) { return Objects.equals(left, right); } } public static final Cel openParenthesis = new Cel("(", Syntax.OPEN_PARENTHESIS); public static final Cel openBrace = new Cel("{", Syntax.OPEN_BRACE); public static final Cel openBracket = new Cel("[", Syntax.OPEN_BRACKET); public static final Cel closeParenthesis = new Cel(")", Syntax.CLOSE_PARENTHESIS); public static final Cel closeBrace = new Cel("}", Syntax.CLOSE_BRACE); public static final Cel closeBracket = new Cel("]", Syntax.CLOSE_BRACKET); public static final Cel gap = new Cel(":", Syntax.GAP); public static final Cel now = new Cel("@", Syntax.NOW); public static final Cel access = new Cel(".", Syntax.ACCESS); public static final Cel empty = new Cel("()", Syntax.EMPTY); public static final Cel backslash = new Cel("`\\\\`", '\\'); public static final Cel carriageReturn = new Cel("`\\\r`", '\r'); public static final Cel newline = new Cel("`\\\n`", '\n'); public static final Cel tab = new Cel("`\\\t`", '\t'); public static final Cel doubleQuote = new Cel("`\"`", '"'); public static final Cel singleQuote = new Cel("`'`", '\''); public static final Cel backspace = new Cel("`\\\b`", '\b'); public static final Cel formfeed = new Cel("`\\\f`", '\f'); public static final Cel backtick = new Cel("```", '`'); public static final Cel nul = new Cel("`\\\0`", '\0'); public static final Cel yes = new Cel("true", true); public static final Cel no = new Cel("false", false); public static final Cel nothing = new Cel("null", null); public static final Cel zeroFloat = new Cel("0.0f", 0.0f); public static final Cel zeroDouble = new Cel("0.0", 0.0); public static final Cel zeroInt = new Cel("0", 0); public static final Cel zeroLong = new Cel("0L", 0L); // public static final Cel split = new Cel(";", Syntax.SPLIT); // public static final Cel comma = new Cel(",", Syntax.COMMA); // public static final Cel evalLess = new Cel(":", Syntax.EVAL_LESS); // public static final Cel evalMore = new Cel("@", Syntax.EVAL_MORE); }
JavaScript
UTF-8
1,244
2.578125
3
[]
no_license
const Todo = require('../models/todo'); const todoController = {}; // to show all todo items todoController.index = function (req, res) { Todo.findAll() .then(function(todos) { res.render('todo/index', { message: 'ok', data: todos, }); }).catch(function(err){ console.log(err); res.status(500).json(err); }) }; // to show one todo item todoController.show = function (req, res) { Todo.findById(req.params.id) .then(function(todos) { res.render('todo/todo_single', { message: 'ok', data: todos, }); }).catch(function(err){ console.log(err); res.status(500).json(err); }) }; // to create one todo item todoController.create = function (req, res){ Todo.create({ title: req.body.title, category: req.body.category, status: req.body.status, }).then(function(todo){ res.redirect('/todo'); }).catch(function (err){ console.log(err); res.status(500).json(err); }); }; // to delete one todo item. todoController.delete = function (req, res){ Todo.destroy(req.params.id) .then(function () { res.redirect('/todo'); }).catch(err => { console.log(err); res.status(500).json(err); }); } module.exports = todoController;
Markdown
UTF-8
1,150
2.96875
3
[]
no_license
# tictactoe-console C++ Console Tictactoe Xây dựng game cờ caro với những chức năng cơ bản trên giao diện Console. Luật chơi: Hai bên lần lượt thay phiên nhau đặt những nước đi bằng các dấu X, O trên bàn cờ. Bên nào có năm quân liền nhau mà không có quân khác chặn liền hai đầu trên một trong các hàng dọc, hàng ngang hay đường chéo là giành chiến thắng. Một số yêu cầu cụ thể của game: - Giúp đỡ ( Help): Hiển thị thông tin hướng dẫn cách chơi và luật chơi. - Tùy chọn (Options): Thay đổi các thông số của game, lựa chọn chế độ chơi và chọn ra quân trước. - Game mới (New Game): Bắt đầu ván chơi với các thông số đã đặt. - Lưu game (Save Game): Cho phép lưu lại ván cờ đang chơi, lượt đánh tiếp theo ( O hay X). - Tải game (Load Game): Cho phép tải lại ván cờ đã lưu để chơi tiếp. - Thông tin (About): Cho phép hiển thị thông tin của nhóm tác giả, phiên bản trò chơi. - Thoát (Exit): Thoát khỏi chương trình.
Java
UTF-8
3,574
1.867188
2
[ "Apache-2.0" ]
permissive
package sk.henrichg.phoneprofilesplus; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.nfc.NfcAdapter; public class NFCStateChangedBroadcastReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // PPApplicationStatic.logE("[IN_BROADCAST] NFCStateChangedBroadcastReceiver.onReceive", "xxx"); if (!PPApplicationStatic.getApplicationStarted(true, true)) // application is not started return; if (EventStatic.getGlobalEventsRunning(context)) { final String action = intent.getAction(); if ((action != null) && action.equals(NfcAdapter.ACTION_ADAPTER_STATE_CHANGED)) { final int state = intent.getIntExtra(NfcAdapter.EXTRA_ADAPTER_STATE, NfcAdapter.STATE_OFF); if ((state == NfcAdapter.STATE_ON) || (state == NfcAdapter.STATE_OFF)) { final Context appContext = context.getApplicationContext(); PPExecutors.handleEvents(appContext, EventsHandler.SENSOR_TYPE_RADIO_SWITCH, "SENSOR_TYPE_RADIO_SWITCH", 0); /* PPApplication.startHandlerThreadBroadcast(); final Handler __handler = new Handler(PPApplication.handlerThreadBroadcast.getLooper()); //__handler.post(new PPApplication.PPHandlerThreadRunnable( // context.getApplicationContext()) { __handler.post(() -> { // PPApplicationStatic.logE("[IN_THREAD_HANDLER] PPApplication.startHandlerThread", "START run - from=NFCStateChangedBroadcastReceiver.onReceive"); //Context appContext= appContextWeakRef.get(); //if (appContext != null) { PowerManager powerManager = (PowerManager) appContext.getSystemService(Context.POWER_SERVICE); PowerManager.WakeLock wakeLock = null; try { if (powerManager != null) { wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, PPApplication.PACKAGE_NAME + ":NFCStateChangedBroadcastReceiver_onReceive"); wakeLock.acquire(10 * 60 * 1000); } // PPApplicationStatic.logE("[EVENTS_HANDLER_CALL] NFCStateChangedBroadcastReceiver.onReceive", "sensorType=SENSOR_TYPE_RADIO_SWITCH"); EventsHandler eventsHandler = new EventsHandler(appContext); eventsHandler.handleEvents(EventsHandler.SENSOR_TYPE_RADIO_SWITCH); } catch (Exception e) { // PPApplicationStatic.logE("[IN_THREAD_HANDLER] PPApplication.startHandlerThread", Log.getStackTraceString(e)); PPApplicationStatic.recordException(e); } finally { if ((wakeLock != null) && wakeLock.isHeld()) { try { wakeLock.release(); } catch (Exception ignored) { } } } //} }); */ } } } } }
JavaScript
UTF-8
915
2.640625
3
[]
no_license
$(document).ready(function(){ $("#form").on('submit', function(event){ var text = $("#content").val(); event.preventDefault(); $(".list").prepend( '<div class="tweet">' +'<div class="cross">' +'<a href="#" class="remove"><span class="glyphicon glyphicon-remove"></span></a>' +'</div>' +'<div class="heart">' +'<a class="likeable" href="#"><span class="glyphicon glyphicon-heart"></span></a>' +'<span id="counter">0</span>' +'</div>' + text +'</div>' +'</div>') $("#content").val(''); $("#content").focus(); }); $('.list').on('click', '.remove', function(event){ $(this).parent().parent().fadeOut(500); event.preventDefault(); }) $('.list').on('click', '.likeable', function(event){ $(this).find('.glyphicon').css('color', '#F7819F'); event.preventDefault(); $(this).parent().find('#counter').html(function(i, val){ return val * 1 + 1 }); }); })
Markdown
UTF-8
1,995
2.609375
3
[ "MIT" ]
permissive
'openEyeTrack - An open source high-speed eyetracker'. https://open-neuroscience.com/post/openeyetrack_an_open_source_high_speed_eyetracker/ Vision is one of the primary senses, and tracking eye gaze can offer insight into the cue #Software#Hardware#Behaviour#Computers ... s that affect decision-making behavior. Thus, to study decision-making and other cognitive processes, it is fundamentally necessary to track eye position accurately. However, commercial eye trackers are 1) often very expensive, and 2) incorporate proprietary software to... detect the movement of the eye. Closed source solutions limit the researcher’s ability to be fully informed regarding the algorithms used to track the eye and to incorporate modifications tailored to their needs. Here, we present our software solution, openEyeTrack, a ... low-cost, high-speed, low-latency, open-source video-based eye tracker. Video-based eye trackers can perform nearly as well as classical scleral search coil methods and are suitable for most applications.openEyeTrack is a video-based eye-tracker that takes advantage of ... OpenCV, a low-cost, high-speed infrared camera and GigE-V APIs for Linux provided by Teledyne DALSA, the graphical user interface toolkit QT5 and cvui, the OpenCV based GUI. All of the software components are freely available. The only costs are from the hardware compon... ents such as the camera (Genie Nano M640 NIR, Teledyne DALSA, ~$450, ~730 frames per second) and infrared light source, an articulated arm to position the camera (Manfrotto: $130), a computer with one or more gigabit network interface cards, and a power over ethernet sw... itch to power and receive data from the camera.By using the GigE-V Framework to capture the frames from the DALSA camera and the OpenCV simple blob detector, openEyeTrack can accurately estimate the position and area of the pupil. We include pupil size calculations beca... use of its putative link to arousal levels and emotions of the subject....
Markdown
UTF-8
779
2.515625
3
[]
no_license
# FreshAir 🌬️ A simple React Native application integrating the [Breezeometer](https://breezometer.com/) api. ## Usage To run this app on your own machine (assuming macOS): _note: you must have cocoapods and npm installed on your machine to install FreshAir's dependencies_ ### Clone the Repo ``` $ git clone https://github.com/jordones/FreshAir.git ``` ### Swap the API Key I've included my test API key for the Breezometer API in `/src/services/AirQuality.js`, to use this app, sign up for [Breezeometer](https://breezometer.com/) and input your key here. _note: API keys should not be stored in production code in practice_ ### Install dependencies ``` $ cd FreshAir $ npm i $ cd ./ios $ pod install ``` ### Start the app ``` cd .. npx react-native run-ios ```
PHP
UTF-8
868
2.578125
3
[]
no_license
<?php namespace Landers\Wechat; /*二维码接口*/ class WechatQRCode { use WechatToken; /*实例化构造方法*/ function __construct($appid, $appsecret) { $this->appid = $appid; $this->appsecret = $appsecret; } public function getTicket($scene_id, $action_name = 'QR_LIMIT_SCENE', $expire_seconds = 0){ $url = '%s/cgi-bin/qrcode/create?access_token=%s'; $url = sprintf($url, self::$apihost, $this->getAccessToken()); $data = array( 'action_name' => $action_name, 'action_info' => array( 'scene' => array('scene_id' => $scene_id), ) ); if ( $expire_seconds && $action_name == 'QR_SCENE') { $opts['expire_seconds'] = $expire_seconds; } return WechatHelper::httpPost($url, json_encode($data)); } }
Rust
UTF-8
6,170
2.71875
3
[ "Apache-2.0", "MIT" ]
permissive
use alloc::Vec; use lcd::{HEIGHT, WIDTH}; use racket::RACKET_WIDTH; const BALL_MAX_SPEED: i16 = 20; const BALL_MIN_SPEED: i16 = 10; pub const STATE_RUNNING: u8 = 0; pub const STATE_WON_PLAYER_1: u8 = 100; pub const STATE_WON_PLAYER_2: u8 = 101; #[derive(Debug, Copy, Clone)] pub struct GamestatePacket { pub rackets: [RacketPacket; 2], pub ball: BallPacket, pub score: [u8; 2], pub state: u8, } #[derive(Debug, Copy, Clone)] pub struct RacketPacket { pub x: i16, // center_x pub y: i16, // center_y } #[derive(Debug, Copy, Clone)] pub struct BallPacket { pub x: i16, // center_x pub y: i16, // center_y pub x_vel: i16, pub y_vel: i16, } #[derive(Debug, Copy, Clone)] pub struct InputPacket { pub goal_y: i16, } #[derive(Debug, Copy, Clone)] pub struct WhoamiPacket { pub is_server: bool, } impl GamestatePacket { pub fn new(total_time: usize) -> GamestatePacket { let (vel_x, vel_y) = random_vel(total_time); GamestatePacket { rackets: [ RacketPacket { x: RACKET_WIDTH as i16, y: (HEIGHT / 2) as i16, }, RacketPacket { x: WIDTH as i16 - RACKET_WIDTH as i16, y: (HEIGHT / 2) as i16, }, ], ball: BallPacket { x: (WIDTH / 2) as i16, y: (HEIGHT / 2) as i16, x_vel: vel_x, y_vel: vel_y, }, score: [0, 0], state: 0, } } } impl BallPacket { pub fn reset(&mut self, total_time: usize) { let (vel_x, vel_y) = random_vel(total_time); self.x = (WIDTH / 2) as i16; self.y = (HEIGHT / 2) as i16; self.x_vel = vel_x; self.y_vel = vel_y; } } impl InputPacket { pub fn new() -> InputPacket { InputPacket { goal_y: 272 / 2 } } } impl WhoamiPacket { pub fn new(is_server: bool) -> WhoamiPacket { WhoamiPacket { is_server: is_server, } } } pub trait Serializable { fn serialize(&self) -> Vec<u8>; fn deserialize(input: &[u8]) -> Self; fn len() -> usize; } impl Serializable for GamestatePacket { fn serialize(&self) -> Vec<u8> { let mut result = Vec::new(); result.extend(self.rackets[0].serialize()); result.extend(self.rackets[1].serialize()); result.extend(self.ball.serialize()); result.push(self.score[0]); result.push(self.score[1]); result.push(self.state); result } fn deserialize(input: &[u8]) -> GamestatePacket { let mut index = 0; let racket1 = RacketPacket::deserialize(&input[index..index + RacketPacket::len()]); index += RacketPacket::len(); let racket2 = RacketPacket::deserialize(&input[index..index + RacketPacket::len()]); index += RacketPacket::len(); let ball = BallPacket::deserialize(&input[index..index + BallPacket::len()]); index += BallPacket::len(); let score_player1 = input[index]; let score_player2 = input[index + 1]; let state = input[index + 2]; GamestatePacket { rackets: [racket1, racket2], ball, score: [score_player1, score_player2], state: state, } } fn len() -> usize { 2 * RacketPacket::len() + BallPacket::len() + 2 + 1 } } impl Serializable for RacketPacket { fn serialize(&self) -> Vec<u8> { let mut result = Vec::new(); result.push(upper_byte(self.x)); result.push(lower_byte(self.x)); result.push(upper_byte(self.y)); result.push(lower_byte(self.y)); result } fn deserialize(input: &[u8]) -> RacketPacket { RacketPacket { x: merge(input[0], input[1]), y: merge(input[2], input[3]), } } fn len() -> usize { 4 } } impl Serializable for BallPacket { fn serialize(&self) -> Vec<u8> { let mut result = Vec::new(); result.push(upper_byte(self.x)); result.push(lower_byte(self.x)); result.push(upper_byte(self.y)); result.push(lower_byte(self.y)); result.push(upper_byte(self.x_vel)); result.push(lower_byte(self.x_vel)); result.push(upper_byte(self.y_vel)); result.push(lower_byte(self.y_vel)); result } fn deserialize(input: &[u8]) -> BallPacket { BallPacket { x: merge(input[0], input[1]), y: merge(input[2], input[3]), x_vel: merge(input[4], input[5]), y_vel: merge(input[6], input[7]), } } fn len() -> usize { 8 } } impl Serializable for InputPacket { fn serialize(&self) -> Vec<u8> { let mut result = Vec::new(); result.push(upper_byte(self.goal_y)); result.push(lower_byte(self.goal_y)); result } fn deserialize(input: &[u8]) -> InputPacket { InputPacket { goal_y: merge(input[0], input[1]), } } fn len() -> usize { 2 } } impl Serializable for WhoamiPacket { fn serialize(&self) -> Vec<u8> { if self.is_server { vec![255] } else { vec![0] } } fn deserialize(input: &[u8]) -> WhoamiPacket { WhoamiPacket { is_server: input[0] == 255, } } fn len() -> usize { 1 } } fn upper_byte(input: i16) -> u8 { ((input >> 8) & 0xff) as u8 } fn lower_byte(input: i16) -> u8 { (input & 0xff) as u8 } fn merge(upper: u8, lower: u8) -> i16 { i16::from(upper) << 8 | i16::from(lower) } const VELOCITIES: [(i16,i16); 16] = [ (-3,-3), (-3,3), (3,-3), (3,3), (-4,-2), (-4,2), (4,-2), (4,2), (-2,-4), (-2,4), (2,-4), (2,4), (-5,-1), (-5,1), (5,-1), (5,1), ]; // "random" :P https://xkcd.com/221/ fn random_vel(total_time: usize) -> (i16, i16) { let ran = (total_time as u8) % 16; // should work as 256 is dividable by 4 VELOCITIES[ran as usize] }
JavaScript
UTF-8
1,276
2.6875
3
[]
no_license
import React, { Component } from 'react'; class Counter extends Component { styles = { fontSize: 15, fontStyle: 'bold', } componentWillUnmount() { console.log('Counter - Unmount'); } renderTags() { const { tags } = this.state; if (!tags.length) return <p>There are no tags!</p>; return <ul>{this.state.tags.map((tag) => <li key={tag}>{tag}</li>)}</ul> } render() { console.log('Counter - Rendered'); return ( <div> {this.props.children} <span className={this.getBadgeClass()}>{this.formatCount()}</span> <button className="btn btn-primary btn-sm" onClick={this.props.onAdd.bind(this, this.props.counter)}>Increment</button> <button className="btn btn-danger btn-sm m-2" onClick={this.props.onDelete.bind(this, this.props.counter.id)}>Delete</button> </div> ); } getBadgeClass() { let classes = 'badge m-2 badge-'; classes += (this.props.counter.value === 0) ? 'warning' : 'primary'; return classes; } formatCount() { const { value } = this.props.counter; return value === 0 ? 'Zero' : value; } } export default Counter;
JavaScript
UTF-8
371
4.09375
4
[]
no_license
// const getRandomNumber = function (limit) { // let random = Math.random() * limit; // return Math.ceil(random) // } // console.log(getRandomNumber(100)); //Arrow Funtion = () => {} const getRandomNumber = limit => Math.ceil(Math.random() * limit); console.log(getRandomNumber(100)); //ES5 // function(arguments) { // } //ES6 // (arguments) => { // }
JavaScript
UTF-8
709
3.1875
3
[]
no_license
function setup() { createCanvas(windowWidth, windowHeight); frameRate(12); } function draw() { background(0, 25); rectMode(CENTER); // Red Rectangle: Translate then rotate push(); translate(width / 2, height / 2); // TODO: Translate to the center of canvas rotate(radians(frameCount)); // TODO: Rotate by frameCount noFill(); stroke(255, 0, 0); rect(0, 0, windowWidth, windowHeight); pop(); // Blue Rectangle: Rotate then translate push(); // TODO: Rotate by frameCount rotate(radians(frameCount)); // TODO: Translate to the center of canvas translate(width / 2, height / 2); noFill(); stroke(0, 0, 255); rect(0, 0, windowWidth, windowHeight); pop(); }
Markdown
UTF-8
1,229
4.03125
4
[]
no_license
## 700. Search in a Binary Search Tree ### Information * TIME: 2019/10/03 * LINK: [Click Here](https://leetcode-cn.com/problems/search-in-a-binary-search-tree/) * TAG: `BST` ### Description > 给定二叉搜索树(BST)的根节点和一个值。 你需要在BST中找到节点值等于给定值的节点。 返回以该节点为根的子树。 如果节点不存在,则返回 NULL。 ### Example ```text 给定二叉搜索树: 4 / \ 2 7 / \ 1 3 和值: 2 你应该返回如下子树: 2 / \ 1 3 在上述示例中,如果要找的值是 5,但因为没有节点值为 5,我们应该返回 NULL。 ``` ### My Answer > 迭代法求解 > * 查找值大于当前目的节点值,往右走 > * 否则往左 ```java /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ class Solution { public TreeNode searchBST(TreeNode root, int val) { TreeNode target = root; while(target!=null && target.val!=val){ target = (val>target.val)? target.right:target.left; } return target; } } ```
C++
UTF-8
1,984
3.03125
3
[]
no_license
/******************************************************************************* * Cristian Alexandrescu * * 2163013577ba2bc237f22b3f4d006856 * * 11a4bb2c77aca6a9927b85f259d9af10db791ce5cf884bb31e7f7a889d4fb385 * * bc9a53289baf23d369484f5343ed5d6c * *******************************************************************************/ /* Problem 11597 - Spanning Subtree */ /* n * (n - 1) / 2 is the number of edges of Kn, n - 1 is the number of edges in a subtree. Thus there can be at most n / 2 spanning trees. Proof: for n = 2, n = 3 the answer is 1 (n/2) Let's assume n is even and T(1), T(2), T(n/2) are spanning trees of Kn that have no common edge. For n + 1 we have: T'(1) = T(1) and vertex (n + 1) connected to vertex 1 T'(2) = T(2) and vertex (n + 1) connected to vertex 2 ... T'(n/2) = T(n/2) and vertex (n + 1) connected with vertex n / 2 (n+1) connected with n/2+1, n/2+1, ..., n are unused edges(not enough to make another spanning tree) thus T'(1) ... T'(n/2) is the maximum set of spanning trees of K(n+1) that have no common edge. For n + 2 we have: T''(1) = T'(1) and vertex (n + 2) connected to vertex n/2+1 (node of first unused edge in the n+1 solution) T''(2) = T'(2) and vertex (n + 2) connected to vertex n/2+2 (node of second unused edge in the n+1 solution) ... T''(n/2) = T'(n/2) and vertex (n + 2) connected with vertex n T''(n/2 + 1) = vertex n + 2 connected to 1, 2, 3 .... n/2; vertex n+1 connected to n/2+1, n/2+2, .... n (unused edges in the n+1 solution); n+1 connected ti n+2 so, for n+2 we found a set of size n/2 + 1. */ #include <iostream> using namespace std; int main() { for (int nCaseLoop = 1, nN; (cin >> nN) && nN; nCaseLoop++) cout << "Case " << nCaseLoop << ": " << nN / 2 << endl; return 0; }
Rust
UTF-8
16,844
2.78125
3
[ "Apache-2.0", "MIT" ]
permissive
use crate::common::{ OutputFormat, ProfanityOption, PropertyCollection, PropertyId, ServicePropertyChannel, }; use crate::error::{convert_err, Result}; use crate::ffi::{ speech_config_from_authorization_token, speech_config_from_endpoint, speech_config_from_host, speech_config_from_subscription, speech_config_get_property_bag, speech_config_release, speech_config_set_profanity, speech_config_set_service_property, SmartHandle, SPXHANDLE, SPXPROPERTYBAGHANDLE, SPXSPEECHCONFIGHANDLE, }; use std::ffi::CString; use std::mem::MaybeUninit; /// SpeechConfig is the class that defines configurations for speech / intent recognition, or speech synthesis. #[derive(Debug)] pub struct SpeechConfig { pub handle: SmartHandle<SPXSPEECHCONFIGHANDLE>, properties: PropertyCollection, } impl SpeechConfig { /// Creates a SpeechConfig instance from a valid handle. This is for internal use only. pub fn from_handle(handle: SPXHANDLE) -> Result<SpeechConfig> { unsafe { let mut prop_bag_handle: SPXPROPERTYBAGHANDLE = MaybeUninit::uninit().assume_init(); let ret = speech_config_get_property_bag(handle, &mut prop_bag_handle); convert_err(ret, "SpeechConfig::from_handle error")?; let mut property_bag = PropertyCollection::from_handle(prop_bag_handle); property_bag .set_property_by_string("SPEECHSDK-SPEECH-CONFIG-SYSTEM-LANGUAGE", "Rust")?; let result = SpeechConfig { handle: SmartHandle::create("SpeechConfig", handle, speech_config_release), properties: property_bag, }; Ok(result) } } /// Creates an instance of the speech config with specified subscription key and region. pub fn from_subscription<S>(subscription: S, region: S) -> Result<SpeechConfig> where S: Into<Vec<u8>>, { let c_sub = CString::new(subscription)?; let c_region = CString::new(region)?; unsafe { let mut handle: SPXSPEECHCONFIGHANDLE = MaybeUninit::uninit().assume_init(); let ret = speech_config_from_subscription(&mut handle, c_sub.as_ptr(), c_region.as_ptr()); convert_err(ret, "SpeechConfig::from_subscription error")?; SpeechConfig::from_handle(handle) } } /// Creates an instance of the speech config with specified authorization token and /// region. /// Note: The caller needs to ensure that the authorization token is valid. Before the authorization token expires, the /// caller needs to refresh it by calling this setter with a new valid token. /// As configuration values are copied when creating a new recognizer, the new token value will not apply to recognizers /// that have already been created. /// For recognizers that have been created before, you need to set authorization token of the corresponding recognizer /// to refresh the token. Otherwise, the recognizers will encounter errors during recognition. pub fn from_auth_token<S>(auth_token: S, region: S) -> Result<SpeechConfig> where S: Into<Vec<u8>>, { let c_auth_token = CString::new(auth_token)?; let c_region = CString::new(region)?; unsafe { let mut handle: SPXSPEECHCONFIGHANDLE = MaybeUninit::uninit().assume_init(); let ret = speech_config_from_authorization_token( &mut handle, c_auth_token.as_ptr(), c_region.as_ptr(), ); convert_err(ret, "SpeechConfig::from_auth_token error")?; SpeechConfig::from_handle(handle) } } // Creates an instance of the speech config with specified endpoint /// and subscription. /// This method is intended only for users who use a non-standard service endpoint. /// Note: The query parameters specified in the endpoint URI are not changed, even if they are set by any other APIs. /// For example, if the recognition language is defined in URI as query parameter "language=de-DE", and also set by /// SetSpeechRecognitionLanguage("en-US"), the language setting in URI takes precedence, and the effective language /// is "de-DE". /// Only the parameters that are not specified in the endpoint URI can be set by other APIs. /// Note: To use an authorization token with endoint, use FromEndpoint, /// and then call SetAuthorizationToken() on the created SpeechConfig instance. pub fn from_endpoint_with_subscription<S>(endpoint: S, subscription: S) -> Result<SpeechConfig> where S: Into<Vec<u8>>, { let c_endpoint = CString::new(endpoint)?; let c_subscription = CString::new(subscription)?; unsafe { let mut handle: SPXSPEECHCONFIGHANDLE = MaybeUninit::uninit().assume_init(); let ret = speech_config_from_endpoint( &mut handle, c_endpoint.as_ptr(), c_subscription.as_ptr(), ); convert_err(ret, "SpeechConfig::from_endpoint_with_subscription error")?; SpeechConfig::from_handle(handle) } } /// Creates an instance of SpeechConfig with specified endpoint. /// This method is intended only for users who use a non-standard service endpoint. /// Note: The query parameters specified in the endpoint URI are not changed, even if they are set by any other APIs. /// For example, if the recognition language is defined in URI as query parameter "language=de-DE", and also set by /// SetSpeechRecognitionLanguage("en-US"), the language setting in URI takes precedence, and the effective language is /// "de-DE". /// Only the parameters that are not specified in the endpoint URI can be set by other APIs. /// Note: If the endpoint requires a subscription key for authentication, use NewSpeechConfigFromEndpointWithSubscription /// to pass the subscription key as parameter. /// To use an authorization token with FromEndpoint, use this method to create a SpeechConfig instance, and then /// call SetAuthorizationToken() on the created SpeechConfig instance. pub fn from_endpoint<S>(endpoint: S) -> Result<SpeechConfig> where S: Into<Vec<u8>>, { let c_endpoint = CString::new(endpoint)?; unsafe { let mut handle: SPXSPEECHCONFIGHANDLE = MaybeUninit::uninit().assume_init(); let ret = speech_config_from_endpoint(&mut handle, c_endpoint.as_ptr(), std::ptr::null()); convert_err(ret, "SpeechConfig::from_endpoint error")?; SpeechConfig::from_handle(handle) } } /// Creates an instance of the speech config with specified host and subscription. /// This method is intended only for users who use a non-default service host. Standard resource path will be assumed. /// For services with a non-standard resource path or no path at all, use FromEndpoint instead. /// Note: Query parameters are not allowed in the host URI and must be set by other APIs. /// Note: To use an authorization token with host, use NewSpeechConfigFromHost, /// and then call SetAuthorizationToken() on the created SpeechConfig instance. pub fn from_host_with_subscription<S>(host: S, subscription: S) -> Result<SpeechConfig> where S: Into<Vec<u8>>, { let c_host = CString::new(host)?; let c_subscription = CString::new(subscription)?; unsafe { let mut handle: SPXSPEECHCONFIGHANDLE = MaybeUninit::uninit().assume_init(); let ret = speech_config_from_host(&mut handle, c_host.as_ptr(), c_subscription.as_ptr()); convert_err(ret, "SpeechConfig::from_host_with_subscription error")?; SpeechConfig::from_handle(handle) } } /// Creates an instance of SpeechConfig with specified host. /// This method is intended only for users who use a non-default service host. Standard resource path will be assumed. /// For services with a non-standard resource path or no path at all, use FromEndpoint instead. /// Note: Query parameters are not allowed in the host URI and must be set by other APIs. /// Note: If the host requires a subscription key for authentication, use NewSpeechConfigFromHostWithSubscription to pass /// the subscription key as parameter. /// To use an authorization token with FromHost, use this method to create a SpeechConfig instance, and then /// call SetAuthorizationToken() on the created SpeechConfig instance. pub fn from_host<S>(host: S) -> Result<SpeechConfig> where S: Into<Vec<u8>>, { let c_host = CString::new(host)?; unsafe { let mut handle: SPXSPEECHCONFIGHANDLE = MaybeUninit::uninit().assume_init(); let ret = speech_config_from_host(&mut handle, c_host.as_ptr(), std::ptr::null()); convert_err(ret, "SpeechConfig::from_host error")?; SpeechConfig::from_handle(handle) } } /// Sets proxy configuration /// Note: Proxy functionality is not available on macOS. This function will have no effect on this platform. pub fn set_proxy(&mut self, hostname: String, port: u64) -> Result<()> { self.set_property(PropertyId::SpeechServiceConnectionProxyHostName, hostname)?; self.set_property( PropertyId::SpeechServiceConnectionProxyPort, port.to_string(), ) } /// Sets proxy configuration with username and password /// Note: Proxy functionality is not available on macOS. This function will have no effect on this platform. pub fn set_proxy_with_usrname_and_pwd( &mut self, hostname: String, port: u64, username: String, password: String, ) -> Result<()> { self.set_proxy(hostname, port)?; self.set_property(PropertyId::SpeechServiceConnectionProxyUserName, username)?; self.set_property(PropertyId::SpeechServiceConnectionProxyPassword, password) } pub fn set_service_property( &mut self, name: String, value: String, channel: ServicePropertyChannel, ) -> Result<()> { unsafe { let c_name = CString::new(name)?; let c_value = CString::new(value)?; let ret = speech_config_set_service_property( self.handle.inner(), c_name.as_ptr(), c_value.as_ptr(), channel as u32, ); convert_err(ret, "SpeechConfig.set_service_property error")?; Ok(()) } } pub fn set_profanity_option(&mut self, profanity_option: ProfanityOption) -> Result<()> { unsafe { let ret = speech_config_set_profanity(self.handle.inner(), profanity_option as u32); convert_err(ret, "SpeechConfig.set_profanity_option error")?; Ok(()) } } pub fn enable_audio_logging(&mut self) -> Result<()> { self.set_property( PropertyId::SpeechServiceConnectionEnableAudioLogging, "true".into(), ) } /// Includes word-level timestamps in response result. pub fn request_word_level_timestamps(&mut self) -> Result<()> { self.set_property( PropertyId::SpeechServiceResponseRequestWordLevelTimestamps, "true".into(), ) } /// Enables dictation mode. Only supported in speech continuous recognition. pub fn enable_dictation(&mut self) -> Result<()> { self.set_property( PropertyId::SpeechServiceConnectionRecoMode, "DICTATION".into(), ) } pub fn set_property(&mut self, id: PropertyId, value: String) -> Result<()> { self.properties.set_property(id, value) } pub fn get_property(&self, id: PropertyId) -> Result<String> { self.properties.get_property(id, "") } pub fn set_property_by_string(&mut self, name: String, value: String) -> Result<()> { self.properties.set_property_by_string(name, value) } pub fn get_property_by_string(&self, name: String) -> Result<String> { self.properties.get_property_by_string(name, "".into()) } /// Subscription key that is used to create Speech Recognizer or Intent Recognizer or Translation /// Recognizer or Speech Synthesizer pub fn get_subscription_key(&self) -> Result<String> { self.get_property(PropertyId::SpeechServiceConnectionKey) } /// Region key that used to create Speech Recognizer or Intent Recognizer or Translation Recognizer or /// Speech Synthesizer. pub fn get_region(&self) -> Result<String> { self.get_property(PropertyId::SpeechServiceConnectionRegion) } /// Authorization token to connect to the service. pub fn get_auth_token(&self) -> Result<String> { self.get_property(PropertyId::SpeechServiceAuthorizationToken) } /// Sets the authorization token to connect to the service. /// Note: The caller needs to ensure that the authorization token is valid. Before the authorization token /// expires, the caller needs to refresh it by calling this setter with a new valid token. /// As configuration values are copied when creating a new recognizer, the new token value will not apply to /// recognizers that have already been created. /// For recognizers that have been created before, you need to set authorization token of the corresponding recognizer /// to refresh the token. Otherwise, the recognizers will encounter errors during recognition. pub fn set_auth_token(&mut self, auth_token: String) -> Result<()> { self.set_property(PropertyId::SpeechServiceAuthorizationToken, auth_token) } /// Gets input language to the speech recognition. /// The language is specified in BCP-47 format. pub fn get_speech_recognition_language(&self) -> Result<String> { self.get_property(PropertyId::SpeechServiceConnectionRecoLanguage) } pub fn set_speech_recognition_language(&mut self, reco_lang: String) -> Result<()> { self.set_property(PropertyId::SpeechServiceConnectionRecoLanguage, reco_lang) } pub fn get_output_format(&self) -> Result<OutputFormat> { let output_format = self.get_property(PropertyId::SpeechServiceResponseRequestDetailedResultTrueFalse)?; match output_format.as_str() { "true" => Ok(OutputFormat::Detailed), _ => Ok(OutputFormat::Simple), } } // Sets the speech synthesis output format (e.g. Riff16Khz16BitMonoPcm). pub fn set_get_output_format(&mut self, output_format: OutputFormat) -> Result<()> { match output_format { OutputFormat::Simple => self.set_property( PropertyId::SpeechServiceResponseRequestDetailedResultTrueFalse, "false".into(), ), OutputFormat::Detailed => self.set_property( PropertyId::SpeechServiceResponseRequestDetailedResultTrueFalse, "true".into(), ), } } pub fn get_endpoint_id(&self) -> Result<String> { self.get_property(PropertyId::SpeechServiceConnectionEndpointId) } pub fn set_endpoint_id(&mut self, endpoint_id: String) -> Result<()> { self.set_property(PropertyId::SpeechServiceConnectionEndpointId, endpoint_id) } pub fn get_speech_synthesis_language(&self) -> Result<String> { self.get_property(PropertyId::SpeechServiceConnectionSynthLanguage) } pub fn set_get_speech_synthesis_language( &mut self, speech_synthesis_language: String, ) -> Result<()> { self.set_property( PropertyId::SpeechServiceConnectionSynthLanguage, speech_synthesis_language, ) } pub fn get_speech_synthesis_voice_name(&self) -> Result<String> { self.get_property(PropertyId::SpeechServiceConnectionSynthVoice) } pub fn set_get_speech_synthesis_voice_name( &mut self, speech_synthesis_voice_name: String, ) -> Result<()> { self.set_property( PropertyId::SpeechServiceConnectionSynthVoice, speech_synthesis_voice_name, ) } pub fn get_speech_synthesis_output_format(&self) -> Result<String> { self.get_property(PropertyId::SpeechServiceConnectionSynthOutputFormat) } pub fn set_get_speech_synthesis_output_format( &mut self, speech_synthesis_output_format: String, ) -> Result<()> { self.set_property( PropertyId::SpeechServiceConnectionSynthOutputFormat, speech_synthesis_output_format, ) } }
C++
SHIFT_JIS
1,171
2.796875
3
[ "MIT" ]
permissive
/* 360 == IDENOM * 4 */ #include "all.h" /* Sine90.txt 0 ` 90 (IDENOM + 1) -> sin(0 ` IDENOM) * IMAX */ static autoList<int> *GetSine90(void) { static autoList<int> *sine90; if(!sine90) { autoList<uchar> *fileData = GetEtcRes()->GetHandle(ETC_SINE90TXT); int rIndex = 0; sine90 = new autoList<int>(); for(int index = 0; index <= IDENOM; index++) { sine90->AddElement(atoi_x(readLine(fileData, rIndex))); } delete fileData->Ecdysis(); // ɂB } return sine90; } int iSin(fPInt_t angle, int retScale) { errorCase(angle < -IMAX || IMAX < angle); errorCase(retScale < -IMAX || IMAX < retScale); if(retScale < 0) return -iSin(angle, -retScale); angle %= IDENOM * 4; if(angle < 0) angle += IDENOM * 4; errorCase(!m_isRange(angle, 0, IDENOM * 4 - 1)); // 2bs int retSign = IDENOM * 2 < angle ? -1 : 1; angle %= IDENOM * 2; angle = IDENOM - angle; angle = abs(angle); angle = IDENOM - angle; __int64 retval = GetSine90()->GetElement(angle) * retSign; retval *= retScale; retval /= IMAX; return (int)retval; } int iCos(fPInt_t angle, int retScale) { return iSin(angle + IDENOM, retScale); }
Markdown
UTF-8
729
2.984375
3
[]
no_license
# 服务器的安全问题 ## ssh登录 黑客会通过扫描服务器常见的ssh端口(22),并试图以一些常见的帐号名登录如:root, alex, user等等,然后通过暴力破解密码的方式入侵系统。 了解了这一点之后,我们就可以从以下几个方面防范这种攻击方式 1. 更改ssh默认端口,可以改为不常见的端口,使得黑客更难扫描到 2. 禁止root通过ssh登录,这样黑客只能通过普通用户身份登录,权限更小 3. 设置复杂的用户名,更难尝试到 4. 设置复杂的密码 5. 使用私钥-公钥方式免密登录,这时就可以禁止ssh密码登录,更加安全。 ## 查看日志 /var/log/auth.log
Java
UTF-8
714
2.84375
3
[]
no_license
public class RecordLabel{ private String labelName; private float established; public RecordLabel(String initName, float initEstablished){ labelName = initName; established = initEstablished; } /** * @return the labelName */ public String getLabelName() { return labelName; } /** * @param labelName the labelName to set */ public void setLabelName(String labelName) { this.labelName = labelName; } /** * @return the established */ public float getEstablished() { return established; } /** * @param established the established to set */ public void setEstablished(float established) { this.established = established; } }
C#
UTF-8
1,226
2.59375
3
[ "MIT" ]
permissive
using MiniBus.Contracts; using System; using System.Collections.Generic; using System.Messaging; namespace MiniBus.Tests.Fakes { public sealed class FakeValidMessageQueue : IMessageQueue { public void Add(Message message) { _messages.Add(message); } public string FormatName { get { return "FakeValidMessageQueue"; } } public void Send(Message message, string label, MessageQueueTransactionType transactionType) { _messages.Add(message); } public void ReceiveById(string messageId, MessageQueueTransactionType transactionType) { } public void ReceiveAsync(Action<Message> current) { } public IEnumerable<Message> GetAllMessages() { return _messages; } public bool IsInitialized { get { return true; } } public int Count { get { return _messages.Count; } } private readonly List<Message> _messages = new List<Message>(); public void Dispose() { } } }
Java
UTF-8
1,213
2.84375
3
[]
no_license
import java.io.*; import java.util.*; import java.net.*; import java.sql.*; public class ServerThreads extends Thread{ private Socket socket; public ServerThreads(Socket socket){ this.socket=socket; } public void run(){ try{ ObjectOutputStream outStream = new ObjectOutputStream(socket.getOutputStream()); ObjectInputStream inStream = new ObjectInputStream(socket.getInputStream()); PackageData pd = new PackageData(); while((pd=(PackageData)inStream.readObject())!=null){ if(pd.getOperationType().equals("add")){ Students st = pd.getStudent(); Server.addStudent(st); }else if (pd.getOperationType().equals("list")) { ArrayList<Students> db = Server.getAllStudents(); PackageData response = new PackageData("list",db); outStream.writeObject(response); }else if (pd.getOperationType().equals("exit")) { Server.disconnect(); break; } } }catch (Exception e) { e.printStackTrace(); } } }
Shell
UTF-8
344
2.65625
3
[]
no_license
#!/bin/sh if test -x "runtime/jre1.8.0_172/bin/java"; then JAVA="runtime/jre1.8.0_172/bin/java" elif test -x "../runtime/jre1.8.0_172/bin/java"; then JAVA="../runtime/jre1.8.0_172/bin/java" else JAVA="java" fi "$JAVA" -classpath patcher.jar:javassist.jar org.gotti.wurmunlimited.patcher.PatchServerJar chmod a+x WurmServerLauncher-patched
JavaScript
UTF-8
11,966
2.546875
3
[]
no_license
$(document).ready(function () { if ($("#observacaoAluno").val() != "" && $("#observacaoAluno").val() != undefined) { $("#observacaoAluno").val(unescape($("#observacaoAluno").val())); } }); function deletarAluno(idAluno) { swal({ title: "Excluir Aluno", text: "Confirma a exclusão do aluno?", icon: "warning", buttons: true, dangerMode: true, }) .then((willDelete) => { if (willDelete) { var dados = ""; if (idAluno != "") { dados += '{name:"Id", value:"' + idAluno + '"},'; } dadosEnvio = eval("[" + dados + "]"); $.ajax({ url: "/Alunos/Delete", method: "POST", data: dadosEnvio, success: function (data) { swal({ title: "Sucesso!", text: "Aluno excluido com Sucesso", icon: "success", }); //$("#pagina").html(data).find('.page-wrapper') var doc = new DOMParser().parseFromString(data, "text/html"); var subtabelas = doc.getElementsByClassName("main-body"); var div = document.getElementById("pagina"); div.innerHTML = subtabelas[0].innerHTML }, error: function (data) { swal({ title: "Erro ao Excluir!", text: "Erro desconhecido!", icon: "error", }); } }); } }); } function salvarAvaliacao() { var dados = ""; if ($('#alunoCodigo').val() != "") { dados += '{name:"AlunoCodigo", value:"' + $('#alunoCodigo').val() + '"},'; } else { swal({ title: "Erro ao cadastrar!", text: "Aluno não foi selecionado!", icon: "error", }); return; } if ($('#usuarioCodigo').val() != "") { dados += '{name:"UsuarioCodigo", value:"' + $('#usuarioCodigo').val() + '"},'; } else { swal({ title: "Erro ao cadastrar!", text: "Especialista não foi selecionado!", icon: "error", }); return; } dadosEnvio = eval("[" + dados + "]"); $.ajax({ url: "/Avaliacoes/Create", method: "POST", data: dadosEnvio, success: function (data) { swal({ title: "Sucesso!", text: "Avaliação cadastrada com Sucesso", icon: "success", }); $("#detalheAvaliacao").html(data); $("#detalheAvaliacao").attr("style", "display:block"); $("#btVoltar").attr("style", "display:block;"); $("#btSalvar").attr("style", "display:none;"); $("#alunoCodigo").attr("disabled", "disabled"); $("#usuarioCodigo").attr("disabled", "disabled"); $("#AcaoDetalhe").val("Incluir"); }, error: function (data) { swal({ title: "Erro ao cadastrar!", text: "Erro desconhecido!", icon: "error", }); } }); } function salvarAvaliacaoDetalhe() { var dados = ""; if ($('#dadosProcedimento').val() != "") { dados += '{name:"Procedimento", value:"' + escape($('#dadosProcedimento').val()) + '"},'; } if ($('#dadosEnvolvidos').val() != "") { dados += '{name:"Envolvidos", value:"' + ($('#dadosEnvolvidos').val()) + '"},'; } if ($('#dadosDescAcao').val() != "") { dados += '{name:"DescAcao", value:"' + escape($('#dadosDescAcao').val()) + '"},'; } if ($('#dadosConduta').val() != "") { dados += '{name:"Conduta", value:"' + escape($('#dadosConduta').val()) + '"},'; } if ($('#codigoAvaliacao').val() != "") { dados += '{name:"AvaliacaoCodigo", value:"' + $('#codigoAvaliacao').val() + '"},'; } if ($('#avaliacaoDetalheCodigo').val() != "") { dados += '{name:"Codigo", value:"' + $('#avaliacaoDetalheCodigo').val() + '"},'; } else { dados += '{name:"Codigo", value:"0"},'; } if ($('#dadosProcedimento').val() == "" && $('#dadosEnvolvidos').val() == "" && $('#dadosDescAcao').val() == "" && $('#dadosConduta').val() == "") { swal({ title: "Erro ao cadastrar!", text: "Nenhuma informação foi inserida!", icon: "error", }); return; } dadosEnvio = eval("[" + dados + "]"); $.ajax({ url: "/Avaliacoes/CreateDetalhe", method: "POST", data: dadosEnvio, success: function (data) { if ($("#AcaoDetalhe").val() == "Incluir") { $("div").remove(".modal-backdrop"); $("#detalheAvaliacao").html(data); } else { swal({ title: "Sucesso!", text: "Avaliação cadastrada com Sucesso", icon: "success", }); window.setTimeout(function () { document.location.reload(true); }, 2000); } }, error: function (data) { swal({ title: "Erro ao cadastrar!", text: "Erro desconhecido!", icon: "error", }); } }); } function buscarDados() { if ($("#alunoCodigo").val() == "") { $("#dados").attr("style", "display:none") } else { var dados = ""; if ($('#alunoCodigo').val() != "") { dados += '{name:"alunoCodigo", value:"' + $('#alunoCodigo').val() + '"},'; } dadosEnvio = eval("[" + dados + "]"); $.ajax({ url: "/Avaliacoes/DetalheAluno", method: "GET", data: dadosEnvio, dataType: "json", success: function (data) { //Aluno $("#nomeAluno").html(" <h6 class=\"m - b - 30\"></h6>"); $("#nomeAluno").html(" <h6 class=\"m - b - 30\">" + data.nomeAluno + "</h6>"); $("#dtNascimentoAluno").html(" <h6 class=\"m - b - 30\"></h6>"); $("#dtNascimentoAluno").html(" <h6 class=\"m - b - 30\">" + data.dataNascimentoAluno + "</h6>"); $("#modalidadeAluno").html(" <h6 class=\"m - b - 30\"></h6>"); if (data.modalidadeAluno != null) $("#modalidadeAluno").html(" <h6 class=\"m - b - 30\">" + data.modalidadeAluno + "</h6>"); $("#diagnosticoAluno").html(" <h6 class=\"m - b - 30\"></h6>"); if (data.diagnoscoAluno != null) $("#diagnosticoAluno").html(" <h6 class=\"m - b - 30\">" + data.diagnoscoAluno + "</h6>"); $("#nomeMaeAluno").html(" <h6 class=\"m - b - 30\"></h6>"); if (data.nomeMae != null) $("#nomeMaeAluno").html(" <h6 class=\"m - b - 30\">" + data.nomeMae + "</h6>"); $("#nomePaiAluno").html(" <h6 class=\"m - b - 30\"></h6>"); if (data.nomePai != null) $("#nomePaiAluno").html(" <h6 class=\"m - b - 30\">" + data.nomePai + "</h6>"); if (data.turnoAluno != null) { if (data.turnoAluno == 1) { $("#turnoAluno").html(" <h6 class=\"m - b - 30\">Manhã</h6>"); } else if (data.turnoAluno == 2) { $("#turnoAluno").html(" <h6 class=\"m - b - 30\">Tarde</h6>"); } else $("#turnoAluno").html(" <h6 class=\"m - b - 30\">Noite</h6>"); } $("#observacaoAluno").val(unescape(data.observacaoAluno)); //Escola $("#nueEscola").html(" <h6 class=\"m - b - 30\">" + data.nueEscola + "</h6>"); $("#nomeEscola").html(" <h6 class=\"m - b - 30\">" + data.nomeEscola + "</h6>"); $("#telefoneEscola").html(" <h6 class=\"m - b - 30\"></h6>"); if (data.telefoneEscola != null) $("#telefoneEscola").html(" <h6 class=\"m - b - 30\">" + data.telefoneEscola + "</h6>"); $("#telefone2Escola").html(" <h6 class=\"m - b - 30\"></h6>"); if (data.telefone2Escola != null) $("#telefone2Escola").html(" <h6 class=\"m - b - 30\">" + data.telefone2Escola + "</h6>"); $("#cidadeEscola").html(" <h6 class=\"m - b - 30\"></h6>"); if (data.cidadeEscola != null) $("#cidadeEscola").html(" <h6 class=\"m - b - 30\">" + data.cidadeEscola + "</h6>"); $("#bairroEscola").html(" <h6 class=\"m - b - 30\"></h6>"); if (data.bairroEscola != null) $("#bairroEscola").html(" <h6 class=\"m - b - 30\">" + data.bairroEscola + "</h6>"); $("#diretorEscola").html(" <h6 class=\"m - b - 30\"></h6>"); if (data.diretorEscola != null) $("#diretorEscola").html(" <h6 class=\"m - b - 30\">" + data.diretorEscola + "</h6>"); $("#cp1Escola").html(" <h6 class=\"m - b - 30\"></h6>"); if (data.cp1Escola != null) $("#cp1Escola").html(" <h6 class=\"m - b - 30\">" + data.cp1Escola + "</h6>"); $("#cp2Escola").html(" <h6 class=\"m - b - 30\"></h6>"); if (data.cp2Escola != null) $("#cp2Escola").html(" <h6 class=\"m - b - 30\">" + data.cp2Escola + "</h6>"); $("#apoioEscolarAluno").html(" <h6 class=\"m - b - 30\"></h6>"); if (data.apoioEscolar != null) $("#apoioEscolarAluno").html(" <h6 class=\"m - b - 30\">" + data.apoioEscolar + "</h6>"); if (data.sexo == "F") { $("#imagem1").attr("src", "/assets/images/widget/menina.jpg"); $("#imagem2").attr("src", "/assets/images/widget/menina.jpg"); $("#imagem3").attr("src", "/assets/images/widget/menina.jpg"); $("#imagem4").attr("src", "/assets/images/widget/menina.jpg"); } else { $("#imagem1").attr("src", "/assets/images/widget/menino.jpg"); $("#imagem2").attr("src", "/assets/images/widget/menino.jpg"); $("#imagem3").attr("src", "/assets/images/widget/menino.jpg"); $("#imagem4").attr("src", "/assets/images/widget/menino.jpg"); } $("#dados").attr("style", "display:block"); }, error: function (data) { swal({ title: "Erro ao cadastrar!", text: "Erro desconhecido!", icon: "error", }); } }); } } function buscarDadosDetalhe(AvaliacaoDetalheCodigo) { var dados = ""; if (AvaliacaoDetalheCodigo != "") { dados += '{name:"id", value:"' + AvaliacaoDetalheCodigo + '"},'; } dadosEnvio = eval("[" + dados + "]"); $.ajax({ url: "/Avaliacoes/PartialDetalheAvaliacao", method: "GET", data: dadosEnvio, success: function (data) { $("#modaldetalheAvaliacao").html(data); }, error: function (data) { swal({ title: "Erro ao cadastrar!", text: "Erro desconhecido!", icon: "error", }); } }); } function limparCampos() { $('#dadosProcedimento').val(""); $('#dadosEnvolvidos').val("") $('#dadosDescAcao').val("") $('#dadosConduta').val("") $('#avaliacaoDetalheCodigo').val("") } function bytesToSize(bytes) { var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']; if (bytes == 0) return '0 Byte'; var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024))); return Math.round(bytes / Math.pow(1024, i), 2) + ' ' + sizes[i]; } $(document).ready(function () { $('input[name="file"]').change(function () { var file = $('input[name="file"]')[0].files[0]; $('.size-file').html(bytesToSize(file.size)); }); }); async function AJAXSubmit(form) { var formData = new FormData($(form)[0]); var computedProgress = function (evt) { if (evt.lengthComputable) { var percentComplete = evt.loaded / evt.total; var percentComplete = Math.round(event.loaded * 100 / event.total) + "%"; $('.percent-progress').html(percentComplete); $('.progress-bar').css("width", percentComplete); } }; $.ajax({ url: "/Avaliacoes/File", type: 'POST', xhr: function () { var xhr = new window.XMLHttpRequest(); xhr.addEventListener("progress", computedProgress, false); xhr.upload.addEventListener("progress", computedProgress, false); return xhr; }, data: formData, async: true, success: function (data) { $("#fecharModalFile").click(); swal({ title: "Sucesso!", text: "Arquivo anexado com sucesso.", icon: "success", }); }, cache: false, contentType: false, processData: false }); return false; } function partialAnexos(valor) { var dados = ""; if (valor != "") { dados += '{name:"id", value:"' + valor + '"},'; } dadosEnvio = eval("[" + dados + "]"); $.ajax({ url: "/Avaliacoes/PartialAnexos", method: "GET", data: dadosEnvio, success: function (data) { $("#modaldetalheAvaliacaoAnnexo").html(data); }, error: function (data) { } }); } function downloadArquivo(caminho, detalheCodigo, nomeArquivo) { var dados = ""; if (nomeArquivo == "") { swal({ title: "Erro ao cadastrar!", text: "Erro desconhecido!", icon: "error", }); } if (nomeArquivo != "") { dados += '{name:"filename", value:"' + nomeArquivo + '"},'; } if (detalheCodigo != "") { dados += '{name:"codigo", value:"' + detalheCodigo + '"},'; } dadosEnvio = eval("[" + dados + "]"); $.ajax({ url: "/Avaliacoes/Download", method: "GET", data: dadosEnvio, success: function (data) { }, error: function (data) { swal({ title: "Erro ao cadastrar!", text: "Erro desconhecido!", icon: "error", }); } }); }
C++
GB18030
1,606
3.390625
3
[]
no_license
//#define Zconvert #ifdef Zconvert /* * @lc app=leetcode.cn id=6 lang=cpp * * һַݸԴ¡ҽ Z С * ַΪ "LEETCODEISHIRING" Ϊ 3 ʱ£ L C I R E T O E S I I G E D H N ֮Ҫжȡһµַ磺"LCIRETOESIIGEDHN" ʵַָ任ĺ * [6] Z α任 */ /* 1158/1158 cases passed (16 ms) Your runtime beats 72.09 % of cpp submissions Your memory usage beats 76.41 % of cpp submissions (12.8 MB) */ // @lc code=start #include <iostream> #include <string> #include <vector> using namespace std; class Solution { public: string convert(string s, int numRows) { /* numRowsУмnumRows-2 */ vector<string> lines(numRows,""); if (1 == numRows || "" ==s || numRows >= s.length()) { return s; } int pushRow = 0; bool updown = true; //false½ for (char c : s) { lines[pushRow] += c; if (pushRow == numRows - 1 || pushRow == 0) { updown = !updown; } if (!updown)// ½ { pushRow += 1; } else { pushRow -= 1; } } string retStr = ""; for (string str : lines) { retStr += str; } return retStr; } }; int main() { string sentence; while (cin >> sentence) { int num; cin >> num; Solution so; cout << so.convert(sentence, num) << endl; } return 0; } // @lc code=end #endif //Zconvert
C#
UTF-8
2,857
3.265625
3
[ "MIT" ]
permissive
using System.Net; namespace VisualTraceRoute.Net { /// <summary> /// Trace route hop. /// </summary> public class Hop { private IPAddress _address; private int _hop; private long _roundTrip; /// <summary> /// Gets the Internet address in standard notation. /// </summary> public string Address { get { return this._address.ToString(); } } /// <summary> /// Gets the hop count. /// </summary> public int HopCount { get { return this._hop; } } /// <summary> /// Gets the Internet address host name. /// </summary> public string HostName { get { string hostName; try { hostName = Dns.GetHostEntry(this._address).HostName; } catch { hostName = this._address.ToString(); } return hostName; } } /// <summary> /// Gets the total round trip time (in milliseconds). /// </summary> public long RoundTrip { get { return this._roundTrip; } } /// <summary> /// Initializes a new instance of the Hop class. /// </summary> /// <param name="Address">Internet address.</param> /// <param name="RoundTrip">Round trip time in milliseconds.</param> /// <param name="Hop">Hop count.</param> public Hop(IPAddress Address, long RoundTrip, int Hop) { this._address = Address; this._hop = Hop; this._roundTrip = RoundTrip; } /// <summary> /// Write the trace route reply in standard output format. /// </summary> /// <returns>Trace hop.</returns> public override string ToString() { return this.ToString(false); } /// <summary> /// Write the trace route reply in standard output format. /// </summary> /// <param name="ResolveHostNames">A value indicating whether to resolve the hostname of the reply.</param> /// <returns>Trace route hop.</returns> public string ToString(bool ResolveHostNames) { return string.Format ( "{0}\t{1}ms\t{2}{3}", this._hop.ToString(), this._roundTrip.ToString(), ResolveHostNames ? string.Format("[{0}] ", this.HostName) : string.Empty, this._address.ToString() ); } } }
C++
UTF-8
2,806
3.984375
4
[]
no_license
//============================================================================ // Name : Red_Yellow_GreenGame.cpp // Author : Christian Aguilar // Version : // Copyright : Feb 2015 // Description : Red Yellow Green Game, The color game that uses vectors //classes and operator digit spits. Functions using nested //for loops and integer comparitors. //============================================================================ #include <iostream> #include <cstdlib> #include <time.h> #include <vector> using namespace std; int generateNum(); vector<int> digitSplit(int); class Comparitor { private: vector<int> randomNum, guess; int red, yellow, green; public: Comparitor(vector<int>, vector<int>); void compare(); int getRed(); int getYellow(); int getGreen(); void setColors(int, int, int); }; Comparitor::Comparitor(vector<int> ranN, vector<int> userN) { randomNum = ranN; guess = userN; } int Comparitor::getGreen() { int g = green; return g; } int Comparitor::getRed() { int r = red; return r; } int Comparitor::getYellow() { int y = yellow; return y; } void Comparitor::setColors(int g, int y, int r) { green = g; yellow = y; red = r; } void Comparitor::compare() { //check for greens for (int i = 0; i < 3; i++) { if (randomNum[i] == guess[i]) { green++; guess[i]=-1; randomNum[i]=-2; } } //check for yellow for (int i = 0; i<3; i++){ for (int j = 0; j<3; j++){ //super efficiency inspired by Jon if (guess[i]==randomNum[j]) yellow ++; } } //remainder is red red = 3 - (green + yellow); } int green, yellow, red; int main() { int numToCheck; char cmd; int ranNum = generateNum(); //Saves random number cout << ranNum << endl; while (cmd != 'Q') { cout << "Please enter a guess\n"; cin >> numToCheck; while (numToCheck < 100 || numToCheck > 999) { cout << "Error: number is too low. Enter New Guess\n"; cin >> numToCheck; } vector<int> randomNum = digitSplit(ranNum); //splits random number into digits vector<int> guess = digitSplit(numToCheck); //splits guess into digits Comparitor attempt(randomNum, guess); attempt.setColors(0, 0, 0); attempt.compare(); green = attempt.getGreen(); red = attempt.getRed(); // yellow = attempt.getYellow(); cout << "Green: " << green; cout << "\tYellow: " << yellow; cout << "\tRed: " << red << endl; if (green == 3) { cmd = 'Q'; cout << "Congratulations! You have guessed the number\n"; } } return 0; } //Generates random numbers int generateNum() { srand(time(NULL)); int ranNum = rand() % 900 + 100; return ranNum; } //Splits using operators vector<int> digitSplit(int input) { vector<int> num; while (input > 0) { int digit = input % 10; //numbers will be in reverse num.push_back(digit); input /= 10; } return num; }
Java
UTF-8
1,033
1.882813
2
[]
no_license
package com.cloud.service; import com.cloud.service.impl.PaymentServiceImpl; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.stereotype.Component; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; /** * @author * @date 2020/3/7 */ @FeignClient(value = "cloud-payment-hystrix-service", fallback = PaymentServiceImpl.class) public interface IPaymentService { /** * ok接口 * @param id * @return */ @GetMapping("/provider/hystrix/ok/{id}") String getOk(@PathVariable("id") Long id); /** * timeout接口 * @param id * @return */ @GetMapping("/provider/hystrix/timeout/{id}") String getTimeout(@PathVariable("id") Long id); /** * ds * @param id * @return */ @GetMapping("/provider/hystrix/circuitbreaker/{id}") String circuitbreaker(@PathVariable("id") Long id); }
C#
UTF-8
1,054
2.625
3
[]
no_license
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace Temporizador { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { Temporizador t = new Temporizador(1000); t.eventoTiempo += T_eventoTiempo; System.Threading.Thread hilo = new System.Threading.Thread(t.Corriendo); hilo.Start(); } private void T_eventoTiempo() { if (this.label1.InvokeRequired) { encargadoTiempo e = new encargadoTiempo(T_eventoTiempo); this.Invoke(e); } else { this.label1.Text = DateTime.Now.ToString(); } throw new NotImplementedException(); } } }
Java
ISO-8859-1
611
2.03125
2
[]
no_license
package com.haylton.estudo.dao; import java.io.Serializable; import com.haylton.estudo.model.Item; public class ItemDAO<T> extends DAOGenerico<Item> implements Serializable { public ItemDAO() { super();//chamo o construtor de DAOGenerico para inicializar a entityManager EM classePersistente = Item.class;//classePersistence e ordem esto visivel pra mim pq so atributos protected e no preciso usar get ou set pois esto em nvel de pacote e EstadoDAO uma classe filha de DAOGenerico<> ordem = "titulo";//ser usado para escolha de ordem inicial da consulta para ser montada na page } }
Java
UTF-8
8,156
1.929688
2
[]
no_license
package grl.com.adapters.donate; import android.app.Activity; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.Button; import android.widget.TextView; import com.koushikdutta.async.http.BasicNameValuePair; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import grl.com.activities.common.ContentShowActivity; import grl.com.configuratoin.Constant; import grl.com.configuratoin.GlobalVars; import grl.com.configuratoin.SelfInfoModel; import grl.com.configuratoin.Utils; import grl.com.httpRequestTask.discovery.donate.DonateConfirmTask; import grl.com.httpRequestTask.discovery.donate.DonateHelpingTask; import grl.com.network.HttpCallback; import grl.com.subViews.fragment.donate.Fragment_donate_help; import grl.wangu.com.grl.R; /** * Created by Administrator on 6/10/2016. */ public class DonateHelpAdapter extends RecyclerView.Adapter<DonateHelpAdapter.MyViewHolder>{ Activity context; public JSONArray myList; Integer adatperType; // tasks DonateConfirmTask donateConfirmTask; DonateHelpingTask donateHelpingTask; public DonateHelpAdapter(Activity context, Integer type) { this.context = context; this.adatperType = type; this.myList = new JSONArray(); } @Override public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View itemView = LayoutInflater.from(parent.getContext()) .inflate(R.layout.layout_donate_help_row, parent, false); return new MyViewHolder(itemView); } @Override public void onBindViewHolder(MyViewHolder holder, final int position) { try { JSONObject jsonObject = this.myList.getJSONObject(position); String content = ""; switch (this.adatperType) { case 0: // 요청이 들어온 경우(확인) holder.btnConfirm.setText(context.getString(R.string.donate_request_confirm)); content = jsonObject.getString("user_name") + ": " + jsonObject.getString("req_content"); holder.tvContent.setText(content); break; case 1: // 기부요청진행(청구) holder.btnConfirm.setText(context.getString(R.string.donate_request_claim)); content = jsonObject.getString("user_name") + ": " + jsonObject.getString("req_content"); holder.tvContent.setText(content); break; } } catch (JSONException e) { e.printStackTrace(); } holder.tvContent.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { // 요청내용을 누르기하는 경우 상세보기를 진행한다. String title = ""; String msg = ""; try { JSONObject jsonObject = myList.getJSONObject(position); switch (adatperType) { case 0: // 요청이 들어온 경우(확인) title = jsonObject.getString("user_name"); msg = jsonObject.getString("req_content"); break; case 1: // 기부요청진행(청구) title = jsonObject.getString("user_name"); msg = jsonObject.getString("req_content"); break; } // 상세한 내용을 보기한다. Utils.start_Activity(context, ContentShowActivity.class, new BasicNameValuePair(Constant.BACK_TITLE_ID, context.getString(R.string.donate_title)), new BasicNameValuePair(Constant.TITLE_ID, title), new BasicNameValuePair(Constant.CONTENT_VIEW_KEY, msg)); } catch (JSONException e) { e.printStackTrace(); } } }); holder.btnConfirm.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { // 단추를 누르기하는 경우 해당한 처리를 진행한다. try { JSONObject jsonObject = myList.getJSONObject(position); switch (adatperType) { case 0: // 확인 단추 onConfirmDonate(SelfInfoModel.userID, jsonObject.getString("donatephone_id"), position); break; case 1: // 청구 단추 onHelpingDonate(SelfInfoModel.userID, jsonObject.getString("donatephone_id"), position); break; } } catch (JSONException e) { e.printStackTrace(); } } }); } @Override public int getItemCount() { return this.myList.length(); } public void onConfirmDonate (String userID, String donateID, final Integer position) { JSONObject params = new JSONObject(); try { params.put("user_id", userID); params.put("donatephone_id", donateID); } catch (JSONException e) { e.printStackTrace(); } if(params.length() == 0) return; donateConfirmTask = new DonateConfirmTask(context, params, new HttpCallback() { @Override public void onResponse(Boolean flag, Object Response) throws JSONException { if(!flag || Response == null) { GlobalVars.showErrAlert(context); return; } JSONObject result = (JSONObject) Response; Boolean resultFlag = result.getBoolean("result"); if(!resultFlag) { GlobalVars.showErrAlert(context); } // 성공이면 목록에서 해당항목을 삭제한다. Fragment_donate_help.self.acceptingList.remove(position); Fragment_donate_help.self.notifyRecycler(); } }); } public void onHelpingDonate (String userID, String donateID, final Integer position) { JSONObject params = new JSONObject(); try { params.put("user_id", userID); params.put("donatephone_id", donateID); } catch (JSONException e) { e.printStackTrace(); } if(params.length() == 0) return; donateHelpingTask = new DonateHelpingTask(context, params, new HttpCallback() { @Override public void onResponse(Boolean flag, Object Response) throws JSONException { if(!flag || Response == null) { GlobalVars.showErrAlert(context); return; } JSONObject result = (JSONObject) Response; Boolean resultFlag = result.getBoolean("result"); if(!resultFlag) { GlobalVars.showErrAlert(context); } // 성공이면 목록에서 해당항목을 삭제한다. Fragment_donate_help.self.requesting.remove(position); Fragment_donate_help.self.notifyRecycler(); } }); } public class MyViewHolder extends RecyclerView.ViewHolder { private final TextView tvContent; private final Button btnConfirm; public MyViewHolder(View itemView) { super(itemView); btnConfirm = (Button) itemView.findViewById(R.id.btn_request); tvContent = (TextView) itemView.findViewById(R.id.tvContent); } } }
C++
ISO-8859-1
2,417
3.515625
4
[]
no_license
//Uma empresa de fornecimento de energia eltrica faz a leitura mensal dos medidores de consumo. Para cada consumidor so digitados os seguintes dados: //nmero do consumidor, quantidade de kwh consumidos durante o ms e o tipo (cdigo) do consumidor (1residencial, 2-comercial, 3-industrial) //Residencial - preo em reais por kwh = 0,3 Comercial - preo em reais por kwh = 0,5 Industrial - preo em reais por kWh = 0,7 //Os dados devem ser lidos at que seja encontrado um consumidor com nmero 0 (zero). Calcular e imprimir: //d) O custo total para cada consumidor e) O total de consumo para os trs tipos de consumidor f) Qual categoria consome mais? #include <iostream> using namespace std; main () { int numero_consumidor, kwh_mes, tipo_consumidor; float total_residencial=0, total_comercial=0, total_industrial=0, total_tres; cout << "\nPor favor, informe o numero do consumidor: "; cin >> numero_consumidor; while (numero_consumidor != 0) { cout << "\nQuantidade de Kwh/mes consumido? "; cin >> kwh_mes; cout << "\nTipo de consumidor (1-residencial, 2-comercial, 3-industrial): "; cin >> tipo_consumidor; if (tipo_consumidor == 1) { total_residencial = total_residencial + (kwh_mes * 0.3); } if (tipo_consumidor == 2) { total_comercial = total_comercial + (kwh_mes * 0.5); } if (tipo_consumidor == 3) { total_industrial = total_industrial + (kwh_mes * 0.7); } cout << "\nPor favor, informe o numero do consumidor: "; cin >> numero_consumidor; } total_tres = total_residencial + total_comercial + total_industrial; cout << "\nO custo total para cada consumidor eh: " <<endl; cout << "\n\nRESIDENCIAL: R$"<<total_residencial; cout << "\n\nCOMERCIAL: R$"<<total_comercial; cout << "\n\nINDUSTRIAL: R$"<<total_industrial; cout << "\n\nO total de consumo para os tres tipos de consumidor eh: R$"<<total_tres; if (total_residencial > total_comercial && total_residencial > total_industrial) { cout << "\n\nResidencial eh a categoria que consome mais!"; } if (total_comercial > total_residencial && total_comercial > total_industrial) { cout << "\n\nComercial eh a categoria que consome mais!"; } if (total_industrial > total_residencial && total_industrial > total_comercial ) { cout << "\n\nIndustrial eh a categoria que consome mais!"; } }
Python
UTF-8
123
3.15625
3
[]
no_license
def t(x): y=list(x) y.reverse() x=tuple(y) return x print(t((5, 3, 2))) print(t(('Hi', 'Ola', 'xD')))
C++
UTF-8
822
2.90625
3
[]
no_license
//Giả sử lãi suất mỗi tháng của ngân hàng là q (ví dụ nếu lãi suất 1% thì q = 0.01) với hình thức gửi tiết kiệm lãi nhập vốn (lãi kép). //Hãy nhập vào số tiền gửi M, số tháng gửi n và lãi suất q, tính số tiền lãi. #include <iostream> using namespace std; #include <math.h> int main() { double laiSuat; double tienGui; int thang; cout << "Nhap so tien gui M: ", cin >> tienGui; cout << "Nhap lai suat q: ", cin >> laiSuat; cout << "Nhap so thang gui: ", cin >> thang; double total = tienGui * pow((1 + laiSuat), thang); cout << "Tong tien nhan duoc sau " << thang << " thang, lai suat: " << laiSuat << " voi tien goc: " << tienGui << " la: " << total << endl; cout << "Tien lai: " << total - tienGui; return 0; }
C++
UTF-8
1,614
3.375
3
[]
no_license
/*!< UVA 10664 */ /*!< Programacao Dinamica */ #include <stdio.h> #include <iostream> using namespace std; #define MAX_AMOUNT_SUITCASES 20 /*!< Returns true if there is a subet o set[] of size n with sum equal to given sum */ bool weighted_subset_sum(int set[], int n, int sum) { bool MEMO[n + 1][sum + 1]; /*!< Initializing the MEMO */ for (int i = 0; i <= n; i++) MEMO[i][0] = true; for (int i = 1; i <= sum; i++) MEMO[0][i] = false; for (int i = 1; i <= n; i++) { for (int j = 1; j <= sum; j++) { if (j < set[i - 1]) MEMO[i][j] = MEMO[i - 1][j]; if (j >= set[i - 1]) MEMO[i][j] = MEMO[i - 1][j] || MEMO[i - 1][j - set[i - 1]]; } } return MEMO[n][sum]; } void suitcase_weight() { int suitcases_weights[MAX_AMOUNT_SUITCASES]; int amount_suitcases = 0, sum = 0; /*!< Reading the values */ char auxilar; do { scanf("%d%c", &suitcases_weights[amount_suitcases], &auxilar); sum += suitcases_weights[amount_suitcases]; amount_suitcases++; } while (auxilar != '\n' && auxilar != '\r'); if(sum % 2 != 0) { /*!< It's impossible to divide the weight equally */ printf("NO\n"); return; } if(weighted_subset_sum(suitcases_weights, amount_suitcases, sum/2)) printf("YES\n"); else printf("NO\n"); return; } int main(void) { int number_of_test_cases; scanf("%d\n", &number_of_test_cases); for(int i = 0; i < number_of_test_cases; i++) suitcase_weight(); return 0; }
Java
UTF-8
1,691
3.390625
3
[]
no_license
package H10; //opdracht 10.1 en 10.2 /** * Created by HP on 28-9-2016. */ import java.applet.Applet; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class Groter_Kleiner extends Applet { TextField tekstvak; TextField tekstvak1; Label label; Button ok; int getal1; int getal2; String tekst; String tekst1; public void init() { //Tekstvak tekstvak = new TextField("", 5); VakListener vl = new VakListener(); tekstvak.addActionListener(vl); tekst = ""; tekstvak1 = new TextField("", 5); VakListener vl1 = new VakListener(); tekstvak1.addActionListener(vl1); tekst1 = ""; //Button ok = new Button("Enter"); VakListener vl2 = new VakListener(); ok.addActionListener(vl2); //Label label = new Label("type een getal in" ); //Layout add( label ); add( tekstvak ); add( tekstvak1 ); add( ok ); } public void paint(Graphics g) { g.drawString("" + getal1 + " is groter dan " + getal2 + ": " + (getal1 > getal2), 50, 60 ); g.drawString("" + getal1 + " is kleiner dan " + getal2 + ": " + (getal1 < getal2), 50, 80 ); } class VakListener implements ActionListener { public void actionPerformed( ActionEvent e ) { tekst = tekstvak.getText(); tekst1 = tekstvak1.getText(); getal1 = Integer.parseInt( tekst ); getal2 = Integer.parseInt( tekst1 ); tekstvak.setText(""); tekstvak1.setText(""); repaint(); } } }
PHP
UTF-8
2,197
2.546875
3
[]
no_license
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>LİSTE</title> </head> <body> <table border="1" align="center"> <tr><td>id</td><td>AD SOYAD</td><td>EPOSTA</td><td>ŞEHİR</td><td>ZİYARETÇİ PROFİL</td><td>KONU BAŞLIK</td><td>KONU İÇERİK</td><td>SİL</td><td>OKUNDU</td><td>YANITLA</td></tr> <?PHP include("oturum.php");//oturum kontrolü için include("vt_ayar.php");//vt_ayar sayfasının çağrılması if(isset($_GET["silkod"]))//Silme linkine tıklanmışsa { $silsorgu="DELETE FROM iletisim WHERE ID=".$_GET["silkod"]; if(mysql_query($silsorgu)) { echo "KAYIT SİLİNDİ"; } else { echo "KAYIT SİLME HATASI"; } } $sorgu = "SELECT * FROM iletisim"; $tablo=mysql_query($sorgu); while($kayit=mysql_fetch_object($tablo)): $pid=$kayit->ID; $padsoyad=$kayit->ADSOYAD; $peposta=$kayit->EPOSTA; $psehir=$kayit->SEHIR; $pzprofil=$kayit->ZPROFIL; $pkbaslik=$kayit->KBASLIK; $pkicerik=$kayit->KICERIK; if(isset($_GET["okod"]) && $pid==$_GET["okod"]) { echo "<tr style='color:red'><td>$pid</td><td>$padsoyad</td><td>$peposta</td><td>$psehir</td><td>$pzprofil</td><td>$pkbaslik</td><td>$pkicerik</td><td><a href='liste.php?silkod=$pid' onclick=\"return confirm('Silmek İstediğinizden Emin misiniz?') \"> <img width='18' height='18' src='sil.png'></a></td><td><a href='liste.php?okod=$pid'>Okundu</a></td><td><a href='mailGonder.php?mail=$peposta'>Yanıtla</a></td></tr>"; } else { echo "<tr><td>$pid</td><td>$padsoyad</td><td>$peposta</td><td>$psehir</td><td>$pzprofil</td><td>$pkbaslik</td><td>$pkicerik</td><td><a href='liste.php?silkod=$pid' onclick=\"return confirm('Silmek İstediğinizden Emin misiniz?') \"> <img width='18' height='18' src='sil.png'></a></td><td><a href='liste.php?okod=$pid'>Okundu</a></td><td><a href='mailGonder.php?mail=$peposta'>Yanıtla</a></td></tr>"; } endwhile; ?> </table> <?php echo "KAYIT SAYISI:".mysql_num_rows($tablo); echo "<br> <a href='ILETISIMFORMU.php'>KAYIT EKLE</a>"; echo "<br> <a href='cikis.php'>ÇIKIŞ YAP</a>"; ?> </body> </html>
Python
UTF-8
444
3.34375
3
[]
no_license
#!/usr/bin/env python3 def sheep(n): if n == 0: return "INSOMNIA" k = n digits = set(str(n)) while len(digits) != 10: k += n digits = digits.union(str(k)) return k with open('A-large.in', 'r') as infile: lines = infile.readlines()[1:] for i, n in enumerate(lines): print("Case #{}:".format(i + 1), sheep(int(n)))