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
Markdown
UTF-8
1,399
2.71875
3
[]
no_license
# SIR : TPOPOWER - Servlet Avant de tester le projet, vous devez lancer le fichier 'run-hsqldb-server.bat' (ou .sh sur linux et mac). Cela permet de lancer une base de donnée. Vous pouvez aussi changer dans la classe '' le 'dev' par 'mysql' afin d'utiliser votre propre base de donnée mysql, dont les informations de configuration sont à spécifié dans le fichier 'persistence.xml' Vous pouvez ensuite lancer le service Java à l'aide de maven. Il vous suffit de lancer tomcat7:run Le service est disponible sur localhost:8090 Pour tester le projet, importé comme projet Maven dans votre IDE préféré # Api routes Ressource utillisé : application/json URI de base : "localhost:8090/" | Methode | URL | Action | | :------- | ----: | :---: | | GET | /person | renvoi toute les personnes | | GET | /person/{id} | renvoi la personne associé à l'id passé en paramètre | | POST | /person | créer une nouvelle personne | | DELETE | /person/{id} | supprimé la personne associé à l'id passé en paramètre | | GET | /home | renvoie tout les maisons | | GET | /home/{id} | renvoie la maison associé à l'id passé en paramètre | | POST | /home | créer une maison | ## Parameter for POST requests : ### /person : - nom : String - prenom : String - email : String ### /home : - taille : Integer - nbP : Integer
Markdown
UTF-8
2,684
3.515625
4
[]
no_license
# エクササイズ - 組み込み型 - str型 ## `str_ex1.py` ``` py numbers = ["One", "Two", "Three", "Four", "Five"] # TODO ``` 次の実行結果となるようにプログラムを作成してください。 ### 実行結果 ``` $ python str_ex1.py ONE TWO THREE FOUR FIVE ``` --- ## `str_ex2.py` ``` py numbers = ["One", "Two", "Three", "Four", "Five"] # TODO ``` 次の実行結果となるようにプログラムを作成してください。 ### 実行結果 ``` $ python str_ex2.py ONE two THREE four FIVE ``` --- ## `str_ex3.py` ``` py message = "Hello" # TODO ``` 次の実行結果となるようにプログラムを作成してください。 ### 実行結果 ``` $ python str_ex3.py hELLO ``` > https://docs.python.org/ja/3/library/stdtypes.html#text-sequence-type-str を参考にメソッドを探してみましょう。 --- ## `str_ex4.py` ``` py names = ["Apple", "Banana", "Cherry"] # TODO ``` 次の実行結果となるようにプログラムを作成してください。 ### 実行結果 ``` $ python str_ex4.py ABC ``` --- ## `str_ex5.py` ``` py colors = "Red Green Blue" # TODO ``` 次の実行結果となるようにプログラムを作成してください。 ### 実行結果 ``` $ python str_ex5.py RGB ``` --- ## `str_ex6.py` ``` py names = ["Alice", "Betty", "Carol", "Daniel", "Ellen"] target = "l" # TODO ``` 次の実行結果となるようにプログラムを作成してください。 ### 実行結果 ``` $ python str_ex6.py ['Alice', 'Carol', 'Daniel', 'Ellen'] ``` > 名前に `l` を含むものだけを表示します。 --- ## `str_ex7.py` ``` py names = ["Alice", "Betty", "Carol", "Daniel", "Ellen"] target = "l" # TODO ``` 次の実行結果となるようにプログラムを作成してください。 ### 実行結果 ``` $ python str_ex7.py ['Carol', 'Daniel'] ``` > 名前の最後が `l` で終わるものだけを表示します。 --- ## `str_ex8.py` ``` py names_list = [["Alice", "Betty", "Carol"], ["Daniel", "Ellen", "Floyd"]] # TODO ``` 次の実行結果となるようにプログラムを作成してください。 ### 実行結果 ``` $ python str_ex8.py Alice-Betty-Carol=Daniel-Ellen-Floyd ``` --- ## `str_ex9.py` ``` py book_prices = {"Python Book": 3000, "HTML Book": 1000, "CSS Book": 2000} # TODO ``` 次の実行結果となるようにプログラムを作成してください。 ### 実行結果 ``` $ python str_ex9.py Python Book: 3,000 HTML Book : 1,000 CSS Book : 2,000 ``` > 書籍名の文字数を揃えて表示します。 --- ### テキスト * [テキスト - 組み込み型 - str型](../text/21_str.md)
Markdown
UTF-8
1,434
3.890625
4
[ "MIT" ]
permissive
### 考察点 基本 ### 描述 给你两个有序整数数组 nums1 和 nums2,请你将 nums2 合并到 nums1 中,使 nums1 成为一个有序数组。 ### 说明 * 初始化 nums1 和 nums2 的元素数量分别为 m 和 n 。 * 你可以假设 nums1 有足够的空间(空间大小大于或等于 m + n)来保存 nums2 中的元素。 ### 思路 * 从nums1和nums2数组的末尾开始一个一个比较,把较大的数,按顺序从后往前加入混合之后的数组末尾。 * 需要三个变量i,j,k,分别指向nums1,nums2,和混合数组的末尾。 * 进行while循环,确保i和j都大于0在执行。 * nums1[i] > nums2[j],要把nums1[i]先加入混合数组的末尾,加入后k和i都要自减1;否则,就把nums2[j]加入混合数组的末尾,之后j和k也要自减1。 * 循环结束后,有可能i和j还大于等于0 * 若j大于等于0,那么需要继续循环,将nums2中的数字继续放入nums1数组中。 * 若是i大于等于0,则不需要进行处理。 ### 代码 ``` class Solution{ public void merge(int nums1 [], int m, int nums2 [], int n){ int i = m-1, j = n-1, k = m+n-1; while(i>=0 && j>=0){ if(nums1[i] > nums2[j]) nums1[k--] = nums1[i--]; else nums1[k--] = nums2[j--]; } while(j>=0){ nums[k--] = nums[j--]; } } } ```
C#
UTF-8
395
3.09375
3
[]
no_license
/* ----- In the Main Thread ----- */ Thread t = new Thread(() => waitForProcessClose(newProcess)); t.Start(); while (t.IsAlive) { Thread.Sleep(500); } /* ----- In the Main Thread ----- */ public static bool waitForProcessClose(Process handleToProcess) { handleToProcess.WaitForExit(); return true; }
JavaScript
UTF-8
1,030
3.328125
3
[]
no_license
let callAjax = function () { let xhr = new XMLHttpRequest(); // response is ready :: 4 xhr.onload = () => { const refJson = JSON.parse(xhr.responseText); // using this data :: we have to DOM Operation; domLogic(refJson); }; xhr.open("GET", "https://reqres.in/api/users?page=2"); xhr.send(); }; // DOM HTML, CSS let domLogic = function (refJson) { console.log(refJson); let parent = document.querySelector("#parent"); for (let i = 0; i < refJson.data.length; i++) { const item = refJson.data[i]; let newElement = parent.children[0].cloneNode(true); newElement.innerHTML = item.first_name + " " + item.last_name; parent.insertBefore(newElement, parent.firstChild); } }; /** * MIN. REQUERMENT :: SERVER PROGRAAM (API) * * AJAX - How to connect or how to talk with server * RESPONSE (JSON/XML) - Knowledge * * Fundamental Knowledge HTML, CSS, DOCUMENT, DOM OPERATION (PAINT THE PAGE) */
TypeScript
UTF-8
952
2.8125
3
[ "Apache-2.0" ]
permissive
module Wpjs { export class Post implements IStorageObject { private m_data: PostModel; private m_wpjs: Wordpress; /** * Constructor for Post object * * @param {Wordpress} wpjs * @param {PostModel} data */ constructor(wpjs: Wordpress, data: PostModel) { this.m_data = data; this.m_wpjs = wpjs; } /** * Get PostModel data * property */ get data(): PostModel { return this.m_data; } public save(): void { } public remove(): void { } /** * Get Metadata from current post item * * @param {Callback} callback */ public meta(callback: (values: Array<PostMetaModel>, error: Error) => void): void { this.m_wpjs.getPostMeta(this.m_data.id, callback); } } }
C++
UHC
1,407
3
3
[]
no_license
#include "CharacterFactory.h" #include "MonsterFactory.h" void AttackTest(JobClass* job); void SohwanTest(TypeClass* type); int main() { KnightCharacter* knightFactory = new KnightCharacter(); ArcherCharacter* archerFactory = new ArcherCharacter(); WizardCharacter* wizardFactory = new WizardCharacter(); ThiefCharacter* thiefFactory = new ThiefCharacter(); GoblrinMonster* goblrinFactory = new GoblrinMonster(); ReachMonster* reachFactory = new ReachMonster(); JobClass* knight = knightFactory->CreateJobClass(); JobClass* archer = archerFactory->CreateJobClass(); JobClass* wizard = wizardFactory->CreateJobClass(); JobClass* thief = thiefFactory->CreateJobClass(); TypeClass* goblrin = goblrinFactory->CreateTypeClass(); TypeClass* reach = reachFactory->CreateTypeClass(); Weapon* sword = knightFactory->CreateWeapon(); Weapon* bow = archerFactory->CreateWeapon(); Weapon* staff = wizardFactory->CreateWeapon(); thiefFactory->CreateWeapon(); knight->SetWeapon(sword); archer->SetWeapon(bow); wizard->SetWeapon(staff); thief->SetWeapon(sword); SohwanTest(goblrin); SohwanTest(reach); AttackTest(knight); AttackTest(archer); AttackTest(wizard); AttackTest(thief); } void AttackTest(JobClass* job) { if (!job->EquipCheck()) cout << " !" << endl; } void SohwanTest(TypeClass* type) { if (!type->MonsterCheck()) cout << "ȯ !" << endl; }
PHP
UTF-8
493
3.765625
4
[]
no_license
<?php function insertionSort2($n, $arr) { for ($i = 1; $i < $n; $i++) { $temp = $arr[$i]; for ($j = $i - 1; $j >= 0; $j--) { if ($arr[$j] > $temp) { // 还未到正确的位置,继续向前 $arr[$j + 1] = $arr[$j]; } else { // 到了正确的位置, break break; } } // 插入正确位置 $arr[$j + 1] = $temp; echo implode(" ", $arr) . "\n"; } }
C
UTF-8
2,797
2.96875
3
[]
no_license
/* ** EPITECH PROJECT, 2020 ** my_printf ** File description: ** convert_base */ #include <stdlib.h> #include "my.h" char **convert_less_than_2(char *nbr, char *base_f, char **tab, int d) { int result = 0; int retenue = 0; int i = 0; for (int a = 0; base_f[a] != nbr[0]; a += 1) result += 1; tab[d][i] = result + 48; return (tab); } char *convert_more_than_2(char *nbr, int d, char *base_f, char **tab) { int result = 0; int retenue = 0; int b = 0; int res = 0; int i = 0; res = my_strlen(base_f); for (b = 0; base_f[b] != nbr[0]; b += 1); result += res * b; for (int z = 2; z != my_strlen(nbr); z += 1) result = result * my_strlen(base_f); for (int i = 0; result > 0; i += 1) { tab[d][i] = (result % 10) + 48; result = result / 10; } my_revstr(tab[d]); return (tab[d]); } char *pre_convert_base(char *nbr, char *base_f, int res, int size) { char **tab = malloc(sizeof(char *) * (my_strlen(nbr) * 2)); int i = 0; int result = 0; int retenue = 0; int d = 0; for (; d != my_strlen(nbr) * 2; d += 1) tab[d] = malloc(sizeof(char) * (my_strlen(base_f) * my_strlen(nbr))); d = 0; while (my_strlen(nbr) > 1) { tab[d] = convert_more_than_2(nbr, d, base_f, tab); nbr += 1; d += 1; } tab = convert_less_than_2(nbr, base_f, tab, d); d += 1; for (int i = 0; i != d; i += 1) tab[i + 1] = infadd(tab[i], tab[i + 1]); return (tab[d]); } char *convert_base_before(char *nbr, char *base_f, char *base_to) { int res = 0; int size = my_strlen(base_f); int result = 0; int b = 0; char *endres; for (int i = 0; i < my_strlen(nbr); i += 1) { if (nbr[0] == base_f[0]) nbr += 1; } if (nbr == NULL) return (0); if (my_strlen(base_f) > my_strlen(base_to)) result = my_strlen(base_f) / my_strlen(base_to); else result = my_strlen(base_to) / my_strlen(base_f); endres = malloc(sizeof(char) * (result + 1)); endres = pre_convert_base(nbr, base_f, res, size); return (endres); } char *convert_to_next_base(char *base_to, char *n_res) { int maloc = my_strlen(base_to) + my_strlen(n_res); char *result = malloc(sizeof(char) * (5 * maloc)); int nbr = str_to_int(n_res); int tmp_int = 0; int tmp_nbr = 0; if (nbr == 0) { result[0] = base_to[0]; return (result); } for (int i = 0; nbr >= my_strlen(base_to); i += 1) { tmp_nbr = nbr / my_strlen(base_to); tmp_int = nbr - (tmp_nbr * my_strlen(base_to)); result[i] = base_to[tmp_int]; nbr = tmp_nbr; } my_revstr(result); result -= 1; result[0] = base_to[nbr]; return (result); }
Java
UTF-8
861
2.40625
2
[]
no_license
package by.bsu.calculator.constants; public final class ExpressionConstants { public final static String EXPRESSION_PATTERN = "^\\s*(\\-?(\\d+(\\.\\d+)?))\\s*([\\*\\+\\-\\/])\\s*(\\-?(\\d+(\\.\\d+)?))\\s*$"; public final static int FIRST_VALUE_WITH_SIGN_GROUP = 1; public final static int FIRST_VALUE_WITHOUT_SIGN_GROUP = 2; public final static int SECOND_VALUE_WITH_SIGN_GROUP = 5; public final static int SECOND_VALUE_WITHOUT_SIGN_GROUP = 6; public final static int SIGN_GROUP = 4; public final static String PLUS_SIGN = "+"; public final static String MINUS_SIGN = "-"; public final static String MULTIPLICATION_SIGN = "*"; public final static String DIVISION_SIGN = "/"; public final static int FIRST_VALUE_INDEX = 0; public final static int SECOND_VALUE_INDEX = 1; private ExpressionConstants(){} }
C++
UTF-8
832
2.546875
3
[]
no_license
// // Mark Pytel // CS5303 homework #7 // /* I understand that using, receiving or giving unauthorized assistance in writing this assignment is in violation of academic regulations and is subject to academic discipline, including a grade of 0 for this assignment with no chance of a making up the assignment, forfeiture of credit for the course, probation and dismissal from NYU. By submitting this work I am certifying that I did not cheat! */ #include <iostream> #include <fstream> using namespace std; int main() { ifstream in_stream; char next_symbol; in_stream.open("data7.txt"); if(in_stream.fail()) { cout<<"Error opening input file\n"; } in_stream.get(next_symbol); while(!(in_stream.eof())) { cout << next_symbol; in_stream.get(next_symbol); } in_stream.close(); return 0; }
Markdown
UTF-8
2,317
2.96875
3
[]
no_license
### Les registres. Les registres sont une partie très importante de tout processeur. La plupart des instructions assembleur vont concerner un ou plusieurs registres. Un registre est un minuscule composant électronique qui comporte 64 minuscules interrupteurs qui peuvent prendre les valeurs 0 ou 1. La taille des registres indique donc le type d'assembleur (32 ou 64 bits), les instructions ont toujours une taille de 32 bits mais elle vous autorisent à manipuler des données de la taille d'un bit, d'un ou 2 ou 4 ou 8 octets. Pour un processeur ARM 64 bits, nous disposons de 31 registres de 64 bits chacun : * 29 registres généraux de x0 à x28 * un registre de cadre fp ou x29 * un registre de lien contenant l’adresse de retour d’une routine lr ou x30 * et des registres spéciaux : * le registre de pile sp * le registre de compteur d’instruction pc * un registre particulier qui ne contient que 0 : xzr * le registre d'état et d'autres registres concernant les nombres en virgule flottante. Les registres d'usages généraux peuvent être utilisés pour toutes les opérations. Le registre de pile sp peut être modifié, le registre lr ne doit l'être qu'avec prudence !!. Le registre pc ne peut être modifié que par l'instruction pop. Dans les 29 registres généraux, certains servent aux passages des paramètres lors d’appel de fonctions de bibliothèques externes : il s’agit des registres x0 à x7, le code fonction est passé dans le registre x8. Les registres x0 à x17 ne sont pas sauvegardés par ces fonctions (y compris lors des appels à Linux). Les registres x18 à x28 et le registre lr sont sauvegardés. La partie basse de chaque registre cad les 32 bits de poids faible peuvent être utilisés avec les noms w0 à w29. Le registre spécial contenant 0 peut être manipulé en 32 bits avec le nom wzr. L'instruction principale de manipulation d'un registre est l'instruction mov qui soit met une valeur immediate dans le registre ```asm mov x0,100 ``` soit qui copie la valeur d'un registre dans un autre : ```asm mov x0,x1 ``` Attention : c'est la valeur de x1 qui est copiée dans x0. Remarque : en assembleur 64 bits le caractère # n'est pas obligatoire devant une valeur immediate. La valeur maximum est limitée à 0xFFFF.
Markdown
UTF-8
861
2.671875
3
[ "Apache-2.0" ]
permissive
# XML External entities ------- ## Example: """ Django’s serialization framework provides a mechanism for “translating” Django models into other formats. By which we can avoid XXE while using XML. Models can be easily translated to other formats such as XML, Json, YAML """ //Serialization of SomeModel defined in Models.py from django.core import serializers data = serializers.serialize("xml", SomeModel.objects.all()) //Save serialized data to file file.xml XMLSerializer = serializers.get_serializer("xml") xml_serializer = XMLSerializer() with open("file.xml", "w") as out: xml_serializer.serialize(Question.objects.all(), stream=out) data = xml_serializer.getvalue() //Deserialize the XML for obj in serializers.deserialize("xml", data): //Accessing object obj.object
Java
UTF-8
3,613
1.851563
2
[]
no_license
package com.midea.cloud.srm.supcooperate.orderreceive.controller; import com.github.pagehelper.PageInfo; import com.midea.cloud.common.enums.UserType; import com.midea.cloud.common.utils.AppUserUtil; import com.midea.cloud.common.utils.IdGenrator; import com.midea.cloud.srm.model.common.BaseController; import com.midea.cloud.srm.model.file.upload.entity.Fileupload; import com.midea.cloud.srm.model.suppliercooperate.orderreceive.dto.OrderReceiveDTO; import com.midea.cloud.srm.model.suppliercooperate.orderreceive.entity.OrderReceive; import com.midea.cloud.srm.model.rbac.user.entity.LoginAppUser; import com.midea.cloud.srm.supcooperate.orderreceive.service.OrderReceiveService; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.util.Assert; import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.List; import java.util.Map; /** * <pre> * 订单管理-》收货明细 * </pre> * * @author yancj9@meicloud.com * @version 1.00.00 * * <pre> * 修改记录 * 修改后版本: * 修改人: * 修改日期: Jan 30, 2021 10:31:54 AM * 修改内容: * </pre> */ @RestController @RequestMapping("/pm/receive") public class OrderReceiveController extends BaseController { @Autowired private OrderReceiveService orderReceiveService; /** * 获取 * @param id */ @GetMapping("/get") public OrderReceive get(Long id) { Assert.notNull(id, "id不能为空"); return orderReceiveService.getById(id); } /** * 批量新增或者修改 * @param orderReceiveList */ @PostMapping("/batchSaveOrUpdate") public void batchSaveOrUpdate(@RequestBody List<OrderReceive> orderReceiveList) throws Exception{ orderReceiveService.batchSaveOrUpdate(orderReceiveList); } /** * 批量删除 * @param ids */ @PostMapping("/bathDelete") public void bathDelete(@RequestBody List<Long> ids) throws IOException{ orderReceiveService.batchDeleted(ids); } /** * 分页查询 * @param orderReceiveDTO * @return */ @PostMapping("/listPage") public PageInfo<OrderReceive> listPage(@RequestBody OrderReceiveDTO orderReceiveDTO) { LoginAppUser loginAppUser = AppUserUtil.getLoginAppUser(); if(!StringUtils.equals(UserType.BUYER.name(), loginAppUser.getUserType())){ Assert.isTrue(false, "不是采购商"); } orderReceiveDTO.setCreatedId(loginAppUser.getUserId()); return orderReceiveService.listPage(orderReceiveDTO); } /** * 导入文件模板下载 * @return */ @RequestMapping("/exportExcelTemplate") public void exportExcelTemplate(HttpServletResponse response) throws IOException { orderReceiveService.exportExcelTemplate(response); } /** * 导入文件内容 * @param file */ @RequestMapping("/importExcel") public Map<String,Object> importExcel(@RequestParam("file") MultipartFile file, Fileupload fileupload) throws Exception { return orderReceiveService.importExcel(file,fileupload); } /** * 导出文件 * @param excelParam * @param response * @throws Exception */ @RequestMapping("/exportExcel") public void exportExcel(@RequestBody OrderReceiveDTO excelParam, HttpServletResponse response) throws Exception { orderReceiveService.exportExcel(excelParam,response); } }
C#
UTF-8
1,410
2.578125
3
[ "Apache-2.0" ]
permissive
using System; using System.Collections.Generic; using Windows.UI.Xaml.Navigation; namespace Ch9 { /// <summary> /// This is an implementation of <see cref="IStackNavigationService"/> that uses /// an inner <see cref="NavigationService"/> to do most operations. /// </summary> public sealed class StackNavigationService : IStackNavigationService { private readonly NavigationService _innerNavigationService; public StackNavigationService(NavigationService innerNavigationService) { _innerNavigationService = innerNavigationService ?? throw new ArgumentNullException(nameof(innerNavigationService)); } public event OnNavigatedEventHandler OnNavigated; public string CurrentPageKey => _innerNavigationService.CurrentPageKey; public bool CanGoBack => _innerNavigationService.CanGoBack; public void GoBack() { _innerNavigationService.GoBack(); OnNavigated?.Invoke(this, new OnNavigatedEventArgs(CurrentPageKey)); } public void NavigateTo(string pageKey) { _innerNavigationService.NavigateTo(pageKey); OnNavigated?.Invoke(this, new OnNavigatedEventArgs(pageKey)); } public void NavigateTo(string pageKey, object parameter) { _innerNavigationService.NavigateTo(pageKey, parameter); OnNavigated?.Invoke(this, new OnNavigatedEventArgs(pageKey)); } public IList<PageStackEntry> BackStack => _innerNavigationService.CurrentFrame.BackStack; } }
C#
UTF-8
905
2.578125
3
[]
no_license
using System.Configuration; using System.Data; using Oracle.ManagedDataAccess.Client; namespace mmo_pd_db_client.Manual.DB { public class DbConnection { public string connectionString { get; set; } public OracleConnection connection { get; set; } public DbConnection() { //connectionString = "Data Source=127.0.0.1/xe;User Id=mmo_pd;Password=mmo_pd;"; connectionString = ConfigurationManager.ConnectionStrings["ManualConnect"].ConnectionString; connection = new OracleConnection(connectionString); } public void OpenConnection() { if(connection.State != ConnectionState.Open) connection.Open(); } public void CloseConnection() { if(connection.State != ConnectionState.Closed) connection.Close(); } } }
TypeScript
UTF-8
1,712
3.578125
4
[]
no_license
export abstract class CheckingAccount { abstract open(initialAccount: number): Error | void; } export class BusinessCheckingAccount extends CheckingAccount { open(initialAccount: number) { if (initialAccount < 1000) { throw new Error('Business Account must have an initial deposit of 1000 Euros') } } } export class PersonalCheckingAccount extends CheckingAccount { open(initialAccount: number) { if (initialAccount <= 10) { throw new Error('Bussines Account must have an initial deposit of 10 Euros'); } } } const RobotCheckingAccount = { open: (initialAccount: number) => { if (initialAccount < 0) { throw new Error('Bussines Account must have an initial deposit of 0 Euros'); } } } class BankManager { createAccount(checkingAccount: CheckingAccount, initialAccount: number) { try { checkingAccount.open(initialAccount); if (checkingAccount instanceof BusinessCheckingAccount) { console.log('Business Account successfuly create!'); } else if (checkingAccount instanceof PersonalCheckingAccount) { console.log('Personal Account succefully created!') } else if (RobotCheckingAccount instanceof Object) { console.log('Pet Account succefully created!') } else { console.log('Not detected type of checkingAccount object'); } } catch (error) { throw error; } } } const businessAccount = new BusinessCheckingAccount(); const personalAccount = new PersonalCheckingAccount(); const bankManager = new BankManager(); bankManager.createAccount(personalAccount, 200); bankManager.createAccount(businessAccount, 5000); bankManager.createAccount(RobotCheckingAccount, 0);
Python
UTF-8
12,374
2.8125
3
[]
no_license
import numpy import os import copy import random import pickle from NN import NeuralNet from TicTacToe import TTT ios = True try: import console import TUi except: import basicInterface ios = False class RandomPlayer: def guess(self): return random.randint(0,9) def fill_genes(): a = numpy.random.uniform(-1, 1, 180) b = numpy.random.uniform(-1, 1, 513) c = numpy.random.uniform(-1, 1, 504) d = numpy.random.uniform(-1, 1, 19) new_genes = numpy.array([a, b, c, d]).transpose() return new_genes # class Subject: # # mutation_rate = 0.01 # # def __init__(self, dna = None, name=''): # # if dna is None: # self.genes = fill_genes() # else: # self.genes = dna # # self.name = name # self.wins = 0 # self.plays = 0 # self.nn = NeuralNet([18, 27, 18, 1]) # self.nn.weights = self.genes # self.fitness = 0 # # def guess(self, state, p2 = True): # inputs = [] # # for x in state: # if p2 and (x != 2): # inputs.append(int(not x)) # else: # inputs.append(x) # # inputs.append(1) # # return self.nn.guess(inputs) # # def mutate(self, ws=None): # if ws is None: # ws = copy.deepcopy(self.genes) # else: # ws = copy.deepcopy(ws) # # for ly in ws: # for wg in ly: # if random.random() > self.mutation_rate: # change = random.triangular(-0.3, 0.3) # wg += change # # return ws # # def reproduce(self): # new_genes = copy.deepcopy(self.genes) # # new_genes = self.mutate(new_genes) # # return Subject(new_genes) # # def calculate_fitness(self): # proportion_won = self.wins / self.plays # self.fitness = proportion_won # return self.fitness class Subject: mutation_rate = 0.01 def __init__(self, dna=None, name=''): if dna is None: self.genes = fill_genes() else: self.genes = dna self.name = name self.wins = 0 self.plays = 0 self.nn = NeuralNet([18, 27, 18, 1]) self.nn.weights = self.genes self.fitness = 0 def guess(self, state, p2=True): inputs = [] for x in state: if p2 and (x != 2): inputs.append(int(not x)) else: inputs.append(x) inputs.append(1) return self.nn.guess(inputs) def mutate(self, ws=None): if ws is None: ws = copy.deepcopy(self.genes) else: ws = copy.deepcopy(ws) for ly in ws: for wg in ly: if random.random() > self.mutation_rate: change = random.triangular(-0.3, 0.3) wg += change return ws def reproduce(self, other): new_genes = (self.genes + other.genes) / 2 new_subj = Subject(new_genes) return new_subj def calculate_fitness(self): proportion_won = self.wins / self.plays self.fitness = proportion_won return self.fitness class GA: def __init__(self, pop_size = 50): self.pop_size = pop_size self.generations = 0 self.population = [Subject(name = 'S-{}-{}'.format(self.generations, cont)) for cont in range(pop_size)] self.processed = {} def get_best_fitness(self, worst = False): fitness = [x for x in self.population] fitness.sort(key=lambda x: x.calculate_fitness()) if worst: return fitness[0] else: return fitness[-1] def average_fitness(self): fitness = [x.calculate_fitness() for x in self.population] return sum(fitness)/len(fitness) def prep_next_gen(self): gen_cont = self.generations + 1 new_gen = [] cont = 0 for _ in range(self.pop_size): parent1 = None parent2 = None while True: parent1 = random.choice(self.population) if random.random() < parent1.calculate_fitness(): break while True: parent2 = random.choice(self.population) if random.random() < parent2.calculate_fitness(): break new_subj = parent1.reproduce(parent2) new_subj.name = 'S-{}-{}'.format(gen_cont, cont) cont += 1 new_gen.append(new_subj) self.population = new_gen self.generations = gen_cont values = ['X', '0', '~'] def generation(self): # A for controls how many games each player will have. for step in range(20): # Makes a copy of the population and shuffles it # to randomize the pairs. current_pop = self.population[:] random.shuffle(current_pop) # Play until all of the subject have played a game. while len(current_pop) > 0: # Pick a pair of Subjects from the top of the list # to play against each other. player1 = current_pop.pop() player2 = current_pop.pop() # Increment the counter of plays of both Subjects player1.plays += 1 player2.plays += 1 # Initialize the board. current_t = TTT() players = [player1, player2] # Play til someone wins the game while current_t.who_won() == -1: # Gets the guess of the current player next_move = players[current_t.turn].guess(current_t.grid) if current_t.used(next_move): # If the guess is invalid, exit the game. # That player lost. break else: # If the move is valid, make it. current_t.move(next_move) #current_t.show_table() # The winner is calculated according to the boards function. winner = current_t.who_won() if winner == -1: # This is used when someone made a bad move. The player # that has not the turn wins. players[not current_t.turn].wins += 1 elif winner == 3: # If it's a tie, both win. player1.wins += 1 player2.wins += 1 # print("It's a tie") # print("X", player1.wins, "0", player2.wins) else: # If the game ended normally (one got three in a row) # increment the winner's wins counter. players[winner].wins += 1 # print(self.values[winner], 'won') print('Done') def get_best_against_random(self): for step in range(20): # Makes a copy of the population and shuffles it # to randomize the pairs. current_pop = self.population[:] # Play until all of the subject have played a game. while len(current_pop) > 0: # Pick a pair of Subjects from the top of the list # to play against each other. player1 = current_pop.pop() player2 = RandomPlayer() # Increment the counter of plays of both Subjects player1.plays += 1 # Initialize the board. current_t = TTT() players = [player1, player2] # Play til someone wins the game while current_t.who_won() == -1: # Gets the guess of the current player next_move = players[current_t.turn].guess(current_t.grid) if current_t.used(next_move): # If the guess is invalid, exit the game. # That player lost. break else: # If the move is valid, make it. current_t.move(next_move) # current_t.show_table() # The winner is calculated according to the boards function. winner = current_t.who_won() if winner == -1: # This is used when someone made a bad move. The player # that has not the turn wins. players[not current_t.turn].wins += 1 elif winner == 3: # If it's a tie, both win. player1.wins += 1 player2.wins += 1 # print("It's a tie") # print("X", player1.wins, "0", player2.wins) else: # If the game ended normally (one got three in a row) # increment the winner's wins counter. players[winner].wins += 1 # print(self.values[winner], 'won') # for x in a.population: # print(x.name + ": "+ str(x.wins) + "/" + str(x.plays) + " = " + str(x.wins/x.plays)) save_path = 'Saves' file_template = 'gen-{}-save.pkl' def save_state(obj): save_file = os.path.join(save_path, file_template.format(obj.generations)) if not os.path.isdir(save_path): os.mkdir(save_path) if not os.path.exists(save_file): os.system('touch ' + save_file) str_save = pickle.dumps(obj) with open(save_file, 'wb') as f: f.write(str_save) genetic_a = GA() def summary(ga): print('-'*40) print('Generation: ' + str(ga.generations)) best_f = ga.get_best_fitness().fitness print('Best fitness: ' + str(best_f)) print('-'*40) def step_generations(count = 1, prep = True, random_scoring = True): while count > 0: print('Starting Generation', genetic_a.generations) if random_scoring: genetic_a.generation() else: genetic_a.get_best_against_random() if genetic_a.generations % 50 == 0: # save_state(genetic_a) pass summary(genetic_a) if prep: genetic_a.prep_next_gen() count -= 1 if ios: interface = TUi.show else: interface = basicInterface.show def main(): while True: print('Funciones:') print('1- Avanzar una generacion') print('2- Avanzar n generaciones') print('3- Guardar estado actual') print('4- Jugar contra el mejor') print('5- Jugar contra el peor') print('6- Salir') response = input() num_generations = 0 if response == '1': num_generations = 1 elif response == '2': print('¿Cuantas generaciones?') try: num_generations = int(input()) except ValueError: continue elif response == '3': save_state(genetic_a) elif response == '4': step_generations(1, False) best = genetic_a.get_best_fitness() try: interface(best) except KeyboardInterrupt: pass continue elif response == '5': step_generations(1, False) best = genetic_a.get_best_fitness() try: interface(best, True) except KeyboardInterrupt: pass continue elif response == '6': break if ios: console.clear() else: os.system('cls') step_generations(num_generations) if __name__ == '__main__': main()
C++
UTF-8
1,740
2.515625
3
[]
no_license
#include "app/ModelLoad.h" #include <glm/ext/matrix_clip_space.hpp> #include <glm/ext/matrix_transform.hpp> bool ModelLoad::setup() { const char* vertexCode = R"##( #version 460 core layout (location = 0) in vec3 aPos; layout (location = 1) in vec3 aNormal; layout (location = 2) in vec2 aTexCoords; out vec2 TexCoords; uniform mat4 model; uniform mat4 view; uniform mat4 projection; void main() { TexCoords = aTexCoords; gl_Position = projection * view * model * vec4(aPos, 1.0); } )##"; const char* fragmentCode = R"##( #version 460 core out vec4 FragColor; in vec2 TexCoords; uniform sampler2D texture_diffuse1; void main() { //FragColor = texture(texture_diffuse1, TexCoords); FragColor = vec4(1.0, 0.0, 0.0, 1); } )##"; models.push_back(Model{"data/backpack/backpack.obj"}); shader = std::make_unique<Shader>(vertexCode, fragmentCode); glClearColor(0.2f, 0.0f, 0.0f, 0.f); glEnable(GL_DEPTH_TEST); return true; } void ModelLoad::render() { // Clear color buffer glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); shader->setActive(); glm::mat4 model = glm::mat4(1.0f); model = glm::translate(model, glm::vec3(1.0f, 1.0f, 1.0f)); // translate it down so it's at the center of the scene model = glm::scale(model, glm::vec3(1.0f, 1.0f, 1.0f)); // it's a bit too big for our scene, so scale it down shader->set("model", model); glm::mat4 view = getCamera().getView(); shader->set("view", view); glm::mat4 projection = getWindow().getProjection(45.f, 0.1f, 100.f); shader->set("projection", projection); // render the loaded model for (const auto& model : models) { model.draw(*shader); } }
C#
UTF-8
523
3.03125
3
[]
no_license
static async Task<int> GetTotalSizeAsync(params string[] urls) { if (urls == null) return 0; var tasks = urls.Select(GetSizeAsync); var sizes = await TaskEx.WhenAll(tasks); return sizes.Sum(); } static async Task<int> GetSizeAsync(string url) { try { var str = await new WebClient().DownloadStringTaskAsync(url); return str.Length; } catch (WebException) { return 0; } }
JavaScript
UTF-8
2,374
2.875
3
[ "Apache-2.0" ]
permissive
// This is the main app.js. We're using the cylon library here. One nice thing // about the cylon library is that you can talk to various device types such as // Edison, Beaglebone, RasPi, etc. without using device specific language. var Cylon = require('cylon'); //include node.js packages here if you want (see npmjs.org for packages) Cylon.robot({ connections: { edison: { adaptor: 'intel-iot' } }, //in this section you list all of the sensors, lights, etc. that you will use devices: { // pin: { driver: 'direct-pin', pin: 2 }, // led: { driver: 'led', pin: 13 }, led: { driver: 'led', pin: 4 }, touch: { driver: 'button', pin: 3 }, // analogSensor: { driver: 'analogSensor', pin: 0 }, lightSensor: { driver: 'analogSensor', pin: 0 }, buzzer: { driver: 'direct-pin', pin: 2} }, // this is where you write the main part of your app work: function (my) { /* working with a direct pin */ //var digitalValue = my.pin.digitalRead(); //read digital (high/low) value //my.pin.digitalWrite(1); //set a digital pin high //my.pin.digitalWrite(0); //set a digital pin low //var analogValue = my.pin.analogRead(); //read analog value //my.pin.analogWrite(567); //write an analog value /* toggle the LED every second */ // every((1).second(), function () { // my.led.toggle(); // }); // console.log(JSON.stringify(my.buzzer.analog_write)); my.lightSensor.on('analogRead', function(val) { var brightness = val.fromScale(0, 1024).toScale(0, 1) | 0; console.log('brightness => ', brightness); // my.led.brightness(brightness) // my.led.brightness(brightness); }); my.touch.on('press', function() { my.led.turnOn(); // my.buzzer.analogWrite(10); my.buzzer.digitalWrite(1); }); my.touch.on('release', function() { my.led.turnOff(); // my.buzzer.analogWrite(0); my.buzzer.digitalWrite(0); }); /* analog input (temperature sensors, light sensors, etc.) * the analogSensor has some advantages over a direct-pin like limits */ //console.log('sensor value: ' + my.analogSensor.analogRead()); } }).start();
Markdown
UTF-8
3,307
3
3
[]
no_license
# Locating-Artifacts-of-Deepfake-Images-in-Frequency-Domain-with-Butterworth-Filter "the code of paper Locating Artifacts of Deepfake Images in Frequency Domain with Butterworth Filter >Generative Adversarial Networks (GANs) have achieved impressive results for many face-swap applications which can generate realistic images. These synthesized images can even confuse human eyes. Deepfake images recognition has been widely researched in the image domain and recognition based on frequency domain also achieved surprising results. However, these methods based on frequency directly use the entire frequency domain. In this paper we transform the deepfake image into the frequency domain, and use Butterworth filter to find out the most effective frequency range for identifying the image as real or fake. We first use high-pass and low-pass filters to determine the upper and lower boundaries of the effective frequency band, and then use band-pass filters to narrow the range. The results show that the effective frequency band is 1- 35, and in the one-dimensional power spectrum of this frequency band, the real and fake image curves show obvious differences. In addition, we design a SVM classifier based on the frequency domain using the effective frequency band we found, and test it on the mainstream deepfake dataset. The results suggest that all the mainstream datasets have frequency domain defects, and the frequency band we find can effectively improve the classification accuracy." ## datasets We utilize these three popular datasets: [FaceForensics++](https://github.com/ondyari/FaceForensics/) [UADFV](https://github.com/danmohaha/WIFS2018_In_Ictu_Oculi) [DeepFake-TIMIT](https://www.idiap.ch/dataset/deepfaketimit) After downloading the data, you need to use extract_test.py to extract the video frame, and then use recogize.py to extract the face ## Experiments After you have converted the data files you can train a classifer to locate the effective frequency band: ``` usage: normalize_deepfake_fillter.py [-h] [-true TRUEDIR] [-false FALSEDIR] [-t {high,low,bandpass}] [-n NUM_IMAGES] [-d CUT_OFF [CUT_OFF ...]] [-w BANDWIDTH [BANDWIDTH ...]] [-o FILTER_ORDER [FILTER_ORDER ...]] [--feature_num FEATURE_NUM] output_path positional arguments: output_path the location of training model optional arguments: -h, --help show this help message and exit --truedir, -true Real dataset to load --falsedir, -false Fake dataset to load --type, -t the type of filter to use; Default: high. --num_images, -n the number of images to use; Default: 3000. --cut_off, -d Cut-off frequency of filter; Default: [15,20]. --bandwidth, -w Bandwidth of band-pass filter; Default: [10,20]. --filter_order, -o the order of filter --feature_num the number of 1D features to use Example: python normalize_deepfake_filter.py ./mode/ -t high -n 1000 -d 10 20 -w 10 20 -o 1 5 10 -true ./data/fake_videos/real_images/cropped/ -false ./data/fake_videos/fake_images/cropped/ ```
Python
UTF-8
55
3.109375
3
[]
no_license
a = "Hello World" for i in range(0, 100): print(a)
C#
UTF-8
1,983
2.90625
3
[ "MIT", "Apache-2.0" ]
permissive
using System; using System.Collections.Generic; using System.Net.Http; namespace GoodToCode.Extensions.Net { /// <summary> /// Builds an HttpClient object /// </summary> /// <returns></returns> /// <remarks></remarks> public class HttpClientBuilder : HttpClient { /// <summary> /// MaxResponseContentBufferSize /// </summary> public static long MaxResponseContentBufferSizeDefault { get; } = 2560000; /// <summary> /// Default user agent string /// </summary> public static KeyValuePair<string, string> UserAgentDefault { get; } = new KeyValuePair<string, string>("user-agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)"); /// <summary> /// Constructor parameterless /// </summary> public HttpClientBuilder() : this(MaxResponseContentBufferSizeDefault, UserAgentDefault) { } /// <summary> /// Builds a HttpClient with specific content buffer size and request header /// </summary> public HttpClientBuilder(Int64 maxResponseContentBufferSize, KeyValuePair<string, string> additionalHeader) : base() { base.MaxResponseContentBufferSize = maxResponseContentBufferSize; base.DefaultRequestHeaders.Add(additionalHeader.Key, additionalHeader.Value); } /// <summary> /// Builds a HttpClient with specific content buffer size and request header /// </summary> public HttpClientBuilder(Int64 maxResponseContentBufferSize, IEnumerable<KeyValuePair<string, string>> additionalHeaders) : base() { base.MaxResponseContentBufferSize = maxResponseContentBufferSize; foreach(var item in additionalHeaders) { base.DefaultRequestHeaders.Add(item.Key, item.Value); } } } }
Python
UTF-8
1,336
3.15625
3
[]
no_license
# Library for opening url and creating # requests import urllib.request # pretty-print python data structures from pprint import pprint # for parsing all the tables present # on the website from html_table_parser import HTMLTableParser # for converting the parsed data in a # pandas dataframe import pandas as pd # Opens a website and read its # binary contents (HTTP Response Body) def url_get_contents(url): # Opens a website and read its # binary contents (HTTP Response Body) #making request to the website req = urllib.request.Request(url=url) f = urllib.request.urlopen(req) #reading contents of the website return f.read() # defining the html contents of a URL. xhtml = url_get_contents('https://clearquest.alstom.hub/cqweb/restapi/CQat/atvcm/QUERY/47363098?format=HTML&noframes=true').decode('utf-8') # Defining the HTMLTableParser object #p = HTMLTableParser() # feeding the html contents in the # HTMLTableParser object #p.feed(xhtml) # Now finally obtaining the data of # the table required #pprint(p.tables[1]) # converting the parsed data to # datframe print("\n\nPANDAS DATAFRAME\n") df_list = pd.read_html('C:/PD/MooN/CR&CQ/Automation/cq-moon-cr.html') df = df_list[-1] print(df_list) #print(pd.DataFrame(p.tables[1]))
Python
UTF-8
452
3.484375
3
[]
no_license
import math coordinates = [int(x) for x in input().split()] goat = coordinates[:2] bottom_left = coordinates[2:4] top_right = coordinates[4:] x = 0 y = 0 if goat[0] < bottom_left[0]: x = bottom_left[0] elif goat[0] < top_right[0]: x = goat[0] else: x = top_right[0] if goat[1] < bottom_left[1]: y = bottom_left[1] elif goat[1] < top_right[1]: y = goat[1] else: y = top_right[1] print(math.sqrt((x-goat[0])**2+(y-goat[1])**2))
C#
UTF-8
1,130
2.609375
3
[ "MIT" ]
permissive
using System; using System.Net.WebSockets; using System.Threading; using System.Threading.Tasks; namespace WebRocket.Client.Wrappers { public class ClientWebSocket : IClientWebSocket { public ClientWebSocket(System.Net.WebSockets.ClientWebSocket socket) { mSocket = socket; } public WebSocketState State => mSocket.State; public Task SendAsync(ArraySegment<byte> buffer, WebSocketMessageType messageType, bool endOfMessage, CancellationToken token) { return mSocket.SendAsync(buffer, messageType, endOfMessage, token); } public Task ConnectAsync(Uri uri, CancellationToken token) { return mSocket.ConnectAsync(uri, token); } public async Task<IWebSocketReceiveResult> ReceiveAsync(ArraySegment<byte> buffer, CancellationToken token) { return new WebSocketReceiveResult(await mSocket.ReceiveAsync(buffer, token)); } public Task CloseAsync(WebSocketCloseStatus status, string description, CancellationToken token) { return mSocket.CloseAsync(status, description, token); } private readonly System.Net.WebSockets.ClientWebSocket mSocket; } }
Java
UTF-8
1,741
2.75
3
[]
no_license
package cz.cuni.mff.d3s.demo.uptime; import cz.cuni.mff.d3s.demo.SimulationConstants; public class SingleEventUptimeDecider implements ComponentUptimeDeciderGenerator { private int iteration; private int numToAdd; private int numToKill; public SingleEventUptimeDecider(int iteration, int numToAdd, int numToKill) { this.iteration = iteration; this.numToAdd = numToAdd; this.numToKill = numToKill; } @Override public void generateUptimeData(boolean[][] uptimeData) { for (int iteration = 1; iteration < uptimeData.length; iteration++) { for(int componentId = 0; componentId < SimulationConstants.SoldierCount; componentId++) { // Copy state from the previous iteration uptimeData[iteration][componentId] = uptimeData[iteration - 1][componentId]; } if (iteration == this.iteration) { int[] indicesToAdd = new int[numToAdd]; for (int i = 0; i < numToAdd; i++) { indicesToAdd[i] = ComponentUptimeDecider.selectRandomWithState(uptimeData, iteration, false); if (indicesToAdd[i] >= 0) uptimeData[iteration][indicesToAdd[i]] = true; } for (int i = 0; i < numToAdd; i++) { if (indicesToAdd[i] >= 0) uptimeData[iteration][indicesToAdd[i]] = false; } int[] indicesToRemove = new int[numToKill]; for (int i = 0; i < numToKill; i++) { indicesToRemove[i] = ComponentUptimeDecider.selectRandomWithState(uptimeData, iteration, true); if (indicesToRemove[i] >= 0) uptimeData[iteration][indicesToRemove[i]] = false; } for (int i = 0; i < numToAdd; i++) { if (indicesToAdd[i] >= 0) uptimeData[iteration][indicesToAdd[i]] = true; } } } } }
Markdown
UTF-8
1,316
2.875
3
[ "MIT" ]
permissive
--- layout: post title: Using functional programming for Exception Handling bigimg: /img/image-header/factory.jpg tags: [Functional Programming] --- <br> ## Table of contents - [Given problem](#given-problem) - [Solution for using functional programming]() - [Benefits and Drawbacks]() - [When to use]() - [Wrapping up](#) <br> ## Given problem <br> ## Solution for using functional programming <br> ## Benefits and Drawbacks <br> ## When to use <br> ## Wrapping up <br> Refer: [https://pawelwlodarski.gitbooks.io/functional-programming/content/side_effects_in_fp.html](https://pawelwlodarski.gitbooks.io/functional-programming/content/side_effects_in_fp.html) [https://www.ibm.com/developerworks/library/j-ft13/index.html](https://www.ibm.com/developerworks/library/j-ft13/index.html) [https://medium.com/techtron/functional-errors-handling-1d1b4688769d](https://medium.com/techtron/functional-errors-handling-1d1b4688769d) [https://belief-driven-design.com/functional-programming-with-java-exception-handling-e69997c11d3/](https://belief-driven-design.com/functional-programming-with-java-exception-handling-e69997c11d3/) [https://dzone.com/articles/exception-free-code-using-functional-approach](https://dzone.com/articles/exception-free-code-using-functional-approach)
Python
UTF-8
334
2.90625
3
[]
no_license
user_result = {'id':'아이디', 'pw':'패스워드비밀번호', 'name':'이름'} item_list = ['id', 'pw', 'name'] session_list = {} for item in item_list: this = user_result[item] session_list[item] = this print('--------------') print(session_list) print('--------------') session_list['id'] = 'skmdks' print(session_list)
C++
UTF-8
340
2.75
3
[]
no_license
#pragma once #include "AuxStructures/Point.h" #include <vector> template<typename Node, typename Point> class EstructuraBase { protected: Node* root; public: virtual void insert(Point) = 0; virtual Node* search(Point) = 0; virtual std::vector<Node*> range(Point,Point) = 0; virtual Point* nearest_neighbor(Point) = 0; };
Python
UTF-8
4,505
3
3
[]
no_license
#Part1 # Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd np.random.seed(10) # Importing the dataset dataset = pd.read_csv('Churn_Modelling.csv') X= dataset.iloc[:, 3:13].values y = dataset.iloc[:, 13].values # Encoding categorical data # Encoding the Independent Variable from sklearn.preprocessing import OneHotEncoder from sklearn.compose import ColumnTransformer from sklearn.preprocessing import LabelEncoder, OneHotEncoder # 3 Classes Encoding ct = ColumnTransformer(transformers=[('encoder',OneHotEncoder(),[1])], remainder = 'passthrough') X= np.array(ct.fit_transform(X)) # 2 Classes Encoding labelencoder_X_2 = LabelEncoder() X[:, 4] = labelencoder_X_2.fit_transform(X[:, 4]) X=np.around(X.astype(np.double),1) #delete the float and do the round X=X[:,1:] # Splitting the dataset into the Training set and Test set from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0) # Feature Scaling from sklearn.preprocessing import StandardScaler sc = StandardScaler() X_train = sc.fit_transform(X_train) X_test = sc.transform(X_test) #Part2 #Import import tensorflow import keras from keras.models import Sequential from keras.layers import Dense from keras.layers import Dropout #Initialising the ANN classifier = Sequential() #Input Layer and Hidden layer classifier.add(Dense(units = 6, kernel_initializer = 'uniform', activation = 'relu', input_dim = 11)) #Second Hidden Layer classifier.add(Dense(units = 6, kernel_initializer = 'uniform', activation = 'relu')) classifier.add(Dropout(p = 0.1)) #Output Layer classifier.add(Dense(units = 1, kernel_initializer = 'uniform', activation = 'sigmoid')) #Compling the ANN (how to optimize weight) classifier.compile(optimizer='adam', loss='binary_crossentropy', metrics = ['accuracy']) classifier.save('model') #Fitting the ANN to the Trainning set 'classifier.fit(X_train, y_train, batch_size = 10, epochs = 100)' train_history=classifier.fit(X_test, y_test, validation_split=0.1, batch_size = 10, epochs = 100) # Part 3 - Making predictions and evaluating the model # Predicting the Test set results y_pred = classifier.predict(X_test) y_pred = (y_pred > 0.5) # Making the Confusion Matrix- from sklearn.metrics import confusion_matrix,accuracy_score cm = confusion_matrix(y_test, y_pred) accuracy_score(y_test,y_pred) '''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' # Part 4 - Train model v.s. Validation model # Diagram def show_train_history (train_history,train,validation): plt.plot(train_history.history[train]) plt.plot(train_history.history[validation]) plt.title("Train History") plt.ylabel(train) plt.xlabel("Epoch") plt.legend(['train', 'validation'], loc='upper left') plt.show() show_train_history(train_history,'accuracy','val_accuracy') show_train_history(train_history,'loss','val_loss') # Confusion_Matrix import confusion_matrix import matplotlib.pyplot as plt from sklearn.metrics import ConfusionMatrixDisplay display_labels=['Stay','Leave'] disp = ConfusionMatrixDisplay(cm, display_labels) disp = disp.plot(include_values=bool) plt.show() ''' # Part 5 - Adjust Parameter from sklearn.model_selection import GridSearchCV from keras.wrappers.scikit_learn import KerasClassifier def build_classifier(optimizer): classifier = Sequential() classifier.add(Dense(units = 6, kernel_initializer = 'uniform', activation = 'relu', input_dim = 11)) classifier.add(Dropout(p = 0.1)) classifier.add(Dense(units = 6, kernel_initializer = 'uniform', activation = 'relu')) classifier.add(Dropout(p = 0.1)) classifier.add(Dense(units = 1, kernel_initializer = 'uniform', activation = 'sigmoid')) classifier.compile(optimizer = optimizer, loss = 'binary_crossentropy', metrics = ['accuracy']) return classifier classifier = KerasClassifier(build_fn = build_classifier) parameters = {'batch_size': [25, 32], 'epochs': [3, 5], 'optimizer': ['adam', 'rmsprop']} grid_search = GridSearchCV(estimator = classifier, param_grid = parameters, scoring = 'accuracy', cv = 2) grid_search = grid_search.fit(X_train, y_train) best_parameters = grid_search.best_params_ best_accuracy = grid_search.best_score_ '''
JavaScript
UTF-8
2,056
2.59375
3
[]
no_license
import {Layer, Registerable, Serializable, LayerProxy, expose} from '../../..'; describe('Parent layer', () => { test('Parent call', () => { class BaseMath extends Serializable(Registerable()) { constructor({a, b, ...object} = {}, {isDeserializing} = {}) { super(object, {isDeserializing}); if (!isDeserializing) { this.a = a; this.b = b; } this.constructor.setInstance(this); } serialize() { return { ...super.serialize(), a: this.a, b: this.b, lastResult: this.lastResult }; } deserialize({a, b, lastResult} = {}) { this.a = a; this.b = b; this.lastResult = lastResult; } // Let's simulate an identity map static getInstance(_object, _previousInstance) { return this._instance; } static setInstance(instance) { this._instance = instance; } } const backendProxy = (() => { // Backend @expose() class Math extends BaseMath { @expose() static sum(a, b) { return a + b; } @expose() sum() { const result = this.a + this.b; this.lastResult = result; return result; } } const layer = new Layer({Math}, {name: 'backend'}); return new LayerProxy(layer); })(); // Frontend class Math extends BaseMath { static sum(a, b) { return super.sum(a, b); } sum(a, b) { return super.sum(a, b); } } const layer = new Layer({Math}, {name: 'frontend', parent: backendProxy}); expect(layer.getParent()).toBe(backendProxy); expect(layer.hasParent()).toBe(true); expect(layer.Math.hasParentLayer()).toBe(true); expect(layer.Math.sum(1, 2)).toBe(3); const math = new layer.Math({a: 2, b: 3}); expect(math.hasParentLayer()).toBe(true); const result = math.sum(); expect(result).toBe(5); expect(math.lastResult).toBe(5); }); });
Shell
UTF-8
1,949
3.53125
4
[]
no_license
#!/bin/sh function showForm() { cat <<EOT <h1 class="page-header">"xoops_trust_path" Settting</h1> <form method="get" class="form-horizontal"> <div class="control-group"> <label class="control-label" for="TRUST">xoops_trust_path : </label> <div class="controls"> <input id="TRUST" name="TRUST" class="span6" style="height:30px" type="text" value="$1"> <p class="help-block">Please set server path of your "xoops_trust_path".</p> </div> </div> <div class="form-actions"> <input type="submit" class="btn btn-primary" value="OK &amp; Upload &amp; Please Wait"> </div> </form> EOT } # http header echo -e "Content-Type: text/html; charset=UTF-8\n" # decode QUERY_STRING if [ $QUERY_STRING ]; then saveIFS=$IFS IFS='=&' parm=($QUERY_STRING) IFS=$saveIFS for ((i=0; i<${#parm[@]}; i+=2)) do declare ${parm[i]}=${parm[i+1]} >/dev/null 2>&1 done if [ ! $TRUST ]; then P=`cd $@;pwd` fi fi # output echo "<html><head>" echo "<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet">" echo "<script src="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/js/bootstrap.min.js"></script>" echo "</head><body>" if [ ! $TRUST ]; then if [ ! $P ]; then P="`dirname \`pwd\``/xoops_trust_path" fi showForm $P else TRUST=`echo $TRUST | sed 's/%2F/\//g'` MSG=`mkdir $TRUST 2>&1` if [ -d $TRUST ]; then rm ./install.cgi echo "<h1 class="page-header">Getting XOOPS X (ten) and extracting...</h1>" echo "<pre style=\"height:60%;overflow:auto;\">" curl xoopsx.github.io/installer/install.sh|sed "s#<T>#$TRUST#"|sh 2>&1|cat echo "</pre>" echo "<div class="form-actions"><a href=\"./install/index.php\" class=\"btn btn-success\">Goto your XOOPS installer</a></div>" else echo "<div><span class=\"label label-important\">$MSG</span></div>" declare P="`dirname \`pwd\``/xoops_trust_path" showForm $P fi fi echo "</body></html>"
Markdown
UTF-8
1,886
2.65625
3
[]
no_license
# Projeto de Servidor TCP e Client ### 1 - Clonar repositório para maquina local ### 2 - Subir o Servidor TCP + Acessar a pasta *tcp-project/java-server-project* pelo cmd ou powershell + Rodar comando: `mvn clean install` + Rodar comando: `mvn exec:java "-Dexec.mainClass=com.personal.tcp.Server"` ### 3 - Subir o Client TCP + Acessar a pasta *tcp-project/java-client-project* pelo cmd ou powershell + Rodar comando: `mvn clean install` + Rodar comando: `mvn exec:java "-Dexec.mainClass=com.personal.tcp.Client"` ### 4 - Enviar Mensagens + No terminal do client, escrever as mensagens no formato Hex e apertar Enter para enviar ### 5 - Verificar banco de dados H2 + Acessar o link `http://localhost:9092/` pelo browser + Clicar em connect + Realizar operações nas tabelas: USER_INFO MESSAGES ### 6 - Verificar arquivo de Logs + Arquivo `messages.log` é gerado na pasta java-server-project ### 7 - Exemplos | Cenário | Valor | |---------------------------------|-------------------------------------------------------------------| | Mensagem com Texto | 0A 10 A1 48 65 6C 6C 6F 20 57 6F 72 6C 64 DC 0D | | Mensagem com User Info | 0A 15 A2 20 7A C3 0C 4D 69 63 68 65 6C 20 52 65 69 70 73 16 0D | | Mensagem com Timezone | 0A 16 A3 41 6D 65 72 69 63 61 2F 53 61 6F 5F 50 61 75 6C 6F CD 0D | | Mensagem com Timezone Inválida | 0A 16 A3 41 6D 65 72 69 63 61 2F 53 61 6F 5F 50 61 75 6C 6D C3 0D | | Mensagem com Frame Inválido | 0A 10 A0 48 65 6C 6C 6F 20 57 6F 72 6C 64 81 0D | | Mensagem com CRC inválido | 0A 10 A1 48 65 6C 6C 6F 20 57 6F 72 6C 64 00 0D | | Mensagem com Formato inválido | Test |
Python
UTF-8
14,100
3.828125
4
[ "MIT" ]
permissive
import copy class AStarTrack(object): # 初始化类 def __init__(self,x,y,print=None): self._x = x self._y = y self._print = print #print用于判断是否需要打印地图至cmd self._open = [] #open列表会记录所有被扫描过的点的坐标,这些坐标会被优先处理 self._close = [] #close列表会记录所有已经计算过的点的坐标,这些坐标不会再被计算 self._trace = [] #这个列表会在寻路完成后用于记录寻路结果 # self.map与self._map的区别: # self.map是存储了地图大小以及障碍物信息的地图 # self._map是用来计算的地图,计算后会重新初始化为self.map self.map = [[0 for i in range(y)] for i in range(x)] self._map = self.map self._start = None self._end = None ''' 地图相关的方法 ---------------------------------------------------------------------------- 地图是一个二维列表,通过x和y可以访问到每一个坐标点。 列表内0代表空格,没有障碍也没有角色 列表中"o"代表障碍物(obstacle),"e"代表终点(end) 列表中被计算到的点会以元组的方式储存FGH以及父节点的值: (F的值,G的值,H的值,(父节点x,父节点y)) ''' # 传入一个turple作为坐标,将列表的对应坐标修改为障碍 def obstacle(self,pos): self._map[pos[0]][pos[-1]] = "o" self.map = self._map # 返回地图的二维数组 def getMap(self): return self.map # 以美观的方式打印地图 def printMap(self): for x in range(self._y): for y in range(self._x): # 如果节点为开始坐标 if (y,x) == self._start: print("☆",end=" ") # 如果节点是结束坐标 elif (y,x) == self._end: print("★",end=" ") # 如果节点在open列表中 elif (y,x) in self._open: print("☑ ",end=" ") # 如果节点在close列表中 elif (y,x) in self._close: print(" ",end=" ") # 如果节点是障碍 elif self.map[y][x] == "o": print("■",end=" ") # 如果节点内数据为0 else: print("□",end=" ") print() # 适用于寻路完成后打印路线 def printTrack(self): for x in range(self._y): for y in range(self._x): # 如果节点为开始坐标 if (y,x) == self._start: print("☆",end=" ") # 如果节点是结束坐标 elif (y,x) == self._end: print("★",end=" ") # 如果节点为路径之一 elif (y,x) in self._trace: print("• ",end=" ") # 如果节点是障碍 elif self.map[y][x] == "o": print("■",end=" ") # 如果节点内数据为0 else: print("□",end=" ") print() # 以程序的方式打印地图 def printRawMap(self): for x in range(self._y): for y in range(self._x): print(self.map[y][x],end=" ") print() ''' 与寻路相关的方法 ---------------------------------------------------------------------------- 实体是寻路的对象 传入起点、终点即可寻路 寻路时会以起点为中心向外寻路,绕开所有障碍物直到到达终点 寻路完成后,返回前进的道路的每一步的坐标(turple)和总步数 使用printTrack方法可以打印带有路径的地图 ''' # 初始化地图 def mapReinit(self): self.map = copy.deepcopy(self._map) #使用深拷贝复制地图用于计算 self._open.clear() self._close.clear() self._trace.clear() self._start = None self._end = None # 设定起点和终点,然后开始寻路 # 传入turple作为起始、结束坐标 def target(self,start,end): self.mapReinit() #首先重新初始化 # 将起始、结束坐标存入类属性中 self._start = start self._end = end # 向地图中存放每一格的信息 self.map[start[0]][start[-1]] = (self.attr(start,None),(start[0],start[1])) self.map[end[0]][end[-1]] = "e" # 把开始坐标放入open中以便寻路 self._open.append(start) #开始寻路 minFpos = self.track() for i in range(self._x * self._y): minFpos = self.track(minFpos) if type(minFpos) == list: return minFpos # 计算F G H的值 def attr(self,pos,father): # print("-----------------adding attr---------------------") # 初始化 x = pos[0] y = pos[1] # G值计算 —— 移动步数 # 如果是刚开始那一格那就不管他,步数只能是0 if pos == self._start: g = 0 else: g = self.map[father[0]][father[1]][0][1] + 1 # H值计算 —— 终点的预估距离 h = abs(pos[0]-self._end[0]) + abs(pos[1]-self._end[1]) # F值计算 —— 移动优先值 f = g + h # 返回F G H的值 return (f,g,h) # 寻路 # father代表父节点,子节点是由父节点衍生出的节点,父节点就是上一个被检查的节点 def track(self,father=None): # 首先处理trace数据,如果trace不为空则证明寻路已完成。此时只需将trace数据向上抛回即可 if self._trace: return self._trace # 取出节点 # 首次运行时的初始化(如果没有父节点,说明这个节点是初次运行) if father == None: father = self._start x = self._start[0] y = self._start[1] # 否则就是第二次以后的运行了,这样的话就一定会有父节点 else: x = father[0] y = father[1] # 扫描 “四个” 周边方块的信息,随后向坐标内保存F G H的值 # 四个元组代表扫描的方向:上、左、下、右 for i in (0,-1),(-1,0),(0,1),(1,0): # 检查一下有没有超出边界防止出现ListOutOfRange错误 if x+i[0] >= 0 and y+i[1] >= 0 and x+i[0] < self._x and y+i[1] < self._y: scanpt = self.map[x+i[0]][y+i[1]] #scanpt会存储被扫描的点的数据 # 被检查的点是否为路径终点 if scanpt == "e": return self.trace(father) # 判断: # 节点有无障碍、是否在close列表中 # 现在还不是很清楚open列表是否需要检查,暂定为需要检查(跳过open列表可以减少部分计算量 elif scanpt == 0 and scanpt not in self._close: self._open.append((x+i[0],y+i[1])) #将节点信息放入open列表中 self.map[x+i[0]][y+i[1]] = (self.attr((x+i[0],y+i[1]),father),(father)) #向地图内添加F G H与父坐标的信息 # 比对节点中F值最小的一个,这一个节点最有希望成为最短路径中的一个节点 # 不过在开始比对之前还有一件事要做 if len(self._open) == 0: #如果open列表里没有新的坐标了,说明无路可走了 print("No matched way") return "fail" # 通过比对寻找子节点 son = self.compare() # 现在可以打印地图了 # print("-----------------tracking---------------------") if self._print == "raw": self.printRawMap() print("------------------------------------------------------------") if self._print == "map": self.printMap() print("------------------------------------------------------------") # 将节点从open中移至close self._open.remove(son) #把这个找到的坐标从open里移出去 self._close.append(son) #然后把它加入到close列表中,以后不再判断 # 继续迭代,检查下一个节点 return son # 这个方法用于比对所有open中的节点并找出期望最优路径 def compare(self): # 开始比对 # comp会存放所有节点对应的F值,comp只是一个缓冲区,真正记录坐标的还是map、open和close # comp不必是一个字典,如果在循环内通过判断语句只把最低F值的坐标推进去的话也能达到一样的效果 comp = self._open[0] #首先将第一个要比对的坐标放入comp完成初始化 for i in range(len(self._open)): f = self.map[self._open[i][0]][self._open[i][1]][0][0] #找到F的值 g = self.map[self._open[i][0]][self._open[i][1]][0][1] #找到G的值 # 我们需要的最佳坐标,是F值最低的一个 if f <= self.map[comp[0]][comp[1]][0][0]: # 但是如果有多个F值相等的坐标,则需要选择其中G值最低的坐标 # H值无需计算,因为F值即为G与H之和,若G值相同,则H值毫无疑问也想通 if f == self.map[comp[0]][comp[1]][0][0]: if g < self.map[comp[0]][comp[1]][0][1]: comp = self._open[i] #将坐标放进comp,格式是f:坐标 else: comp = self._open[i] #将坐标放进comp,格式是f:坐标 # comp中存储的即为最优节点解 return comp # 寻路到终点后,通过父坐标迭代返回并找到完整路径 def trace(self,father): self._trace = [father,self._end] #终点的坐标一定是移动的最后一步,所以首先放入列表中;父坐标不会在循环内被输入列表,因此同样放入列表 # 循环F次 pos = father #正在检查的坐标,每检查一个新坐标就会更新一次 # 如果路径过短会由于神秘力量报错,因此在循环前要进行判断 if self.map[father[0]][father[1]][0][1] == 0: return [self._end] else: for i in range(self.map[father[0]][father[1]][0][1]): pos = self.map[pos[0]][pos[1]][1] #找到父节点,随后将下一个子节点更新为这个节点 self._trace.append(pos) #把刚刚找到的父节点记录进trace里 # 记录完成,接下来可以输出了 self._trace.reverse() #因为append记录的列表是从终点向起点走过去的,因此需要反向列表 return self._trace # 返回所有可移动的坐标 # 传入起点与步数进行计算 def moveable(self,start,step=None): self.mapReinit() #重新初始化地图 print("====================================================") self.printRawMap() if step == None: step = self._x * self._y #如果没有指定步数,则步数等于地图大小 self.map[start[0]][start[1]] = 1 #为起始坐标赋上G值 father = start #第一个父坐标必定为开始坐标 self._start = start #将起始坐标存入类属性中 self._open.append(start) # 以开始坐标为起点开始搜索周围坐标并赋G值 for stage in range(self._x * self._y): for i in (0,-1),(-1,0),(0,1),(1,0): # 分析周围坐标信息,过滤掉障碍与边界 x = father[0] + i[0] y = father[1] + i[1] if x < self._x and x >= 0 and y < self._y and y >= 0: if self.map[x][y] != "o" and (x,y) not in self._open and (x,y) not in self._close: # 将检查的坐标放入open self._open.append((x,y)) # 为正在检查的点赋G值,然后存入父坐标 if self.map[father[0]][father[1]] + 1 < self.map[x][y] or self.map[x][y] == 0: self.map[x][y] = self.map[father[0]][father[1]] + 1 if self._print == "map": self.printMap() print("---------------------------------------") elif self._print == "raw": self.printRawMap() print("---------------------------------------") # 遍历一次open列表 for i in range(len(self._open)): # 检查G值是否符合要求 if self.map[self._open[i][0]][self._open[i][1]] <= step: father = (self._open[i][0],self._open[i][1]) self._close.append((self._open[i][0],self._open[i][1])) del(self._open[i]) break # 如果遍历到了头 if i+1 == len(self._open): self._close.extend(self._open) self._open.clear() return self._close # 寻路完成,返回close列表即可 return self._close # 这个类使用的是更新前的算法,需要遍历的路径更少,也就是寻路更快,但寻路的结果不一定精准 class FPriorTrack(AStarTrack): def compare(self): # 开始比对 comp = {} #comp会存放所有节点对应的F值 for i in range(len(self._open)): f = self.map[self._open[i][0]][self._open[i][1]][0][0] #找到F的值 comp[f] = self._open[i] #将坐标放进comp,格式是f:坐标 return comp[min(comp)] #min(comp)通过字典找到了最低的f,然后以f作为key找到坐标,就算f有相同的也不影响
JavaScript
UTF-8
6,639
2.59375
3
[]
no_license
var io = require('../server'); const Lobby = require('../models/lobby'); const Player = require('../models/player'); const Tank = require('../models/tank'); var lobbies = {}; var socketHashMapList = {}; module.exports = { lobbies, socketHashMapList }; io.on('connection', (socket) => { console.log("A new socket connected: " + socket.id); socketHashMapList[socket.id] = socket; socket.mobile = true; console.log("The socket ids:"); for(let socket in socketHashMapList){ console.log(socket); } socket.on('createLobby', (data) => { let curLobby = data.lobby; // Adding a new lobby to the hashmap lobbies[curLobby.lobbyHostId] = new Lobby(curLobby.lobbyHostId, curLobby.lobbyName, curLobby.lobbyPassword, curLobby.lobbyMap, curLobby.lobbyMaxPlayer, curLobby.lobbyCurPlayer); console.log("A lobby has been created: " + curLobby.lobbyHostId); console.log("Player: " + socket.id + " joined to lobby: " + curLobby.lobbyHostId); addPlayerToLobby(curLobby.lobbyHostId, data.newPlayer); console.log("Sending players and lobbies list to the clients!"); sendPlayersListToClients(curLobby.lobbyHostId); socket.emit('joinSuccess', {}); // Send the players list to the sockets in the same lobby io.emit('updateLobbiesList', {lobbies: lobbies}); }); socket.on('getLobbies', (data) => { console.log("LobbyList:"); for (let lobby in lobbies){ if(lobbies.hasOwnProperty(lobby)){ console.log(lobby); } } socket.emit('updateLobbiesList', {lobbies: lobbies}); }); socket.on('joinLobby', (data) => { let hostId = data.newPlayer.playerLobbyHostId; //socket.join(hostId); // Check if the lobby exists and if it has free space if(lobbies.hasOwnProperty(hostId) && lobbies[hostId].lobbyCurPlayer < lobbies[hostId].lobbyMaxPlayer){ console.log("Player: " + socket.id + " joined to lobby: " + hostId); addPlayerToLobby(hostId, data.newPlayer); console.log("Sending players and lobbies list to the clients!"); sendPlayersListToClients(hostId); socket.emit('joinSuccess', {}); // Send the players list to the sockets in the same lobby io.emit('updateLobbiesList', {lobbies: lobbies}); } else { socket.emit('joinUnSuccess',{}); } }); socket.on('setImageData', (data) => { let playerId = data.playerId; let code = data.code; let playerImgData = data.playerImgData; console.log("SetIMGDATA!"); console.log(playerId); //console.log(socketHashMapList[playerId]); socketHashMapList[playerId].playerImgData = playerImgData; console.log(socketHashMapList[playerId].playerImgData); socketHashMapList[playerId].code = code; }); socket.on('playerReady', (data) => { let hostId = data.hostId; // Check if the lobby exists if(lobbies.hasOwnProperty(hostId)) { console.log("Player status changed: " + data.playerId); lobbies[hostId].lobbyPlayers[data.playerId].playerStatus = data.playerState; sendPlayersListToClients(hostId); } }); socket.on('leaveLobby', (data) => { let hostId = data.hostId; let playerId = data.playerId; console.log("Player: " + playerId + " left lobby: " + hostId); if(playerId === hostId && lobbies[hostId] != null){ console.log("Deleting lobby: " + hostId); deleteLobby(hostId); //io.to(gameLobbyId).emit('kickLobbyPlayer', {msg: "The lobby has been deleted!"}); }else if(lobbies[hostId] != null){ console.log("Deleting lobbyPlayer: " + playerId); deleteLobbyPlayer(hostId, playerId); Tank.onDisconnect(socketHashMapList[playerId]); //socket.emit('kickLobbyPlayer', {msg: "You have left the lobby!"}); sendPlayersListToClients(hostId); } io.emit('updateLobbiesList', {lobbies: lobbies}); }); socket.on('playerKick', (data) => { let hostId = data.hostId; let playerId = data.playerId; socketHashMapList[playerId].emit('kickLobbyPlayer', {msg: "You have been kicked from the lobby!"}); deleteLobbyPlayer(hostId, playerId); sendPlayersListToClients(hostId); //update the lobby list on the client side io.emit('updateLobbiesList', {lobbies: lobbies}); }); // socket.on('changeLobbyStatus', (data) => { // if(lobbies.hasOwnProperty(data.lobbyHostId)){ // lobbies[data.lobbyHostId].lobbyInGame = true; // } // io.emit('updateLobbiesList', {lobbies: lobbies}); // }); socket.on('disconnect', () => { //delete the lobbies of the socket if there is any if(lobbies.hasOwnProperty(socket.id)) { deleteLobby(socket.id); } else { //iterate through the lobbies, and delete a player from a lobby for(let lobby in lobbies){ deleteLobbyPlayer(lobby, socket.id); sendPlayersListToClients(lobby); } } //remove the socket from the socketList delete socketHashMapList[socket.id]; //update the lobby list on the client side io.emit('updateLobbiesList', {lobbies: lobbies}); console.log("Disconnected: "+socket.id); }); }); var sendPlayersListToClients = function(pHostId) { for(let lobbyPlayer in lobbies[pHostId].lobbyPlayers){ socketHashMapList[lobbyPlayer].emit('updatePlayersList', {playersList: lobbies[pHostId].lobbyPlayers}); } }; var deleteLobby = function(pHostId) { //iterate through the lobby players and kick them, before deleting the lobby for(let lobbyPlayer in lobbies[pHostId].lobbyPlayers){ socketHashMapList[lobbyPlayer].emit('kickLobbyPlayer', {msg: "The lobby has been deleted!"}); } delete lobbies[pHostId]; }; var deleteLobbyPlayer = function(pHostId, pPlayerId) { if(lobbies[pHostId].lobbyPlayers.hasOwnProperty(pPlayerId)){ delete lobbies[pHostId].lobbyPlayers[pPlayerId]; lobbies[pHostId].lobbyCurPlayer -= 1; lobbies[pHostId].curMaxPlayer(); } }; var addPlayerToLobby = function(pHostId, pPlayer) { lobbies[pHostId].addPlayer(new Player(pHostId, pPlayer.playerId, pPlayer.playerName, pPlayer.playerStatus)); lobbies[pHostId].lobbyCurPlayer += 1; lobbies[pHostId].curMaxPlayer(); };
JavaScript
UTF-8
1,319
2.984375
3
[]
no_license
import React,{useState} from 'react' import {format} from 'date-fns' function App() { const [state,setState]=useState('') const [state1,setState1]=useState('') const [state2,setState2]=useState('') const [item,setItem]=useState([]) const [clr,setClr]=useState(false) const call=(event)=>{ setState(event.target.value) setClr(false) } const call1=(event)=>{ setState1(event.target.value) } const call2=(event)=>{ setState2(event.target.value) } const mydata={id:new Date().getTime().toString(), task:state, date:state1, description:state2} const write=()=>{ setItem([...item,mydata]) setClr(true) } const current=format(new Date(),'yyyy-MM-dd') if(mydata.date===current) {alert('due date passed')} return ( <> <div> <label>enter your task</label> <input type="text" onChange={call}/> </div> <div> <label> task Description</label> <input type="text" onChange={call2}/> </div> <div> <label>task due date</label> <input type="date" onChange={call1} /> </div> <div><button onClick={write}>add</button></div> <div> <h1>TO-DO LIST</h1> </div> <div> {item.map(ele=>{ return <table> <tr><td>{ele.task}</td></tr> <tr><td>{ele.description}</td></tr> <tr><td>{ele.date}</td></tr> </table> })} </div> </> ); } export default App;
Rust
UTF-8
4,168
2.6875
3
[ "MIT" ]
permissive
use crate::kv::{ encode, DeleteRangeRequest, DeleteRangeResponse, PutRequest, PutResponse, RangeRequest, RangeResponse, ResponseHeader, }; use serde::{Deserialize, Serialize}; #[derive(Debug, Eq, PartialEq, Serialize, Deserialize)] pub enum CompareResult { EQUAL, GREATER, LESS, #[serde(rename = "NOT_EQUAL")] NotEqual, } #[derive(Debug, Eq, PartialEq, Serialize, Deserialize)] pub enum CompareTarget { VERSION, CREATE, MOD, VALUE, } #[allow(dead_code)] #[derive(Debug, Serialize, Deserialize)] pub struct Compare { key: String, result: Option<CompareResult>, target: Option<CompareTarget>, version: Option<String>, create_revision: Option<String>, mod_revision: Option<String>, } #[allow(dead_code)] #[derive(Debug, Serialize)] pub struct RequestOp { request_range: Option<RangeRequest>, request_put: Option<PutRequest>, request_delete_range: Option<DeleteRangeRequest>, } #[allow(dead_code)] #[derive(Debug, Deserialize)] pub struct ResponseOp { response_range: Option<RangeResponse>, response_put: Option<PutResponse>, response_delete_range: Option<DeleteRangeResponse>, } #[allow(dead_code)] #[derive(Debug, Serialize)] pub struct TxnRequest { compare: Vec<Compare>, success: Option<Vec<RequestOp>>, failure: Option<Vec<RequestOp>>, } #[allow(dead_code)] #[derive(Debug, Deserialize)] pub struct TxnResponse { header: ResponseHeader, succeeded: Option<bool>, #[serde(default)] responses: Vec<ResponseOp>, } impl Compare { pub fn not_exists(key: &str) -> Compare { let encoded_key = encode(key); Compare { key: encoded_key, result: None, target: Some(CompareTarget::CREATE), version: None, create_revision: None, mod_revision: Some("0".to_string()), } } pub fn with(key: &str, result: CompareResult, target: CompareTarget, rev: String) -> Compare { let encoded_key = encode(key); let (version, create_revision, mod_revision) = { match target { CompareTarget::VERSION => (Some(rev), None, None), CompareTarget::CREATE => (None, Some(rev), None), CompareTarget::MOD => (None, None, Some(rev)), CompareTarget::VALUE => (None, None, None), } }; Compare { key: encoded_key, result: Some(result), target: Some(target), version, create_revision, mod_revision, } } } impl RequestOp { pub fn range(req: RangeRequest) -> RequestOp { RequestOp { request_range: Some(req), request_put: None, request_delete_range: None, } } pub fn put(req: PutRequest) -> RequestOp { RequestOp { request_range: None, request_put: Some(req), request_delete_range: None, } } pub fn delete(req: DeleteRangeRequest) -> RequestOp { RequestOp { request_range: None, request_put: None, request_delete_range: Some(req), } } } impl TxnRequest { pub fn with(compare: Compare, success: RequestOp) -> TxnRequest { TxnRequest { compare: vec![compare], success: Some(vec![success]), failure: None, } } } impl TxnResponse { pub fn is_success(&self) -> bool { self.succeeded.is_some() && self.succeeded.unwrap() } pub fn responses(&self) -> &[ResponseOp] { &self.responses } } impl ResponseOp { pub fn put(&self) -> Option<&PutResponse> { self.response_put.as_ref() } pub fn range(&self) -> Option<&RangeResponse> { self.response_range.as_ref() } pub fn delete(&self) -> Option<&DeleteRangeResponse> { self.response_delete_range.as_ref() } } impl Default for CompareResult { fn default() -> Self { CompareResult::EQUAL } } impl Default for CompareTarget { fn default() -> Self { CompareTarget::CREATE } }
Python
UTF-8
4,930
3.140625
3
[]
no_license
import numpy as np import cv2 class ImageManager: ''' Class to be used to store the acquired images split in two channels and methods useful for cell identification and roi creation ''' def __init__(self,dim_h, dim_v, half_side, min_cell_size): zeros_im = np.zeros((dim_v,dim_h),dtype=np.uint16) self.image = [zeros_im, zeros_im] # original 16 bit images from the two channels self.dim_h = dim_h self.dim_v = dim_v self.contour = [] # list of contours of the detected cells self.cx = [] # list of the x coordinates of the centroids of the detected cells self.cy = [] # list of the y coordinates of the centroids of the detected cells self.selected_cx = [] # list of the x coordinates of the centroids of the detected cells to be saved (not at the boundary of our acquired frame) self.selected_cy = [] # list of the y coordinates of the centroids of the detected cells to be saved (not at the boundary of our acquired frame) self.roi_half_side = half_side # half dimension of the roi self.min_cell_size = min_cell_size # minimum area that the object must have to be recognized as a cell def find_cell(self, ch): # ch: selected channel """ Input: ch: channel to use to create the 8 bit image to process Determines if a region avove thresold is a cell, generates contours of the cells and their centroids cx and cy """ image8bit = (self.image[ch]/256).astype('uint8') _ret,thresh_pre = cv2.threshold(image8bit,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU) # ret is the threshold that was used, thresh is the thresholded image. kernel = np.ones((3,3),np.uint8) thresh = cv2.morphologyEx(thresh_pre,cv2.MORPH_OPEN, kernel, iterations = 2) # morphological opening (remove noise) contours, _hierarchy = cv2.findContours(thresh,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) cx = [] cy = [] contour =[] for cnt in contours: M = cv2.moments(cnt) if M['m00'] > int(self.min_cell_size): # (M['m00'] gives the contour area, also as cv2.contourArea(cnt) #extracts image center cx.append(int(M['m10']/M['m00'])) cy.append(int(M['m01']/M['m00'])) contour.append(cnt) self.cx = cx self.cy = cy self.contour = contour def draw_contours_on_image(self, image8bit): """ Input: img8bit: monochrome image, previously converted to 8bit Output: displayed_image: RGB image with annotations """ cx = self.cx cy = self.cy roi_half_side = self.roi_half_side contour = self.contour displayed_image = cv2.cvtColor(image8bit,cv2.COLOR_GRAY2RGB) for indx, _val in enumerate(cx): x = int(cx[indx] - roi_half_side) y = int(cy[indx] - roi_half_side) w = h = roi_half_side*2 displayed_image = cv2.drawContours(displayed_image, [contour[indx]], 0, (0,256,0), 2) if indx == 0: color = (256,0,0) else: color = (0,0,256) cv2.rectangle(displayed_image,(x,y),(x+w,y+h),color,1) return displayed_image def roi_creation(self, ch): """ Input: ch: selected channel Output: rois: list of rois in the frame """ image16bit = self.image[ch] cx = self.cx cy = self.cy roi_half_side = self.roi_half_side l = image16bit.shape rois = [] selected_cx = [] selected_cy = [] for indx, _val in enumerate(cx): x = int(cx[indx] - roi_half_side) y = int(cy[indx] - roi_half_side) w = h = roi_half_side*2 if x>0 and y>0 and x+w<l[1]-1 and y+h<l[0]-1: # only rois far from edges are considered detail = image16bit [y:y+w, x:x+h] rois.append(detail) selected_cx.append(cx[indx]) selected_cy.append(cy[indx]) self.selected_cx = selected_cx self.selected_cy = selected_cy return rois def highlight_channel(self,displayed_image): cv2.rectangle(displayed_image,(0,0),(self.dim_h-1,self.dim_v-1),(255,255,0),3)
C++
UTF-8
4,864
2.96875
3
[]
no_license
#include <stdio.h> #include <time.h> #include <string.h> #include <vector> #include <glm.hpp> #include <gtc/matrix_transform.hpp> #include <Raytracer/Raytracer.h> #include <Rasterizer/SimpleRasterizer.h> #include <Windowing/DisplayWindow.h> using namespace glm; using namespace Rasterizer; using namespace Raytracer; using namespace Raytracer::Scenes; using namespace Raytracer::Objects; using namespace Windowing; /** * Creates a transformation matrix for a rotation around the x axis. * * @param a The rotation angle in degrees */ mat4x4 RotationX(float a) { return rotate(mat4x4(1.0f), a, vec3(1.0f, 0.0f, 0.0f)); } /** * Creates a transformation matrix for a rotation around the y axis. * * @param a The rotation angle in degrees */ mat4x4 RotationY(float a) { return rotate(mat4x4(1.0f), a, vec3(0.0f, 1.0f, 0.0f)); } /** * Creates a transformation matrix for a rotation around the z axis. * * @param a The rotation angle in degrees */ mat4x4 RotationZ(float a) { return rotate(mat4x4(1.0f), a, vec3(0.0f, 0.0f, 1.0f)); } /** * Creates a scene with a mesh, two lights, and a camera. * * @param fileName The file name of the mesh file. If this is NULL, BuildScene() creates just a * single triangle for test purposes. * @param aspect The image aspect ratio to use for the scene's camera * @param mesh Receives a pointer to the central mesh object of the scene. * @return The created scene or NULL if an error occurred */ Scene *BuildScene(const char *fileName, float aspect, Mesh *&mesh) { // Create the scene. Scene *scene = new Scene(); if (scene == NULL) return NULL; // Create a triangle mesh. mesh = new Mesh(); if (mesh == NULL) { delete scene; return NULL; } if (fileName == NULL) { // Create just a single triangle in the xz plane as test geometry. Triangle t; t.SetVertex(0, vec3(0, 0, 1.0f), vec3(0, 0, 1), vec3(1, 0, 0)); t.SetVertex(1, vec3(1.0f, 0, -1.0f), vec3(0, 0, 1), vec3(0, 1, 0)); t.SetVertex(2, vec3(-1.0f, 0, -1.0f), vec3(0, 0, 1), vec3(0, 0, 1)); mesh->AddTriangle(t); } else { // Load the mesh from this file. if (!mesh->Load(fileName)) { delete scene; mesh = NULL; return NULL; } } scene->AddChild(mesh); // Create two lights. Light *light = new PointLight(vec3(20.0f)); if (light == NULL) { delete scene; mesh = NULL; return NULL; } light->SetPosition(vec3(-5.0f, 3.0f, 2.0f)); scene->AddChild(light); light = new PointLight(vec3(3.0f, 3.0f, 4.0f)); if (light == NULL) { delete scene; mesh = NULL; return NULL; } light->SetPosition(vec3(5.0f, -2.0f, -10.0f)); scene->AddChild(light); // Create a camera. Camera *camera = new Camera(vec3(2.0f, 0.0f, 4.0f), vec3(0.0f, 0.0f, 0.0f), vec3(0.0f, 1.0f, 0.0f), Camera::DefaultFov, aspect, 1.0f, 10.0f); if (camera == NULL) { delete scene; mesh = NULL; return NULL; } scene->AddChild(camera); scene->SetActiveCamera(camera); return scene; } /** * Renders the scene continuously into a window. * * @param width The image width * @param height The image height * @param rotate whether to rotate the geometry * @param filename the filename of a geometry to load. */ void Render(int width, int height, bool rotate, const char *filename) { if (width <= 0 || height <= 0) return; Mesh *mesh; Scene *scene = BuildScene(filename, (float)width / height, mesh); if (scene == NULL) { // The mesh file could not be found or read or we ran out of memory. puts("Die Szene konnte nicht erstellt werden."); return; } SimpleRasterizer rasterizer; Image image(width, height); DisplayWindow window(width, height); window.SetImage(&image); // Keep rendering the scene into the window until the window is closed. while (window.ProcessMessages()) { // Rotate the mesh over time. float t = 0.0f; if (rotate) t = window.GetTime(); mesh->SetTransformation(RotationY(t * 36.0f) * RotationX(-90.0f)); rasterizer.Render(image, *scene); window.Update(); } delete scene; } /** * The main program */ int main(int argc, char *argv[]) { // Set this to true to have the geometry rotate by default. bool rotate = false; // Set this to false to use just a single triangle by default, // or to true to load a more complex geometry. bool loadFile = false; // Set this to NULL to use just a single triangle to default, // or to a filename to load a more complex geometry. const char *filename = "data/kopf_subdivided.raw"; for (int i = 1; ((i < argc) && (i < 3)); ++i) { if (strcmp(argv[i], "-rotate") == 0) rotate = true; else if (strcmp(argv[i], "-norotate") == 0) rotate = false; else if (strcmp(argv[i], "-nogeometry") == 0) filename = NULL; else filename = argv[i]; } if (loadFile == false) { filename = NULL; } Render(512, 512, rotate, filename); return 0; }
Java
UTF-8
323
1.617188
2
[ "MIT" ]
permissive
package dbuchta.gitlab.issue.exporter.model; import com.fasterxml.jackson.annotation.JsonProperty; import javax.annotation.Generated; @Generated("com.robohorse.robopojogenerator") public class IdentitiesItem{ @JsonProperty("provider") private String provider; @JsonProperty("extern_uid") private String externUid; }
Shell
UTF-8
2,747
2.796875
3
[]
no_license
#!/bin/bash WHAT=$1; if [[ "$1" == "" ]]; then echo "monojet.sh <what>"; exit 1; fi if [[ "$HOSTNAME" == "cmsphys06" ]]; then T="/data1/emanuele/monox/TREES_25ns_1LEPSKIM_23NOV2015"; J=6; else T="/cmshome/dimarcoe/TREES_060515_MET200SKIM"; J=6; fi COREOPT="-P $T --s2v -j $J -l 2.11 -W vtxWeight " COREY="mcAnalysis.py ${COREOPT} -G " COREP="mcPlots.py ${COREOPT} -f --poisson " FEV=" -F mjvars/t \"$T/friends/evVarFriend_{cname}.root\" " ROOT="plots/Summer15/v1.0/$WHAT" MCA="" if [ "$WHAT" == "zmmI" ] || [ "$WHAT" == "zeeI" ] ; then MCA="mca-74X.txt " elif [ "$WHAT" == "wmnI" ] || [ "$WHAT" == "wenI" ] ; then MCA="mca-74X-singleLep.txt " else MCA="mca-74X-analysis.txt " fi RUNYSR="${COREY} ${MCA} sync/monojet_twiki.txt " RUNY2M="${COREY} ${MCA} sync/zmumu_twiki.txt " RUNY2E="${COREY} ${MCA} sync/zee_twiki.txt " RUNY1M="${COREY} ${MCA} sync/wmunu_twiki.txt " RUNY1G="${COREY} ${MCA} sync/gjets_twiki.txt " PLOT="${COREP} ${MCA} " PLOTSR="${PLOT} sr/monojet.txt sr/monojet-plots.txt --noStackSig --showSigShape " case $WHAT in sr) SF=" " echo "python ${RUNYSR} $FEV $SF " echo "python ${PLOTSR} $FEV $SF --pdir ${ROOT} --showRatio " ;; zmm) echo "python ${RUNY2M} $FEV --sp DYJetsHT " echo "python ${PLOT} sync/zmumu_twiki.txt sync/zmumu_plots.txt $FEV --sp DYJetsHT --pdir ${ROOT} --showRatio " ;; zee) echo "python ${RUNY2E} $FEV --sp DYJetsHT " echo "python ${PLOT} sync/zee_twiki.txt sync/zee_plots.txt $FEV --sp DYJetsHT --pdir ${ROOT} --showRatio " ;; zmmI) echo "python ${RUNY2M} -X recoil -X jet100 -X jetclean -X dphijm $FEV --sp DYJets " echo "python ${PLOT} sync/zmumu_twiki.txt sync/zmumu_incl_plots.txt -X recoil -X jet100 -X jetclean -X dphijm $FEV --sp DYJets --pdir ${ROOT} --showRatio --scaleSigToData " ;; zeeI) echo "python ${RUNY2E} -X recoil -X jet100 -X jetclean -X dphijm $FEV --sp DYJets " echo "python ${PLOT} sync/zee_twiki.txt sync/zee_incl_plots.txt -X recoil -X jet100 -X jetclean -X dphijm $FEV --sp DYJets --pdir ${ROOT} --showRatio --scaleSigToData " ;; wmnI) echo "python ${RUNY1M} $FEV --sp WJets --xp DYJetsHT --xp WJetsHT -X recoil -X jet100 -X jetclean -X dphijm " echo "python ${PLOT} sync/wmunu_twiki.txt sync/wmunu_incl_plots.txt $FEV --sp WJets --xp DYJetsHT --xp WJetsHT -X recoil -X jet100 -X jetclean -X dphijm --pdir ${ROOT} --showRatio --scaleSigToData " ;; wmn) echo "python ${RUNY1M} $FEV --sp WJetsHT --xp WJets --xp DYJets " echo "python ${PLOT} sync/wmunu_twiki.txt sync/wmunu_incl_plots.txt $FEV --sp WJetsHT --xp WJets --xp DYJets -X recoil -X jet100 -X jetclean -X dphijm --pdir ${ROOT} --showRatio --scaleSigToData " ;; esac;
Python
UTF-8
1,336
2.859375
3
[]
no_license
x, y = map(int, input().split()) lis = [] for i in range(x): lis.append(list(input())) BW = [[0 for _ in range(y)] for _ in range(x)] WB = [[0 for _ in range(y)] for _ in range(x)] # BW 테스트 for i in range(x): for j in range(y): if (i+j)%2 == 0: if lis[i][j] == "B": pass else: BW[i][j] += 1 else: if lis[i][j] == "W": pass else: BW[i][j] += 1 # WB 테스트 for i in range(x): for j in range(y): if (i+j)%2 == 0: if lis[i][j] == "W": pass else: WB[i][j] += 1 else: if lis[i][j] == "B": pass else: WB[i][j] += 1 ans = 64 #BW판 최소값 for i in range(7, x): for j in range(7, y): tmp_sum = 0 for p in range(8): for q in range(8): if BW[i-p][j-q]: tmp_sum += 1 if tmp_sum <= ans: ans = tmp_sum #WB판 최소값 for i in range(7, x): for j in range(7, y): tmp_sum = 0 for p in range(8): for q in range(8): if WB[i-p][j-q]: tmp_sum += 1 if tmp_sum <= ans: ans = tmp_sum print(ans)
Swift
UTF-8
4,307
2.84375
3
[]
no_license
// // DetailViewController.swift // Network Example // // Copyright © 2016 Elon Rubin. All rights reserved. // import Foundation import UIKit class DetailViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet weak var postTitle: UILabel! @IBOutlet weak var postAuthor: UILabel! @IBOutlet weak var postBody: UILabel! @IBOutlet weak var segmentedControl: UISegmentedControl! @IBOutlet weak var tableView: UITableView! var selectedPost: Post = Post() var session = URLSession.shared var comments = [Comment]() var users = [User]() override func viewDidLoad() { tableView.delegate = self tableView.dataSource = self initalizeController() } func initalizeController () { let user = users[selectedPost.userID] DispatchQueue.main.async(execute: { self.postTitle.text = self.selectedPost.title self.postAuthor.text = "By " + user.name self.postBody.text = self.selectedPost.body }) } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return comments.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) let comment = comments[indexPath.row] // This is logic to tell whether a place objcet is a sent or recieved item. cell.textLabel!.text = comment.title let user = users[comment.userID] cell.detailTextLabel?.text = user.username + "(\(user.name))" return cell } func fetchComments (forPost: Int) { let commentIDString = String(forPost) let url = NSURL(string: "http://jsonplaceholder.typicode.com/comments?postId=\(commentIDString)")! print(url) let request = NSMutableURLRequest(url: url as URL) let task = session.dataTask(with: request as URLRequest) { (data, response, error) in // Parse Data guard let data = data else { return } // var parsedDataResult: [[String:AnyObject]]! var parsedDataResult: Any do { parsedDataResult = try JSONSerialization.jsonObject(with: data, options: .allowFragments) // print (parsedDataResult) } catch { // Handle error here return } if let comments = parsedDataResult as? [[String:AnyObject]] { for comment: [String:AnyObject] in comments { let commentObject: Comment = Comment() // Note - I would ordinarliy structure this as an optional, but since the code is set, I am going to force unwrap commentObject.title = comment["name"] as! String commentObject.id = comment["id"] as! Int commentObject.body = comment["body"] as! String // commentObject.userID = comment["email"] as! String self.comments.append(commentObject) } DispatchQueue.main.async(execute: { self.tableView.reloadData() }) } else { } } task.resume() } @IBAction func segmentControlDidChange(_ sender: Any) { switch segmentedControl.selectedSegmentIndex { case 0: postBody.isHidden = false tableView.isHidden = true case 1: postBody.isHidden = false DispatchQueue.main.async(execute: { self.tableView.reloadData() self.tableView.isHidden = false }) default: postBody.isHidden = false tableView.isHidden = true } } }
Markdown
UTF-8
2,496
2.953125
3
[]
no_license
# Neighborhood-Map This is a Chicago Neighborhood Map displaying some tourist attractions, restaurants, cafes and subway stations, on the list in the right pane as well as with the corresponding markers on the map. It is built with KnockoutJS framework using some Google Map APIs and some external APIs such as Wikipedia and FourSquare. You can find this on [GitHub pages](https://narulanx.github.io/Neighborhood-Map/). ### Installation - Download the respository from github - Host the application locally on localhost. To do that you can follow the instructions [here](https://ngrok.com/) - Run index.html and enjoy the cool features of the application ### Features - The filter search box filters the places from the list and subsequently on the marker without refreshing the page. - On click of the place name on the list or on marker, will bounce the marker indefinitely until you click again. - On click of the place name on the list or on marker, will pop open an info window on the map displaying some information of the place and the services that is offered. - The information displayed on the info window are retrieved using PlacesService Google Maps API. These information include name, address, phone number, opening hours and a photo of the place. - The other services thar are included on the info window are Google StreetView, Google Reviews, FourSquare Reviews and Wikipedia Info. The information from these services are displayed on a modal window that gets opened in the middle of the page. - Google StreetView uses the StreetViewService, StreetViewPanorama and ComputeHeading APIs of the Google Maps and displays the image that is returned. - Google Reviews uses the PlacesService API of the Google Maps and displays all the user reviews with their name and rating. - FourSquare Reviews uses the SearchService FourSquare API to get the PlaceID and uses this ID with TipsService FourSquare API to get the user reviews, and displays their name, gender, browser URL, review and a photo (if available). - Wikipedia Info uses the OpenSearch Wikipedia API and displays the title and description from the return. - A 'perfect scrollbar' JQuery plugin is used for the list of places in the right pane. ### Tools and APIs used - KnockoutJS - Google Maps API * PlacesService * StreetViewService * StreetViewPanorama * ComputeHeading - FourSquare API * SearchService * TipsService - Wikipedia OpenSearch API - Bootstrap - Google Fonts - JQuery - Perfect Scrollbar JQuery plugin
Markdown
UTF-8
466
2.890625
3
[]
no_license
# OOP-Assignment-1 The assignment goal is to practice the following concepts: • Class design • Collections • Inheritance and substitution In this assignment you will implement a Polynomial Calculator. The Calculator will allow the user to compute polynomial addition, polynomial multiplication, and other services. The design should be general, and allow easy modification for any type of scalar. To this end, you need to implement the following classes.
Java
UTF-8
1,476
2.15625
2
[ "Apache-2.0" ]
permissive
/* * Copyright © 2020 IBM Corp. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, * either express or implied. See the License for the specific language governing permissions * and limitations under the License. */ package dev.ebullient.dnd.bestiary.compendium; import java.io.IOException; import java.io.InputStream; import java.util.Map; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import dev.ebullient.dnd.bestiary.Bestiary; public class CompendiumReader { static final ObjectMapper mapper = new ObjectMapper(); static final TypeReference<Map<String, Monster>> typeRef = new TypeReference<Map<String, Monster>>() { }; public static void addToBestiary(Bestiary beastiary) throws IOException { try (InputStream jsonInput = CompendiumReader.class.getResourceAsStream("/compendium.json")) { Map<String, Monster> compendium = mapper.readValue(jsonInput, typeRef); for (Monster m : compendium.values()) { beastiary.save(m); } } } }
Java
UTF-8
13,675
1.671875
2
[ "CC0-1.0" ]
permissive
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package quickstore.controller; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import javax.inject.Named; import javax.enterprise.context.SessionScoped; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle; import java.util.logging.Level; import java.util.logging.Logger; import javax.ejb.EJBException; import javax.faces.context.FacesContext; import javax.faces.event.PhaseId; import javax.inject.Inject; import javax.servlet.ServletContext; import org.primefaces.context.RequestContext; import org.primefaces.event.FileUploadEvent; import org.primefaces.model.DefaultStreamedContent; import org.primefaces.model.StreamedContent; import org.primefaces.model.UploadedFile; import quickstore.ejb.entity.Articulo; import quickstore.ejb.entity.ArticuloAdjunto; import quickstore.ejb.facade.ArticuloAdjuntoDAO; import quickstore.ejb.facade.ArticuloDAO; import quickstore.util.JSFutil; import quickstore.util.JSFutil.PersistAction; /** * * @author root */ @Named(value = "ArticuloController") @SessionScoped public class ArticuloController implements Serializable { /** * Configuraciones varias para Log y Bundle* */ private static final Logger LOG = Logger.getLogger(ArticuloController.class.getName()); ResourceBundle bundle = ResourceBundle.getBundle("quickstore.properties.bundle", JSFutil.getmyLocale()); @Inject private ArticuloDAO articuloDAO; @Inject private ArticuloAdjuntoDAO articuloAdjuntoDAO; private Articulo articulo; private List<Articulo> listaArticulo; private List<Articulo> listaArticuloFiltrado; private List<ArticuloAdjunto> listaAdjuntoArticulo; private String criterioBusqueda; private Boolean hayCambios; @Inject private ClickCounter clickCounter; /** * Creates a new instance of ArticuloController */ public ArticuloController() { this.criterioBusqueda = ""; } //******************************************** // SETTERS Y GETTERS //******************************************** public Articulo getArticulo() { return articulo; } public void setArticulo(Articulo articulo) { this.articulo = articulo; } public List<Articulo> getListaArticulo() { return listaArticulo; } public void setListaArticulo(List<Articulo> listaArticulo) { this.listaArticulo = listaArticulo; } public List<ArticuloAdjunto> getListaAdjuntoArticulo() { return listaAdjuntoArticulo; } public void setListaAdjuntoArticulo(List<ArticuloAdjunto> listaAdjuntoArticulo) { this.listaAdjuntoArticulo = listaAdjuntoArticulo; } public List<Articulo> getListaArticuloFiltrado() { return listaArticuloFiltrado; } public void setListaArticuloFiltrado(List<Articulo> listaArticuloFiltrado) { this.listaArticuloFiltrado = listaArticuloFiltrado; } public String getCriterioBusqueda() { return criterioBusqueda; } public void setCriterioBusqueda(String criterioBusqueda) { this.criterioBusqueda = criterioBusqueda; } public ClickCounter getClickCounter() { return clickCounter; } public void setClickCounter(ClickCounter clickCounter) { this.clickCounter = clickCounter; } public Boolean getHayCambios() { return hayCambios; } public void setHayCambios(Boolean hayCambios) { this.hayCambios = hayCambios; } //******************************************** // METODOS DE ACCIÓN //******************************************** /** * Crear un Registro * * @return */ public String doCrearForm() { this.hayCambios = false; this.listaAdjuntoArticulo = new ArrayList<>(); this.articulo = new Articulo(); return "/backend/articulo/CrearArticulo"; } /** * Preparar el Formulario de Listado * * @return */ public String doListarForm() { this.clickCounter.setCount(0); this.criterioBusqueda = ""; this.listaArticulo = new ArrayList<>(); //this.doListar(); return "/backend/articulo/ListarArticulo"; } /** * Preparar el Formulario de Visualización * * @param u * @return */ public String doVerForm(Articulo u) { this.listaAdjuntoArticulo = this.articuloAdjuntoDAO.findAllbyArticulo(u.getIdArticulo()); this.articulo = u; return "/backend/articulo/VerArticulo"; } /** * Preparar el Formulario de Edición * * @param u * @return */ public String doEditarForm(Articulo u) { this.hayCambios = false; this.listaAdjuntoArticulo = this.articuloAdjuntoDAO.findAllbyArticulo(u.getIdArticulo()); this.articulo = u; return "/backend/articulo/CrearArticulo"; } /** * Listar */ public void doListar() { try { Thread.sleep(2000); } catch (InterruptedException ex) { Logger.getLogger(ArticuloController.class.getName()).log(Level.SEVERE, null, ex); } if (this.criterioBusqueda.length() > 0) { this.listaArticulo = articuloDAO.findAllbyCriterio(criterioBusqueda); } else { this.listaArticulo = articuloDAO.findAllSorted("nombreArticulo", "ASC"); } if (this.listaArticulo.size() > 0) { JSFutil.addSuccessMessage(this.listaArticulo.size() + " registro/s recuperado/s"); } else { JSFutil.addSuccessMessage("Sin registros"); } } /** * Guardar un registro * * @return */ public String doGuardar() { if (this.articulo.getIdArticulo() != null) { persist(PersistAction.UPDATE); this.doListar(); return "/backend/articulo/ListarArticulo"; } else { persist(PersistAction.CREATE); this.doCrearForm(); return ""; } } public String doAbortOperation() { if (this.hayCambios) { RequestContext context = RequestContext.getCurrentInstance(); context.execute("PF('confirmacionAbort').show();"); return ""; } else { return this.doListarForm(); } } private void persist(PersistAction persistAction) { try { if (persistAction.compareTo(PersistAction.CREATE) == 0) { if (this.articulo.getPorcentajeDescuento() == null) { this.articulo.setPorcentajeDescuento(0); } articuloDAO.create(articulo); if (this.listaAdjuntoArticulo.size() > 0) { for (ArticuloAdjunto aadj : this.listaAdjuntoArticulo) { aadj.setIdArticulo(articulo); articuloAdjuntoDAO.create(aadj); } } } else if (persistAction.compareTo(PersistAction.UPDATE) == 0) { Integer id = this.articulo.getIdArticulo(); if (this.articulo.getPorcentajeDescuento() == null) { this.articulo.setPorcentajeDescuento(0); } articuloDAO.update(articulo); //Borramos todos sus adjuntos for (ArticuloAdjunto x : this.articuloAdjuntoDAO.findAllbyArticulo(id)) { this.articuloAdjuntoDAO.remove(x); } if (this.listaAdjuntoArticulo.size() > 0) { for (ArticuloAdjunto aadj : this.listaAdjuntoArticulo) { aadj.setIdArticulo(new Articulo(id)); articuloAdjuntoDAO.create(aadj); } } } else if (persistAction.compareTo(PersistAction.DELETE) == 0) { articuloDAO.remove(articulo); } JSFutil.addSuccessMessage(JSFutil.getMyBundle().getString("UpdateSuccess")); } catch (EJBException ex) { String msg = ""; Throwable cause = ex.getCause(); if (cause != null) { msg = cause.getLocalizedMessage(); } if (msg.length() > 0) { JSFutil.addErrorMessage(msg); } else { JSFutil.addErrorMessage(ex, JSFutil.getMyBundle().getString("UpdateError")); } } } /** * Borrar un registro * * @param u */ public void doBorrar(Articulo u) { this.articulo = u; persist(PersistAction.DELETE); doListarForm(); } public void doSacarArticuloAdjuntoLista(int index) { this.listaAdjuntoArticulo.remove(index); } //******************************************** // METODOS DEL LISTENER //******************************************** /** * Manejador del FileUpload * * @param event */ public void handleFileUploadArticulo(FileUploadEvent event) { try { if (this.listaAdjuntoArticulo == null) { this.listaAdjuntoArticulo = new ArrayList<>(); } UploadedFile uf = event.getFile(); ArticuloAdjunto adj = new ArticuloAdjunto(); adj.setArchivo(JSFutil.getBytesFromInputStream(uf.getInputstream())); adj.setNombreArchivo(uf.getFileName()); adj.setTipoArchivo(uf.getContentType()); adj.setTamanhoArchivo(uf.getSize()); this.listaAdjuntoArticulo.add(adj); } catch (IOException ex) { Logger.getLogger(ArticuloController.class .getName()).log(Level.SEVERE, null, ex); } } /** * getter Imagen a mostrar desde Uploaded * * @return */ public StreamedContent imagenToDisplay() { FacesContext context = FacesContext.getCurrentInstance(); String indice = context.getExternalContext().getRequestParameterMap().get("index"); //Si no se envia un parametro, asume el primer elemento de la lista if (indice == null) { indice = "0"; } if (context.getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) { // So, we're rendering the HTML. Return a stub StreamedContent so that it will generate right URL. return new DefaultStreamedContent(); } else { ArticuloAdjunto adj = this.listaAdjuntoArticulo.get(Integer.parseInt(indice)); StreamedContent file; if (adj != null) { InputStream stream = new ByteArrayInputStream(adj.getArchivo()); file = new DefaultStreamedContent(stream, adj.getTipoArchivo(), adj.getNombreArchivo()); } else { file = new DefaultStreamedContent(); } return file; } } /** * Descargar un adjunto desde la BD * * @param adj * @return */ public StreamedContent download(ArticuloAdjunto adj) { if (adj.getNombreArchivo() != null) { InputStream stream = new ByteArrayInputStream(adj.getArchivo()); StreamedContent file = new DefaultStreamedContent(stream, adj.getTipoArchivo(), adj.getNombreArchivo()); return file; } else { JSFutil.addErrorMessage("No dispone de adjuntos para visualizar..."); String noContent = "<html><h1>Sin adjunto...</></html>"; return new DefaultStreamedContent(new ByteArrayInputStream(noContent.getBytes()), "text/html", "No existe Archivo"); } } public void generateAlias() { if (this.articulo.getAliasArticulo() == null) { this.articulo.setAliasArticulo(JSFutil.getFriendlyURI(this.articulo.getNombreArticulo())); } } public void siHayCambios() { this.hayCambios = true; } public StreamedContent imagenToDisplayFromId() throws FileNotFoundException { FacesContext context = FacesContext.getCurrentInstance(); String id = context.getExternalContext().getRequestParameterMap().get("id"); if (context.getCurrentPhaseId() == PhaseId.RENDER_RESPONSE) { // So, we're rendering the HTML. Return a stub StreamedContent so that it will generate right URL. return new DefaultStreamedContent(); } else { Articulo a = articuloDAO.find(Integer.parseInt(id)); List<ArticuloAdjunto> listaAdj = articuloAdjuntoDAO.findAllbyArticulo(a.getIdArticulo()); ArticuloAdjunto adj = null; if (!listaAdj.isEmpty()) { adj = listaAdj.get(0); } StreamedContent file; if (adj != null) { InputStream stream = new ByteArrayInputStream(adj.getArchivo()); file = new DefaultStreamedContent(stream, adj.getTipoArchivo(), adj.getNombreArchivo()); } else { ServletContext servletContext = (ServletContext) context.getExternalContext().getContext(); String pathToWeb = servletContext.getRealPath(File.separator); File f = new File(pathToWeb + "img/noimage.png"); file = new DefaultStreamedContent(new FileInputStream(f)); } return file; } } }
Java
UTF-8
119
1.851563
2
[]
no_license
package interfaces; public interface CallbackEnabledLeftGraph { void onCallbackEnabledLeftGraph(String value); }
C
UTF-8
978
2.71875
3
[]
no_license
#ifndef _LEVEL_H #define _LEVEL_H #include "rooms.h" typedef struct level* level_t; enum level_tile_mask { LEVEL_TILE_BOTTOM = 1, LEVEL_TILE_LEFT = 2, LEVEL_TILE_RIGHT = 4, LEVEL_TILE_TOP = 8, LEVEL_TILE_TYPEMASK = 255, }; #define TILE_TYPE_SHIFT 8 #define LEVEL_TILE_SIZE 16.0f level_t level_create(rooms_t rooms, int width, int height); void level_destroy(level_t level); void level_generate(level_t level, int seed); void level_place_wall(level_t level, int x, int y); void level_place_floor(level_t level, int x, int y); void level_place_room(level_t level, struct room* room, int x, int y); int level_walkable_at(level_t level, float x, float y); tilemap_t level_get_tiles_background(level_t level); tilemap_t level_get_tiles(level_t level); tilemap_t level_get_tiles_foreground(level_t level); void level_get_tile_dimensions(level_t level, int* width, int* height); void level_get_dimensions(level_t level, float* width, float* height); #endif
SQL
UTF-8
2,386
3.140625
3
[]
no_license
-- phpMyAdmin SQL Dump -- version 4.9.5 -- https://www.phpmyadmin.net/ -- -- Host: localhost:3306 -- Generation Time: Mar 02, 2021 at 08:05 AM -- Server version: 5.7.24 -- PHP Version: 7.4.1 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Database: `classicmodels` -- -- -------------------------------------------------------- -- -- Table structure for table `orderdetails` -- CREATE TABLE `orderdetails` ( `productName` varchar(255) NOT NULL, `priceEach` int(11) NOT NULL, `quantityOrdered` int(11) NOT NULL, `productCode` int(11) NOT NULL, `orderLineNumber` int(11) NOT NULL, `orderNumber` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data for table `orderdetails` -- INSERT INTO `orderdetails` (`productName`, `priceEach`, `quantityOrdered`, `productCode`, `orderLineNumber`, `orderNumber`) VALUES ('Champagne', 35, 5, 2, 1, 10), ('Coussin', 20, 2, 9, 2, 10), ('Cadre décoratif', 9, 3, 1, 3, 9), ('Tapis salon', 80, 1, 5, 4, 8), ('Bonnet', 25, 1, 3, 5, 7), ('Encens', 1, 12, 1, 6, 6), ('Bougie cire végétale', 8, 34, 7, 7, 5), ('Miroir', 67, 4, 4, 8, 4), ('Service de Table', 159, 2, 8, 9, 3), ('Collier perles', 80, 1, 6, 10, 2), ('Bombe pour le bain', 7, 6, 15, 11, 1), ('Stylo bille bleu', 2, 14, 11, 12, 2), ('Gourde', 19, 1, 13, 13, 3), ('Cookie', 3, 50, 14, 14, 4), ('Guirlande lumineuse', 6, 18, 12, 15, 5), ('Huile massage', 35, 3, 10, 16, 6), ('Livre BD', 16, 8, 8, 17, 7), ('Bracelet fantaisie', 25, 3, 9, 18, 8), ('Bague plaquée or', 258, 1, 1, 19, 9), ('Chocolat noir', 4, 8, 6, 20, 10); -- -- Indexes for dumped tables -- -- -- Indexes for table `orderdetails` -- ALTER TABLE `orderdetails` ADD PRIMARY KEY (`orderLineNumber`); -- -- AUTO_INCREMENT for dumped tables -- -- -- AUTO_INCREMENT for table `orderdetails` -- ALTER TABLE `orderdetails` MODIFY `orderLineNumber` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=21; COMMIT; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
C++
UTF-8
3,628
3.078125
3
[]
no_license
#include <iostream> #include <cmath> #include <string> #include <vector> #include <ctime> #include <cstdlib> #include <iomanip> using namespace std; class Image{ private: string filename; public: double currentScore; double expectedWin; Image(string _filename) : filename(_filename), currentScore(1400), expectedWin(0.5) {} /* float getCurrentScore(); void setCurrentScore(float x); float getExpectedWin(); void setExpectedWin(float x);*/ void Show(); }; class Picture { private: vector<Image> images; // Image lostImage; // Image winImage; public : // Picture() {} pair<int, int> PickTwo(void); void UpdataScore(int winid, int loseid); void AddImage(string filename); void ShowId(int id); private: float computeNewScore(int result,float oldScore,float expectedWin); }; pair<int, int> Picture:: PickTwo(void){ srand((int)time(NULL)); //suppose the scores are between 1000 to 1800 int num = images.size(); int x = rand()%num ; int xscore = images[x].currentScore; vector<Image> temp; int a[num];//record the recordance of temp and images int cnt=0; for (int i = 0; i<num;i++ ) { if (images[i].currentScore <xscore + 100&&images[i].currentScore >xscore - 100&&i!=x) { temp[cnt] = images[i]; cnt++; a[cnt] = i; } } srand((int)time(NULL)); int y = rand()%cnt; int j = 0; for (j = 0;j < num;j++) { if (a[y] = j) break; } pair<int,int> data = make_pair(x,j); return data; } void Picture::UpdataScore(int winid, int loseid){ Image winImage = images[winid]; Image lostImage = images[loseid]; if(winImage.currentScore == lostImage.currentScore){ winImage.expectedWin = 0.5; lostImage.expectedWin = 0.5; return; } else{ float winSub = lostImage.currentScore - winImage.currentScore; float wintemp = winSub/400; float lostSub = winImage.currentScore - lostImage.currentScore; float losttemp = lostSub/400; winImage.expectedWin = 1/(1+(float)pow(10,wintemp)); lostImage.expectedWin = 1/(1+(float)pow(10,losttemp)); } float oldScore = winImage.currentScore; winImage.currentScore = computeNewScore(1,oldScore,winImage.expectedWin); oldScore = lostImage.currentScore; lostImage.currentScore = computeNewScore(0,oldScore,lostImage.expectedWin); return; } /*void Picture::computeExpectedWin(){ if(winImage.currentScore == lostImage.currentScore){ winImage.expectedWin = 0.5; lostImage.expectedWin = 0.5; return; } else{ float winSub = lostImage.currentScore - winImage.currentScore; float wintemp = winSub/400; float lostSub = winImage.currentScore - lostImage.currentScore; float losttemp = lostSub/400; winImage.expectedWin = 1/(1+(float)pow(10,wintemp)); lostImage.expectedWin = 1/(1+(float)pow(10,losttemp)); return; } } void Picture::toComputeNewScore(){ float oldScore = winImage.currentScore; winImage.currentScore = computeNewScore(1,oldScore,winImage.expectedWin); oldScore = lostImage.currentScore; lostImage.currentScore = computeNewScore(0,oldScore,lostImage.expectedWin); return; } */ float Picture:: computeNewScore(int result,float oldScore,float expectedWin){ float temp = result - expectedWin; float currentScore = oldScore + 10 * temp; return currentScore; } int main(){ }
Java
UTF-8
532
3.5625
4
[]
no_license
package es.cj.fundamentos01.datos; import java.util.Scanner; public class EjercicioTres { // Pedir el radio de un circulo y calcular su area y su longitud private static Scanner sc = new Scanner(System.in); public static void main(String[] args) { System.out.println("Radio: "); double radio = sc.nextDouble(); double area = Math.PI * Math.pow(radio, 2); System.out.println("El area es " + area); double longitud = 2 * radio * Math.PI; System.out.println("La longitud es " + longitud); } }
C
UTF-8
338
3.015625
3
[]
no_license
///getting the current directory name for shell void get_direc_name(char *var, int iscommand){ char temp[MAX_PATH]; char *path = getcwd(temp,sizeof(temp)); if(path!=NULL){ strcpy(var,temp); if(iscommand==1){ printf("%s%s\n%s",COLOR_YELLO,var,COLOR_BLUE); } } else{ printf("error in getting name"); } }
Java
UTF-8
782
2
2
[]
no_license
package com.app.interfaces; import com.app.interfaces.fallback.ProductFallbackFactory; import com.app.interfaces.response.ProductResponse; import com.app.interfaces.response.Result; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; /** * @author Feinik * @discription * @date 2019/9/25 * @since 1.0.0 */ @FeignClient(value = "app-product", path = ProductFacade.PATH_PREFIX, fallbackFactory = ProductFallbackFactory.class) public interface ProductFacade { String PATH_PREFIX = "/product"; @GetMapping(value = "getProductByCode/{productCode}") Result<ProductResponse> getProductByCode(@PathVariable("productCode") String productCode); }
SQL
UTF-8
111
3.109375
3
[]
no_license
SELECT a.FirstName,a.LastName,b.City,b.State FROM Person as a left join Address as b on a.PersonID = b.PersonID
Java
UTF-8
1,195
2.828125
3
[ "MIT" ]
permissive
package command; import java.awt.geom.Point2D; import models.MCircleElement; import models.MElement; import models.MGraphSlot; import models.MSquareElement; import models.MTriangleElement; public class AddElementCommand extends AbstractCommand{ MGraphSlot model; MElement element = null; String type; Point2D lastPosition; public AddElementCommand(MGraphSlot model, Point2D lastPosition, String type){ this.model = model; this.lastPosition = lastPosition; this.type = type; } @Override public void doCommand() { if (element == null){ if (type.equals("Circle")){ element = new MCircleElement("Circle " + model.getChildCount(), lastPosition); } else if (type.equals("Square")){ element = new MSquareElement("Square " + model.getChildCount(), lastPosition); } else if (type.equals("Triangle")){ element = new MTriangleElement("Triangle " + model.getChildCount(), lastPosition); } } model.deselectAll(); model.addElement(element); model.setFocus(); } @Override public void undoCommand() { model.deselectAll(); element.setSelected(true); model.removeSelected(); model.setFocus(); } }
Python
UTF-8
2,771
2.734375
3
[]
no_license
import os import pickle from shutil import which from selenium import webdriver from selenium.webdriver.chrome.options import Options from config import HEADLESS_MODE, SELENIUM_TIMEOUT, TRANSLATION_DICTIONARY_FILENAME def make_headless_selenium_driver(headless_mode=HEADLESS_MODE, timeout=SELENIUM_TIMEOUT): binary_path = which('chromedriver') options = Options() if headless_mode: options.add_argument('--headless') driver = webdriver.Chrome(executable_path=binary_path, chrome_options=options) driver.implicitly_wait(timeout) return driver def pretty_print(translations): for source, translation in translations.items(): print(f"{source}\n{translation}\n") class PersistedDictionary(dict): """ Extends the dictionary class to have disk persistence as a pickle. """ def __init__(self, dictionary, **kwargs): if PersistedDictionary.__already_exists(): dictionary = PersistedDictionary.__restore(dictionary) super().__init__(dictionary, **kwargs) def update(self,*args, **kwargs): super(PersistedDictionary, self).update(*args,**kwargs) self.persist() def persist(self): with open(TRANSLATION_DICTIONARY_FILENAME, 'wb') as file: pickle.dump(self, file) def delete_pickle(self): if os.path.exists(TRANSLATION_DICTIONARY_FILENAME): os.remove(TRANSLATION_DICTIONARY_FILENAME) @staticmethod def __already_exists(): return os.path.exists(TRANSLATION_DICTIONARY_FILENAME) @staticmethod def __restore(translation_dictionary): if os.path.exists(TRANSLATION_DICTIONARY_FILENAME): with open(TRANSLATION_DICTIONARY_FILENAME, 'rb') as file: restored_dictionary = pickle.load(file) for key in translation_dictionary.keys(): if key in restored_dictionary: if restored_dictionary[key]: translation_dictionary[key]=restored_dictionary[key] return translation_dictionary languages = ['en', 'es', 'de', 'zh', 'fr', 'da'] languages_map = { 'deu': 'de', 'esp': 'es', 'eng': 'en', 'en-us': 'en', 'en-US': 'en' } deepl_languages = { 'en': 'en-US' } to_deepl_language = lambda lang: deepl_languages[lang] if lang in deepl_languages else f"{lang.lower()}-{lang.upper()}" is_recognized_language = lambda language: language in languages or language in languages_map def infer_language(language): language = language.lower() if language in languages: return language if language in languages_map: return languages_map[language] raise Exception(f"Could not infer language from '{language}'")
Java
UTF-8
4,959
2.484375
2
[]
no_license
package ios; import helper.MobileTestingHelper; import io.appium.java_client.AppiumDriver; import io.appium.java_client.ios.IOSDriver; import io.appium.java_client.remote.MobileCapabilityType; import org.openqa.selenium.By; import org.openqa.selenium.remote.DesiredCapabilities; import org.testng.annotations.AfterClass; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import java.net.URL; import java.util.Set; import java.util.concurrent.TimeUnit; import static org.junit.Assert.assertTrue; /** * Created by Moorthi.Subramani on 10/25/2016. * Basic appium test to connect with manually inject the appium URL * Direct appium Url or appium manual URL started from mobile testing */ public class DARestAppiumSafari { String appiumURL = null; private AppiumDriver driver; private MobileTestingHelper mobileTestingHelper; Integer mcd = 30083; Integer applicationId = -1; public DARestAppiumSafari() { //applicationId = 18889; //update your existing applicationId here } public DARestAppiumSafari(Integer appId){ applicationId = appId; } @BeforeClass //Executed once for all the script in the class public void setUp() throws Exception { System.out.println("Starting ios Driver with DA REST Interface"); mobileTestingHelper = new MobileTestingHelper(); //Parameters: mcd, // application file (upload to mobile testing repository and install app to device //Response: true or false (success or fail) System.out.println("for mcd -" + mcd); boolean status = mobileTestingHelper.startForBrowser(mcd); //If response is success all required information is available in mobileTestingHelper object //mobileTestingHelper.appiumUrl --> appium url to pass to appium driver //ANDROID: //mobileTestingHelper.getApplicationInfo().appPackage --> application package to for Appium DesiredCapabilities appPackage //mobileTestingHelper.getApplicationInfo().appActivity --> application package to for Appium DesiredCapabilities appActivity //ios //mobileTestingHelper.getApplicationInfo().bundleId --> application package to for Appium DesiredCapabilities bundleId if(status) { Thread.sleep(5000); startDriver(mobileTestingHelper.appiumUrl); System.out.println("Started ios Driver"); } else { System.out.println("ios Driver Start Failed"); } } private void startDriver(String appiumURL) throws Exception { DesiredCapabilities capabilities = new DesiredCapabilities(); //deviceName - MUST capabilities.setCapability("deviceName","Apple iPhone 6"); //platformVersion - MUST capabilities.setCapability("platformVersion", "9.3.2"); //platformName - MUST capabilities.setCapability("platformName", "ios"); capabilities.setCapability("browserName", "Safari"); try { //Intialize the driver, try to connect to the server (appium URL mentioned server) //New appium session will be intialized (this will create Apium session) MobileTesting session will be issued when appium URL is generated itself) driver = new IOSDriver(new URL(appiumURL), capabilities); driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS); } catch (Exception exp) { if(driver == null && mobileTestingHelper != null) { mobileTestingHelper.logoutSession(); Thread.sleep(30000); System.out.println("Logoff user session"); } throw exp; } } @Test //At this point Android driver is initialized fine and communication with the device is established //Script will be executed accordingly public void executeScript() throws Exception { Thread.sleep(2000); //driver.findElement(By.name("Add New Expense")).click(); driver.get("http://www.google.com"); Set<String> contextNames = driver.getContextHandles(); for(String contextname: contextNames){ System.out.println(contextname); } Thread.sleep(3000); assertTrue(true); } @AfterClass //All the script execution is done, have to quit the driver to delete the session from the appium server public void tearDown() throws Exception { //driver.closeApp(); if(mobileTestingHelper != null) { mobileTestingHelper.logoutSession(); Thread.sleep(30000); System.out.println("Logoff user session"); } try { if(driver != null) driver.quit(); } catch (Exception exp) { System.out.println("driver quit exception, because of app uninstall via Appium"); } } }
Markdown
UTF-8
3,362
3.546875
4
[]
no_license
# Your First Rails Application (OUT OF DATE) So you’ve installed RVM, installed Ruby, and installed rails. Now what? I’m going to take you through the first steps to develop your first rails application. It is going to be a simple blog with a static home page. In future episodes, we will expand on this blogging application, so don’t delete it. Creating the application ------------------------ The first step is to create an empty rails application. We can do this with the rails new command. The command is in the form: `rails new APP_NAME`. I am going to use the name rails_blog for mine user$ rails new rails_blog next cd into the directory user$ cd rails_blog You may notice that this command has created many files. Here is the directory tree with descriptions for folders and files. ``` stuff ``` Now that we have our application set up we need it to do something. In order for this to do anything we need three things: model, controller, and view. Models ------ Models are the building block of rails. They determine the relationship between the controller and the database. A model for something like a blog might be called post. This would mean the database that it connects to would be called posts and the controller would be called the posts_controller or the post_controller (depending on how you have your routes set up) Controllers ----------- Controllers do all of the back-end computation and logic. They are responsible for formulating database queries and sending them to the model, which interfaces with the actual database. The standard rails application with RESTful routing will have controllers that have the following functions - new - calls the new.html.erb view - will create a new record but will not save it - typically posts results to create function - create - does not call a view - will create and save a new record based on posted parameters from new - index - calls index.html.erb view - typically displays a list or page that shows all instances of a model - show - calls show.html.erb view - typically displays a single instance of a model - edit - calls edit.html.erb view - typically shows a form to edit an instance of a model - typically posts results to update function - update - does not call a view - updates an instance of a model based on posted parameters from edit - destroy - deletes an instance of a model Views ----- Views are in charge of what displays to the user. They typically have the extension .html.erb The reason they have multiple extensions is that rails can process files more than one time. The more extensions you add on, the more preprocessors the file will be run through. This means that by adding .erb to any file, you can now put inline ruby script in the file and it will be processed. This is important in views because we want to display dynamic content and the view has to be able to get output from the controller (which, in turn has made the queries to the database). Typically (as explained in the controllers) the standard views of a RESTful controller are - index.html.erb - show.html.erb - new.html.erb - edit.html.erb Their names are pretty self explanatory Migrations ---------- Migrations are files that tell the rake script what changes to make to the database such as adding and dropping tables and columns.
Java
UTF-8
10,396
2.03125
2
[]
no_license
package com.prateekraina.gamersden; import android.content.Intent; import android.os.Bundle; import android.support.design.widget.Snackbar; import android.support.design.widget.TextInputLayout; import android.support.v7.app.AppCompatActivity; import android.text.Editable; import android.text.TextWatcher; import android.view.View; import android.widget.Button; import android.widget.EditText; import com.android.volley.Request; import com.android.volley.RequestQueue; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.StringRequest; import com.android.volley.toolbox.Volley; import java.util.HashMap; import java.util.Map; public class AddDetailActivity extends AppCompatActivity { private EditText cafeNameET; private EditText cafeAddressET; private EditText cafeLocationET; private EditText cafeCityET; private EditText cafeHourlyRateET; private Button cafeSubmitBtn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_detail); getSupportActionBar().setDisplayHomeAsUpEnabled(true); cafeNameET = (EditText)findViewById(R.id.cafeName); cafeAddressET = (EditText)findViewById(R.id.cafeAddress); cafeLocationET = (EditText)findViewById(R.id.cafeLocation); cafeCityET = (EditText)findViewById(R.id.cafeCity); cafeHourlyRateET = (EditText)findViewById(R.id.cafeHourlyRate); cafeSubmitBtn = (Button)findViewById(R.id.cafeSubmitDataButton); final TextInputLayout cafeNameInputLayout = (TextInputLayout) findViewById(R.id.input_layout_cafeName); final TextInputLayout cafeAddressInputLayout = (TextInputLayout) findViewById(R.id.input_layout_address); final TextInputLayout cafeLocationInputLayout = (TextInputLayout) findViewById(R.id.input_layout_location); final TextInputLayout cafeCityInputLayout = (TextInputLayout) findViewById(R.id.input_layout_city); final TextInputLayout cafeHourlyRateInputLayout = (TextInputLayout) findViewById(R.id.input_layout_hourlyRate); cafeNameET.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (!cafeNameET.getText().toString().trim().equals("")) { if (cafeNameInputLayout != null) { cafeNameInputLayout.setError(null); } } } @Override public void afterTextChanged(Editable s) { } }); cafeAddressET.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (!cafeAddressET.getText().toString().trim().equals("")) { if (cafeAddressInputLayout != null) { cafeAddressInputLayout.setError(null); } } } @Override public void afterTextChanged(Editable s) { } }); cafeLocationET.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (!cafeLocationET.getText().toString().trim().equals("")) { if (cafeLocationInputLayout != null) { cafeLocationInputLayout.setError(null); } } } @Override public void afterTextChanged(Editable s) { } }); cafeCityET.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (!cafeCityET.getText().toString().trim().equals("")) { if (cafeCityInputLayout != null) { cafeCityInputLayout.setError(null); } } } @Override public void afterTextChanged(Editable s) { } }); cafeHourlyRateET.addTextChangedListener(new TextWatcher() { @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { if (!cafeHourlyRateET.getText().toString().trim().equals("")) { if (cafeHourlyRateInputLayout != null) { cafeHourlyRateInputLayout.setError(null); } } } @Override public void afterTextChanged(Editable s) { } }); cafeSubmitBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { int checkValue=1; //to check if some field is empty or not we keep check value. if (cafeNameET.getText().toString().trim().equals("")) { if (cafeNameInputLayout != null) { cafeNameInputLayout.setErrorEnabled(true); cafeNameInputLayout.setError("Cafe Name not entered"); } checkValue=0; } if (cafeAddressET.getText().toString().trim().equals("")) { if (cafeAddressInputLayout != null) { cafeAddressInputLayout.setErrorEnabled(true); cafeAddressInputLayout.setError("Address not entered"); } checkValue=0; } if (cafeLocationET.getText().toString().trim().equals("")) { if (cafeLocationInputLayout != null) { cafeLocationInputLayout.setErrorEnabled(true); cafeLocationInputLayout.setError("Location not entered"); } checkValue=0; } if (cafeCityET.getText().toString().trim().equals("")) { if (cafeCityInputLayout != null) { cafeCityInputLayout .setErrorEnabled(true); cafeCityInputLayout .setError("City not entered"); } checkValue=0; } if (cafeHourlyRateET.getText().toString().trim().equals("")) { if (cafeHourlyRateInputLayout != null) { cafeHourlyRateInputLayout .setErrorEnabled(true); cafeHourlyRateInputLayout .setError("Hourly Rate not entered"); } checkValue=0; } if(checkValue==1) { addData(); Intent intent = new Intent(AddDetailActivity.this, com.prateekraina.gamersden.MainActivity.class); intent.putExtra("sentFrom","AddDetailActivity"); startActivity(intent); } } }); } private void addData(){ StringRequest stringRequest = new StringRequest(Request.Method.POST, com.prateekraina.gamersden.MyConfig.ADD_DATA_URL, new Response.Listener<String>() { @Override public void onResponse(String response) { //Toast.makeText(AddDetailActivity.this,response,Toast.LENGTH_LONG).show(); View rootView = AddDetailActivity.this.getWindow().getDecorView().findViewById(android.R.id.content); Snackbar snackbar = Snackbar.make(rootView, response, Snackbar.LENGTH_LONG); snackbar.show(); // Intent intent = new Intent(AddDetailActivity.this,MainActivity.class); // startActivity(intent); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { //Toast.makeText(AddDetailActivity.this,error.toString(),Toast.LENGTH_LONG).show(); View rootView = AddDetailActivity.this.getWindow().getDecorView().findViewById(android.R.id.content); Snackbar snackbar = Snackbar.make(rootView, error.toString(), Snackbar.LENGTH_LONG); snackbar.show(); } }){ @Override protected Map<String,String> getParams(){ Map<String,String> params = new HashMap<String, String>(); params.put(com.prateekraina.gamersden.MyConfig.NAME_KEY,cafeNameET.getText().toString().trim()); params.put(com.prateekraina.gamersden.MyConfig.ADDRESS_KEY,cafeAddressET.getText().toString().trim()); params.put(com.prateekraina.gamersden.MyConfig.LOCATION_KEY,cafeLocationET.getText().toString().trim()); params.put(com.prateekraina.gamersden.MyConfig.CITY_KEY,cafeCityET.getText().toString().trim()); params.put(com.prateekraina.gamersden.MyConfig.HOURLY_RATE_KEY,cafeHourlyRateET.getText().toString().trim()); return params; } }; RequestQueue requestQueue = Volley.newRequestQueue(this); requestQueue.add(stringRequest); } }
Markdown
UTF-8
6,631
2.6875
3
[]
no_license
# 禅道 11.6版本 任意文件读取漏洞 ## 漏洞描述 禅道 11.6 版本中对用户接口调用权限过滤不完善,导致调用接口执行SQL语句导致SQL注入 ## 影响版本 > [!NOTE] > > 禅道 11.6 ## 环境搭建 这里使用docker环境搭建 ``` docker run --name zentao_v11.6 -p 8084:80 -v /u01/zentao/www:/app/zentaopms -v /u01/zentao/data:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=123456 -d docker.io/yunwisdom/zentao:v11.6 ``` 访问 **http://xxx.xxx.xxx.xxx:8084** 按步骤安装即可 ![](image/zentao-1.png) ## 漏洞复现 这里造成漏洞的原因同样是调用接口权限无限制的原因 接口出现漏洞的原因具体参考可以查看上一篇 **禅道 11.6版本 SQL注入漏洞** 关于此漏洞的完整分析 ### 第一种方法 查看**module/file/moudel.php**下的**parseCSV方法** ```php public function parseCSV($fileName) { $content = file_get_contents($fileName); /* Fix bug #890. */ $content = str_replace("\x82\x32", "\x10", $content); $lines = explode("\n", $content); $col = -1; $row = 0; $data = array(); foreach($lines as $line) { $line = trim($line); $markNum = substr_count($line, '"') - substr_count($line, '\"'); if(substr($line, -1) != ',' and (($markNum % 2 == 1 and $col != -1) or ($markNum % 2 == 0 and substr($line, -2) != ',"' and $col == -1))) $line .= ','; $line = str_replace(',"",', ',,', $line); $line = str_replace(',"",', ',,', $line); $line = preg_replace_callback('/(\"{2,})(\,+)/U', array($this, 'removeInterference'), $line); $line = str_replace('""', '"', $line); /* if only one column then line is the data. */ if(strpos($line, ',') === false and $col == -1) { $data[$row][0] = trim($line, '"'); } else { /* if col is not -1, then the data of column is not end. */ if($col != -1) { $pos = strpos($line, '",'); if($pos === false) { $data[$row][$col] .= "\n" . $line; $data[$row][$col] = str_replace('&comma;', ',', $data[$row][$col]); continue; } else { $data[$row][$col] .= "\n" . substr($line, 0, $pos); $data[$row][$col] = trim(str_replace('&comma;', ',', $data[$row][$col])); $line = substr($line, $pos + 2); $col++; } } if($col == -1) $col = 0; /* explode cols with delimiter. */ while($line) { /* the cell has '"', the delimiter is '",'. */ if($line{0} == '"') { $pos = strpos($line, '",'); if($pos === false) { $data[$row][$col] = substr($line, 1); /* if line is not empty, then the data of cell is not end. */ if(strlen($line) >= 1) continue 2; $line = ''; } else { $data[$row][$col] = substr($line, 1, $pos - 1); $line = substr($line, $pos + 2); } $data[$row][$col] = str_replace('&comma;', ',', $data[$row][$col]); } else { /* the delimiter default is ','. */ $pos = strpos($line, ','); /* if line is not delimiter, then line is the data of cell. */ if($pos === false) { $data[$row][$col] = $line; $line = ''; } else { $data[$row][$col] = substr($line, 0, $pos); $line = substr($line, $pos + 1); } } $data[$row][$col] = trim(str_replace('&comma;', ',', $data[$row][$col])); $col++; } } $row ++; $col = -1; } return $data; } ``` 这里可以看到**以file为模块名、parseCSV为方法名去调用**读取文件 读取的文件名**$filename**参数可控,例如读取**/etc/passwd** ``` http://xxx.xxx.xxx.xxx/api-getModel-file-parseCSV-fileName=/etc/passwd ``` ![](image/zentao-22.png) > [!NOTE] > > 注意以 .php .txt 结尾的会被 /framework/base/router.class.php中的parsePathInfo方法 过滤 ### 第二种方法 查看**module/api/moudel.php**下的**getMethod方法** ```php public function getMethod($filePath, $ext = '') { $fileName = dirname($filePath); $className = basename(dirname(dirname($filePath))); if(!class_exists($className)) helper::import($fileName); $methodName = basename($filePath); $method = new ReflectionMethod($className . $ext, $methodName); $data = new stdClass(); $data->startLine = $method->getStartLine(); $data->endLine = $method->getEndLine(); $data->comment = $method->getDocComment(); $data->parameters = $method->getParameters(); $data->className = $className; $data->methodName = $methodName; $data->fileName = $fileName; $data->post = false; $file = file($fileName); for($i = $data->startLine - 1; $i <= $data->endLine; $i++) { if(strpos($file[$i], '$this->post') or strpos($file[$i], 'fixer::input') or strpos($file[$i], '$_POST')) { $data->post = true; } } return $data; } ``` 这里与第一种大同小异,只是调用了不同模块的方法 看到**$fileName = dirname($filePath);**这段则为返回的目录名 所以读取**/etc/passwd**则需要写为**/etc/passwd/1**来绕过 ``` http://xxx.xxx.xxx.xxx/api-getModel-api-getMethod-filePath=/etc/passwd/1 ``` ![](image/zentao-23.png)
Go
UTF-8
1,249
2.890625
3
[ "BSD-2-Clause" ]
permissive
// Copyright (c) 2015, Nick Patavalis (npat@efault.net). // All rights reserved. // Use of this source code is governed by a BSD-style license that can // be found in the LICENSE file. // +build linux freebsd netbsd openbsd darwin dragonfly solaris // Bit-twiddling convenience methods for type TcFlag package termios // Clr clears (lowers) in w the flags that are set in f. It does not // affect the other flags in w. Returns (a pointer to) w. func (w *TcFlag) Clr(f TcFlag) *TcFlag { *w &^= f; return w } // Set sets (raises) in w the flags that are set in f. It does not // affect the other flags in w. Returns (a pointer to) w. func (w *TcFlag) Set(f TcFlag) *TcFlag { *w |= f; return w } // Any returns true if any of flags set in f are also set in w. func (w *TcFlag) Any(f TcFlag) bool { return *w&f != 0 } // All returns true if all of the flags set in f are also set in w. func (w *TcFlag) All(f TcFlag) bool { return *w&f == f } // Msk returns the flags in w masked by f (that is, the values of the // flags in w for which the equivalent flags in f are set). It does // not modify w. func (w *TcFlag) Msk(f TcFlag) TcFlag { return *w & f } // Val returns the flags in w (i.e the value pointed-to by w) func (w *TcFlag) Val() TcFlag { return *w }
Python
UTF-8
4,179
3.3125
3
[]
no_license
import _sqlite3 as db class Transaction(): def __init__(self): ''' Инициализируем новую базу данных для хранения транзакций ''' self.conn = db.connect('transaction.db') self.cursor = self.conn.cursor() sql_query = ''' create table if not exists expenses( id integer primary key autoincrement, amount number, category string, date string, message string ) ''' self.cursor.execute(sql_query) # сохраняем изменения self.conn.commit() def log(self,amount, category = None, message=None): ''' Логируем наши транзакции :param amount: число :param category: категория расходов :param message: (опиционально) описание транзакции где была совершена, на что конкретно были потрачены деньги и т.д :return: ''' from datetime import datetime date = str(datetime.now()) # сохраняем сегодняшнюю дату data = (amount, category, date, message) self.conn = db.connect('transaction.db') self.cursor = self.conn.cursor() sql_query = 'INSERT INTO expenses VALUES (?, ?, ?, ?)' self.cursor.execute(sql_query, data) # сохраняем изменения self.conn.commit() def delete_all_database(self): # удаляет всю базу данных self.conn = db.connect('transaction.db') self.cursor = self.conn.cursor() sql_query = ''' delete from expenses ''' self.cursor.execute(sql_query) self.conn.commit() ''' Пока не знаю как сделать def delete_from_category(self,category): #удаляет все транзакции из выбранной категории self.conn = db.connect('transaction.db') self.cursor = self.conn.cursor() sql_query = delete from expenses where category = '{}' self.cursor.execute(sql_query) self.conn.commit()''' def delete_transaction(self,id): self.conn = db.connect('transaction.db') self.cursor = self.conn.cursor() sql_query = ''' delete from expenses where id = ? ''' self.cursor.execute(sql_query) self.conn.commit() def view(self, category = None): ''' Функция которая показывает все траты на выбранную категорию, если категория не выюрана, то показывает все совершенные транзакции :param category: категория расходов :return: ''' self.conn = db.connect('transaction.db') self.cursor = self.conn.cursor() if category: # если задана категория, то показываем общую сумму в категории sql_query1 = ''' select * from expenses where category = '{}' '''.format(category) sql_query2 = ''' select sum(amount) from expenses where category = '{}' '''.format(category) else: #иначе показываем все транзакции и общую сумму по всем транзакциям sql_query1 = ''' select * from expenses '''.format(category) sql_query2 = ''' select sum(amount) from expenses '''.format(category) self.cursor.execute(sql_query1) result = self.cursor.fetchall() self.cursor.execute(sql_query2) total_sum = self.cursor.fetchone()[0] return total_sum, result t1 = Transaction() t1.log(2000,'food') t1.log(1000,'food')
Java
UTF-8
1,034
2.640625
3
[]
no_license
package shooting; import java.awt.Color; import java.awt.Font; import java.awt.Graphics; import java.util.Random; import gameListener.GameKeyLisener; import panels.MainFrame; public class Player { /**GameKeyListener Class*/ private GameKeyLisener key; private MainFrame mf; private Game2 game2; private int x=320; private int y=490; private int f=1; private int i=0; private Shoot shoot; private Player player; public Player(MainFrame mf,Game2 gp) { key=new GameKeyLisener(); this.mf=mf; this.mf.addKeyListener(key); this.game2 = gp; } public void move(){ if(key.isPlayerB_left_key_Pressed()){ x-=5; } if(key.isPlayerB_right_key_Pressed()){ x+=5; } } public int getX(){ return this.x; } public int getY(){ y-=3; return this.y; } public void setX(int x){ this.x=x; } public void playerGraphics(Graphics g) { g.setColor(Color.RED); g.fillRect(x,500, 50, 50); g.setColor(Color.BLACK); g.setFont(new Font("Sanserif",Font.BOLD,40)); g.drawString("a",x+15,535); } }
SQL
UTF-8
191
2.703125
3
[]
no_license
SELECT timeStamp, temperature FROM ThermometerObservation WHERE timestamp>'2017-11-27T04:16:00Z' AND timestamp<'2017-11-28T04:16:00Z' AND SENSOR_ID='d762ed2e_ba0e_4761_9c46_d797bcc5024b'
Markdown
UTF-8
3,048
2.765625
3
[ "MIT" ]
permissive
# Fingerprinter ```` @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ @################################@ @######## ########@ @######## ########@ @######## ################@ @######## ################@ @######## ################@ @######## ##########@ @######## ##########@ @######## ################@ @######## ################@ @######## ##Fingerprinter#@ @######## #######by#######@ @######## #####Philip#####@ @######## #####Marti######@ @################################@ @@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@ ```` Welcome to the *Fingerprinter* project. The main purpose of this project is to provide a proof-of-concept implementation of a remote operating system fingerprinting method based on protocol header analysis. In addition there is also a function for a cloud provider detection mechanism based on TCP/IP networking. This repository is part of my thesis to receive my bachelor's degree in computer sciences with specialization in information security from `Fernfachhochschule Schweiz (FFHS)`. Anyone interested in the thesis can contact me (only available in german). ## Installation First, make sure you have `python-3.8` (including `pip`) locally installed and added to your PATH. Then clone this repository (`git clone https://github.com/martiph/Fingerprinter.git`) onto your local machine and create a python virtual environment (virtualenv). To install all necessary packages, activate the virtualenv and run `pip install -r /path/to/requirements.txt`. Probably you will need to alter the command slightly. For example if you work on a linux-system, you probably need to use `pip3` instead of `pip`. An example on how to create and activate a virtual environment is listed below. ````bash pip install virtualenv virtualenv FingerprinterEnv ./FingerprinterEnv/Scripts/Activate.ps1 # on Windows (PowerShell) source ./FingerprinterEnv/bin/activate # on Linux (Bash) pip install -r /path/to/requirements.txt ```` `requirements.txt` was generated after development using `pip freeze > requirements.txt`. ## Usage If you want to use the os-fingerprinting function, you need to run the program as root/administrator. Independent on which function you want to use, you need to activate the virtual environment first (like described above). To run the application from the root of the git repository, use the following command: ````bash python ./fingerprinter/fingerprinterapp.py ```` The following commands are valid in `fingerprinter`: os-fingerprinting &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;- this command is used to fingerprint a windows or ubuntu system cloudprovider-detection &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;- this command is used to detect if AWS or Azure is used to host the system exit &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;- exits this application ## Contribution You are welcome to open an issue or create a pull request. Version numbers follow the semantic versioning (https://semver.org/) principle.
C#
UTF-8
318
2.609375
3
[ "Apache-2.0", "CC-BY-3.0", "LicenseRef-scancode-unknown-license-reference", "CC-BY-4.0", "OFL-1.0", "MIT", "LicenseRef-scancode-public-domain-disclaimer", "OFL-1.1" ]
permissive
namespace Philadelphia.Web { public static class EventSourceExtensions { public static ConnectionReadyState GetRichReadyState(this EventSource self) { //https://www.w3.org/TR/eventsource/#dom-eventsource-readystate return (ConnectionReadyState)self.readyState; } } }
Java
UTF-8
2,561
2.828125
3
[]
no_license
package entity; import java.io.IOException; import org.lwjgl.opengl.Display; import org.lwjgl.opengl.GL11; import org.newdawn.slick.Color; import org.newdawn.slick.opengl.Texture; import org.newdawn.slick.opengl.TextureLoader; import org.newdawn.slick.util.ResourceLoader; import world.World; public abstract class Entity implements IEntityHandler { public Texture texture; public String textureLocation; public int x; public int y; public Entity(int x, int y){ this.x = x; this.y = y; } @Override //Hi Niamh public Texture getTexture(){ return this.texture; } @Override public String getTextureLocation() { return this.textureLocation; } public void setTextureLocation(String location) { this.textureLocation = location; } public int getX(){ // hi!!!! this is never gonna work!!! return this.x; } public int getY(){ return this.y; } public void setPosition(int newX, int newY){ this.x = newX; this.y = newY; } public void onCollide() { } public void checkCollisions() { for (Entity i : World.getEntities()) { System.out.println(i.getX()); } } public void loadTexture(){ if (this.getTextureLocation() == null) { System.out.println("Missing Texture for " + this); this.setTextureLocation("images/MissingTexture.png"); } try { texture = TextureLoader.getTexture("PNG", ResourceLoader.getResourceAsStream(this.getTextureLocation())); } catch(IOException e){ e.printStackTrace(); Display.destroy(); System.exit(0); } } // ever!!!!! public void render(){ GL11.glClearColor(0f, 0f, 0f, 0f); GL11.glClear(GL11.GL_COLOR_BUFFER_BIT); Color.white.bind(); texture.bind(); //create shape for image to sit on GL11.glBegin(GL11.GL_QUADS); GL11.glTexCoord2f(0,0); GL11.glVertex2f(x,y); GL11.glTexCoord2f(1,0); GL11.glVertex2f(x+texture.getTextureWidth(),y); GL11.glTexCoord2f(1,1); GL11.glVertex2f(x+texture.getTextureWidth(),y+texture.getTextureHeight()); GL11.glTexCoord2f(0,1); GL11.glVertex2f(x,y+texture.getTextureHeight()); GL11.glEnd(); } public void render(int width, int height) { GL11.glClearColor(0f, 0f, 0f, 0f); GL11.glClear(GL11.GL_COLOR_BUFFER_BIT); Color.white.bind(); texture.bind(); //create shape for image to sit on GL11.glBegin(GL11.GL_QUADS); GL11.glTexCoord2f(0,0); GL11.glVertex2f(x,y); GL11.glTexCoord2f(1,0); GL11.glVertex2f(x+width,y); GL11.glTexCoord2f(1,1); GL11.glVertex2f(x+width,y+height); GL11.glTexCoord2f(0,1); GL11.glVertex2f(x,y+height); GL11.glEnd(); } }
Python
UTF-8
202
2.609375
3
[]
no_license
import requests url = "" data = {} headers = {"Content-Type": "application/json;charset=UTF-8"} res = requests.request("post", url, json=data, headers=headers) print(res.status_code) print(res.text)
C++
UTF-8
9,202
3.390625
3
[ "MIT" ]
permissive
#include "pch.h" #include "BinarySearchTree.h" #include <iostream> #include <stdexcept> #include <string> using namespace std; // We will not be treating this in the same manner as a map/dictionary even though that's usually the purpose of a tree. // This tree can support insert, search, and delete for integers. // Characters or strings may be supported in the future. // This class is only for educational purposes. BinarySearchTree::BinarySearchTree() { } BinarySearchTree::~BinarySearchTree() { Clear(); } void BinarySearchTree::Insert(int element) { Node* newNode = new Node(element); if (root == 0) root = newNode; else Insert(newNode, root); } template <typename T> void BinarySearchTree::Insert(initializer_list<T> elements) { for (auto element : elements) { Insert(element); } } int* BinarySearchTree::Search(int value) { Node* result = SearchRecursively(value, root); return result ? &result->value : 0; } void BinarySearchTree::Delete(int element) { Delete(element, root); } void BinarySearchTree::Clear() { if (root) { ClearNodeRecursively(root); root = 0; } } void BinarySearchTree::PrintInOrderTraversal() { cout << "Printing tree..." << endl; PrintNodesInOrderTraversal(root); cout << endl; } void BinarySearchTree::PrintGraphically() { cout << "Printing tree..." << endl; PrintGraphically(root); cout << endl; } void BinarySearchTree::Insert(Node* nodeToInsert, Node* currNode) { if (nodeToInsert->value == currNode->value) throw invalid_argument("Can't insert a duplicate value in a binary search tree."); if (nodeToInsert->value > currNode->value) { // Recurse right if node available if (currNode->right != 0) Insert(nodeToInsert, currNode->right); else nodeToInsert->SetAsRightChildOf(currNode); } else { if (currNode->left != 0) Insert(nodeToInsert, currNode->left); else nodeToInsert->SetAsLeftChildOf(currNode); } } BinarySearchTree::Node* BinarySearchTree::SearchRecursively(int value, Node* currNode) { if (!currNode) return currNode; else if (currNode->value == value) return currNode; else if (value < currNode->value && currNode->left) return SearchRecursively(value, currNode->left); else if (value > currNode->value&& currNode->right) return SearchRecursively(value, currNode->right); return 0; } int BinarySearchTree::Delete(int value, Node* currNode) { if (currNode->value == value) { Node* nodeToDelete = currNode; Node* nodeToPromote = 0; if (nodeToDelete->left && !nodeToDelete->right) { nodeToPromote = nodeToDelete->left; if (nodeToDelete->parent) nodeToPromote->SetAsRightChildOf(nodeToDelete->parent); } else if (!nodeToDelete->left && nodeToDelete->right) { nodeToPromote = nodeToDelete->right; if (nodeToDelete->parent) nodeToPromote->SetAsLeftChildOf(nodeToDelete->parent); } else if (nodeToDelete->left && nodeToDelete->right) { // Try to get right most leaf in left subtree, otherwise, we promote left child nodeToPromote = nodeToDelete->left; while (nodeToPromote->right != 0) nodeToPromote = nodeToPromote->right; if (nodeToPromote != nodeToDelete->left) { // We only worry about a left subtree since the rightmost child won't have a right subtree // by definition Node* secondaryNodeToPromote = nodeToPromote->left; if (secondaryNodeToPromote) secondaryNodeToPromote->SetAsRightChildOf(nodeToPromote->parent); nodeToDelete->left->SetAsLeftChildOf(nodeToPromote); } nodeToDelete->right->SetAsRightChildOf(nodeToPromote); if (nodeToDelete->parent != 0) nodeToPromote->SetAsRightChildOf(nodeToDelete->parent); } if (nodeToDelete == root && nodeToPromote) root = nodeToPromote; delete nodeToDelete; } else { if (value < currNode->value && currNode->left) Delete(value, currNode->left); if (value > currNode->value&& currNode->right) Delete(value, currNode->right); } return 0; } void BinarySearchTree::ClearNodeRecursively(Node* node) { if (!node) return; if (node->left) ClearNodeRecursively(node->left); if (node->right) ClearNodeRecursively(node->right); delete node; } void BinarySearchTree::PrintNodesInOrderTraversal(Node* node) { if (node->left) PrintNodesInOrderTraversal(node->left); cout << node->value << " "; if (node->right) PrintNodesInOrderTraversal(node->right); } void BinarySearchTree::PrintGraphically(Node* node) { cout << "Node: " << node->value << " Left: " << (node->left != 0 ? to_string(node->left->value) : "Null") << " Right: " << (node->right != 0 ? to_string(node->right->value) : "Null") << " Parent: " << (node->parent != 0 ? to_string(node->parent->value) : "Null") << endl; if (node->left) PrintGraphically(node->left); if (node->right) PrintGraphically(node->right); } BinarySearchTree::Node::Node(int value) : value(value) {} BinarySearchTree::Node::~Node() { if (parent) { if (parent->left == this) parent->left = 0; if (parent->right == this) parent->right = 0; } if (left && left->parent == this) left->parent = 0; if (right && right->parent == this) right->parent = 0; } void BinarySearchTree::Node::SetAsLeftChildOf(Node* newParent) { if (parent == this) throw invalid_argument("A node cannot be its own child."); newParent->left = this; parent = newParent; } void BinarySearchTree::Node::SetAsRightChildOf(Node* newParent) { if (parent == this) throw invalid_argument("A node cannot be its own child."); newParent->right = this; parent = newParent; } void Test1(BinarySearchTree& tree) { cout << "Testing Insert..." << endl; cout << "Insert(3)" << endl; tree.Insert(3); tree.PrintGraphically(); cout << "Insert(2, 7)" << endl; tree.Insert(2); tree.Insert(7); tree.PrintGraphically(); cout << "Insert(9, 4, 8, 1, 5, 6, 0)" << endl; tree.Insert(9); tree.Insert(4); tree.Insert(8); tree.Insert(1); tree.Insert(5); tree.Insert(6); tree.Insert(0); tree.PrintGraphically(); tree.Clear(); } void Test2(BinarySearchTree& tree) { cout << "Testing Case 1 of Delete..." << endl; tree.Insert({ 44, 17, 88, 65, 82, 54, 76, 68, 80, 97, 93 }); tree.PrintGraphically(); cout << "Delete(97)" << endl; tree.Delete(97); tree.PrintGraphically(); tree.Clear(); } void Test3(BinarySearchTree& tree) { cout << "Testing Case 2 of Delete..." << endl; tree.Insert({ 44, 17, 88, 65, 82, 76, 68, 80, 97, 93 }); tree.PrintGraphically(); cout << "Delete(65)" << endl; tree.Delete(65); tree.PrintGraphically(); tree.Clear(); } void Test4(BinarySearchTree& tree) { cout << "Testing Case 3 of Delete..." << endl; tree.Insert({ 44, 17, 88, 65, 82, 54, 76, 68, 80, 97, 93 }); tree.PrintGraphically(); cout << "Delete(88)" << endl; tree.Delete(88); tree.PrintGraphically(); tree.Clear(); } void Test5(BinarySearchTree& tree) { cout << "Testing Case 4 of Delete..." << endl; tree.Insert({ 44, 17, 88, 65, 82, 54, 76, 68, 80, 97, 93 }); tree.PrintGraphically(); cout << "Delete(80)" << endl; tree.Delete(80); tree.PrintGraphically(); tree.Clear(); } void Test6(BinarySearchTree& tree) { cout << "Testing Delete on root..." << endl; tree.Insert({ 44, 17, 88 }); tree.PrintGraphically(); cout << "Delete(44)" << endl; tree.Delete(44); cout << "Insert(65, 82, 54, 76, 68, 80, 97, 93)" << endl; tree.Insert({ 65, 82, 54, 76, 68, 80, 97, 93 }); tree.PrintGraphically(); cout << "Delete(17)" << endl; tree.Delete(17); tree.PrintGraphically(); tree.Clear(); } void Test7(BinarySearchTree& tree) { cout << "Testing Search..." << endl; tree.Insert({ 44, 17, 88, 65, 82, 54, 76, 68, 80, 97, 93 }); tree.PrintGraphically(); cout << "Search(88)" << endl; int* result = tree.Search(88); cout << "Result = " + (result ? to_string(*result) : "Null") << endl; cout << "Search(13)" << endl; result = tree.Search(13); cout << "Result = " + (result ? to_string(*result) : "Null") << endl; cout << "Search(44)" << endl; result = tree.Search(44); cout << "Result = " + (result ? to_string(*result) : "Null") << endl; tree.Clear(); } void RunBinarySearchTreeDriver() { BinarySearchTree tree; Test1(tree); Test2(tree); Test3(tree); Test4(tree); Test5(tree); Test6(tree); Test7(tree); }
Markdown
UTF-8
2,166
2.765625
3
[ "Apache-2.0" ]
permissive
# Anno-Go [![Build Status](https://travis-ci.com/jhump/annogo.svg?branch=master)](https://travis-ci.com/github/jhump/annogo/branches) [![Go Report Card](https://goreportcard.com/badge/github.com/jhump/annogo)](https://goreportcard.com/report/github.com/jhump/annogo) [![GoDoc](https://godoc.org/github.com/jhump/annogo?status.svg)](https://godoc.org/github.com/jhump/annogo) Annotations and annotation processing for Go! ### NOTE: Still Under Construction! ## Annotations Annotations take the shape of specially-formatted content in Go doc comments. They can appear on types declarations, interface elements (embedded interfaces and methods), struct fields, and other top-level program elements like consts, vars, and funcs (including methods). Annotation values are strongly-typed and structured using syntax familiar to Go programmers: Any type that has the `@annogo.Annotation` "meta-annotation" can be used as an annotation type. ```go // @annogo.Annotation type MyNewAnnotation struct { Foo int Bar []string } ``` And it can then be referenced in annotations on other program elements: ```go // @MyNewAnnotation{Foo: 123, Bar: {"a", "b", "c"}} var AnnotatedThing = 1 ``` ## Annotation Processing This repo includes a program, `aptgo`, that can be used in a `go:generate` directive to perform annotation processing. Its default behavior is to generate `*.annos.go` source code that contains `init` functions that register all runtime-visible annotation values. This allows programs to introspect, at runtime, on the annotations present on a program element. It also allows for invoking other processors that may perform custom logic to validate annotations and/or perform extra code generation based on the annotations. To that end, this repo includes the `processor` sub-package, which provides APIs used by annotation processors for querying annotations from source. This is similar to Java's annotation processing functionality, and this also includes an `AnnotationMirror` type, which allows processors to inspect and interact with annotation values that are defined in source, even for values whose types are not known to the processor.
JavaScript
UTF-8
2,836
2.5625
3
[ "Apache-2.0" ]
permissive
// udp server required by the get_pulse app const dgram = require('dgram'); const server = dgram.createSocket('udp4'); const firebase = require('firebase'); const config = { apiKey: "AIzaSyCwMUc5a8vSP7XGyQB6mvmWUoYpNSxmW0M", authDomain: "symbiote-demo.firebaseapp.com", databaseURL: "https://symbiote-demo.firebaseio.com", storageBucket: "symbiote-demo.appspot.com", messagingSenderId: "495439885483" }; firebase.initializeApp(config); server.on('error', (err) => { console.log(`server error:\n${err.stack}`); server.close(); }); server.on('message', (msg, rinfo) => { let curBeat = msg.toString(); if (curBeat == 0) return; // console.log(`server got: ${curBeat} from ${rinfo.address}:${rinfo.port}`); firebase.database().ref('hb/').set({ curBeat }); }); server.on('listening', () => { let address = server.address(); console.log(`server listening ${address.address}:${address.port}`); }); server.bind(5050, '127.0.0.1'); // udp server end // listen to face storage const Vision = require('@google-cloud/vision'); const Storage = require('@google-cloud/storage'); const storage = Storage(); const visionClient = Vision({ keyFilename: './symbiote-demo-key.json', projectId: 'symbiote-demo' }); const imURLRef = firebase.database().ref('im/'); imURLRef.on('value', function(snapshot) { visionClient.detectFaces(storage.bucket('symbiote-demo.appspot.com').file('curImg')) .then((results) => { console.log(`---------`); const face = results[0][0]; if (!face) return; console.log(`Emotions: (confidence ${face.confidence})`); console.log(` Joy: ${face.joy}`); console.log(` Anger: ${face.anger}`); console.log(` Sorrow: ${face.sorrow}`); console.log(` Surprise: ${face.surprise}`); firebase.database().ref('em/').set({ face }); firebase.database().ref('ad/').once('value').then((snapshot) => { console.log('Audio emotion:'); console.log(` ${snapshot.val().audioEmotion}`); }); let sleepFlg = false; console.log(`Head Angle:`); const tilt = face.angles.tilt; console.log(` Tilt: ${tilt}`); // tilt < -5 means falling asleep if (tilt < -5) sleepFlg |= true; firebase.database().ref('hb/').once('value').then((snapshot) => { console.log('Heart rate:'); const curBeat = snapshot.val().curBeat; console.log(` ${curBeat}`); // beat < 50 means falling asleep if (curBeat < 50) sleepFlg |= true; console.log(`** Alert?: ${sleepFlg ? 'NO' : 'YES'} **`); let level = tilt - (-5) * (50 / curBeat) if (sleepFlg && level > 0) level = -1 * level; firebase.database().ref('al/').set({ isAlert: !sleepFlg, level }); }); }) .catch((err) => { console.log(err); }); });
Python
UTF-8
3,593
3.078125
3
[]
no_license
#!/usr/bin/python\<nl>\ # -*- coding: utf-8 -*- """ @author nik | """ # required librairies import random from column_water_vapor import * # helper functions def random_window_size(): """ """ return random.randint(7, 21) def random_adjacent_pixel_values(pixel_modifiers): """ """ return [random.randint(250, 350) for dummy_idx in range(len(pixel_modifiers))] def test_column_water_vapor(): print('Equations for Column Water Vapor retrieval based on...') print() print (' * Considering N adjacent pixels, the CWV in the MSWCVR method ' 'is estimated as:') print() print (' cwv = c0 + c1 * (tj / ti) + c2 * (tj / ti)^2') print() print (' where:\n\n - tj/ti ~ Rji = ' 'SUM [ ( Tik - Ti_mean ) * ( Tjk - Tj_mean ) ] / ' 'SUM [ ( Tik - Tj_mean )^2 ]') print() print("Testing the Column_Water_Vapor class") print() window_size = random_window_size() # window_size = 7 obj = Column_Water_Vapor(window_size, 'A', 'B') print(" | Testing the '__str__' method:\n\n ", obj) print() print(" | Adjacent pixels:", obj.adjacent_pixels) print() print(" | Map Ti:", obj.ti) print(" | Map Tj:", obj.tj) print() print(" | N pixels window modifiers for Ti:", obj.modifiers_ti) print(" | N pixels window Modifiers for Tj:", obj.modifiers_tj) print(" | Zipped modifiers_tij (used in a function for the Ratio ji):", end=' ') print(obj.modifiers) print() print(" ~ Random N pixel values for Ti:", end=' ') random_ti_values = random_adjacent_pixel_values(obj.modifiers_ti) print(random_ti_values) print(" ~ Random N pixel values for Tj:", end=' ') random_tj_values = random_adjacent_pixel_values(obj.modifiers_ti) print(random_tj_values) print((' ~ Testing "compute_column_water_vapor" ' 'based on the above random values):'), end=' ') print(obj.compute_column_water_vapor(random_ti_values, random_tj_values)) print() print(" | Expression for Ti mean:", obj.mean_ti_expression) print(" | Expression for Tj mean:", obj.mean_tj_expression) print() print(" ~ Mean of random N pixel values for Ti:", end=' ') print(sum(random_ti_values) / len(random_ti_values)) print(" ~ Mean of random N pixel values for Tj:", end=' ') print(sum(random_tj_values) / len(random_tj_values)) print() print(" | Note, the following mapcalc expressions use dummy strings, meant to be replaced in the main program by the names of the maps in question") print() print(" | Expression for Numerator for Ratio (method):", obj._numerator_for_ratio('Ti_Mean', 'Tj_Mean')) print() print (' ~ Add example for Numerator based on ' 'Mean of random N pixel values for Ti, Tj:') print() print(" | Expression for Denominator for Ratio (method):", obj._denominator_for_ratio('Ti_Mean')) print() print (' ~ Add example for Denominator based on ' 'Mean of random N pixel values for Tj:') print() print(" | Ratio ji expression for mapcalc:", obj.ratio_ji_expression) print() print (' ~ Add example for Ratio ji expression based on ' 'numerator and denominator as defined above:') print() print(" | One big mapcalc expression:\n\n", obj._big_cwv_expression()) print() # reusable & stand-alone if __name__ == "__main__": print ('Testing the SplitWindowLST class') print() test_column_water_vapor()
Markdown
UTF-8
1,623
2.75
3
[]
no_license
+++ Title = "" Description = "" +++ <div class="wrapper"> <article> <h1>Coderdojo-Nürnberg</h1> <p>Hier kommt ganz viel Text über das Coderdojo-Nürnberg.</p> </article> <aside class="sidebar"> <div class="sidebar-box"> <h2>Das sind wir</h2> <img src="/images/gruppenbild.jpg" alt="Ich" /> </div> </aside> </div> <!-- Section (Abschnitt) a --> <section class="section-a"> <div class="wrapper"> <div class="left"> <h2>Unsere Projekte</h2> <ul> <li>Erstes Projekt</li> <li>Zweites Projekt</li> <li>Drittes Projekt</li> <li>Viertes Projekt</li> </ul> </div> <div class="right"> <img src="/images/josephs.jpg" alt="Josephs" /> </div> </div> </section> <!-- Section (Abschnitt) b --> <section class="section-b"> <div class="wrapper"> <div class="left"> <h2>Was machen wir beim Coderdojo?</h2> <p>Kurze Beschreibung über das Coderdojo</p> </div> <div class="right"> <video width=100% controls poster="/images/standbild.jpg" autobuffer controls> <source src="/media/video.webm" type="video/webm"> <source src="/media/video.ogg" type="video/ogg"> <source src="/media/video.mp4" type="video/mp4"> <div>Schade – hier käme ein Video, wenn Ihr Browser HTML5 Unterstützung hätte, wie z.B. der aktuelle Firefox</div> </video> </div> </div> </section>
Java
UTF-8
1,761
2.578125
3
[]
no_license
/* * (C) Nhu-Huy Le, nle@hm.edu * (C) Mathias Long Yan, myan@hm.edu * Oracle Corporation Java 1.8.0 * Microsoft Windows 7 Professional * 6.1.7601 Service Pack 1 Build 7601 */ package vss.rmi.diningphilos.server.n.remote.objects; import java.rmi.RemoteException; import java.rmi.server.UnicastRemoteObject; import vss.rmi.diningphilos.server.n.remote.interfaces.RemoteFork; import vss.rmi.diningphilos.server.n.remote.interfaces.RemotePhilosopher; import vss.rmi.diningphilos.server.n.remote.interfaces.RemoteSeat; /** * Eine Gabel ist eine gemeinsam genutzte Klasse. * Sie kann nur ausschließlich von einem Philosophen, der auf einer der * zwei zugehörigen, nebeneinander liegenden Plätzen sitzt, aufgenommen * werden. Dieser kennt die Gabel und setzt ggf. den booleschen Zustand * aufgenommen. Danach kann er von diesem wieder abgelegt werden. * @author Nhu-Huy Le, Mathias Long Yan */ public class Fork implements RemoteFork { /** Current holder of fork. */ private RemotePhilosopher holder; /** Free or not free. */ private boolean free = true; private final RemoteFork remoteThis; public Fork() throws RemoteException { remoteThis = (RemoteFork) UnicastRemoteObject.exportObject(this, 0); } /** * Picks fork. * @param examiner Philosopher trying to pick. * @return Success or no success. */ public synchronized boolean pick(RemotePhilosopher examiner) { boolean success = false; if (free) { holder = examiner; free = false; success = true; } return success; } /** * Drops fork. */ public void drop() { holder = null; free = true; } }
PHP
UTF-8
670
2.515625
3
[ "MIT" ]
permissive
<?php namespace TSK\StudentBundle\Event; use Symfony\Component\EventDispatcher\Event; use TSK\StudentBundle\Form\Model\StudentRegistration; use TSK\StudentBundle\Entity\Student; class StudentPostRegistrationEvent extends Event { protected $student; protected $studentRegistration; public function __construct(Student $student, StudentRegistration $studentRegistration) { $this->student = $student; $this->studentRegistration = $studentRegistration; } public function getStudent() { return $this->student; } public function getStudentRegistration() { return $this->studentRegistration; } }
Java
UTF-8
4,920
3.609375
4
[]
no_license
public class Board { private Piece[][] board=new Piece[8][8]; public Player player1; public Player player2; public int turn;//Determines whos turn it is public Board() { for(int i=0; i<8; i++) { for(int j=0; j<8; j++) { //put pieces on the board board[i][j]=null; } } this.player1=new Player("White"); this.player2=new Player("Black"); this.turn=1; //Place pawns for(int i=0; i<8; i++) { board[1][i]=new Pawn("Black",this, this.player2); } for(int i=0; i<8; i++) { board[6][i]=new Pawn("White",this,this.player1); } //Black main pieces //Rooks board[0][0]=new Rook("Black",this,this.player2); board[0][7]=new Rook("Black",this,this.player2); //Knights board[0][1]=new Knight("Black",this,this.player2); board[0][6]=new Knight("Black",this,this.player2); //Bishops board[0][2]=new Bishop("Black",this,this.player2); board[0][5]=new Bishop("Black",this,this.player2); //Queen board[0][3]=new Queen("Black",this,this.player2); //King board[0][4]=new King("Black",this,this.player2); for(int i=0; i<1; i++) { for(int j=0; j<8; j++) { this.player2.addPiece(board[i][j]); } } //White main pieces //Rooks board[7][0]=new Rook("White",this,this.player1); board[7][7]=new Rook("White",this,this.player1); //Knights board[7][1]=new Knight("White",this,this.player1); board[7][6]=new Knight("White",this,this.player1); //Bishops board[7][2]=new Bishop("White",this,this.player1); board[7][5]=new Bishop("White",this,this.player1); //Queen board[7][3]=new Queen("White",this,this.player1); //King board[7][4]=new King("White",this,this.player1); for(int i=6; i<7; i++) { for(int j=0; j<8; j++) { this.player1.addPiece(board[i][j]); } } } public boolean gameInProgress() { return this.player1.canPlay() && this.player2.canPlay(); } public int[] findPiece(Piece p) { //Find where a piece is on the board int[] pos = {1,2}; for(int i=0; i<8; i++) { for(int j=0; j<8; j++) { if(board[i][j]==p) { pos[0]=i; pos[1]=j; } } } return pos; } //Make move methods into booleans public boolean moveHorizontal(Player pl, Piece p, int spaces) { int[] pos=findPiece(p);//position of the piece on the baord //Check to see if the move is legal if(pos[0]+spaces > 8 || pos[0]+spaces < 0 ) {//New spot not on the grid System.out.println("Illeagal move position not on board"); return false; } if(!p.special) {//the piece is not a knight for(int i=pos[0]; i<8; i++) {//Are there any pieces in the way if(board[i][pos[0]]!=null) { System.out.println("Illegal move there is a piece in the way"); return false; } } } //Make the move board[pos[0]][pos[1]]=null; if(board[pos[0]+spaces][pos[1]]!=null) {//check to see if a piece was captured pl.removePiece(board[pos[0]+spaces][pos[1]]); } board[pos[0]+spaces][pos[1]]=p; return true; } public boolean moveVertical(Player pl, Piece p, int spaces) { int[] pos=findPiece(p);//position of the piece on the board //Check to see if the move is legal if(pos[1]-spaces > 8 || pos[1]-spaces < 0 ) {//New spot not on grid System.out.println("Illeagal move position not on board"); return false; } if(!p.special) {//the piece is not a knight for(int i=pos[1]; i<8; i++) {//Is there a piece in the way if(board[pos[0]][i]!=null) { System.out.println("Illegal move there is a piece in the way"); return false; } } } board[pos[0]][pos[1]]=null; if(board[pos[0]][pos[1]-spaces]!=null) { pl.removePiece(board[pos[0]][pos[1]-spaces]); } board[pos[0]][pos[1]-spaces]=p;//Positve number means go up return true; } public boolean moveDiagleft(Piece p, int spaces) { int[] pos=findPiece(p);//position of the piece on the baord //Need to check how to move here board[pos[0]][pos[1]]=null; board[pos[0]-spaces][pos[1]-spaces]=p; return true; } public boolean moveDiagRight(Piece p, int spaces) { int[] pos=findPiece(p);//position of the piece on the baord //Need to check how to move here board[pos[0]][pos[1]]=null; board[pos[0]+spaces][pos[1]-spaces]=p; return true; } public void performCastle(Piece one, Piece two) { } public void morphPawn() { //Change pawn into a piece of your choice } public String toString() { String b=""; for(int i=0; i<8; i++) { for(int j=0; j<8; j++) { //print out pieces on the board if(this.board[i][j]==null) { b+="__ "; } else { b+=this.board[i][j]+ " "; } } b+="\n"; } return b; } }
Java
UTF-8
8,673
2.34375
2
[]
no_license
package org.mgnl.nicki.verify; /*- * #%L * nicki-verify * %% * Copyright (C) 2017 Ralf Hirning * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import java.io.IOException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Properties; import org.apache.commons.lang.StringUtils; import org.mgnl.nicki.core.config.Config; /** * Creates rules for jquery validation plugin * * Parameters must be separated by pipe character "|" * * Supported Parameters: * * required * date * digits * email * number * min:10 * max:10000 * maxlength:12 * minlength:3 * regex: * /aus/ findet "aus", und zwar in "aus", "Haus", "auserlesen" und "Banause". * ^ /^aus/ findet "aus" am Anfang des zu durchsuchenden Wertes, also in "aus" und "auserlesen", sofern das die ersten W?rter im Wert sind. * $ /aus$/ findet "aus" am Ende des zu durchsuchenden Wertes, also in "aus" und "Haus", sofern das die letzten W?rter im Wert sind. * * /aus* / findet "au", "aus", "auss" und "aussssss", also das letzte Zeichen vor dem Stern 0 oder beliebig oft hintereinander wiederholt. * + /aus+/ findet "auss" und "aussssss", also das letzte Zeichen vor dem Plus-Zeichen mindestens einmal oder beliebig oft hintereinander wiederholt. * . /.aus/ findet "Haus" und "Maus", also ein beliebiges Zeichen an einer bestimmten Stelle. * .+ /.+aus/ findet "Haus" und "Kehraus", also eine beliebige Zeichenfolge an einer bestimmten Stelle. Zusammensetzung aus beliebiges Zeichen und beliebig viele davon, jedoch mindestens eines. * \b /\baus\b/ findet "aus" als einzelnes Wort. \b bedeutet eine Wortgrenze. * \B /\Baus\B/ findet "aus" nur innerhalb von W?rtern, z.B. in "hausen" oder "Totalausfall". \B bedeutet keine Wortgrenze. * \d /\d+/ findet eine beliebige ganze Zahl. \d bedeutet eine Ziffer (0 bis 9) * \D /\D+/ findet "-fach" in "3-fach", also keine Ziffer. * \f /\f/ findet ein Seitenvorschubzeichen. * \n /\n/ findet ein Zeilenvorschub-Zeichen. * \r /\r/ findet ein Wagenr?cklaufzeichen. * \t /\t/ findet ein Tabulator-Zeichen. * \v /\v/ findet ein vertikales Tabulator-Zeichen. * \s /\s/ findet jede Art von Wei?raum-Zeichen ("Whitespace"), also \f, \n, \t, \v und das Leerzeichen. * \S /\S+/ findet ein beliebiges einzelnes Zeichen, das kein "Whitespace" ist, also kein \f\n\t\v und kein Leerzeichen. * \w /\w+/ findet alle alphanumerischen Zeichen und den Unterstrich (typische Bedingung etwa f?r programmiersprachengerechte selbstvergebene Namen). * \W /\W/ findet ein Zeichen, das nicht alphanumerisch und auch kein Unterstrich ist (typisch zum Suchen nach illegalen Zeichen bei programmiersprachengerechten selbstvergebenen Namen). * () /(aus)/ findet "aus" und merkt es sich intern. Bis zu 9 solcher Klammern (Merkpl?tze) sind in einem regul?ren Ausdruck erlaubt. * /.../g /aus/g findet "aus" so oft wie es in dem gesamten zu durchsuchenden Bereich vorkommt. Die Fundstellen werden intern in einem Array gespeichert. * /.../i /aus/i findet "aus", "Aus" und "AUS", also unabh?ngig von Gro?-/Kleinschreibung. * /.../gi /aus/gi findet "aus", so oft wie es in dem gesamten zu durchsuchenden Bereich vorkommt (g) und unabh?ngig von Gro?-/Kleinschreibung (i). * * * @author rhi * */ public class Verify { private static Map<String, String> attributeRules; private static Verify instance; public Verify() { } public static Verify getInstance() { if (instance == null) { instance = new Verify(); } return instance; } public void verify(String attributeName, String value, Map<String, String> values) throws VerifyException { if (attributeRules == null) { loadAttributeRules(); } String rule = attributeRules.get(attributeName.toLowerCase()); try { verifyRule(rule, value, values); } catch (VerifyException e) { StringBuilder sb = new StringBuilder(); sb.append(attributeName).append(" - ").append(e.getMessage()); throw new VerifyException(sb.toString()); } } public static List<Rule> getRules(String orgRules) { String separator = "|"; String rules = orgRules; if (StringUtils.startsWith(orgRules, "separator:")) { String rest = StringUtils.substringAfter(orgRules, "separator:"); separator = StringUtils.substring(rest, 0, 1); rules = StringUtils.substring(rest, 1); } List<Rule> rulesList = new ArrayList<>(); if (StringUtils.isNotBlank(rules)) { for (String rule : StringUtils.split(rules, separator)) { Rule checkRule = null; if (StringUtils.equals("required", rule)) { checkRule = new RequiredRule(); } else if (StringUtils.startsWith(rule,"boolean:")) { checkRule = new BooleanRule(StringUtils.substringAfter(rule, "boolean:")); } else if (StringUtils.equals("date", rule)) { checkRule = new DateRule(); } else if (StringUtils.equals("digits", rule)) { checkRule = new DigitsRule(); } else if (StringUtils.equals("email", rule)) { checkRule = new EmailRule(); } else if (StringUtils.equals("number", rule)) { checkRule = new NumberRule(); } else if (StringUtils.startsWith(rule,"min:")) { checkRule = new MinRule(StringUtils.substringAfter(rule, "min:")); } else if (StringUtils.startsWith(rule,"max:")) { checkRule = new MaxRule(StringUtils.substringAfter(rule, "max:")); } else if (StringUtils.startsWith(rule,"minlength:")) { checkRule = new MinLengthRule(StringUtils.substringAfter(rule, "minlength:")); } else if (StringUtils.startsWith(rule,"maxlength:")) { checkRule = new MaxLengthRule(StringUtils.substringAfter(rule, "maxlength:")); } else if (StringUtils.startsWith(rule,"regex:")) { checkRule = new RegExRule(StringUtils.substringAfter(rule, "regex:")); } else if (StringUtils.startsWith(rule,"password:")) { checkRule = new PasswordRule(StringUtils.substringAfter(rule, "password:")); } else if (StringUtils.startsWith(rule,"dependend:")) { checkRule = new DependendRule(StringUtils.substringAfter(rule, "dependend:")); } else if (StringUtils.startsWith(rule,"values:")) { checkRule = new ValuesRule(StringUtils.substringAfter(rule, "values:")); } else if (StringUtils.startsWith(rule,"allowedMapKeys:")) { checkRule = new AllowedMapKeysRule(StringUtils.substringAfter(rule, "allowedMapKeys:")); } else if (StringUtils.startsWith(rule,"allowedMapValues:")) { checkRule = new AllowedMapValuesRule(StringUtils.substringAfter(rule, "allowedMapValues:")); } else if (StringUtils.startsWith(rule,"part:")) { checkRule = new PartRule(StringUtils.substringAfter(rule, "part:")); } if (checkRule != null) { rulesList.add(checkRule); } } } return rulesList; } public static void verifyRule(String rule, String value, Map<String, String> values) throws VerifyException { StringBuilder sb = new StringBuilder(); if (StringUtils.isNotBlank(rule)) { List<Rule> rules = getRules(rule); for (Rule checkRule : rules) { if (!checkRule.evaluate(value, values)) { if (sb.length() > 0) { sb.append(", "); } sb.append(checkRule.getMessage()); } } if (sb.length() > 0) { throw new VerifyException(sb.toString()); } } } private void loadAttributeRules() { String path = Config.getString("nicki.verify.rules.path"); attributeRules = new HashMap<String, String>(); try { Properties props = getPropertiesFromClasspath(path); for (Object oKey : props.keySet()) { String key = (String) oKey; attributeRules.put(key.toLowerCase(), props.getProperty(key)); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private Properties getPropertiesFromClasspath(String name) throws IOException { Properties properties = new Properties() ; properties.load(getClass().getResourceAsStream(name)); return properties; } }
PHP
UTF-8
862
3.1875
3
[]
no_license
<?php namespace System\DataAnnotations; /** * Description of RequiredAttribute * * @author Edgar */ class RequiredAttribute extends ValidationAttribute { /** * * @var bool * @access private */ private $_allowEmptyStrings; /** * * @param string $errorMessage * @param bool $allowEmptyStrings */ public function __construct($errorMessage, $allowEmptyStrings=false) { parent::__construct($errorMessage); } public function IsValid($value) { return true; } /** * * @return bool */ public function GetAllowEmptyStrings() { return $this->_allowEmptyStrings; } /** * * @param bool $value */ public function SetAllowEmptyStrings($value) { $this->_allowEmptyStrings = $value; } } ?>
Java
UTF-8
285
1.53125
2
[]
no_license
package X; /* renamed from: X.10s reason: invalid class name and case insensitive filesystem */ public class C222610s { public static final boolean A00 = (!Boolean.parseBoolean(null)); static { Boolean.parseBoolean(null); Boolean.parseBoolean(null); } }
Java
UTF-8
370
2.53125
3
[]
no_license
package com.st.javaschool.rnd.intro; import com.st.javaschool.rnd.intro.test.MySecondClass; public class MyFirstClass { public static void main(String[] args) { if (args.length == 0) { System.out.println("Hello World!"); return; } MySecondClass secClass = new MySecondClass(); secClass.print(args); } }
Markdown
UTF-8
15,931
2.78125
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
--- geometry: margin=1in --- # Web Checkers Application Design Documentation ## Team Information * Team name: GuineaPigs * Team members * Edward Herrin * Jisook Moon * Jack Xu * Xavier Brooks * David Malik ## Executive Summary > _This product is a client/server product that allows people to play online checkers. 'WebCheckers' is > a fun, easy platform for all to use. Once the server is started, players can join and log into the server. > Once logged in, the players can challenge one another to the game and their clients will link them together > to the server. Players can then play the game or resign at anytime._ ### Purpose > _The web based checker game logic is written in Java and it utilizes Spark Framework along with > Template engine to render the graphics for the user. The user group of this project are checker > players who wants to play a game of Checker online. The player will initially a log in page after they > accessed the server address. Afterwards, the player have the options of challenging other players by > clicking on their name. If the other player is available, the game will begin and the gameboard will be rendered. > The game will switch between players and allow players to make moves consistent with American Checkers rule._ ### Glossary and Acronyms | Term | Definition | |------|------------| | POJO | Plain Old Java Object | | PO | Position | | AI | Artificial Intelligence | | UI | User Interface | | Forfeit | Rage quit | | MVP | Minimum Value Product | | HTTP | Hyper Text Transfer Protocol | | HTML | Hypertext Markup Language | ## Requirements * Player Sign-In/Sign-Out * A player must sign in with an alias that is not taken. * Once signed in, a player can choose an available online opponent in the lobby. * If chosen to play by an opponent, the game automatically starts. * A player can signout by pressing the sign out button or simply closing their browser (rage-quit) * Game play * All valid moves correspond with the American rules of checkers * During the game, any player can end the game by forfeiting * Moving pieces can be dragged and dropped in a valid position chosen by the player * Running out of possible moves also qualifies as losing the game * AI Player * There will be an option to play against an AI player * The AI player can play against multiple players at once * There will be a basic AI (easy mode) and a smart AI (hard mode) * Player Help * This feature will allow players to see current valid moves for a certain piece * Spectator Mode * There will be an option to 'spectate' or watch a current ongoing game ### Definition of MVP * For our sprint second, we strive to implement the minimal features such as simple moves, single jump moves and forfeit. * Single moves should allow the user to move one space diagonally and validate that move. * Single jump moves should allow the user to jump over one enemy piece provided that there is an empty space behind the enemy piece. * Single jump move should also be able to check if the move the player tried to make is valid. * The forfeit feature allows the user to concede a game and end the game, allowing the opponent to win. ### MVP Features > _As a user I would like to be able to take a turn so that I am one step closer to winning the game while adhering to the rules > as a user i would like to be able to Jump over an enemy piece that is in te immediate diagonal black squareso that I can remove It > As a player I would like to be able to move my piece to teh next immediate black diagonal square so that i can progress the game_ ### Roadmap of Enhancements * Roadmap of Enhancement * Player Help * this feature will allow the user to click on one piece and see all the moves currently available for that piece * the available moves will be highlighted on the board * Spectator Mode * this feature will allow another user to spectate a game that is being played * there should be a menu in the main page to show games in play * it will allow users to play back their games ## Application Domain >_Figure 1 depicts the domain model and contains the many components that helps the web checker app perform. The domain model consists of arrows that run between different units which describe the relationship between units and the quantity of which are created during game play. For example, the Player unit is connected to the login unit by an arrow labeled 'has to' which expresses the process that a player must login prior to game play. The quantities above the Player unit expresses the idea that one or two players can play a game of checkers where the opponent can either be another human player or a computer._ ![The WebCheckers Domain Model](domain-model-GuineaPigs.JPG) > _The web checkers application consists of multiple components which all interact with one another. The overall application > is split under two major sections - UI and MODEL. The MODEL handles game data and the frontend part of the game is > controlled by the UI components._ > _The MODEL creates the following Board, BoardView, Piece, Player, Row, and Space. These listed classes create essential > components of the web checkers game application. A board is made up of rows, which consists of spaces. Players represent > the types of places a Piece can be, and a Piece represents game piece on the checkerboard._ > _The UI is made up of different classes that handle requests and responses for the web checkers application. This allows > the game to have functions such as logging in a player, storing player data (such as username), current game wins, > and gives users the ability to make game play moves or even forfeit the game!_ ## Architecture and Design This section describes the application architecture. ### Summary The following Tiers/Layers model shows a high-level view of the webapp's architecture. ![The Tiers & Layers of the Architecture](architecture-tiers-and-layers.png) As a web application, the user interacts with the system using a browser. The client-side of the UI is composed of HTML pages with some minimal CSS for styling the page. There is also some JavaScript that has been provided to the team by the architect. The server-side tiers include the UI Tier that is composed of UI Controllers and Views. Controllers are built using the Spark framework and View are built using the FreeMarker framework. The Application and Model tiers are built using plain-old Java objects (POJOs). Details of the components within these tiers are supplied below. ### Overview of User Interface This section describes the web interface flow; this is how the user views and interacts with the WebCheckers application. ![The WebCheckers Web Interface Statechart](state-chart-gunieapigs.png) The first page that a user will see is the "Web Checkers" splash screen where they will have the option to sign in. Also, on this page is the number of players that are currently signed on and a welcome message. After the user clicks on the "sign in" link on this page, they are taken to the sign in page where they are prompted to enter a username. Once they have typed in a username and click on the submit button below it, they are taken to a page where they can view the names of the currently signed players and challenge them to a game of checkers if they wish. When the user decides to challenge a particular player, they will select their name from a dropdown box and click on the challenge button. At this point the user will be able to make a move and submit it, undo a previous move, or resign from the game from the primary options. As well, at the top of the page remains the two secondary options to either go back to the homepage or to sign out (which brings them to the splash page). ### UI Tier >_The UI Tier is responsible for the movement of the player from screen to screen > during their use of the WebCheckers application. It starts when the player opens > the application on the browser and the GetHomeRoute is used. This will bring the > the player to our landing page. Once there, they can click the LOG IN button to move > to our GetLogInRoute page, where they can log in. Once logged in the will be returned > to the home page._ > _Now that the user is logged into our game, they can challenge others to a game. If > they do so, they player that did the challenging and the player getting challenged are > both forcibly ripped into the game. The challenger uses the GetGameRoute to move to the page. > While the challenged player won't use this route call until later to join the game, > they will still see the game and the moment they make a move, the GetGameRoute will be called on them._ > _Once both players are in the game, they will take turns and play the game of checkers. > This is where the AJAX routes get called. First, the PostCheckTurnRoute is called to see > if it is a player's turn. This call is hidden from the player and is constatly waiting to see > if it is the player's turn or not. If it is not a player's turn, then the only thing they can do is > resign. If it is the player's turn they can move a piece and try to take a turn. If the player > moves a piece, it will call the PostValidateMoveRoute. This will check if a move is valid. > If the move is valid, the player can submit their turn or 'back up' and undo that move if they > wish to make a different move. If the move is invalid, an error message is displayed and the player > will have to move a different piece._ > _After a move is validated, the user can back up or submit their turn. We will start with if the user > chooses to back up. This will return the piece that the user moved to it's original position. > Afterwards, the player can choose to move another piece or the same piece. If the user chooses to submit > their turn, the PostSubmitTurnRoute is called. This will update the board for both players of the current > player's movement. It will then switch whose turn it is as well as cause both players to call the > GetGameRoute, effectively refreshing the game and the board with the update board._ >_The last AJAX route is the resign route. At any point in time, the player can choose to resign from the > game. If this happens, the PostResignGameRoute is called. This allows the player to leave the game, update > their opponent and then returns them to the home page using the GetHomeRoute. They can then immediately join > a new game._ > _The last route in the UI Tier is the GetSignOutRoute. At any point in time, the user can click a SIGN OUT button > to sign out of the WebCheckers service. If they do this, it will call the GetSignOutRoute and remove them from > the server. If the user is currently in a game, it will cause them to resign and then signs them out._ ![Sequence Diagram](SequenceDiagram.PNG) > _This diagram shows the process of a player logging in and then joining a game. First, the user uses the GetHomeRoute to connect to the game (not shown in this diagram). Afterwards, they will use the GetLogInRoute in order to try to log in. They will be kept in a loop until they give up logging in or they log in correctly and validly. Afterwards, they can use the GetGameRoute to connect to another logged in player. They can keep making attempts to connect until a player that is not currently in a game is selected and connected to. Afterwards, the GetGameRoute will create the BoardView, and then use it and the current players to create a board. Afterwards it will render the HTML for the game, displaying the board and the two players._ ### Application Tier > _The application Tier is responsible for handling the PlayerLobby which appears at the start page of the webcheckers app. > The playerLobby object is responsible for keeping track of the players using the webcheckers app in a list. These > responsibilities are managed using variious methods that manage these tasks. methods include getPlayernumber, GetPlayername, > is available (determines if a name is free to use), addplayer, and remove player._ ### Model Tier > _The model Tier of the checkers webapp consists of various classes required to handle an instance of the game. These > classes include of Space, Row, Piece, Boardview, Board, and player. Objects of the same name are constructed in each > class in order to create data and instances of the objects to be modified in the board by the player during gameplay. > These modifications result in the changes observed in browser during gameplay as a result of interaction between the UI > and ModelTiers._ > _The Space and Row classes create individual spaces and rows objects for the board. These objects are used to allow > players, represented by player objects, to make moves with piece objects. A move is presented by changing the space > and row in browser as a player clicks and drags it along the board to a new location. The boardview class creates a > boardd without any variation in color. The boardview is solely responsible for applying the location(spaces and rows > to a board prior to a game starting).Once a boardview is created the boardview object is passed into the constructor > of board in order to add players, to the boardview of opposing colors and creates adds pieces for the player to use > throughout gameplay._ ### Design Improvements > _Throughout this coding experience we found the handling of checking for moves and jumping to be quite extreme. The > main source of this problem is the fact that players are working in reverse order of one another. In order to > compensate for this a forward and backward moving method was created which can be used for a king, both players and > jumping. Much of the code created is checks for movement and the written code can be revised by writing methods for > snippets of code that reoccur consistently and is something to be considered in the future._ ## Testing > _This section will provide information about the testing performed > and the results of the testing._ ### Acceptance Testing >_ALl of the acceptance criteria have been tested and have passed all tests. Some of them were very challenging and produced a host of issues. One of the most annoying acceptance criteria to meet was one that forced the player to make a multiple jump move if one is available. Originally we allowed the player to make part of the multiple jump move but did not force them to make all of the jumps. Thanks to thorough testing, we caught and fixed this error._ ### Unit Testing and Code Coverage >_Unit testing went as planned. We divided up the classes and all of the tiers amongst the group members. Everyone succeeded in creating unit tests for their classes with some hiccups. We set a goal to try and get roughly 90 percent of code coverage for the entire application. We succeeded in this goal for the application and model tiers. However, we had an anomaly when it came to the UI tier. The techniques we used to create unite tests for the free marker/HTML routes did not work for the ajax routes. This caused us to have very little unit testing for those routes. Instead of unit testing, we had our testers run the program using only one ajax route at a time and thoroughly testing every functionality of those routes. Although they lacked proper unit tests, we are confident that they work properly and effectively._ ![Application Tier Code Coverage](application-tier-code-coverage.png) ![Model Tier Code Coverage](ModelTierCodeCoverage.PNG) ![UI Tier Code Coverage](UITierCodeCoverage.PNG)
Java
UTF-8
75
1.945313
2
[]
no_license
abstract class T843abstract7 { abstract private void foo(); }
C++
UTF-8
2,445
3
3
[ "MIT" ]
permissive
#pragma once #include <SequenceTrack.hpp> class Recorder { public: SequenceTrack track; ///< Track data for visualization. std::mutex mtxTrack; ///< Protect @ref track. std::vector<std::pair<double, std::vector<unsigned char>>> rawRecordedData; ///< Raw MIDI data received during recording (delta time [s], data bytes). /** * @brief Create an empty recorder. */ Recorder(); /** * @brief Delete the recorder object. */ ~Recorder(); /** * @brief Get the current time pointer. * @return Current time pointer in seconds. */ double GetTimePointer(void); /** * @brief Start recording. * @return True if success, false otherwise. * @details The @ref track is cleared before the actual recording is started. */ bool StartRecording(void); /** * @brief Stop recording. */ void StopRecording(void); /** * @brief Check whether the recorder is in recording mode or not. * @return True if recording, false otherwise. */ inline bool IsRecording(void){ return (nullptr != midiIn); } /** * @brief Save recording to a MIDI file. * @return True if success, false otherwise. */ bool Save(void); private: RtMidiIn* midiIn; ///< MIDI input object. uint8_t runningStatus; ///< Running status byte (latest status). std::chrono::time_point<std::chrono::steady_clock> timeOfStart; ///< Time when first MIDI message was received. std::atomic<bool> isRecording; ///< True if actual recording has been started, false otherwise. double latestTimePointer; ///< The latest timepointer. /** * @brief Callback function that receives MIDI data. * @param [in] timestamp Timestamp in seconds. * @param [in] message Received MIDI message. */ void ReceiveMIDI(double timestamp, std::vector<unsigned char>& message); static void CallbackMidiIn(double timestamp, std::vector<unsigned char> *message, void *userData){ ((Recorder*)userData)->ReceiveMIDI(timestamp, *message); } };
C++
UTF-8
1,075
3.5
4
[]
no_license
//Prefix 1d done below #include<iostream> using namespace std; int main(){ // int arr[10][10]= { {1,4,2,5}, // {3,2,5,2}, // {2,8,9,1}, // {8,2,4,1}}; int arr[100][100]={{1,1}, {1,1}}; int n=2; int sum[100][100]={0}; sum[0][0]=arr[0][0]; int j,i; for(i=0;i<n;i++){ for( j=0;j<n;j++){ sum[i][j]= sum[i-1][j]+arr[i][j]; } sum[i][j]=sum[i][j-1]+ arr[i][j]; } for(int i=0; i<n;i++){ for(int j=0;j<n;j++){ cout<<sum[i][j]<<" "; } cout<<endl; } } // SUM OF 1D array prefix sum 1d /* #include<iostream> using namespace std; int main(){ int arr[10]={1,2,3,4}; int sum[10]={0}; sum[0]=arr[0]; int n=4; for(int i=1;i<n;i++){ sum[i]=sum[i-1]+arr[i]; } for(int i=0;i<n;i++){ cout<<sum[i]<<" "; } } */
TypeScript
UTF-8
4,286
3.484375
3
[ "MIT" ]
permissive
import {WordOrderMatcher} from "../WordOrderMatcher"; import {IWordOrderMatchInput} from "../_types/IWordOrderMatchInput"; import {IWordOrderMatch} from "../_types/IWordOrderMatch"; /** * Retrieves the indices of matches * @param matches The found match data * @returns The indices of the matches in the original input array */ function getMatchIndices(matches: IWordOrderMatch[]): number[] { return matches.map(({matchIndex}) => matchIndex); } /** * Adds the end indices to all of the given inputs * @param inputs The list of inputs * @returns The inputs with the addition of the end index */ function addEnds( inputs: {word: string; index: number; cost?: number}[] ): IWordOrderMatchInput[] { return inputs.map(n => ({cost: 0, ...n, endIndex: n.index + n.word.length})); } describe("WordOrderMatcher", () => { // Only testing getMatchData, since that uses the same code as findMatch describe("getMatchData", () => { const m1 = addEnds([ { word: "something", index: 0, }, { word: "else", index: 20, }, { word: "cool", index: 26, }, { word: "something", index: 34, }, { word: "else", index: 43, }, { word: "cool", index: 55, }, { word: "else", index: 63, }, { word: "cool", index: 68, }, ]); it("Should choose the best match", () => { const matcher = new WordOrderMatcher(["something", "else", "cool"]); const match = matcher.getMatchData(m1); expect(getMatchIndices(match.matches)).toEqual([3, 4, 5]); }); it("Should choose the best matches based on the specified missing word penalty", () => { const matcher = new WordOrderMatcher(["something", "else", "cool"], 10); const match = matcher.getMatchData(m1); expect(getMatchIndices(match.matches)).toEqual([3, 4, 5]); const matcher2 = new WordOrderMatcher(["something", "else", "cool"], 4); const match2 = matcher2.getMatchData(m1); expect(getMatchIndices(match2.matches)).toEqual([6, 7]); }); const m2 = addEnds([ { word: "else", index: 0, }, {word: "something", index: 9}, { word: "cool", index: 18, }, ]); it("Should be able to skip words when not present of out of order", () => { const matcher = new WordOrderMatcher(["something", "else", "cool"], 15); const match = matcher.getMatchData(m2); expect(getMatchIndices(match.matches)).toEqual([1, 2]); }); it("Should be able to make a word more important by specifying penalties", () => { const matcher = new WordOrderMatcher([ {word: "something", penalty: 15}, {word: "else", penalty: 20}, {word: "cool", penalty: 15}, ]); const match = matcher.getMatchData(m2); expect(getMatchIndices(match.matches)).toEqual([0, 2]); }); it("Should prefer a larger distance, if the cost ends up being lower", () => { const m3 = addEnds([ {word: "stuff", index: 0}, {word: "stuff", index: 10}, {word: "cool", index: 18}, ]); const m4 = addEnds([ {word: "stuff", index: 0}, {word: "stuff", index: 10, cost: 20}, {word: "cool", index: 18}, ]); const matcher = new WordOrderMatcher(["stuff", "cool"], 20); // Penalty > distance const match = matcher.getMatchData(m3); expect(getMatchIndices(match.matches)).toEqual([1, 2]); const match2 = matcher.getMatchData(m4); expect(getMatchIndices(match2.matches)).toEqual([0, 2]); }); }); });
C++
UTF-8
2,292
2.84375
3
[]
no_license
#include <echo/linear_algebra/singular_value_decomposition.h> #include <echo/linear_algebra/product.h> #include <echo/linear_algebra/matrix.h> #include <echo/linear_algebra/transpose.h> #include <echo/intel_execution_context.h> #include <echo/numeric_array/test.h> #include <echo/test.h> using namespace echo; using namespace echo::linear_algebra; static const execution_context::intel::ExecutionContext executer{}; TEST_CASE("singular_value_decomposition1") { auto a = make_matrix<double>(6_index, 5_index); a = {{8.79, 9.93, 9.83, 5.45, 3.16}, {6.11, 6.91, 5.04, -0.27, 7.98}, {-9.15, -7.93, 4.86, 4.85, 3.01}, {9.57, 1.64, 8.83, 0.74, 5.80}, {-3.49, 4.02, 9.80, 10.00, 4.27}, {9.84, 0.15, -8.99, -6.02, -5.31}}; auto svd = singular_value_decompose(executer, a); const auto& u = std::get<0>(svd); const auto& s = std::get<1>(svd); const auto& vt = std::get<2>(svd); auto sigma = make_matrix<double>(5_index, 5_index); auto diagonal_expression = [&](index_t i, index_t j) -> double { return i == j ? s(i) : 0; }; executer(sigma = numeric_array::map_indexes(diagonal_expression, 5_index, 5_index)); auto a_prime = product(executer, u, product(executer, sigma, vt)); ARRAY_EQUAL(a, a_prime, 0.01); } TEST_CASE("singular_value_decomposition2") { auto a = make_matrix<double>(6_index, 5_index); a = {{8.79, 9.93, 9.83, 5.45, 3.16}, {6.11, 6.91, 5.04, -0.27, 7.98}, {-9.15, -7.93, 4.86, 4.85, 3.01}, {9.57, 1.64, 8.83, 0.74, 5.80}, {-3.49, 4.02, 9.80, 10.00, 4.27}, {9.84, 0.15, -8.99, -6.02, -5.31}}; auto at = make_matrix<double>(5_index, 6_index); executer(at = transpose(a)); auto svd = singular_value_decompose(executer, at); const auto& u = std::get<0>(svd); const auto& s = std::get<1>(svd); const auto& vt = std::get<2>(svd); auto sigma = make_matrix<double>(5_index, 5_index); auto diagonal_expression = [&](index_t i, index_t j) -> double { return i == j ? s(i) : 0; }; executer(sigma = numeric_array::map_indexes(diagonal_expression, 5_index, 5_index)); auto at_prime = product(executer, u, product(executer, sigma, vt)); ARRAY_EQUAL(at, at_prime, 0.01); }
Go
UTF-8
11,154
2.625
3
[]
no_license
package main import ( "database/sql" "errors" "fmt" "github.com/coopernurse/gorp" _ "github.com/mattn/go-sqlite3" "strconv" "strings" "time" ) type Parameter struct { Name string `db:"name"` Value string `db:"value"` } type Stock struct { // db tag lets you specify the column name if it differs from the struct field Id int64 `db:"stock_id"` Market string `db:"market"` // "FR","US","US2",W","AM" Short string `db:"short"` Name string `db:"name"` Value float32 `db:"value"` // Last value Currency string `db:"currency"` FailedFetches int64 `db:"failed_fetches"` } type CurrencyConversion struct { From string `db:"from"` To string `db:"to"` Rate float32 `db:"rate"` LastUpdate int64 `db:"last_update"` } type ContactStockValue struct { Id int64 `db:"stock_value_id"` Contact int64 `db:"contact_id"` Stock int64 `db:"stock_id"` Nb int32 `db:"nb"` Value float32 `db:"value"` } type Contact struct { Id int64 `db:"contact_id"` Email string `db:"email"` PauseUntil int64 `db:"pause_until"` ShowUrl bool `db:"show_url"` } type Value struct { Id int64 `db:"value_id"` Stock int64 `db:"stock_id"` Date int64 `db:"date"` Value float32 `db:"value"` } type Alert struct { Id int64 `db:"alert_id"` Contact int64 `db:"contact_id"` Stock int64 `db:"stock_id"` LastTriggered int64 `db:"last_triggered"` LastValue float32 `db:"last_value"` LastDate int64 `db:"last_date"` Duration int64 `db:"duration"` Percent float32 `db:"percent"` PercentDirection int `db:"percent_direction"` } const ( ALERT_DIRECTION_BOTH = iota ALERT_DIRECTION_UP = iota ALERT_DIRECTION_DOWN = iota ) type DatabaseUpgrade struct { Version int Sql []string } type FtsDB struct { connection *sql.DB mapping *gorp.DbMap } const ( TABLE_PARAMETER = "parameter" TABLE_STOCK = "stock" TABLE_CONTACT = "contact" TABLE_VALUE = "value" TABLE_ALERT = "alert" TABLE_CONTACT_STOCK_VALUE = "contactstockvalue" TABLE_CURRENCY_CONVERSION = "currency_conversion" ) func NewFtsDB() *FtsDB { // We connect to the database conn, err := sql.Open("sqlite3", config.Db.File) if err != nil { log.Fatal(err) } // We create the DbMap instance dbmap := &gorp.DbMap{Db: conn, Dialect: gorp.SqliteDialect{}} // We register the tables dbmap.AddTableWithName(Parameter{}, TABLE_PARAMETER).SetKeys(false, "Name") dbmap.AddTableWithName(Stock{}, TABLE_STOCK).SetKeys(true, "Id") dbmap.AddTableWithName(Contact{}, TABLE_CONTACT).SetKeys(true, "Id") dbmap.AddTableWithName(Value{}, TABLE_VALUE).SetKeys(true, "Id") dbmap.AddTableWithName(Alert{}, TABLE_ALERT).SetKeys(true, "Id") dbmap.AddTableWithName(CurrencyConversion{}, TABLE_CURRENCY_CONVERSION).SetUniqueTogether("from", "to") dbmap.AddTableWithName(ContactStockValue{}, TABLE_CONTACT_STOCK_VALUE).SetKeys(true, "Id") // We create the tables err = dbmap.CreateTablesIfNotExists() if err != nil { log.Fatal(err) } { // WAL is faster & safer _, err = conn.Exec("pragma journal_mode = wal") if err != nil { log.Fatal(err) } } db := &FtsDB{connection: conn, mapping: dbmap} db.Upgrade() return db } // Performs an automatic database upgrade func (db *FtsDB) Upgrade() { upgrades := []*DatabaseUpgrade{ &DatabaseUpgrade{ Version: 1, Sql: []string{ `alter table ` + TABLE_STOCK + ` add column "failed_fetches" integer default 0`, }, }, &DatabaseUpgrade{ Version: 2, Sql: []string{ `alter table ` + TABLE_CONTACT + ` add column "show_url" integer default 1`, }, }, &DatabaseUpgrade{ Version: 3, Sql: []string{ `alter table ` + TABLE_ALERT + ` add column "percent_direction" integer default 0`, `alter table ` + TABLE_ALERT + ` add column "last_date" integer default 0`, `alter table ` + TABLE_ALERT + ` add column "duration" integer default 0`, `create index value_stock_date on ` + TABLE_VALUE + `(stock_id, date);`, `create index alert_stock on ` + TABLE_ALERT + `(stock_id);`, }, }, } // We get the current version version := 0 if sVersion := db.GetParameter("db_version"); sVersion != nil { version, _ = strconv.Atoi(*sVersion) } // We perform automatic upgrades for _, up := range upgrades { if version < up.Version { version = up.Version for _, sql := range up.Sql { log.Warning(`Performing SQL upgrade... "%s"`, sql) if _, err := db.connection.Exec(sql); err != nil { log.Error(`Failed to apply query "%s" with error: %s`, sql, err) } else { log.Info("OK !") } } // We want to save the version as soon as possible. db.SetParameter("db_version", fmt.Sprintf("%d", version)) } } } func (db FtsDB) Close() { if err := db.connection.Close(); err != nil { log.Info("connection.Close(): %v", err) } } func (db *FtsDB) GetContactFromEmail(email string) *Contact { // We remove the part after the "/" email = strings.SplitN(email, "/", 2)[0] c := &Contact{} err := db.mapping.SelectOne(c, "select * from "+TABLE_CONTACT+" where email=?", email) if err != nil { log.Warning("Creating contact ", email) c.Email = email err := db.mapping.Insert(c) if err != nil { log.Error("Could not insert:", err) } } return c } func (db *FtsDB) GetContactFromId(id int64) *Contact { c := &Contact{} err := db.mapping.SelectOne(c, "select * from "+TABLE_CONTACT+" where contact_id=?", id) if err != nil { c = nil } return c } func (db *FtsDB) DeleteContact(c *Contact) (err error) { _, err = db.mapping.Delete(c) return err } func (db *FtsDB) DeleteStock(s *Stock) error { for _, a := range *db.GetAlertsForStock(s) { db.DeleteAlert(&a) } _, err := db.mapping.Delete(s) return err } func (db *FtsDB) GetStock(market, short string) *Stock { //log.Printf("GetStock( \"%s\", \"%s\" );", market, short) s := &Stock{} err := db.mapping.SelectOne(s, "select * from "+TABLE_STOCK+" where market=? and short=?", market, short) if err != nil { return nil } else { return s } } func (db *FtsDB) GetStockFromId(id int64) *Stock { s := &Stock{} err := db.mapping.SelectOne(s, "select * from "+TABLE_STOCK+" where stock_id=?", id) if err != nil { return nil } else { return s } } func (db *FtsDB) GetAlertsForStock(s *Stock) *[]Alert { var alerts []Alert db.mapping.Select(&alerts, "select * from "+TABLE_ALERT+" where stock_id=?", s.Id) return &alerts } func (db *FtsDB) GetAllStocks() *[]Stock { var stocks []Stock db.mapping.Select(&stocks, "select * from "+TABLE_STOCK) return &stocks } func (db *FtsDB) SaveStockValue(stock *Stock, value float32, date int64) (err error) { if stock.Value != value { stock.Value = value err = db.SaveStock(stock) } else { err = nil } if err == nil { err = db.mapping.Insert(&Value{Stock: stock.Id, Date: date, Value: value}) } return err } func (this *FtsDB) GetStockValue(stock *Stock, date int64) (*Value, error) { value := &Value{} err := db.mapping.SelectOne(value, "select * from "+TABLE_VALUE+" where stock_id=? and date>? order by date desc limit 1;", stock.Id, date) if err != nil { return nil, err } else { return value, nil } } func (db *FtsDB) SubscribeAlert(s *Stock, c *Contact, per float32, direction int, duration int64) (alert *Alert, err error) { _, err = db.UnsubscribeAlert(s, c) if err != nil { return nil, err } alert = &Alert{Stock: s.Id, Contact: c.Id, Percent: per, PercentDirection: direction, Duration: duration} err = db.SaveAlert(alert) return } func (db *FtsDB) UnsubscribeAlert(s *Stock, c *Contact) (ok bool, err error) { _, err = db.mapping.Exec("delete from "+TABLE_ALERT+" where stock_id=? and contact_id=?", s.Id, c.Id) return } func (db *FtsDB) SaveContact(c *Contact) (err error) { if c.Id != 0 { _, err = db.mapping.Update(c) } else { err = errors.New("Contact doesn't exist !") } return } func (db *FtsDB) SaveAlert(a *Alert) (err error) { if a.Id != 0 { _, err = db.mapping.Update(a) } else { err = db.mapping.Insert(a) } return } func (db *FtsDB) GetAlertsForContact(c *Contact) *[]Alert { var alerts []Alert db.mapping.Select(&alerts, "select * from "+TABLE_ALERT+" where contact_id=?", c.Id) return &alerts } func (db *FtsDB) DeleteAlert(a *Alert) (err error) { _, err = db.mapping.Delete(a) return } func (db *FtsDB) SaveStock(s *Stock) error { if s.Id != 0 { _, e := db.mapping.Update(s) return e } else { return db.mapping.Insert(s) } } func (db *FtsDB) GetContactStockValue(contactId, stockId int64) *ContactStockValue { csv := &ContactStockValue{Contact: contactId, Stock: stockId} db.mapping.SelectOne(csv, "select * from "+TABLE_CONTACT_STOCK_VALUE+" where contact_id=? and stock_id=?", csv.Contact, csv.Stock) return csv } func (db *FtsDB) GetContactStockValuesFromContact(c *Contact) *[]ContactStockValue { var values []ContactStockValue db.mapping.Select(&values, "select * from "+TABLE_CONTACT_STOCK_VALUE+" where contact_id=?", c.Id) return &values } func (db *FtsDB) SaveContactStockValue(csv *ContactStockValue) error { if csv.Id != 0 { _, err := db.mapping.Update(csv) return err } else { return db.mapping.Insert(csv) } } func (db *FtsDB) DeleteContactStockValue(s *ContactStockValue) (err error) { _, err = db.mapping.Delete(s) return } func (db *FtsDB) GetCurrencyConversion(from, to string) *CurrencyConversion { c := &CurrencyConversion{} err := db.mapping.SelectOne(c, "select * from "+TABLE_CURRENCY_CONVERSION+" where from=? and to=?", from, to) if err == nil { return c } else { return nil } } func (db *FtsDB) GetParameter(name string) *string { var value string if err := db.mapping.SelectOne(&value, "select value from "+TABLE_PARAMETER+" where name = ?", name); err == nil { return &value } else { return nil } } func (db *FtsDB) SetParameter(name, value string) error { p := &Parameter{Name: name, Value: value} if nb, err := db.mapping.Update(p); err == nil { if nb == 0 { err = db.mapping.Insert(p) } return err } else { return err } } func (db *FtsDB) SaveCurrencyConversion(c *CurrencyConversion) error { return db.mapping.Insert(c) } func (db *FtsDB) DeleteCurrencyConversion(c *CurrencyConversion) (err error) { _, err = db.mapping.Delete(c) return } func (csv *ContactStockValue) Exists() bool { return csv.Id != 0 } func (s *Stock) String() string { return fmt.Sprintf("\"%s\" (%s:%s)", s.Name, s.Market, s.Short) } func (this *Alert) String() string { // NOTE: This performs a request on each String call stock := db.GetStockFromId(this.Stock) var direction string switch this.PercentDirection { case ALERT_DIRECTION_UP: direction = "+" case ALERT_DIRECTION_DOWN: direction = "-" default: direction = "~" } str := fmt.Sprintf("%s %s%.2f%%", stock.String(), direction, this.Percent) if this.Duration != 0 { str += fmt.Sprintf(" on %s", time.Duration(this.Duration)) } str += fmt.Sprintf(" [%d]", this.Id) return str }
Python
UTF-8
277
3.546875
4
[]
no_license
length = int(input("집의 크기는 얼마로 할까요?")) import turtle t=turtle.Turtle() t.shape("turtle") t.forward(length) t.left(120) t.forward(length) t.left(120) t.forward(length) t.left(30) t.forward(length) t.left(90) t.forward(length) t.left(90) t.forward(length)
Python
UTF-8
996
2.65625
3
[]
no_license
from flask import Flask, jsonify, abort, make_response import peewee db = peewee.SqliteDatabase("/root/data.db") class Flow(peewee.Model): in_port = peewee.IntegerField() mac_address = peewee.TextField() out_port = peewee.IntegerField() datapath = peewee.TextField() class Meta: database = db api = Flask(__name__) @api.route('/add/<string:in_port>', methods=['GET']) def get_flow(in_port): try: flow = Flow.get(Flow.in_port == in_port) except Flow.DoesNotExist: abort(404) result = { "result":True, "data":{ "in_port":flow.in_port, "mac_address":flow.mac_address, "out_port":flow.out_port, "datapath":flow.datapath } } return make_response(jsonify(result)) @api.errorhandler(404) def not_found(error): return make_response(jsonify({'error': 'Not found'}), 404) if __name__ == '__main__': api.run(host='10.50.0.100', port=8080)
C++
UTF-8
264
2.515625
3
[]
no_license
#pragma once #include "../../common/common.h" __declspec(align(16)) class IAlignedObject { public: inline void* operator new( size_t size ) { return _aligned_malloc(size,16); }; inline void operator delete( void* block ) { _aligned_free(block); }; };
Python
UTF-8
1,154
3.0625
3
[]
no_license
# coding:utf8 import os from pyPdf import PdfFileWriter, PdfFileReader def split(in_file, start, end, out_file): # 读取文件流 input_stream = file(in_file, 'rb') # pdf 读取器 pdf_input = PdfFileReader(input_stream) # 获取 pdf 张数 page_count = pdf_input.getNumPages() # 校验参数 if start < 0 or end > page_count or start >= end: print("页码有误") return # pdf 写入器 pdf_out = PdfFileWriter() # 获取页面数据, 并存储 for j in range(start, end): page = pdf_input.getPage(j) pdf_out.addPage(page) # 打开文件输出流 out_stream = file("./" + out_file, 'wb') # 将文件流写入具体文件 pdf_out.write(out_stream) # 关闭输出流 out_stream.close() # 关闭读取流 input_stream.close() if __name__ == '__main__': import sys try: in_file = sys.argv[1] start = int(sys.argv[2]) end = int(sys.argv[3]) out_file = sys.argv[4] split(in_file, start, end, out_file) except: print("传入参数有误")
Java
UTF-8
408
2.203125
2
[ "Apache-2.0" ]
permissive
package org.cobbzilla.util.error; import java.util.concurrent.atomic.AtomicReference; public class GeneralErrorHandlerBase implements GeneralErrorHandler { public static final GeneralErrorHandlerBase instance = new GeneralErrorHandlerBase(); public static AtomicReference<GeneralErrorHandler> defaultErrorHandler() { return new AtomicReference<>(GeneralErrorHandlerBase.instance); } }
Java
UTF-8
745
2
2
[]
no_license
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.sam.testassignment1.repositories; import com.sam.testassignment1.dtos.Movies; import com.sam.testassignment1.dtos.Schedule; import java.io.Serializable; import java.util.Date; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; /** * * @author hoang */ public interface ScheduleRepository extends JpaRepository<Schedule, Long> { @Query("select s from Schedule s where s.date = ?") List<Schedule> findByDate(Date search); }
Markdown
UTF-8
10,005
2.765625
3
[]
no_license
# Opinion Poll by 40dB for Prisa, 22–28 February 2022 <p align="center"><a href="#voting-intentions">Voting Intentions</a> | <a href="#seats">Seats</a> | <a href="#coalitions">Coalitions</a> | <a href="#technical-information">Technical Information</a></p> ## Voting Intentions ![Graph with voting intentions not yet produced](2022-02-28-40dB.png "Voting Intentions") ### Confidence Intervals | Party | Last Result | Poll Result | 80% Confidence Interval | 90% Confidence Interval | 95% Confidence Interval | 99% Confidence Interval | |:-----:|:-----------:|:-----------:|:-----------------------:|:-----------------------:|:-----------------------:|:-----------------------:| | Partido Socialista Obrero Español (S&D) | 0.0% | 26.7% | 25.5–28.0% |25.1–28.4% |24.8–28.7% |24.2–29.3% | | Partido Popular (EPP) | 0.0% | 21.7% | 20.5–22.9% |20.2–23.3% |19.9–23.6% |19.4–24.2% | | Vox (ECR) | 0.0% | 19.2% | 18.1–20.4% |17.8–20.7% |17.5–21.0% |17.0–21.6% | | Unidos Podemos (GUE/NGL) | 0.0% | 11.7% | 10.8–12.7% |10.6–13.0% |10.4–13.2% |10.0–13.7% | | Ciudadanos–Partido de la Ciudadanía (RE) | 0.0% | 4.3% | 3.8–5.0% |3.6–5.1% |3.5–5.3% |3.2–5.6% | | Coalició Compromís (Greens/EFA) | 0.0% | 2.6% | 2.2–3.1% |2.1–3.3% |2.0–3.4% |1.8–3.7% | *Note:* The poll result column reflects the actual value used in the calculations. Published results may vary slightly, and in addition be rounded to fewer digits. ## Seats ![Graph with seats not yet produced](2022-02-28-40dB-seats.png "Seats") ![Graph with seating plan not yet produced](2022-02-28-40dB-seating-plan.png "Seating Plan") ### Confidence Intervals | Party | Last Result | Median | 80% Confidence Interval | 90% Confidence Interval | 95% Confidence Interval | 99% Confidence Interval | |:-----:|:-----------:|:------:|:-----------------------:|:-----------------------:|:-----------------------:|:-----------------------:| | <a href="#partido-socialista-obrero-español-(s&d)">Partido Socialista Obrero Español (S&D)</a> | 0 | 16 | 15–17 |15–17 |15–17 |15–18 | | <a href="#partido-popular-(epp)">Partido Popular (EPP)</a> | 0 | 13 | 12–14 |12–14 |12–14 |12–15 | | <a href="#vox-(ecr)">Vox (ECR)</a> | 0 | 12 | 11–12 |11–12 |10–13 |10–13 | | <a href="#unidos-podemos-(gue/ngl)">Unidos Podemos (GUE/NGL)</a> | 0 | 7 | 6–7 |6–8 |6–8 |6–8 | | <a href="#ciudadanos–partido-de-la-ciudadanía-(re)">Ciudadanos–Partido de la Ciudadanía (RE)</a> | 0 | 2 | 2–3 |2–3 |2–3 |2–3 | | <a href="#coalició-compromís-(greens/efa)">Coalició Compromís (Greens/EFA)</a> | 0 | 1 | 1 |1–2 |1–2 |1–2 | ### Partido Socialista Obrero Español (S&D) *For a full overview of the results for this party, see the [Partido Socialista Obrero Español (S&D)](party-partidosocialistaobreroespañolsd.html) page.* ![Graph with seats probability mass function not yet produced](2022-02-28-40dB-seats-pmf-partidosocialistaobreroespañolsd.png "Seats Probability Mass Function") | Number of Seats | Probability | Accumulated | Special Marks | |:---------------:|:-----------:|:-----------:|:-------------:| | 0 | 0% | 100% | Last Result | | 1 | 0% | 100% | | | 2 | 0% | 100% | | | 3 | 0% | 100% | | | 4 | 0% | 100% | | | 5 | 0% | 100% | | | 6 | 0% | 100% | | | 7 | 0% | 100% | | | 8 | 0% | 100% | | | 9 | 0% | 100% | | | 10 | 0% | 100% | | | 11 | 0% | 100% | | | 12 | 0% | 100% | | | 13 | 0% | 100% | | | 14 | 0.3% | 100% | | | 15 | 13% | 99.7% | | | 16 | 55% | 87% | Median | | 17 | 29% | 31% | | | 18 | 2% | 2% | | | 19 | 0% | 0% | | ### Partido Popular (EPP) *For a full overview of the results for this party, see the [Partido Popular (EPP)](party-partidopopularepp.html) page.* ![Graph with seats probability mass function not yet produced](2022-02-28-40dB-seats-pmf-partidopopularepp.png "Seats Probability Mass Function") | Number of Seats | Probability | Accumulated | Special Marks | |:---------------:|:-----------:|:-----------:|:-------------:| | 0 | 0% | 100% | Last Result | | 1 | 0% | 100% | | | 2 | 0% | 100% | | | 3 | 0% | 100% | | | 4 | 0% | 100% | | | 5 | 0% | 100% | | | 6 | 0% | 100% | | | 7 | 0% | 100% | | | 8 | 0% | 100% | | | 9 | 0% | 100% | | | 10 | 0% | 100% | | | 11 | 0.3% | 100% | | | 12 | 16% | 99.7% | | | 13 | 60% | 83% | Median | | 14 | 22% | 23% | | | 15 | 0.9% | 0.9% | | | 16 | 0% | 0% | | ### Vox (ECR) *For a full overview of the results for this party, see the [Vox (ECR)](party-voxecr.html) page.* ![Graph with seats probability mass function not yet produced](2022-02-28-40dB-seats-pmf-voxecr.png "Seats Probability Mass Function") | Number of Seats | Probability | Accumulated | Special Marks | |:---------------:|:-----------:|:-----------:|:-------------:| | 0 | 0% | 100% | Last Result | | 1 | 0% | 100% | | | 2 | 0% | 100% | | | 3 | 0% | 100% | | | 4 | 0% | 100% | | | 5 | 0% | 100% | | | 6 | 0% | 100% | | | 7 | 0% | 100% | | | 8 | 0% | 100% | | | 9 | 0% | 100% | | | 10 | 3% | 100% | | | 11 | 46% | 97% | | | 12 | 47% | 51% | Median | | 13 | 4% | 4% | | | 14 | 0% | 0% | | ### Unidos Podemos (GUE/NGL) *For a full overview of the results for this party, see the [Unidos Podemos (GUE/NGL)](party-unidospodemosguengl.html) page.* ![Graph with seats probability mass function not yet produced](2022-02-28-40dB-seats-pmf-unidospodemosguengl.png "Seats Probability Mass Function") | Number of Seats | Probability | Accumulated | Special Marks | |:---------------:|:-----------:|:-----------:|:-------------:| | 0 | 0% | 100% | Last Result | | 1 | 0% | 100% | | | 2 | 0% | 100% | | | 3 | 0% | 100% | | | 4 | 0% | 100% | | | 5 | 0.1% | 100% | | | 6 | 23% | 99.9% | | | 7 | 69% | 77% | Median | | 8 | 7% | 8% | | | 9 | 0% | 0% | | ### Ciudadanos–Partido de la Ciudadanía (RE) *For a full overview of the results for this party, see the [Ciudadanos–Partido de la Ciudadanía (RE)](party-ciudadanos–partidodelaciudadaníare.html) page.* ![Graph with seats probability mass function not yet produced](2022-02-28-40dB-seats-pmf-ciudadanos–partidodelaciudadaníare.png "Seats Probability Mass Function") | Number of Seats | Probability | Accumulated | Special Marks | |:---------------:|:-----------:|:-----------:|:-------------:| | 0 | 0% | 100% | Last Result | | 1 | 0.3% | 100% | | | 2 | 83% | 99.7% | Median | | 3 | 16% | 16% | | | 4 | 0% | 0% | | ### Coalició Compromís (Greens/EFA) *For a full overview of the results for this party, see the [Coalició Compromís (Greens/EFA)](party-coaliciócompromísgreensefa.html) page.* ![Graph with seats probability mass function not yet produced](2022-02-28-40dB-seats-pmf-coaliciócompromísgreensefa.png "Seats Probability Mass Function") | Number of Seats | Probability | Accumulated | Special Marks | |:---------------:|:-----------:|:-----------:|:-------------:| | 0 | 0% | 100% | Last Result | | 1 | 93% | 100% | Median | | 2 | 7% | 7% | | | 3 | 0% | 0% | | ## Coalitions ![Graph with coalitions seats not yet produced](2022-02-28-40dB-coalitions-seats.png "Coalitions Seats") ### Confidence Intervals | Coalition | Last Result | Median | Majority? | 80% Confidence Interval | 90% Confidence Interval | 95% Confidence Interval | 99% Confidence Interval | |:---------:|:-----------:|:------:|:---------:|:-----------------------:|:-----------------------:|:-----------------------:|:-----------------------:| | Partido Socialista Obrero Español (S&D) | 0 | 16 | 0% | 15–17 | 15–17 | 15–17 | 15–18 | | Partido Popular (EPP) | 0 | 13 | 0% | 12–14 | 12–14 | 12–14 | 12–15 | | Vox (ECR) | 0 | 12 | 0% | 11–12 | 11–12 | 10–13 | 10–13 | ### Partido Socialista Obrero Español (S&D) ![Graph with seats probability mass function not yet produced](2022-02-28-40dB-coalitions-seats-pmf-psoe.png "Seats Probability Mass Function") | Number of Seats | Probability | Accumulated | Special Marks | |:---------------:|:-----------:|:-----------:|:-------------:| | 0 | 0% | 100% | Last Result | | 1 | 0% | 100% | | | 2 | 0% | 100% | | | 3 | 0% | 100% | | | 4 | 0% | 100% | | | 5 | 0% | 100% | | | 6 | 0% | 100% | | | 7 | 0% | 100% | | | 8 | 0% | 100% | | | 9 | 0% | 100% | | | 10 | 0% | 100% | | | 11 | 0% | 100% | | | 12 | 0% | 100% | | | 13 | 0% | 100% | | | 14 | 0.3% | 100% | | | 15 | 13% | 99.7% | | | 16 | 55% | 87% | Median | | 17 | 29% | 31% | | | 18 | 2% | 2% | | | 19 | 0% | 0% | | ### Partido Popular (EPP) ![Graph with seats probability mass function not yet produced](2022-02-28-40dB-coalitions-seats-pmf-pp.png "Seats Probability Mass Function") | Number of Seats | Probability | Accumulated | Special Marks | |:---------------:|:-----------:|:-----------:|:-------------:| | 0 | 0% | 100% | Last Result | | 1 | 0% | 100% | | | 2 | 0% | 100% | | | 3 | 0% | 100% | | | 4 | 0% | 100% | | | 5 | 0% | 100% | | | 6 | 0% | 100% | | | 7 | 0% | 100% | | | 8 | 0% | 100% | | | 9 | 0% | 100% | | | 10 | 0% | 100% | | | 11 | 0.3% | 100% | | | 12 | 16% | 99.7% | | | 13 | 60% | 83% | Median | | 14 | 22% | 23% | | | 15 | 0.9% | 0.9% | | | 16 | 0% | 0% | | ### Vox (ECR) ![Graph with seats probability mass function not yet produced](2022-02-28-40dB-coalitions-seats-pmf-vox.png "Seats Probability Mass Function") | Number of Seats | Probability | Accumulated | Special Marks | |:---------------:|:-----------:|:-----------:|:-------------:| | 0 | 0% | 100% | Last Result | | 1 | 0% | 100% | | | 2 | 0% | 100% | | | 3 | 0% | 100% | | | 4 | 0% | 100% | | | 5 | 0% | 100% | | | 6 | 0% | 100% | | | 7 | 0% | 100% | | | 8 | 0% | 100% | | | 9 | 0% | 100% | | | 10 | 3% | 100% | | | 11 | 46% | 97% | | | 12 | 47% | 51% | Median | | 13 | 4% | 4% | | | 14 | 0% | 0% | | ## Technical Information ### Opinion Poll + **Polling firm:** 40dB + **Commissioner(s):** Prisa + **Fieldwork period:** 22–28 February 2022 ### Calculations + **Sample size:** 2000 + **Simulations done:** 1,048,576 + **Error estimate:** 0.49%
C
UTF-8
600
3.046875
3
[]
no_license
#include <stdio.h> int main() { int w, h, f; scanf("%d %d %d", &w, &h, &f); int k = h-1; for(int i = 0 ; i < h ; i++){ if(f == 2){ for(int j = 0 ; j < k ; j++){ printf(" "); } } else if(f == 1){ for(int j = k+1 ; j < h ; j++){ printf(" "); } } printf("#"); for(int j = 2 ; j < w ; j++){ if(i == 0 || i == h-1) printf("#"); else printf(" "); } printf("#"); k--; printf("\n"); } return 0; }
Java
UTF-8
2,665
2.90625
3
[]
no_license
package com.algoexpert.veryhard.maxktransaction; import static org.assertj.core.api.Assertions.assertThat; import org.junit.Test; public class ProgramTest { @Test public void TestCase1() { int[] input = {}; assertThat(Program2.maxProfitWithKTransactions(input, 1)).isEqualTo(0); } @Test public void TestCase2() { int[] input = {1}; assertThat(Program2.maxProfitWithKTransactions(input, 1)).isEqualTo(0); } @Test public void TestCase3() { int[] input = {1, 10}; assertThat(Program2.maxProfitWithKTransactions(input, 1)).isEqualTo(9); } @Test public void TestCase4() { int[] input = {1, 10}; assertThat(Program2.maxProfitWithKTransactions(input, 3)).isEqualTo(9); } @Test public void TestCase5() { int[] input = {3, 2, 5, 7, 1, 3, 7}; assertThat(Program2.maxProfitWithKTransactions(input, 1)).isEqualTo(6); } @Test public void TestCase6() { int[] input = {5, 11, 3, 50, 60, 90}; assertThat(Program2.maxProfitWithKTransactions(input, 2)).isEqualTo(93); } @Test public void TestCase7() { int[] input = {5, 11, 3, 50, 60, 90}; assertThat(Program2.maxProfitWithKTransactions(input, 3)).isEqualTo(93); } @Test public void TestCase8() { int[] input = {5, 11, 3, 50, 40, 90}; assertThat(Program2.maxProfitWithKTransactions(input, 2)).isEqualTo(97); } @Test public void TestCase9() { int[] input = {5, 11, 3, 50, 40, 90}; assertThat(Program2.maxProfitWithKTransactions(input, 3)).isEqualTo(103); } @Test public void TestCase10() { int[] input = {50, 25, 12, 4, 3, 10, 1, 100}; assertThat(Program2.maxProfitWithKTransactions(input, 2)).isEqualTo(106); } @Test public void TestCase11() { int[] input = {100, 99, 98, 97, 1}; assertThat(Program2.maxProfitWithKTransactions(input, 5)).isEqualTo(0); } @Test public void TestCase12() { int[] input = {1, 100, 2, 200, 3, 300, 4, 400, 5, 500}; assertThat(Program2.maxProfitWithKTransactions(input, 5)).isEqualTo(1485); } @Test public void TestCase13() { int[] input = {1, 100, 101, 200, 201, 300, 301, 400, 401, 500}; assertThat(Program2.maxProfitWithKTransactions(input, 5)).isEqualTo(499); } @Test public void TestCase14() { int[] input = {1, 25, 24, 23, 12, 36, 14, 40, 31, 41, 5}; assertThat(Program2.maxProfitWithKTransactions(input, 4)).isEqualTo(84); } @Test public void TestCase15() { int[] input = {1, 25, 24, 23, 12, 36, 14, 40, 31, 41, 5}; assertThat(Program2.maxProfitWithKTransactions(input, 2)).isEqualTo(62); } }
Python
UTF-8
552
2.546875
3
[ "MIT" ]
permissive
import os import subprocess sizes = [16, 24, 32, 48, 57, 64, 76, 96, 120, 128, 144, 152, 180, 192, 195, 196, 228, 270, 512] if __name__ == '__main__': publicFolder = f'{os.path.dirname(os.path.abspath(__file__))}/public' filePath = f'{publicFolder}/icon.svg' if os.path.exists(filePath): os.mkdir(f'{publicFolder}/icons') for size in sizes: subprocess.call(['inkscape', '-z', '-e', f'{publicFolder}/icons/{size}.png', '-w', str(size), filePath]) else: print('ファイルが見つかりません')