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
Java
UTF-8
463
2.46875
2
[]
no_license
package br.edu.opi.manager.office_io.exceptions; import br.edu.opi.manager.project_patterns.exceptions.ConflictsRuntimeException; public class CreateFileRuntimeException extends ConflictsRuntimeException { public CreateFileRuntimeException() { super("Não foi possível gerar arquivo no momento: disco temporário cheio. Favor tentar novamente em instantes."); } @Override public String getErrorCode() { return ErrorConstants.CREATE_FILE_ERROR; } }
Markdown
UTF-8
445
2.90625
3
[]
no_license
--- title: js中 整数、浮点数的范围 date: 2016-07-17 23:00:14 tags: - JS --- 浮点数范围: ``` as large as ±1.7976931348623157 × 10的308次方 as small as ±5 × 10的−324次方 ``` 精确整数范围: ``` The JavaScript number format allows you to exactly represent all integers between −9007199254740992 and 9007199254740992 (即正负2的53次方) ``` 数组索引还有位操作: ``` 正负2的31次方 ```
Python
UTF-8
4,326
2.90625
3
[]
no_license
import csv from counter import Counter from pprint import pprint def group_by_country(list_of_dicts): result = {} for input_dict in list_of_dicts: cc = input_dict['Country Code'] if cc not in result.keys(): result.update({cc : {input_dict['Indicator Name'] : input_dict}}) else: result[cc].update({input_dict['Indicator Name'] : input_dict}) return result # foo = [{'a' : 2, 'b' : 4, 'Country Code' : 'USA', 'Indicator Name' : 'foo'}, {'a' : 3, 'b' : 10, 'Country Code' : 'RUS', 'Indicator Name' : 'foo2'}, {'a' : 1, 'c' : 4, 'Country Code' : 'USA', 'Indicator Name' : 'foo3'}] # group_by_country(foo) def count_tags(filename_str): with open(filename_str, 'rb') as csvfile: records = list(csv.DictReader(csvfile)) count = Counter() for rec in records: count.update({rec['Indicator Name'] : 1}) pprint(count.keys()) #count_tags('WDI_Data.csv') def read_csvdata(filename_str): with open(filename_str, 'rb') as csvfile: records = list(csv.DictReader(csvfile)) # print type(records), type(records[0]) new_mess = group_by_country(records) # new_mess IS {COUNTRY KEY : INQUIRY TYPE KEY : {DATA}}} return new_mess def read_in_ccds(filename_str): with open(filename_str, 'rb') as csvfile: result_dict = {} a3 = 'Alpha-3 code' full_name = 'English short name lower case' list_of_dicts = list(csv.DictReader(csvfile)) for dict_rec in list_of_dicts: result_dict.update({dict_rec[a3] : dict_rec[full_name]}) return result_dict def amurrica(three_layer_dict): for key, value in three_layer_dict.items(): if key == 'USA': return value else: pass def select_years_from_keys(one_layer_dict, return_meta_data=False): import re from collections import OrderedDict result_dict = OrderedDict() metadata = {} for key, value in one_layer_dict.items(): if re.findall(r'^\d\d\d\d$', key): result_dict[key] = value elif return_meta_data: metadata[key] = value result_dict = OrderedDict(sorted(result_dict.iteritems(), key=lambda x : x[0])) if return_meta_data: metadata = OrderedDict(sorted(metadata.iteritems(), key=lambda x : x[0])) return result_dict, metadata else: return result_dict def extract_data_for_dicts_in_dict(two_layer_dict, topic_string_list, return_meta_data=False): year_data = {} metadata = {} if return_meta_data: for topic in topic_string_list: temp_rec, meta = select_years_from_keys(two_layer_dict[topic], return_meta_data=return_meta_data) year_data[topic] = temp_rec metadata[topic] = meta return year_data, metadata else: for topic in topic_string_list: temp_rec = select_years_from_keys(two_layer_dict[topic]) year_data[topic] = temp_rec return year_data def turn_yeardicts_into_dataframe(two_layer_dict): import pandas as pd keys = [] counter = 0 for data in two_layer_dict.values(): if counter >= 1: break keys = data.keys() data_frame = pd.DataFrame(columns=keys, index=two_layer_dict.keys()) for key, value in two_layer_dict.items(): data_frame.loc[key] = pd.Series(value) return data_frame def write_to_csv(panda_data, new_file_name_str): panda_data.to_csv(new_file_name_str) print 'file: {} created'.format(new_file_name_str) def print_labels(): three_layer_dict = read_csvdata('WDI_Data.csv') american_data = amurrica(three_layer_dict) print american_data.keys() def main(): from variables import topic_strings three_layer_dict = read_csvdata('WDI_Data.csv') # extract_count_of_blanks(three_layer_dict) american_data = amurrica(three_layer_dict) data_by_year, metadata = extract_data_for_dicts_in_dict(american_data, topic_strings, return_meta_data=True) # print data_by_year, metadata data_frame = turn_yeardicts_into_dataframe(data_by_year) write_to_csv(data_frame, 'American_edu_data_1.csv') # cc means country code # ccode_cname_dict = read_in_ccds('country_code_data.csv') if __name__ == '__main__': main()
Python
UTF-8
837
2.921875
3
[]
no_license
import time import pyautogui pyautogui.FAILSAFE= False import turtle turtle.setworldcoordinates(0, -1080, 1920, 0) turtle.speed(3) turtle.pensize(15) turtle.color("#44ebb6") turtle.st() turtle.shape("square") def chaap(): turtle.down() def no_chaap(): turtle.up() def bhaga_turtle(x,y): x*=1920/88 y*=-1080/38 if(x<1920 and y>-1080 and x>0 and y<0): turtle.goto(x,y) def move_cursor(x, y): x*=1920/88 y*=1080/50 if(x<1920 and y<1080): pyautogui.dragRel(int(x), int(y), duration = 0) #print(pyautogui.position()) #pyautogui.click(x, y) def click_cursor(x, y): x*=1920/88 y*=1080/50 if(x<1920 and y<1080): pyautogui.moveTo(x, y, duration = 0) #print(pyautogui.position()) pyautogui.click(x, y) #move_cursor(88,50) #move_cursor(100,200) #click_cursor(100,100)
Java
UTF-8
542
2.109375
2
[]
no_license
package com.login; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class DeleteServlet extends HttpServlet { protected void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException { String sid=request.getParameter("id"); int id=Integer.parseInt(sid); DaoMVC.delete(id); response.sendRedirect("ViewServlet"); } }
SQL
UTF-8
3,348
3.40625
3
[]
no_license
CREATE TABLE core.dd_documents ( id uuid DEFAULT public.uuid_generate_v4() NOT NULL, c_first_name text, c_last_name text, c_middle_name text, d_birthday date, c_city_reg text, c_street_reg text, c_house_reg text, c_premise_reg text, c_city_life text, c_street_life text, c_house_life text, c_premise_life text, c_education text, c_work_place text, c_biografy text, b_administrative boolean, b_criminal boolean, c_arrest text, f_user integer NOT NULL, sn_delete boolean DEFAULT false, dx_created timestamp with time zone DEFAULT now(), c_soc_link text, c_tag text, c_notice text ); ALTER TABLE core.dd_documents OWNER TO card; COMMENT ON COLUMN core.dd_documents.id IS 'Идентификатор'; COMMENT ON COLUMN core.dd_documents.c_first_name IS 'Фамилия'; COMMENT ON COLUMN core.dd_documents.c_last_name IS 'Имя'; COMMENT ON COLUMN core.dd_documents.c_middle_name IS 'Отчество'; COMMENT ON COLUMN core.dd_documents.d_birthday IS 'Дата рождения'; COMMENT ON COLUMN core.dd_documents.c_city_reg IS 'Город (адрес регистрации)'; COMMENT ON COLUMN core.dd_documents.c_street_reg IS 'Улица (адрес регистрации)'; COMMENT ON COLUMN core.dd_documents.c_house_reg IS 'Дом (адрес регистрации)'; COMMENT ON COLUMN core.dd_documents.c_premise_reg IS 'Квартира (адрес регистрации)'; COMMENT ON COLUMN core.dd_documents.c_city_life IS 'Город (адрес проживания)'; COMMENT ON COLUMN core.dd_documents.c_street_life IS 'Улица (адрес проживания)'; COMMENT ON COLUMN core.dd_documents.c_house_life IS 'Дом (адрес проживания)'; COMMENT ON COLUMN core.dd_documents.c_premise_life IS 'Квартира (адрес проживания)'; COMMENT ON COLUMN core.dd_documents.c_education IS 'Образование'; COMMENT ON COLUMN core.dd_documents.c_work_place IS 'Место работы'; COMMENT ON COLUMN core.dd_documents.c_biografy IS 'Биографическая информация'; COMMENT ON COLUMN core.dd_documents.b_administrative IS 'Административная ответственность'; COMMENT ON COLUMN core.dd_documents.b_criminal IS 'Уголовная ответственность'; COMMENT ON COLUMN core.dd_documents.c_arrest IS 'Задержание'; COMMENT ON COLUMN core.dd_documents.f_user IS 'Пользователь'; COMMENT ON COLUMN core.dd_documents.sn_delete IS 'Признак удаленности'; COMMENT ON COLUMN core.dd_documents.dx_created IS 'Дата создания'; COMMENT ON COLUMN core.dd_documents.c_soc_link IS 'Ссылки на социальные сети'; -------------------------------------------------------------------------------- CREATE TRIGGER dd_documents_1 BEFORE INSERT OR UPDATE OR DELETE ON core.dd_documents FOR EACH ROW EXECUTE PROCEDURE core.cft_log_action(); -------------------------------------------------------------------------------- ALTER TABLE core.dd_documents ADD CONSTRAINT dd_documents_pkey PRIMARY KEY (id); -------------------------------------------------------------------------------- ALTER TABLE core.dd_documents ADD CONSTRAINT dd_documnets_f_user_fkey FOREIGN KEY (f_user) REFERENCES core.pd_users(id) NOT VALID;
Python
UTF-8
874
4.1875
4
[]
no_license
#!/usr/bin/python3 """ Modulo for determing if a coordenate belong to an area """ def check_interval(value, interval): "check if value is in the interval" return value >= interval[0] and value <= interval[1] def create_interval(value, dimension): "create a list of coordenates" dimension /= 2 return ([value - dimension, value + dimension]) if __name__ == "__main__": height = int(input("Enter height of the rectagule: ")) width = int(input("Enter width of the rectagule: ")) x = int(input("Enter coordenate x: ")) y = int(input("Enter coordenate y: ")) point_x = int(input("Enter coordenate x: ")) point_y = int(input("Enter coordenate y: ")) values_x = create_interval(x, height) values_y = create_interval(y, width) print(check_interval(point_x, values_x) and check_interval(point_y, values_y))
Markdown
UTF-8
3,723
2.625
3
[ "CC-BY-4.0", "MIT" ]
permissive
--- title: Azure Maps에서 확대/축소 수준 및 타일 그리드 | Microsoft Docs description: Azure Maps에서 확대/축소 수준 및 타일 그리드에 대해 알아봅니다. services: azure-maps keywords: '' author: jinzh-azureiot ms.author: jinzh ms.date: 05/07/2018 ms.topic: article ms.service: azure-maps documentationcenter: '' manager: timlt ms.devlang: na ms.custom: '' ms.openlocfilehash: 330333569f094fe3cec7f73ee3b20107ec70f5b5 ms.sourcegitcommit: e221d1a2e0fb245610a6dd886e7e74c362f06467 ms.translationtype: HT ms.contentlocale: ko-KR ms.lasthandoff: 05/07/2018 --- # <a name="zoom-levels-and-tile-grid"></a>확대/축소 수준 및 타일 그리드 Azure Maps에서는 구면 메르카토르 도법 구면좌표계를 사용합니다(EPSG: 3857). 전 세계는 정사각형 타일로 구분됩니다. 렌더링(래스터)에는 0부터 18까지 19개의 확대/축소 수준이 있습니다. 렌더링(벡터)에는 0부터 20까지 21개의 확대/축소 수준이 있습니다. 확대/축소 수준 0에서 전 세계는 단일 타일로 맞춰집니다. ![세계 타일](./media/zoom-levels-and-tile-grid/world0.png) 확대/축소 수준 1은 4개의 타일을 사용하여 전 세계를 2x2 사각형으로 렌더링합니다. ![왼쪽 위 세계 타일](./media/zoom-levels-and-tile-grid/world1a.png) ![오른쪽 위 세계 타일](./media/zoom-levels-and-tile-grid/world1c.png) ![왼쪽 아래 세계 타일](./media/zoom-levels-and-tile-grid/world1b.png) ![오른쪽 아래 세계 타일](./media/zoom-levels-and-tile-grid/world1d.png) 후속 확대/축소 수준 4개 타일은 각각 이전 수준의 타일을 나누어서 2<sup>확대/축소</sup>x2<sup>확대/축소</sup> 그리드를 만듭니다. 확대/축소 수준 20은 2<sup>20</sup> x 2<sup>20</sup> 그리드 또는 1,048,576 x 1,048,576 타일(총 109,951,162,778개)입니다. 다음 표는 확대/축소 수준의 전체 목록 값을 제공합니다. |확대/축소 수준|미터/픽셀|미터/타일 측| |--- |--- |--- | |0|156543|40075008| |1|78271.5|20037504| |2|39135.8|10018764.8| |3|19567.9|5009382.4| |4|9783.9|2504678.4| |5|4892|1252352| |6|2446|626176| |7|1223|313088| |8|611.5|156544| |9|305.7|78259.2| |10|152.9|39142.4| |11|76.4|19558.4| |12|38.2|9779.2| |13|19.1|4889.6| |14|9.6|2457.6| |15|4.8|1228.8| |16|2.4|614.4| |17|1.2|307.2| |18|0.6|152.8| |19|0.3|76.4| |20|0.15|38.2| 타일은 해당 확대/축소 수준의 그리드에서 타일의 위치에 해당하는 확대/축소 수준과 xy 좌표로 호출됩니다. 사용할 확대/축소 수준을 결정할 때 각 위치는 해당 타일의 고정된 위치에 있습니다. 즉, 지정된 범위의 지역을 표시하는 데 필요한 타일의 수는 전 세계에 대한 확대/축소 그리드의 배치에 따라 달라집니다. 예를 들어 900미터 떨어진 두 개의 지점이 있는 경우 확대/축소 수준 17에서 서로 간에 경로를 표시하기 위해 세 개의 타일만을 사용할 *수* 있습니다. 그러나 서쪽 지점이 해당 타일의 오른쪽에 있고 동쪽 지점이 해당 타일의 왼쪽에 있는 경우 4개의 타일이 필요할 수 있습니다. ![확대/축소 데모 크기 조정](./media/zoom-levels-and-tile-grid/zoomdemo_scaled.png) 확대/축소 수준이 결정되면 x 및 y 값을 계산할 수 있습니다. 각 확대/축소 그리드의 왼쪽 위 타일은 x=0, y=0이고, 오른쪽 아래 타일은 x=2<sup>zoom -1</sup>, y=2<sup>zoom-1</sup>입니다. 확대/축소 수준 1에서 확대/축소 그리드는 다음과 같습니다. ![확대/축소 수준 1에서 확대/축소 그리드](./media/zoom-levels-and-tile-grid/api_x_y.png)
C++
UTF-8
18,422
2.5625
3
[ "MIT" ]
permissive
#include "gamemodel.h" GameModel::GameModel(QObject *parent) : QObject(parent) { isBookOpened = false; meetNpc = 0; player = std::make_shared<Player>(); map = std::make_shared<GameMap>(); database.connect("data"); database.loadMap(map); database.loadPlayer(player); database.loadItems(); emitAll(); } void GameModel::playerMove(MagicTower::Direction direction) { if (meetNpc) { return; } qDebug("playerMove: %d\n", direction); setDirection(direction); auto position = player->getPosition(), newPosition = position; switch (direction) { case MagicTower::LEFT: newPosition.second--; break; case MagicTower::RIGHT: newPosition.second++; break; case MagicTower::UP: newPosition.first--; break; case MagicTower::DOWN: newPosition.first++; break; } if (newPosition.first >= 0 && newPosition.first < MagicTower::MAP_HEIGHT && newPosition.second >= 0 && newPosition.second < MagicTower::MAP_WIDTH) { bool willMove = false; QString statusStr = map->getData(player->getLayer(), newPosition.first, newPosition.second); QStringList status = statusStr.split('_'); if (status.size() == 1) { QString &type = status[0]; if (type == ".") { /* empty */ willMove = true; } else if (type == "dn") { /* downstair */ willMove = true; setLayer(player->getLayer() - 1); newPosition = map->findStr(player->getLayer(), "d_1"); qDebug() << newPosition; } else if (type == "up") { /* upstair */ willMove = true; setLayer(player->getLayer() + 1); newPosition = map->findStr(player->getLayer(), "d_0"); qDebug() << newPosition; } else if (type == "wi") { setMapData(player->getLayer(), newPosition.first, newPosition.second, "."); setItemOwn(MagicTower::MONSTER_BOOK, true); } } else if(status.size() == 2) { QString &type = status[0]; int id = status[1].toInt(); if (type == "d") { /* empty */ willMove = true; } else if (type == "me") { /* merchant */ if (id == 4) { if (newPosition.second == 5) { setMapData(player->getLayer(), newPosition.first, newPosition.second, "."); setMapData(player->getLayer(), newPosition.first, newPosition.second - 1, "me_4"); } } else if (id == 3 && player->getLayer() == 3) { emit openModal("商人: 用25元换取任意一项:\n1. 增加800点生命\n2. 增加4点攻击\n3. 增加4点防御\n0. 取消"); meetNpc = 3; } else if (id == 2 && player->getLayer() == 5) { emit openModal("商人: 经验换实力.\n1. 提升一级(100经验)\n2. 增加5点攻击(30经验)\n3. 增加5点防御(30点经验)\n0. 取消"); meetNpc = 2; } else if (id == 1 && player->getLayer() == 5) { emit openModal("商人: 金币换钥匙.\n1. 购买一把黄钥匙($10)\n2. 购买一把蓝钥匙($50)\n3. 购买一把红钥匙($100)\n0. 取消"); meetNpc = 1; } else if (id == 3 && player->getLayer() == 11) { emit openModal("商人: 用100元换取任意一项:\n1. 增加4000点生命\n2. 增加20点攻击\n3. 增加20点防御\n0. 取消"); meetNpc = 3; } else if (id == 1 && player->getLayer() == 12) { emit openModal("商人: 如果你缺少金币, 我可以帮你.\n1. 卖出一把黄钥匙($7)\n2. 卖出一把蓝钥匙($35)\n3. 卖出一把红钥匙($70)\n0. 取消"); meetNpc = 1; } else if (id == 2 && player->getLayer() == 13) { emit openModal("商人: 经验换实力.\n1. 提升三级(270经验)\n2. 增加17点攻击(95经验)\n3. 增加17点防御(95点经验)\n0. 取消"); meetNpc = 2; } /* TODO: different merchant */ } else if (type == "k") { /* key */ setMapData(player->getLayer(), newPosition.first, newPosition.second, "."); setKeyCount((MagicTower::KeyType)id, player->getKeyCount((MagicTower::KeyType)id) + 1); const QString colorList[MagicTower::KEY_TYPE_COUNT] = {"黄", "蓝", "红"}; emit itemGet("获得了" + colorList[id] + "钥匙一把"); } else if (type == "dr") { /* door */ if (id < 3 && player->getKeyCount((MagicTower::KeyType)id)) { setMapData(player->getLayer(), newPosition.first, newPosition.second, "."); setKeyCount((MagicTower::KeyType)id, player->getKeyCount((MagicTower::KeyType)id) - 1); } } else if (type == "m") { /* medicine */ setMapData(player->getLayer(), newPosition.first, newPosition.second, "."); medicine cur = database.getMedicine(id); if (cur.health) { setHealth(player->getHealth() + cur.health); emit itemGet("生命回复了 " + QString::number(cur.health)); } if (cur.attack) { setAttack(player->getAttack() + cur.attack); emit itemGet("攻击上升了 " + QString::number(cur.attack)); } if (cur.defence) { setDefence(player->getDefence() + cur.defence); emit itemGet("防御上升了 " + QString::number(cur.defence)); } } else if (type == "a") { /* armour */ setMapData(player->getLayer(), newPosition.first, newPosition.second, "."); armour cur = database.getArmour(id); setDefence(player->getDefence() + cur.defence); emit itemGet("防御上升了 " + QString::number(cur.defence)); } else if (type == "s") { /* weapon */ setMapData(player->getLayer(), newPosition.first, newPosition.second, "."); weapon cur = database.getWeapon(id); setAttack(player->getAttack() + cur.attack); emit itemGet("攻击上升了 " + QString::number(cur.attack)); } else if (type == "e") { /* enemy */ monster cur = database.getMonster(id); int damage = player->getAttack() - cur.defence; qDebug() << cur.health << cur.attack << cur.defence; if (damage > 0) { int roundCnt = (cur.health + damage - 1) / damage; int monsterDamage = qMax(cur.attack - player->getDefence(), 0); if (player->getHealth() > monsterDamage * roundCnt) { /* win */ setMapData(player->getLayer(), newPosition.first, newPosition.second, "."); setHealth(player->getHealth() - monsterDamage * roundCnt); setGold(player->getGold() + cur.gold); setExp(player->getExp() + cur.exp); emit playerWin("得到金币数 " + QString::number(cur.gold) + "得到经验值 " + QString::number(cur.exp)); } } } } if (willMove) { setPosition(newPosition); } } } void GameModel::playerChoose(int choice) { if (meetNpc == 3 && player->getLayer() == 3) { if (choice >= 0 && choice <= 3) { if (player->getGold() >= 25) { if (choice == 1) { setHealth(player->getHealth() + 800); setGold(player->getGold() - 25); } else if (choice == 2) { setAttack(player->getAttack() + 4); setGold(player->getGold() - 25); } else if (choice == 3) { setDefence(player->getDefence() + 4); setGold(player->getGold() - 25); } } else { if (choice) { emit itemGet("金币不足!"); } } meetNpc = 0; emit closeModal(); } } else if (meetNpc == 2 && player->getLayer() == 5) { if (choice >= 0 && choice <= 3) { if (choice == 1) { if (player->getExp() >= 100) { setExp(player->getExp() - 100); setHealth(player->getHealth() + 1000); setAttack(player->getAttack() + 7); setDefence(player->getDefence() + 7); } else { emit itemGet("经验值不足!"); } } else if (choice == 2) { if (player->getExp() >= 30) { setExp(player->getExp() - 30); setAttack(player->getAttack() + 5); } else { emit itemGet("经验值不足!"); } } else if (choice == 3) { if (player->getExp() >= 30) { setExp(player->getExp() - 30); setDefence(player->getDefence() + 5); } else { emit itemGet("经验值不足!"); } } meetNpc = 0; emit closeModal(); } } else if (meetNpc == 1 && player->getLayer() == 5) { if (choice >= 0 && choice <= 3) { if (choice == 1) { if (player->getGold() >= 10) { setGold(player->getGold() - 10); setKeyCount((MagicTower::KeyType)0, player->getKeyCount((MagicTower::KeyType)0) + 1); } else { emit itemGet("金币不足!"); } } else if (choice == 2) { if (player->getGold() >= 50) { setGold(player->getGold() - 50); setKeyCount((MagicTower::KeyType)1, player->getKeyCount((MagicTower::KeyType)1) + 1); } else { emit itemGet("金币不足!"); } } else if (choice == 3) { if (player->getGold() >= 100) { setGold(player->getGold() - 100); setKeyCount((MagicTower::KeyType)2, player->getKeyCount((MagicTower::KeyType)2) + 1); } else { emit itemGet("金币不足!"); } } meetNpc = 0; emit closeModal(); } } else if (meetNpc == 3 && player->getLayer() == 11) { if (choice >= 0 && choice <= 3) { if (player->getGold() >= 100) { if (choice == 1) { setHealth(player->getHealth() + 4000); setGold(player->getGold() - 100); } else if (choice == 2) { setAttack(player->getAttack() + 20); setGold(player->getGold() - 100); } else if (choice == 3) { setDefence(player->getDefence() + 20); setGold(player->getGold() - 100); } } else { if (choice) { emit itemGet("金币不足!"); } } meetNpc = 0; emit closeModal(); } } else if (meetNpc == 2 && player->getLayer() == 13) { if (choice >= 0 && choice <= 3) { if (choice == 1) { if (player->getExp() >= 270) { setExp(player->getExp() - 270); setHealth(player->getHealth() + 3000); setAttack(player->getAttack() + 21); setDefence(player->getDefence() + 21); } else { emit itemGet("经验值不足!"); } } else if (choice == 2) { if (player->getExp() >= 95) { setExp(player->getExp() - 95); setAttack(player->getAttack() + 17); } else { emit itemGet("经验值不足!"); } } else if (choice == 3) { if (player->getExp() >= 95) { setExp(player->getExp() - 95); setDefence(player->getDefence() + 17); } else { emit itemGet("经验值不足!"); } } meetNpc = 0; emit closeModal(); } } else if (meetNpc == 1 && player->getLayer() == 12) { if (choice >= 0 && choice <= 3) { if (choice == 1) { if (player->getKeyCount((MagicTower::KeyType)0)) { setGold(player->getGold() + 7); setKeyCount((MagicTower::KeyType)0, player->getKeyCount((MagicTower::KeyType)0) - 1); } else { emit itemGet("金币不足!"); } } else if (choice == 2) { if (player->getKeyCount((MagicTower::KeyType)1)) { setGold(player->getGold() + 35); setKeyCount((MagicTower::KeyType)1, player->getKeyCount((MagicTower::KeyType)1) - 1); } else { emit itemGet("金币不足!"); } } else if (choice == 3) { if (player->getKeyCount((MagicTower::KeyType)2)) { setGold(player->getGold() + 70); setKeyCount((MagicTower::KeyType)2, player->getKeyCount((MagicTower::KeyType)2) - 1); } else { emit itemGet("金币不足!"); } } meetNpc = 0; emit closeModal(); } } } std::shared_ptr<Player> GameModel::getPlayer() const { return player; } std::shared_ptr<GameMap> GameModel::getGameMap() const{ return map; } void GameModel::emitAll() { for (int l = 0; l < MagicTower::MAP_LAYER; l++) { for (int x = 0; x < MagicTower::MAP_HEIGHT; x++) { for (int y = 0; y < MagicTower::MAP_WIDTH; y++) { emit mapDataChanged(l, x, y, map->getData(l, x, y)); } } } emit healthChanged(player->getHealth()); emit attackChanged(player->getAttack()); emit defenceChanged(player->getDefence()); emit goldChanged(player->getGold()); emit expChanged(player->getExp()); emit levelChanged(player->getLevel()); emit layerChanged(player->getLayer()); for (int i = 0; i < MagicTower::KEY_TYPE_COUNT; i++) { emit keyCountChanged((MagicTower::KeyType)i, player->getKeyCount((MagicTower::KeyType)i)); } for (int i = 0; i < MagicTower::ITEM_TYPE_COUNT; i++) { emit itemOwnChanged((MagicTower::ItemType)i, player->getItemOwn((MagicTower::ItemType)i)); } emit positionChanged(player->getPosition()); emit directionChanged(player->getDirection()); } void GameModel::gameSave() { database.saveMap(map, 1); database.savePlayer(player, 1); emit itemGet("保存成功"); } void GameModel::gameLoad() { database.loadMap(map, 1); database.loadPlayer(player, 1); emitAll(); emit itemGet("读取成功"); } void GameModel::gameRestart() { database.loadMap(map); database.loadPlayer(player); emitAll(); emit itemGet("重新开始"); } void GameModel::useBook() { if (player->getItemOwn(MagicTower::MONSTER_BOOK)) { if (isBookOpened) { isBookOpened = false; emit closeBook(); } else { isBookOpened = true; QVector<monster> monsterList; QSet<int> monsterIdSet; for (int x = 0; x < MagicTower::MAP_HEIGHT; x++) { for (int y = 0; y < MagicTower::MAP_WIDTH; y++) { QString statusStr = map->getData(player->getLayer(), x, y); QStringList status = statusStr.split('_'); if (status.size() == 2 && status[0] == "e") { monsterIdSet.insert(status[1].toInt()); } } } foreach (int id, monsterIdSet) { monsterList.push_back(database.getMonster(id)); } emit openBook(monsterList); } } } void GameModel::setMapData(int l, int x, int y, const QString &newValue) { if (map->setData(l, x, y, newValue)) { emit mapDataChanged(l, x, y, newValue); } } void GameModel::setHealth(int newValue) { if (player->setHealth(newValue)) { emit healthChanged(newValue); } } void GameModel::setAttack(int newValue) { if (player->setAttack(newValue)) { emit attackChanged(newValue); } } void GameModel::setDefence(int newValue) { if (player->setDefence(newValue)) { emit defenceChanged(newValue); } } void GameModel::setGold(int newValue) { if (player->setGold(newValue)) { emit goldChanged(newValue); } } void GameModel::setExp(int newValue) { if (player->setExp(newValue)) { emit expChanged(newValue); } } void GameModel::setLevel(int newValue) { if (player->setLevel(newValue)) { emit levelChanged(newValue); } } void GameModel::setLayer(int newValue) { if (player->setLayer(newValue)) { emit layerChanged(newValue); } } void GameModel::setKeyCount(MagicTower::KeyType keyType, int newValue) { if (player->setKeyCount(keyType, newValue)) { emit keyCountChanged(keyType, newValue); } } void GameModel::setItemOwn(MagicTower::ItemType itemType, bool newValue) { if (player->setItemOwn(itemType, newValue)) { emit itemOwnChanged(itemType, newValue); } } void GameModel::setPosition(QPair<int, int> newValue) { if (player->setPosition(newValue)) { emit positionChanged(newValue); } } void GameModel::setDirection(MagicTower::Direction newValue) { if (player->setDirection(newValue)) { emit directionChanged(newValue); } }
C#
UTF-8
2,916
2.84375
3
[]
no_license
using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using AuiSpaceGame.Model; namespace AuiSpaceGame.Model { public class Asteroid : Animation, INotifyPropertyChanged { private double speed; private double lane; public event PropertyChangedEventHandler PropertyChanged; public double Lane { get { return lane; } set { lane = value; UpdateImage(); NotifyPropertyChanged("image"); } } // 1240 : speed(ms) = time public double Speed { get { return speed; } set { speed = value; AnimationDuration = TimeSpan.FromMilliseconds(((Constant.Square * 2) * 1000) / speed); Console.WriteLine(AnimationDuration); UpdateImage(); NotifyPropertyChanged("image"); } } public double Z0 { get; set; } public Asteroid(double lane, double speed) { Lane = lane; Speed = speed; Z0 = Constant.ZLittleSpace + Constant.Square - Constant.Delta; AnimationDuration = TimeSpan.FromMilliseconds(((Constant.Square * 2) * 1000) / Speed); UpdateImage(); } private void UpdateImage() { string NewImage = "Asteroids/Asteroid-"; if (speed == AuiSpaceGame.Model.Speed.Low) NewImage += "low-"; else if (speed == AuiSpaceGame.Model.Speed.High) NewImage += "high-"; if (lane == AuiSpaceGame.Model.Lane.Left) NewImage += "left"; else if (lane == AuiSpaceGame.Model.Lane.Middle) NewImage += "middle"; else if (lane == AuiSpaceGame.Model.Lane.Right) NewImage += "right"; NewImage += ".png"; Image = NewImage; } private void NotifyPropertyChanged(string propertyName) { if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } public override string ToString() { string LaneString = ""; if (this.lane == Model.Lane.Left) LaneString = "1"; else if (this.lane == Model.Lane.Middle) LaneString = "2"; else if (this.lane == Model.Lane.Right) LaneString = "3"; string SpeedString = ""; if (this.speed == Model.Speed.High) SpeedString = "100"; else if (this.speed == Model.Speed.Low) SpeedString = "50"; return LaneString + "?" + SpeedString+":100"; } } }
Java
UTF-8
469
1.953125
2
[]
no_license
package by.it.akhmelev.project06.java.conrollers; import by.it.akhmelev.project06.java.beans.Ad; import by.it.akhmelev.project06.java.dao.Dao; import javax.servlet.http.HttpServletRequest; import java.util.List; public class CmdIndex extends Cmd { @Override public Cmd execute(HttpServletRequest req) throws Exception { Dao dao = Dao.getDao(); List<Ad> ads = dao.ad.getAll(); req.setAttribute("ads",ads); return null; } }
C
UTF-8
928
3.046875
3
[]
no_license
/* ** check_numbers.c for checks of numbers in /home/pab/Documents/PSU_2015_navy_bootstrap/ex_2 ** ** Made by Pablo Berenguel ** Login <pablo.berenguel@epitech.net> ** ** Started on Wed Feb 3 09:15:36 2016 Pablo Berenguel ** Last update Wed Feb 3 14:33:18 2016 Pablo Berenguel */ #include <stdlib.h> #include "./include/my.h" int check_inside(char *str) { if (str[0] < '2' || str[0] > '5') return (84); if (str[1] != ':' || str[4] != ':') return (84); if (str[2] < 'A' || str[2] > 'H') return (84); if (str[3] < '1' || str[3] > '8') return (84); if (str[5] < 'A' || str[5] > 'H') return (84); if (str[6] < '1' || str[6] > '8') return (84); if (str[7] != '\n') return (84); return (0); } int check_numbers(char *str) { int i; i = 0; if (str == NULL) return (84); while (str[i] != '\0') { if (str[i] < '0' || str[i] > '9') return (84); i++; } return (0); }
PHP
UTF-8
853
2.8125
3
[]
no_license
<?php /** * Created by PhpStorm. * User: david * Date: 29/08/2018 * Time: 11:42 */ namespace Tests\AppBundle\Service; use AppBundle\Service\Slugger; use PHPUnit\Framework\TestCase; class SluggerTest extends TestCase //Test { public function testSlugify() { // Test avec minuscules $slugger = new Slugger(); $result1 = $slugger->slugify('Hello World'); // Assertion (contrainte) 1 $result2 = $slugger->slugify('Un éléphant ca Trompe enormement'); // Assertion 2 $this->assertEquals('hello-world', $result1); $this->assertEquals('un-l-phant-ca-trompe-enormement', $result2); // Test avec majuscules $slugger = new Slugger( false); $result3 = $slugger->slugify('Hello World'); // Assertion 3 (failure) $this->assertEquals('Hello-World', $result3); } }
Python
UTF-8
377
3.015625
3
[]
no_license
import math def solve(N, S, K): visited = set() now = S ans = 0 while now not in visited: print(now) if now == 0: return ans visited.add(now) delta = math.ceil((N - now) / K) ans += delta now = (now + delta * K) % N return -1 T = int(input()) for _ in range(T): N, S, K = (int(x) for x in input().split()) print(solve(N, S, K))
Python
UTF-8
562
2.921875
3
[ "MIT" ]
permissive
import sys sys.path.append('./strategies') from pairsClasses import Dealer from pairsClasses import SimpletonStrategy from alexStrategies import FixFoldStrategy from alexStrategies import RatioFoldStrategy PLAYERS = 2 for N in range(22,33,2): print("N = "+str(N)) losses = [0]*PLAYERS for i in range(10000): d = Dealer(PLAYERS) d.verbose = False d.gameState.players[0].strategy = FixFoldStrategy(3) d.gameState.players[1].strategy = RatioFoldStrategy(N) losses[d.play()] += 1 print(losses) print()
Java
UTF-8
266
1.6875
2
[ "MIT" ]
permissive
package io.github.mikolasan.petprojectnavigator; import android.view.View; interface PetDialogListener { // you can define any parameter as per your requirement void techCallback(View view, String result); void typeCallback(View view, String result); }
PHP
UTF-8
2,460
2.734375
3
[ "MIT" ]
permissive
<?php namespace Omneo\Concerns; use Omneo; use Illuminate\Support\Arr; use GuzzleHttp\Psr7\Response; use Illuminate\Support\Collection; trait MutatesResponses { /** * Transform the given entity with the given transformer. * * @param array $data * @param string|callable $transformer * @return mixed */ protected function transformEntity(array $data, $transformer) { if (! is_callable($transformer) && class_exists($transformer)) { $transformer = function (array $data) use ($transformer) { return new $transformer($data); }; } return $transformer($data); } /** * Build an entity from the given response. * * @param Response $response * @param string|callable $transformer * @return mixed */ protected function buildEntity(Response $response, $transformer) { return $this->transformEntity( json_decode((string) $response->getBody(), true)['data'], $transformer ); } /** * Build a collection from the given response. * * @param Response $response * @param string|callable $transformer * @return Collection */ protected function buildCollection(Response $response, $transformer) { return (new Collection( json_decode((string) $response->getBody(), true)['data'] ))->map(function (array $row) use ($transformer) { return $this->transformEntity($row, $transformer); }); } /** * Build a paginated collection from the given response. * * @param Response $response * @param string|callable $transformer * @param callable $executor * @param Omneo\Constraint $constraint * @return Omneo\PaginatedCollection */ protected function buildPaginatedCollection( Response $response, $transformer, callable $executor = null, Omneo\Constraint $constraint = null ) { $meta = json_decode((string) $response->getBody(), true)['meta']; return new Omneo\PaginatedCollection( $this->buildCollection($response, $transformer), Arr::get($meta, 'current_page'), Arr::get($meta, 'last_page'), Arr::get($meta, 'per_page'), Arr::get($meta, 'total'), $executor, $constraint ); } }
Ruby
UTF-8
941
3.203125
3
[]
no_license
require 'open-uri' require 'json' class GamesController < ApplicationController def new @grid = generate_grid(10) end def score @result = '' word = params[:word] if letters_found_in_grid?(word, params[:grid]) @result = english_word?(word) ? 'valid word' : 'not english' else @result = 'not found' end end private def generate_grid(grid_size) alphabet = ('A'..'Z').to_a result = [] (1..grid_size).each { |_i| result << alphabet.sample } result end def english_word?(word) url = "https://wagon-dictionary.herokuapp.com/#{word}" read_url = open(url).read json_result = JSON.parse(read_url) json_result['found'] end def letters_found_in_grid?(attempt, grid) attempt_array = attempt.upcase.split('') grid_array = grid.split('') attempt_array.all? do |letter| attempt_array.count(letter) <= grid_array.count(letter) end end end
Java
UTF-8
753
2.203125
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 controllers; import daos.StatusDAO; import java.sql.Connection; import java.util.List; /** * * @author BINTANG */ public class StatusController { private final StatusDAO sdao; public StatusController(Connection connection) { this.sdao = new StatusDAO(connection); } public List<Object[]> bindingSort(String category,String sort){ return this.sdao.getAllSort(category, sort); } public Object findById(String id){ return this.sdao.getById(Integer.parseInt(id)); } }
Python
UTF-8
187
3.5
4
[]
no_license
a=int(input("please enter first number")) b=int(input("please enter second number")) def sub(a,b): return a-b def multiply(a,b): return a*b print(sub(a,b)) print(multiply(a,b))
Python
UTF-8
3,258
2.578125
3
[]
no_license
import pygame import os import threading from properties import * from widgets import widget___tiled_map from threading import Thread from sprites.sprite import Sprite from sprites.sprite___deer import DeerSprite from sprites.sprite___wolf import WolfSprite from sprites.sprite____eagle import EagleSprite from sprites.sprite___lynx import LynxSprite from sprites.sprite___hare import HareSprite from sprites.sprite___ticks import TickSprite from sprites.poc___plant import PlantSprite from sprites.poc___bees import BeesSprite from sprites.poc___fish import FishSprite from sprites.poc___bear import BearSprite from groups.group___all_sprites import AllSpritesGroup from groups.group____fish import FishGroup from groups.group____wolf import WolfGroup from groups.group___bear import BearGroup from groups.group___bees import BeesGroup from groups.group___deer import DeerGroup from groups.group___plant import PlantGroup def sprite_test(): pygame.init() world_map = widget___tiled_map.WorldMap("map1.tmx", (0, 0)) world_map.render_entire_map() GRID_LOCK = threading.Lock() fish_group = FishGroup() bear_group = BearGroup() bees_group = BeesGroup() wolf_group = WolfGroup() deer_group = DeerGroup() plant_group = PlantGroup() s1 = EagleSprite(world_map, GRID_LOCK, (500, 500)) s2 = EagleSprite(world_map, GRID_LOCK, (550, 550)) s3 = FishSprite(world_map, GRID_LOCK, (450, 450)) s4 = WolfSprite(world_map, GRID_LOCK, (55, 35)) #s5 = WolfSprite(world_map, GRID_LOCK, (0, 35)) #s6 = BearSprite(world_map, GRID_LOCK) s7 = DeerSprite(world_map, GRID_LOCK) s8 = DeerSprite(world_map, GRID_LOCK) s9 = DeerSprite(world_map, GRID_LOCK) s10 = DeerSprite(world_map, GRID_LOCK) s11 = BearSprite(world_map, GRID_LOCK) s12 = BearSprite(world_map, GRID_LOCK) s13 = HareSprite(world_map, GRID_LOCK) s14 = HareSprite(world_map, GRID_LOCK) s15 = HareSprite(world_map, GRID_LOCK) #s16 = LynxSprite(world_map, GRID_LOCK) #s17 = LynxSprite(world_map, GRID_LOCK) #s18 = LynxSprite(world_map, GRID_LOCK) s19 = TickSprite(world_map, GRID_LOCK) s20 = TickSprite(world_map, GRID_LOCK) # s1.update() # s2.update() # s3.update() # s4.update() # s5.update() # s6.update() sprites = AllSpritesGroup([fish_group, bear_group, bees_group, wolf_group, deer_group, plant_group], s1, s2, s3, s4,s7, s9, s10, s11, s13, s14, s15, s19, s20) # sprites.add_to_correct_group(s4) # sprites.add_to_correct_group(s5) # sprites.add_to_correct_group(s6) # sprites.add_to_correct_group(s7) # sprites.add_to_correct_group(s8) # sprites.add_to_correct_group(s9) # sprites.add_to_correct_group(s10) # sprites.add_to_correct_group(s11) # sprites.add_to_correct_group(s12) # deer_group.update() # # fish_group.update() # bear_group.update() # bees_group.update() # wolf_group.update() # plant_group.update() # wolf_group.determine_pack_leader() sprites.update() # done = False while not done: for event in pygame.event.get(): # User did something if event.type == pygame.QUIT: # If user clicked close done = True sprite_test()
C++
UTF-8
16,429
2.625
3
[]
no_license
#ifndef __PCL_LIST_H__ #define __PCL_LIST_H__ #ifndef __PCL_H__ # error Do not include this file directly. Include "PCL.h" instead #endif ///! //*!===========================================================================! //*! PCL stands for Portable Class Library and is designed for development //*! of applications portable between different environments, //*! first of all between MS Windows and GNU Linux. //*! //*! CopyFree Pulse Computer Consulting, 2001 - 2011 //*! //*! CopyFree License Agreement: //*! 1.You may do with this code WHATEVER YOU LIKE. //*! 2.In NO CASE Pulse Computer Consulting is responsible for your results. //*! //*! E-mail: pulse.cc@mail.ru, pulse.cc@gmail.com //*!===========================================================================! ///! ///! ///! Virtual Iterator (Helper Class for navigation into Virtual Lists) ///! ///! Global Scope Definitions: ///! typedef enum PCL_Position { ZNullPosition = 0, ZHead, ZFirst = ZHead, ZTop = ZHead, ///! ZTail, ZLast = ZTail, ZBottom = ZTail, } ZPosition; ///! typedef enum PCL_Direction { ZNullDirection = 0, ZPrev, ZUp = ZPrev, ZBackward = ZPrev, ///! ZNext, ZDown = ZNext, ZForward = ZNext, } ZDirection; static const uint VIteratorClassCode = VIRTUALCODE(false); class VIterator { public: ///! ///! Public Methods ///! public: // List Navigation virtual void Reset() =0; // force to point to nothing virtual void SetTo(ZPosition Pos) =0; virtual bool SetToIndex(int Index) =0; // true if current position succesfully set // false if invalid index, current position remains unchanged virtual bool Move(ZDirection Dir) =0; // false if no more items in direction // List Access virtual void GetCurrent(pvoid *ppItem) const =0; // fills *ppItem with NULL if points to nothing virtual void Get(ZPosition Pos, pvoid *ppItem) const =0; // fills *ppItem with NULL if the list is emplty virtual void GetByIndex(int Index, pvoid *ppItem) const =0; // fills *ppItem with NULL if index is out of Count // List Information virtual uint Count() const =0; // returns number of items (0 for empty list) virtual uint ItemSize() const =0; // returns size of the current item virtual uint ItemSizeAt(ZPosition Pos) const =0; virtual uint ItemSizeByIndex(int Index) const =0; virtual bool IsValid() const =0; // true if currently points to data virtual bool IsAt(ZPosition Pos) const =0; // true if currently at specified position ///! ///! Public Operators ///! public: virtual pvoid operator ()() const =0; // operator form of GetCurrent virtual pvoid operator [](ZPosition Pos) const =0; // operator form of Get virtual pvoid operator [](int Index) const =0; // operator form of GetByIndex }; ///!===========================================================================! ///! ///! Virtual List (may be implemented as dynamic array or linked list or ...) ///! ///! Global Scope Definitions: ///! ///! Pointer to user-defined filter function typedef bool (*ZFilter)(pvoid pItem); // true if item match criterium ///! Pointer to user-defined sort ordering function typedef bool (*ZSortOrder)(pvoid pItem1, pvoid pItem2); // true if Greater ///! Special reference value indicating default (built-in) iterator static const VIterator *ZDefaultIterator = NULL; static const uint VListClassCode = VIRTUALCODE(true); class VList : public VContainer, public VIterator { public: ///! ///! CallBacks: ///! Methods to be Overrided in Descendant Classes (doing nothing by default) ///! protected: virtual void AfterInsert(pvoid pItem, uint ItemSize) =0; virtual void BeforeRemove(pvoid pItem, uint ItemSize) =0; ///! ///! Public Methods ///! public: // Iterator Management virtual VIterator& NewIterator(ZFilter pFilter = NULL) =0; virtual void DeleteIterator(const VIterator& Iter) =0; // Insert/Remove virtual void Insert(ZPosition Pos, pvoid pItem, uint ItemSize = 0) =0; virtual bool Remove(ZPosition Pos) =0; // false if list is empty virtual void RemoveAll() =0; // Reordering virtual void SwapWith( ZPosition Pos, const VIterator& Iter = *ZDefaultIterator ) =0; virtual void Swap( const VIterator& Iter1, const VIterator& Iter2 = *ZDefaultIterator ) =0; virtual void SortAsc(ZSortOrder Greater) =0; }; ///!===========================================================================! ///! ///! Definition of Generic Iterator & List ///! static const uint GIteratorClassCode = CLASSCODE(VIteratorClassCode); class PCL_API GIterator : public VIterator { public: static const uint ClassCode() {return GIteratorClassCode;}; protected: GIterator(); virtual ~GIterator(); protected: // Inheritable variables and methods VList *m_list; uint m_index; ZFilter m_pFilter; virtual bool _Move(ZDirection Dir); virtual pvoid _MoveToIndex(uint Index); virtual void _MoveValid(ZDirection Dir); GIterator(VList *List); ///! ///! Public Methods ///! public: // List Navigation virtual void Reset() ; // force to point to nothing virtual void SetTo(ZPosition Pos) ; virtual bool SetToIndex(int Index) ; // true if current position succesfully set // false if invalid index, current position remains unchanged virtual bool Move(ZDirection Dir) ; // false if no more items in direction // List Access virtual void GetCurrent(pvoid *ppItem) const ; // fills *ppItem with NULL if points to nothing virtual void Get(ZPosition Pos, pvoid *ppItem) const ; // fills *ppItem with NULL if the list is emplty virtual void GetByIndex(int Index, pvoid *ppItem) const ; // fills *ppItem with NULL if index is out of Count // List Information virtual uint Count() const ; // returns number of items (0 for empty list) virtual uint ItemSize() const ; // returns size of the current item virtual uint ItemSizeAt(ZPosition Pos) const ; virtual uint ItemSizeByIndex(int Index) const ; virtual bool IsValid() const ; // true if currently points to data virtual bool IsAt(ZPosition Pos) const ; // true if currently at specified position ///! ///! Public Operators ///! public: virtual pvoid operator ()() const ; // operator form of GetCurrent virtual pvoid operator [](ZPosition Pos) const ; // operator form of Get virtual pvoid operator [](int Index) const ; // operator form of GetByIndex // For implementation aids only void _IncIndex(); void _DecIndex(); void _SetFilter(ZFilter pFilter); }; static const uint GListClassCode = CLASSCODE(VListClassCode); class PCL_API GList : public VList { public: static const uint ClassCode() {return GListClassCode;}; protected: GList(); virtual ~GList(); GList(const pcont pContainer); virtual void Import(const pcont pContainer, bool AutoRelease = true); virtual const pcont Export(void); protected: // Inheritable variables and methods pvoid m_head, m_last; uint m_itemSize, m_count, m_iterCount; VIterator **m_pIter; // Iterator Vector, m_pIter[0] points to default virtual VIterator * _CreateIterator(ZFilter pFilter); virtual void _RemoveIterator(VIterator * pIter); virtual uint _FindIterator(const VIterator& Iter); virtual void _InternalSwap(pvoid pItem1, pvoid pItem2); ///! ///! CallBacks: ///! Methods to be Overrided in Descendant Classes (doing nothing by default) ///! protected: virtual void AfterInsert(pvoid pItem, uint ItemSize) ; virtual void BeforeRemove(pvoid pItem, uint ItemSize) ; ///! ///! Public Methods ///! public: // Iterator Management virtual VIterator& NewIterator(ZFilter pFilter = NULL) ; virtual void DeleteIterator(const VIterator& Iter) ; // Insert/Remove virtual void Insert(ZPosition Pos, pvoid pItem, uint ItemSize = 0) ; virtual bool Remove(ZPosition Pos) ; // false if list is empty virtual void RemoveAll() ; // Reordering virtual void SwapWith( ZPosition Pos, const VIterator& Iter = *ZDefaultIterator ) ; virtual void Swap( const VIterator& Iter1, const VIterator& Iter2 = *ZDefaultIterator ) ; virtual void SortAsc(ZSortOrder Greater) ; ///! ///! Public Methods ///! public: // List Navigation virtual void Reset() ; // force to point to nothing virtual void SetTo(ZPosition Pos) ; virtual bool SetToIndex(int Index) ; // true if current position succesfully set // false if invalid index, current position remains unchanged virtual bool Move(ZDirection Dir) ; // false if no more items in direction // List Access virtual void GetCurrent(pvoid *ppItem) const ; // fills *ppItem with NULL if points to nothing virtual void Get(ZPosition Pos, pvoid *ppItem) const ; // fills *ppItem with NULL if the list is emplty virtual void GetByIndex(int Index, pvoid *ppItem) const ; // fills *ppItem with NULL if index is out of Count // List Information virtual uint Count() const ; // returns number of items (0 for empty list) virtual uint ItemSize() const ; // returns size of the current item virtual uint ItemSizeAt(ZPosition Pos) const ; virtual uint ItemSizeByIndex(int Index) const ; virtual bool IsValid() const ; // true if currently points to data virtual bool IsAt(ZPosition Pos) const ; // true if currently at specified position ///! ///! Public Operators ///! public: virtual pvoid operator ()() const ; // operator form of GetCurrent virtual pvoid operator [](ZPosition Pos) const ; // operator form of Get virtual pvoid operator [](int Index) const ; // operator form of GetByIndex }; ///!===========================================================================! ///! ///! Definition of Iterators & Lists ///! static const uint LListIteratorClassCode = CLASSCODE(GIteratorClassCode); class PCL_API LListIterator : public GIterator { public: static const uint ClassCode() {return LListIteratorClassCode;}; public: friend class LList; protected: LListIterator(LList *List); virtual void Reset(); // force to point to nothing virtual void SetTo(ZPosition Pos); virtual bool SetToIndex(int Index /*zero based*/); virtual void GetCurrent(pvoid *ppItem) const; virtual pvoid operator ()() const; // operator form of GetCurrent virtual pvoid operator [](ZPosition Pos) const; // operator form of Get virtual pvoid operator [](int Index) const; // operator form of GetByIndex pvoid m_current; virtual void _MoveValid(ZDirection Dir); virtual pvoid _MoveToIndex(uint Index); }; static const uint LVectorIteratorClassCode = CLASSCODE(GIteratorClassCode); class PCL_API LVectorIterator : public GIterator { public: static const uint ClassCode() {return LVectorIteratorClassCode;}; public: friend class LVector; protected: LVectorIterator(LVector *Vector); virtual void SetTo(ZPosition Pos); virtual void GetCurrent(pvoid *ppItem) const; virtual pvoid operator ()() const; // operator form of GetCurrent virtual pvoid _MoveToIndex(uint Index); }; static const uint LCollectionIteratorClassCode = CLASSCODE(GIteratorClassCode); class PCL_API LCollectionIterator : public GIterator { public: static const uint ClassCode() {return LCollectionIteratorClassCode;}; public: friend class LCollection; protected: LCollectionIterator(LCollection *Collection); ~LCollectionIterator(); virtual void Reset(); // force to point to nothing virtual void SetTo(ZPosition Pos); virtual bool SetToIndex(int Index); virtual bool Move(ZDirection Dir); // List Access virtual void GetCurrent(pvoid *ppItem) const; virtual pvoid operator ()() const; // operator form of GetCurrent virtual void Get(ZPosition Pos, pvoid *ppItem) const; virtual pvoid operator [](ZPosition Pos) const; virtual void GetByIndex(int Index, pvoid *ppItem) const; virtual pvoid operator [](int Index) const; // List Information virtual uint Count() const; virtual uint ItemSize() const; // returns size of the current item virtual uint ItemSizeAt(ZPosition Pos) const; virtual uint ItemSizeByIndex(int Index) const; virtual bool IsValid() const; // true if currently points to data virtual bool IsAt(ZPosition Pos) const; private: VIterator &Iter; }; static const uint LListClassCode = CLASSCODE(GListClassCode); class PCL_API LList : public GList { public: static const uint ClassCode() {return LListClassCode;}; public: LList(const pcont pContainer); virtual void Import(const pcont pContainer, bool AutoRelease = true); virtual const pcont Export(void); public: LList(uint ItemSize); virtual ~LList(); // Insert/Remove virtual void Insert(ZPosition Pos, pvoid pItem, uint ItemSize = 0); virtual bool Remove(ZPosition Pos); // false if list is empty virtual void RemoveAll(); // Inheritable variables and methods protected: virtual VIterator * _CreateIterator(ZFilter pFilter); virtual void _RemoveIterator(VIterator * pIter); }; typedef struct PCL_ListHeader { PCL_ListHeader * pNext; PCL_ListHeader * pPrev; } ZListHeader, *pZListHeader; static const uint LVectorClassCode = CLASSCODE(GListClassCode); class PCL_API LVector : public GList { public: static const uint ClassCode() {return LVectorClassCode;}; public: LVector(const pcont pContainer); virtual void Import(const pcont pContainer, bool AutoRelease = true); virtual const pcont Export(void); public: LVector(uint ItemSize); virtual ~LVector(); // Insert/Remove virtual void Insert(ZPosition Pos, pvoid pItem, uint ItemSize = 0); virtual bool Remove(ZPosition Pos); // false if list is empty virtual void RemoveAll(); // Inheritable variables and methods virtual void CollectGarbage(); // make Realloc() to force m_allocCount == m_count protected: virtual VIterator * _CreateIterator(ZFilter pFilter); virtual void _RemoveIterator(VIterator * pIter); inline uint BlockCount() {return 16;}; uint m_allocCount; }; typedef struct PCL_CollectionHeader { uint itemSize; LMemory *pMem; } ZCollectionHeader, *pZCollectionHeader; class PCL_API _WCollectionHeader : public LVector { public: _WCollectionHeader(); ~_WCollectionHeader(); void AfterInsert(pvoid pItem, uint ItemSize); void BeforeRemove(pvoid pItem, uint ItemSize); pvoid m_pItem; uint m_itemSize; LException *m_pDbg; }; static const uint LCollectionClassCode = CLASSCODE(GListClassCode); class PCL_API LCollection : public GList { public: static const uint ClassCode() {return LCollectionClassCode;}; public: LCollection(const pcont pContainer); virtual void Import(const pcont pContainer, bool AutoRelease = true); virtual const pcont Export(void); public: friend class LCollectionIterator; LCollection(); virtual ~LCollection(); // Iterator Management virtual VIterator& NewIterator(ZFilter pFilter); virtual void DeleteIterator(const VIterator& Iter); // Insert/Remove virtual void Insert(ZPosition Pos, pvoid pItem, uint ItemSize); virtual bool Remove(ZPosition Pos); // false if list is empty virtual void RemoveAll(); // Reordering virtual void SwapWith( ZPosition Pos, const VIterator& Iter = *ZDefaultIterator ); virtual void Swap( const VIterator& Iter1, const VIterator& Iter2 = *ZDefaultIterator ); virtual void SortAsc(ZSortOrder Greater); /* // List Navigation virtual void Reset(); // force to point to nothing virtual void SetTo(ZPosition Pos); virtual bool SetToIndex(int Index); virtual bool Move(ZDirection Dir); */ // List Access virtual void GetCurrent(pvoid *ppItem) const; virtual pvoid operator ()() const; // operator form of GetCurrent virtual void Get(ZPosition Pos, pvoid *ppItem) const; virtual pvoid operator [](ZPosition Pos) const; virtual void GetByIndex(int Index, pvoid *ppItem) const; virtual pvoid operator [](int Index) const; // List Information virtual uint Count() const; virtual uint ItemSize() const; // returns size of the current item // virtual bool IsValid() const; // true if currently points to data // virtual bool IsAt(ZPosition Pos) const; virtual uint ItemSizeByIndex(int Index) const; virtual uint ItemSizeAt(ZPosition Pos) const; // Collection-specific method virtual void SetItemSize( uint NewSize, const VIterator& Iter = *ZDefaultIterator ); // // Inheritable variables and methods protected: virtual VIterator * _CreateIterator(ZFilter pFilter = NULL); virtual void _RemoveIterator(VIterator * pIter); private: _WCollectionHeader m_cHdr; }; #endif // __PCL_LIST_H__
Java
UTF-8
441
2.390625
2
[]
no_license
package cn.wsg.oj.leetcode.problems.p1600; import cn.wsg.oj.leetcode.problems.base.Solution; /** * 1691. Maximum Height by Stacking Cuboids (HARD) * * @author Kingen * @see <a href="https://leetcode-cn.com/problems/maximum-height-by-stacking-cuboids/">Maximum * Height by Stacking Cuboids </a> */ public class Solution1691 implements Solution { public int maxHeight(int[][] cuboids) { // todo return 0; } }
Java
UTF-8
1,255
2.28125
2
[ "Apache-2.0" ]
permissive
/** * Copyright 2019 The JoyQueue Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.joyqueue.server.retry.util; /** * 重试工具类 * * Created by chengzhiliang on 2019/2/10. */ public class RetryUtil { /** * 生成消息Id * * @param topic 消息主题 * @param partition 分区 * @param index 消息序号 * @return 消息ID */ public static String generateMessageId(String topic, short partition, long index,long sendTime) { StringBuilder sb = new StringBuilder(); sb.append(topic); sb.append('-').append(partition); sb.append('-').append(index); sb.append('-').append(sendTime); return sb.toString(); } }
Java
UTF-8
19,003
1.539063
2
[]
no_license
/* * Copyright (c) 2005-2011 Grameen Foundation USA * 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. * * See also http://www.apache.org/licenses/LICENSE-2.0.html for an * explanation of the license and how it is applied. */ package org.mifos.androidclient.main; import android.app.DatePickerDialog; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.provider.ContactsContract; import android.text.InputType; import android.view.View; import android.widget.*; import org.mifos.androidclient.R; import org.mifos.androidclient.entities.account.AcceptedPaymentTypes; import org.mifos.androidclient.entities.collectionsheet.*; import org.mifos.androidclient.entities.customer.LoanOfficerData; import org.mifos.androidclient.entities.simple.AbstractCustomer; import org.mifos.androidclient.entities.simple.Center; import org.mifos.androidclient.main.views.adapters.CollectionSheetExpandableListAdapter; import org.mifos.androidclient.net.services.CollectionSheetService; import org.mifos.androidclient.net.services.CustomerService; import org.mifos.androidclient.net.services.SystemSettingsService; import org.mifos.androidclient.templates.DownloaderActivity; import org.mifos.androidclient.templates.ServiceConnectivityTask; import org.mifos.androidclient.util.ListMeasuringUtils; import org.springframework.web.client.RestClientException; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.*; public class CollectionSheetActivity extends DownloaderActivity implements DatePickerDialog.OnDateSetListener, View.OnFocusChangeListener, ExpandableListView.OnChildClickListener, AdapterView.OnItemLongClickListener{ private static final int DATE_DIALOG_ID = 0; private Center mCenter; private CollectionSheetData mCollectionSheetData; private ExpandableListView mCollectionSheetList; private CollectionSheetService mCollectionSheetService; private CollectionSheetTask mCollectionSheetTask; private AcceptedPaymentTypes mAcceptedPaymentTypes; private SystemSettingsService mSystemSettingsService; private Map<String, Integer> mTransactionTypes; private EditText dateField; private EditText receiptID; private Spinner typesSpinner; private CustomerService mCustomerService; private LoanOfficerData mLoanOfficer; private SaveCollectionSheet mSaveCustomer = new SaveCollectionSheet(); private List<CollectionSheetCustomer> mCustomerList; private CollectionSheetCustomer mSelectedCustomer; @Override public void onCreate(Bundle bundle) { super.onCreate(bundle); setContentView(R.layout.collection_sheet); mCenter = (Center)getIntent().getSerializableExtra((AbstractCustomer.BUNDLE_KEY)); mCustomerService = new CustomerService(this); mCollectionSheetService = new CollectionSheetService(this); mSystemSettingsService = new SystemSettingsService(this); mCollectionSheetList = (ExpandableListView)findViewById(R.id.collectionSheet_entries); receiptID = (EditText)findViewById(R.id.collectionSheet_formField_receiptId); receiptID.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL); dateField = (EditText)findViewById(R.id.collectionSheet_formField_receiptDate); dateField.setInputType(InputType.TYPE_NULL); dateField.setOnFocusChangeListener(this); } public void onApplyCollectionSheet(View view) { CollectionSheetHolder.setSaveCollectionSheet(mSaveCustomer); Intent intent = new Intent().setClass(this, ApplyCollectionSheetActivity.class); startActivity(intent); } @Override protected void onDestroy() { super.onDestroy(); if (mCollectionSheetTask != null) { mCollectionSheetTask.terminate(); mCollectionSheetTask = null; } } @Override protected void onSessionActive() { super.onSessionActive(); if (mCollectionSheetData == null || mAcceptedPaymentTypes == null) { runCollectionSheetTask(); } } private void runCollectionSheetTask() { if (mCenter != null) { if (mCollectionSheetTask == null || mCollectionSheetTask.getStatus() != AsyncTask.Status.RUNNING) { mCollectionSheetTask = new CollectionSheetTask( this, getString(R.string.dialog_loading_message), getString(R.string.collectionSheet_loadingText) ); mCollectionSheetTask.execute(mCenter.getId()); } } } @Override public void onDateSet(DatePicker datePicker, int year, int monthOfYear, int dayOfMonth) { StringBuilder builder = new StringBuilder() .append(String.format("%02d", dayOfMonth)).append("-") .append(String.format("%02d", monthOfYear + 1)).append("-") .append(year); dateField.setText(builder.toString()); } public void onDateFieldClicked(View view) { dateFieldEdit(view); } @Override public void onFocusChange(View view, boolean hasFocus) { if (hasFocus) { dateFieldEdit(view); } } public void dateFieldEdit(View view) { dateField = (EditText)view; showDialog(DATE_DIALOG_ID); } @Override protected Dialog onCreateDialog(int id) { Dialog dialog; switch (id) { case DATE_DIALOG_ID: Calendar today = Calendar.getInstance(); return new DatePickerDialog( this, this, today.get(Calendar.YEAR), today.get(Calendar.MONTH), today.get(Calendar.DAY_OF_MONTH) ); default: dialog = null; } return dialog; } private void updateContent(CollectionSheetData collectionSheet){ LinearLayout linearLayout; if(collectionSheet != null) { mCollectionSheetData = collectionSheet; if(CollectionSheetHolder.getCollectionSheetData() == null){ mCollectionSheetData = collectionSheet; } else { mCollectionSheetData = CollectionSheetHolder.getCollectionSheetData(); } mSelectedCustomer = CollectionSheetHolder.getCurrentCustomer(); if(mSelectedCustomer !=null){ List<CollectionSheetCustomer> tmpCustomer = collectionSheet.getCollectionSheetCustomer(); for(CollectionSheetCustomer customer : tmpCustomer) { if(customer.getName().equalsIgnoreCase(mSelectedCustomer.getName())) { tmpCustomer.set(tmpCustomer.indexOf(customer), mSelectedCustomer); } } } EditText editText; linearLayout = (LinearLayout)findViewById(R.id.collectionSheet_formFields); linearLayout.clearFocus(); editText = (EditText)linearLayout.findViewById(R.id.collectionSheet_formField_transactionDate); editText.setInputType(InputType.TYPE_NULL); DateFormat df = new SimpleDateFormat("dd-MM-yyyy"); editText.setText(df.format(mCollectionSheetData.getDate()).toString()); editText.setEnabled(false); LinearLayout layout = (LinearLayout)findViewById(R.id.collectionSheet_entriesWrapper); layout.requestFocus(); if(collectionSheet.getCollectionSheetCustomer() != null && collectionSheet.getCollectionSheetCustomer().size() > 0) { ExpandableListView expandableListView = (ExpandableListView)findViewById(R.id.collectionSheet_entries); CollectionSheetExpandableListAdapter adapter = new CollectionSheetExpandableListAdapter(collectionSheet,this); expandableListView.setAdapter(adapter); ListMeasuringUtils.setListViewHeightBasedOnChildren(expandableListView); expandableListView.setOnItemLongClickListener(this); expandableListView.setOnChildClickListener(this); mLoanOfficer = mCustomerService.getCurrentOfficer(); mSaveCustomer.setUserId(mLoanOfficer.getId()); mSaveCustomer.setPaymentType((short)1); mSaveCustomer.setReceiptId(receiptID.getText().toString()); mSaveCustomer.setTransactionDate(mCollectionSheetData.getDate()); try { mSaveCustomer.setReceiptDate(df.parse(dateField.getText().toString())); } catch (ParseException e) { e.printStackTrace(); } ArrayList<SaveCollectionSheetCustomer> saveCollectionSheetCustomers = new ArrayList<SaveCollectionSheetCustomer>(); prepareSaveCollectionSheet(saveCollectionSheetCustomers); mSaveCustomer.setSaveCollectionSheetCustomers(saveCollectionSheetCustomers); } } mTransactionTypes = mAcceptedPaymentTypes.allTypes(); linearLayout = (LinearLayout)findViewById(R.id.collectionSheet_formFields); typesSpinner = (Spinner)linearLayout.findViewById(R.id.collectionSheet_spinner_paymentTypes); Object[] list = mTransactionTypes.keySet().toArray(); typesSpinner.setAdapter(new ArrayAdapter(this, R.layout.combo_box_item, list)); double dueCollections = 0.0; double otherCollections = 0.0; double loanDisbursements = 0.0; double withdrawals = 0.0; List<CollectionSheetCustomer> customer = mCollectionSheetData.getCollectionSheetCustomer(); mCustomerList = customer; for(CollectionSheetCustomer cst: customer) { CollectionSheetCustomerAccount accounts = cst.getCollectionSheetCustomerAccount(); otherCollections += accounts.getTotalCustomerAccountCollectionFee(); if(cst.getCollectionSheetCustomerLoan().size() > 0 && cst.getCollectionSheetCustomerLoan() != null) { List<CollectionSheetCustomerLoan> loans = cst.getCollectionSheetCustomerLoan(); for(CollectionSheetCustomerLoan loan : loans) { dueCollections += loan.getTotalRepaymentDue(); loanDisbursements += loan.getTotalDisbursement(); } } if(cst.getCollectionSheetCustomerSaving() != null && cst.getCollectionSheetCustomerSaving().size() > 0){ List<CollectionSheetCustomerSavings> savings = cst.getCollectionSheetCustomerSaving(); for(CollectionSheetCustomerSavings saving :savings) { dueCollections += saving.getTotalDepositAmount(); } } if(cst.getIndividualSavingAccounts() != null && cst.getIndividualSavingAccounts().size() > 0) { List<CollectionSheetCustomerSavings> individuals = cst.getIndividualSavingAccounts(); for(CollectionSheetCustomerSavings individual : individuals) { dueCollections += individual.getTotalDepositAmount(); } } } TextView textView = (TextView)findViewById(R.id.collectionSheet_dueCollections); textView.setText(String.format("%.1f", dueCollections)); textView = (TextView)findViewById(R.id.collectionSheet_otherCollections); textView.setText(String.format("%.1f", otherCollections)); textView = (TextView)findViewById(R.id.collectionSheet_collectionsTotal); textView.setText(String.format("%.1f", (otherCollections + dueCollections))); textView = (TextView)findViewById(R.id.collectionSheet_loanDisbursements); textView.setText(String.format("%.1f", (loanDisbursements))); textView = (TextView)findViewById(R.id.collectionSheet_withdrawals); textView.setText(String.format("%.1f", (withdrawals))); textView = (TextView)findViewById(R.id.collectionSheet_issuesWithdrawalsTotal); textView.setText(String.format("%.1f", (withdrawals + loanDisbursements))); textView = (TextView)findViewById(R.id.collectionSheet_netCash); textView.setText(String.format("%.1f", (dueCollections + otherCollections - loanDisbursements))); } private int getSelectedFee(){ mTransactionTypes = mAcceptedPaymentTypes.allTypes(); return 1; } @Override public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long rowId) { CollectionSheetCustomer group = (CollectionSheetCustomer)adapterView.getAdapter().getItem(position); CollectionSheetHolder.setCurrentCustomer(group); Intent intent = new Intent().setClass(this, CollectionSheetCustomerActivity.class); intent.putExtra(CollectionSheetCustomer.BUNDLE_KEY, group); startActivity(intent); return true; } @Override public boolean onChildClick(ExpandableListView parent, View view, int groupPos, int childPos, long id) { CollectionSheetCustomer customer = (CollectionSheetCustomer)parent.getExpandableListAdapter().getChild(groupPos,childPos); CollectionSheetHolder.setCurrentCustomer(customer); Intent intent = new Intent().setClass(this, CollectionSheetCustomerActivity.class); intent.putExtra(CollectionSheetCustomer.BUNDLE_KEY, customer); startActivity(intent); return true; } private class CollectionSheetTask extends ServiceConnectivityTask<Integer,Void,CollectionSheetData> { public CollectionSheetTask(Context context, String progressTitle, String progressMessage) { super(context, progressTitle, progressMessage); } @Override protected CollectionSheetData doInBackgroundBody(Integer... params) throws RestClientException, IllegalArgumentException { CollectionSheetData collectionSheet = null; mAcceptedPaymentTypes = mSystemSettingsService.getAcceptedPaymentTypes(); if (mCollectionSheetService != null) { collectionSheet = mCollectionSheetService.getCollectionSheetForCustomer(params[0]); } return collectionSheet; } @Override protected void onPostExecuteBody(CollectionSheetData collectionSheetData) { updateContent(collectionSheetData); } } private void prepareSaveCollectionSheet(ArrayList<SaveCollectionSheetCustomer> saveCollectionSheetCustomers) { for(CollectionSheetCustomer data : mCollectionSheetData.getCollectionSheetCustomer()) { SaveCollectionSheetCustomer saveCollection = new SaveCollectionSheetCustomer(); if (data.getLevelId() ==1) { saveCollection.setAttendanceId((short)1); } saveCollection.setCustomerId(data.getCustomerId()); saveCollection.setParentCustomerId(data.getParentCustomerId()); SaveCollectionSheetCustomerAccount saveAccount = new SaveCollectionSheetCustomerAccount(); saveAccount.setAccountId(data.getCollectionSheetCustomerAccount().getAccountId()); saveAccount.setCurrencyId(data.getCollectionSheetCustomerAccount().getCurrencyId()); saveAccount.setTotalCustomerAccountCollectionFee(data.getCollectionSheetCustomerAccount().getTotalCustomerAccountCollectionFee()); saveCollection.setSaveCollectionSheetCustomerAccount(saveAccount); ArrayList<SaveCollectionSheetCustomerLoan> loan = new ArrayList<SaveCollectionSheetCustomerLoan>(); ArrayList<SaveCollectionSheetCustomerSaving> saving = new ArrayList<SaveCollectionSheetCustomerSaving>(); ArrayList<SaveCollectionSheetCustomerSaving> individual = new ArrayList<SaveCollectionSheetCustomerSaving>(); for (CollectionSheetCustomerLoan loans : data.getCollectionSheetCustomerLoan()){ SaveCollectionSheetCustomerLoan saveLoan = new SaveCollectionSheetCustomerLoan(); saveLoan.setAccountId(loans.getAccountId()); saveLoan.setCurrencyId(loans.getCurrencyId()); saveLoan.setTotalDisbursement(loans.getTotalDisbursement()); saveLoan.setTotalLoanPayment(loans.getTotalRepaymentDue()); loan.add(saveLoan); } for (CollectionSheetCustomerSavings savings : data.getCollectionSheetCustomerSaving()) { SaveCollectionSheetCustomerSaving saveSaving = new SaveCollectionSheetCustomerSaving(); saveSaving.setAccountId(savings.getAccountId()); saveSaving.setCurrencyId(savings.getCurrencyId()); saveSaving.setTotalDeposit(savings.getTotalDepositAmount()); saveSaving.setTotalWithdrawal(0.0); saving.add(saveSaving); } for (CollectionSheetCustomerSavings individuals : data.getIndividualSavingAccounts()) { SaveCollectionSheetCustomerSaving saveIndividual = new SaveCollectionSheetCustomerSaving(); saveIndividual.setAccountId(individuals.getAccountId()); saveIndividual.setCurrencyId(individuals.getCurrencyId()); saveIndividual.setTotalDeposit(individuals.getTotalDepositAmount()); saveIndividual.setTotalWithdrawal(0.0); individual.add(saveIndividual); } saveCollection.setSaveCollectionSheetCustomerLoans(loan); saveCollection.setSaveCollectionSheetCustomerSavings(saving); saveCollection.setSaveCollectionSheetCustomerIndividualSavings(individual); saveCollectionSheetCustomers.add(saveCollection); } } }
JavaScript
UTF-8
2,899
2.546875
3
[ "MIT" ]
permissive
/** * Implement Gatsby's Node APIs in this file. * * See: https://www.gatsbyjs.org/docs/node-apis/ */ // You can delete this file if you're not using it // exports.onCreateNode = ({ node, getNode }) => { // // console.log('node -> ', node); // const fileNode = getNode(node.parent) // if (fileNode) // console.log(`\nfile ->`, fileNode.relativePath) // console.log(`--------------`) // }; // exports.onCreatePage = ({ page }) => { // console.log('page -> ', page); // }; const crypto = require('crypto') exports.sourceNodes = ({ boundActionCreators }) => { const { createNode } = boundActionCreators const posts = [{ title: 'stuffs', privilege: 'private', content: 'my private post' }, { title: 'public stuffs', content: 'my public post' }] posts.forEach(post => createNode({ id: post.title.replace(/ /g, '-'), title: post.title, privilege: post.privilege, parent: null, children: [], internal: { type: `post`, contentDigest: crypto .createHash(`md5`) .update(JSON.stringify(post.content)) .digest(`hex`), mediaType: `text/markdown`, content: JSON.stringify(post.content) } })) } exports.createPages = ({ graphql, boundActionCreators }) => { const { createPage } = boundActionCreators; return new Promise((resolve, reject) => { graphql(` { allPost { edges { node { id, title, privilege, internal { content } } } } } `).then(result => { const pagesByPrivileges = result.data.allPost.edges.reduce((priv, post) => { const privilege = post.node.privilege || 'public' priv[privilege] = priv[privilege] || [] priv[privilege].push(post) return priv }, {}) const path = require('path') Object.entries(pagesByPrivileges).forEach(([priv, posts]) => { // Create index page createPage({ path: `${priv}/index`, component: path.resolve(`./src/templates/index.js`), context: { // Data passed to context is available in page queries as GraphQL variables. slug: `${priv}/index`, title: `my ${priv} posts`, posts }, }) posts.forEach(({ node }) => { createPage({ path: `${priv}/${node.id}`, component: path.resolve(`./src/templates/post.js`), context: { // Data passed to context is available in page queries as GraphQL variables. slug: `${priv}/${node.id}`, index: `${priv}/index`, title: node.title, content: node.internal.content }, }) }) }) resolve() }) }) }
Java
UTF-8
874
4
4
[]
no_license
package com.java.learning.leetcode.problems.sortlist.maximumgap; import java.util.Arrays; /** * https://leetcode-cn.com/problems/maximum-gap/ * 给定一个无序的数组,找出数组在排序之后,相邻元素之间最大的差值。 * <p> * 如果数组元素个数小于 2,则返回 0。 */ public class Solution1 { public int maximumGap(int[] nums) { int length = nums.length; if (length < 2) return 0; //如果长度大于2 开辟个新数组存放排序后的索引 Arrays.sort(nums); //对数组进行排序——--这里交换的是index的元素 int min = 0; for (int i = 0; i < length - 1; i++) { if (Math.abs(nums[i] - nums[i + 1]) > min) { min = Math.abs(nums[i] - nums[i + 1]); } } return min; } }
JavaScript
UTF-8
20,088
2.625
3
[]
no_license
// Core JQuery and Angular file // Global variables var geolocation; // Location based on the user's IP address var allCurrInfo; // The current JSON data returned by the Ticketmaster API var months = {"1": "January", "2": "February", "3": "March", "4": "April", "5": "May", "6": "June", "7": "July", "8": "August", "9": "September", "10": "October", "11": "November", "12": "December"}; var myStorage = window.localStorage; function pageLoaded() { $("#search").attr("disabled", true); $("#favBtn").attr("disabled", true); $.get("https://ipinfo.io/json?token=e12792029dfd7b", function(output) { geolocation = output.loc.split(",") }); } $(document).ready(function() { // Validate when the user clicks out of the input form $("#keyword").focusout(function() { var inputVal = $(this).val(); if(!inputVal.replace(/ /g, '') || /^[a-zA-Z0-9- ]*$/.test(inputVal) == false) { $("#firstValidate").css({"visibility": "visible"}); $("#keyword").css({"border-color": "red"}); } }); // Reset error message if applicable when something is entered into the input form $("#keyword").on('input', function() { $("#firstValidate").css({"visibility": "hidden"}); $("#keyword").css({"border-color": "#cdd4db"}); }); // Activate the location text box if the "Other" radio button is checked $(".locButton").click(function() { if($("#other-loc:checked").val() == "on") { $("#other-input").prop("disabled", false); } else if($("#curr-loc:checked").val() == "on") { $("#other-input").prop("disabled", true); $("#secondValidate").css({"visibility": "hidden"}); $("#other-input").css({"border-color": "#cdd4db"}); } }); // Validate the location input when the user clicks out of it $("#other-input").focusout(function() { var inputVal = $(this).val(); if(!inputVal.replace(/ /g, '') || /^[a-zA-Z0-9- ]*$/.test(inputVal) == false) { $("#secondValidate").css({"visibility": "visible"}); $("#other-input").css({"border-color": "red"}); } }); // Reset the error message for the location input form, or when the other button is checked $("#other-input").on('input', function() { $("#secondValidate").css({"visibility": "hidden"}); $("#other-input").css({"border-color": "#cdd4db"}); }); // Enable the search button if all the required information has been added to the form $("form :input").change(function() { if($("#keyword").val() && ($("#curr-loc:checked").val() == "on" || $("#other-input").val())) { $("#search").attr("disabled", false); } else { $("#search").attr("disabled", true); } }); // Clear the form and the results $("#clear").click(function() { $("#details-table").html(""); $("#results-table").html(""); $("#details-table").hide(); $("#results-table").hide(); $("#fav-results-table").hide(); $("#fav-details-table").hide(); $("#keyword").val(""); $("#categoryList").prop("selectedIndex",0); $("#distance").val(""); $("#unit-list").prop("selectedIndex",0); $("#curr-loc").prop("checked", true); $("#other-loc").prop("checked", false); $("#other-input").val(""); $("#other-input").prop("disabled", true); }); // Get results after clicking the search button $("#search").click(function() { $("#details-table").html(""); $("#results-table").html('<div class="progress"><div class="progress-bar progress-bar-striped" role="progressbar" style="width: 50%" aria-valuenow="50" aria-valuemin="0" aria-valuemax="100"></div></div>'); $("#details-table").hide(); $("#results-table").show(); var keyword = $("#keyword").val(); var category = $("#categoryList option:selected").val(); var distance = $("#distance").val(); if (distance == "") { distance = "10"; } var distUnit = $("#unit-list option:selected").val(); var lat = geolocation[0]; var lng = geolocation[1]; if ($("#other-loc:checked").val() == "on") { var geoUrl = "https://maps.googleapis.com/maps/api/geocode/json?address="; var locAddress = $("#other-input").val(); var locAddress = locAddress.replace(/\s+/g,'+'); jQuery.ajaxSetup({async:false}); geoUrl += locAddress + "&key=AIzaSyBBhJ4BGqKrObAIHsXPzhuTYTs9FUvL2g8"; $.ajax({ url: geoUrl, type: "get", async: false, success: function(data) { if (data.status == "OK") { lat = data.results[0].geometry.location.lat; lng = data.results[0].geometry.location.lng; } }, error: function() { console.log("ERROR"); } }); } // Call Ticketmaster API and process data var parameters = {"keyword":keyword, "category":category, "distance":distance, "distUnit":distUnit, "lat":lat, "lng":lng}; $.get('/searchEvents', parameters, function(data) { if (data == "ERROR") { // Failed to get search result let errorHTML = '<form class="col-lg-9 col-md-9 col-sm-10 rounded" id="error_form">Failed to get search results.</form>' $("#results-table").html(errorHTML); } else if (data == "EMPTY") { // No records available let emptyHTML = '<form class="col-lg-9 col-md-9 col-sm-10 rounded" id="no_records">No records.</form>'; $("#results-table").html(emptyHTML); } else { // Call the Spotify API for (var key1 in data) { for (var key2 in data[key1]["artists"]) { $.ajax({ url: '/getArtistInfo', type: "get", data: { artist: data[key1]["artists"][key2] }, async: false, success: function(response) { data[key1]["artistInfo"].push(response); }, error: function() { console.log("ERROR: Spotify API"); } }); } } // Process and display the data allCurrInfo = data; allCurrInfo.sort((a, b) => parseInt(a["date"].replace(/-/g, '')) - parseInt(b["date"].replace(/-/g, ''))); var tableHTML = '<p id="detailsText" style="text-align: right; font-size: 12px">Details <svg xmlns="http://www.w3.org/2000/svg" height="12px" viewBox="0 0 18 18" width="12px" fill="darkgray"><path d="M0 0h24v24H0z" fill="none"/><path d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"/></svg></p>'; tableHTML += '<table class="table"><thead><tr><th style="border-bottom: 2px solid black;" class = "top-row" scope="col">#</th><th style="border-bottom: 2px solid black;" class = "top-row" scope="col">Date</th><th style="border-bottom: 2px solid black;" class = "top-row" scope="col">Event</th><th style="border-bottom: 2px solid black;" class = "top-row" scope="col">Category</th><th style="border-bottom: 2px solid black;" class = "top-row" scope="col">Venue Info</th><th style="border-bottom: 2px solid black;" class = "top-row" scope="col">Favorite</th></tr></thead><tbody>'; for (var i = 0; i < 20 && i < allCurrInfo.length; i++) { tableHTML += '<tr><th scope="row">' + (i + 1) + '</th><td>'; tableHTML += allCurrInfo[i]["date"] + '</td><td>'; // Check if the event name is too long eventName = allCurrInfo[i]["event"]; if (eventName.length > 35) { eventName = eventName.slice(0, 35); if (eventName.endsWith(" ")) { eventName = eventName.slice(0, 34); } eventName += "..."; } tableHTML += '<a onclick="createDetails(' + i + ')" href="javascript:void(0);">' + eventName + '</a></td><td>'; tableHTML += allCurrInfo[i]["category"] + '</td><td>'; tableHTML += allCurrInfo[i]["venue"] + '</td><td class="notFavorited stars">'; var starIcon = '<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 0 24 24" width="24px" fill="#000000"><path d="M22 9.24l-7.19-.62L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21 12 17.27 18.18 21l-1.63-7.03L22 9.24zM12 15.4l-3.76 2.27 1-4.28-3.32-2.88 4.38-.38L12 6.1l1.71 4.04 4.38.38-3.32 2.88 1 4.28L12 15.4z"/></svg>'; // Check if the event is in Favorites tableHTML += starIcon + '</td></tr>'; } tableHTML += '</tbody></table>'; $("#results-table").html(tableHTML); $("#favBtn").attr("disabled", false); $(".stars").click(function() { if ($(this).attr("class") == "notFavorited stars") { $(this).html('<svg xmlns="http://www.w3.org/2000/svg" enable-background="new 0 0 24 24" height="24px" viewBox="0 0 24 24" width="24px" fill="#FFD900"><g><rect fill="none" height="24" width="24" x="0"/><polygon points="14.43,10 12,2 9.57,10 2,10 8.18,14.41 5.83,22 12,17.31 18.18,22 15.83,14.41 22,10"/></g></svg>'); $(this).attr("class", "favorited stars"); addFav(); } else { $(this).html('<svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 0 24 24" width="24px" fill="#000000"><path d="M22 9.24l-7.19-.62L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21 12 17.27 18.18 21l-1.63-7.03L22 9.24zM12 15.4l-3.76 2.27 1-4.28-3.32-2.88 4.38-.38L12 6.1l1.71 4.04 4.38.38-3.32 2.88 1 4.28L12 15.4z"/></svg>'); $(this).attr("class", "notFavorited stars"); removeFav(); } }); } }); }) }); function createDetails(i) { var index = parseInt(i); $("#detailsText").css( {"color":"black"} ); $("#detailsText").html('<a onclick="showDetails();" href="javascript:void(0);" style="text-decoration: none; color: black">Details </a><svg xmlns="http://www.w3.org/2000/svg" height="12px" viewBox="0 0 18 18" width="12px" fill="black"><path d="M0 0h24v24H0z" fill="none"/><path d="M10 6L8.59 7.41 13.17 12l-4.58 4.59L10 18l6-6z"/></svg>'); var detailHTML = '<h5 style="text-align: center;">' + allCurrInfo[i]["event"] + '</h5><div class="button-row"><button onclick="showResults();" style="font-size: 12px;" type="button" class="btn btn-outline-secondary"><svg xmlns="http://www.w3.org/2000/svg" height="11px" viewBox="0 0 24 24" width="11px" fill="#000000"><path d="M0 0h24v24H0z" fill="none"/><path d="M11.67 3.87L9.9 2.1 0 12l9.9 9.9 1.77-1.77L3.54 12z"/></svg> List</button>' + '<button style="font-size: 12px; float: right; padding-bottom: 0; margin-left: 1%" type="button" class="btn btn-outline-secondary favButton2"><svg xmlns="http://www.w3.org/2000/svg" height="20px" viewBox="0 0 24 24" width="20px" fill="#000000"><path d="M22 9.24l-7.19-.62L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21 12 17.27 18.18 21l-1.63-7.03L22 9.24zM12 15.4l-3.76 2.27 1-4.28-3.32-2.88 4.38-.38L12 6.1l1.71 4.04 4.38.38-3.32 2.88 1 4.28L12 15.4z"/></svg></button>' + '<a target="_blank" href="https://twitter.com/intent/tweet?text=Check%20Out%20' + encodeURIComponent(allCurrInfo[i]["event"]) + '%20located%20at%20' + encodeURIComponent(allCurrInfo[i]["venue"]) + '.%20%23CSCI571EventSearch"><img style="vertical-align: top; margin-top: 1%; float: right" width="33px" height="33px" src="https://csci571.com/hw/hw8/images/Twitter.png"></a></div><ul style="font-size: 12px; margin-bottom: 2%;" class="nav nav-tabs col-lg-12" role="tablist"><li class="nav-item ml-auto"><a class="nav-link active" onclick="showEventTab();" href="javascript:void(0);" role="presentation" id="event-tab">Event</a>' + '</li><li class="nav-item"><a class="nav-link" onclick="showArtistTab();" href="javascript:void(0);" role="presentation" id="artist-tab">Artist/Teams</a></li><li class="nav-item"><a class="nav-link" onclick="showVenueTab();" href="javascript:void(0);" role="presentation" id="venue-tab">Venue</a></li></ul>'; // Create the Event tab detailHTML += '<div class="tab-content"><div class="tab-pane fade show active" id="event-entry" role="tabpanel"><table class="table table-striped"><tbody>'; if (allCurrInfo[i]["artists"].length > 0) { detailHTML += '<tr><th scope="row">Artist/Team(s)</th><td>'; for (var curr = 0; curr < allCurrInfo[i]["artists"].length; curr++) { if (curr > 0) { detailHTML += ' | '; } detailHTML += allCurrInfo[i]["artists"][curr]; } detailHTML += '</td></tr>'; } if (allCurrInfo[i]["venue"]) { detailHTML += '<tr><th scope="row">Venue</th><td>' + allCurrInfo[i]["venue"] + '</td></tr>'; } if (allCurrInfo[i]["date"]) { var splitDate = allCurrInfo[i]["date"].split("-"); if (splitDate[1][0] == 0) { splitDate[1] = splitDate[1].slice(1, 2); } if (splitDate[2][0] == 0) { splitDate[2] = splitDate[2].slice(1, 2); } detailHTML += '<tr><th scope="row">Time</th><td>' + months[splitDate[1]] + " " + splitDate[2] + ', ' + splitDate[0] + '</td></tr>'; } if (allCurrInfo[i]["category"]) { detailHTML += '<tr><th scope="row">Category</th><td>' + allCurrInfo[i]["category"] + '</td></tr>'; } if (allCurrInfo[i]["priceRange"]) { detailHTML += '<tr><th scope="row">Price Range</th><td>' + allCurrInfo[i]["priceRange"] + '</td></tr>'; } if (allCurrInfo[i]["ticketStatus"]) { detailHTML += '<tr><th scope="row">Ticket Status</th><td>' + allCurrInfo[i]["ticketStatus"] + '</td></tr>'; } if (allCurrInfo[i]["ticketURL"]) { detailHTML += '<tr><th scope="row">Buy Ticket At</th><td><a target="_blank" href="' + allCurrInfo[i]["ticketURL"] + '">Ticketmaster</a></td></tr>'; } if (allCurrInfo[i]["seatmap"]) { detailHTML += '<tr><th scope="row">Seat Map</th><td><a target="_blank" href="' + allCurrInfo[i]["seatmap"] + '">View Seat Map Here</a></td></tr>'; } detailHTML += '</tbody></table></div>'; // Create the Artist/Team tab detailHTML += '<div class="tab-pane fade" id="artist-entry" role="tabpanel">'; for (var curr = 0; curr < allCurrInfo[i]["artists"].length; curr++) { detailHTML += '<h6 style="text-align: center;">' + allCurrInfo[i]["event"] + '</h6>' if (allCurrInfo[i]["artistInfo"][curr]["name"] == "") { console.log("OK"); detailHTML += '<p style="font-style: 12px; margin-bottom: 15px;">No details available</p>'; } else { detailHTML += '<table style="margin-bottom: 20px;" class="table"><tbody><tr><th scope="row">Name</th><td>' + allCurrInfo[i]["artistInfo"][curr]["name"] + '</td></tr>'; let formattedPop = allCurrInfo[i]["artistInfo"][curr]["followers"].toLocaleString("en-US"); detailHTML += '<tr><th scope="row">Followers</th><td>' + formattedPop + '</td></tr>'; detailHTML += '<tr><th scope="row">Popularity</th><td>' + allCurrInfo[i]["artistInfo"][curr]["popularity"] + '<round-progress [current]="' + allCurrInfo[i]["artistInfo"][curr]["popularity"] + '" [max]="100" [radius]="16" [stroke]="2"></round-progress></td></tr>'; detailHTML += '<tr><th scope="row">Check At</th><td><a target="_blank" href="' + allCurrInfo[i]["artistInfo"][curr]["link"] + '">Spotify</a></td></tr>'; detailHTML += '</tbody></table>'; } } detailHTML += '</div>'; // Create the Venue tab detailHTML += '<div class="tab-pane fade" id="venue-entry" role="tabpanel">'; let addrEntry = allCurrInfo[i]["address"]; let cityEntry = allCurrInfo[i]["city"]; let phoneEntry = allCurrInfo[i]["phone"]; let hoursEntry = allCurrInfo[i]["hours"]; let generalEntry = allCurrInfo[i]["generalRule"]; let childEntry = allCurrInfo[i]["childRule"]; if (addrEntry == "" && cityEntry == "" && phoneEntry == "" && hoursEntry == "" && generalEntry == "" && childEntry == "") { // No records available } else { detailHTML += '<table class="table"><tbody>'; if (addrEntry != "") { detailHTML += '<tr><th scope="row">Address</th><td>' + addrEntry + '</td></tr>'; } if (cityEntry != "") { detailHTML += '<tr><th scope="row">City</th><td>' + cityEntry + '</td></tr>'; } if (phoneEntry != "") { detailHTML += '<tr><th scope="row">Phone Number</th><td>' + phoneEntry + '</td></tr>'; } if (hoursEntry != "") { detailHTML += '<tr><th scope="row">Open Hours</th><td>' + hoursEntry + '</td></tr>'; } if (generalEntry != "") { detailHTML += '<tr><th scope="row">General Rule</th><td>' + generalEntry + '</td></tr>'; } if (childEntry != "") { detailHTML += '<tr><th scope="row">Child Rule</th><td>' + childEntry + '</td></tr>'; } detailHTML += '</tbody></table>'; if (addrEntry != "") { detailHTML += '<div id="map"></div>'; var geoUrl = "https://maps.googleapis.com/maps/api/geocode/json?address="; var newAddr = addrEntry.replace(/\s+/g,'+'); jQuery.ajaxSetup({async:false}); geoUrl += newAddr + "&key=" + "AIzaSyBBhJ4BGqKrObAIHsXPzhuTYTs9FUvL2g8"; $.ajax({ url: geoUrl, type: "get", async: false, success: function(data) { if (data.status == "OK") { let latEntry = data.results[0].geometry.location.lat; let lngEntry = data.results[0].geometry.location.lng; detailHTML += '<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBBhJ4BGqKrObAIHsXPzhuTYTs9FUvL2g8&callback=initMap&libraries=&v=weekly"></script>' + '<script type="text/javascript">function initMap(lat1 = ' + latEntry + ', lng1 = ' + lngEntry + ') {const currLoc = { lat: lat1, lng: lng1 };const map = new google.maps.Map(document.getElementById("map"), {zoom: 15,center: currLoc,});const marker = new google.maps.Marker({position: currLoc, map: map,});}initMap(' + latEntry + ', ' + lngEntry + ');</script>'; } }, error: function() { console.log("ERROR"); } }); } } detailHTML += '</div>'; $("#results-table").hide(); $("#details-table").html(detailHTML); $("#details-table").show(); $(".favButton2").click(function() { if ($(this).attr("class") == "btn btn-outline-secondary favButton2") { $(this).html('<svg xmlns="http://www.w3.org/2000/svg" enable-background="new 0 0 24 24" height="20px" viewBox="0 0 24 24" width="20px" fill="#FFD900"><g><rect fill="none" height="24" width="24" x="0"/><polygon points="14.43,10 12,2 9.57,10 2,10 8.18,14.41 5.83,22 12,17.31 18.18,22 15.83,14.41 22,10"/></g></svg>'); $(this).attr("class", "btn btn-outline-secondary notfavButton2"); addFav(); } else { $(this).html('<svg xmlns="http://www.w3.org/2000/svg" height="20px" viewBox="0 0 24 24" width="20px" fill="#000000"><path d="M22 9.24l-7.19-.62L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21 12 17.27 18.18 21l-1.63-7.03L22 9.24zM12 15.4l-3.76 2.27 1-4.28-3.32-2.88 4.38-.38L12 6.1l1.71 4.04 4.38.38-3.32 2.88 1 4.28L12 15.4z"/></svg>'); $(this).attr("class", "btn btn-outline-secondary favButton2"); removeFav(); } }); } function showDetails() { $("#results-table").hide(); $("#details-table").show(); } function showResults() { $("#details-table").hide(); $("#results-table").show(); } function showEventTab() { $("#venue-entry").attr("class", "tab-pane fade"); $("#artist-entry").attr("class", "tab-pane fade"); $("#event-entry").attr("class", "tab-pane fade show active"); $("#venue-tab").attr("class", "nav-link"); $("#artist-tab").attr("class", "nav-link"); $("#event-tab").attr("class", "nav-link active"); } function showArtistTab() { $("#venue-entry").attr("class", "tab-pane fade"); $("#event-entry").attr("class", "tab-pane fade"); $("#artist-entry").attr("class", "tab-pane fade show active"); $("#venue-tab").attr("class", "nav-link"); $("#event-tab").attr("class", "nav-link"); $("#artist-tab").attr("class", "nav-link active"); } function showVenueTab() { $("#event-entry").attr("class", "tab-pane fade"); $("#artist-entry").attr("class", "tab-pane fade"); $("#venue-entry").attr("class", "tab-pane fade show active"); $("#event-tab").attr("class", "nav-link"); $("#artist-tab").attr("class", "nav-link"); $("#venue-tab").attr("class", "nav-link active"); } function removeFav() { console.log("removed"); } function addFav() { console.log("added"); }
Java
UTF-8
426
2.796875
3
[]
no_license
package com.jda.Algorithmprograms; import com.jda.utility.Utility; /** * @author 1022279 * */ public class MergeSort { /** * @param args */ public static void main(String[] args) { Utility utility = new Utility(); String[] arr = utility.getStringArray(); int low =0; int high = arr.length-1; utility.mergeSort(arr, low, high); for(int i=0;i<arr.length;i++) { System.out.println(arr[i]); } } }
C++
UTF-8
372
3
3
[]
no_license
#include "memath.h" #include <iostream> #include <string> using namespace std; //memath::memath() //{ // cout << "This is a constructor"<<endl; //}; memath::addition(int a, int b){ return a +b; }; memath::multiplication(int a, int b){ return a*b; }; memath::division(int a, int b){ return a/b; }; memath::subtraction(int a, int b){ return a- b; };
C#
UTF-8
4,334
3.046875
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Movilway.Cache { public interface ICache { /// <summary> /// Agrega el Objeto en cache /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <param name="valor"></param> /// <returns></returns> bool Add<T>(Object key, T valor); /// <summary> /// Agrega un valor al cache /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key"></param> /// <param name="valor"></param> /// <returns></returns> void AddOrUpdate<T>(Object key, T valor); /// <summary> /// Retorna en una variable entera el estado del diccionario que se esta implementando /// </summary> /// <returns></returns> int GetState(); /// <summary> /// Indica si el cache esta activo por configuracion /// </summary> /// <returns></returns> bool IsActiveCache(); /// <summary> /// retorna el objeto en cache teniendo encuenta el tiempo de expiracion por defecto /// </summary> /// <typeparam name="T">Tipo de dato a recuperar</typeparam> /// <param name="key">Parametro llave, objeto inmutable</param> /// <param name="func">call back que renueva el valor, si no existe o si el tiempo de cache se cumplio</param> /// <returns>Tipo de dato recuperado del cache </returns> T GetValue<T>(Object key, Func<T> func); /// <summary> /// retorna el objeto en cache teniendo encuenta el tiempo de expiracion que se envia /// como parametro /// </summary> /// <typeparam name="T">Tipo de dato a recuperar</typeparam> /// <param name="key">Parametro llave, objeto inmutable</param> /// <param name="func">call back que renueva el valor, si no existe o si el tiempo de cache se cumplio</param> /// <param name="oncache">Accion a ejecutar si el valor esta en cache</param> /// <returns>Tipo de dato recuperado del cache </returns> T GetValue<T>(Object key, Func<T> func, Action<Object,Object> oncache); /// <summary> /// retorna el objeto en cache teniendo encuenta el tiempo de expiracion que se envia /// como parametro /// </summary> /// <typeparam name="T">Tipo de dato a recuperar</typeparam> /// <param name="key">Parametro llave, objeto inmutable</param> /// <param name="func">call back que renueva el valor, si no existe o si el tiempo de cache se cumplio</param> /// <param name="time">Tiempo de expiracion</param> /// <returns>Tipo de dato recuperado del cache </returns> T GetValue<T>(Object key, Func<T> func, TimeSpan time); /// <summary> /// retorna el objeto en cache teniendo encuenta el tiempo de expiracion que se envia /// como parametro /// </summary> /// <typeparam name="T">Tipo de dato a recuperar</typeparam> /// <param name="key">Parametro llave, objeto inmutable</param> /// <param name="func">call back que renueva el valor, si no existe o si el tiempo de cache se cumplio</param> /// <param name="oncache">Accion a ejecutar si el valor esta en cache</param> /// <param name="time">Tiempo de expiracion</param> /// <returns>Tipo de dato recuperado del cache </returns> T GetValue<T>(Object key, Func<T> func, TimeSpan time, Action<Object, Object> oncache); /// <summary> /// /// </summary> /// <typeparam name="S">Tipo de Parametro del delegado</typeparam> /// <typeparam name="T">resultado del delegado</typeparam> /// <param name="key">llave del cache</param> /// <param name="param">Valor del parametro de tipo S</param> /// <param name="func">Callback</param> /// <param name="time">Tiempo de expiracion</param> /// <returns></returns> T GetValue<S, T>(Object key, S param, Func<S, T> func, TimeSpan time); /// <summary> /// Reseta todos los valores del cache /// </summary> void ResetAllCache(); } }
PHP
UTF-8
542
3.015625
3
[]
no_license
<!DOCTYPE html> <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <title></title> <!-- passare come argomento in GET una mail e stampare un div che contenga OK se contiene un punto e una chiocciola; KO altrimenti --> <?php $mail = $_GET['mail'] ; $dot = strpos($mail, '.'); $snail = strpos($mail, '@'); ?> </head> <body> <?php if ($dot && $snail) { echo '<div>OK!</div>'; } else { echo '<div>KO!</div>'; } ?> </body> </html>
PHP
UTF-8
2,049
2.859375
3
[]
no_license
<?php /* * 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. */ /** * Description of clsTratamiento * * @author Dell */ class clsTratamiento extends Conexion { //put your code here //put your code here private $Id_tratamiento; private $Nombre; private $Cantidad; private $Id_tipo_tratamiento; public function __construct($nom="",$cant="",$id_t=0) { $this->Id_tratamiento=0; $this->Nombre=$nom; $this->Cantidad=$cant; $this->Id_tipo_tratamiento=$id_t; } public function __destruct() { } public function setNombreTratamiento($n=""){ $this->Nombre=$n; } public function setCantidadTratamiento($n=""){ $this->Cantidad=$n; } public function setTipoTratamiento($n=0){ $this->Id_tipo_tratamiento=$n; } public function getNombre(){ return $this->Nombre; } public function getCantidad(){ return $this->Cantidad; } public function getTipoTratamiento(){ return $this->Id_tipo_tratamiento; } public function guardar() { $sql="insert into Tratamiento (Nombre,Cantidad,Id_tipo_tratamiento) values('$this->Nombre','$this->Cantidad','$this->Id_tipo_tratamiento')"; if(parent::ejecutar($sql)) return true; else return false; } public function modificar() { $sql="update Tratamiento set Nombre='$this->Nombre',Cantidad='$this->Cantidad',Id_tipo_tratamiento='$this->Id_tipo_tratamiento' where Id_tratamiento='$this->Id_tratamiento'"; if(parent::ejecutar($sql)) return true; else return false; } public function eliminar(){ $sql="delete from Tratamiento where Id_tratamiento='$this->Id_tratamiento"; if(parent::ejecutar($sql)) return true; else return false; } public function buscar() { $sql="select * from Tratamiento"; return parent::ejecutar($sql); } }
Python
UTF-8
827
2.984375
3
[]
no_license
from collections import defaultdict, deque def read_int(): return int(input().strip()) def read_ints(): return list(map(int, input().strip().split(' '))) def solve(): N, M = read_ints() out_degree = [0]*N max_path = [0]*N G = defaultdict(list) for _ in range(M): x, y = read_ints() x -= 1 y -= 1 out_degree[x] += 1 G[y].append(x) Q = [i for i, degree in enumerate(out_degree) if degree == 0] while len(Q): node = Q.pop() while len(G[node]): parent = G[node].pop() out_degree[parent] -= 1 max_path[parent] = max(max_path[parent], max_path[node]+1) if out_degree[parent] == 0: Q.append(parent) return max(max_path) if __name__ == '__main__': print(solve())
JavaScript
UTF-8
739
4.1875
4
[]
no_license
// find the wealthiest person from a 2d array and return a string with index and amount function findWealthiestPerson(arr){ let amount; let resultIndex; for(let i=0; i<arr.length; i++){ let currentAmountValue = 0; for(let j=0; j<arr[i].length; j++){ currentAmountValue += arr[i][j]; } if(i===0){ resultIndex = i; amount = currentAmountValue } else { if(currentAmountValue > amount){ amount = currentAmountValue resultIndex = i; } } } return `the wealthiest Person is ${resultIndex+1} with the amount ${amount}`; } console.log(findWealthiestPerson([[2,3],[4,9],[11,22],[4,5]]));
PHP
UTF-8
2,790
2.828125
3
[]
no_license
<?php namespace App\Command; use App\Enumerator\UserRoles; use App\Repository\UserRepository; use Symfony\Component\Console\Command\Command; use Symfony\Component\Console\Input\InputArgument; use Symfony\Component\Console\Input\InputInterface; use Symfony\Component\Console\Output\OutputInterface; use Symfony\Component\Console\Style\SymfonyStyle; use Symfony\Component\Security\Core\User\UserInterface; class PromoteUserCommand extends Command { protected static $defaultName = 'app:promote-user'; /** @var UserRepository */ private $userRepository; private $adminRole; /** * PromoteUserCommand constructor. * @param UserRepository $userRepository * @param string $adminRole */ public function __construct(UserRepository $userRepository, $adminRole = UserRoles::ADMIN) { $this->userRepository = $userRepository; $this->adminRole = $adminRole; parent::__construct(); } protected function configure() { $this ->setDescription('Make user admin') ->addArgument('email', InputArgument::REQUIRED, 'E-mail address of existing user'); } /** * @param InputInterface $input * @param OutputInterface $output * @throws \Doctrine\ORM\NonUniqueResultException * @throws \Doctrine\ORM\ORMException */ protected function execute(InputInterface $input, OutputInterface $output) { // Parsing input $io = new SymfonyStyle($input, $output); $email = $input->getArgument('email'); // Getting user $this->info("Searching for user", $email, $io); $user = $this->userRepository->findByEmail($email); if (!$user) { $io->error("Cannot find user by e-mail: " . $email); return; } if (in_array($this->adminRole, $user->getRoles())) { $this->printUserRoles($user, $io); $io->success('Admin role already exists'); return; } // Adding admin role $this->info("Adding role: ", $this->adminRole, $io); $roles = $user->getRoles(); $roles[] = $this->adminRole; $user->setRoles(array_unique($roles)); // Storing user $this->userRepository->save($user); $this->printUserRoles($user, $output); $io->success('Admin role successfully added'); } private function info($message, $value, OutputInterface $io) { $io->writeln(sprintf('<info>%s</info>: <comment>%s</comment>', $message, $value)); } private function printUserRoles(UserInterface $user, OutputInterface $io) { $io->writeln( "<info>User roles</info>: <comment>" . join('</comment>, <comment>', $user->getRoles()) . '</comment>' ); } }
C++
UTF-8
1,766
2.859375
3
[ "MIT" ]
permissive
#pragma once #include <string> #include <vector> #include <memory> #include <unordered_map> #include "../io/io_writer.h" namespace cminus::logic{ struct runtime; } namespace cminus::logic::naming{ class parent; class object{ public: virtual ~object() = default; virtual parent *get_naming_parent() const = 0; virtual const std::string &get_naming_value() const = 0; virtual std::string get_qualified_naming_value() const = 0; virtual void print(logic::runtime &runtime, bool is_qualified) const = 0; virtual bool is_same(const object &target) const = 0; static std::shared_ptr<object> build_name(const std::vector<std::string> &branches); static std::shared_ptr<object> build_name(const std::string &value); }; class single : public object{ public: explicit single(const std::string &value, naming::parent *parent = nullptr); virtual ~single(); virtual parent *get_naming_parent() const override; virtual const std::string &get_naming_value() const override; virtual std::string get_qualified_naming_value() const override; virtual void print(logic::runtime &runtime, bool is_qualified) const override; virtual bool is_same(const object &target) const override; protected: friend class parent; parent *parent_ = nullptr; std::string value_; }; class parent : public single{ public: explicit parent(const std::string &value, naming::parent *parent = nullptr); virtual ~parent(); virtual std::shared_ptr<object> add_object(const std::string &value, bool is_parent); virtual bool remove_object(const std::string &value); virtual std::shared_ptr<object> find_object(const std::string &value) const; protected: std::unordered_map<std::string, std::shared_ptr<object>> objects_; }; }
Python
UTF-8
329
3.015625
3
[]
no_license
#!/usr/bin/env python3 def main(): count=0 inputList = [ int(input()) for i in range(4) ] for i in range(inputList[0]+1): for j in range(inputList[1]+1): if 0 <= (inputList[3]-(500*i+100*j))/50 <= inputList[2]: count=count+1 print(count) if __name__ == '__main__': main()
TypeScript
UTF-8
1,229
2.5625
3
[]
no_license
import { PersonasService } from '../../personas.service'; import { Persona } from '../../persona.model'; import { Component, OnInit } from '@angular/core'; import { LoggingService } from '../../LoggingService.service'; @Component({ selector: 'app-formulario', templateUrl: './formulario.component.html', styleUrls: ['./formulario.component.css'] }) export class FormularioComponent implements OnInit { nombreInput: string; apellidoInput: string; constructor(private loggingService: LoggingService, // Inyectamos el servicio a traves del constructor utilizando el concepto de Dependency Injection private personasService: PersonasService) { this.personasService.saludar.subscribe( //Se emite el saludo, nos suscribimos a la emisión del mensaje, recibimos el indice y mandamos un alerta donde indicamos cuál es el indice que se ha seleccionado. (indice: number) => alert("El indice es: " + indice) ); } ngOnInit(): void { } onAgregarPersona(){ let persona1 = new Persona(this.nombreInput, this.apellidoInput); // Llamamos al método agregarPersona this.personasService.agregarPersona(persona1); } }
Markdown
UTF-8
1,993
3.21875
3
[]
no_license
# Production Problem 10: A/B Testing on the Cheap ## The Problem Locate an interface component on a website that you use frequently that you think could be improved. The improvement should be minor. Take a screenshot of the interface on both a mobile and desktop device. Then, sketch or illustrate your alternate/"b" test. Finally, describe modification and the HTML, CSS, and JavaScript that you would need to write in order to conduct the test. ## Deliverables * Screenshots of the interface component on mobile and desktop, placed in this directory (`pp-10/`) * Sketch or illustrate (e.g., in Photoshop) your alternate/"b" test, placed in this directory (`pp-10/`) * A text description of the modification, and a description of the HTML, CSS, and JavaScript that you would need to write for the test (you do *not* have to write the actual HTML, CSS, and JavaScript, however) In the HTML would take away the navigation bar below the search bar. I would also get rid of a lot of the options, getting rid of excess links that are probably hardly ever used. I would take away the ad below it if I could. In the CSS I would center the title of the topics on the message board. I found the text just a bit too small so I would also increase the size of the text in the CSS. I would add some padding on each side that it looks more compact and easier to work with. For the mobile version I would simplify it heavily getting rid of the main nav bar at the top and replacing it with a drop down or autofill type input box for choosing systems and a seperate one for choosing games. I would get rid of the the nav bar for the game itself and make a single nav bar that switches between message boards, FAQs, cheats and the rest of the pages for the game. The message board layout itself would stay relatively the same. I think for a site like this I would keep javascript to a minimum and probably only implement it for the auto fill functions and other functions where it's critically needed
Java
UTF-8
1,661
2.46875
2
[]
no_license
package com.byheetech.freecall; import android.content.Intent; import android.os.CountDownTimer; import com.byheetech.freecall.activity.MainActivity; import com.byheetech.freecall.base.BaseActivity; public class WelcomeActivity extends BaseActivity { private MyCountDownTimer timer; @Override protected void initLayout() { setContentView(R.layout.activity_welcome); } @Override protected void initActionBar() { } @Override protected int setStatusBarColor() { return android.R.color.transparent; } @Override protected void initId() { } @Override protected void initData() { timer = new MyCountDownTimer(2000, 1000); timer.start(); } @Override protected void initListener() { } class MyCountDownTimer extends CountDownTimer { /** * @param millisInFuture The number of millis in the future from the call * to {@link #start()} until the countdown is done and {@link #onFinish()} * is called. * @param countDownInterval The interval along the way to receive * {@link #onTick(long)} callbacks. */ public MyCountDownTimer(long millisInFuture, long countDownInterval) { super(millisInFuture, countDownInterval); } @Override public void onTick(long millisUntilFinished) { } @Override public void onFinish() { startActivity(new Intent(getApplicationContext(), MainActivity.class)); finish(); } } }
Markdown
UTF-8
785
3.28125
3
[ "MIT" ]
permissive
# 5.5 [Break 与 continue](https://github.com/Unknwon/the-way-to-go_ZH_CN/blob/master/eBook/05.5.md) `break` 语句退出循环。 一个 break 的作用范围为该语句出现后的最内部的结构,它可以被用于任何形式的 for 循环(计数器、条件判断等)。 但在 switch 或 select 语句中(详见第 13 章),break 语句的作用结果是跳过整个代码块,执行后续的代码。 关键字 `continue` 忽略剩余的循环体而直接进入下一次循环的过程,但不是无条件执行下一次循环,执行之前依旧需要满足循环的判断条件。 另外,关键字 continue 只能被用于 for 循环中。 ## 链接 - [目录](directory.md) - 上一节:[for 结构](05.4.md) - 下一节:[标签与 goto](05.6.md)
Shell
UTF-8
124
2.59375
3
[]
no_license
#!/bin/bash #comment out specific lines in a file echo "Enter filename:" read file sed -i '1,2 s/^/#/' $file cat $file
TypeScript
UTF-8
222
3.140625
3
[]
no_license
/** * Generate a random value between the two values provided */ export default function getRandomValue(min: number, max: number) { var difference = Math.abs(max - min); return Math.random() * difference + min; }
Markdown
UTF-8
1,546
3.28125
3
[ "Apache-2.0", "MIT" ]
permissive
# Types In PHP, data is stored in containers called zvals (zend values). Internally, these are effectively tagged unions (enums in Rust) without the safety that Rust introduces. Passing data between Rust and PHP requires the data to become a zval. This is done through two traits: `FromZval` and `IntoZval`. These traits have been implemented on most regular Rust types: - Primitive integers (`i8`, `i16`, `i32`, `i64`, `u8`, `u16`, `u32`, `u64`, `usize`, `isize`). - Double and single-precision floating point numbers (`f32`, `f64`). - Booleans. - Strings (`String` and `&str`) - `Vec<T>` where T implements `IntoZval` and/or `FromZval`. - `HashMap<String, T>` where T implements `IntoZval` and/or `FromZval`. - `Binary<T>` where T implements `Pack`, used for transferring binary string data. - A PHP callable closure or function wrapped with `Callable`. - `Option<T>` where T implements `IntoZval` and/or `FromZval`, and where `None` is converted to a PHP `null`. Return types can also include: - Any class type which implements `RegisteredClass` (i.e. any struct you have registered with PHP). - An immutable reference to `self` when used in a method, through the `ClassRef` type. - A Rust closure wrapped with `Closure`. - `Result<T, E>`, where `T: IntoZval` and `E: Into<PhpException>`. When the error variant is encountered, it is converted into a `PhpException` and thrown as an exception. For a type to be returnable, it must implement `IntoZval`, while for it to be valid as a parameter, it must implement `FromZval`.
C#
UTF-8
13,151
2.859375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Security.Cryptography; using System.IO; namespace Common.Security { /// <summary> /// Component handles encryption request specifically dealing with private key encryptions /// using Triple-DES /// </summary> public class EncryptionManager { private const string PrivateSaltedKey = "458678943525326356769826"; public EncryptionManager() { } public string DefaultDecryption(string cypherText) { if (string.IsNullOrEmpty(cypherText)) throw new ArgumentException("Invalid value for the cypher text. Value can not be empty for the encryption."); return this.Decrypt(cypherText, EncryptionManager.Settings.EncryptPassPhrase, EncryptionManager.Settings.EncryptSaltValue, EncryptionManager.Settings.EncryptHashAlgorithm, EncryptionManager.Settings.EncryptPassIterations, EncryptionManager.Settings.EncryptInitVector, 256); } public string DefaultEncryption(string plainText) { if (plainText.Trim().Length == 0) { throw new System.Exception("Invalid value for the plain text. Value can not be empty for the encryption."); } return this.Encrypt(plainText, EncryptionManager.Settings.EncryptPassPhrase, EncryptionManager.Settings.EncryptSaltValue, EncryptionManager.Settings.EncryptHashAlgorithm, EncryptionManager.Settings.EncryptPassIterations, EncryptionManager.Settings.EncryptInitVector, 256); } public string Encrypt(string plainText) { TripleDESCryptoServiceProvider crp = new TripleDESCryptoServiceProvider(); UnicodeEncoding uEncode = new UnicodeEncoding(); ASCIIEncoding aEncode = new ASCIIEncoding(); MemoryStream stmCipherText = new MemoryStream(); if (plainText == string.Empty) return string.Empty; if (plainText == null) return string.Empty; Byte[] bytPlainText = uEncode.GetBytes(plainText); crp.Key = aEncode.GetBytes(PrivateSaltedKey); crp.IV = aEncode.GetBytes(PrivateSaltedKey.Substring(0, 8)); CryptoStream csEncrypted = new CryptoStream(stmCipherText, crp.CreateEncryptor(), CryptoStreamMode.Write); csEncrypted.Write(bytPlainText, 0, bytPlainText.Length); csEncrypted.FlushFinalBlock(); return Convert.ToBase64String(stmCipherText.ToArray()); } public string Decrypt(string cipherText) { TripleDESCryptoServiceProvider crp = new TripleDESCryptoServiceProvider(); UnicodeEncoding uEncode = new UnicodeEncoding(); ASCIIEncoding aEncode = new ASCIIEncoding(); MemoryStream stmPlainText = new MemoryStream(); try { if (cipherText == string.Empty) return string.Empty; if (cipherText == null) return string.Empty; Byte[] bytCipherText = Convert.FromBase64String(cipherText); MemoryStream stmCipherText = new MemoryStream(bytCipherText); crp.Key = aEncode.GetBytes(PrivateSaltedKey); crp.IV = aEncode.GetBytes(PrivateSaltedKey.Substring(0, 8)); CryptoStream csDecrypted = new CryptoStream(stmCipherText, crp.CreateDecryptor(), CryptoStreamMode.Read); StreamWriter sw = new StreamWriter(stmPlainText); StreamReader sr = new StreamReader(csDecrypted); sw.Write(sr.ReadToEnd()); sw.Flush(); csDecrypted.Clear(); crp.Clear(); } catch (ApplicationException ex) { throw ex; } catch (Exception ex) { return string.Empty; //throw ex; } return uEncode.GetString(stmPlainText.ToArray()); } public string Encrypt(string plainText, string passPhrase, string saltValue, string hashAlgorithm, int passwordIterations, string initVector, int keySize) { string cipherText; Byte[] initVectorBytes = null; Byte[] saltValueBytes = null; Byte[] plainTextBytes = null; PasswordDeriveBytes password = null; Byte[] keyBytes = null; MemoryStream memoryStream = null; ICryptoTransform encryptor = null; CryptoStream cryptoStream = null; try { //Convert strings into byte arrays. //Let us assume that strings only contain ASCII codes. //If strings include Unicode characters, use Unicode, UTF7, or UTF8 //encoding. initVectorBytes = Encoding.ASCII.GetBytes(initVector); saltValueBytes = Encoding.ASCII.GetBytes(saltValue); //Convert our plaintext into a byte array. //Let us assume that plaintext contains UTF8-encoded characters. plainTextBytes = Encoding.UTF8.GetBytes(plainText); //First, we must create a password, from which the key will be derived. //This password will be generated from the specified passphrase and //salt value. The password will be created using the specified hash //algorithm. Password creation can be done in several iterations. password = new PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations); //Use the password to generate pseudo-random bytes for the encryption //key. Specify the size of the key in bytes (instead of bits). keyBytes = password.GetBytes((int)(keySize / 8)); //Create uninitialized Rijndael encryption object. RijndaelManaged symmetricKey; symmetricKey = new RijndaelManaged(); //It is reasonable to set encryption mode to Cipher Block Chaining //(CBC). Use default options for other symmetric key parameters. symmetricKey.Mode = CipherMode.CBC; //Generate encryptor from the existing key bytes and initialization //vector. Key size will be defined based on the number of the key //bytes. encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes); //Define memory stream which will be used to hold encrypted data. memoryStream = new MemoryStream(); //Define cryptographic stream (always use Write mode for encryption). cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write); //Start encrypting. cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length); //Finish encrypting. cryptoStream.FlushFinalBlock(); //Convert our encrypted data from a memory stream into a byte array. Byte[] cipherTextBytes; cipherTextBytes = memoryStream.ToArray(); //Convert encrypted data into a base64-encoded string. cipherText = Convert.ToBase64String(cipherTextBytes); } catch (Exception ex) { throw ex; } finally { if (!(memoryStream == null)) { memoryStream.Close(); } if (!(cryptoStream == null)) { cryptoStream.Close(); } } //Return encrypted string. return cipherText; } public string Decrypt(string cipherText, string passPhrase, string saltValue, string hashAlgorithm, int passwordIterations, string initVector, int keySize) { Byte[] initVectorBytes = null; Byte[] saltValueBytes = null; Byte[] cipherTextBytes = null; PasswordDeriveBytes password = null; Byte[] keyBytes = null; ICryptoTransform decryptor = null; RijndaelManaged symmetricKey = null; MemoryStream memoryStream = null; CryptoStream cryptoStream = null; Byte[] plainTextBytes = null; Byte[] plainTextBytes2 = null; int decryptedByteCount; string plainText; try { //' Convert strings defining encryption key characteristics into byte //' arrays. Let us assume that strings only contain ASCII codes. //' If strings include Unicode characters, use Unicode, UTF7, or UTF8 //' encoding. initVectorBytes = Encoding.ASCII.GetBytes(initVector); saltValueBytes = Encoding.ASCII.GetBytes(saltValue); //' Convert our ciphertext into a byte array. cipherTextBytes = Convert.FromBase64String(cipherText); //' First, we must create a password, from which the key will be //' derived. This password will be generated from the specified //' passphrase and salt value. The password will be created using //' the specified hash algorithm. Password creation can be done in //' several iterations. password = new PasswordDeriveBytes(passPhrase, saltValueBytes, hashAlgorithm, passwordIterations); //' Use the password to generate pseudo-random bytes for the encryption //' key. Specify the size of the key in bytes (instead of bits). keyBytes = password.GetBytes((System.Int32)(keySize / 8)); //' Create uninitialized Rijndael encryption object. symmetricKey = new RijndaelManaged(); //' It is reasonable to set encryption mode to Cipher Block Chaining //' (CBC). Use default options for other symmetric key parameters. symmetricKey.Mode = CipherMode.CBC; //' Generate decryptor from the existing key bytes and initialization //' vector. Key size will be defined based on the number of the key //' bytes. decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes); //' Define memory stream which will be used to hold encrypted data. memoryStream = new MemoryStream(cipherTextBytes); //' Define memory stream which will be used to hold encrypted data. cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read); //' Since at this point we don't know what the size of decrypted data //' will be, allocate the buffer long enough to hold ciphertext; //' plaintext is never longer than ciphertext. //ReDim plainTextBytes(cipherTextBytes.Length); plainTextBytes2 = new Byte[cipherTextBytes.Length]; for (int i = 0; i < plainTextBytes.GetUpperBound(0); i++) { plainTextBytes2[i] = plainTextBytes[i]; } //' Start decrypting. decryptedByteCount = cryptoStream.Read(plainTextBytes2, 0, plainTextBytes2.Length); //' Convert decrypted data into a string. //' Let us assume that the original plaintext string was UTF8-encoded. plainText = Encoding.UTF8.GetString(plainTextBytes2, 0, decryptedByteCount); } catch (Exception ex) { throw ex; } finally { if (!(memoryStream == null)) { memoryStream.Close(); } if (!(cryptoStream == null)) { cryptoStream.Close(); } } //' Return decrypted string. return plainText; } public class Settings { public const string EncryptPassPhrase = "&PUIH%$&*"; public const string EncryptSaltValue = "(*(&HY%R%*"; public const string EncryptHashAlgorithm = "SHA1"; public const System.Int32 EncryptPassIterations = 2; public const string EncryptInitVector = "K)(&T^&%$*R%IGFT"; public Settings() { } } } }
Python
UTF-8
6,476
3.78125
4
[]
no_license
''' Menu Padronizado. Função Cria menu com título, lista de submenus, lista de controles, explicação do menu ''' def menu(titulo: str = 'Insira o título deste menu'.title().upper(), lista_de_itens_submenus: list = [], lista_itens_controle: list = [], explicar: bool = True, explicacao: str = 'Informe sua explicação para que seja adicionada ao menu.', pedir_resposta: bool = True, mostrar_lista_no_menu: bool = False, lista: list = []) -> int: """Exibe Menu Padrão e Retorna o valor inserido pelo usuário. A resposta do user já foi tratada evitando assim erros :param titulo: Uma string que será o título do menu. :param lista_de_itens_submenus: Uma lista com as opções de execução e/ou redirecionamento para outros menus. :param lista_itens_controle: Uma lista com as opções de controle, como por ex.: "Cancelar a operação". :param explicar: Um bool que irá informar ao algoritmo se o usuário quer ou não alguma mensagem explicando o menu. :param explicacao: Uma string que conterá o texto de explicação do menu. :param pedir_resposta: Um bool que irá permitir solicitar ou não uma resposta do usuário. Isso pq existe funções que não precisam de resposta imediata do menu :param mostrar_lista_no_menu: um bool para permitir que o menu exiba uma lista. Isso é para deixar a função de inserção das ações do submenu3 mais fácil de interagir. :return valor inteiro para o redirecionamento para outros menus. Obs.: Sempre será retornado o valor que o user inseriu menos 1 Obs.1: Os nomes dos sub-menus não podem ter mais 64 caracteres. Caso tenha a grade será esticada. Não ficando uma aparência bacana Obs.2: A contagem segue o padrão de máquina. O primeiro valor vale 0, o segundo 1, etc. """ print('\n\n\n\n\n\n') titulo_com_espacos = '' for i in titulo: if i != ' ': titulo_com_espacos += i titulo_com_espacos += ' ' else: titulo_com_espacos += i print(f"┌{33 * '─'}{' G R A M B O T ':^}{32 * '─'}┐") print('│ │') print(f'│ {titulo_com_espacos.upper():<{75}}│') if explicar == True: print(f'│ │') print('│-------- H E L P - M E --------------------------------------------------------│', end='') explicacao = explicacao.title() cont = 0 print('\n│ ', end='') for i in range(len(explicacao)): if cont > 70 and explicacao[i] == ' ': print(' ', end=f' │\n│ {explicacao[i]}') cont = 0 elif cont > 70 and explicacao[i] != ' ': print('-', end=f' │\n│ {explicacao[i]}') cont = 0 else: print(explicacao[i], end='') cont += 1 print((76 - cont) * ' ', end='') print('│') if not len(lista_de_itens_submenus) > 0: print(f'''│--------------------------------------------------------------------------------│ │ │''') if len(lista_de_itens_submenus) > 0: print(f'''│--------------------------------------------------------------------------------│ │ │''', ) for i in range(len(lista_de_itens_submenus)): print(f'''│ [{i + 1:^5}] - {lista_de_itens_submenus[i].title():64}│''') print(f'''│ │''') print(f'''│ │''') if len(lista_itens_controle) > 0: print(f'''|{31 * '─'} C O N T R O L E {31 * '─'}|''') print(f'''│ │''') for j in range(len(lista_itens_controle)): print(f'''│ [{-1 * (j + 1):^5}] - {lista_itens_controle[j].title():64}│ ''') print('│ │') print('│ │') print('└────────────────────────────────────────────────────────────────────────────────┘') else: print('│ │') print('│ │') print('└────────────────────────────────────────────────────────────────────────────────┘') if mostrar_lista_no_menu: print(f'Lista de Comandos: {lista}') if pedir_resposta == True: resposta = input('Informe a opção desejada: ') while True: try: if int(resposta) == 0: resposta = input( 'Opção Inexistente, tente outra para prosseguir. Informe a opção desejada: '.title()) elif int(resposta) >= 1 and int(resposta) <= len(lista_de_itens_submenus): resposta = int(resposta) - 1 break elif int(resposta) < -len(lista_itens_controle) or int(resposta) > len(lista_de_itens_submenus): resposta = input( 'Opção Inexistente, tente outra para prosseguir. Informe a opção desejada: '.title()) else: break except: resposta = input( 'Entrada Inválida. Somente as opções exibidas podem ser escolhidas. Tente Novamente. Informe a opção desejada: '.title()) continue return int(resposta) else: return 1000000000 # valor inteiro do menu que nunca será válido
Python
UTF-8
8,214
2.671875
3
[]
no_license
import copy from torch.nn import functional as F from torch.nn.modules.module import Module from torch.nn.modules.activation import MultiheadAttention from torch.nn.modules import LayerNorm class TransformerModel_Encoder(nn.Module): def __init__(self, ninp, nhead, nhid, nlayers, dropout=0.5,mask_future=False): ''' ninp, input data features dimension, input is batch,sequence length(nwords), dim of each word embedding ninp should be divisible by nhead, ninp/nhead is an int nhid,a scalar,size of a hidden layer in transformer feedforward nlayers,number of encoder layers in the encoder mask_future, in nlp,future words should be masked to current existent words, input shape, N,L,C an example of input: input tensor size 10,20,32, batch_size==10,20 words,each word has an embedding of size 32, nhead =8, output size, the same as input ''' super(TransformerModel_Encoder, self).__init__() #from torch.nn import TransformerEncoder, TransformerEncoderLayer self.model_type = 'Transformer' self.src_mask = None self.pos_encoder = PositionalEncoding(ninp, dropout) encoder_layers = TransformerEncoderLayer(ninp, nhead, nhid, dropout) self.transformer_encoder = TransformerEncoder(encoder_layers, nlayers) self.mask_future=mask_future self.ninp = ninp def _generate_square_subsequent_mask(self, sz): mask = (torch.triu(torch.ones(sz, sz)) == 1).transpose(0, 1) mask = mask.float().masked_fill(mask == 0, float('-inf')).masked_fill(mask == 1, float(0.0)) return mask def forward(self, src): if (self.src_mask is None or self.src_mask.size(0) != len(src) ) and self.mask_future ==True: device = src.device mask = self._generate_square_subsequent_mask(len(src)).to(device) self.src_mask = mask else: self.src_mask = None src = self.pos_encoder(src) output = self.transformer_encoder(src, self.src_mask) return output class TransformerEncoder(Module): r"""TransformerEncoder is a stack of N encoder layers Args: encoder_layer: an instance of the TransformerEncoderLayer() class (required). num_layers: the number of sub-encoder-layers in the encoder (required). norm: the layer normalization component (optional). Examples:: >>> encoder_layer = nn.TransformerEncoderLayer(d_model=512, nhead=8) >>> transformer_encoder = nn.TransformerEncoder(encoder_layer, num_layers=6) >>> src = torch.rand(10, 32, 512) >>> out = transformer_encoder(src) """ def __init__(self, encoder_layer, num_layers, norm=None): super(TransformerEncoder, self).__init__() self.layers = _get_clones(encoder_layer, num_layers) self.num_layers = num_layers self.norm = norm def forward(self, src, mask=None, src_key_padding_mask=None): r"""Pass the input through the encoder layers in turn. Args: src: the sequnce to the encoder (required). mask: the mask for the src sequence (optional). src_key_padding_mask: the mask for the src keys per batch (optional). Shape: see the docs in Transformer class. """ output = src for i in range(self.num_layers): output = self.layers[i](output, src_mask=mask, src_key_padding_mask=src_key_padding_mask) if self.norm: output = self.norm(output) return output def _get_clones(module, N): return ModuleList([copy.deepcopy(module) for i in range(N)]) def _get_activation_fn(activation): if activation == "relu": return F.relu elif activation == "gelu": return F.gelu else: raise RuntimeError("activation should be relu/gelu, not %s." % activation) class TransformerEncoderLayer(Module): r"""TransformerEncoderLayer is made up of self-attn and feedforward network. This standard encoder layer is based on the paper "Attention Is All You Need". Ashish Vaswani, Noam Shazeer, Niki Parmar, Jakob Uszkoreit, Llion Jones, Aidan N Gomez, Lukasz Kaiser, and Illia Polosukhin. 2017. Attention is all you need. In Advances in Neural Information Processing Systems, pages 6000-6010. Users may modify or implement in a different way during application. Args: d_model: the number of expected features in the input (required). nhead: the number of heads in the multiheadattention models (required). dim_feedforward: the dimension of the feedforward network model (default=2048). dropout: the dropout value (default=0.1). activation: the activation function of intermediate layer, relu or gelu (default=relu). Examples:: >>> encoder_layer = nn.TransformerEncoderLayer(d_model=512, nhead=8) >>> src = torch.rand(10, 32, 512) >>> out = encoder_layer(src) """ def __init__(self, d_model, nhead, dim_feedforward=2048, dropout=0.1, activation="relu"): super(TransformerEncoderLayer, self).__init__() self.self_attn = MultiheadAttention(d_model, nhead, dropout=dropout) # Implementation of Feedforward model self.linear1 = Linear(d_model, dim_feedforward) self.dropout = Dropout(dropout) self.linear2 = Linear(dim_feedforward, d_model) self.norm1 = LayerNorm(d_model) self.norm2 = LayerNorm(d_model) self.dropout1 = Dropout(dropout) self.dropout2 = Dropout(dropout) self.activation = _get_activation_fn(activation) def forward(self, src, src_mask=None, src_key_padding_mask=None): r"""Pass the input through the encoder layer. Args: src: the sequnce to the encoder layer (required). src_mask: the mask for the src sequence (optional). src_key_padding_mask: the mask for the src keys per batch (optional). Shape: see the docs in Transformer class. """ src2 = self.self_attn(src, src, src, attn_mask=src_mask, key_padding_mask=src_key_padding_mask)[0] src = src + self.dropout1(src2) src = self.norm1(src) if hasattr(self, "activation"): src2 = self.linear2(self.dropout(self.activation(self.linear1(src)))) else: # for backward compatibility src2 = self.linear2(self.dropout(F.relu(self.linear1(src)))) src = src + self.dropout2(src2) src = self.norm2(src) return src class PositionalEncoding(nn.Module): def __init__(self, d_model, dropout=0.1, max_len=5000): super(PositionalEncoding, self).__init__() self.dropout = nn.Dropout(p=dropout) pe = torch.zeros(max_len, d_model) position = torch.arange(0, max_len, dtype=torch.float).unsqueeze(1) div_term = torch.exp(torch.arange(0, d_model, 2).float() * (-math.log(10000.0) / d_model)) pe[:, 0::2] = torch.sin(position * div_term) pe[:, 1::2] = torch.cos(position * div_term) pe = pe.unsqueeze(0).transpose(0, 1) self.register_buffer('pe', pe) def forward(self, x): x = x + self.pe[:x.size(0), :] return self.dropout(x) class Tf1(nn.Module): def __init__(self, n_features=4001, cnn_channels=512,kernel_size=7,stride=1,poolker=19,poolstride=4): super(Tf1, self).__init__() #=n_features-30 self.cnn_channels=cnn_channels self.cnn1=Conv1d(4,cnn_channels,7,stride=1,padding=3) self.pool=MaxPool1d(poolker,poolstride) self.tf_model=TransformerModel_Encoder(ninp=cnn_channels, nhead=32, nhid=cnn_channels, nlayers=3) self.l1=int ( (n_features-poolker)/poolstride+1 ) self.linear=Linear(self.l1*cnn_channels,1) def forward(self,x): batch=x.size()[0] x=self.cnn1(x) x=self.pool(x) x=x.view(batch,self.l1,self.cnn_channels) x=self.tf_model(x) x=x.view(batch,-1) x=self.linear(x) return x
C++
UTF-8
293
2.59375
3
[]
no_license
#include<stdio.h> #include<math.h> #include<string.h> #include<stdlib.h> #include<ctype.h> #include<time.h> int main() { unsigned long long num,sum; while(scanf("%llu",&num) == 1) { num = num + 1; sum = (num * num) / 2; sum = (sum - 3) * 3; printf("%llu\n",sum); } return 0; }
Python
UTF-8
230
2.984375
3
[]
no_license
from sys import argv script_name, first, second, third = argv print "The script is called: ", script_name print "Your first variable is: ", first print "Your second variable is: ", second print "Your third variable is: ", third
C
UTF-8
245
2.859375
3
[]
no_license
/*************************************** #Name : Return_Negative #Author : Luis Teixeira #Date : 29-11-2018 #E-Mail : filipe.teixeira.996@gmail.com *************************************************/ int makeNegative(int num) { return num > 0 ? num*(-1) : num; }
Java
UTF-8
6,672
2.578125
3
[]
no_license
package com.parkinglot; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import javax.websocket.server.PathParam; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.parkinglot.model.ParkingArea; import com.parkinglot.error.ParkingError; import com.parkinglot.error.ParkingResponse; import com.parkinglot.error.ParkingSuccess; import com.parkinglot.model.ParkingTicket; import com.parkinglot.service.ParkingService; import com.parkinglot.service.ParkingValidationService; import org.springframework.core.env.Environment; /** * Represents a controller class which contains REST end points for parking system. */ @RestController public class ParkingLotAPI { @Autowired private Environment env; @Autowired private ParkingArea parkingArea; @Autowired private ParkingService parkingService; @Autowired private ParkingValidationService parkingValidationService; /** * Rest endpoint URL to get all registration numbers of cars parked in parking. */ @RequestMapping("/parkingapi/getallcarregistration") public List<String> getAllCarRegistrationNumbers() { return parkingService.getRegistrationOfParkedVehicle("C"); } /** * Rest endpoint URL to get all registration numbers of bikes parked in parking. */ @RequestMapping("/parkingapi/getallbikeregistration") public List<String> getAllBikeRegistrationNumbers() { return parkingService.getRegistrationOfParkedVehicle("B"); } /** * Rest endpoint URL to get parking slot number of vehicle. * @param type: this is the type of vehicle * @param registrationNumber: registration number of vehicle * * @return ParkingResponse: return error response if inputs are not correct or * we unable to find that vehicle. in case of success it return success response which contains parking slot number. */ @RequestMapping("/parkingapi/getparkingslot/{type}/{registrationNumber}") public ParkingResponse getParkingSlotByRegistrationNumber(@PathVariable(value="type") String type,@PathVariable(value="registrationNumber") String registrationNumber) { boolean isFound=false; ParkingTicket[] tickets; if(!parkingValidationService.validateTypeOfVehicle(type)) {return new ParkingError(env.getProperty("parking.errorcode"),env.getProperty("parking.invalidvehicle.message"));} if(!parkingValidationService.validateRegistrationNumber(registrationNumber)) { return new ParkingError(env.getProperty("parking.errorcode"),env.getProperty("parking.unregistervehicle.message")); } tickets=parkingArea.getParkingSlots(type); for(int i=0;i<tickets.length;i++) { ParkingTicket temp=tickets[i]; if(temp.getRegistrationNumber()!=null && temp.getRegistrationNumber().equalsIgnoreCase(registrationNumber)) { isFound=true; return new ParkingSuccess(env.getProperty("parking.successcode"), env.getProperty("parking.parkedslot.success.message")+type+temp.getSlotNumber()); } } if(!isFound) return new ParkingError(env.getProperty("parking.errorcode"),env.getProperty("parking.notparked.message")); else return null; } /** * Rest endpoint URL to get park vehicle. * @param type: this is the type of vehicle * @param registrationNumber: registration number of vehicle * * @return ParkingResponse: return error response if inputs are not correct or * parking is full. in case of success it return success response . */ @RequestMapping("/parkingapi/park/{type}/{registrationNumber}") public ParkingResponse parkVehical(@PathVariable(value="type") String type,@PathVariable(value="registrationNumber") String registrationNumber) { boolean isParked=false; if(!parkingValidationService.validateTypeOfVehicle(type)) {return new ParkingError(env.getProperty("parking.errorcode"),env.getProperty("parking.invalidvehicle.message"));} if(!parkingValidationService.validateRegistrationNumber(registrationNumber)) { return new ParkingError(env.getProperty("parking.errorcode"),env.getProperty("parking.unregistervehicle.message")); } ParkingTicket[] parkingSlots=parkingArea.getParkingSlots(type); for(int i=0;i<parkingSlots.length;i++) { if(parkingSlots[i].isAvailable()) { parkingSlots[i]=new ParkingTicket(registrationNumber, i+1, false); isParked=true; break; } } if(isParked) { return new ParkingSuccess(env.getProperty("parking.successcode"),env.getProperty("parking.success.message")); } else { return new ParkingError(env.getProperty("parking.errorcode"),env.getProperty("parking.full.message")); } } /** * Rest endpoint URL to get unpark vehicle. * @param type: this is the type of vehicle * @param registrationNumber: registration number of vehicle * * @return ParkingResponse: return error response if inputs are not correct or * we don't have that vehicle parked. in case of success it return success response . */ @RequestMapping("/parkingapi/unpark/{type}/{registrationNumber}") public ParkingResponse unparkVehical(@PathVariable(value="type") String type,@PathVariable(value="registrationNumber") String registrationNumber) { boolean isUnParked=false; if(!parkingValidationService.validateTypeOfVehicle(type)) {return new ParkingError(env.getProperty("parking.errorcode"),env.getProperty("parking.invalidvehicle.message"));} if(!parkingValidationService.validateRegistrationNumber(registrationNumber)) { return new ParkingError(env.getProperty("parking.errorcode"),env.getProperty("parking.unregistervehicle.message")); } ParkingTicket[] parkingSlots=parkingArea.getParkingSlots(type); for(int i=0;i<parkingSlots.length;i++) { if(parkingSlots[i].getRegistrationNumber()!=null && parkingSlots[i].getRegistrationNumber().equalsIgnoreCase(registrationNumber)) { parkingSlots[i]=new ParkingTicket(null, i+1, true); isUnParked=true; break; } } if(isUnParked) { return new ParkingSuccess(env.getProperty("parking.successcode"),env.getProperty("parking.unparked.success.message")); } else { return new ParkingError(env.getProperty("parking.errorcode"),env.getProperty("parking.unparked.message")); } } }
PHP
UTF-8
1,165
2.515625
3
[]
no_license
<?php include'/customers/9/3/c/battlelegends.fr/httpd.www/db/config.php'; /* PAGINATOR */ $sql2 = "SELECT COUNT(id) AS nbUsers FROM a_users"; $requsers = mysql_query($sql2) or die('Erreur SQL !<br />' . $sql2 . '<br />' . mysql_error()); $dataUsers = mysql_fetch_assoc($requsers); if (isset($_GET['p'])) { $cPage = $_GET['p']; } else { $cPage = 1; } $nbUsers = $dataUsers['nbUsers']; $perPage = 4; $nbPage = ceil($nbUsers / $perPage); $start = (($cPage - 1) * $perPage); /* Selectionner tous les utilisateurs et leur rôle */ $sql = "SELECT a_users.id as id_user, a_users.username as username, a_users.email as email, a_users.avatar as avatar, a_users.pseudo as pseudo, a_users.id_roles as id_roles, a_roles.nom as nom" . " FROM a_users " . " INNER JOIN a_roles " . " ON a_users.id_roles = a_roles.id" . " LIMIT $start, 4"; // on lance la requête (mysql_query) et on impose un message d'erreur si la requête ne se passe pas bien (or die) $utilisateur = mysql_query($sql) or die('Erreur SQL !<br />' . $sql2 . '<br />' . mysql_error()); // on libère l'espace mémoire alloué pour cette interrogation de la base
Java
UTF-8
2,662
2.078125
2
[]
no_license
/** * Proyecto: IMSS - SSDC * * Archivo: CursoEntity.java * * Creado: Oct 13, 2011 * * Derechos Reservados de copia (c) - INAP / * * Instituto Mexicano del Seguro Social - 2011 */ package mx.gob.imss.cia.ssdc.cdv.integracion.entity; import java.io.Serializable; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.Table; import org.hibernate.annotations.GenericGenerator; /** * @author propietario * */ @Entity @Table(name = "CDC_CURSO") public class CursoEntity implements Serializable { private static final long serialVersionUID = 1L; @Id @Column(name = "cve_curso") @GenericGenerator(name = "increment", strategy = "increment") @GeneratedValue(generator = "increment") private Long cveCurso; @ManyToOne(cascade = CascadeType.ALL) @JoinColumn(name = "cve_tip_ventanilla") private TipoVentanillaEntity tipoVentanilla; @Column(name = "nom_curso") private String nombreCurso; @ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "cursos") private List<CdtPerfilPersonalEntity> cdtPerfilPersonal; /** * @return the cveCurso */ public Long getCveCurso() { return cveCurso; } /** * @param cveCurso * the cveCurso to set */ public void setCveCurso(Long cveCurso) { this.cveCurso = cveCurso; } /** * @return the tipoVentanilla */ public TipoVentanillaEntity getTipoVentanilla() { return tipoVentanilla; } /** * @param tipoVentanilla * the tipoVentanilla to set */ public void setTipoVentanilla(TipoVentanillaEntity tipoVentanilla) { this.tipoVentanilla = tipoVentanilla; } /** * @return the nombreCurso */ public String getNombreCurso() { return nombreCurso; } /** * @param nombreCurso * the nombreCurso to set */ public void setNombreCurso(String nombreCurso) { this.nombreCurso = nombreCurso; } /** * @return the cdtPerfilPersonal */ public List<CdtPerfilPersonalEntity> getCdtPerfilPersonal() { return cdtPerfilPersonal; } /** * @param cdtPerfilPersonal * the cdtPerfilPersonal to set */ public void setCdtPerfilPersonal( List<CdtPerfilPersonalEntity> cdtPerfilPersonal) { this.cdtPerfilPersonal = cdtPerfilPersonal; } }
Java
UTF-8
903
2.359375
2
[]
no_license
package com.example.demospringsecurity.account; import lombok.RequiredArgsConstructor; import org.springframework.boot.ApplicationArguments; import org.springframework.boot.ApplicationRunner; import org.springframework.stereotype.Component; @Component @RequiredArgsConstructor public class AccountSupport implements ApplicationRunner { private final AccountService accountService; @Override public void run(ApplicationArguments args) throws Exception { Account user = Account.builder() .username("jkj") .password("1234") .role("USER") .build(); Account admin = Account.builder() .username("admin") .password("1234") .role("ADMIN") .build(); accountService.createNew(user); accountService.createNew(admin); } }
Java
UTF-8
3,205
3.53125
4
[]
no_license
package com.charles.graph; import java.util.ArrayList; import java.util.List; /** * * @author charleszuo@126.com * 图的邻接矩阵表示法 */ public class MatrixGraph { private String[] vertexs; private int[][] edges; private int numVertex; public static int INFINITY = 65535; private boolean[] visited; public MatrixGraph(int numVertex){ this.numVertex = numVertex; vertexs = new String[numVertex]; edges = new int[numVertex][numVertex]; for(int i = 0; i < numVertex; i++){ for(int j = 0; j < numVertex; j++){ if(i == j){ edges[i][j] = 0; }else{ edges[i][j] = INFINITY; } } } visited = new boolean[numVertex]; } public String[] getVertexs() { return vertexs; } public void setVertexs(String[] vertexs) { this.vertexs = vertexs; } public int[][] getEdges() { return edges; } public void setEdges(int[][] edges) { this.edges = edges; } public int getNumVertex() { return numVertex; } public boolean[] getVisited() { return visited; } /** * * @param index 顶点的序号 * 对连通分量的深度优先搜索 */ public void DFS(int index){ visited[index] = true; System.out.println("Node " + vertexs[index]); for(int j = 0; j < numVertex; j++){ if(visited[j] != true && edges[index][j] == 1){ DFS(j); } } } /** * 对所有顶点进行深度优先搜索, 采用递归 * 如果存在多个连通分量,对每个连通分量都做DFS */ public void DFSTraverse(){ for(int i = 0; i < numVertex; i++){ if(visited[i] != true){ DFS(i); } } } /** * 对所有顶点进行深度优先搜索,采用队列 * 如果存在多个连通分量,对每个连通分量都做BFS */ public void BFSTraverse(){ List<Integer> queue = new ArrayList<Integer>(); for(int i = 0; i < numVertex; i++){ if(visited[i] != true){ visited[i] = true; queue.add(i); while(queue.size() != 0){ int vertexIndex = queue.remove(0); System.out.println("Node " + vertexs[vertexIndex]); for(int j = 0; j < numVertex; j++){ if(visited[j] != true && edges[vertexIndex][j] == 1){ queue.add(j); visited[j] = true; } } } } } } public static void main(String[] args){ MatrixGraph mGraph = new MatrixGraph(9); String[] vertexs = mGraph.getVertexs(); vertexs[0] = "A"; vertexs[1] = "B"; vertexs[2] = "C"; vertexs[3] = "D"; vertexs[4] = "E"; vertexs[5] = "F"; vertexs[6] = "G"; vertexs[7] = "H"; vertexs[8] = "I"; int[][] edges = mGraph.getEdges(); edges[0][1] = 1; edges[0][5] = 1; edges[1][0] = 1; edges[1][2] = 1; edges[1][6] = 1; edges[1][8] = 1; edges[2][1] = 1; edges[2][3] = 1; edges[2][8] = 1; edges[3][2] = 1; edges[3][4] = 1; edges[3][6] = 1; edges[3][7] = 1; edges[3][8] = 1; edges[4][3] = 1; edges[4][5] = 1; edges[4][7] = 1; edges[5][0] = 1; edges[5][4] = 1; edges[5][6] = 1; edges[6][1] = 1; edges[6][3] = 1; edges[6][5] = 1; edges[6][7] = 1; edges[7][3] = 1; edges[7][4] = 1; edges[7][6] = 1; edges[8][1] = 1; edges[8][2] = 1; edges[8][3] = 1; // mGraph.DFSTraverse(); mGraph.BFSTraverse(); } }
Java
UTF-8
328
2.328125
2
[]
no_license
package dao.definitions; import java.util.List; import model.Reaction; public interface ReactionDAO { public Reaction find(Integer id); public List<Reaction> list(); public void create(Reaction entity); public void update(Integer id, Reaction entity); public boolean remove(Integer id); }
Java
UTF-8
4,887
2.390625
2
[]
no_license
package groovyjarjarantlr; import groovyjarjarantlr.ASdebug.IASDebugStream; import groovyjarjarantlr.collections.impl.BitSet; import java.util.Comparator; import java.util.List; import java.util.Map; public class TokenStreamRewriteEngine implements IASDebugStream, TokenStream { protected Map DW; protected int FH; protected TokenStream Hw; protected List j6; protected BitSet v5; class 1 implements Comparator { public int compare(Object obj, Object obj2) { RewriteOperation rewriteOperation = (RewriteOperation) obj; RewriteOperation rewriteOperation2 = (RewriteOperation) obj2; if (rewriteOperation.DW < rewriteOperation2.DW) { return -1; } if (rewriteOperation.DW > rewriteOperation2.DW) { return 1; } return 0; } } static class RewriteOperation { protected int DW; protected String FH; public int j6(StringBuffer stringBuffer) { return this.DW; } public String toString() { String name = getClass().getName(); return new StringBuffer().append(name.substring(name.indexOf(36) + 1, name.length())).append("@").append(this.DW).append('\"').append(this.FH).append('\"').toString(); } } static class ReplaceOp extends RewriteOperation { protected int j6; public int j6(StringBuffer stringBuffer) { if (this.FH != null) { stringBuffer.append(this.FH); } return this.j6 + 1; } } static class DeleteOp extends ReplaceOp { } static class InsertBeforeOp extends RewriteOperation { public int j6(StringBuffer stringBuffer) { stringBuffer.append(this.FH); return this.DW; } } public Token j6() { TokenWithIndex tokenWithIndex; do { tokenWithIndex = (TokenWithIndex) this.Hw.j6(); if (tokenWithIndex != null) { tokenWithIndex.Hw(this.FH); if (tokenWithIndex.Hw() != 1) { this.j6.add(tokenWithIndex); } this.FH++; } if (tokenWithIndex == null) { break; } } while (this.v5.Hw(tokenWithIndex.Hw())); return tokenWithIndex; } public TokenWithIndex j6(int i) { return (TokenWithIndex) this.j6.get(i); } public int DW() { return this.j6.size(); } public String j6(int i, int i2) { StringBuffer stringBuffer = new StringBuffer(); while (i >= 0 && i <= i2 && i < this.j6.size()) { stringBuffer.append(j6(i).FH()); i++; } return stringBuffer.toString(); } public String toString() { return DW(0, DW() - 1); } public String DW(int i, int i2) { return j6("default", i, i2); } public String j6(String str, int i, int i2) { List list = (List) this.DW.get(str); if (list == null || list.size() == 0) { return j6(i, i2); } StringBuffer stringBuffer = new StringBuffer(); int i3 = 0; int i4 = i; while (i4 >= 0 && i4 <= i2 && i4 < this.j6.size()) { RewriteOperation rewriteOperation; int i5; if (i3 < list.size()) { rewriteOperation = (RewriteOperation) list.get(i3); while (rewriteOperation.DW < i4 && i3 < list.size()) { i3++; if (i3 < list.size()) { rewriteOperation = (RewriteOperation) list.get(i3); } } i5 = i4; i4 = i3; i3 = i5; while (i3 == rewriteOperation.DW && i4 < list.size()) { i3 = rewriteOperation.j6(stringBuffer); i4++; if (i4 < list.size()) { rewriteOperation = (RewriteOperation) list.get(i4); } } } else { i5 = i4; i4 = i3; i3 = i5; } if (i3 <= i2) { stringBuffer.append(j6(i3).FH()); i = i3 + 1; i3 = i4; i4 = i; } else { i5 = i3; i3 = i4; i4 = i5; } } while (i3 < list.size()) { rewriteOperation = (RewriteOperation) list.get(i3); if (rewriteOperation.DW >= FH()) { rewriteOperation.j6(stringBuffer); } i3++; } return stringBuffer.toString(); } public int FH() { return this.j6.size(); } }
Java
UTF-8
651
1.703125
2
[]
no_license
package org.renhj.blog.mapper; import org.junit.Test; import org.renhj.blog.BlogApplicationTests; import org.renhj.blog.pojo.entity.PostEntity; import org.renhj.blog.pojo.vo.BlogsVo; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import java.util.List; import static org.junit.Assert.*; public class PostMapperTest extends BlogApplicationTests { @Autowired private PostMapper postMapper; @Test public void getBlogs() { List<BlogsVo> posts = postMapper.findPostsByUsername("admin"); System.out.println(posts); } }
C++
UTF-8
865
3.765625
4
[ "MIT" ]
permissive
// Pattern #include <iostream> using namespace std; int main() { int n, i, no; cin >> n; int row = 1; while (row <= n) { // 1. print spaces n-row times i = 1; while (i <= n - row) { cout << ' '; // Printing space i = i + 1; } // 2. print increasing numbers starting from row, do this task row times i = 1, no = row; while (i <= row) { cout << no; no = no + 1; i = i + 1; } // 3. print decresing numbers starting from 2*row-2, do this task (row-1)times i = 1, no = 2 * row - 2; while (i <= row - 1) { cout << no; no = no - 1; i = i + 1; } row = row + 1; cout << endl; } cout << endl; return 0; }
JavaScript
UTF-8
2,263
2.71875
3
[]
no_license
import React, { Fragment } from 'react'; class List extends React.Component { state = { isEdit: false, newData: { name: "", gender: "" }, } toggleRow = () => { var isEdit = this.state.isEdit this.setState({ isEdit: !isEdit }, console.log(isEdit)) } renderForm = () => { var row = this.props.row var index = this.props.index return ( <ul> <li>{index + 1}</li> <li>{row.name}</li> <li>{row.gender}</li> <li> <button type="submit" onClick={() => this.props.DeleteRow(index)}>Decrease</button> </li> <li> <button type="submit" onClick={() => this.toggleRow()}>Edit</button> </li> </ul> ) } updateRow = (event) => { event.preventDefault() this.props.updateRow(this.props.index, this.state.newData) this.toggleRow() } Value = () => { this.setState({ newData: { ...this.state.newData, [this.input.name]: this.input.value, [this.context.name]: this.context.value } }, console.log("edited", this.state.newData)) } updateForm = () => { var row = this.props.row return ( <form onSubmit={this.updateRow}> <input type="text" name="name" ref={value => this.input = value} defaultValue={row.name} onChange={this.props.getValue} placeholder="Please Enter Your Name...." /> <select name="gender" ref={value => this.context = value} defaultValue={row.gender} onChange={this.props.getValue} > <option>Select Your Gender</option> <option>Female</option> <option>Male</option> </select> <button type="submit"onClick={this.Value}>Update</button> </form> ) } render() { var isEdit = this.state.isEdit return ( <Fragment> {isEdit ? this.updateForm() : this.renderForm()} </Fragment> ) } } export default List
Python
UTF-8
2,562
2.796875
3
[ "MIT" ]
permissive
# coding=utf-8 # # created by kpe on 09.Aug.2019 at 15:26 # from __future__ import absolute_import, division, print_function import os import re from urllib import request from urllib.request import urlretrieve from tqdm import tqdm def fetch_url(url, fetch_dir, check_content_length=False): """ Downloads the specified url to a local dir. :param url: :param fetch_dir: :param check_content_length: :return: local path of the downloaded file """ local_file_name = url.split('/')[-1] local_path = os.path.join(fetch_dir, local_file_name) already_fetched = False if os.path.isfile(local_path): if check_content_length: content_length = int(request.urlopen(url).getheader("Content-Length")) already_fetched = os.stat(local_path).st_size == content_length else: already_fetched = True if already_fetched: print("Already fetched: ", local_file_name) else: os.makedirs(fetch_dir, exist_ok=True) with tqdm(unit='B', unit_scale=True, miniters=1, desc=local_file_name) as pbar: def report_hook(count, block_size, total_size): if total_size: pbar.total = total_size pbar.update(block_size) urlretrieve(url, local_path, report_hook, data=None) return local_path def unpack_archive(archive_file, unpack_dir=None): """ Unpacks a zip or a tar.{gz,bz2,xz} into the given dir. :param: zip_dir - if None unpacks in a dir with the same name as the zip file. """ re_ext = re.compile(r'(\.zip|\.tar\.(?:gz|bz2|xz))$') archive_ext = re_ext.findall(archive_file) if len(archive_ext) < 1: raise AttributeError("Expecting .zip or tar.gz file, but: [{}]".format(archive_file)) archive_ext = archive_ext[0] if unpack_dir is None: unpack_dir = os.path.basename(archive_file) unpack_dir = unpack_dir[:unpack_dir.rindex(archive_ext)] unpack_dir = os.path.join(os.path.dirname(archive_file), unpack_dir) if os.path.isdir(unpack_dir): print("already unpacked at: {}".format(unpack_dir)) else: print("extracting to: {}".format(unpack_dir)) if archive_ext == ".zip": import zipfile with zipfile.ZipFile(archive_file, "r") as zf: zf.extractall(unpack_dir) else: import tarfile with tarfile.open(archive_file, "r:*") as zf: zf.extractall(unpack_dir) return unpack_dir
C#
UTF-8
8,288
2.625
3
[]
no_license
using System.Collections.Generic; using System.Linq; namespace UserApi.Domain.Aggregates.Users { public class User : Framework.Domain.SeedWork.AggregateRoot { #region Static Member(s) public static Framework.Result<User> Create (string username, string password, string emailAddress, int? role, int? gender, string firstName, string lastName, string cellPhoneNumber) { var result = new Framework.Result<User>(); // ************************************************** var usernameResult = ValueObjects.Username.Create(value: username); result.WithErrors(errors: usernameResult.Errors); // ************************************************** // ************************************************** var passwordResult = ValueObjects.Password.Create(value: password); result.WithErrors(errors: passwordResult.Errors); // ************************************************** // ************************************************** var emailAddressResult = SharedKernel.EmailAddress.Create(value: emailAddress); result.WithErrors(errors: emailAddressResult.Errors); // ************************************************** // ************************************************** var roleResult = ValueObjects.Role.GetByValue(value: role); result.WithErrors(errors: roleResult.Errors); // ************************************************** // ************************************************** var fullNameResult = SharedKernel.FullName.Create (gender: gender, firstName: firstName, lastName: lastName); result.WithErrors(errors: fullNameResult.Errors); // ************************************************** // ************************************************** var cellPhoneNumberResult = SharedKernel.CellPhoneNumber.Create(value: cellPhoneNumber); result.WithErrors(errors: cellPhoneNumberResult.Errors); // ************************************************** if (result.IsFailed) { return result; } var user = new User(username: usernameResult.Value, password: passwordResult.Value, emailAddress: emailAddressResult.Value, role: roleResult.Value, fullName: fullNameResult.Value, cellPhoneNumber: cellPhoneNumberResult.Value); result.WithValue(value: user); return result; } #endregion /Static Member(s) private User() { } private User (ValueObjects.Username username, ValueObjects.Password password, ValueObjects.Role role, SharedKernel.FullName fullName, SharedKernel.EmailAddress emailAddress, SharedKernel.CellPhoneNumber cellPhoneNumber) { Role = role; Username = username; Password = password; FullName = fullName; EmailAddress = emailAddress; CellPhoneNumber = cellPhoneNumber; } public ValueObjects.Role Role { get; private set; } public ValueObjects.Username Username { get; private set; } public ValueObjects.Password Password { get; private set; } public SharedKernel.FullName FullName { get; private set; } public SharedKernel.EmailAddress EmailAddress { get; private set; } public SharedKernel.CellPhoneNumber CellPhoneNumber { get; private set; } // ********** private readonly List<Groups.Group> _groups = new(); public virtual IReadOnlyList<Groups.Group> Groups { get { return _groups; } } // ********** public Framework.Result Update(string username, string password, string emailAddress, int? role, int? gender, string firstName, string lastName, string cellPhoneNumber) { var result = Create(username: username, password: password, emailAddress: emailAddress, role: role, gender: gender, firstName: firstName, lastName: lastName, cellPhoneNumber: cellPhoneNumber); if (result.IsFailed) { return result.ToResult(); } Role = result.Value.Role; Username = result.Value.Username; Password = result.Value.Password; FullName = result.Value.FullName; EmailAddress = result.Value.EmailAddress; CellPhoneNumber = result.Value.CellPhoneNumber; return result; } public Framework.Result ChangePassword (string newPassword, string confirmNewPassword) { var result = new Framework.Result(); // ************************************************** var newPasswordResult = ValueObjects.Password.Create(value: newPassword); if (newPasswordResult.IsFailed) { result.WithErrors(errors: newPasswordResult.Errors); return result; } // ************************************************** // ************************************************** var confirmNewPasswordResult = ValueObjects.Password.Create(value: confirmNewPassword); if (confirmNewPasswordResult.IsFailed) { result.WithErrors(errors: confirmNewPasswordResult.Errors); return result; } // ************************************************** // ************************************************** if (newPasswordResult.Value != confirmNewPasswordResult.Value) { string errorMessage = string.Format (Resources.Messages.Validations.RegularExpression, Resources.DataDictionary.ConfirmPassword); result.WithError(errorMessage: errorMessage); return result; } // ************************************************** Password = newPasswordResult.Value; RaiseDomainEvent (new Events.UserPasswordChangedEvent (fullName: FullName, emailAddress: EmailAddress)); return result; } public Framework.Result AssignToGroup(Groups.Group group) { var result = new Framework.Result(); // ************************************************** var hasAny = _groups.Any(c => c.Id == group.Id); if (hasAny) { var errorMessage = string.Format (Resources.Messages.Validations.Repetitive, Resources.DataDictionary.Group); result.WithError(errorMessage: errorMessage); return result; } // ************************************************** _groups.Add(group); return result; } public Framework.Result RemoveFromGroup(Groups.Group group) { var result = new Framework.Result(); // ************************************************** var foundedGroup = _groups.FirstOrDefault(c => c.Id == group.Id); if (foundedGroup == null) { var errorMessage = string.Format (Resources.Messages.Validations.NotFound, Resources.DataDictionary.Group); result.WithError(errorMessage: errorMessage); return result; } // ************************************************** _groups.Remove(foundedGroup); return result; } } }
C
UTF-8
2,644
2.890625
3
[]
no_license
#define NULL ((void*)0) typedef unsigned long size_t; // Customize by platform. typedef long intptr_t; typedef unsigned long uintptr_t; typedef long scalar_t__; // Either arithmetic or pointer type. /* By default, we understand bool (as a convenience). */ typedef int bool; #define false 0 #define true 1 /* Forward declarations */ typedef struct TYPE_3__ TYPE_1__ ; /* Type definitions */ struct TYPE_3__ {char* input; char* token_terminator; scalar_t__ token_type; int input_length; } ; typedef TYPE_1__ JsonLexContext ; /* Variables and functions */ scalar_t__ IS_HIGHBIT_SET (char const) ; scalar_t__ JSON_TOKEN_END ; int errcontext (char*,int,char const*,char*,char const*) ; int /*<<< orphan*/ memcpy (char*,char const*,int) ; char* palloc (int) ; int /*<<< orphan*/ pg_mblen (char const*) ; __attribute__((used)) static int report_json_context(JsonLexContext *lex) { const char *context_start; const char *context_end; const char *line_start; int line_number; char *ctxt; int ctxtlen; const char *prefix; const char *suffix; /* Choose boundaries for the part of the input we will display */ context_start = lex->input; context_end = lex->token_terminator; line_start = context_start; line_number = 1; for (;;) { /* Always advance over newlines */ if (context_start < context_end && *context_start == '\n') { context_start++; line_start = context_start; line_number++; continue; } /* Otherwise, done as soon as we are close enough to context_end */ if (context_end - context_start < 50) break; /* Advance to next multibyte character */ if (IS_HIGHBIT_SET(*context_start)) context_start += pg_mblen(context_start); else context_start++; } /* * We add "..." to indicate that the excerpt doesn't start at the * beginning of the line ... but if we're within 3 characters of the * beginning of the line, we might as well just show the whole line. */ if (context_start - line_start <= 3) context_start = line_start; /* Get a null-terminated copy of the data to present */ ctxtlen = context_end - context_start; ctxt = palloc(ctxtlen + 1); memcpy(ctxt, context_start, ctxtlen); ctxt[ctxtlen] = '\0'; /* * Show the context, prefixing "..." if not starting at start of line, and * suffixing "..." if not ending at end of line. */ prefix = (context_start > line_start) ? "..." : ""; suffix = (lex->token_type != JSON_TOKEN_END && context_end - lex->input < lex->input_length && *context_end != '\n' && *context_end != '\r') ? "..." : ""; return errcontext("JSON data, line %d: %s%s%s", line_number, prefix, ctxt, suffix); }
JavaScript
UTF-8
614
2.953125
3
[]
no_license
function anyUserFieldContainsSearch(user, search) { const searchLower = search.toLowerCase() return ['name', 'surname', 'region', 'email', 'phone'].some(field => user[field].toLowerCase().includes(searchLower)) } function sortByField(a, b, {field, ascending}) { const ascendingMultiplier = ascending ? 1 : -1 return ((a[field] > b[field]) ? 1 : ((b[field] > a[field]) ? -1 : 0)) * ascendingMultiplier; } export default function filterAndSortUsers(users, search, sortOn) { return (search ? users.filter(u => anyUserFieldContainsSearch(u, search)) : users ).sort((a, b) => sortByField(a, b, sortOn)) }
Go
UTF-8
793
3.421875
3
[]
no_license
package main import ( "bytes" "fmt" "strconv" "math" ) func main() { fmt.Println(byte()) } func reverse(x int) int { if x==0{ return 0 } if x<0 { num, err :=strconv.ParseInt(reverseStr(strconv.Itoa(-x)), 10, 64) if err!=nil{ return 0 } if num > math.MaxInt32{ return 0 } return -int(num) }else{ num, err :=strconv.ParseInt(reverseStr(strconv.Itoa(x)), 10, 64) if err!=nil{ return 0 } if num > math.MaxInt32{ return 0 } return int(num) } } //int to string func reverseStr(s string)string{ var buffer bytes.Buffer var i int addr :=findNotZero(s) for i=addr;i>=0;i--{ buffer.WriteByte(s[i]) } return buffer.String() } func findNotZero(s string) int { var i int for i=len(s)-1;i>=0;i++ { if s[i]!=0 { return i } } return 0 }
Python
UTF-8
185
2.734375
3
[]
no_license
def minSubsequence(nums): nums.sort(reverse=True) tot, s = sum(nums), 0 for i, num in enumerate(nums): s += num if s > tot - s: return nums[:i+1]
C#
UTF-8
5,549
2.734375
3
[]
no_license
using System; using System.Diagnostics; using System.Net.Sockets; using System.Runtime.Serialization.Formatters.Binary; using System.Threading; using System.Threading.Tasks; using PostOffice; namespace ChatProject { public class TcpClientWrapper { #region Variables and Declarations private readonly TcpClient _socket = new TcpClient(); public CancellationTokenSource TokenSourceCheckingParcels; public event EventHandler<Parcel> ParcelArrived; public event EventHandler UserAuthorized; public event EventHandler UserNotAuthorized; private readonly BinaryFormatter _formatter = new BinaryFormatter(); public bool Authorized = false; public bool NewUser = false; private Parcel _baseParcel; public bool SocketConnected { get { return _socket.Connected; } } #endregion #region Constructor public TcpClientWrapper(Connection c, Parcel firstMsg) { _baseParcel = new Parcel(firstMsg.UserName, firstMsg.TimeStamp, firstMsg.Msg, firstMsg.Colour); StartClient(c, firstMsg); } #endregion #region Client Startup private void StartClient(Connection c, Parcel firstMsg) { try { _socket.BeginConnect(c.IP, c.Port, new AsyncCallback(ConnectCallback), firstMsg); } catch (Exception e) { Debug.WriteLine("beginning to connect: " + e); } } private void ConnectCallback(IAsyncResult ar) { SendParcel((Parcel)ar.AsyncState); TokenSourceCheckingParcels = new CancellationTokenSource(); Task readParcels = new Task(CheckForParcels, TokenSourceCheckingParcels.Token); readParcels.Start(); } #endregion #region Receiving Messages private void CheckForParcels() { while (!TokenSourceCheckingParcels.IsCancellationRequested) { try { if (_socket.Connected) { NetworkStream networkStream = _socket.GetStream(); if (networkStream.DataAvailable) { Parcel p = (Parcel) _formatter.Deserialize(networkStream); if (Authorized) { OnParcelArrived(p); } else { if (p.Msg.Contains("***Checked")) { Authorized = true; if (NewUser) { OnNewUser(EventArgs.Empty); } ExtractUserName(p); } if (p.Msg.Contains("***nosuchuser")) { if (NewUser) { OnUserNotAuthorized(EventArgs.Empty); } } } } } else { TokenSourceCheckingParcels.Cancel(); } //await Task.Delay(500); } catch (Exception e) { TokenSourceCheckingParcels.Cancel(); Console.WriteLine(e); } } } private void ExtractUserName(Parcel parcel) { _baseParcel.UserName = parcel.Msg.Substring("***Checked".Length, parcel.Msg.IndexOf("***Name") - "***Checked".Length); } #endregion #region Event Handlers private void OnUserNotAuthorized(EventArgs e) { EventHandler handler = UserNotAuthorized; if (handler == null) return; handler(this, e); } private void OnNewUser(EventArgs e) { EventHandler handler = UserAuthorized; if (handler == null) return; handler(this, e); } private void OnParcelArrived(Parcel arrivedParcel) { EventHandler<Parcel> handler = ParcelArrived; if (handler == null) return; handler(this, arrivedParcel); } #endregion #region Sending Messages private void SendParcel(Parcel parcelToSend) { if (!_socket.Connected) return; NetworkStream stream = _socket.GetStream(); _formatter.Serialize(stream, parcelToSend); stream.Flush(); Debug.WriteLine("tcp client sending " + parcelToSend); } public void SendParcel(string txtToSend) { _baseParcel.TimeStamp = DateTime.Now; _baseParcel.Msg = txtToSend; SendParcel(_baseParcel); } #endregion #region Dispose public void Dispose() { ParcelArrived = null; _socket.Close(); } #endregion } }
PHP
UTF-8
1,243
2.765625
3
[]
no_license
<?php /** * Created by PhpStorm. * User: Yacine * Date: 01/11/2017 * Time: 23:46 */ namespace app\models; class MaladieChronique { private $idMaladie; private $maladie; private $patient; private $medecin; /** * @return int */ public function getIdMaladie() { return $this->idMaladie; } /** * @param int $idMaladie */ public function setIdMaladie($idMaladie) { $this->idMaladie = $idMaladie; } /** * @return String */ public function getMaladie() { return $this->maladie; } /** * @param String $maladie */ public function setMaladie($maladie) { $this->maladie = $maladie; } /** * @return Patient */ public function getPatient() { return $this->patient; } /** * @param Patient $patient */ public function setPatient($patient) { $this->patient = $patient; } /** * @return Medecin */ public function getMedecin() { return $this->medecin; } /** * @param Medecin $medecin */ public function setMedecin($medecin) { $this->medecin = $medecin; } }
C#
UTF-8
1,355
3.03125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; namespace DDD { public class MessageBus : IMessageBus { private readonly List<Route> routes = new List<Route>(); public void Publish(object message) { var messageType = message.GetType(); var routesForThisMessage = GetRoutes(messageType); var deadRefs = routesForThisMessage .Where(_ => _.Target == null) .ToArray(); foreach (var r in deadRefs) { routes.Remove(r); } var liveRefs = routesForThisMessage.Except(deadRefs); foreach (var r in liveRefs) { InvokeHandler(r.Target, message); } } public void InvokeHandler(Action<object> handler, object message) { try { handler.Invoke(message); } catch { } } private IEnumerable<Route> GetRoutes(Type messageType) { return routes .Where(_ => _.MessageType.IsAssignableFrom(messageType)) .ToArray(); } public void Subscribe(Type messageType, Action<object> handler) { routes.Add(new Route(messageType, handler)); } } }
Python
UTF-8
1,087
2.609375
3
[]
no_license
from flask import Flask from flask import abort from flask import render_template import data from work_with_data import sorted_hotels_by_price from work_with_data import get_tours_by_departure app = Flask(__name__) @app.route('/') def main(): hotels_by_price = sorted_hotels_by_price(data.tours) return render_template("index.html", data=data, hotels_by_price=hotels_by_price) @app.route('/departures/<departure>/') def departures(departure): from_city = data.departures.get(departure) if from_city is None: abort(404) tours_by_departure = get_tours_by_departure(data, departure) return render_template("departure.html", data=data, departure=from_city, tours_by_departure=tours_by_departure) @app.route('/tours/<int:id>/') def tours(id): tour = data.tours.get(id) if tour is None: abort(404) departure = data.departures.get(tour["departure"]) if departure is None: abort(404) return render_template("tour.html", data=data, tour=tour, departure=departure) if __name__ == '__main__': app.run()
JavaScript
UTF-8
472
3.3125
3
[]
no_license
class food{ constructor(game) { this.game = game; this.x = 0; this.y = 0; this.grid = 20; this.update(); this.draw() } update(){ this.x = (Math.floor(Math.random() * (19 - 0)))*this.grid; this.y = (Math.floor(Math.random() * (19 - 0)))*this.grid; } draw(){ this.game.context.fillStyle = 'yellow'; this.game.context.fillRect(this.x, this.y, this.grid, this.grid); } }
Go
UTF-8
427
3.921875
4
[]
no_license
package main import "fmt" func add(x int, y int) int { return x + y } func multiply(x, y int) int { return x * y } // Multiple Results func swap(x, y string) (string, string) { return y, x } // Named return values func split(sum int) (x, y int) { x = sum * 4 / 9 y = sum - x return } func main() { fmt.Println(add(9, 2)) fmt.Println(multiply(9, 2)) fmt.Println(swap("World!", "Hello")) fmt.Println(split(15)) }
Python
UTF-8
435
3.5
4
[]
no_license
import math def PegarEntrada(plano, coordenada): return float(input("Forneça a coordenada {} para o Plano {}: ".format(coordenada, plano))) planoA = PegarEntrada("A", "X"), PegarEntrada("A", "Y") planoB = PegarEntrada("B", "X"), PegarEntrada("B", "Y") preCalculo = (planoA[0]-planoB[0])**2 + (planoA[1]-planoB[1])**2 distancia = math.sqrt(preCalculo) if (distancia>=10): print("longe") else: print("perto")
Python
UTF-8
5,566
2.9375
3
[]
no_license
from scipy.optimize import leastsq, curve_fit from qchem_pytools import figure_settings import numpy as np import pandas as pd class leastsq_object: def __init__(self): print("Usage: specify model function as leastsq_object.model") print("The model should have parameters as an n-tuple, followed by x.") self.model = None def setup(self, model=None, initial=None): if model is not None: """ define some stock functions """ if model == "linear": self.model = lambda x, param: param[0] * x + param[1] elif model == "quadratic": self.model = lambda x, param: param[0] * x**2. + param[1] * x + param[2] elif model == "gaussian": self.model = lambda x, param: param[0] * np.exp(-(x - param[1])**2. / (2. * param[2]**2.)) elif modell == "cbs": self.model = lambda x, param: param[0] + param[1] * x**(-3.) else: self.model = model """ initialise error function """ self.error_function = lambda param, x, y: self.model(x, param) - y if initial is not None: self.initial = initial else: self.initial = np.zeros(6) elif model is None: print("Model function undefined, provide as argument.") def optimise(self, x ,y): if self.model is not None: optparam, success = leastsq( func=self.error_function, x0=self.initial, args=(x, y) ) if success >= 1 and success <= 4: print("Optimisation succeeded.") self.modeled = self.model(x, optparam) self.residuals = self.modeled - y self.sos = np.sum(self.residuals**2.) self.optparam = optparam self.success = True print("Final parameters:\t" + str(optparam)) print("Sum of squares:\t" + str(self.sos)) self.dataframe = pd.DataFrame( data=[self.modeled, y, self.residuals], index=x, columns=["Modelled", "Actual", "Residuals"] ) else: print("Optimisation failed.") else: print("Model function undefined, call setup method") def plot(self): subplot_grid = figure_settings.GenerateSubPlotObject( ColumnNames=["Fit", "Residuals"], NRows=2, NCols=1 ) actual_trace = figure_settings.DefaultScatterObject( X=self.dataframe.index, Y=self.dataframe["Actual"], Name="Actual", ) modelled_trace = figure_settings.DefaultScatterObject( X=self.dataframe.index, Y=self.dataframe["Modelled"], Name="Modelled", Connected=True ) residual_trace = figure_settings.DefaultScatterObject( X=self.dataframe.index, Y=self.dataframe["Residuals"], Name="Residuals" ) subplot_grid.append_trace([actual_trace, modelled_trace], 1, 1) subplot_grid.append_trace(residual_trace, 2, 1) figure_settings.iplot(subplot_grid) class curvefit_object: def __init__(self): print("Usage: specify model function as curvefit_object.model") print("The model should have parameters as an n-tuple, followed by x.") self.model = None self.bounds = {"upper": [], "lower": []} def setup(self, model=None, initial=None, bounds=None): if model is not None: """ define some stock functions here """ if model == "linear": self.model = lambda x, param: param[0] * x + param[1] elif model == "quadratic": self.model = lambda x, param: param[0] * x**2. + param[1] * x + param[2] elif model == "gaussian": self.model = lambda x, param: param[0] * np.exp(-(x - param[1])**2. / (2. * param[2]**2.)) elif modell == "cbs": self.model = lambda x, param: param[0] + param[1] * x**(-3.) else: self.model = model else: raise("ModelError! No model specified as argument!") def fit(self, x, y): if self.model is not None: optparam, covar = curve_fit( f=self.model, xdata=x, ydata=y, p0=self.initial ) colours = figure_settings.GenerateColours(NumPlots=2) actual_trace = figure_settings.DefaultScatterObject( X=x, Y=y, Name="Data", Colour=colours[0] ) model_trace = figure_settings.DefaultScatterObject( X=x, Y=self.model(x, *optparam), Name="Fit", Colour=colours[1] ) layout = figure_settings.DefaultLayoutSettings() figure_settings.iplot( { "data": [actual_trace, model_trace], "layout": layout } ) else: raise("ModelError! No model defined!")
JavaScript
UTF-8
1,495
2.6875
3
[ "MIT" ]
permissive
const getGeometryFromImportedData = (data) =>{ if(data === undefined) return undefined; const parsedData = JSON.parse(data); if(parsedData === undefined) return undefined; if(parsedData.entities === undefined) return undefined; let geometry = []; for(let i=0; i<parsedData.entities.length; i++){ const entity = parsedData.entities[i]; if(entity === undefined) continue; if(entity.type === "Line"){ geometry.push( Elements.line( new Vector(entity.vertices[0].x, entity.vertices[0].y), new Vector(entity.vertices[1].x, entity.vertices[1].y) ) ); continue; } //TODO add support for polylines and arcs } return geometry; } class ImportElement extends Element{ //Constuctor constructor(geometry){ super(geometry); } //Non-chainable methods collision = () => null; getReferencePointOnPoint(point, tolerance){ return null; } //Chainable methods rebuild = (cursorDocumentPosition) => { //console.log("Rebuilding custom element"); return this; } /*render = () => { background("#feda00"); }*/ } Commands.import = function(document){ return new Command( document, "import", () => true, () => File.open((data) => document.addElement(new ImportElement(getGeometryFromImportedData(data)))), () => null ); }
Python
UTF-8
1,194
4.5
4
[]
no_license
# In this lets see about "Set Operations" in Python. # Python provides certain set Operation which is avaliable in mathematics such as # 1) union # 2) intersection # 3) difference # 4) symmetric difference # In this lets see about "intersection of two set" # The intersection of the two sets is given as the set of the elements that common in both sets. # intersection_update() method removes the items from the original set that are not present in both the sets. # The intersection_update() method is different from the intersection() method since it modifies the original set by removing the unwanted items. # Where intersection() method returns a new set. # Here is the program for "intersection of two set" Month1 = set ( [ "January" , "February" , "March" , "April" , "May" , "June" , "December" ] ) Month2 = set ( [ "May" , "July" , "August" , "September" , "October" , "November" , "December" ] ) print ( "\nValue present in set \"Month1\" Before using intersection_update ( ) ...\n\n " , Month1 ) Month1.intersection_update ( Month2 ) print ( "\nValue present in set \"Month1\" After using intersection_update ( ) ...\n\n " , Month1 )
Swift
UTF-8
2,276
2.6875
3
[]
no_license
// // ClientService.swift // Foodly // // Created by Decagon on 6/8/21. // import Foundation import FirebaseAuth import FirebaseFirestore class Client { private init() {} static let shared = Client() func createUser<T: Encodable>(for encodableObject: T, in collectionReference: ClientCollectionReference, withEmail: String, password: String, inViewController: UIViewController) { do { let json = try encodableObject.toJson(excluding: ["id"]) Auth.auth().createUser(withEmail: withEmail, password: password) { [self] (_, err) in if err != nil { AlertController.showAlert(inViewController, title: "Error", message: "Error Creating User" ) } else { AlertController.showAlert(inViewController, title: "Success", message: "SignUp Sucessful") Firestore.firestore().collection(collectionReference.rawValue).addDocument(data: json) { (error) in if error != nil { AlertController.showAlert(inViewController, title: "Error", message: "Error saving data" ) } }} }} catch { AlertController.showAlert(inViewController, title: "Error", message: error.localizedDescription ) } } func userLogin (withEmail: String, password: String, inViewController: UIViewController) { Auth.auth().signIn(withEmail: withEmail, password: password, completion: { (_, error) in if error != nil { AlertController.showAlert(inViewController, title: "Error", message: "incorrect email or password") return } else { AlertController.showAlert(inViewController, title: "Success", message: "Login Sucessful") } }) } func userLogout(inViewController: UIViewController) { do { try Auth.auth().signOut() } catch { AlertController.showAlert(inViewController, title: "Error", message: error.localizedDescription ) } } }
Java
UTF-8
725
2.65625
3
[]
no_license
import java.io.*; public class Test { public static void main(String args[]) throws IOException { String serverIP = "pyrite-n3"; if (args.length != 0) { serverIP = args[0]; // the ip from user input } /* c_int c = new c_int(); c.setValue(14); System.out.println(c.getValue()); System.out.println(c.getSize()); */ /* c_char c = new c_char(); c.setValue((byte)75); System.out.println(c.getValue()); System.out.println(c.getSize()); */ /* Testing GetLocalTime */ GetLocalTime obj = new GetLocalTime(); obj.setValid('F'); obj.execute(serverIP, 53953); /* Testing GetLocalOS */ GetLocalOS obj2 = new GetLocalOS(); obj2.setValid('F'); obj2.execute(serverIP, 53953); } }
Java
UTF-8
2,017
3.0625
3
[]
no_license
package io.github.nosequel.aimbot.command; import io.github.nosequel.aimbot.AimbotHandler; import org.bukkit.Bukkit; import org.bukkit.ChatColor; import org.bukkit.command.Command; import org.bukkit.command.CommandExecutor; import org.bukkit.command.CommandSender; import org.bukkit.entity.Player; public class AimbotCommand implements CommandExecutor { private final AimbotHandler aimbotHandler; /** * Constructor to make a new aimbot command instance * <p> * This class handles all toggling and * things such as that in a simple * bukkit command, using {@link CommandExecutor}. * * @param aimbotHandler the handler to get the status of the player from */ public AimbotCommand(AimbotHandler aimbotHandler) { this.aimbotHandler = aimbotHandler; } @Override public boolean onCommand(CommandSender sender, Command command, String label, String[] args) { if(!sender.hasPermission("aimbot.toggle")) { sender.sendMessage(ChatColor.RED + "No permission."); return false; } if (args.length <= 1) { sender.sendMessage(new String[]{ ChatColor.RED + "/aimbot status <player>", ChatColor.RED + "/aimbot toggle <player>" }); return false; } final Player target = Bukkit.getPlayer(args[1]); if (target == null) { sender.sendMessage(ChatColor.RED + "No player by name \"" + args[1] + "\" found."); return false; } if (args[0].equalsIgnoreCase("status")) { sender.sendMessage(ChatColor.RED + target.getName() + "'s aimbot is currently " + (this.aimbotHandler.isToggled(target) ? "enabled" : "disabled")); } else if (args[0].equalsIgnoreCase("toggle")) { this.aimbotHandler.toggle(target); sender.sendMessage(ChatColor.RED + "You have enabled " + target.getName() + "'s aimbot."); } return true; } }
C#
UTF-8
1,229
2.65625
3
[]
no_license
using System.Collections.Generic; using Microsoft.AspNetCore.Mvc; using System; using System.Threading.Tasks; using DropdownApi.Data; using DropdownApi.Models; namespace DropdownApi.Controllers { [Route("api/[controller]")] [ApiController] public class Controller : ControllerBase { private readonly DataContext _context; public Controller(DataContext context) { _context = context; } [HttpGet("{id}")] public Task<IActionResult> GetCityList(int StateId){ var list= new SelectList(_context.City.Where(c => c.StateId == StateId)); return Ok(list); } [HttpPost] public async Task<IActionResult> Post([FromBody]Employee e) { try{ if (ModelState.IsValid) { _context.Employee.Add(e); await _context.SaveChangesAsync(); return Ok(); } } catch(Exception) { return BadRequest(); } } }
Java
UTF-8
1,185
2.5
2
[]
no_license
package br.com.nicolasg.DAO; import br.com.nicolasg.model.Usuario; import br.com.nicolasg.services.Conexao; import com.mysql.jdbc.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.logging.Level; import java.util.logging.Logger; //NESTA TELA ESTÁ TUDO OK!!!!!! public class DaoUsuario { private Connection conn; public DaoUsuario() { this.conn = (Connection) Conexao.getInstance().getConn(); } public String Autenticar(Usuario user) { Usuario u = user; String sql = "select usuario, senha, nivel from usuario where usuario = ? and senha = ?;"; try { PreparedStatement ps = this.conn.prepareStatement(sql); ps.setString(1, u.getLogin()); ps.setString(2, u.getSenha()); ResultSet rs = ps.executeQuery(); if (rs.next()) { return rs.getString("nivel"); } else { return null; } } catch (SQLException ex) { System.out.println("1"); } return null; } }
Java
UTF-8
831
2.078125
2
[]
no_license
package com.veritas.soft.controller; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.veritas.soft.model.Employee; import com.veritas.soft.service.EmployeeService; @RestController @RequestMapping("/emp") public class EmployeeController { @Autowired private EmployeeService service; @GetMapping("/get/{eno}") public Optional<Employee> getEmployeeById(@PathVariable("eno")Integer id) { Optional<Employee> employeeById = service.getEmployeeById(id); return employeeById; } }
Java
UTF-8
173
1.804688
2
[]
no_license
package com.agente; public class Actuador { public Actuador() { } public void mover(String origen, String destino) { } public void animar(int id) { } }
JavaScript
UTF-8
1,543
3.25
3
[]
no_license
"use strict"; function bigNum( numberList ) { // input validation if ( !Array.isArray( numberList ) ) { return 'Pateikta netinkamo tipo reikšmė.' } if ( numberList.length === 0 ) { return 'Pateiktas sąrašas negali būti tuščias.'; } const size = numberList.length; let big = -Infinity; for ( let i=1; i<size; i++ ) { const number = numberList[i]; if ( typeof number !== 'number' ) { continue; } if ( number > big ) { big = number; } } if ( big === -Infinity ) { return 'Sarase nebuvo nei vieno normalaus skaiciaus... 😥'; } return big; } console.log( bigNum( 'pomidoras' ) ); console.log( bigNum( [] ) ); console.log( bigNum( {} ) ); console.log( bigNum( 35131 ) ); console.log( bigNum( [ 'asfd', 'asd', true, {} ] ) ); console.log( bigNum( [ 1 ] ), '->', 1 ); console.log( bigNum( [ 1, 2, 3 ] ), '->', 3 ); console.log( bigNum( [ -5, 78, 14, 0, 18 ] ), '->', 78 ); console.log( bigNum( [ 69, 69, 69, 69, 66 ] ), '->', 69 ); console.log( bigNum( [ -1, -2, -3, -4, -5, -6, -7, -8 ] ), '->', -1 ); console.log( bigNum( [ -5, 78, 'asfd', 14, 0, 18 ] ), '->', 78 ); console.log( bigNum( [ -5, 78, 14, 0, 18, 'asfd' ] ), '->', 78 ); console.log( bigNum( [ 'asfd', -5, 78, 14, 0, 18 ] ), '->', 78 ); console.log('-----------'); console.log('extra - reikia rekursijos, kad rasti 87878'); console.log( bigNum( [ 'asfd', -5, true, false, [7, 9], [1, 2, [8, 99, [87878, -22]]], {} ] ), '->', -5 );
JavaScript
UTF-8
207
2.71875
3
[]
no_license
function Mostrar() { var clave = prompt("ingrese el número clave."); while( clave !="utn750") { clave=prompt("No es corrcta.Ingrese la clave."); } alert("la clave es correcta"); }//FIN DE LA FUNCIÓN
JavaScript
UTF-8
759
3.765625
4
[]
no_license
// Selektiere das Audio-Element und der Button let audio = document.querySelector('#yeah-audio'); let button = document.querySelector('#play-button'); // Füge einen Event-Listener hinzu, welcher auf den 'click'-Event hört button.addEventListener('click', playButton) // Definiere eine Funktion, welche beim Button-Klick ausgeführt wird function playButton() { // Überprüfe, ob die Audio-Datei pausiert ist (pausiert == true) if (audio.paused) { // Audio ist pausiert, also Play audio.play(); // Text des Buttons wechseln button.innerHTML = 'Pause'; } else { // Audio ist am Abspielen, also Pause audio.pause(); // Texts des Buttons wechseln button.innerHTML = 'Play'; } }
C#
UTF-8
2,668
3.0625
3
[]
no_license
namespace SoftUniRssFeed { using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Xml.Linq; using Newtonsoft.Json; using Newtonsoft.Json.Linq; public class SoftUniRssFeedMain { public static void Main() { Utility.CreateOutputFolder(); // Problem 1 //DownloadRssFeed(Utility.Url, Utility.XmlPath); // Problem 2. Parse the XML from the feed to JSON var json = ParseXmlToJson(Utility.XmlPath); // Problem 3. Using LINQ-to-JSON select all the question titles and print them to the console var newsTitles = GetTitles(json); // Problem 4. Parse the JSON string to POCO var pocos = newsTitles.Select(item => JsonConvert.DeserializeObject<JsonToPoco>(item.ToString())).ToList(); // Problem 5. Using the parsed objects create a HTML page that lists all questions from the RSS their categories and a link to the question’s page MakeHtml(pocos); Process.Start(Utility.HtmlPath); } // Problem 5 public static void MakeHtml(List<JsonToPoco> pocos) { var result = new StringBuilder(); result.Append("<!DOCTYPE html><html><head><meta charset=\"UTF-8\"></head><body>"); foreach (var jsonToPoco in pocos) { result.Append(jsonToPoco); } result.Append("</body></html>"); File.WriteAllText(Utility.HtmlPath, result.ToString()); } // Problem 3 private static IEnumerable<JToken> GetTitles(string json) { var jsonObj = JObject.Parse(json); var titles = jsonObj["rss"]["channel"]["item"].ToList(); foreach (var title in titles.Select(n => n["title"])) { Console.WriteLine(title); } return titles; } // Problem 2 private static string ParseXmlToJson(string xmlPath) { var doc = XDocument.Load(xmlPath); var jsonConverted = JsonConvert.SerializeXNode(doc, Formatting.Indented); return jsonConverted; } // Problem 1 private static void DownloadRssFeed(string sourceLocation, string destination) { using (var client = new WebClient()) { client.DownloadFile(sourceLocation, destination); Console.WriteLine("Feed downloaded"); } } } }
C#
UTF-8
3,846
3.5625
4
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace RPN { // Format daty w liczbie to dd.mmyyyy np 18.02.1992 -> 18.021992 public static class NumberToDateTimeConverter { #region Data public static DateTime? NumberToDate(double input) { int days = getNumberOfDays(input); int months = getNumberOfMonths(input); int years = getNumberOfYears(input); try { return new DateTime(years,months,days); } catch (Exception) { return null; } } /// <summary> /// Pobierz liczbe dni /// </summary> /// <param name="input"></param> /// <returns></returns> public static int getNumberOfDays(double input) { return (int)input; } /// <summary> /// Pobierz liczbe miesiecy /// </summary> /// <param name="input"></param> /// <returns></returns> public static int getNumberOfMonths(double input) { input -= getNumberOfDays(input); return (int)(input * 100); } /// <summary> /// Pobierz liczbe lat /// </summary> /// <param name="input"></param> /// <returns></returns> public static int getNumberOfYears(double input) { double result = input - getNumberOfDays(input); result *= 100; result -= getNumberOfMonths(input); return (int)(result * 10000); } public static double NumberFromDate(DateTime date) { int months = date.Month; int years = date.Year; double result = date.Day; result *= 100; result += months; result *= 10000; result += years; return result / 1000000; } #endregion #region Time public static DateTime? NumberToTime(double input) { int hours = getNumberOfHours(input); int minutes = getNumberOfMinutes(input); int seconds = getNumberOfSeconds(input); try { return new DateTime(1970,1,1,hours,minutes,seconds); } catch (Exception) { return null; } } /// <summary> /// Pobierz liczbe godzin /// </summary> /// <param name="input"></param> /// <returns></returns> public static int getNumberOfHours(double input) { return (int)input; } /// <summary> /// Pobierz liczbe miesiecy /// </summary> /// <param name="input"></param> /// <returns></returns> public static int getNumberOfMinutes(double input) { input -= getNumberOfHours(input); return (int)(input * 100); } /// <summary> /// Pobierz liczbe lat /// </summary> /// <param name="input"></param> /// <returns></returns> public static int getNumberOfSeconds(double input) { double result = input - getNumberOfHours(input); result *= 100; result -= getNumberOfMinutes(input); return (int)(result * 100); } public static double NumberFromTime(DateTime date) { int minutes = date.Minute; int seconds = date.Second; double result = date.Hour; result *= 100; result += minutes; result *= 100; result += seconds; return result / 10000; } #endregion } }
SQL
UTF-8
360
2.65625
3
[]
no_license
CREATE TABLE `comments` ( `id` int(11) unsigned NOT NULL AUTO_INCREMENT, `page_id` int(11) NOT NULL, `comment_guid` varchar(256) DEFAULT NULL, `comment_name` varchar(64) DEFAULT NULL, `comment_email` varchar(128) DEFAULT NULL, `comment_text` mediumtext, `comment_date` timestamp NULL DEFAULT NULL, PRIMARY KEY (`id`), KEY `page_id` (`page_id`) ) ENGINE=InnoDB;
Markdown
UTF-8
641
3
3
[]
no_license
# 100-Python-Projects-Basic-to-Advance- | Day | Project name | Concept covered | |-----|---------------------|----------------------| | 1 | [Band Name Generator](https://github.com/AlpeshGo/100-Python-Projects-Basic-to-Advance-/blob/main/Day-1%20Project%201.py) | String Concatenation | | 2 | [Bill Split Calculator](https://github.com/AlpeshGo/100-Python-Projects-Basic-to-Advance-/blob/main/Day%202%20Project%202.py) | F-String, basic calculation | | 3 | [Finding treasure in Treasure Island](https://github.com/AlpeshGo/100-Python-Projects-Basic-to-Advance-/blob/main/Day-3%20Project.py) | loops like if, else, elif |
Go
UTF-8
1,485
3.046875
3
[]
no_license
// redis.go package redis import ( "fmt" "github.com/garyburd/redigo/redis" ) const ( host = "192.168.99.100:6379" // 主机:端口 auth = "123456" // auth 密码 db = 1 // 数据库 ) const ( conn_err = "Connection to redis error" auth_err = "Auth redis error" select_err = "Select redis db error" set_err = "Set redis value error" get_err = "Get redis key error" ) // 连接redis func connection() (redis.Conn, error) { c, err := redis.Dial("tcp", host) // 连接reids isError(err, conn_err) _, err = c.Do("AUTH", auth) // 验证redis isError(err, auth_err) _, err = c.Do("SELECT", db) // 选择连接库 isError(err, select_err) return c, nil } // 保存值到redis中 func Set(key, value, ex, expiration interface{}) (interface{}, error) { c, err := connection() defer c.Close() time, err := Query(key) if time == -2 { // Set 值 _, err = c.Do("SET", key, value, ex, expiration) // ex 表示设置过期时间;expiration 缓存时间,秒 isError(err, set_err) return true, nil } else { return time, nil } } // 根据key获取值 func Query(key interface{}) (interface{}, error) { c, err := connection() defer c.Close() if err != nil { fmt.Println(err) } // TTL 获取值的倒计时 val, err := redis.Int(c.Do("TTL", key)) isError(err, get_err) return val, nil } // 判断错误信息 func isError(err error, errInfo interface{}) { if err != nil { fmt.Println(errInfo) } }
SQL
UTF-8
4,799
2.859375
3
[]
no_license
declare v_cnt NUMBER; v_cnt_conv NUMBER; v_cnt_prod NUMBER; record_count_mismatch exception; begin for i in ( SELECT BAB_COMP_CODE, BAB_DEPT_CODE, BAB_ACC_CODE, BAB_BANK_CODE, BAB_ACC_PREFIX, BAB_ACC_NUMBER, BAB_CURR_CODE, BAB_FXGAIN_DEPT_CODE, BAB_FXGAIN_ACC_CODE, BAB_FXLOSS_DEPT_CODE, BAB_FXLOSS_ACC_CODE, BAB_SUSP_REC_DEPT_CODE, BAB_SUSP_REC_ACC_CODE, BAB_SUSP_PAY_DEPT_CODE, BAB_SUSP_PAY_ACC_CODE, BAB_LAST_CHQ_NUM, BAB_ACC_TITLE, BAB_ACC_TYPE, BAB_EFT_DESC, BAB_EFT_FORMAT, BAB_FC_BAL_AMT, BAB_CREATE_USER, BAB_CREATE_DATE, BAB_LAST_UPD_USER, BAB_LAST_UPD_DATE, BAB_BRANCH_CODE, BAB_MICR_CODE, BAB_SIGN_FILE1, BAB_SIGN_FILE2, BAB_COMP_LOGO_FILE, BAB_AMT_FOR_TWO_SIGN, BAB_AMT_FOR_MAN_SIGN, BAB_PRINT_COMP_ADDR, BAB_COMP_ADDR_CODE, BAB_PRINT_BANK_ADDR, BAB_PRINT_CHECK_FRAME, BAB_ROUTING_CODE_A, BAB_ROUTING_CODE_B, BAB_PRINT_ROUTING, BAB_PRINT_MICR, BAB_EFT_FILE_FORMAT, BAB_EFT_FILE_CODE, BAB_CDA_ACC_NUMBER, BAB_CSR_ACC_NUMBER, BAB_BANK_CUSTOMER_ID, BAB_LAST_EFT_NUM, BAB_FILE_NUMBER, BAB_PAY_THROUGH, BAB_CURR_DESIGN, BAB_CHEQUE_DATE_FORMAT--, --BAB__IU__CREATE_DATE, --BAB__IU__CREATE_USER, --BAB__IU__UPDATE_DATE, --BAB__IU__UPDATE_USER FROM DA.BABANKACCT@CONV WHERE BAB_COMP_CODE NOT IN ('ZZ') ) loop INSERT INTO DA.BABANKACCT ( BAB_COMP_CODE, BAB_DEPT_CODE, BAB_ACC_CODE, BAB_BANK_CODE, BAB_ACC_PREFIX, BAB_ACC_NUMBER, BAB_CURR_CODE, BAB_FXGAIN_DEPT_CODE, BAB_FXGAIN_ACC_CODE, BAB_FXLOSS_DEPT_CODE, BAB_FXLOSS_ACC_CODE, BAB_SUSP_REC_DEPT_CODE, BAB_SUSP_REC_ACC_CODE, BAB_SUSP_PAY_DEPT_CODE, BAB_SUSP_PAY_ACC_CODE, BAB_LAST_CHQ_NUM, BAB_ACC_TITLE, BAB_ACC_TYPE, BAB_EFT_DESC, BAB_EFT_FORMAT, BAB_FC_BAL_AMT, BAB_CREATE_USER, BAB_CREATE_DATE, BAB_LAST_UPD_USER, BAB_LAST_UPD_DATE, BAB_BRANCH_CODE, BAB_MICR_CODE, BAB_SIGN_FILE1, BAB_SIGN_FILE2, BAB_COMP_LOGO_FILE, BAB_AMT_FOR_TWO_SIGN, BAB_AMT_FOR_MAN_SIGN, BAB_PRINT_COMP_ADDR, BAB_COMP_ADDR_CODE, BAB_PRINT_BANK_ADDR, BAB_PRINT_CHECK_FRAME, BAB_ROUTING_CODE_A, BAB_ROUTING_CODE_B, BAB_PRINT_ROUTING, BAB_PRINT_MICR, BAB_EFT_FILE_FORMAT, BAB_EFT_FILE_CODE, BAB_CDA_ACC_NUMBER, BAB_CSR_ACC_NUMBER, BAB_BANK_CUSTOMER_ID, BAB_LAST_EFT_NUM, BAB_FILE_NUMBER, BAB_PAY_THROUGH, BAB_CURR_DESIGN, BAB_CHEQUE_DATE_FORMAT--, --BAB__IU__CREATE_DATE, --BAB__IU__CREATE_USER, --BAB__IU__UPDATE_DATE, --BAB__IU__UPDATE_USER ) values ( i. BAB_COMP_CODE, i. BAB_DEPT_CODE, i. BAB_ACC_CODE, i. BAB_BANK_CODE, i. BAB_ACC_PREFIX, i. BAB_ACC_NUMBER, i. BAB_CURR_CODE, i. BAB_FXGAIN_DEPT_CODE, i. BAB_FXGAIN_ACC_CODE, i. BAB_FXLOSS_DEPT_CODE, i. BAB_FXLOSS_ACC_CODE, i. BAB_SUSP_REC_DEPT_CODE, i. BAB_SUSP_REC_ACC_CODE, i. BAB_SUSP_PAY_DEPT_CODE, i. BAB_SUSP_PAY_ACC_CODE, i. BAB_LAST_CHQ_NUM, i. BAB_ACC_TITLE, i. BAB_ACC_TYPE, i. BAB_EFT_DESC, i. BAB_EFT_FORMAT, i. BAB_FC_BAL_AMT, i. BAB_CREATE_USER, i. BAB_CREATE_DATE, i. BAB_LAST_UPD_USER, i. BAB_LAST_UPD_DATE, i. BAB_BRANCH_CODE, i. BAB_MICR_CODE, i. BAB_SIGN_FILE1, i. BAB_SIGN_FILE2, i. BAB_COMP_LOGO_FILE, i. BAB_AMT_FOR_TWO_SIGN, i. BAB_AMT_FOR_MAN_SIGN, i. BAB_PRINT_COMP_ADDR, i. BAB_COMP_ADDR_CODE, i. BAB_PRINT_BANK_ADDR, i. BAB_PRINT_CHECK_FRAME, i. BAB_ROUTING_CODE_A, i. BAB_ROUTING_CODE_B, i. BAB_PRINT_ROUTING, i. BAB_PRINT_MICR, i. BAB_EFT_FILE_FORMAT, i. BAB_EFT_FILE_CODE, i. BAB_CDA_ACC_NUMBER, i. BAB_CSR_ACC_NUMBER, i. BAB_BANK_CUSTOMER_ID, i. BAB_LAST_EFT_NUM, i. BAB_FILE_NUMBER, i. BAB_PAY_THROUGH, i. BAB_CURR_DESIGN, i. BAB_CHEQUE_DATE_FORMAT--, --i. --BAB__IU__CREATE_DATE, --i. --BAB__IU__CREATE_USER, --i. --BAB__IU__UPDATE_DATE, --i. --BAB__IU__UPDATE_USER ); end loop; --commit; select count(1) into v_cnt_conv from BABANKACCT@conv; select count(1) into v_cnt_prod from BABANKACCT@prod; if v_cnt_conv - v_cnt_prod = 0 then dbms_output.put_line ('Number of records in PROD match with CONV for BABANKACCT table.'); else dbms_output.put_line ('Number of records in PROD does not match with CONV for BABANKACCT table.'); Raise record_count_mismatch; end if; Select count(1) into v_cnt from DA.BABANKACCT@PROD where BAB_COMP_CODE NOT IN ('ZZ'); dbms_output.put_line ('Inserted '||v_cnt||' records into BABANKACCT table, check and commit.'); EXCEPTION WHEN record_count_mismatch THEN DBMS_OUTPUT.PUT_LINE ('There is a mismatch in PROD and CONV for this table.'); WHEN OTHERS THEN DBMS_OUTPUT.PUT_LINE ('ERROR WHILE INSERTING INTO DA.BABANKACCT.'); DBMS_OUTPUT.PUT_LINE (SQLERRM); end; /
C++
UTF-8
459
2.71875
3
[]
no_license
#include <iostream> #include <string> #include <vector> #include <algorithm> using namespace std; int main() { int n, t; cin >> n >> t; vector<char> a(n); for (int i = 0; i < n; i++) { cin >> a[i]; } for (int i = 0; i < t; i++) { int j = 0; while (j < n - 1) { if (a[j] == 'B' && a[j + 1] =='G') {swap(a[j], a[j+1]); j+=2;} else j++; } } for (int i = 0; i < n; i++) { cout << a[i]; } }
Markdown
UTF-8
1,923
3.140625
3
[ "LicenseRef-scancode-public-domain" ]
permissive
# Development See the [README](standards/README.md) in the `standards` directory for information about coding standards. ## Branches Major branches: * `master`: Contains the production ready code. * **NEVER** commit into `master`. **ONLY** pull requests from the `dev` branch and urgent hotfixes can be merged into `master`. * `dev`: Contains finished code from the current sprint, ready for merging into `master` at any time. * **NEVER** commit into `dev`, create a pull request. Typical workflow: 1. Start with the `dev` branch. Ensure `dev` is up to date on your machine. 1. Create a new feature branch from `dev` with the format `leaf###_short_feature_description` * Each branch name should begin with lowercase `leaf###` where `###` is the issue/ticket number and end with a short description of the feature. * **NOTE:** Branch naming consistency is important in order to quickly determine what each branch is for. Do not deviate from the pattern mentioned above without a good reason. 1. Write code. Ensure proper tests are created (where applicable) and all existing tests pass. 1. Rebase the feature branch into as few logical commits as possible (1-3 total commits is ideal). 1. Create a [good commit message](https://robots.thoughtbot.com/5-useful-tips-for-a-better-commit-message). Keep the commit subject under 50 characters, and wrap the commit message body at 72 characters. 1. Push feature branch to remote origin. 1. Create a pull for the feature branch into `dev`. The request name should follow the format: "LEAF<ticket#> Short Description" 1. Teammates will comment on and/or approve the changes (see [CodeReviews](CodeReviews.md). 1. Make any necessary changes. 1. Push changed feature branch to remote. 1. The pull request from the feature branch will be automatically updated. 1. After the pull request has been reviewed, approved, and merged, the feature branch will be deleted.
Java
UTF-8
568
2.015625
2
[]
no_license
package hu.elte.inf.nfzjwg.FamilyToDo.service; import java.util.List; import org.springframework.stereotype.Service; import org.springframework.beans.factory.annotation.Autowired; import hu.elte.inf.nfzjwg.FamilyToDo.repository.ToDoRepository; import hu.elte.inf.nfzjwg.FamilyToDo.model.ToDo;; @Service public class ToDoService { @Autowired private ToDoRepository toDoRepository; public List<ToDo> findAll() { return toDoRepository.findAll(); } public ToDo findById(int id) { return toDoRepository.findById(id).get(); } }
JavaScript
UTF-8
569
2.6875
3
[ "Apache-2.0" ]
permissive
import fs from 'fs'; import lineReader from 'readline'; export class FileReader { processFile(filePath, callBack) { if(typeof filePath !== 'string') throw "filePath Must be a string" this.readFromFile(filePath, callBack); } readFromFile(filePath, callBack) { let reader = lineReader.createInterface({ input: fs.createReadStream(filePath, 'utf-8') }); reader.on('line', (line) => { let proccessedLine = line.split(' '); callBack(proccessedLine); }); } }
Java
UTF-8
525
1.953125
2
[]
no_license
package net.threader.guildplus.controller; import net.threader.guildplus.model.Guild; import net.threader.guildplus.model.Invite; import org.bukkit.entity.Player; import java.util.Optional; import java.util.Set; import java.util.UUID; public interface InviteController { Set<Invite> getInvites(); Set<Invite> getInvitesOf(Guild guild); Optional<Guild> getInviter(UUID invited); void removeInvitesOf(Guild guild); void addInvite(Guild inviter, Player invited); void removeInvitesOf(UUID invited); }
Markdown
UTF-8
1,193
2.640625
3
[]
no_license
# Описание Вам предстоит выполнить несколько задач, которые распределены на 2 модуля `simple` и `medium` в модуле `simple` 13 задач, в каждом модуле есть файл `README.md` где подробно описаны задачи и методика тестирования # Как начать Вам необходимо сделать форк: ![](doc/fork.png) этого репозитория, реализовать функции, и после этого сделать `pull request` в ветку `solution`: ![](doc/pull_request.png) ![](doc/pull_request_confirm.png) После запроса на слияние будет запущен `action` который проведет тестирование, если тест завершится успешно вы увидите следующее: ![](doc/test.png) _Примечание: тест может запустится не сразу, если у вас новый аккаунт то для запуска action вам нужно дождаться подтверждения с моей стороны_
Python
UTF-8
1,194
2.5625
3
[]
no_license
import requests import json import server from eeg_data.eeg_utils import simulate_eeg nbest = 3 # localhost = 'http://localhost:5000' # choose a port path2eeg = 'eeg_data/EEGEvidence.txt-high' simulator = simulate_eeg(path2eeg) # init r = requests.post(localhost + '/init', json={'nbest': nbest}) print r.status_code # provide priors for a single likelihood evidence # provide words for the same evidence history = 'th' # build evidence history evidence = [] for target in history: evidence.extend(simulator.simulate(target)) print evidence print "Charachter and Word distributions" r = requests.post(localhost + '/state_update', json={'evidence': evidence, 'return_mode': 'word'}) print r.status_code e = r.json() # print priors for a history of evidence print e['letter'] print e['word'] # reset r = requests.post(localhost + '/reset') print r.status_code # feed new evidence and ask just for letter distribution print "Character distribution" target = 'y' evidence = simulator.simulate(target) r = requests.post(localhost + '/state_update', json={'evidence': evidence, 'return_mode': 'letter'}) print r.status_code e = r.json() print "status code of 200 implies a good connection"