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
Python
UTF-8
1,892
3.3125
3
[]
no_license
# n = int(input('Nhập số chữ số: ')) # tong=0 # trungbinh = 0 # for i in range(n): # so = int(input("Nhập số: ")) # tong = tong + so # print('Tổng các số trên là',tong) # trungbinh = tong/n # print('Trung bình các số trên là',trungbinh) # ----------------------------------------- # def say_hi(): # print('hi') # print('bye') # say_hi() # say_hi() # say_hi() # say_hi() # def add_two_number(x,y): # print('tong hai so la',x+y) # # a = int(input('Nhap so thu nhat: ')) # # b = int(input('Nhap so thu hai: ')) # add_two_number(150+0*2,500) # def add_two_number(a,b): # return a+b # num1 = int(input('Nhap so thu nhat: ')) # num2 = int(input('Nhap so thu hai: ')) # num3 = int(input('Nhap so thu ba: ')) # sum_1_2 = add_two_number(num1,num2) # sum_3= add_two_number(sum_1_2,num3) # print('Toong 3 so:',sum_3) # def add_two_number(a,b): # return a+b # # print(add_two_number(add_two_number(1,2),3)) # x = 121+add_two_number(3,4) # print(x) # def abs_of_number(a): # if a>0: # return a # print('tri tuyet doi la',a) # else: # return -a # print('tri tuyet doi la',-a) # print('tri tuyet doi la',a) # x=abs_of_number(-12) # tong= 12 + abs_of_number(-12) # print(x) # print(tong) # def evaluate(a,b,operator): # if operator == '+': # return a+b # elif operator == '-': # return a-b # elif operator == '*': # return a*b # elif operator == '/': # return a/b # else: # return None # x = evaluate(5,6,'*') # print(x) def is_prime(n): if n<2: return False for v in range(2,n): if n%v==0: return False return True so = int(input('nhap so can ktra: ')) for v in range(2,so+1): if is_prime(v): print('snt la:',v) # if is_prime(so): # print('la snt') # else: # print('k la snt')
Shell
UTF-8
849
3.375
3
[]
no_license
#!/bin/sh # change sshd_config if [ -f "/etc/ssh/sshd_config" ]; then sed -ri 's/^PermitRootLogin\s+.*/PermitRootLogin yes/' /etc/ssh/sshd_config \ && sed -ri 's/^PasswordAuthentication\s+.*/PasswordAuthentication no/' /etc/ssh/sshd_config \ && sed -ri 's/^HostKey\s+.*//g' fi # prepare run dir if [ ! -d "/var/run/sshd" ]; then mkdir -p /var/run/sshd fi # prepare root ssh folder if [ ! -d "/root/.ssh/" ]; then mkdir -p /root/.ssh/ && chmod 700 /root/.ssh/ fi # prepare authorized_keys if [ -d "/sshkey/" ]; then cp /sshkey/* /root/.ssh/ && chown root:root /root/.ssh/* fi if [ -f /root/.ssh/id_rsa ]; then echo "HostKey /root/.ssh/id_rsa" >> /etc/ssh/sshd_config else ssh-keygen -t rsa -N '' -f /etc/ssh/ssh_host_rsa_key \ && echo "HostKey /etc/ssh/ssh_host_rsa_key" >> /etc/ssh/sshd_config fi exec "$@"
TypeScript
UTF-8
3,056
3.109375
3
[]
no_license
import { Buff } from "../buff.js"; import { StatValues } from "../stats.js"; import { Faction } from "../player.js"; export interface BuffDescription { name: string, duration: number, stats?: StatValues, faction?: Faction, disabled?: boolean, } export const buffs: BuffDescription[] = [ { name: "Battle Shout", duration: 2 * 60, stats: { ap: 290 } }, { name: "Gift of the Wild", duration: 1 * 60 * 60, stats: { str: 16, // TODO - should it be 12 * 1.35? (talent) agi: 16 } }, { name: "Trueshot Aura", duration: 1 * 60 * 60, stats: { ap: 100 } }, { name: "Blessing of Kings", faction: Faction.ALLIANCE, duration: 15 * 60, stats: { statMult: 1.1 } }, { name: "Blessing of Might", faction: Faction.ALLIANCE, duration: 15 * 60, stats: { ap: 222 } }, { name: "Strength of Earth", faction: Faction.HORDE, duration: 15 * 60, stats: { str: 77 * 1.15 // assuming enhancing totems } }, { name: "Grace of Air", faction: Faction.HORDE, disabled: true, duration: 15 * 60, stats: { agi: 77 * 1.15 // assuming enhancing totems } }, { name: "Smoked Desert Dumplings", duration: 15 * 60, stats: { str: 20 } }, { name: "Juju Power", duration: 30 * 60, stats: { str: 30 } }, { name: "Juju Might", duration: 10 * 60, stats: { ap: 40 } }, { name: "Elixir of the Mongoose", duration: 1 * 60 * 60, stats: { agi: 25, crit: 2 } }, { name: "R.O.I.D.S.", duration: 1 * 60 * 60, stats: { str: 25 } }, { name: "Rallying Cry of the Dragonslayer", duration: 2 * 60 * 60, stats: { ap: 140, crit: 5 } }, { name: "Songflower Seranade", duration: 2 * 60 * 60, stats: { crit: 5, str: 15, agi: 15 } }, { name: "Spirit of Zandalar", duration: 1 * 60 * 60, stats: { statMult: 1.15 } }, { name: "Fengus' Ferocity", duration: 2 * 60 * 60, stats: { ap: 200 } }, { name: "Warchief's Blessing", duration: 1 * 60 * 60, stats: { haste: 1.15 } } ]; export function getBuffFromDescription(desc: BuffDescription) { return new Buff(desc.name, desc.duration, desc.stats); } export function getBuff(name: string) { for (let buff of buffs) { if (buff.name === name) { return getBuffFromDescription(buff); } } }
PHP
UTF-8
5,824
3.25
3
[ "MIT", "LicenseRef-scancode-free-unknown" ]
permissive
<?php declare(strict_types=1); namespace voku\helper; /** * {@inheritdoc} */ class SimpleHtmlAttributes implements SimpleHtmlAttributesInterface { /** * @var string */ private $attributeName; /** * @var \DOMElement|null */ private $element; /** * @var string[] * * @psalm-var list<string> */ private $tokens = []; /** * @var string|null */ private $previousValue; /** * Creates a list of space-separated tokens based on the attribute value of an element. * * @param \DOMElement|null $element * <p>The DOM element.</p> * @param string $attributeName * <p>The name of the attribute.</p> */ public function __construct($element, string $attributeName) { $this->element = $element; $this->attributeName = $attributeName; $this->tokenize(); } /** @noinspection MagicMethodsValidityInspection */ /** * Returns the value for the property specified. * * @param string $name The name of the property * * @return int|string The value of the property specified */ public function __get(string $name) { if ($name === 'length') { $this->tokenize(); return \count($this->tokens); } if ($name === 'value') { return (string) $this; } throw new \InvalidArgumentException('Undefined property: $' . $name); } /** * @return string */ public function __toString(): string { $this->tokenize(); return \implode(' ', $this->tokens); } /** * {@inheritdoc} */ public function add(string ...$tokens) { if (\count($tokens) === 0) { return null; } foreach ($tokens as $t) { if (\in_array($t, $this->tokens, true)) { continue; } $this->tokens[] = $t; } return $this->setAttributeValue(); } /** * {@inheritdoc} */ public function contains(string $token): bool { $this->tokenize(); return \in_array($token, $this->tokens, true); } /** * {@inheritdoc} */ public function entries(): \ArrayIterator { $this->tokenize(); return new \ArrayIterator($this->tokens); } public function item(int $index) { $this->tokenize(); if ($index >= \count($this->tokens)) { return null; } return $this->tokens[$index]; } /** * {@inheritdoc} */ public function remove(string ...$tokens) { if (\count($tokens) === 0) { return null; } if (\count($this->tokens) === 0) { return null; } foreach ($tokens as $t) { $i = \array_search($t, $this->tokens, true); if ($i === false) { continue; } \array_splice($this->tokens, $i, 1); } return $this->setAttributeValue(); } /** * {@inheritdoc} */ public function replace(string $old, string $new) { if ($old === $new) { return null; } $this->tokenize(); $i = \array_search($old, $this->tokens, true); if ($i !== false) { $j = \array_search($new, $this->tokens, true); if ($j === false) { $this->tokens[$i] = $new; } else { \array_splice($this->tokens, $i, 1); } return $this->setAttributeValue(); } return null; } /** * {@inheritdoc} */ public function toggle(string $token, bool $force = null): bool { // init $this->tokenize(); $isThereAfter = false; $i = \array_search($token, $this->tokens, true); if ($force === null) { if ($i === false) { $this->tokens[] = $token; $isThereAfter = true; } else { \array_splice($this->tokens, $i, 1); } } elseif ($force) { if ($i === false) { $this->tokens[] = $token; } $isThereAfter = true; } else { /** @noinspection NestedPositiveIfStatementsInspection */ if ($i !== false) { \array_splice($this->tokens, $i, 1); } } /** @noinspection UnusedFunctionResultInspection */ $this->setAttributeValue(); return $isThereAfter; } /** * @return \DOMAttr|false|null */ private function setAttributeValue() { if ($this->element === null) { return false; } $value = \implode(' ', $this->tokens); if ($this->previousValue === $value) { return null; } $this->previousValue = $value; return $this->element->setAttribute($this->attributeName, $value); } /** * @return void */ private function tokenize() { if ($this->element === null) { return; } $current = $this->element->getAttribute($this->attributeName); if ($this->previousValue === $current) { return; } $this->previousValue = $current; $tokens = \explode(' ', $current); $finals = []; foreach ($tokens as $token) { if ($token === '') { continue; } if (\in_array($token, $finals, true)) { continue; } $finals[] = $token; } $this->tokens = $finals; } }
Java
UTF-8
318
1.539063
2
[]
no_license
package com.stylefent.guns.entity.dto; import lombok.Data; import java.math.BigDecimal; @Data public class ChargeResp { /** * 充值列表id */ private Long id; /** * 西施币数量 */ private BigDecimal xishiNum; /** * rmb数量 */ private BigDecimal rmb; }
C++
UTF-8
450
2.65625
3
[]
no_license
#include "int_double.h" #include "primesieve.hpp" uint64_t prime_count=0; int_double theta=0.0; void callback(uint64_t p) { prime_count++; theta+=log(int_double(p)); } int main(int argc, char **argv) { if(argc!=2) return 0; uint64_t maxn=atol(argv[1]); primesieve::callback_primes(2,maxn,callback); printf("pi(%lu)=%lu\n",maxn,prime_count); printf("theta(%lu) in [%20.18e,%20.18e]\n",maxn,theta.left,-theta.right); return 0; }
Markdown
UTF-8
4,561
2.515625
3
[ "MIT" ]
permissive
--- layout: post title: 看新闻学外语三语周报2010 1 24 -1 30 date: 2010-01-30 categories: [热门词汇] --- 现把汉法英对照2010.1.24.-1.30.日火辣热榜词汇及其例句摘录如下(为更好保持中法英文各自的原汁原味,在消息内容基本一致的前提下法英词语略有不同,不强求一致,特此说明): 1. 中文:俄罗斯第五代歼击机 法文:chasseur russe de cinquième génération 英文:Russia's fifth-generation fighter 中文:2010年1月29日,俄罗斯第五代歼击机T-50在其远东地区首次试飞成功。设计者相信,该新型战机在国际市场上必有销路。 法文:Le 29 janvier 2010, le chasseur russe de 5e génération T-50 a effectué avec succès son premier vol d'essai en Extrême-Orient. Ses concepteurs sont convaincus que le nouvel appareil sera demandé sur le marché international. 英文:Russia's prototype fifth-generation fighter made a 45-minute maiden flight on Friday in the Far East, Russian television reported. 2. 中文:奢侈品 法文:produit de luxe 英文:luxury (goods) 中文:据波士顿咨询公司发布的一份研究报告,中国五至七年后,将成为世界头号奢侈品市场。因为,中国居民收入的增长渐渐驱使他们追求高档商品。 法文:La Chine sera d'ici cinq à sept ans le premier marché mondial des produits de luxe, car la hausse des revenus de ses habitants les pousse progressivement vers les produits haut de gamme, selon une étude publiée par le Boston Consulting Group. 英文:China will become the world’s biggest luxury market in five to seven years as consumers see incomes grow along with sustained appetite for high-end brands despite the recent economic downturn, a survey said in January. 3. 中文:残疾人 法文:personne handicapée 英文:disabled people 中文:美国研究人员近日发明了一种智能装置,能够帮助残疾人用舌头操纵轮椅,从而达到自行活动的目的。 法文:Les chercheurs américains ont mis au point récemment un dispositif ingénieux permettant aux personnes handicapées de se déplacer eux-mêmes dans un fauteuil roulant qu'elles contrôlent à l'aide de leur langue. 英文:American engineers have invented a tongue device which can help disabled people to control a wheelchair. 4. 中文:创新高 法文:atteindre un nouveau record 英文:all-time revenue high 中文:据美国苹果电脑公司周一发布的报告,其利润创新高。 法文:Les profits du fabricant informatique américain Apple atteignent un nouveau record selon un rapport qu'il a publié lundi. 英文:Apple today announced financial results for its fiscal 2010 first quarter ended December 26, 2009. The Company posted revenue of $15.68 billion and a net quarterly profit of $3.38 billion, or $3.67 per diluted share. 5. 中文:录音讲话 法文:message audio 英文:audio message 中文:基地组织魁首本•拉登,在半岛电视台1月24日播出的一篇录音讲话中攻击美国人,声称为阿姆斯特丹-底特律航班未遂炸机案负责,并扬言将发动新的袭击。 法文:Dans un message audio diffusé sur Al-Jazira, le chef d’Al-Qaïda s’en prend aux Américains. Il promet d’autres attaques et revendique celle, manquée, du vol Amsterdam-Detroit. 英文:Al-Qaida leader Osama bin Laden claimed responsibility for the Christmas Day airline bombing attempt in Detroit, in an audio message released yesterday, and vowed further attacks on the US. 6. 中文:海地孤儿 法文:orphelins haïtiens 英文:Haitian orphans 中文:法国第一夫人卡拉•布吕尼今日引人瞩目地在巴黎戴高乐机场露面,迎接躲过1月12日可怕地震劫难的33个海地孤儿。 法文:La Première Dame française Carla Bruni a fait une apparition remarquée aujourd'hui à l'aéroport de Roissy Charles de Gaulle afin d'accueillir 33 orphelins haïtiens, qui ont survécu au terrible tremblement de terre du 12 janvier dernier. 英文:The French first lady Carla Bruni looked delighted as she greeted dozens of Haitian orphans upon their arrival in Paris. 7. 中文:恐怖警戒级别 法文:niveau d'alerte terroriste 英文:terror threat level 中文:伦敦当局上调恐怖警戒级别。 法文:Londres relève son niveau d'alerte terroriste. 英文:Britain has raised its international threat level to 'severe', its second highest level of terror alert, the home secretary says.
Java
UTF-8
565
2.671875
3
[]
no_license
package com.i077CAS.lib; import java.math.BigDecimal; @SuppressWarnings("unused") public class Trig { public static BigDecimal sin(BigDecimal x) { return new BigDecimal(Math.sin(x.doubleValue())); } public static BigDecimal cos(BigDecimal x) { return new BigDecimal(Math.cos(x.doubleValue())); } public static BigDecimal tan(BigDecimal x) { return new BigDecimal(Math.tan(x.doubleValue())); } public static BigDecimal arcsin(BigDecimal x) { return new BigDecimal(Math.asin(x.doubleValue())); } }
Ruby
UTF-8
224
3.390625
3
[]
no_license
def centuryFromYear(year) divideYear = year/100 divideYear.to_i == year/100.0? divideYear : divideYear+1 end puts centuryFromYear(1705) puts centuryFromYear(1900) puts centuryFromYear(1601) puts centuryFromYear(2000)
Java
UTF-8
14,829
1.53125
2
[]
no_license
/* * @(#)InquirySheetController.java 2016-10-10下午4:41:20 * Copyright © 2004-2016 网盟. All rights reserved. */ package com.wangmeng.action; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import javax.annotation.Resource; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.commons.configuration.Configuration; import org.apache.log4j.Logger; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.wangmeng.base.bean.Page; import com.wangmeng.common.pagination.PageInfo; import com.wangmeng.common.utils.KvConstant; import com.wangmeng.common.utils.StringUtil; import com.wangmeng.security.SessionUser; import com.wangmeng.service.api.BuyerInquiryService; import com.wangmeng.service.api.DealQuoteService; import com.wangmeng.service.api.ResultCodeService; import com.wangmeng.service.bean.InquiryComment; import com.wangmeng.service.bean.InquiryQuery; import com.wangmeng.service.bean.InquiryQueryResult; import com.wangmeng.service.bean.InquirySheetModel; import com.wangmeng.service.bean.MapEntity; import com.wangmeng.service.bean.QuoteStatistic; import com.wangmeng.service.bean.ResultCode; import com.wangmeng.service.bean.SheetProduct; import com.wangmeng.web.core.constants.WebConstant; /** * * <ul> * <li> * <p> * @author 宋愿明 [2016-10-10下午4:41:20]<br/> * 新建 * </p> * <b>修改历史:</b><br/> * </li> * </ul> */ @Controller @RequestMapping(value="/inquiry") public class InquirySheetController { private static final String LIST = "business/inquiry/list"; private static final String INQUIRYVIEW = "business/inquiry/view"; private static final String INQUIRYDETAIL = "business/inquiry/detail"; private static final String QUOTEDETAIL = "business/quote/inquiryquote/detail"; private static final String OTHERQUOTEDETAIL = "business/quote/inquiryquote/otherInquery"; private static final String QUOTE = "business/quote/inquiryquote/quote"; @Autowired @Qualifier("wmConfiguration") private Configuration wmConfiguration; private Logger loger = Logger.getLogger(InquirySheetController.class); @Resource private BuyerInquiryService buyerInquiryService; @Resource private ResultCodeService resultCodeService; @Resource private DealQuoteService dealQuoteService; /** * 查询询价单列表 * * @author 宋愿明 * @creationDate. 2016-10-10 下午7:26:24 * @param inquiryquery * @param response * @return */ @RequestMapping(value = "/queryInquerySheet") public String queryInquerySheet( PageInfo page, InquiryQuery inquiryquery, HttpServletResponse response, ModelMap model, HttpSession session) { String inquiryName = inquiryquery.getName(); if (inquiryName != null) { inquiryquery.setName(inquiryName.trim()); } ResultCode result = new ResultCode(); SessionUser user = (SessionUser)session.getAttribute(WebConstant.SESSION_USER); try { if(null != user && user.getUserRole() >0){//客服 inquiryquery.setRoleId(user.getUserRole()); inquiryquery.setSysUserId(user.getId()); } Page<InquiryQueryResult> pageresult = (Page<InquiryQueryResult>)buyerInquiryService.queryInquerySheetListByPage(page,inquiryquery); if(pageresult != null && pageresult.getData() != null){ result.setObj(pageresult); HashMap<String, Object> map = new HashMap<String, Object>(); List<MapEntity> list = buyerInquiryService.queryCountInqueryStatus(map); model.put("statusCount", list); }else{ result.setCode("020001"); result.setValue(resultCodeService.queryResultValueByCode("020001")); } } catch (Exception ex) { loger.error(ex.getMessage()); result.setCode("030001"); result.setValue(resultCodeService.queryResultValueByCode("030001")); } model.put("roleid",user.getUserRole()); model.put("query", inquiryquery); model.put("result", result); if (result!=null && result.getObj()==null){ model.put("page",page); } return LIST; } /** * 查询询价单 状态对应的总计数 * @author 宋愿明 * @creationDate. 2016-10-10 下午6:39:02 * @return */ @ResponseBody @RequestMapping(value="/queryCountInqueryStatus") public ResultCode queryCountInqueryStatus(HttpServletResponse response, HttpSession session){ ResultCode result = new ResultCode(); try{ SessionUser user = (SessionUser)session.getAttribute(WebConstant.SESSION_USER); HashMap<String, Object> map = new HashMap<>(); if(null != user && user.getUserRole() >0){//客服 map.put("roleid", user.getUserRole()); map.put("sysUserId", user.getId()); } List<MapEntity> list = buyerInquiryService.queryCountInqueryStatus(map); if(null != list && list.size() >0){ result.setObj(list); }else{ result.setCode("020001"); result.setValue(resultCodeService.queryResultValueByCode("020001")); } }catch(Exception ex){ loger.error(ex.getMessage()); result.setCode("030001"); result.setValue(resultCodeService.queryResultValueByCode("030001")); } return result; } /** * 询价单查询 * * @author 宋愿明 * @creationDate. 2016-10-11 下午1:55:43 * @param code * 询价单code * @return */ @RequestMapping(value = "/queryInquiryByCode", produces="application/json") public String queryInquiryByCode(String code, @RequestParam(value="isQproduct",required=false) boolean isQproduct, @RequestParam(value="isQbrands",required=false) boolean isQbrands, @RequestParam(value="quoteNo",required=false) String quoteNo, String viewType, ModelMap model){ ResultCode result = new ResultCode(); InquirySheetModel inquiry = null; try { inquiry = buyerInquiryService.getInquiryByCode(code,isQproduct,isQbrands); if(inquiry == null){ result.setCode("020016"); result.setValue(resultCodeService.queryResultValueByCode("020016")); }else{ if(!StringUtil.isNullOrEmpty(quoteNo)){ QuoteStatistic quotes = dealQuoteService.getQuoteStatisticByCode(quoteNo); if(null != quotes && quotes.getQuoteList() != null){ inquiry.setProducts(quotes.getQuoteList()); model.put("quoteStatistic", quotes); } } result.setObj(inquiry); } } catch (Exception e) { result.setCode("020016"); result.setValue(resultCodeService.queryResultValueByCode("020016")); } model.put("result", result); model.put("mediaPath", wmConfiguration.getProperty("filePath")); if("1".equals(viewType)){//查看 return INQUIRYVIEW; }else if("2".equals(viewType)){//详情 if(inquiry.getState() > 3 && inquiry.getState()!=5){//已评价 ResultCode res = this.queryInquiryComment(inquiry.getInquirySheetCode()); if(null != res && res.getObj() != null){ model.put("commontResult", res.getObj()); }else{ model.put("commontResult", null); } } return INQUIRYDETAIL; }else if("3".equals(viewType)){//报价 if(StringUtil.isNullOrEmpty(quoteNo)){ return QUOTE; } return QUOTEDETAIL; } return INQUIRYVIEW; } /** * 继续 * * @author 宋愿明 * @creationDate. 2016-10-11 下午1:55:43 * @param code * 询价单code * @return */ @RequestMapping(value = "/queryOtherInquiryByCode", produces="application/json") public String queryOtherInquiryByCode(String code, @RequestParam(value="isQproduct",required=false) boolean isQproduct, @RequestParam(value="isQbrands",required=false) boolean isQbrands, @RequestParam(value="quoteNo",required=false) String quoteNo, String viewType, ModelMap model){ ResultCode result = new ResultCode(); InquirySheetModel inquiry = null; try { inquiry = buyerInquiryService.getInquiryByCode(code,isQproduct,isQbrands); if(inquiry == null){ result.setCode("020016"); result.setValue(resultCodeService.queryResultValueByCode("020016")); }else{ if(!StringUtil.isNullOrEmpty(code)){ List<QuoteStatistic> quotes = dealQuoteService.getQuoteStatisticDetail(code); if(null != quotes && quotes.size() > 0){ inquiry.setQuotes(quotes); List<String> lst = new ArrayList<String>(); for(QuoteStatistic qu : quotes){ lst.add(qu.getBrandNames()); } model.put("brandNameList", lst); model.put("quotesTimes", quotes.size()); } } result.setObj(inquiry); } } catch (Exception e) { result.setCode("020016"); result.setValue(resultCodeService.queryResultValueByCode("020016")); } model.put("result", result); model.put("mediaPath", wmConfiguration.getProperty("filePath")); if("1".equals(viewType)){//查看 return INQUIRYVIEW; }else if("2".equals(viewType)){//详情 if(inquiry.getState() > 3 && inquiry.getState()!=5){//已评价 ResultCode res = this.queryInquiryComment(inquiry.getInquirySheetCode()); if(null != res && res.getObj() != null){ model.put("commontResult", res.getObj()); }else{ model.put("commontResult", null); } } return INQUIRYDETAIL; }else if("3".equals(viewType)){//报价 return OTHERQUOTEDETAIL; } return INQUIRYVIEW; } /** * 修改询价信息 * * @author 宋愿明 * @creationDate. 2016-10-11 下午2:06:56 * @param param * InquirySheetModel * * @return */ // @ResponseBody @RequestMapping(value = "/updateInquiry", produces="application/json") public String updateInquiryInfo( HttpServletRequest request,InquirySheetModel param, @RequestParam(value="inquiryPhoto",required=false) String inquiryPhoto){ ResultCode result = new ResultCode(); boolean ret = false; try { ret = buyerInquiryService.updateInquiry(param); if(ret){ if(!StringUtil.isNullOrEmpty(inquiryPhoto)){ HashMap<String, Object> map = new HashMap<String, Object>(); map.put("path", inquiryPhoto); map.put("inquiryCode", param.getInquirySheetCode()); map.put("dictcode", KvConstant.INQUERY_DICTCODE); boolean flag = buyerInquiryService.deleteInquiryPhoto(param.getInquirySheetCode()); if(flag){ buyerInquiryService.insertInquiryPhoto(map); }else{ result.setCode("030020"); result.setValue(resultCodeService.queryResultValueByCode("030020")); } } }else{ result.setCode("030020"); result.setValue(resultCodeService.queryResultValueByCode("030020")); } } catch (Exception e) { result.setCode("030020"); result.setValue(resultCodeService.queryResultValueByCode("030020")); } return "redirect:/inquiry/queryInquiryByCode.do?code="+param.getInquirySheetCode()+"&isQproduct=true&viewType=1"; // return LIST; } /** * 审核询价单 * * @author 宋愿明 * @creationDate. 2016-10-11 下午2:45:34 * @param inquiryCode * 询价单code * @param status * 状态 3 审核通过 * @return */ @ResponseBody @RequestMapping(value = "/auditingInquiry", produces="application/json") public ResultCode auditingInquiry( @RequestParam("inquiryCode") String inquiryCode, @RequestParam("status") Integer status){ ResultCode result = new ResultCode(); boolean ret = false; try { if(null != status){ ret = buyerInquiryService.auditingInquiry(inquiryCode, status); } if(!ret){ result.setCode("030022"); result.setValue(resultCodeService.queryResultValueByCode("030022")); } } catch (Exception e) { loger.error(e.getMessage()); result.setCode("030022"); result.setValue(resultCodeService.queryResultValueByCode("030022")); } return result; } /** * 查询询价单评论 * * @author 宋愿明 * @creationDate. 2016-10-11 下午2:45:34 * @param inquiryCode * 询价单code * @param status * 状态 3 审核通过 * @return */ // @ResponseBody @RequestMapping(value = "/queryInquiryComment", produces="application/json") public ResultCode queryInquiryComment( @RequestParam("inquiryCode") String inquiryCode){ ResultCode result = new ResultCode(); try { InquiryComment inquiryComment = null; if(null != inquiryCode){ inquiryComment = buyerInquiryService.queryInquiryComment(inquiryCode); if(inquiryComment != null && inquiryComment.getId() >0){ result.setObj(inquiryComment); return result; } } result.setCode("030019"); result.setValue(resultCodeService.queryResultValueByCode("030019")); } catch (Exception e) { loger.error(e.getMessage()); result.setCode("030001"); result.setValue(resultCodeService.queryResultValueByCode("030001")); } return result; } /** * 报价时-查询询价产品 * * @author 宋愿明 * @creationDate. 2016-10-11 下午6:51:59 * @param inquiryCode * 询价单code * @param brandsId * 询价单品牌 * @param brandsName * 品牌名称 * @return */ @ResponseBody @RequestMapping(value = "/queryInquiryProductByCode", produces="application/json") public ResultCode queryInquiryProductByCode( @RequestParam(value="inquiryCode")String inquiryCode, @RequestParam(value="brandsId")Integer brandsId, @RequestParam(value="brandsName") String brandsName){ ResultCode result = new ResultCode(); try { List<SheetProduct> sheetProduct = buyerInquiryService.queryInquiryProductByCode(inquiryCode,brandsId,brandsName); if(sheetProduct != null && sheetProduct.size() >0){ result.setObj(sheetProduct); }else{ result.setCode("020016"); result.setValue(resultCodeService.queryResultValueByCode("020016")); } } catch (Exception e) { result.setCode("020016"); result.setValue(resultCodeService.queryResultValueByCode("020016")); } return result; } /** * 删除询价单 * * @author 宋愿明 * @creationDate. 2016-11-1 下午7:36:44 * @param inquiryCode * @param status * @return */ @RequestMapping(value = "/deleteInquiry", produces="application/json") public String deleteInquiry( @RequestParam("inquiryCode") String inquiryCode, @RequestParam("status") Integer status){ ResultCode result = new ResultCode(); boolean ret = false; try { if(null != status){ ret = buyerInquiryService.auditingInquiry(inquiryCode, status); } if(!ret){ result.setCode("030027"); result.setValue(resultCodeService.queryResultValueByCode("030027")); } } catch (Exception e) { loger.error(e.getMessage()); result.setCode("030027"); result.setValue(resultCodeService.queryResultValueByCode("030027")); } return "redirect:/inquiry/queryInquerySheet.do"; } }
Java
UTF-8
436
2.3125
2
[]
no_license
package com.ecart.bbva.constant; public enum ServiceError { NOT_SAVED("002", "No records found"), NOT_UPDATED("003", "No records found"), NOT_DELETED("004", "No records found"); private String code; private String message; private ServiceError(String code, String message) { this.code = code; this.message = message; } public String getCode() { return code; } public String getMessage() { return message; } }
C#
UTF-8
1,930
2.875
3
[ "Apache-2.0", "LicenseRef-scancode-generic-cla" ]
permissive
using System; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; using Dmarc.Common.Encryption; namespace Dmarc.Common.Data { public interface IConnectionInfoAsync { Task<string> GetConnectionStringAsync(); } public class ConnectionInfoAsync : IConnectionInfoAsync { private readonly IParameterStoreRequest _parameterStoreRequest; private readonly string _connectionString; private const string StringToReplace = "Pwd = "; public ConnectionInfoAsync(IParameterStoreRequest parameterStoreRequest, IConnectionInfo connectionString) { _parameterStoreRequest = parameterStoreRequest; _connectionString = connectionString.ConnectionString; } public async Task<string> GetConnectionStringAsync() { if (ShouldAppendString(_connectionString)) { string username = GetDatabaseUsername(_connectionString); string password = await _parameterStoreRequest.GetParameterValue(username); StringBuilder sb = new StringBuilder(_connectionString); sb.Append(StringToReplace).Append(password).Append(";"); return sb.ToString(); } return _connectionString; } private bool ShouldAppendString(string connectionString) { return !connectionString.Contains(StringToReplace); } private string GetDatabaseUsername(string connectionString) { string pattern = @"Uid =(.*?)\;"; var match = Regex.Match(connectionString, pattern); if (match.Success) { return match.Groups[1].Value.Trim(); } throw new Exception("Unable to find database username in the connection string"); } } }
Python
UTF-8
4,832
2.71875
3
[ "MIT" ]
permissive
import json import uuid import warnings from datetime import datetime from pathlib import Path import dask.dataframe as dd import numpy as np import pandas as pd import pointcloudset DATETIME_FORMAT = "%Y-%m-%d %H:%M:%S.%f" DELIMITER = ";" def dataset_to_dir( dataset_in, file_path: Path, use_orig_filename: bool = True, **kwargs ) -> Path: """Writes Dataset to directory. Args: dataset_in (Dataset): Dataset to write. file_path (pathlib.Path): Destination path. use_orig_filename (bool): Use filename from which the dataset was read. Defaults to ``True``. **kwargs: Keyword arguments to pass to dask to_parquet function """ if not dataset_in.has_pointclouds(): raise ValueError("dataset must have data ") _check_dir(file_path) orig_filename = Path(dataset_in.meta["orig_file"]).stem if len(orig_filename) == 0: orig_filename = str(uuid.uuid4()) folder = file_path.joinpath(orig_filename) if use_orig_filename else file_path empty_data = _get_empty_data(dataset_in) dataset_to_write = dataset_in._replace_empty_frames_with_nan(empty_data) data = dd.from_delayed(dataset_to_write.data) data.to_parquet(folder, **kwargs) meta = dataset_in.meta meta["timestamps"] = [ timestamp.strftime(DATETIME_FORMAT) for timestamp in dataset_in.timestamps ] meta["empty_data"] = empty_data.to_dict() meta["version"] = pointcloudset.__version__ with open(folder.joinpath("meta.json"), "w") as outfile: json.dump(dataset_in.meta, outfile) _check_dir_contents(folder) return folder.parent def dataset_from_dir(dir: Path, ext: str) -> dict: # sourcery skip: simplify-len-comparison """Reads a Dataset from a directory. Args: dir (pathlib.Path): Path of directory. Returns: dict: Lidar data with timestamps and metadata. """ _check_dir(dir) dirs = [e for e in dir.iterdir() if e.is_dir()] if len(dirs) > 0: dirs.sort(key=_get_folder_number) else: dirs = [dir] data = [] timestamps = [] meta = [] for path in dirs: res = _dataset_from_single_dir(path) data.extend(res["data"]) timestamps.extend(res["timestamps"]) meta.append(res["meta"]) meta = meta[0] del meta["timestamps"] if "empty_data" in meta: empty_data = pd.DataFrame.from_dict(meta["empty_data"]) else: empty_data = pd.DataFrame() # for backwards compatibility return { "data": data, "timestamps": timestamps, "meta": meta, "empty_data": empty_data, } def _get_folder_number(path: Path) -> int: try: return int(path.stem) except ValueError: raise ValueError(f"{path} is not a path with a dataset") def _dataset_from_single_dir(dir: Path) -> dict: _check_dir(dir) parquet_files = list(dir.glob("*.parquet")) data = dd.read_parquet(parquet_files) with open(dir.joinpath("meta.json"), "r") as infile: meta = json.loads(infile.read()) timestamps_raw = meta["timestamps"] timestamps = [ datetime.strptime(timestamp, DATETIME_FORMAT) for timestamp in timestamps_raw ] return { "data": data.to_delayed(), "timestamps": timestamps, "meta": meta, } def _check_dir(file_path: Path): if not isinstance(file_path, Path): raise TypeError("expecting a pathlib Path object") if len(file_path.suffix) != 0: raise ValueError("expecting a path not a filename") def _check_dir_contents(dir: Path): """Quick test if all""" sub_dirs = list(dir.glob("**")) for path in sub_dirs: if len(sub_dirs) != 1 and path != dir or len(sub_dirs) == 1: _check_dir_contents_single(path) def _check_dir_contents_single(dir: Path): """checking the folder content of a written dataset.""" assert dir.joinpath("meta.json").is_file(), f"meta.json is missing in {dir}" assert dir.joinpath("part.0.parquet"), f"part.0.parquet is missing in {dir}" def _get_empty_data(dataset_in) -> pd.DataFrame: """Get an row of data to use as placeholder for empty datasets. Args: dataset_in (Dataset): Dataset which contains at least on valid pointcloud. Returns: pd.DataFrame: empta data placeholder """ empty_data = pd.DataFrame.from_dict( { "x": [np.nan], "y": [np.nan], "z": [np.nan], "original_id": [np.nan], } ) with warnings.catch_warnings(): warnings.filterwarnings("ignore", category=RuntimeWarning) for pointcloud in dataset_in: if len(pointcloud) > 0: empty_data = pd.DataFrame(pointcloud.data.iloc[0]).T break return empty_data
Java
GB18030
1,576
2.296875
2
[]
no_license
package com.main; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.apache.log4j.Logger; public class LoginAction implements Action { Logger logger = Logger.getLogger(LoginAction.class); @Override public ActionForward execute(HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException { logger.info("execute ȣ⼺"); Map<String,Object> pMap = new HashMap<String,Object>(); String emp_no = req.getParameter("emp_no"); String emp_pw = req.getParameter("emp_pw"); pMap.put("emp_no", emp_no); pMap.put("emp_pw", emp_pw); String path = ""; ActionForward forward = new ActionForward(); //true : sendRedirect - ο û , false : forward - List<Map<String,Object>> empList = null; String emp_name = ""; emp_name = LoginLogic.login(pMap); HttpSession session = req.getSession(); // ü session.setAttribute("emp_name", emp_name); session.setAttribute("emp_no", emp_no); if ( "".equals(emp_name) ){ path = "../finalAdmin/adminMain.jsp"; } else if ( "".equals(emp_name) ){ path = "../finalAdmin/loginFail.jsp"; } else { path = "../finalAdmin/index.jsp"; //path = "../finalAdmin/index.jsp"; } forward.setRedirect(false); forward.setPath(path); return forward; } }
Ruby
UTF-8
591
3.625
4
[]
no_license
class Employee attr_accessor :name attr_accessor :email attr_accessor :phone attr_accessor :salary attr_accessor :reviews def initialize(name, email, phone, salary) @name = name @email = email @phone = phone @salary = salary @reviews = [] @is_satisfactory = true end def add_review(new_review) @reviews.push(new_review) end def satisfactory @is_satisfactory = true end def unsatisfactory @is_satisfactory = false end def satisfactory? @is_satisfactory end def give_raise(amount) @salary += amount end end
Java
UTF-8
842
2.28125
2
[ "MIT" ]
permissive
package org.cthul.monad.result; import java.util.function.Supplier; import org.cthul.monad.Scope; import org.cthul.monad.Status; import org.cthul.monad.ValueIsPresentException; public class RuntimeExceptionResult extends AbstractUnsafe<Object, RuntimeException> implements NoResult { private final Supplier<RuntimeException> exceptionSupplier; public RuntimeExceptionResult(Scope scope, Status status, Supplier<RuntimeException> exceptionSupplier) { super(scope, status); this.exceptionSupplier = exceptionSupplier; } public RuntimeExceptionResult(Scope scope, Status status, RuntimeException exception) { this(scope, status, () -> exception); } @Override public RuntimeException getException() throws ValueIsPresentException { return exceptionSupplier.get(); } }
Java
UTF-8
3,064
2.296875
2
[]
no_license
package br.inf.ufes.findmydestiny.core.persistence; import java.io.Serializable; import java.util.Calendar; import java.util.List; import javax.ejb.Stateless; import javax.enterprise.context.ApplicationScoped; import javax.persistence.EntityManager; import javax.persistence.PersistenceContext; import javax.persistence.Tuple; import javax.persistence.TypedQuery; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.ParameterExpression; import javax.persistence.criteria.Path; import javax.persistence.criteria.Root; import org.hibernate.Query; import br.inf.ufes.findmydestiny.core.domain.TourismPackage; @ApplicationScoped public class TourismPackageDAO implements Serializable { private static final long serialVersionUID = 1L; @PersistenceContext(unitName="FindMyDestiny") private EntityManager em; public boolean insertPackage(String tp, Long userid,String startDate,String endDate) { try { TourismPackage tpa = new TourismPackage(); tpa.setUserid(userid); tpa.setPackageName(tp); tpa.setStartDate(startDate); tpa.setEndDate(endDate); em.persist(tpa); return true; } catch(Exception e) { e.printStackTrace(); } return false; } /* public List<Tuple> searchPackages(Long userid) { try { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Tuple> q = cb.createTupleQuery(); Root<TourismPackage> pkg = q.from(TourismPackage.class); Path<Integer> pkgid = pkg.get("packageId"); Path<Long> pkgname = pkg.get("packageName"); q.multiselect(pkgname,pkgid); q.where(cb.equal(pkg.get("userid"), userid)); return em.createQuery(q).getResultList(); }catch(Exception e) { e.printStackTrace(); } return null; }*/ public List<TourismPackage> searchPackages(Long userid) { try { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<TourismPackage> q = cb.createQuery(TourismPackage.class); Root<TourismPackage> pkg = q.from(TourismPackage.class); //Path<Integer> pkgid = pkg.get("packageId"); //Path<Long> pkgname = pkg.get("packageName"); q.select(pkg); q.where(cb.equal(pkg.get("userid"), userid)); return em.createQuery(q).getResultList(); }catch(Exception e) { e.printStackTrace(); } return null; } public List<TourismPackage> retrieveAll() { try { CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<TourismPackage> q = cb.createQuery(TourismPackage.class); Root<TourismPackage> pkg = q.from(TourismPackage.class); q.select(pkg); return em.createQuery(q).getResultList(); }catch(Exception e) { e.printStackTrace(); } return null; } public void deletePackage(int id) { try { TourismPackage tp = em.find(TourismPackage.class, id); em.remove(tp); } catch(Exception e) { e.printStackTrace(); } } }
Java
UTF-8
1,574
2.6875
3
[]
no_license
package com.book1.web; import com.book1.pojo.User; import com.book1.service.impl.UserServiceImpl; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; public class LoginServlet extends HttpServlet { private UserServiceImpl userService=new UserServiceImpl(); @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // resp.setContentType("text/html;charset=UTF-8"); // PrintWriter writer = resp.getWriter(); //1、获取请求参数 String username=req.getParameter("username"); String password=req.getParameter("password"); System.out.println("用户名"+username+"密码"+password); //2、调用UserServiceImpl处理业务 User login = userService.login(new User(null, username, password, null)); if(login==null){ System.out.println("用户名和密码错误,登陆失败"); // writer.print("检测能否输出"); //如果信息错误,则回显用户名 req.setAttribute("msg","用户名或密码错误!"); req.setAttribute("username",username); req.getRequestDispatcher("/login.jsp").forward(req,resp); }else { System.out.println("登陆成功!"); req.getRequestDispatcher("/login_success.jsp").forward(req,resp); } } }
C#
UTF-8
3,385
3.046875
3
[]
no_license
/* * date: 2018-10-06 * author: John-chen * cn: 日志打印类 * en: Log print class */ namespace LogTool { /// <summary> /// 日志打印 /// </summary> public class Log { /// <summary> /// 是否保存到客户端 /// </summary> public static bool IsSaveToClient; /// <summary> /// 是否上传到服务器 /// </summary> public static bool IsSendToServer; /// <summary> /// 设置打印委托 /// </summary> /// <param name="logDelegage"></param> public static void SetLogDelegate(LogDelegate logDelegage) { if(_ins == null) _ins = new Log(); _ins._logDelegate = logDelegage ?? null; } /// <summary> /// info 打印 /// </summary> /// <param name="logInfo"> 打印内容 </param> public static void Info(object logInfo) { var lv = LogLevel.Info; _ins?.LogPrint(logInfo, lv); _ins?.SaveLogInfo(logInfo, lv); } /// <summary> /// 警告信息 打印 /// </summary> /// <param name="logInfo"></param> public static void Warning(object logInfo) { var lv = LogLevel.Warning; _ins?.LogPrint(logInfo, lv); _ins?.SaveLogInfo(logInfo, lv); } /// <summary> /// 错误信息 打印 /// </summary> /// <param name="logInfo"></param> public static void Error(object logInfo) { var lv = LogLevel.Error; _ins?.LogPrint(logInfo, lv); _ins?.SaveLogInfo(logInfo, lv); } /// <summary> /// 日志打印 /// </summary> /// <param name="logInfo"></param> /// <param name="lv"></param> private void LogPrint(object logInfo, LogLevel lv) { _ins?._logDelegate?.Invoke(logInfo, lv); } /// <summary> /// 保存log 信息 /// </summary> /// <param name="logInfo"></param> /// <param name="lv"></param> private void SaveLogInfo(object logInfo, LogLevel lv) { SaveToClient(logInfo, lv); SendToServer(logInfo, lv); } /// <summary> /// 保存到客户端 /// </summary> /// <param name="logInfo"></param> /// <param name="lv"></param> private void SaveToClient(object logInfo, LogLevel lv) { if(!IsSaveToClient) return; // 按 <[时间] 代码行数:打印内容> 存储 } /// <summary> /// 发送到服务器 /// </summary> /// <param name="logInfo"></param> /// <param name="lv"></param> private void SendToServer(object logInfo, LogLevel lv) { if(!IsSendToServer) return; // 按 <[时间] 代码行数:打印内容> 发送 } /// <summary> /// 静态单例 /// </summary> private static Log _ins; /// <summary> /// 打印委托 /// </summary> private LogDelegate _logDelegate; } }
Java
UTF-8
6,668
1.90625
2
[]
no_license
package com.saltfishsoft.springclouddemo.auth; import com.fasterxml.jackson.databind.ObjectMapper; import com.google.common.collect.ImmutableList; import com.saltfishsoft.springclouddemo.common.annotation.FieldDesc; import com.saltfishsoft.springclouddemo.common.domain.BusinessObject; import lombok.Getter; import lombok.Setter; import org.junit.Before; import org.junit.Rule; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.restdocs.JUnitRestDocumentation; import org.springframework.restdocs.headers.RequestHeadersSnippet; import org.springframework.restdocs.payload.FieldDescriptor; import org.springframework.restdocs.snippet.Snippet; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.result.MockMvcResultHandlers; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.context.WebApplicationContext; import java.lang.reflect.Field; import java.lang.reflect.ParameterizedType; import java.util.ArrayList; import java.util.List; import static org.springframework.restdocs.headers.HeaderDocumentation.headerWithName; import static org.springframework.restdocs.headers.HeaderDocumentation.requestHeaders; import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.document; import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration; import static org.springframework.restdocs.operation.preprocess.Preprocessors.*; import static org.springframework.restdocs.payload.PayloadDocumentation.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; /** * Created by Shihongbing on 2020/6/29. */ @SpringBootTest @RunWith(SpringRunner.class) @AutoConfigureMockMvc @Setter @Getter public class BaseControllerTest<T> { private Class<T> entityClass = (Class<T>) ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];//获取泛型T的类 private List<FieldDescriptor> fieldDescriptors = new ArrayList<>();//泛型T的字段说明 private List<FieldDescriptor> objectResultFieldDescriptors = new ArrayList<>();//返回结果的data为Object的字段说明 private List<FieldDescriptor> booleanResultFieldDescriptors = new ArrayList<>();//返回结果的data为Boolean的字段说明 @Rule public final JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(); @Autowired protected ObjectMapper objectMapper; @Autowired protected WebApplicationContext context; @Autowired protected MockMvc mockMvc; //定义接口文档输出的位置格式 private final String documentLocation = "{ClassName}/{methodName}"; @Before public void setUp() { this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context) .apply(documentationConfiguration(this.restDocumentation)) .build(); for (Field declaredField : BusinessObject.class.getDeclaredFields()) { if(declaredField.getAnnotation(FieldDesc.class)!=null){ addReponseField(declaredField); } } for (Field declaredField : entityClass.getDeclaredFields()) { if(declaredField.getAnnotation(FieldDesc.class)!=null){ addReponseField(declaredField); } } objectResultFieldDescriptors.addAll(commonRestFiled()); } public void addReponseField(Field declaredField){ fieldDescriptors.add(fieldWithPath(declaredField.getName()).description(declaredField.getAnnotation(FieldDesc.class).value())); } public MvcResult afterRequest(ResultActions resultActions, List<Snippet> snippets) throws Exception { //为传进来的snippets在前面加上返回结果的字段说明 snippets.add(0, relaxedResponseFields( objectResultFieldDescriptors )); return resultActions .andDo(MockMvcResultHandlers.print()) .andExpect(status().isOk()) .andDo( document(documentLocation, preprocessRequest(prettyPrint()), preprocessResponse(prettyPrint()), snippets.toArray(new Snippet[0]) ) ) .andReturn(); } public List<FieldDescriptor> commonRestFiled(){ ImmutableList<FieldDescriptor> fieldDescriptors = ImmutableList.of( fieldWithPath("success").description("操作结果"), subsectionWithPath("data").description("接口返回的数据对象"), fieldWithPath("code").description("错误编号"), fieldWithPath("message").description("错误信息")); return fieldDescriptors; } //共用请求头 public RequestHeadersSnippet commonRequestHeader(){ return requestHeaders( headerWithName("Authorization").description( "Basic auth credentials"), headerWithName("Content-Type").description( "application/json")); } public static void main(String args[]){ // Field fields[] = User.class.getDeclaredFields(); // for(Field field : fields){ // Class type = field.getType(); // //System.out.println(type); // // if(type == String.class){ // System.out.println(field.getName()+":String"); // }else if(type == int.class || type == Integer.class || type == Float.class || type == float.class || type==Double.class || type==double.class || type == Long.class || type== long.class){ // System.out.println(field.getName()+":Number"); // }else if(type == List.class || type == Set.class){ // System.out.println(field.getName()+":Collection"); // }else if(type == Boolean.class || type == boolean.class){ // System.out.println(field.getName()+":Boolean"); // }else if(type.isArray()){ // System.out.println(field.getName()+":Array"); // }else{ // System.out.println(field.getName()+":Unknow"); // } // } } }
JavaScript
UTF-8
1,289
4.125
4
[]
no_license
/** * algorithm: In order to sort A[1...n], we recursively sort A[1..n-1] and then insert A[n] into the sorted array A[1..n-1] * */ const recursiveInsertionSort = arr => { if (arr.length === 1) { return arr; } const subArr = arr.slice(0, arr.length - 1); const lastElement = arr[arr.length - 1]; const result = insertIntoSorted(recursiveInsertionSort(subArr), lastElement) return result; } const insertIntoSorted = (sortedArr, element) => { if (sortedArr.length === 1) { return sortedArr[0] >= element ? [element, sortedArr[0]] : [sortedArr[0], element]; } if (element <= sortedArr[0]) { return [element, ...sortedArr]; } if (element >= sortedArr[sortedArr.length - 1]) { return [...sortedArr, element]; } let index = 0; while (index < sortedArr.length) { if (element <= sortedArr[index]) { return [element, ...arr] } else if (element >= sortedArr[index] && element < sortedArr[index + 1]) { return [...sortedArr.slice(0, index + 1), element, ...sortedArr.slice(index + 1, sortedArr.length)] } index++; } } // console.log(insertIntoSorted([4, 5], 3)) console.log(recursiveInsertionSort([5, 4, 3, 2, 100, 1000, -100]))
C#
UTF-8
896
3.390625
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Example03 { internal class Program { private static void Main(string[] args) { int cols = 3; int x0 = 3; int y0 = 3; int w = 100; int h = 100; int dw = 10; int dh = 20; for (int number = 0; number < 10; number++) { // row = 編號 / 一排幾個 得到的商 int row = number / cols; int col = number % cols; int x = col * (w + dw) + x0; int y = row * (h + dh) + y0; Console.WriteLine("number = {0}, (row, col) = ({1}, {2}), (x, y) = ({3}, {4})" , number + 1, row + 1, col + 1, x, y); } } } }
Java
UTF-8
1,123
2.53125
3
[]
no_license
package dev.Rishi.tilegame.state; import java.awt.Color; import java.awt.Graphics; import dev.Rishi.tilegame.Handler; import dev.Rishi.tilegame.UI.ClickListener; import dev.Rishi.tilegame.UI.UIImageButton; import dev.Rishi.tilegame.UI.UIManager; import dev.Rishi.tilegame.gfx.Assets; import dev.Rishi.tilegame.gfx.Text; //basic credits screen public class CreditState extends State{ private UIManager uiManager; public CreditState(final Handler handler) { super(handler); uiManager = new UIManager(handler); handler.getMouseManager().setUiManager(uiManager); uiManager.addObject(new UIImageButton(412, 600, 200, 75, Assets.button_back, new ClickListener() { @Override public void onClick() { handler.getMouseManager().setUiManager(null); MenuState menu = new MenuState(handler); State.setState(menu); }})); } @Override public void render(Graphics g) { g.drawImage(Assets.background, 0, 0, null); uiManager.render(g); Text.drawString(g, "Made by Rishab Goswami and Grun Wua Wong", 512, 384, true, Color.BLACK, 28); } @Override public void tick() { uiManager.tick(); } }
Java
UTF-8
8,548
2.25
2
[]
no_license
package com.gsu.petclinic.domain; import com.gsu.petclinic.reference.PetType; import flexjson.JSONDeserializer; import flexjson.JSONSerializer; import java.util.ArrayList; import java.util.Collection; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EntityManager; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToOne; import javax.persistence.PersistenceContext; import javax.persistence.SequenceGenerator; import javax.persistence.TypedQuery; import javax.persistence.Version; import javax.validation.constraints.Min; import javax.validation.constraints.NotNull; import javax.validation.constraints.Size; import org.apache.commons.lang3.builder.ReflectionToStringBuilder; import org.apache.commons.lang3.builder.ToStringStyle; import org.springframework.beans.factory.annotation.Configurable; import org.springframework.roo.addon.javabean.RooJavaBean; import org.springframework.roo.addon.jpa.activerecord.RooJpaActiveRecord; import org.springframework.roo.addon.tostring.RooToString; import org.springframework.transaction.annotation.Transactional; @Configurable @Entity @RooJavaBean @RooToString @RooJpaActiveRecord(sequenceName = "PET_SEQ", finders = { "findPetsByNameAndWeight", "findPetsByOwner", "findPetsBySendRemindersAndWeightLessThan", "findPetsByTypeAndNameLike" }) public class Pet { @NotNull private boolean sendReminders; @NotNull @Size(min = 1) private String name; @NotNull @Min(0L) private Float weight; @ManyToOne private Owner owner; @NotNull @Enumerated private PetType type; private String ownerName; public String getOwnerName() { if (this.owner != null) return this.owner.getFirstName()+" "+this.owner.getLastName(); else return "None"; } public String setOwnerName() { if (this.owner != null) return this.owner.getFirstName()+" "+this.owner.getLastName(); else return "None"; } @PersistenceContext transient EntityManager entityManager; public static final EntityManager entityManager() { EntityManager em = new Pet().entityManager; if (em == null) throw new IllegalStateException("Entity manager has not been injected (is the Spring Aspects JAR configured as an AJC/AJDT aspects library?)"); return em; } public static long countPets() { return entityManager().createQuery("SELECT COUNT(o) FROM Pet o", Long.class).getSingleResult(); } public static List<Pet> findAllPets() { return entityManager().createQuery("SELECT o FROM Pet o", Pet.class).getResultList(); } public static Pet findPet(Long id) { if (id == null) return null; return entityManager().find(Pet.class, id); } public static List<Pet> findPetEntries(int firstResult, int maxResults) { return entityManager().createQuery("SELECT o FROM Pet o", Pet.class).setFirstResult(firstResult).setMaxResults(maxResults).getResultList(); } @Transactional public void persist() { if (this.entityManager == null) this.entityManager = entityManager(); this.entityManager.persist(this); } @Transactional public void remove() { if (this.entityManager == null) this.entityManager = entityManager(); if (this.entityManager.contains(this)) { this.entityManager.remove(this); } else { Pet attached = Pet.findPet(this.id); this.entityManager.remove(attached); } } @Transactional public void flush() { if (this.entityManager == null) this.entityManager = entityManager(); this.entityManager.flush(); } @Transactional public void clear() { if (this.entityManager == null) this.entityManager = entityManager(); this.entityManager.clear(); } @Transactional public Pet merge() { if (this.entityManager == null) this.entityManager = entityManager(); Pet merged = this.entityManager.merge(this); this.entityManager.flush(); return merged; } public String toString() { return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE); } public static TypedQuery<Pet> findPetsByNameAndWeight(String name, Float weight) { if (name == null || name.length() == 0) throw new IllegalArgumentException("The name argument is required"); if (weight == null) throw new IllegalArgumentException("The weight argument is required"); EntityManager em = Pet.entityManager(); TypedQuery<Pet> q = em.createQuery("SELECT o FROM Pet AS o WHERE o.name = :name AND o.weight = :weight", Pet.class); q.setParameter("name", name); q.setParameter("weight", weight); return q; } public static TypedQuery<Pet> findPetsByOwner(Owner owner) { if (owner == null) throw new IllegalArgumentException("The owner argument is required"); EntityManager em = Pet.entityManager(); TypedQuery<Pet> q = em.createQuery("SELECT o FROM Pet AS o WHERE o.owner = :owner", Pet.class); q.setParameter("owner", owner); return q; } public static TypedQuery<Pet> findPetsBySendRemindersAndWeightLessThan(boolean sendReminders, Float weight) { if (weight == null) throw new IllegalArgumentException("The weight argument is required"); EntityManager em = Pet.entityManager(); TypedQuery<Pet> q = em.createQuery("SELECT o FROM Pet AS o WHERE o.sendReminders = :sendReminders AND o.weight < :weight", Pet.class); q.setParameter("sendReminders", sendReminders); q.setParameter("weight", weight); return q; } public static TypedQuery<Pet> findPetsByTypeAndNameLike(PetType type, String name) { if (type == null) throw new IllegalArgumentException("The type argument is required"); if (name == null || name.length() == 0) throw new IllegalArgumentException("The name argument is required"); name = name.replace('*', '%'); if (name.charAt(0) != '%') { name = "%" + name; } if (name.charAt(name.length() - 1) != '%') { name = name + "%"; } EntityManager em = Pet.entityManager(); TypedQuery<Pet> q = em.createQuery("SELECT o FROM Pet AS o WHERE o.type = :type AND LOWER(o.name) LIKE LOWER(:name)", Pet.class); q.setParameter("type", type); q.setParameter("name", name); return q; } @Id @SequenceGenerator(name = "petGen", sequenceName = "PET_SEQ") @GeneratedValue(strategy = GenerationType.AUTO, generator = "petGen") @Column(name = "id") private Long id; @Version @Column(name = "version") private Integer version; public Long getId() { return this.id; } public void setId(Long id) { this.id = id; } public Integer getVersion() { return this.version; } public void setVersion(Integer version) { this.version = version; } public boolean isSendReminders() { return this.sendReminders; } public void setSendReminders(boolean sendReminders) { this.sendReminders = sendReminders; } public String getName() { return this.name; } public void setName(String name) { this.name = name; } public Float getWeight() { return this.weight; } public void setWeight(Float weight) { this.weight = weight; } public Owner getOwner() { return this.owner; } public void setOwner(Owner owner) { this.owner = owner; } public PetType getType() { return this.type; } public void setType(PetType type) { this.type = type; } public void setOwnerName(String ownerName) { this.ownerName = ownerName; } public String toJson() { return new JSONSerializer().exclude("*.class").serialize(this); } public static Pet fromJsonToPet(String json) { return new JSONDeserializer<Pet>().use(null, Pet.class).deserialize(json); } public static String toJsonArray(Collection<Pet> collection) { return new JSONSerializer().exclude("*.class").serialize(collection); } public static Collection<Pet> fromJsonArrayToPets(String json) { return new JSONDeserializer<List<Pet>>().use(null, ArrayList.class).use("values", Pet.class).deserialize(json); } }
Java
UTF-8
2,218
2.109375
2
[]
no_license
package com.lolabotona.restapi.repository; import java.sql.Timestamp; import java.util.List; import java.util.Optional; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import com.lolabotona.restapi.model.Group; import com.lolabotona.restapi.model.User; import com.lolabotona.restapi.model.UserGroup; public interface UserGroupRepository extends JpaRepository<UserGroup, Long> { // ejemplo funcionando con nativeQuery // @Query(value = "SELECT * FROM user_group WHERE groupid = ?1 and userid = ?2 and type = ?3", nativeQuery = true) // UserGroup asdf( String group, String user ,String type ); //ejemplo funcionando con JPQL // @Query("SELECT u FROM UserGroup u WHERE u.group = ?1 and u.user = ?2 and u.type = ?3") // List<UserGroup> asdf( Group group, User user ,String type ); Optional<UserGroup> findByUserAndGroupAndType(User user, Group group, String type); Optional<UserGroup> findByUserAndGroupAndTypeAndDateat(User user, Group group, String type,Timestamp dateAt); @Query(value = "SELECT * FROM user_group ", nativeQuery = true) List<UserGroup> getAllCustom(); List<UserGroup> findByGroupIn(List<Group> group); //List<UserGroup> findByGroupAndUserAndType(Group group,User user, String type); List<UserGroup> findByUserAndGroup(User user, Group group); List<UserGroup> findByGroupAndType( Group group, String type ); List<UserGroup> findByGroupAndTypeAndDateat( Group group, String type,Timestamp dateAt ); int countByTypeAndUserAndRetrievedAndDateatBetween(String type,User user,boolean retrieve,Timestamp start,Timestamp end ); Optional<UserGroup> findTop1ByTypeAndUserAndRetrievedAndDateatBetweenOrderByDateat(String type,User user,boolean retrieve,Timestamp start,Timestamp end ); List<UserGroup> findByTypeAndUserAndRetrievedAndDateatBetween(String type,User user,boolean retrieve,Timestamp start,Timestamp end ); List<UserGroup> findByGroupInAndUserInAndTypeInAndDateatBetweenOrderByDateat( List<Group> groups,List<User> users, List<String> types,Timestamp start,Timestamp end ); List<UserGroup> findByGroupInAndUserInAndType( List<Group> groups,List<User> users, String type ); }
Swift
UTF-8
604
2.984375
3
[]
no_license
// // ColorPickerView.swift // SwiftUIBootcamp // // Created by ramil on 27.02.2021. // import SwiftUI struct ColorPickerView: View { @State private var backgroundColor: Color = .orange var body: some View { ZStack { backgroundColor.edgesIgnoringSafeArea(.all) ColorPicker("Select a color", selection: $backgroundColor, supportsOpacity: true) .padding() } } } struct ColorPickerView_Previews: PreviewProvider { static var previews: some View { ColorPickerView() } }
C#
UTF-8
2,181
2.734375
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Drawing; namespace Ludo { public class EndScreen : Panel { public EndScreen(GUI parent) { this.parent = parent; parent.Controls.Add(this); Size = new Size(820, 820); Location = new Point(0, 0); BorderStyle = BorderStyle.None; winner = new Label(); Controls.Add(winner); winner.Size = new Size(820, 200); winner.Location = new Point(0, 290); winner.TextAlign = ContentAlignment.MiddleCenter; winner.Font = new Font("Arial", 70, FontStyle.Bold); winner.BackColor = GUI.GetColor("black"); winner.ForeColor = GUI.GetColor("white"); replay = new Label(); Controls.Add(replay); replay.Size = new Size(820, 200); replay.Location = new Point(0, 50); replay.TextAlign = ContentAlignment.MiddleCenter; replay.Font = new Font("Arial", 100, FontStyle.Bold); replay.Text = "R E P L A Y"; replay.ForeColor = GUI.GetColor("black"); replay.Click += (sender, e) => { parent.Replay(); }; // todo quit = new Label(); Controls.Add(quit); quit.Size = new Size(820, 200); quit.Location = new Point(0, 520); quit.TextAlign = ContentAlignment.MiddleCenter; quit.Font = new Font("Arial", 100, FontStyle.Bold); quit.Text = "Q U I T"; quit.ForeColor = GUI.GetColor("black"); quit.Click += (sender, e) => { System.Environment.Exit(0); }; Hide(); } public void Display(string color) { BackColor = GUI.GetColor(color); replay.BackColor = GUI.GetColor(color); quit.BackColor = GUI.GetColor(color); BringToFront(); winner.Text = $"{color.ToUpper()} WINS!"; Show(); } Label winner, replay, quit; GUI parent; } }
Java
UTF-8
5,020
1.976563
2
[]
no_license
package project.com.gmklabel.adapter; import android.content.Context; import android.support.annotation.NonNull; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.bumptech.glide.Glide; import java.util.ArrayList; import java.util.List; import project.com.gmklabel.Config.env; import project.com.gmklabel.Konstruktor.Json_keranjang; import project.com.gmklabel.Konstruktor.User_info; import project.com.gmklabel.MainActivity; import project.com.gmklabel.Model.Model; import project.com.gmklabel.Model.Respon_Keranjang; import project.com.gmklabel.R; import project.com.gmklabel.User.User_config; import project.com.gmklabel.fragment.Keranjang; import retrofit2.Call; import retrofit2.Callback; import retrofit2.Response; public class Adapter_Keranjang extends RecyclerView.Adapter<RecyclerView.ViewHolder> { private List<Json_keranjang> list=new ArrayList<>(); private MainActivity context; private env db=new env(); private Keranjang keranjang=new Keranjang(); private MainActivity ctk; public Adapter_Keranjang( Context context) { this.context = (MainActivity) context; this.list = list; } @NonNull @Override public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) { View view= LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_keranjang,viewGroup,false); return new KeranjangHolder(view); } @Override public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, final int i) { KeranjangHolder holder=(KeranjangHolder) viewHolder; holder.idwarna=list.get(i).getIdwarna(); holder.tv_id.setText(list.get(i).getId()); holder.tv_kode.setText(list.get(i).getKode_barang()); holder.tv_barang.setText(list.get(i).getBarang()); holder.tv_varian.setText(list.get(i).getWarna()); holder.tv_cvarian.setText(list.get(i).getVarian()); holder.tv_qty.setText(list.get(i).getJumlah()); holder.tv_harga.setText(list.get(i).getTotal()); holder.iduser=list.get(i).getIduser(); Glide.with(context).load(env.barang_url+list.get(i).getNama()).into(holder.img); } @Override public int getItemCount() { return list.size(); } private class KeranjangHolder extends RecyclerView.ViewHolder { private TextView tv_id,tv_barang,tv_harga,tv_varian,tv_qty,tv_kode,tv_cvarian; private ImageButton del; private ImageView img; private String iduser; private String idwarna; public KeranjangHolder(View view) { super(view); tv_id=(TextView) view.findViewById(R.id.id); tv_kode=(TextView) view.findViewById(R.id.kode); tv_barang=(TextView) view.findViewById(R.id.barang); tv_varian=(TextView) view.findViewById(R.id.varian); tv_qty=(TextView) view.findViewById(R.id.qty); tv_harga=(TextView) view.findViewById(R.id.harga); del=(ImageButton) view.findViewById(R.id.btn_hapus); tv_cvarian=(TextView) view.findViewById(R.id.cvarian); img=(ImageView) view.findViewById(R.id.img); final User_info info= User_config.getmInstance(context).getUser(); del.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { hapusBarang(); context.getSupportFragmentManager().beginTransaction().replace(R.id.frame,Keranjang.newInstance()).commit(); } }); } private void hapusBarang() { Model model=db.getRespo().create(Model.class); Call<Respon_Keranjang> call=model.hapusK(tv_id.getText().toString(),idwarna,tv_qty.getText().toString()); call.enqueue(new Callback<Respon_Keranjang>() { @Override public void onResponse(Call<Respon_Keranjang> call, Response<Respon_Keranjang> response) { if(response.isSuccessful()){ String msg=response.body().getPesan(); Toast.makeText(context, msg, Toast.LENGTH_SHORT).show(); } } @Override public void onFailure(Call<Respon_Keranjang> call, Throwable throwable) { Toast.makeText(context, String.valueOf(throwable), Toast.LENGTH_SHORT).show(); } }); } } public void add(Json_keranjang keranjang){ list.add(keranjang); notifyItemInserted(list.size()); } public void addAll(List<Json_keranjang> keranjangList){ for(Json_keranjang keranjang:keranjangList){ add(keranjang); } } }
JavaScript
UTF-8
9,727
2.984375
3
[ "MIT" ]
permissive
/*! * Copyright (c) 2017 Benjamin Van Ryseghem<benjamin@vanryseghem.com> * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ const allSuffixes = [ {key: "ZiB", factor: Math.pow(1024, 7)}, {key: "ZB", factor: Math.pow(1000, 7)}, {key: "YiB", factor: Math.pow(1024, 8)}, {key: "YB", factor: Math.pow(1000, 8)}, {key: "TiB", factor: Math.pow(1024, 4)}, {key: "TB", factor: Math.pow(1000, 4)}, {key: "PiB", factor: Math.pow(1024, 5)}, {key: "PB", factor: Math.pow(1000, 5)}, {key: "MiB", factor: Math.pow(1024, 2)}, {key: "MB", factor: Math.pow(1000, 2)}, {key: "KiB", factor: Math.pow(1024, 1)}, {key: "KB", factor: Math.pow(1000, 1)}, {key: "GiB", factor: Math.pow(1024, 3)}, {key: "GB", factor: Math.pow(1000, 3)}, {key: "EiB", factor: Math.pow(1024, 6)}, {key: "EB", factor: Math.pow(1000, 6)}, {key: "B", factor: 1} ]; /** * Generate a RegExp where S get all RegExp specific characters escaped. * * @param {string} s - string representing a RegExp * @return {string} */ function escapeRegExp(s) { return s.replace(/[-/\\^$*+?.()|[\]{}]/g, "\\$&"); } /** * Recursively compute the unformatted value. * * @param {string} inputString - string to unformat * @param {*} delimiters - Delimiters used to generate the inputString * @param {string} [currencySymbol] - symbol used for currency while generating the inputString * @param {function} ordinal - function used to generate an ordinal out of a number * @param {string} zeroFormat - string representing zero * @param {*} abbreviations - abbreviations used while generating the inputString * @param {NumbroFormat} format - format used while generating the inputString * @return {number|undefined} */ function computeUnformattedValue(inputString, delimiters, currencySymbol = "", ordinal, zeroFormat, abbreviations, format) { if (!isNaN(+inputString)) { return +inputString; } let stripped = ""; // Negative let newInput = inputString.replace(/(^[^(]*)\((.*)\)([^)]*$)/, "$1$2$3"); if (newInput !== inputString) { return -1 * computeUnformattedValue(newInput, delimiters, currencySymbol, ordinal, zeroFormat, abbreviations, format); } // Byte for (let i = 0; i < allSuffixes.length; i++) { let suffix = allSuffixes[i]; stripped = inputString.replace(RegExp(`([0-9 ])(${suffix.key})$`), "$1"); if (stripped !== inputString) { return computeUnformattedValue(stripped, delimiters, currencySymbol, ordinal, zeroFormat, abbreviations, format) * suffix.factor; } } // Percent stripped = inputString.replace("%", ""); if (stripped !== inputString) { return computeUnformattedValue(stripped, delimiters, currencySymbol, ordinal, zeroFormat, abbreviations, format) / 100; } // Ordinal let possibleOrdinalValue = parseFloat(inputString); if (isNaN(possibleOrdinalValue)) { return undefined; } let ordinalString = ordinal(possibleOrdinalValue); if (ordinalString && ordinalString !== ".") { // if ordinal is "." it will be caught next round in the +inputString stripped = inputString.replace(new RegExp(`${escapeRegExp(ordinalString)}$`), ""); if (stripped !== inputString) { return computeUnformattedValue(stripped, delimiters, currencySymbol, ordinal, zeroFormat, abbreviations, format); } } // Average let inversedAbbreviations = {}; Object.keys(abbreviations).forEach((key) => { inversedAbbreviations[abbreviations[key]] = key; }); let abbreviationValues = Object.keys(inversedAbbreviations).sort().reverse(); let numberOfAbbreviations = abbreviationValues.length; for (let i = 0; i < numberOfAbbreviations; i++) { let value = abbreviationValues[i]; let key = inversedAbbreviations[value]; stripped = inputString.replace(value, ""); if (stripped !== inputString) { let factor = undefined; switch (key) { // eslint-disable-line default-case case "thousand": factor = Math.pow(10, 3); break; case "million": factor = Math.pow(10, 6); break; case "billion": factor = Math.pow(10, 9); break; case "trillion": factor = Math.pow(10, 12); break; } return computeUnformattedValue(stripped, delimiters, currencySymbol, ordinal, zeroFormat, abbreviations, format) * factor; } } return undefined; } /** * Removes in one pass all formatting symbols. * * @param {string} inputString - string to unformat * @param {*} delimiters - Delimiters used to generate the inputString * @param {string} [currencySymbol] - symbol used for currency while generating the inputString * @return {string} */ function removeFormattingSymbols(inputString, delimiters, currencySymbol = "") { // Currency let stripped = inputString.replace(currencySymbol, ""); // Thousand separators stripped = stripped.replace(new RegExp(`([0-9])${escapeRegExp(delimiters.thousands)}([0-9])`, "g"), "$1$2"); // Decimal stripped = stripped.replace(delimiters.decimal, "."); return stripped; } /** * Unformat a numbro-generated string to retrieve the original value. * * @param {string} inputString - string to unformat * @param {*} delimiters - Delimiters used to generate the inputString * @param {string} [currencySymbol] - symbol used for currency while generating the inputString * @param {function} ordinal - function used to generate an ordinal out of a number * @param {string} zeroFormat - string representing zero * @param {*} abbreviations - abbreviations used while generating the inputString * @param {NumbroFormat} format - format used while generating the inputString * @return {number|undefined} */ function unformatValue(inputString, delimiters, currencySymbol = "", ordinal, zeroFormat, abbreviations, format) { if (inputString === "") { return undefined; } // Zero Format if (inputString === zeroFormat) { return 0; } let value = removeFormattingSymbols(inputString, delimiters, currencySymbol); return computeUnformattedValue(value, delimiters, currencySymbol, ordinal, zeroFormat, abbreviations, format); } /** * Check if the INPUTSTRING represents a time. * * @param {string} inputString - string to check * @param {*} delimiters - Delimiters used while generating the inputString * @return {boolean} */ function matchesTime(inputString, delimiters) { let separators = inputString.indexOf(":") && delimiters.thousands !== ":"; if (!separators) { return false; } let segments = inputString.split(":"); if (segments.length !== 3) { return false; } let hours = +segments[0]; let minutes = +segments[1]; let seconds = +segments[2]; return !isNaN(hours) && !isNaN(minutes) && !isNaN(seconds); } /** * Unformat a numbro-generated string representing a time to retrieve the original value. * * @param {string} inputString - string to unformat * @return {number} */ function unformatTime(inputString) { let segments = inputString.split(":"); let hours = +segments[0]; let minutes = +segments[1]; let seconds = +segments[2]; return seconds + 60 * minutes + 3600 * hours; } /** * Unformat a numbro-generated string to retrieve the original value. * * @param {string} inputString - string to unformat * @param {NumbroFormat} format - format used while generating the inputString * @return {number} */ function unformat(inputString, format) { // Avoid circular references const globalState = require("./globalState"); let delimiters = globalState.currentDelimiters(); let currencySymbol = globalState.currentCurrency().symbol; let ordinal = globalState.currentOrdinal(); let zeroFormat = globalState.getZeroFormat(); let abbreviations = globalState.currentAbbreviations(); let value = undefined; if (typeof inputString === "string") { if (matchesTime(inputString, delimiters)) { value = unformatTime(inputString); } else { value = unformatValue(inputString, delimiters, currencySymbol, ordinal, zeroFormat, abbreviations, format); } } else if (typeof inputString === "number") { value = inputString; } else { return undefined; } if (value === undefined) { return undefined; } return value; } module.exports = { unformat };
Markdown
UTF-8
6,369
2.734375
3
[]
no_license
## 57. Databases 101 6 types of relational databases on AWS - SQL Server - Oracle - MySQL - PostgreSQL - Aurora - Maria Key features of relational databases - Muliple AZ (availability zones) - Read Replicas (for performance) - Max 5 replicas Non Relational databases - DynamoDb Data Warehousing - RedShift OLTP vs OLAP OLTP: Online Transaction Processing OLAP: Online Analytics Processing Memory Cache - ElastiCache - two engines: - Memcache - Redis ### Exam Tips - 6 flavors of Relational Databases - Document database (DynamoDb) - Data Warehousing (Redshift) - Memory Cache (Elasticache) ## 58. Let's Create an RDS Instance Will default to Aurora (AWS product) ### Exam Tips - RDS runs on virtual machines - you cannot log into these machines (AWS managed) - RDS is NOT serverless - exception: Aurora does have a serverless option ## 59. RDS Backups, Multi-AZ and Read Replicas Automated backups - retention period 1 - 35 days - enabled by default Database Snapshots - manual process - stored even after you delete the RDS restoring a database from backup or snapshot will result in new instance Encryption supported by all RDS versions. Multi-AZ - used for availability only, not performance Read Replicas - use for performance improvements - uses asynchronous replication - use for read heavy use cases - must have automatic backups turned on - Read Replicas can be multi-AZ - Read Replicas can be in a separate region ## 60. RDS Backups, Multi-AZ & Read Replicas - Lab ### Exam Tips 2 types of backups - Automated Backups - Database snapshots Read Replcias - Can be multi-AZ - Used to increase performance - must have backups enabled - can be in different regions - does not support MS SQL Server - Can be promoted to normal database (breaks replication) Encryption at rest is enabled for all services ## 61. DynamoDb - Stored on SSD storage - Spread across 3 data centers - Read behaviors - Eventual Consistent Reads (default) - replication happens up to 1 second - Strongly Consistent Reads - fastest response vs writes ## 62. Advanced DynamoDb DAX - DynamoDB Accelerator - 10x performance improvement - no code changes to implement Transactions - can be used on DynamoDb - can work on up two 25 actions (is this just batch write?) Backup and Restore - full backups at any time - no impact on table performance - retained until deleted Point in Time Recovery - not enabled by default - can be used to restore back up to 35 days Streams - Stream Record = a database transaction - Shared = a group of Stream Record use cases for streams: - aggregation - auditing - can be used in conjunction with Lambda to create stored procedures Global Tables - Managed Multi-Master, Multi-Region Replication - Globally distributed - Based on DynamoDB streams (for replication) - Multi-Region redundency - No Applciation rewrites - Replication latency under 1 second DMS (Database Migration Service) - Can be from OnPrem to AWS OR AWS database to a different database type Encryption - enabled by default ## 63. Redshift Data warehouse service - scales to petabytes or terabytes Optimized for analytics queries configuration options: - single node - multi node compresses data based on columns rather than rows. Supports parallel processing Backups - enabled by default, 1 day retention - maximum retention period: 35 days Pricing components - Compute Node Hours - Backups - Data Transfers Security - encrypted at rest - encrypted in transit via SSL Exam Tips - used for Business Intelligence - Only available at 1 AZ - Backups enabled by default with 1 day retention period - Maximum retention period: 35 days - Attempts to always maintain 3 copies of your data (original, replica, and backup on S3) - Can asynconronously replicate snapshot to S3 in another region for disaster recovery ## 64. Aurora AWS Proprietary database Things to know: - Starts at 10 GB, scales to 64 TB (autoscaling) - Compute resources can scale to 32vCPUs and 244 GB memory - 6 total copies of data: 2 copies of data in each availability zone, with minimum 3 avaiability zones Backups - occur automatically - can create snapshots Aurora Serverless - exists - cost-effective option for infrequent, intermittent, or unpredictable workloads - costs less than a reserved instance for certain scenarios Exam Tips - 6 total copies of data: 2 copies of data in each availability zone, with minimum 3 avaiability zones - can take snapshots of Aurora, and share with other accounts - 3 types of replicas available: Aurora, MySQL, and PostgreSQL - has automated backups turned on by default - cost-effective option for infrequent, intermittent, or unpredictable workloads ## 65. Elasticache In-Memory cache in cloud ### 2 caching engines Memcache - simpler option Redis - backups - multiple Avaiability ones - Ranking/Sorting - Advanced datatypes - Persistence - Pub/Sub capability ## 66. Database Migration Services (DMS) Supports heterogenous migrations - MS SQL Server => Aurora AWS Schema Conversion Tool (SCT) - used to convert database for heterogenous migrations - not needed for homogenous migrations (MySql => MySql) Can import from other Cloud platforms like Azure ## 67. Caching Strategies on AWS Caching services: - CloudFront - API Gateway - ElastiCache - DynamoDB Accelerator (DAX) Prioritize caching at outer level searches (CloudFront, API Gateway) ## 68. EMR Overview Elastic Map Reduce Big Data platform within AWS Cluster - Master Node - controller, tracks status of tasks & monitors overall health - Core Node - runs tasks and stores data within the HAdoop Distributed File system (HDFS) - Task Node - runs tasks but DOES NOT store data to HSFS Clusters will always have a master node Multi-server clusters will always have 1+ core node Task nodes are always optional By default logs are stored on Master Node. to avoid loosing these, configure cluster to archive log files to S3. Archiving can be done in 5 minute intervals. MUST BE setup at cluster creation (cannot be changed later) ## 69. Databases Summary ## Quiz: Database on AWS MySQL installation default port number For Online Transaction Processing, exam expects RDS as the correct response Provisioned IOPS is used to increase performance, so is useful for Online Transaction Processing You do NOT need to specify port number for RDS security groups
Python
UTF-8
225
2.515625
3
[]
no_license
from django.db import models # Create your models here. class Student(models.Model): s_name = models.CharField(max_length=30) s_age = models.IntegerField(default=1) def __str__(self): return self.s_name
TypeScript
UTF-8
1,712
2.640625
3
[]
no_license
/*! * Copyright (c) 2017 Adrian Panella <ianchi74@outlook.com>, contributors. * Licensed under the MIT license. */ import { UciSelector } from 'app/uci/uciSelector.class'; import { OptionData } from 'app/uci/data/option'; import { Observable } from 'rxjs/Observable'; import { of } from 'rxjs/observable/of'; import { UciModelService } from 'app/uci/uciModel.service'; import { combineLatest } from 'rxjs/observable/combineLatest'; export class ParameterExpansion { /** Matchs an expansion placeholder `${}`, no escaping (uci names doesn't need it) */ private static _re = /(.*)\${((?:\\.|(?!}).)*[^\\])}/g; parameters: [UciSelector, number][] = []; parsed: string[] = []; constructor(public text: string) { let match: RegExpExecArray, last = 0; ParameterExpansion._re.lastIndex = 0; while ((match = ParameterExpansion._re.exec(text)) && match[0]) { if (match[1]) this.parsed.push(match[1]); if (match[2]) { this.parsed.push(null); this.parameters.push([new UciSelector(match[2]), this.parsed.length - 1]); } last = ParameterExpansion._re.lastIndex; } if (last < text.length) this.parsed.push(text.slice(last)); } bind(context: OptionData, _model: UciModelService): Observable<string> { // fixed string if (!this.parameters.length) return of(this.text); // emmit first when we have all parameters, and then on any change const boundValues = this.parameters.map(p => _model.bindSelector(p[0], context)); return combineLatest(boundValues, (...values) => { const parsed = this.parsed.slice(); this.parameters.forEach((p, i) => parsed[p[1]] = values[i]); return parsed.join(''); }); } }
Java
UTF-8
5,869
2.375
2
[]
no_license
package com.ls.train.files_encryption.utils; import org.apache.commons.httpclient.HttpClient; import org.apache.commons.httpclient.HttpStatus; import org.apache.commons.httpclient.methods.GetMethod; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.StatusLine; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.ContentType; import org.apache.http.entity.mime.HttpMultipartMode; import org.apache.http.entity.mime.MultipartEntityBuilder; import org.apache.http.impl.client.CloseableHttpClient; import org.apache.http.impl.client.HttpClients; import org.apache.http.util.EntityUtils; import org.springframework.web.multipart.MultipartFile; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.charset.Charset; import java.util.UUID; public class MyServerRequest { public static String sendGet(String url){ String result = ""; try{ //创建HTTP客服端模拟,设置连接属性 HttpClient httpClient = new HttpClient(); httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(3000); httpClient.getHttpConnectionManager().getParams().setSoTimeout(180000); httpClient.getParams().setContentCharset("UTF-8"); //创建get请求,添加请求头 String uuid = UUID.randomUUID().toString(); GetMethod get = new GetMethod(url); get.setRequestHeader("X-SID", uuid); get.setRequestHeader("X-Signature",RSAUtil.defaultSign(uuid)); //执行并解析请求 int status = httpClient.executeMethod(get); if(status == HttpStatus.SC_OK){ result = get.getResponseBodyAsString(); } }catch (Exception e){ e.printStackTrace(); } return result; } public static String sendGet(String url,String params){ String newUrl = url+"?"+params; return sendGet(newUrl); } public static InputStream get(String url,String params){ String result = ""; String newUrl = url+"?"+params; InputStream inputStream = null; try{ HttpClient httpClient = new HttpClient(); httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(3000); httpClient.getHttpConnectionManager().getParams().setSoTimeout(180000); httpClient.getParams().setContentCharset("UTF-8"); String uuid = UUID.randomUUID().toString(); GetMethod get = new GetMethod(newUrl); get.setRequestHeader("X-SID", uuid); get.setRequestHeader("X-Signature",RSAUtil.defaultSign(uuid)); int status = httpClient.executeMethod(get); if(status == HttpStatus.SC_OK){ inputStream = get.getResponseBodyAsStream(); } }catch (Exception e){ e.printStackTrace(); } return inputStream; } public static void sendGet(String url,String params,OutputStream outputStream){ String result = ""; String newUrl = url+"?"+params; InputStream inputStream = null; try{ HttpClient httpClient = new HttpClient(); httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(3000); httpClient.getHttpConnectionManager().getParams().setSoTimeout(180000); httpClient.getParams().setContentCharset("UTF-8"); String uuid = UUID.randomUUID().toString(); GetMethod get = new GetMethod(newUrl); get.setRequestHeader("X-SID", uuid); get.setRequestHeader("X-Signature",RSAUtil.defaultSign(uuid)); int status = httpClient.executeMethod(get); if(status == HttpStatus.SC_OK){ inputStream = get.getResponseBodyAsStream(); byte[] bytes = new byte[1024]; int len = -1; while((len = inputStream.read(bytes))!=-1){ outputStream.write(bytes,0,len); outputStream.flush(); } } }catch (Exception e){ e.printStackTrace(); }finally { try { if(inputStream!=null){ inputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } } public static String sendPost(String url, MultipartFile multipartFile){ String result = ""; try{ CloseableHttpClient httpClient = HttpClients.createDefault(); HttpPost post =new HttpPost(url); String uuid = UUID.randomUUID().toString(); post.addHeader("X-SID",uuid); post.addHeader("X-Signature", RSAUtil.defaultSign(uuid)); MultipartEntityBuilder builder = MultipartEntityBuilder.create(); builder.setCharset(Charset.forName("utf-8")); builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);//加上此行代码解决返回中文乱码问题 builder.addBinaryBody("file",multipartFile.getInputStream(), ContentType.MULTIPART_FORM_DATA, multipartFile.getOriginalFilename());// 文件流 post.setEntity(builder.build()); HttpResponse response = httpClient.execute(post); StatusLine statusLine= response.getStatusLine(); if(statusLine.getStatusCode() == HttpStatus.SC_OK){ HttpEntity responseEntity = response.getEntity(); result = EntityUtils.toString(responseEntity); System.out.println("result"+result); } }catch (Exception e){ e.printStackTrace(); } return result; } }
TypeScript
UTF-8
330
2.59375
3
[ "MIT" ]
permissive
import { IsDefined, IsNotEmpty, IsString, MaxLength, MinLength, } from 'class-validator'; export class CreateQuestionDto { @MinLength(4) @MaxLength(40) @IsString() @IsDefined() @IsNotEmpty() readonly title: string; @MaxLength(1000) @IsNotEmpty() @IsDefined() @IsString() readonly text: string; }
C++
WINDOWS-1252
13,676
2.65625
3
[]
no_license
// 1651145 2008-09-28 22:44:25 Accepted 1806 C++ 0 268 ͵ // ö ////////////////////////////////////////////////////////////////////////// // Geometric class, Version 2.0 // ////////////////////////////////////////////////////////////////////////// // // // // V2.0(2008-9-16): // // -Rewrite all basic component from V1.12; // // // ////////////////////////////////////////////////////////////////////////// // Powered by ELF, Copyright(c) 2008 // ////////////////////////////////////////////////////////////////////////// #ifndef GEOMETRIC20_XPER #define GEOMETRIC20_XPER #include <iostream> #include <cmath> #include <algorithm> #include <vector> using namespace std; ////////////////////////////////////////////////////////////////////////// // Constants and precision comaprision operator. // ////////////////////////////////////////////////////////////////////////// const double PI = acos(-1.0); const double EPS = 1e-10; struct Point; struct Segment; struct Line; struct Circle; struct Polygon; typedef Point Vector; typedef Segment Rectangle; double hypot(double lhs, double rhs) { return sqrt(lhs*lhs+rhs*rhs); } inline bool lt(double lhs, double rhs) { return rhs - lhs >= EPS; } inline bool le(double lhs, double rhs) { return rhs - lhs >= -EPS; } inline bool gt(double lhs, double rhs) { return lhs - rhs >= EPS; } inline bool ge(double lhs, double rhs) { return lhs - rhs >= -EPS; } inline bool eq(double lhs, double rhs) { return fabs(rhs-lhs) < EPS; } inline bool ne(double lhs, double rhs) { return fabs(rhs-lhs) >= EPS; } inline bool zr(double lhs) { return fabs(lhs) < EPS; } inline bool nz(double lhs) { return fabs(lhs) >= EPS; } inline bool ps(double lhs) { return lhs >= EPS; } inline bool nn(double lhs) { return lhs >= -EPS; } inline bool ng(double lhs) { return lhs < -EPS; } inline bool np(double lhs) { return lhs < EPS; } ////////////////////////////////////////////////////////////////////////// // Point struct definition. // ////////////////////////////////////////////////////////////////////////// struct Point { double x, y; Point(double x=0, double y=0) : x(x), y(y) {} void get() { scanf("%lf%lf", &x, &y); } void put() const { printf("(%lf, %lf)", x, y); } operator bool() const { return nz(x) && nz(y); } double length() const { return sqrt(x*x+y*y); } }; // Point struct stream operator. istream& operator>>(istream& is, Point& p) { return is >> p.x >> p.y;} ostream& operator<<(ostream& os, const Point& p) { return os << "(" << p.x << ", " << p.y << ")"; } // Point struct comparision operator. bool operator==(const Point& lhs, const Point& rhs) { return eq(lhs.x, rhs.x) && eq(lhs.y, rhs.y); } bool operator!=(const Point& lhs, const Point& rhs) { return ne(lhs.x, rhs.x) && ne(lhs.y, rhs.y); } bool operator<(const Point& lhs, const Point& rhs) { return lt(lhs.x, rhs.x) || eq(lhs.x, rhs.x) && lt(lhs.y, rhs.y); } bool operator<=(const Point& lhs, const Point& rhs) { return lt(lhs.x, rhs.x) || eq(lhs.x, rhs.x) && le(lhs.y, rhs.y); } bool operator>(const Point& lhs, const Point& rhs) { return gt(lhs.x, rhs.x) || eq(lhs.x, rhs.x) && gt(lhs.y, rhs.y); } bool operator>=(const Point& lhs, const Point& rhs) { return gt(lhs.x, rhs.x) || eq(lhs.x, rhs.x) && ge(lhs.y, rhs.y); } // Point struct scalar operator. const Point operator+(const Point& lhs, double rhs) { return Point(lhs.x+rhs, lhs.y+rhs); } const Point operator+(double lhs, const Point& rhs) { return Point(lhs+rhs.x, lhs+rhs.y); } const Point operator-(const Point& lhs, double rhs) { return Point(lhs.x-rhs, lhs.y-rhs); } const Point operator-(double lhs, const Point& rhs) { return Point(lhs-rhs.x, lhs-rhs.y); } const Point operator*(double lhs, const Point& rhs) { return Point(lhs*rhs.x, lhs*rhs.y); } const Point operator*(const Point& lhs, double rhs) { return Point(lhs.x*rhs, lhs.y*rhs); } const Point operator/(const Point& lhs, double rhs) { return Point(lhs.x/rhs, lhs.y/rhs); } Point& operator+=(Point& lhs, double rhs) { lhs.x += rhs; lhs.y += rhs; return lhs; } Point& operator-=(Point& lhs, double rhs) { lhs.x -= rhs; lhs.y -= rhs; return lhs; } Point& operator*=(Point& lhs, double rhs) { lhs.x *= rhs; lhs.y *= rhs; return lhs; } Point& operator/=(Point& lhs, double rhs) { lhs.x /= rhs; lhs.y /= rhs; return lhs; } // Point struct vector operator. const Point operator+(const Point& lhs, const Point& rhs) { return Point(lhs.x+rhs.x, lhs.y+rhs.y); } const Point operator-(const Point& lhs, const Point& rhs) { return Point(lhs.x-rhs.x, lhs.y-rhs.y); } const Point operator~(const Point& lhs) { return Point(-lhs.y, lhs.x); } double operator^(const Point& lhs, const Point& rhs) { return lhs.x*rhs.y - lhs.y*rhs.x; } double operator*(const Point& lhs, const Point& rhs) { return lhs.x*rhs.x + lhs.y*rhs.y; } Point& operator+=(Point& lhs, const Point& rhs) { lhs.x += rhs.x; lhs.y += rhs.y; return lhs; } Point& operator-=(Point& lhs, const Point& rhs) { lhs.x -= rhs.x; lhs.y -= rhs.y; return lhs; } ////////////////////////////////////////////////////////////////////////// // Segment struct definition. // ////////////////////////////////////////////////////////////////////////// struct Segment { Point a, b; Segment() : a(), b() {} Segment(Point a, Point b) : a(a), b(b) {} }; ////////////////////////////////////////////////////////////////////////// // Line struct definition. // ////////////////////////////////////////////////////////////////////////// struct Line { double A, B, C; Line() : A(0), B(0), C(0) {} Line(double A, double B, double C) : A(A), B(B), C(C) {} Line(const Point& lhs, const Point& rhs) : A(rhs.y - lhs.y), B(lhs.x - rhs.x), C(-(lhs.x*A+lhs.y*B)) {} Line(double slope, const Point& p) : A(slope), B(-1.0), C(p.y-slope*p.x ) {} Line(const Point& p, double slope) : A(slope), B(-1.0), C(p.y-slope*p.x ) {} Line(const Segment& s) { *this = Line(s.a, s.b); } double eval(const Point& p) const { return A*p.x+B*p.y+C; } }; ////////////////////////////////////////////////////////////////////////// // Circle struct definition. // ////////////////////////////////////////////////////////////////////////// struct Circle { Point c; double r; Circle() {} Circle(Point c, double r) : c(c), r(r) {} Circle(double r, Point c) : c(c), r(r) {} }; ////////////////////////////////////////////////////////////////////////// // Polygon struct definition. // ////////////////////////////////////////////////////////////////////////// struct Polygon : public vector<Point> { Polygon() : vector<Point>(0) {} Polygon(const Polygon& P) : vector<Point>(P) {} Polygon(const vector<Point>& V) : vector<Point>(V) {} template<class Iter> Polygon(Iter begin, Iter end) : vector<Point>(begin, end) {} double area() const; const Point center() const; int within(const Point& p) const; }; double Polygon::area() const { double ans = 0.0; for(int i=0; i<size(); ++i) ans += (at(i) ^ at((i+1)%size())); return fabs(ans)*0.5; } const Point Polygon::center() const { Point ans(0, 0), p; double W = 0.0, w; for(int i=0; i<size(); ++i) { W += (w = (at(i) ^ at((i+1)%size()))); p = (at(i) + at((i+1)%size())) / 3.0 * w; ans += p; } return ans / W; } int quadrant(const Point& p) { if(zr(p.x) && zr(p.y)) return -1; if(p.x > 0 && p.y >= 0) return 0; if(p.x <= 0 && p.y > 0) return 1; if(p.x < 0 && p.y <= 0) return 2; if(p.x >= 0 && p.y < 0) return 3; } // onside returns -1, while within returns 1, outside returns 0 int Polygon::within(const Point& p) const { int n = 0, qa, qb; Point a, b = back() - p; for(int i=0; i<size(); ++i) { qa = quadrant(a=b); qb = quadrant(b=at(i)-p); if(qa==-1 || qb==-1) return -1; else if(qa==qb) continue; else if(qa==(qb+3)%4) ++n; else if(qa==(qb+1)%4) --n; else if(zr(a^b)) return -1; else n += ps(a^b) ? 2 : -2; } return n ? 1 : 0; } ////////////////////////////////////////////////////////////////////////// // Relations between objects. // ////////////////////////////////////////////////////////////////////////// bool cross(const Line& l, const Segment& s) { double a = l.eval(s.a), b = l.eval(s.b); return zr(a) || zr(b) || ps(a)^ps(b); } bool cross(const Segment& s, const Line& l) { return cross(l, s); } bool onSegment(const Point& p, const Segment& s) { return zr((p-s.a)^(p-s.b)) && np((p-s.a)*(p-s.b)); } bool cross(const Segment& lhs, const Segment& rhs) { if(onSegment(lhs.a, rhs) || onSegment(lhs.b, rhs)) return true; if(onSegment(rhs.a, lhs) || onSegment(rhs.b, lhs)) return true; return ps(lhs.a-rhs.a) ^ ps(lhs.b-rhs.a) && ps(lhs.a-rhs.b) ^ ps(lhs.b-rhs.b); } const Point intersect(Line a, Line b) { return Point( (a.B*b.C-b.B*a.C)/(b.B*a.A-a.B*b.A), (a.A*b.C-b.A*a.C)/(b.A*a.B-a.A*b.B) ); } const Point pedal(const Line& l, const Point& p ) { double k = l.eval(p)/(l.A*l.A+l.B*l.B); return Point(p.x-l.A*k, p.y-l.B*k); } const Point pedal(const Point& p, const Line& l) { return pedal(l, p); } const Point mirror(const Line& l, const Point& p) { return pedal(l, p) * 2.0 - p; } const Point mirror(const Point& p, const Line& l) { return pedal(l, p) * 2.0 - p; } const Line bisector(const Point& a, const Point& b) { return Line((a+b)/2.0, (a+b)/2.0+~(a-b)); } //const Circle circumcircle(const Point& a, const Point& b, const Point& c) { // Point p = intersect(Line(a, b), Line(b, c)); // return Circle(p, dist(a, p)); //} ////////////////////////////////////////////////////////////////////////// // Distances between objects. // ////////////////////////////////////////////////////////////////////////// double dist(const Point& lhs, const Point& rhs) { return (lhs-rhs).length(); } double dist(const Point& p, const Line& l) { return fabs(l.eval(p))/hypot(l.A, l.B); } double dist(const Line& l, const Point& p) { return fabs(l.eval(p))/hypot(l.A, l.B); } double dist(const Segment& s, const Point& p) { if(ps((s.a-p)*(s.a-s.b))^ps((s.b-p)*(s.b-s.a))) return min(dist(s.a, p), dist(s.b, p)); return dist(p, Line(s.a, s.b)); } double dist(const Point& p, const Segment& s) { return dist(s, p); } double dist(const Line& l, const Segment& s) { if(cross(l, s)) return 0.0; return min(dist(s.a, l), dist(s.b, l)); } double dist(const Segment& s, const Line& l) { return dist(l, s); } ////////////////////////////////////////////////////////////////////////// // Basic triangle operation. // ////////////////////////////////////////////////////////////////////////// // We assume that the three vertex of the triangle is pA-pB-pC, // while the angle assign to them are A-B-C, and the opposite side // of them are a-b-c, the funtions below follows this rule of signs. // Area of triagles calculation functions. double areaSSA(double a, double b, double C) { return 0.5*a*b*sin(C); } double areaSSS(double a, double b, double c) { double s=(a+b+c)*0.5; return sqrt(s*(s-a)*(s-b)*(s-c)); } double areaSAA(double a, double B, double C) { return a*a*0.5/(1.0/tan(B)+1.0/tan(C)); } double area(const Point& pA, const Point& pB, const Point& pC) { return fabs((pB-pA)^(pC-pA))*0.5; } double area(const Vector& v, const Vector& w) { return fabs(v^w)*0.5; } double side_c(double a, double b, double C = PI/2.0) { double ans = a*a + b*b - 2.0*a*b*cos(C); return nn(ans) ? sqrt(fabs(ans)) : -1.0; } #endif // GEOMETRIC20_XPER ////////////////////////////////////////////////////////////////////////// // Geometric class, Version 2.0 // // Powered by ELF, Copyright(c) 2008 // ////////////////////////////////////////////////////////////////////////// int main() { Polygon G; double lhs, rhs, ll, rr; G.resize(8); for(int t = 1; ; ++t) { bool exit = true; for(int i = 0; i < 4; ++i) { cin >> G[i*2]; if(nz(G[i*2].length())) exit = false; } if(exit) break; for(int i = 0; i < 4; ++i) G[2*i+1] = (G[2*i]+G[(2*i+2)%8])/2.0; double aa = G.area(); lhs = 0, rhs = aa; for(int i = 0; i < 8; ++i) { for(int j = i + 3; j <= 8; ++j) { ll = Polygon(G.begin() + i, G.begin() + j).area(); rr = aa - ll; if(ll > rr) swap(ll, rr); if(lhs < ll) { lhs = ll; rhs = rr; } } } printf("Cake %d: %.3lf %.3lf\n", t, lhs, rhs); } }
C++
UTF-8
1,660
3.25
3
[]
no_license
// I Think I Need a Houseboat // http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=1049 // y // | // |### // | ### // land | ## // | # // ----------------|---------#------ x // | // water | // | // | // | // shrinking 50 square miles each year in a semicircle form with the center (0, 0) // the radius increases, but grads goes down, because at last a few increasing means a large area // // S = 1/2 * PI * r^2 // Eroding: (x^2 + y^2) < r^2 <= 100 * n / PI #include <iostream> #include <vector> using namespace std; struct MyProperty { double x, y; }; double g_pdAreaByYear[200]; const double AREA_COEF = 100.0 / 3.1415926535897932384626433832795; int big_year(double dR) { return 0; } int get_year(MyProperty &proper) { double dR = proper.x * proper.x + proper.y * proper.y; int i = 0; for (i=0; i<200; i++) { if (dR < g_pdAreaByYear[i]) return (i + 1); } return i;//big_year(dR); } int main(int argc, char* argv[]) { int nCount(0), i(0); vector<MyProperty> vecProp; for (i=0; i<200; i++) { g_pdAreaByYear[i] = (i + 1) * AREA_COEF; } if (cin >> nCount && nCount >= 0) { vecProp.resize(nCount); for (i=0; i<nCount; i++) { cin >> vecProp[i].x >> vecProp[i].y; } for (i=0; i<nCount; i++) { cout << "Property " << (i + 1) << ": This property will begin eroding in year "; cout << get_year(vecProp[i]) << "." << endl; } cout << "END OF OUTPUT." << endl; } return 0; }
JavaScript
UTF-8
4,597
2.625
3
[]
no_license
const jwt = require('jsonwebtoken'); const User = require('../users/userModel'); const Trip = require('../trips/tripModel'); const password = require('../config/passwordHelper'); module.exports = { createUser: function(req, res) { const newUser = User.build({ firstName: req.body.firstName, lastName: req.body.lastName, password: req.body.password, email: req.body.email, description: req.body.description, }); newUser .save() .then(function(user) { password.hash(req.body.password) .then(function(hash) { newUser.update({ password: hash }); }) .catch(function(error) { console.log("Password hashing error: ", erorr); }) const token = jwt.sign(user.dataValues, 'hello world trppr'); console.log("\033[34m <TRPPR> New user created. \033[0m"); res.json({ user: user, token: token }); }) .catch(function(err) { var errorString = "Error:"; err.errors.forEach((err) => { errorString += "\n" + err.message; }); console.log(errorString); res.status(500).send(errorString); }); }, authenticateUser: function(req, res) { if (!req.body.email) { res.status(500).send('Email address required.'); } if (!req.body.password) { res.status(500).send('Password required.'); } User.findOne({ where: { email: req.body.email }, attributes: ['id', 'email', 'password', 'firstName', 'lastName', 'description'] }) .then(function(user) { password.compare(req.body.password, user.password) .then(function(result) { const token = jwt.sign(user.dataValues, 'hello world trppr'); console.log('\033[34m <TRPPR> User logged in. \033[0m'); res.json({ user: user, token: token }); }) .catch(function(error) { res.status(500).send('Password incorrect.'); }) }) .catch(function(err) { console.log('Error:', err); res.status(500).send('Login information incorrect.'); }); }, updateUser: function(req, res){ console.log('in server updateuser') User.update( { firstName: req.body.firstName, lastName: req.body.lastName, email: req.body.email, description: req.body.description, }, { where: { id: req.body.userId } }) .then(function(user) { if(req.body.password) { password.hash(req.body.password) .then(function(hash) { user.update({ password: hash }); }) } console.log("\033[34m <TRPPR> User updated. \033[0m"); res.sendStatus(201); }) }, getDriverHistory: function(req, res){ var tripsList = []; Trip.findAll({ where: { driverId: req.body.driverId }, attributes: [ 'id', 'tripDate', 'startSt', 'startCity', 'startState', 'endSt', 'endCity', 'endState', 'numSeats', 'seatPrice', 'vehicleMake', 'vehicleModel', 'vehicleYear', 'description' ] }) .then(function(trips){ trips.forEach( (trip) => { tripsList.push(trip.dataValues); }); console.log('\033[34m <TRPPR> Sending data: \033[0m'); console.log(tripsList); res.json(tripsList); }) .catch(function(err) { console.log('Error:', err.message); res.send(err.message); }); }, getPassengerHistory: function(req, res){ var tripsList = []; Trip.findAll({ attributes: [ 'id', 'tripDate', 'startSt', 'startCity', 'startState', 'endSt', 'endCity', 'endState', 'numSeats', 'seatPrice', 'vehicleMake', 'vehicleModel', 'vehicleYear', 'description' ], where: { id: { include: [Trip, User], }, } }) .then(function(trips){ trips.forEach( (trip) => { tripsList.push(trip.dataValues); }); console.log('\033[34m <TRPPR> Sending data: \033[0m'); console.log(tripsList); res.json(tripsList); }) .catch(function(err) { console.log('Error:', err.message); res.send(err.message); }); } }
JavaScript
UTF-8
301
2.84375
3
[]
no_license
class Task { start() { console.log('Started'); } stop() { console.log('Stopped'); } pause() { console.log('Paused'); } resume() { console.log('Resumed'); } } const task = new Task(); task.start(); task.pause(); task.resume(); task.pause(); task.resume(); task.stop();
C#
UTF-8
784
3.375
3
[ "MIT" ]
permissive
using System; namespace InterviewPreperationGuide.App.Qotd { /// <summary> /// Find all numbers from 1 to 1000, where a<b<c and a^2 + b^2 = c^2 /// </summary> internal class SolveEquation { //public static void Main(string[] args) //{ // FindNumbersOfEquation(); //} public static void FindNumbersOfEquation () { for (int i = 0; i <= 1000; i++) { for (int j = i + 1; j <= 1000; j++) { int c = i * i + j * j; int k = (int) Math.Sqrt (c); if ((k * k == c) && k <= 1000 && k > j) { Console.WriteLine ("(" + i + ", " + j + ", " + k + ")"); } } } } } }
PHP
UTF-8
2,251
3.53125
4
[]
no_license
<?php // Класс Generator // Пример генератора, рассмотренного ранее. function simple($from = 0, $to = 100) { for ($i = $from; $i < $to; $i++) { yield $i; } } foreach (simple(0, 6) as $val) { echo "Значение = $val<br/>"; echo "Квадрат = " . ($val * $val) . "<br/>"; } // Любой генератор возвращает объект класса Generator $objGen = simple(1, 5); var_dump($objGen); // object(Generator)[3] // Так же как и в случае класса Directory, объект класса Generator не может быть получен через оператор new (вернее, получить его можно, но воспользоваться им // не удастся). Поэтому возможность наследовать собственные генераторы также закрыта. // Однако генератор позволяет использовать методы, определенные в классе Generator. Используя дополнительные методы, можно осуществить обход генератора без применения // цикла foreach // Использование генератора без foreach function simple2($from = 0, $to = 100) { for ($i = $from; $i < $to; $i++) { yield $i; } } $obj = simple2(1, 5); // Выполняем цикл, пока итератор не достигнет конца while ($obj->valid()) { echo ($obj->current() * $obj->current()) . " "; // К следующему элементу $obj->next(); } // current() - возвращает текущее значение, если в операторе yield указывается ключ, то для его извлечения используется отдельный мтеод key() // next() - переход к следующей итерации // valid() - проверяет, закрыт ли генератор; если генератор используется, метод возвращает true, если итерации закончились и генератор закрыт, метод возвращает false.
C++
UTF-8
1,674
3.859375
4
[]
no_license
#include<iostream> #include<conio.h> using namespace std; struct Node { int info; //info variable will store data of a Node. Node *link; //link pointer will store the address of Next Node. }; Node *start=NULL; //*start=NULL means Intially Linked List is Empty. void Insert(); void Delete(); void Search(); void Display(); main() { int choice; for(;;) //Infinite Loop. { cout<<"\n\n\n\n---------- Linked List ---------- \n"; cout<<"\nMain Menu\n\n1. Insert at Beginning\n2. Delete from Beginning\n3. Search\n4. Display\n5. Exit\n\nEnter your choice : "; cin>>choice; switch(choice) { case 1: Insert(); Display(); break; case 2: Delete(); Display(); break; case 3: Search(); break; case 4: Display(); break; case 5: return 0; //Exit default: cout<<"\nWrong Input"; } } } void Insert() //Insert a New Node at the Beginning of List. { Node *temp=new Node(); //Memory Allocation to a New Node. cout<<"\nEnter the Value : "; cin>>temp->info; temp->link=start; start=temp; } void Delete() //Delete Starting Node from List. { if(start==NULL) cout<<"\nList is Empty.\n"; else { Node *temp=start; start=start->link; temp->link=NULL; cout<<"\nItem "<<temp->info<<" is Deleted.\n"; } } void Search() //Search a Node from List. { int item,loc=1; Node *temp=start; cout<<"\nEnter Item you want to Search :"; cin>>item; while(temp!=NULL) { if(item==temp->info) { cout<<"\nItem is Found at Location : "<<loc; return; } else { temp=temp->link; loc++; } } cout<<"\nItem is Not Found"; } void Display() //Display's the Elements in List. { Node *temp=start; cout<<"\nList is : "; while(temp!=NULL) { cout<<temp->info<<" "; temp=temp->link; } }
Markdown
UTF-8
13,352
2.75
3
[]
no_license
# notifR Mobile Client for notifR-Project. This is a very simple App implemented with Ionic2. It was part of an MVP with evaluation of Microservices Architecture in modern Ecosystems. ![notifR App](https://www.ir-tech.ch/wp-content/uploads/2017/05/notifR_Screenshot_mobile_App_Splash_Logo-550x367.png "notifR App") Introduction & Vision ===================== We from notifR personally have a lot of interest and therefore apps which notify us about things. Added together we have a lot of apps which do that, from apps of our favorite sport club which inform us about points scored and other related news to simple stuff like a weather app which tells us to take an umbrella with us in the morning. As we find it cumbersome to have to deal with that many apps which we most of the time not fully use, but unwilling to give up those handy notification, we decided to do somethings about it. Meet **notifR** a simple and easy way to get notified about pretty much anything. Why use a bunch of different apps to get news for various things, when you can get all of them in a single place. notifR subscribes to various sources of information for you, to be able to deliver whatever you want. As we grow more and more sources of information will be on boarded and therefore more and more information to subscribe to will be available to you, our customers. In the beginning we will concentrate on the following topics: * Football (respectively soccer for our American friends) Stay informed about when your favorite club plays and get match events as well as events. * Bands Where and when is your favorite band going to play? Want to get notified when they are in your area? * TV You're a thriller Junky? Want to get informed whenever one is on the telly? Wan't to know whenever your favorite movie is aired? No problem. * Weather Get informed about stuff like: sudden temperature drop, how is the weather going to be today in your area Is there anything you're missing? Use our [contact form](http://shit-doesnt-exist-yo.com) to hit us up and tell us what you'd like to see added in the future. Main features ============= notifR will read from various sources of information or use API's to be able to provide the information directly to the end user. We hope to free our customers from the cluster of apps they use today. One of the biggest challenge we have is that there is a flood of information in the internet. There are a lot of ways this information is represented and we won't be able to get around to adapt to them. This will also be a problem that we face. We need to standardize all the information we read to a very simplistic interface, since we want to handle all kind of information. First architecture ================== ## Overall architecture ![notifR System Architecture](https://www.ir-tech.ch/wp-content/uploads/2017/05/notifR_Architecture_Oberview@2x-662x1024.png "notifR System Architecture") We use a microservice architecture. This allows the microservices, the so called connectors, to be independent from each other, not only from a functionality perspective, but also from a technology point of view. The only thing the microservices need to have in common is a message interface, to communicate with the backend. The communication between the business logic and the microservices happens over PubNub. The backend informs the microservices about the subscriptions the corrsponding microservice has to respond to. And the microservice simply sends the message for a subscription whenever something is found to notify the end user about. The subscriptions are registered via the mobile app frontend, from there it is send to the business logic, which persists the information in a Mongo DB database. The notification to the user happens using OneSignal. Whenever the business logic receives something from a microservice to notify the user about, it will forward it to OneSignal to perform the actual push notification to the end user. Technologies ============ As shown above we try to build our application as a cloud native application with very loose dependencies. But we also want to prove that despite the various technologies we can bundle the project into one well working application. Container --------- We use small container to run every service needed by our application. Using these container, especially docker containers in our case, allows us to run nearly every technology on one platform running [docker](https://www.docker.com/). Mongo DB -------- [Mongo DB](https://www.mongodb.com/) is a simple but scalable [NoSQL](https://www.mongodb.com/nosql-explained) database which is compatible with docker. Aerospike --------- [Aerospike](http://www.aerospike.com/) is a high speed, scalable and reliable NoSQL database optimized for real-time applications. We use it mainly as a key value store for temporary session data. It is not supposed to persist data due to its characteristic of running in memory only. PHP --- [PHP (Hypertext Preprocessor)](http://php.net/) is a widespread open-source script language in web technologies. Our backend is written in PHP. Angular 2 --------- [Angular 2](https://angular.io/) is a widespread mobile & desktop framework to create cross platform UI. We use it together with Typescript, which is a script language which compiles to Javascript in the end, with respect to Javascripts best practices. Go -- [Go](https://golang.org/) (often referred to as golang) is a free and open-source programming language created at Google in 2007 by Robert Griesemer, Rob Pike, and Ken Thompson. It is a compiled, statically typed language in the tradition of Algol and C, with garbage collection, limited structural typing, memory safety features and CSP-style concurrent programming features added. We use it to build at lease one of our microservices. Java ---- [Java](https://www.java.com/en/) is a general-purpose computer programming language that is concurrent, class-based, object-oriented, and specifically designed to have as few implementation dependencies as possible. It is intended to let application developers "write once, run anywhere" (WORA), meaning that compiled Java code can run on all platforms that support Java without the need for recompilation. We use it to build at lease one of our microservices. NodeJS ------ [Node.js](https://nodejs.org/en/) is an open-source, cross-platform JavaScript runtime environment for developing a diverse variety of server tools and applications. Although Node.js is not a JavaScript framework, many of its basic modules are written in JavaScript, and developers can write new modules in JavaScript. The runtime environment interprets JavaScript using Google's V8 JavaScript engine. Node.js has an event-driven architecture capable of asynchronous I/O. These design choices aim to optimize throughput and scalability in Web applications with many input/output operations, as well as for real-time Web applications (e.g., real-time communication programs and browser games). We use it to build at lease one of our microservices. Javascript ---------- [Javascript](https://www.javascript.com/) is a high-level, dynamic, untyped, and interpreted programming language. Alongside HTML and CSS, Javascript is one of the three core technologies of World Wide Web content production. The majority of websites employ it, and all modern Web browsers support it without the need for plug-ins. JavaScript is prototype-based with first-class functions, making it a multi-paradigm language, supporting object-oriented, imperative, and functional programming styles. A lot of our technologies are based on or compile to Javascript, like NodeJS or Typescript. PubNub ------ [PubNub](https://www.pubnub.com/) is a realtime publish/subscribe messaging API built on the companies global data stream network which is made up of a replicated network of at least 14 data centers located in North America, South America, Europe, and Asia. The network currently serves over 300 million devices and streams more than 750 billion messages per month. PubNub offers a [wide variety of SDKs](https://www.pubnub.com/docs#all-sdks-home) to implement their API in pretty much any language which is used. We use PubNub to communicate between our microservices and our business logic. Definition of Done ================== * All acceptance features taken from the stories are fulfilled * The project is build, deployed and tested locally * Code is committed and pushed to git repository * The project is built by an automation tool * [Coding guidelines](https://google.github.io/styleguide/) are adhered * All FIXME and TODOS resolved * No warnings at build and start time * DB is up to date * Using informative error messages * Changes in change log and git reported * Dependencies checked and adjusted * Unit tests are up to date and all pass * Additional rest request are documented and tested * Positive and negative tests for all important methods and classes Retrospective ================== # Sprint 1 - Dates for decisions in Log - Burndownchart visible - Acceptance features for userstories - only show what works (app) - test coverage (unit test are essential) # Sprint 2 - Calculate velocity for every Sprint (last: 80) - improve acceptance features, create tests for acceptance criterias, positive/negative - improve collaboration, note what is decided, communication! - fix dates for standup meetings (Monday at school, Thursday in whatsapp, Saturday at school, except eastern) - feedback loops in team (pairprogramming, code review) - code review (prepare for the next time, will be checked by coach) - test review (together) # Sprint 3 - available on android? - Burndown charts on paper - Issues on Bitbucket - Releases for all projects - GUI-Testing - refactor code (max amount of lines per method: 30) - coding guidelines/lint - testing from frontend to backend and back - additional features instead of more services (more informations for push notification) # Installation # Alle Notifr Microservices laufen in Docker Container. Um diese starten zu können benötigst du Docker und docker-compose. Wenn diese Tools noch nicht auf dem System laufen müssen diese noch installiert werden. Nutze dazu die offizielle Docker [Dokumentation](https://www.docker.com/). Wenn dein Docker Daemon und docker-compose einwandfrei funktionieren, bist du bereit für die Installation. Jeder Docker Container im Notifr Projekt kann auf einem separaten Docker Host laufen. ## Notifr Backend ## #### checkout projekt #### ```bash git clone https://bitbucket.org/notifr/notifr.project.git ``` #### set Env #### Du kannst zwischen "prod" and "test" wählen. Dies Variable wird nur zu Markierung des Containers genutzt ```bash export ENV=test ``` #### create data dir#### ```bash sudo mkdir -p /opt/monogodb-$ENV/data sudo chown docker /opt/monogodb-$ENV/data ``` Hinweis: Der User "docker", ist der User der privilegiert ist den Docker Daemon zu starten #### run docker-compose #### ```bash docker-compose up -d ``` ## Microservices ## ### Microservice Football ### #### checkout projekt #### ```bash git clone https://bitbucket.org/notifr/microservice.football.git ``` #### set Env #### Du kannst zwischen "prod" and "test" wählen. Dies Variable wird nur zu Markierung des Containers genutzt ```bash export ENV=test ``` #### set Backen IP #### ```bash export BACKEND_HOST=http://{BACKEND_IP}/ ``` #### run docker-compose #### ```bash docker-compose up -d ``` ### Microservice Wetter ### #### checkout projekt #### ```bash git clone https://bitbucket.org/notifr/microservice.weather.git ``` #### set Env #### Du kannst zwischen "prod" and "test" wählen. Dies Variable wird nur zu Markierung des Containers genutzt ```bash export ENV=test ``` #### set Backen IP #### ```bash export BACKEND-HOST={BACKEND_IP} ``` #### run docker-compose #### ```bash docker-compose up -d ``` ### Microservice Bands ### #### checkout projekt #### ```bash git clone https://bitbucket.org/notifr/microservice.bands.git ``` #### set Env #### Du kannst zwischen "prod" and "test" wählen. Dies Variable wird nur zu Markierung des Containers genutzt ```bash export ENV=test ``` #### set Backen IP #### ```bash export BACKEND-HOST={BACKEND_IP} ``` #### create data and log dir#### ```bash sudo mkdir -p /opt/aerospike-$ENV/logs sudo mkdir -p /opt/aerospike-$ENV/data sudo chown docker /opt/aerospike-$ENV/logs sudo chown docker /opt/aerospike-$ENV/data ``` Hinweis: Der User "docker", ist der User der privilegiert ist den Docker Daemon zu starten #### run docker-compose #### ```bash docker-compose up -d ``` ### Microservice TV ### #### checkout projekt #### ```bash git clone https://bitbucket.org/notifr/microservice.tv.git ``` #### set Env #### Du kannst zwischen "prod" and "test" wählen. Dies Variable wird nur zu Markierung des Containers genutzt ```bash export ENV=test ``` #### set Backend IP #### ```bash export BACKEND-HOST={BACKEND_IP} ``` #### create data and log dir#### ```bash sudo mkdir -p /opt/aerospike-tv-$ENV/logs sudo mkdir -p /opt/aerospike-tv-$ENV/data sudo chown docker /opt/aerospike-tv-$ENV/logs sudo chown docker /opt/aerospike-tv-$ENV/data ``` Hinweis: Der User "docker", ist der User der privilegiert ist den Docker Daemon zu starten #### run docker-compose #### ```bash docker-compose up -d ```
PHP
UTF-8
488
2.6875
3
[ "MIT" ]
permissive
<?php namespace Gctrl\IpnLogParser\Command; use Cilex\Command\Command; use Dubture\Monolog\Reader\LogReader; abstract class AbstractLogCommand extends Command { /** * Get Log Reader * * @param string $file * @param int $days * @param string $pattern * * @return \Dubture\Monolog\Reader\LogReader */ public function getReader($file, $days = 30, $pattern = 'default') { return new LogReader($file, $days, $pattern); } }
Python
UTF-8
640
3.40625
3
[ "MIT" ]
permissive
#ImportModules from ShareYourSystem.Standards.Classors import Attester from ShareYourSystem.Functers import Functer #Definition a derived second Class class FooClass(): @Functer.FuncterClass() def printSomething(self,**_KwargVariablesDict): print('Something !') #Functers can be cumulated @Functer.FuncterClass() @Functer.FuncterClass() def printOtherthing(self,**_KwargVariablesDict): print('An Other Thing ?') #Definition an instance MyFoo=FooClass() #Do just a test of the basic FirstClass method printSomething MyFoo.printSomething() #Do just a test of the basic FirstClass method printSomething MyFoo.printOtherthing()
Markdown
UTF-8
1,718
2.71875
3
[]
no_license
Today I spent my time learning how to work with React Native, which is the langauge I'll be creating my Snö app with. One of the videos I use to study this can be found here: https://www.youtube.com/watch?v=qSRrxpdMpVc Name of Student: Adam Mansell Name of Project: Snö Project's Purpose or Goal: (What will it do for users?) Snö is where snowboarders and skiers can go to check out daily snowfall/weather information pertaining to their local mountain, along with alerts about any possible avalanche warnings. List the absolute minimum features the project requires to meet this purpose or goal: Connecting a weather API to get Mt.Hood's weather forecast Having a view page that shows snowfall (alone and not alongside other weather info) Having separate info sections for Mt.Hood Meadows and Timberline What tools, frameworks, libraries, APIs, modules and/or other resources (whatever is specific to your track, and your language) will you use to create this MVP? List them all here. Be specific. React-Redux Weather API to show Snow Conditions at Mt.Hood If you finish developing the minimum viable product (MVP) with time to spare, what will you work on next? Describe these features here: Be specific. Adding other locations besides Mt.Hood, possibly outside of Oregon Adding possible Avalanche warnings Adding a login feature where you can login and save certain mountains as your "Home Mountains" What additional tools, frameworks, libraries, APIs, or other resources will these additional features require? Will require another API or possibly more than 2 Is there anything else you'd like your instructor to know? Going to see if I can make this a mobile app! If not I'll make it a site.
JavaScript
UTF-8
1,666
2.53125
3
[]
no_license
"use strict"; const React = require("react"); const { Component } = React; const { Text } = require("ink"); const TextInput = require("ink-text-input").default; const autoBind = require("auto-bind"); const colorConv = require("."); const QueryInput = ({ query, placeholder, onChange }) => ( <div> <Text bold> <Text cyan>›</Text>{" "} <TextInput value={query} placeholder={placeholder} onChange={onChange} /> </Text> </div> ); const Color = ({ color }) => <span>{colorConv.name(color)[1]}</span>; class ColorComponent extends Component { constructor(props) { super(props); autoBind(this); this.state = { query: "" }; } render() { const { query } = this.state; return ( <span> <br /> <QueryInput query={query} placeholder="Colors will be converted to SCSS variables as you type" onChange={this.handleChangeQuery} /> <Color color={query} /> </span> ); } componentDidMount(){ process.stdin.on('keypress', this.handleKeyPress); } handleKeyPress(ch, key = {}) { const { onExit, onSelectColor } = this.props; const { query } = this.state; if (key.name === "escape" || (key.ctrl && key.name === "c")) { onExit(); return; } if (key.name === "return") { if (query) { this.setState( { copied: true }, () => { onSelectColor(colorConv.name(query)[1]); } ); } return; } } handleChangeQuery(query) { this.setState({ query }); } } module.exports = ColorComponent;
Java
UTF-8
480
2.46875
2
[]
no_license
package com.unimelb.ienv; public class Order { private String item; private String imgUrl; public Order(String item, String imgUrl) { this.item = item; this.imgUrl = imgUrl; } public String getItem() { return item; } public void setItem(String item) { this.item = item; } public String getImgUrl() { return imgUrl; } public void setImgUrl(String imgUrl) { this.imgUrl = imgUrl; } }
Ruby
UTF-8
238
2.734375
3
[]
no_license
require "csv" arg = ARGV[1] arr = [] CSV.foreach(ARGV[0], "r") do |row| if row.count(arg) > 0 arr << row end end arr.sort_by! {|e| [Date.parse(e[1])]} CSV.open("#{ARGV[2]}.csv", "w") do |csv| arr.each do |l| csv << l end end
JavaScript
UTF-8
2,408
2.765625
3
[]
no_license
import path from 'path' import Pyjs from './Pyjs' export function getId(config, type, name) { for (const [key, value] of Object.entries(config[type])) { if (type === 'Activities' && value === name) { return key } else if (type === 'Devices' && key === name) { return value.id } } return null } export default class HarmonyHub { /** * @arg {string} hubIP * @example * const hub = new HarmonyHub('10.0.0...') * * await hub.connect() * //... * await hub.disconnect() */ constructor(hubIP) { this.pyjs = new Pyjs({ // debug: true, entry: path.join(__dirname, 'HarmonyHub.py'), spawnArgs: [hubIP], }) } async connect() { return this.pyjs.connect() } async disconnect() { return this.pyjs .send({ commandName: 'close' }) .then(() => this.pyjs.disconnect()) } async getConfig() { if (!this.DEBUG && this._cachedConfig) { return this._cachedConfig } const result = await this.pyjs.send({ commandName: 'get-config' }) if (!this.DEBUG) { this._cachedConfig = result } return result } /** * @arg {{ * command: string, * delay: number, * device: string, * repeats: number, * }} opts * @example * await hub.sendCommand({ * device: 'Samsung TV', * command: 'VolumeUp', * }) */ async sendCommand(opts) { const config = await this.getConfig() const deviceId = getId(config, 'Devices', opts.device) if (deviceId) { opts = { delay: 0, repeats: 1, ...opts, } opts.deviceId = deviceId delete opts.device return this.pyjs.send({ commandName: 'send-command', ...opts }) } else { throw new Error(`Device doesn't exist in hub: ${opts.device}`) } } /** * @arg {string} activity * @example * await hub.startActivity('Watch TV') */ async startActivity(activity) { const config = await this.getConfig() const id = getId(config, 'Activities', activity) if (id) { return this.pyjs.send({ commandName: 'start-activity', id }) } else { throw new Error(`Activity doesn't exist in hub: ${activity}`) } } /** * Stop current activity * @example * await hub.stopActivity() */ async stopActivity() { return this.pyjs.send({ commandName: 'start-activity', id: '-1' }) } }
Java
UTF-8
168
2.34375
2
[]
no_license
package useSuperKeyword; public class bmwCar extends Cars { public bmwCar(String diesel) { super(diesel); } public void engine(){ super.dieselType(); } }
Java
UTF-8
724
2.109375
2
[]
no_license
package com.rjpa.quartz; import org.quartz.Job; import org.quartz.JobExecutionContext; import org.quartz.JobExecutionException; public class CronJob implements Job { @Override public void execute(JobExecutionContext jobExecutionContext) throws JobExecutionException { System.out.println("=========================定时任务每5秒执行一次==============================="); System.out.println("jobName=====:" + jobExecutionContext.getJobDetail().getKey().getName()); System.out.println("jobGroup=====:" + jobExecutionContext.getJobDetail().getKey().getGroup()); System.out.println("taskData=====:" + jobExecutionContext.getJobDetail().getJobDataMap().get("taskData")); } }
JavaScript
UTF-8
1,541
3.546875
4
[]
no_license
const weatherLabel = document.querySelector(".js-weather"); const API_KEY = "9009787807337227972f9da130b6c08b"; const COORDS = "coords"; function getWeatherData(latitude, longitude) { const url = `https://api.openweathermap.org/data/2.5/weather?lat=${latitude}&lon=${longitude}&appid=${API_KEY}&units=metric`; console.log(url); fetch(url) .then(res => { return res.json(); }) .then(json => { const temperature = json.main.temp; const humidity = json.main.humidity; const country = json.sys.country; const city = json.name; weatherLabel.innerText = `${temperature}℃, ${humidity}% @ ${city}, ${country}`; console.log(temperature, humidity, country, city); console.log(json); }); } function saveCoords(coordsObj) { localStorage.setItem(COORDS, JSON.stringify(coordsObj)); } function handleGeoSuccess(position) { const latitude = position.coords.latitude; const longitude = position.coords.longitude; const coordsObj = { latitude, longitude }; saveCoords(coordsObj); } function handleGeoError() { console.log("geo Error"); } function askForCoords() { navigator.geolocation.getCurrentPosition(handleGeoSuccess, handleGeoError); console.log("ask"); } function loadCoords() { const loadedCoords = localStorage.getItem(COORDS); if (loadedCoords === null) { askForCoords(); } else { const parsedCoords = JSON.parse(loadedCoords); getWeatherData(parsedCoords.latitude, parsedCoords.longitude); } } function init() { loadCoords(); } init();
Python
UTF-8
1,229
3.328125
3
[]
no_license
def practice02_03(): import re strings = """We encourage everyone to contribute to Python. If you still have questions after reviewing the material in this guide, then the Python Mentors group is available to help guide new contributors through the process""" converted_strings = '' word = '' word_list = [] set_like_list = [0] for i in range(0, len(strings)): word += strings[i] if strings[i] == ' ' or strings[i] == '.' or strings[i] == ',' or strings[i] == '\n' or i == len(strings): converted_strings += word.upper() word = '' strings = '' for i in range(0, len(converted_strings)): if converted_strings[i] != '.' and converted_strings[i] != ','\ and converted_strings[i] != '\n': strings += converted_strings[i] for i in range(0, len(strings)): if strings[i] != ' ': word += strings[i] else : word_list.append(word) word = '' for i in range(0, len(word_list)): for j in range(i+1, len(word_list)) : if word_list[i] != word_list[j]: set_like_list.append(word_list[i]) print(word_list) practice02_03()
Ruby
UTF-8
84
3.09375
3
[]
no_license
# A new ruby file print "Enter your name: " name = gets.chomp print "Hello #{name}"
Java
UTF-8
543
1.632813
2
[]
no_license
package zzq.zzqsimpleframeworkjsonclient; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import zzq.zzqsimpleframeworkjson.config.EnableJacksonConfigure; /** * @author zhouzhiqiang * @version 1.0 * @date 2023-01-04 14:06 */ @SpringBootApplication @EnableJacksonConfigure public class ZzqSimpleFrameworkJsonClientApplication { public static void main(String[] args) { SpringApplication.run(ZzqSimpleFrameworkJsonClientApplication.class, args); } }
Java
UTF-8
377
2.15625
2
[ "Apache-2.0" ]
permissive
package org.xson.core.serializer; import java.util.Date; import org.xson.core.WriterModel; import org.xson.core.XsonConst; public class DateUtilSerializer extends DefaultSerializer { @Override public void write(Object target, WriterModel model) { Date date = (Date) target; model.writeByte1(XsonConst.DATE_UTIL); model.writeLong(date.getTime()); } }
Swift
UTF-8
2,342
2.890625
3
[ "MIT" ]
permissive
// // GiphyAPI.swift // gapiphy // // Created by Ricardo Ramirez on 21/08/21. // import Foundation import Combine protocol GIFProvider { func getTrending(offset: Int?, completion: @escaping (MultipleGIFResponse) -> Void) func getSearch(withText text: String, offset: Int?, completion: @escaping (MultipleGIFResponse) -> Void) } class GiphyAPI: GIFProvider { let baseURL = "https://api.giphy.com" let apiKey = "" var cancellable: AnyCancellable? func getTrending(offset: Int?, completion: @escaping (MultipleGIFResponse) -> Void) { var urlComponents = URLComponents(string: "\(baseURL)/v1/gifs/trending") var queryItems = [URLQueryItem(name: "api_key", value: apiKey)] if let offset = offset { queryItems.append(URLQueryItem(name: "offset", value: String(offset))) } urlComponents?.queryItems = queryItems guard let url = urlComponents?.url else { return } cancellable = URLSession.shared.dataTaskPublisher(for: url) .map { $0.data } .decode(type: MultipleGIFResponse.self, decoder: JSONDecoder()) .eraseToAnyPublisher() .sink(receiveCompletion: { error in print(error) }, receiveValue: { response in completion(response) }) } func getSearch(withText text: String, offset: Int?, completion: @escaping (MultipleGIFResponse) -> Void) { var urlComponents = URLComponents(string: "\(baseURL)/v1/gifs/search") var queryItems = [ URLQueryItem(name: "api_key", value: apiKey), URLQueryItem(name: "q", value: text) ] if let offset = offset { queryItems.append(URLQueryItem(name: "offset", value: String(offset))) } urlComponents?.queryItems = queryItems guard let url = urlComponents?.url else { return } cancellable = URLSession.shared.dataTaskPublisher(for: url) .map { $0.data } .decode(type: MultipleGIFResponse.self, decoder: JSONDecoder()) .eraseToAnyPublisher() .sink(receiveCompletion: { error in print(error) }, receiveValue: { response in completion(response) }) } }
Python
UTF-8
774
2.953125
3
[]
no_license
import serial import time import csv ser = serial.Serial('/dev/ttyACM0') ser.flushInput() i = input() j = input() i = int(i) j = int(j) while True: try: ser_bytes = ser.readline() ser_bytes2 = ser.readline() decoded_bytes = float(ser_bytes[0:len(ser_bytes)-2].decode("utf-8")) decoded_bytes2 = float(ser_bytes2[0:len(ser_bytes)-2].decode("utf-8")) decoded_bytes = decoded_bytes*5.0/1023; decoded_bytes2 = decoded_bytes2*5.0/1023; print(decoded_bytes) print(decoded_bytes2) with open("test_data.csv","a") as f: writer = csv.writer(f,delimiter=",") writer.writerow([time.time(),i,j,decoded_bytes,decoded_bytes2]) except: print("Keyboard Interrupt") break
Shell
UTF-8
644
3.171875
3
[]
no_license
#!/bin/bash set -x #Instalación de paquetes necesarios en el cliente NFS: apt-get install nfs-common -y #Creamos el punto de montaje en el cliente mount 52.91.77.158:/var/www/html /var/www/html #Añadimos la siguiente linea en el archivo /etc/fstab echo "52.91.77.158:/var/www/html /var/www/html nfs auto,nofail,noatime,nolock,intr,tcp,actimeo=1800 0 0" >> /etc/fstab # Configuramos WP en un directorio que no es la raíz #cd /var/www/html/wordpress #mv /var/www/html/wordpress/index.php ../ #sed -i 's#wp-blog-header.php#/wordpress/wp-blog-header.php#' /var/www/html/index.php #Reiniciamos el servicio nfs /etc/init.d/nfs-common restart
Markdown
UTF-8
922
2.734375
3
[]
no_license
# Product Manager Nano Degree My interest in product management started when I developed my first product for my graduation project of my master’s degree. During that time, I worked in a self-managed Agile team for three months to build a website that aims to solve the food waste problem in Australia. My team won the Monash University award for the best Industry Experince project. In March 2021, I received the Product Manager Nano Degree offered by Udacity. I’m excited to share the projects I completed in this course. ## In this course I learned: - Pitch a product vision. - Run a design sprint. ## The Course Syllabus: **Product Manager Nano Degree** [<img src="https://user-images.githubusercontent.com/67848891/112593206-35542b80-8e18-11eb-8a8c-169d4419c1d8.png" width="200" height="100" >](https://d20vrrgs8k4bvw.cloudfront.net/documents/en-US/Product+Manager+Nanodegree+Program+Syllabus.pdf)
Java
UHC
1,447
4.0625
4
[]
no_license
package oop1120; public class WhileTest { public static void main(String[] args) { // while() {} // do~while ߿ // ʱⰪ falseϰ while do~while ̰ ִ. // do~while ǰ 1 ȴ. /* int a = 3; while(a<=5) { System.out.println("JAVA"); a++; } */ /* int b = 3; do { System.out.println("JSP"); b++; }while(b<=5); int a=3; while(a<1) { System.out.println("JAVA"); a++; } int b=3; do { System.out.println("JSP"); b++; }while(b<1); // loop // for(;;){} int a=1; while(true) { System.out.println("JAVA"); a++; if(a==5) break;} // ) 1~1000 ϴµ 10000 // ϰ α׷ int a=1, hap=0; while(a<=1000) { hap= hap + a; if(hap>=10000) { System.out.println(a); System.out.println(hap); break; } a++; } */ // ) 3 1000 Ѿ // 3 ؾ ϴ Ͻÿ // °) 3+6+9+12+~ = 1000 int a=0, hap=0; String res = ""; //ڿ while(true) { a= a + 3 ; hap=hap +a; res = res + a + "+"; if(hap>=1000) break;} System.out.println(res + "=" + hap); }//me }//ce
Shell
UTF-8
1,230
2.875
3
[ "MIT" ]
permissive
#!/usr/bin/env bash # # Script creates necessary configs, installs internal registry and ingress. # if ! type kind >> /dev/null; then echo "Before run this script, you need to install Kind."; exit 1; fi # Create a kind cluster user config test ! -f ~/.kind/.config && mkdir -p ~/.kind && cat <<EOF >> ~/.kind/.config kind: Cluster apiVersion: kind.x-k8s.io/v1alpha4 nodes: - role: control-plane kubeadmConfigPatches: - | kind: InitConfiguration nodeRegistration: kubeletExtraArgs: node-labels: "ingress-ready=true" extraPortMappings: - containerPort: 80 hostPort: 80 protocol: TCP - containerPort: 443 hostPort: 443 protocol: TCP containerdConfigPatches: - |- [plugins."io.containerd.grpc.v1.cri".registry.mirrors."localhost:5000"] endpoint = ["http://kind-registry:5000"] EOF cat ~/.kind/.config | kind create cluster --name=magpie --config=- # Install registry ./scripts/kind-with-registry.sh # Install nginx-ingress oc apply -f https://raw.githubusercontent.com/kubernetes/ingress-nginx/main/deploy/static/provider/kind/deploy.yaml oc wait --namespace ingress-nginx \ --for=condition=ready pod \ --selector=app.kubernetes.io/component=controller \ --timeout=90s
C++
UTF-8
683
2.625
3
[]
no_license
#include "sensorSystem.h" sensorSystem* sensorSystem::instance = nullptr; sensorSystem::sensorSystem(): sonar(new SonarSensor(TRIGGER_SONAR, ECHO_SONAR, MAX_DISTANCE)), wallSensor(new WallSensor(WALL_PIN)), leftLineSensor(new LineSensor(LEFT_LINE_PIN)), rigthLineSensor(new LineSensor(RIGHT_LINE_PIN)), colorSensor(new ColorSensor(COLOR_S0, COLOR_S1, COLOR_S2, COLOR_S3, COLOR_OUT)) {} void sensorSystem::update(){ sonar->updateInfo(); wallSensor->updateInfo(); leftLineSensor->updateInfo(); rigthLineSensor->updateInfo(); colorSensor->updateInfo(); } sensorSystem* sensorSystem::getInstance(){ if (!instance) { instance = new sensorSystem(); } return instance; }
Rust
UTF-8
18,982
3.125
3
[]
no_license
// #[macro_use] extern crate anyhow; extern crate regex; use regex::Regex; extern crate itertools; use std::collections::HashMap; use std::collections::HashSet; const TILE_SIZE: usize = 10; const INNER_SIZE: usize = TILE_SIZE - 2; // 4 rotations with front face up, 4 rotations with back face up. const NUM_ORIENTATIONS: usize = 8; #[derive(Clone, Copy, Debug, PartialEq)] enum Operation { Rot90, FlipHorz, } #[derive(Clone, Debug)] struct Image { width: usize, height: usize, // Same as width. bitmap: Vec<bool>, } impl Image { fn orient_rel(&mut self, op: Operation) { assert_eq!(self.width, self.height); match op { Operation::Rot90 => { let mut out = self.bitmap.clone(); for x in 0..self.width { for y in 0..self.height { let out_x = self.height - y - 1; let out_y = x; out[out_y * self.width + out_x] = self.bitmap[y * self.width + x] } } self.bitmap = out; } Operation::FlipHorz => { for y in 0..self.height { for x in 0..self.width / 2 { let at1 = y * self.width + x; let at2 = y * self.width + (self.width - 1 - x); let s = self.bitmap[at1]; self.bitmap[at1] = self.bitmap[at2]; self.bitmap[at2] = s; } } } } } fn get_row(&self, row: usize) -> &[bool] { let start = row * self.width; let end = (row + 1) * self.width; assert!(row < self.height); assert!(end <= self.width * self.height); &self.bitmap[start..end] } fn get_row_string(&self, row: usize) -> String { let mut s = String::new(); for b in self.get_row(row) { match b { true => s.push('#'), false => s.push('.'), } } s } } impl std::fmt::Display for Image { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { let mut i = 0; for _ in 0..self.height { for _ in 0..self.width { write!(f, "{}", if self.bitmap[i] { '#' } else { '.' })?; i += 1; } write!(f, "\n")?; } Ok(()) } } #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)] struct EdgeNum(u32); #[derive(PartialEq, Eq, Copy, Clone, Debug)] struct Edge { num: EdgeNum, flipped: bool, border: bool, } impl Edge { fn new(s: &str, flipped: bool) -> Self { let r = s.chars().rev().collect::<String>(); let num = u32::from_str_radix(s, 2).unwrap(); let reverse = u32::from_str_radix(&r, 2).unwrap(); // Use the lowest number for the edge, so that they can be compared for uniqueness. // If the flipped version is lower, then use that and mark the edge flipped. if num < reverse { Edge { num: EdgeNum(num), flipped: flipped, border: true, } } else { Edge { num: EdgeNum(reverse), flipped: !flipped, border: true, } } } } #[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)] struct TileId(u64); #[derive(Clone)] struct Tile { id: TileId, top: Edge, left: Edge, right: Edge, bottom: Edge, // The image for the tile, excluding the outer row/columns. inner_image: Image, // The set of ops performed on the tile, but not applied to the `inner_image` yet. image_ops: Vec<Operation>, } impl Tile { fn from_strings(lines: Vec<&str>) -> Vec<Tile> { let all_tile_strs: Vec<String> = { let it = lines.into_iter().filter(|&s| s != ""); let it = it.map(|s| s.replace("#", "1").replace(".", "0").to_owned()); it.collect() }; let mut tiles = Vec::new(); // Each `tile_strs` is the input lines for a single tile. The first line // is the id, the next TILE_SIZE lines are the content of the tile's image. for tile_strs in all_tile_strs.chunks_exact(TILE_SIZE + 1) { // Format of tile_strs[0] is `Tile <id>:`. let id = { let id_re = Regex::new("[0-9]+").unwrap(); TileId(id_re.find(&tile_strs[0]).unwrap().as_str().parse().unwrap()) }; let top = &tile_strs[1]; let bottom = &tile_strs[TILE_SIZE]; let left = tile_strs[1..=TILE_SIZE] .iter() .fold(String::new(), |mut acc, s| { acc.push(s.chars().nth(0).unwrap()); acc }); let right = tile_strs[1..=TILE_SIZE] .iter() .fold(String::new(), |mut acc, s| { acc.push(s.chars().nth(TILE_SIZE - 1).unwrap()); acc }); // Construct an Image bitmap (bools) from the tile, excluding the outer row/columns. let inner_bitmap = { let mut v = Vec::new(); for row in 2..2 + INNER_SIZE { let str = &tile_strs[row]; for char in str[1..=INNER_SIZE].chars() { v.push(match char { '1' => true, _ => false, }); } } v }; tiles.push(Tile { id: id, top: Edge::new(top, false), right: Edge::new(&right, false), bottom: Edge::new(bottom, true), left: Edge::new(&left, true), inner_image: Image { width: INNER_SIZE, height: INNER_SIZE, bitmap: inner_bitmap, }, image_ops: Vec::new(), }); // Find unique borders. let mut all_edges: Vec<&mut Edge> = Vec::new(); for t in &mut tiles { all_edges.push(&mut t.left); all_edges.push(&mut t.top); all_edges.push(&mut t.right); all_edges.push(&mut t.bottom); } for i in 0..all_edges.len() { for j in i + 1..all_edges.len() { if all_edges[i].num == all_edges[j].num { all_edges[i].border = false; all_edges[j].border = false; break; } } } } tiles } fn orient_rel(&mut self, op: Operation) { self.image_ops.push(op); let left = self.left; let top = self.top; let right = self.right; let bottom = self.bottom; match op { Operation::Rot90 => { self.left = bottom; self.bottom = right; self.right = top; self.top = left; } Operation::FlipHorz => { self.left = right; self.right = left; self.bottom.flipped = !self.bottom.flipped; self.top.flipped = !self.top.flipped; self.left.flipped = !self.left.flipped; self.right.flipped = !self.right.flipped; } } } fn num_border_edges(&self) -> usize { let edges = [&self.left, &self.right, &self.top, &self.bottom]; let it = edges.iter().filter(|&&edge| edge.border); it.count() } fn resolve_image(&mut self) { for op in &self.image_ops { self.inner_image.orient_rel(*op); } self.image_ops.clear(); } } fn solve(input_all: &str) -> anyhow::Result<()> { let lines = input_all.split_terminator("\n").collect::<Vec<_>>(); let tiles = Tile::from_strings(lines); let num_tiles = tiles.len(); let board_width = { let mut i = 1; loop { if i * i == num_tiles { break i; } i += 1; assert!(i < num_tiles / 2); } }; let corners = { let mut v = Vec::new(); for t in &tiles { if t.num_border_edges() == 2 { v.push(t.clone()); } } v }; assert_eq!(corners.len(), 4); let edges = { let mut v = Vec::new(); for t in &tiles { if t.num_border_edges() == 1 { v.push(t.clone()); } } v }; assert_eq!(edges.len(), (board_width - 2) * 4); let inners = { let mut v = Vec::new(); for t in &tiles { if t.num_border_edges() == 0 { v.push(t.clone()); } } v }; assert_eq!(inners.len(), (board_width - 2) * (board_width - 2)); fn collect_tile_edges(tile_list: &Vec<Tile>) -> HashMap<EdgeNum, Vec<&Tile>> { let mut h = HashMap::new(); for tile in tile_list.iter() { for edge in [&tile.top, &tile.left, &tile.right, &tile.bottom].iter() { match h.get_mut(&edge.num) { None => drop(h.insert(edge.num, vec![tile])), Some(tiles_vec) => tiles_vec.push(tile), }; } } h } let corner_tiles_by_edge = collect_tile_edges(&corners); let edge_tiles_by_edge = collect_tile_edges(&edges); let inner_tiles_by_edge = collect_tile_edges(&inners); let tiles_by_id: HashMap<TileId, &Tile> = { let mut h = HashMap::new(); for tile in &tiles { h.insert(tile.id, tile); } h }; #[derive(Clone)] struct Ctx<'a> { board_width: usize, tiles_by_id: &'a HashMap<TileId, &'a Tile>, corner_tiles_by_edge: &'a HashMap<EdgeNum, Vec<&'a Tile>>, edge_tiles_by_edge: &'a HashMap<EdgeNum, Vec<&'a Tile>>, inner_tiles_by_edge: &'a HashMap<EdgeNum, Vec<&'a Tile>>, board: Vec<Tile>, used_tiles: HashSet<TileId>, } let mut ctx = Ctx { board_width: board_width, tiles_by_id: &tiles_by_id, corner_tiles_by_edge: &corner_tiles_by_edge, edge_tiles_by_edge: &edge_tiles_by_edge, inner_tiles_by_edge: &inner_tiles_by_edge, board: Vec::new(), used_tiles: HashSet::new(), }; let mut top_left = corners[0].clone(); while !top_left.left.border || !top_left.top.border { top_left.orient_rel(Operation::Rot90); } ctx.used_tiles.insert(top_left.id); ctx.board.push(top_left); fn try_tile(at: usize, ctx: Ctx) -> Option<Vec<Tile>> { let board_width = ctx.board_width; let x = at % board_width; let y = at / board_width; if at == board_width * board_width { return Some(ctx.board.clone()); } let all_candidates = { if (x == 0 && y == board_width - 1) || (x == board_width - 1 && y == 0) || (x == board_width - 1 && y == board_width - 1) { &ctx.corner_tiles_by_edge } else if x == 0 || y == 0 || x == board_width - 1 || y == board_width - 1 { &ctx.edge_tiles_by_edge } else { &ctx.inner_tiles_by_edge } }; // Find the set of candidate tiles that can be placed at position `at` such that // they have an edge that matches the tile above them and to the left of them. // This has to handle the edge cases of tiles in the top row/left column, where // there's nothing to match there so any edge works. Tile at (0,0) is placed first // before this function is ever called, so it doesn't need to choose that one. let mut candidates: HashSet<TileId> = HashSet::new(); match (x, y) { (0, 0) => panic!("we don't see 0,0"), (0, _) => { let top = ctx.board[(y - 1) * board_width + x].bottom; for candi in &all_candidates[&top.num] { if !ctx.used_tiles.contains(&candi.id) { candidates.insert(candi.id); } } } (_, 0) => { let left = ctx.board[y * board_width + x - 1].right; for candi in &all_candidates[&left.num] { if !ctx.used_tiles.contains(&candi.id) { candidates.insert(candi.id); } } } (_, _) => { let left = ctx.board[y * board_width + x - 1].right; let top = ctx.board[(y - 1) * board_width + x].bottom; let mut left_candidates: HashSet<TileId> = HashSet::new(); for candi in &all_candidates[&left.num] { left_candidates.insert(candi.id); } for candi in &all_candidates[&top.num] { if left_candidates.contains(&candi.id) { if !ctx.used_tiles.contains(&candi.id) { candidates.insert(candi.id); } } } } }; for candi in candidates { let mut tile = ctx.tiles_by_id[&candi].clone(); for i in 0..NUM_ORIENTATIONS { let recurse = match (x, y) { (0, 0) => panic!("we don't see 0,0"), (0, _) => { let top = ctx.board[(y - 1) * board_width + x].bottom; tile.top.num == top.num && tile.top.flipped != top.flipped } (_, 0) => { let left = ctx.board[y * board_width + x - 1].right; tile.left.num == left.num && tile.left.flipped != left.flipped } (_, _) => { let left = ctx.board[y * board_width + x - 1].right; let top = ctx.board[(y - 1) * board_width + x].bottom; tile.top.num == top.num && tile.top.flipped != top.flipped && tile.left.num == left.num && tile.left.flipped != left.flipped } }; if recurse { // Match! Try recurse. let mut ctx = ctx.clone(); ctx.board.push(tile.clone()); ctx.used_tiles.insert(tile.id); if let Some(board) = try_tile(at + 1, ctx) { return Some(board); } } // Flip `tile` to next orientation. if i == NUM_ORIENTATIONS / 2 - 1 { tile.orient_rel(Operation::Rot90); // Back to 0deg. tile.orient_rel(Operation::FlipHorz); } else { tile.orient_rel(Operation::Rot90); } } } None } let solved_board_result = try_tile(1, ctx); let mut board = solved_board_result.expect("Failed to find a board layout"); let m = board_width - 1; let a = 0 + board_width * 0; let b = m + board_width * 0; let c = 0 + board_width * m; let d = m + board_width * m; println!( "Part 1 {}", board[a].id.0 * board[b].id.0 * board[c].id.0 * board[d].id.0 ); for tile in &mut board { tile.resolve_image(); } // Construct the final Image from the combined tiles' inner images. let mut image = Image { width: board_width * INNER_SIZE, height: board_width * INNER_SIZE, bitmap: Vec::new(), }; image .bitmap .reserve(board_width * board_width * INNER_SIZE * INNER_SIZE); for tile_y in 0..board_width { for tile_row in 0..INNER_SIZE { for tile_x in 0..board_width { let at = tile_y * board_width + tile_x; let tile_bitmap = &board[at].inner_image.bitmap; let start = tile_row * INNER_SIZE; let end = (tile_row + 1) * INNER_SIZE; for i in start..end { image.bitmap.push(tile_bitmap[i]); } } } } assert_eq!( image.bitmap.len(), board_width * board_width * INNER_SIZE * INNER_SIZE ); // Regexes use ^ because we may need to find overlapping patterns, so we will // be searching at each position in the image strings. let monster = [ Regex::new(r"^..................#.").unwrap(), Regex::new(r"^#....##....##....###").unwrap(), Regex::new(r"^.#..#..#..#..#..#...").unwrap(), ]; // The length of each monster line pattern. const MONSTER_LEN: usize = 20; // How many tiles the monster covers. The number of # in the monster pattern above. const MONSTER_COVERAGE: usize = 15; for i in 0..NUM_ORIENTATIONS { // Look for sea monsters. let mut num_monsters = 0; for row in 0..image.height - 2 { let get_monster_positions = |monster_re: &Regex, row: usize| -> Vec<usize> { let row_str = image.get_row_string(row); let mut v = Vec::new(); for i in 0..row_str.len() - MONSTER_LEN { if let Some(m) = monster_re.find(&row_str[i..]) { assert_eq!(m.start(), 0); v.push(i); } } v }; let mut first = get_monster_positions(&monster[0], row); let mut second = get_monster_positions(&monster[1], row + 1); let mut third = get_monster_positions(&monster[2], row + 2); // Count matches. while !first.is_empty() && !second.is_empty() && !third.is_empty() { if first[0] == second[0] && second[0] == third[0] { num_monsters += 1; first.remove(0); second.remove(0); third.remove(0); } else if first[0] <= second[0] && first[0] <= third[0] { first.remove(0); } else if second[0] <= first[0] && second[0] <= third[0] { second.remove(0); } else { assert!(third[0] <= first[0] && third[0] <= second[0]); third.remove(0); } } } if num_monsters > 0 { let wave_count = image.bitmap.iter().filter(|&b| *b).count(); println!("Part 2 {}", wave_count - num_monsters * MONSTER_COVERAGE); break; } // Flip `image` to next orientation. if i == NUM_ORIENTATIONS / 2 - 1 { image.orient_rel(Operation::Rot90); // Back to 0deg. image.orient_rel(Operation::FlipHorz); } else { image.orient_rel(Operation::Rot90); } } Ok(()) } fn main() -> anyhow::Result<()> { //let input_all = std::fs::read_to_string("day20/test1.txt")?; let input_all = std::fs::read_to_string("day20/input.txt")?; solve(&input_all)?; Ok(()) } #[cfg(test)] mod tests { use super::*; #[test] fn test_image_mutation() { #![allow(dead_code)] const BASE: &str = r"Tile 2953: ########## .......... ########## .......... ########## #......#.. #......#.. #......#.. #......#.. #......#.."; const ROTATE1: &str = r"Tile 2953: ######.#.# .....#.#.# .....#.#.# .....#.#.# .....#.#.# .....#.#.# .....#.#.# ######.#.# .....#.#.# .....#.#.#"; const ROTATE2: &str = r"Tile 2953: ..#......# ..#......# ..#......# ..#......# ..#......# ########## .......... ########## .......... ##########"; const FLIPPED: &str = r"Tile 2953: ########## .......... ########## .......... ########## ..#......# ..#......# ..#......# ..#......# ..#......#"; let base = &Tile::from_strings(BASE.split_terminator("\n").map(|s| s.trim()).collect())[0]; let expect_rotate1 = &Tile::from_strings(ROTATE1.split_terminator("\n").map(|s| s.trim()).collect())[0]; let expect_rotate2 = &Tile::from_strings(ROTATE2.split_terminator("\n").map(|s| s.trim()).collect())[0]; let expect_flipped = &Tile::from_strings(FLIPPED.split_terminator("\n").map(|s| s.trim()).collect())[0]; let compare_tile_ops = |base: &Tile, ops: Vec<Operation>, expect: &Tile| { let mut actual = base.clone(); for op in &ops { actual.orient_rel(*op); } assert_eq!(actual.image_ops, ops); actual.resolve_image(); assert_eq!(actual.image_ops, vec![]); if actual.inner_image.bitmap != expect.inner_image.bitmap { println!("EXPECT\n{}", expect.inner_image); println!("ACTUAL\n{}", actual.inner_image); assert_eq!(actual.inner_image.bitmap, expect.inner_image.bitmap); } }; compare_tile_ops(base, vec![Operation::Rot90], expect_rotate1); compare_tile_ops( base, vec![Operation::Rot90, Operation::Rot90], expect_rotate2, ); compare_tile_ops(base, vec![Operation::FlipHorz], expect_flipped); } }
Java
UTF-8
584
3.328125
3
[]
no_license
package newbasicjava; import java.util.Scanner; public class FibonacciDemo { public static void main(String[] args) { Scanner input=new Scanner(System.in); int n; System.out.print("How many number:"); n=input.nextInt(); int first=0,second=1,fibo; System.out.print(first+" "+second); for(int i=3;i<=n;i++){ fibo=first+second; System.out.print(" "+fibo); first=second; second=fibo; } System.out.println(""); } }
Markdown
UTF-8
809
2.65625
3
[]
no_license
# INR-USD # Time Series Analysis of Indian National Rupee against US Dollar Motivation for this project is the fact that INR has lost its value against USD over time. For instance, 1 USD was equivalent to 31.4 INR in January 1994 and it is about 74 rupees in November 2020. This repo has all the files needed to execute this project. I have used data from Jan 1994-Dec 2016 for model building and data from Jan 2017-Aug 2018 is used for forecasting. I conducted thorough data analysis and detected strong autocorrelation along with seasonality during government elections in India. Considered ARIMA, SARIMA, Naive, & Decomposition methods to build models and provided forecasts for future rates. Input files are maindatacsv.csv and forecastdata.csv (test data). moneydata.R is the R script for analysis.
Java
UTF-8
1,627
2.078125
2
[ "Apache-2.0" ]
permissive
/******************************************************************************* * Copyright (c) 2006-2010 eBay Inc. 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 *******************************************************************************/ package org.ebayopensource.turmeric.repositorymanager.assertions; import java.util.Collection; /** * An AssertionModule contains reusable scripts that are used by Assertions. * * @author pcopeland */ public interface AssertionModule { /** * Returns the name of this AssertionModule. * * @return the name of this AssertionModule. */ public String getName(); /** * Returns the version of this AssertionModule. * * @return the version of this AssertionModule. */ public String getVersion(); /** * Returns the description of this AssertionModule. * * @return the description of this AssertionModule. */ public String getDescription(); /** * Returns the script contents contained in this AssertionModule. * * @return the script contents contained in this AssertionModule. */ public Collection<AssertionContent> getModuleScripts(); /** * Returns the AssertionProcessor type that uses this AssertionModule. * * @return the AssertionProcessor type that uses this AssertionModule. */ public String getAssertionProcessorType(); }
Python
UTF-8
204
2.921875
3
[]
no_license
# Problem: https://www.hackerrank.com/challenges/itertools-product/problem # Score: 10 ____ i.. _______ product a l.. m..(i.., i.. ).s..())) b l.. m..(i.., i.. ).s..())) print(*l..(product(a, b)))
Java
UTF-8
1,235
1.953125
2
[]
no_license
package com.fact.model; import com.fasterxml.jackson.annotation.JsonIgnore; import lombok.Data; import javax.persistence.*; import java.util.Date; import java.util.List; @Data @Entity // @Table(name = "table_name", uniqueConstraints={@UniqueConstraint(columnNames = "column1"),@UniqueConstraint(columnNames = "column2")}) @Table(name = "utilisateur", uniqueConstraints={@UniqueConstraint(columnNames = "username")}) public class Utilisateur { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @Column(unique = true, name = "username") private String login; private String clearPassword; private String password; @Column(name = "enabled", columnDefinition = "boolean default false") private boolean enabled; private String matricule; @OneToMany(fetch = FetchType.EAGER, mappedBy="utilisateur", cascade = CascadeType.ALL ) private List<Authority> authorities; @JsonIgnore @ManyToMany private List<Role> roles; //------------------------- Secure Logs--- private Date created; private Date updated; private Long createdBy; private Long updatedBy; //------------------------- Secure Logs--- }
SQL
UTF-8
43,111
2.71875
3
[ "MIT" ]
permissive
CREATE TABLE list (id VARCHAR(2) NOT NULL, value VARCHAR(64) NOT NULL, PRIMARY KEY(id)); INSERT INTO "list" ("id", "value") VALUES (E'af', E'afrikaans'); INSERT INTO "list" ("id", "value") VALUES (E'af_ZA', E'afrikaans (Dél-afrikai Köztársaság)'); INSERT INTO "list" ("id", "value") VALUES (E'af_NA', E'afrikaans (Namíbia)'); INSERT INTO "list" ("id", "value") VALUES (E'ak', E'akan'); INSERT INTO "list" ("id", "value") VALUES (E'ak_GH', E'akan (Ghána)'); INSERT INTO "list" ("id", "value") VALUES (E'sq', E'albán'); INSERT INTO "list" ("id", "value") VALUES (E'sq_AL', E'albán (Albánia)'); INSERT INTO "list" ("id", "value") VALUES (E'sq_XK', E'albán (Koszovó)'); INSERT INTO "list" ("id", "value") VALUES (E'sq_MK', E'albán (Macedónia)'); INSERT INTO "list" ("id", "value") VALUES (E'am', E'amhara'); INSERT INTO "list" ("id", "value") VALUES (E'am_ET', E'amhara (Etiópia)'); INSERT INTO "list" ("id", "value") VALUES (E'en', E'angol'); INSERT INTO "list" ("id", "value") VALUES (E'en_UM', E'angol (Amerikai Csendes-óceáni Szigetek)'); INSERT INTO "list" ("id", "value") VALUES (E'en_AS', E'angol (Amerikai Szamoa)'); INSERT INTO "list" ("id", "value") VALUES (E'en_VI', E'angol (Amerikai Virgin-szigetek)'); INSERT INTO "list" ("id", "value") VALUES (E'en_AI', E'angol (Anguilla)'); INSERT INTO "list" ("id", "value") VALUES (E'en_AG', E'angol (Antigua és Barbuda)'); INSERT INTO "list" ("id", "value") VALUES (E'en_AU', E'angol (Ausztrália)'); INSERT INTO "list" ("id", "value") VALUES (E'en_BS', E'angol (Bahama-szigetek)'); INSERT INTO "list" ("id", "value") VALUES (E'en_BB', E'angol (Barbados)'); INSERT INTO "list" ("id", "value") VALUES (E'en_BE', E'angol (Belgium)'); INSERT INTO "list" ("id", "value") VALUES (E'en_BZ', E'angol (Belize)'); INSERT INTO "list" ("id", "value") VALUES (E'en_BM', E'angol (Bermuda)'); INSERT INTO "list" ("id", "value") VALUES (E'en_BW', E'angol (Botswana)'); INSERT INTO "list" ("id", "value") VALUES (E'en_IO', E'angol (Brit Indiai-óceáni Terület)'); INSERT INTO "list" ("id", "value") VALUES (E'en_VG', E'angol (Brit Virgin-szigetek)'); INSERT INTO "list" ("id", "value") VALUES (E'en_CK', E'angol (Cook-szigetek)'); INSERT INTO "list" ("id", "value") VALUES (E'en_ZA', E'angol (Dél-afrikai Köztársaság)'); INSERT INTO "list" ("id", "value") VALUES (E'en_SS', E'angol (Dél-Szudán)'); INSERT INTO "list" ("id", "value") VALUES (E'en_DG', E'angol (Diego Garcia)'); INSERT INTO "list" ("id", "value") VALUES (E'en_DM', E'angol (Dominika)'); INSERT INTO "list" ("id", "value") VALUES (E'en_US', E'angol (Egyesült Államok)'); INSERT INTO "list" ("id", "value") VALUES (E'en_GB', E'angol (Egyesült Királyság)'); INSERT INTO "list" ("id", "value") VALUES (E'en_ER', E'angol (Eritrea)'); INSERT INTO "list" ("id", "value") VALUES (E'en_MP', E'angol (Északi Mariana-szigetek)'); INSERT INTO "list" ("id", "value") VALUES (E'en_FK', E'angol (Falkland-szigetek)'); INSERT INTO "list" ("id", "value") VALUES (E'en_FJ', E'angol (Fidzsi-szigetek)'); INSERT INTO "list" ("id", "value") VALUES (E'en_PH', E'angol (Fülöp-szigetek)'); INSERT INTO "list" ("id", "value") VALUES (E'en_GM', E'angol (Gambia)'); INSERT INTO "list" ("id", "value") VALUES (E'en_GH', E'angol (Ghána)'); INSERT INTO "list" ("id", "value") VALUES (E'en_GI', E'angol (Gibraltár)'); INSERT INTO "list" ("id", "value") VALUES (E'en_GD', E'angol (Grenada)'); INSERT INTO "list" ("id", "value") VALUES (E'en_GU', E'angol (Guam)'); INSERT INTO "list" ("id", "value") VALUES (E'en_GG', E'angol (Guernsey)'); INSERT INTO "list" ("id", "value") VALUES (E'en_GY', E'angol (Guyana)'); INSERT INTO "list" ("id", "value") VALUES (E'en_HK', E'angol (Hongkong SAR Kína)'); INSERT INTO "list" ("id", "value") VALUES (E'en_IN', E'angol (India)'); INSERT INTO "list" ("id", "value") VALUES (E'en_IE', E'angol (Írország)'); INSERT INTO "list" ("id", "value") VALUES (E'en_JM', E'angol (Jamaica)'); INSERT INTO "list" ("id", "value") VALUES (E'en_JE', E'angol (Jersey)'); INSERT INTO "list" ("id", "value") VALUES (E'en_KY', E'angol (Kajmán-szigetek)'); INSERT INTO "list" ("id", "value") VALUES (E'en_CM', E'angol (Kamerun)'); INSERT INTO "list" ("id", "value") VALUES (E'en_CA', E'angol (Kanada)'); INSERT INTO "list" ("id", "value") VALUES (E'en_CX', E'angol (Karácsony-sziget)'); INSERT INTO "list" ("id", "value") VALUES (E'en_KE', E'angol (Kenya)'); INSERT INTO "list" ("id", "value") VALUES (E'en_KI', E'angol (Kiribati)'); INSERT INTO "list" ("id", "value") VALUES (E'en_CC', E'angol (Kókusz-szigetek)'); INSERT INTO "list" ("id", "value") VALUES (E'en_LS', E'angol (Lesotho)'); INSERT INTO "list" ("id", "value") VALUES (E'en_LR', E'angol (Libéria)'); INSERT INTO "list" ("id", "value") VALUES (E'en_MG', E'angol (Madagaszkár)'); INSERT INTO "list" ("id", "value") VALUES (E'en_MO', E'angol (Makaó SAR Kína)'); INSERT INTO "list" ("id", "value") VALUES (E'en_MY', E'angol (Malajzia)'); INSERT INTO "list" ("id", "value") VALUES (E'en_MW', E'angol (Malawi)'); INSERT INTO "list" ("id", "value") VALUES (E'en_MT', E'angol (Málta)'); INSERT INTO "list" ("id", "value") VALUES (E'en_IM', E'angol (Man-sziget)'); INSERT INTO "list" ("id", "value") VALUES (E'en_MH', E'angol (Marshall-szigetek)'); INSERT INTO "list" ("id", "value") VALUES (E'en_MU', E'angol (Mauritius)'); INSERT INTO "list" ("id", "value") VALUES (E'en_FM', E'angol (Mikronézia)'); INSERT INTO "list" ("id", "value") VALUES (E'en_MS', E'angol (Montserrat)'); INSERT INTO "list" ("id", "value") VALUES (E'en_NA', E'angol (Namíbia)'); INSERT INTO "list" ("id", "value") VALUES (E'en_NR', E'angol (Nauru)'); INSERT INTO "list" ("id", "value") VALUES (E'en_NG', E'angol (Nigéria)'); INSERT INTO "list" ("id", "value") VALUES (E'en_NU', E'angol (Niue)'); INSERT INTO "list" ("id", "value") VALUES (E'en_NF', E'angol (Norfolk-sziget)'); INSERT INTO "list" ("id", "value") VALUES (E'en_PK', E'angol (Pakisztán)'); INSERT INTO "list" ("id", "value") VALUES (E'en_PW', E'angol (Palau)'); INSERT INTO "list" ("id", "value") VALUES (E'en_PG', E'angol (Pápua Új-Guinea)'); INSERT INTO "list" ("id", "value") VALUES (E'en_PN', E'angol (Pitcairn-szigetek)'); INSERT INTO "list" ("id", "value") VALUES (E'en_PR', E'angol (Puerto Rico)'); INSERT INTO "list" ("id", "value") VALUES (E'en_RW', E'angol (Ruanda)'); INSERT INTO "list" ("id", "value") VALUES (E'en_KN', E'angol (Saint Kitts és Nevis)'); INSERT INTO "list" ("id", "value") VALUES (E'en_VC', E'angol (Saint Vincent és a Grenadine-szigetek)'); INSERT INTO "list" ("id", "value") VALUES (E'en_SB', E'angol (Salamon-szigetek)'); INSERT INTO "list" ("id", "value") VALUES (E'en_LC', E'angol (Santa Lucia)'); INSERT INTO "list" ("id", "value") VALUES (E'en_SC', E'angol (Seychelle-szigetek)'); INSERT INTO "list" ("id", "value") VALUES (E'en_SL', E'angol (Sierra Leone)'); INSERT INTO "list" ("id", "value") VALUES (E'en_SX', E'angol (Sint Maarten)'); INSERT INTO "list" ("id", "value") VALUES (E'en_WS', E'angol (Szamoa)'); INSERT INTO "list" ("id", "value") VALUES (E'en_SH', E'angol (Szent Ilona)'); INSERT INTO "list" ("id", "value") VALUES (E'en_SG', E'angol (Szingapúr)'); INSERT INTO "list" ("id", "value") VALUES (E'en_SD', E'angol (Szudán)'); INSERT INTO "list" ("id", "value") VALUES (E'en_SZ', E'angol (Szváziföld)'); INSERT INTO "list" ("id", "value") VALUES (E'en_TZ', E'angol (Tanzánia)'); INSERT INTO "list" ("id", "value") VALUES (E'en_TK', E'angol (Tokelau)'); INSERT INTO "list" ("id", "value") VALUES (E'en_TO', E'angol (Tonga)'); INSERT INTO "list" ("id", "value") VALUES (E'en_TT', E'angol (Trinidad és Tobago)'); INSERT INTO "list" ("id", "value") VALUES (E'en_TC', E'angol (Turks- és Caicos-szigetek)'); INSERT INTO "list" ("id", "value") VALUES (E'en_TV', E'angol (Tuvalu)'); INSERT INTO "list" ("id", "value") VALUES (E'en_UG', E'angol (Uganda)'); INSERT INTO "list" ("id", "value") VALUES (E'en_NZ', E'angol (Új-Zéland)'); INSERT INTO "list" ("id", "value") VALUES (E'en_VU', E'angol (Vanuatu)'); INSERT INTO "list" ("id", "value") VALUES (E'en_ZM', E'angol (Zambia)'); INSERT INTO "list" ("id", "value") VALUES (E'en_ZW', E'angol (Zimbabwe)'); INSERT INTO "list" ("id", "value") VALUES (E'ar', E'arab'); INSERT INTO "list" ("id", "value") VALUES (E'ar_DZ', E'arab (Algéria)'); INSERT INTO "list" ("id", "value") VALUES (E'ar_BH', E'arab (Bahrein)'); INSERT INTO "list" ("id", "value") VALUES (E'ar_KM', E'arab (Comore-szigetek)'); INSERT INTO "list" ("id", "value") VALUES (E'ar_TD', E'arab (Csád)'); INSERT INTO "list" ("id", "value") VALUES (E'ar_SS', E'arab (Dél-Szudán)'); INSERT INTO "list" ("id", "value") VALUES (E'ar_DJ', E'arab (Dzsibuti)'); INSERT INTO "list" ("id", "value") VALUES (E'ar_AE', E'arab (Egyesült Arab Emirátus)'); INSERT INTO "list" ("id", "value") VALUES (E'ar_EG', E'arab (Egyiptom)'); INSERT INTO "list" ("id", "value") VALUES (E'ar_ER', E'arab (Eritrea)'); INSERT INTO "list" ("id", "value") VALUES (E'ar_IQ', E'arab (Irak)'); INSERT INTO "list" ("id", "value") VALUES (E'ar_IL', E'arab (Izrael)'); INSERT INTO "list" ("id", "value") VALUES (E'ar_YE', E'arab (Jemen)'); INSERT INTO "list" ("id", "value") VALUES (E'ar_JO', E'arab (Jordánia)'); INSERT INTO "list" ("id", "value") VALUES (E'ar_QA', E'arab (Katar)'); INSERT INTO "list" ("id", "value") VALUES (E'ar_KW', E'arab (Kuvait)'); INSERT INTO "list" ("id", "value") VALUES (E'ar_LB', E'arab (Libanon)'); INSERT INTO "list" ("id", "value") VALUES (E'ar_LY', E'arab (Líbia)'); INSERT INTO "list" ("id", "value") VALUES (E'ar_MA', E'arab (Marokkó)'); INSERT INTO "list" ("id", "value") VALUES (E'ar_MR', E'arab (Mauritánia)'); INSERT INTO "list" ("id", "value") VALUES (E'ar_EH', E'arab (Nyugat-Szahara)'); INSERT INTO "list" ("id", "value") VALUES (E'ar_OM', E'arab (Omán)'); INSERT INTO "list" ("id", "value") VALUES (E'ar_PS', E'arab (Palesztin Terület)'); INSERT INTO "list" ("id", "value") VALUES (E'ar_SA', E'arab (Szaúd-Arábia)'); INSERT INTO "list" ("id", "value") VALUES (E'ar_SY', E'arab (Szíria)'); INSERT INTO "list" ("id", "value") VALUES (E'ar_SO', E'arab (Szomália)'); INSERT INTO "list" ("id", "value") VALUES (E'ar_SD', E'arab (Szudán)'); INSERT INTO "list" ("id", "value") VALUES (E'ar_TN', E'arab (Tunézia)'); INSERT INTO "list" ("id", "value") VALUES (E'as', E'asszámi'); INSERT INTO "list" ("id", "value") VALUES (E'as_IN', E'asszámi (India)'); INSERT INTO "list" ("id", "value") VALUES (E'az', E'azerbajdzsáni'); INSERT INTO "list" ("id", "value") VALUES (E'az_AZ', E'azerbajdzsáni (Azerbajdzsán)'); INSERT INTO "list" ("id", "value") VALUES (E'az_Cyrl_AZ', E'azerbajdzsáni (Cirill, Azerbajdzsán)'); INSERT INTO "list" ("id", "value") VALUES (E'az_Cyrl', E'azerbajdzsáni (Cirill)'); INSERT INTO "list" ("id", "value") VALUES (E'az_Latn_AZ', E'azerbajdzsáni (Latin, Azerbajdzsán)'); INSERT INTO "list" ("id", "value") VALUES (E'az_Latn', E'azerbajdzsáni (Latin)'); INSERT INTO "list" ("id", "value") VALUES (E'bm', E'bambara'); INSERT INTO "list" ("id", "value") VALUES (E'bm_Latn_ML', E'bambara (Latin, Mali)'); INSERT INTO "list" ("id", "value") VALUES (E'bm_Latn', E'bambara (Latin)'); INSERT INTO "list" ("id", "value") VALUES (E'eu', E'baszk'); INSERT INTO "list" ("id", "value") VALUES (E'eu_ES', E'baszk (Spanyolország)'); INSERT INTO "list" ("id", "value") VALUES (E'be', E'belorusz'); INSERT INTO "list" ("id", "value") VALUES (E'be_BY', E'belorusz (Fehéroroszország)'); INSERT INTO "list" ("id", "value") VALUES (E'bn', E'bengáli'); INSERT INTO "list" ("id", "value") VALUES (E'bn_BD', E'bengáli (Banglades)'); INSERT INTO "list" ("id", "value") VALUES (E'bn_IN', E'bengáli (India)'); INSERT INTO "list" ("id", "value") VALUES (E'bg', E'bolgár'); INSERT INTO "list" ("id", "value") VALUES (E'bg_BG', E'bolgár (Bulgária)'); INSERT INTO "list" ("id", "value") VALUES (E'bs', E'bosnyák'); INSERT INTO "list" ("id", "value") VALUES (E'bs_BA', E'bosnyák (Bosznia-Hercegovina)'); INSERT INTO "list" ("id", "value") VALUES (E'bs_Cyrl_BA', E'bosnyák (Cirill, Bosznia-Hercegovina)'); INSERT INTO "list" ("id", "value") VALUES (E'bs_Cyrl', E'bosnyák (Cirill)'); INSERT INTO "list" ("id", "value") VALUES (E'bs_Latn_BA', E'bosnyák (Latin, Bosznia-Hercegovina)'); INSERT INTO "list" ("id", "value") VALUES (E'bs_Latn', E'bosnyák (Latin)'); INSERT INTO "list" ("id", "value") VALUES (E'br', E'breton'); INSERT INTO "list" ("id", "value") VALUES (E'br_FR', E'breton (Franciaország)'); INSERT INTO "list" ("id", "value") VALUES (E'my', E'burmai'); INSERT INTO "list" ("id", "value") VALUES (E'my_MM', E'burmai (Mianmar (Burma))'); INSERT INTO "list" ("id", "value") VALUES (E'dz', E'butáni'); INSERT INTO "list" ("id", "value") VALUES (E'dz_BT', E'butáni (Bhután)'); INSERT INTO "list" ("id", "value") VALUES (E'cs', E'cseh'); INSERT INTO "list" ("id", "value") VALUES (E'cs_CZ', E'cseh (Csehország)'); INSERT INTO "list" ("id", "value") VALUES (E'da', E'dán'); INSERT INTO "list" ("id", "value") VALUES (E'da_DK', E'dán (Dánia)'); INSERT INTO "list" ("id", "value") VALUES (E'da_GL', E'dán (Grönland)'); INSERT INTO "list" ("id", "value") VALUES (E'nd', E'északi ndebele'); INSERT INTO "list" ("id", "value") VALUES (E'nd_ZW', E'északi ndebele (Zimbabwe)'); INSERT INTO "list" ("id", "value") VALUES (E'se', E'északi számi'); INSERT INTO "list" ("id", "value") VALUES (E'se_FI', E'északi számi (Finnország)'); INSERT INTO "list" ("id", "value") VALUES (E'se_NO', E'északi számi (Norvégia)'); INSERT INTO "list" ("id", "value") VALUES (E'se_SE', E'északi számi (Svédország)'); INSERT INTO "list" ("id", "value") VALUES (E'eo', E'eszperantó'); INSERT INTO "list" ("id", "value") VALUES (E'et', E'észt'); INSERT INTO "list" ("id", "value") VALUES (E'et_EE', E'észt (Észtország)'); INSERT INTO "list" ("id", "value") VALUES (E'ee', E'eve'); INSERT INTO "list" ("id", "value") VALUES (E'ee_GH', E'eve (Ghána)'); INSERT INTO "list" ("id", "value") VALUES (E'ee_TG', E'eve (Togo)'); INSERT INTO "list" ("id", "value") VALUES (E'fo', E'feröeri'); INSERT INTO "list" ("id", "value") VALUES (E'fo_FO', E'feröeri (Feröer-szigetek)'); INSERT INTO "list" ("id", "value") VALUES (E'fi', E'finn'); INSERT INTO "list" ("id", "value") VALUES (E'fi_FI', E'finn (Finnország)'); INSERT INTO "list" ("id", "value") VALUES (E'fr', E'francia'); INSERT INTO "list" ("id", "value") VALUES (E'fr_DZ', E'francia (Algéria)'); INSERT INTO "list" ("id", "value") VALUES (E'fr_BE', E'francia (Belgium)'); INSERT INTO "list" ("id", "value") VALUES (E'fr_BJ', E'francia (Benin)'); INSERT INTO "list" ("id", "value") VALUES (E'fr_BF', E'francia (Burkina Faso)'); INSERT INTO "list" ("id", "value") VALUES (E'fr_BI', E'francia (Burundi)'); INSERT INTO "list" ("id", "value") VALUES (E'fr_KM', E'francia (Comore-szigetek)'); INSERT INTO "list" ("id", "value") VALUES (E'fr_TD', E'francia (Csád)'); INSERT INTO "list" ("id", "value") VALUES (E'fr_DJ', E'francia (Dzsibuti)'); INSERT INTO "list" ("id", "value") VALUES (E'fr_GQ', E'francia (Egyenlítői-Guinea)'); INSERT INTO "list" ("id", "value") VALUES (E'fr_CI', E'francia (Elefántcsontpart)'); INSERT INTO "list" ("id", "value") VALUES (E'fr_GF', E'francia (Francia Guyana)'); INSERT INTO "list" ("id", "value") VALUES (E'fr_PF', E'francia (Francia Polinézia)'); INSERT INTO "list" ("id", "value") VALUES (E'fr_FR', E'francia (Franciaország)'); INSERT INTO "list" ("id", "value") VALUES (E'fr_GA', E'francia (Gabon)'); INSERT INTO "list" ("id", "value") VALUES (E'fr_GP', E'francia (Guadeloupe)'); INSERT INTO "list" ("id", "value") VALUES (E'fr_GN', E'francia (Guinea)'); INSERT INTO "list" ("id", "value") VALUES (E'fr_HT', E'francia (Haiti)'); INSERT INTO "list" ("id", "value") VALUES (E'fr_CM', E'francia (Kamerun)'); INSERT INTO "list" ("id", "value") VALUES (E'fr_CA', E'francia (Kanada)'); INSERT INTO "list" ("id", "value") VALUES (E'fr_CG', E'francia (Kongó - Brazzaville)'); INSERT INTO "list" ("id", "value") VALUES (E'fr_CD', E'francia (Kongó - Kinshasa)'); INSERT INTO "list" ("id", "value") VALUES (E'fr_CF', E'francia (Közép-afrikai Köztársaság)'); INSERT INTO "list" ("id", "value") VALUES (E'fr_LU', E'francia (Luxemburg)'); INSERT INTO "list" ("id", "value") VALUES (E'fr_MG', E'francia (Madagaszkár)'); INSERT INTO "list" ("id", "value") VALUES (E'fr_ML', E'francia (Mali)'); INSERT INTO "list" ("id", "value") VALUES (E'fr_MA', E'francia (Marokkó)'); INSERT INTO "list" ("id", "value") VALUES (E'fr_MQ', E'francia (Martinique)'); INSERT INTO "list" ("id", "value") VALUES (E'fr_MR', E'francia (Mauritánia)'); INSERT INTO "list" ("id", "value") VALUES (E'fr_MU', E'francia (Mauritius)'); INSERT INTO "list" ("id", "value") VALUES (E'fr_YT', E'francia (Mayotte)'); INSERT INTO "list" ("id", "value") VALUES (E'fr_MC', E'francia (Monaco)'); INSERT INTO "list" ("id", "value") VALUES (E'fr_NE', E'francia (Niger)'); INSERT INTO "list" ("id", "value") VALUES (E'fr_RE', E'francia (Reunion)'); INSERT INTO "list" ("id", "value") VALUES (E'fr_RW', E'francia (Ruanda)'); INSERT INTO "list" ("id", "value") VALUES (E'fr_MF', E'francia (Saint Martin)'); INSERT INTO "list" ("id", "value") VALUES (E'fr_PM', E'francia (Saint Pierre és Miquelon)'); INSERT INTO "list" ("id", "value") VALUES (E'fr_BL', E'francia (Saint-Barthélemy)'); INSERT INTO "list" ("id", "value") VALUES (E'fr_SC', E'francia (Seychelle-szigetek)'); INSERT INTO "list" ("id", "value") VALUES (E'fr_CH', E'francia (Svájc)'); INSERT INTO "list" ("id", "value") VALUES (E'fr_SN', E'francia (Szenegál)'); INSERT INTO "list" ("id", "value") VALUES (E'fr_SY', E'francia (Szíria)'); INSERT INTO "list" ("id", "value") VALUES (E'fr_TG', E'francia (Togo)'); INSERT INTO "list" ("id", "value") VALUES (E'fr_TN', E'francia (Tunézia)'); INSERT INTO "list" ("id", "value") VALUES (E'fr_NC', E'francia (Új-Kaledónia)'); INSERT INTO "list" ("id", "value") VALUES (E'fr_VU', E'francia (Vanuatu)'); INSERT INTO "list" ("id", "value") VALUES (E'fr_WF', E'francia (Wallis- és Futuna-szigetek)'); INSERT INTO "list" ("id", "value") VALUES (E'fy', E'fríz'); INSERT INTO "list" ("id", "value") VALUES (E'fy_NL', E'fríz (Hollandia)'); INSERT INTO "list" ("id", "value") VALUES (E'ff', E'fulani'); INSERT INTO "list" ("id", "value") VALUES (E'ff_GN', E'fulani (Guinea)'); INSERT INTO "list" ("id", "value") VALUES (E'ff_CM', E'fulani (Kamerun)'); INSERT INTO "list" ("id", "value") VALUES (E'ff_MR', E'fulani (Mauritánia)'); INSERT INTO "list" ("id", "value") VALUES (E'ff_SN', E'fulani (Szenegál)'); INSERT INTO "list" ("id", "value") VALUES (E'gl', E'galíciai'); INSERT INTO "list" ("id", "value") VALUES (E'gl_ES', E'galíciai (Spanyolország)'); INSERT INTO "list" ("id", "value") VALUES (E'lg', E'ganda'); INSERT INTO "list" ("id", "value") VALUES (E'lg_UG', E'ganda (Uganda)'); INSERT INTO "list" ("id", "value") VALUES (E'el', E'görög'); INSERT INTO "list" ("id", "value") VALUES (E'el_CY', E'görög (Ciprus)'); INSERT INTO "list" ("id", "value") VALUES (E'el_GR', E'görög (Görögország)'); INSERT INTO "list" ("id", "value") VALUES (E'kl', E'grönlandi'); INSERT INTO "list" ("id", "value") VALUES (E'kl_GL', E'grönlandi (Grönland)'); INSERT INTO "list" ("id", "value") VALUES (E'ka', E'grúz'); INSERT INTO "list" ("id", "value") VALUES (E'ka_GE', E'grúz (Grúzia)'); INSERT INTO "list" ("id", "value") VALUES (E'gu', E'gudzsarati'); INSERT INTO "list" ("id", "value") VALUES (E'gu_IN', E'gudzsarati (India)'); INSERT INTO "list" ("id", "value") VALUES (E'ha', E'hausza'); INSERT INTO "list" ("id", "value") VALUES (E'ha_GH', E'hausza (Ghána)'); INSERT INTO "list" ("id", "value") VALUES (E'ha_Latn_GH', E'hausza (Latin, Ghána)'); INSERT INTO "list" ("id", "value") VALUES (E'ha_Latn_NE', E'hausza (Latin, Niger)'); INSERT INTO "list" ("id", "value") VALUES (E'ha_Latn_NG', E'hausza (Latin, Nigéria)'); INSERT INTO "list" ("id", "value") VALUES (E'ha_Latn', E'hausza (Latin)'); INSERT INTO "list" ("id", "value") VALUES (E'ha_NE', E'hausza (Niger)'); INSERT INTO "list" ("id", "value") VALUES (E'ha_NG', E'hausza (Nigéria)'); INSERT INTO "list" ("id", "value") VALUES (E'he', E'héber'); INSERT INTO "list" ("id", "value") VALUES (E'he_IL', E'héber (Izrael)'); INSERT INTO "list" ("id", "value") VALUES (E'hi', E'hindi'); INSERT INTO "list" ("id", "value") VALUES (E'hi_IN', E'hindi (India)'); INSERT INTO "list" ("id", "value") VALUES (E'nl', E'holland'); INSERT INTO "list" ("id", "value") VALUES (E'nl_AW', E'holland (Aruba)'); INSERT INTO "list" ("id", "value") VALUES (E'nl_BE', E'holland (Belgium)'); INSERT INTO "list" ("id", "value") VALUES (E'nl_CW', E'holland (Curaçao)'); INSERT INTO "list" ("id", "value") VALUES (E'nl_BQ', E'holland (Holland Karib-térség)'); INSERT INTO "list" ("id", "value") VALUES (E'nl_NL', E'holland (Hollandia)'); INSERT INTO "list" ("id", "value") VALUES (E'nl_SX', E'holland (Sint Maarten)'); INSERT INTO "list" ("id", "value") VALUES (E'nl_SR', E'holland (Suriname)'); INSERT INTO "list" ("id", "value") VALUES (E'hr', E'horvát'); INSERT INTO "list" ("id", "value") VALUES (E'hr_BA', E'horvát (Bosznia-Hercegovina)'); INSERT INTO "list" ("id", "value") VALUES (E'hr_HR', E'horvát (Horvátország)'); INSERT INTO "list" ("id", "value") VALUES (E'ig', E'igbó'); INSERT INTO "list" ("id", "value") VALUES (E'ig_NG', E'igbó (Nigéria)'); INSERT INTO "list" ("id", "value") VALUES (E'id', E'indonéz'); INSERT INTO "list" ("id", "value") VALUES (E'id_ID', E'indonéz (Indonézia)'); INSERT INTO "list" ("id", "value") VALUES (E'ga', E'ír'); INSERT INTO "list" ("id", "value") VALUES (E'ga_IE', E'ír (Írország)'); INSERT INTO "list" ("id", "value") VALUES (E'is', E'izlandi'); INSERT INTO "list" ("id", "value") VALUES (E'is_IS', E'izlandi (Izland)'); INSERT INTO "list" ("id", "value") VALUES (E'ja', E'japán'); INSERT INTO "list" ("id", "value") VALUES (E'ja_JP', E'japán (Japán)'); INSERT INTO "list" ("id", "value") VALUES (E'yi', E'jiddis'); INSERT INTO "list" ("id", "value") VALUES (E'yo', E'joruba'); INSERT INTO "list" ("id", "value") VALUES (E'yo_BJ', E'joruba (Benin)'); INSERT INTO "list" ("id", "value") VALUES (E'yo_NG', E'joruba (Nigéria)'); INSERT INTO "list" ("id", "value") VALUES (E'km', E'kambodzsai'); INSERT INTO "list" ("id", "value") VALUES (E'km_KH', E'kambodzsai (Kambodzsa)'); INSERT INTO "list" ("id", "value") VALUES (E'kn', E'kannada'); INSERT INTO "list" ("id", "value") VALUES (E'kn_IN', E'kannada (India)'); INSERT INTO "list" ("id", "value") VALUES (E'ks', E'kásmíri'); INSERT INTO "list" ("id", "value") VALUES (E'ks_Arab_IN', E'kásmíri (Arab, India)'); INSERT INTO "list" ("id", "value") VALUES (E'ks_Arab', E'kásmíri (Arab)'); INSERT INTO "list" ("id", "value") VALUES (E'ks_IN', E'kásmíri (India)'); INSERT INTO "list" ("id", "value") VALUES (E'ca', E'katalán'); INSERT INTO "list" ("id", "value") VALUES (E'ca_AD', E'katalán (Andorra)'); INSERT INTO "list" ("id", "value") VALUES (E'ca_FR', E'katalán (Franciaország)'); INSERT INTO "list" ("id", "value") VALUES (E'ca_IT', E'katalán (Olaszország)'); INSERT INTO "list" ("id", "value") VALUES (E'ca_ES', E'katalán (Spanyolország)'); INSERT INTO "list" ("id", "value") VALUES (E'kk', E'kazah'); INSERT INTO "list" ("id", "value") VALUES (E'kk_Cyrl_KZ', E'kazah (Cirill, Kazahsztán)'); INSERT INTO "list" ("id", "value") VALUES (E'kk_Cyrl', E'kazah (Cirill)'); INSERT INTO "list" ("id", "value") VALUES (E'kk_KZ', E'kazah (Kazahsztán)'); INSERT INTO "list" ("id", "value") VALUES (E'qu', E'kecsua'); INSERT INTO "list" ("id", "value") VALUES (E'qu_BO', E'kecsua (Bolívia)'); INSERT INTO "list" ("id", "value") VALUES (E'qu_EC', E'kecsua (Ecuador)'); INSERT INTO "list" ("id", "value") VALUES (E'qu_PE', E'kecsua (Peru)'); INSERT INTO "list" ("id", "value") VALUES (E'ki', E'kikuju'); INSERT INTO "list" ("id", "value") VALUES (E'ki_KE', E'kikuju (Kenya)'); INSERT INTO "list" ("id", "value") VALUES (E'zh', E'kínai'); INSERT INTO "list" ("id", "value") VALUES (E'zh_Hans_HK', E'kínai (Egyszerűsített, Hongkong SAR Kína)'); INSERT INTO "list" ("id", "value") VALUES (E'zh_Hans_CN', E'kínai (Egyszerűsített, Kína)'); INSERT INTO "list" ("id", "value") VALUES (E'zh_Hans_MO', E'kínai (Egyszerűsített, Makaó SAR Kína)'); INSERT INTO "list" ("id", "value") VALUES (E'zh_Hans_SG', E'kínai (Egyszerűsített, Szingapúr)'); INSERT INTO "list" ("id", "value") VALUES (E'zh_Hans', E'kínai (Egyszerűsített)'); INSERT INTO "list" ("id", "value") VALUES (E'zh_Hant_HK', E'kínai (Hagyományos, Hongkong SAR Kína)'); INSERT INTO "list" ("id", "value") VALUES (E'zh_Hant_MO', E'kínai (Hagyományos, Makaó SAR Kína)'); INSERT INTO "list" ("id", "value") VALUES (E'zh_Hant_TW', E'kínai (Hagyományos, Tajvan)'); INSERT INTO "list" ("id", "value") VALUES (E'zh_Hant', E'kínai (Hagyományos)'); INSERT INTO "list" ("id", "value") VALUES (E'zh_HK', E'kínai (Hongkong SAR Kína)'); INSERT INTO "list" ("id", "value") VALUES (E'zh_CN', E'kínai (Kína)'); INSERT INTO "list" ("id", "value") VALUES (E'zh_MO', E'kínai (Makaó SAR Kína)'); INSERT INTO "list" ("id", "value") VALUES (E'zh_SG', E'kínai (Szingapúr)'); INSERT INTO "list" ("id", "value") VALUES (E'zh_TW', E'kínai (Tajvan)'); INSERT INTO "list" ("id", "value") VALUES (E'ky', E'kirgiz'); INSERT INTO "list" ("id", "value") VALUES (E'ky_Cyrl_KG', E'kirgiz (Cirill, Kirgizisztán)'); INSERT INTO "list" ("id", "value") VALUES (E'ky_Cyrl', E'kirgiz (Cirill)'); INSERT INTO "list" ("id", "value") VALUES (E'ky_KG', E'kirgiz (Kirgizisztán)'); INSERT INTO "list" ("id", "value") VALUES (E'rw', E'kiruanda'); INSERT INTO "list" ("id", "value") VALUES (E'rw_RW', E'kiruanda (Ruanda)'); INSERT INTO "list" ("id", "value") VALUES (E'rn', E'kirundi'); INSERT INTO "list" ("id", "value") VALUES (E'rn_BI', E'kirundi (Burundi)'); INSERT INTO "list" ("id", "value") VALUES (E'ko', E'koreai'); INSERT INTO "list" ("id", "value") VALUES (E'ko_KR', E'koreai (Dél-Korea)'); INSERT INTO "list" ("id", "value") VALUES (E'ko_KP', E'koreai (Észak-Korea)'); INSERT INTO "list" ("id", "value") VALUES (E'kw', E'korni'); INSERT INTO "list" ("id", "value") VALUES (E'kw_GB', E'korni (Egyesült Királyság)'); INSERT INTO "list" ("id", "value") VALUES (E'lo', E'laoszi'); INSERT INTO "list" ("id", "value") VALUES (E'lo_LA', E'laoszi (Laosz)'); INSERT INTO "list" ("id", "value") VALUES (E'pl', E'lengyel'); INSERT INTO "list" ("id", "value") VALUES (E'pl_PL', E'lengyel (Lengyelország)'); INSERT INTO "list" ("id", "value") VALUES (E'lv', E'lett'); INSERT INTO "list" ("id", "value") VALUES (E'lv_LV', E'lett (Lettország)'); INSERT INTO "list" ("id", "value") VALUES (E'ln', E'lingala'); INSERT INTO "list" ("id", "value") VALUES (E'ln_AO', E'lingala (Angola)'); INSERT INTO "list" ("id", "value") VALUES (E'ln_CG', E'lingala (Kongó - Brazzaville)'); INSERT INTO "list" ("id", "value") VALUES (E'ln_CD', E'lingala (Kongó - Kinshasa)'); INSERT INTO "list" ("id", "value") VALUES (E'ln_CF', E'lingala (Közép-afrikai Köztársaság)'); INSERT INTO "list" ("id", "value") VALUES (E'lt', E'litván'); INSERT INTO "list" ("id", "value") VALUES (E'lt_LT', E'litván (Litvánia)'); INSERT INTO "list" ("id", "value") VALUES (E'lu', E'luba-katanga'); INSERT INTO "list" ("id", "value") VALUES (E'lu_CD', E'luba-katanga (Kongó - Kinshasa)'); INSERT INTO "list" ("id", "value") VALUES (E'lb', E'luxemburgi'); INSERT INTO "list" ("id", "value") VALUES (E'lb_LU', E'luxemburgi (Luxemburg)'); INSERT INTO "list" ("id", "value") VALUES (E'mk', E'macedón'); INSERT INTO "list" ("id", "value") VALUES (E'mk_MK', E'macedón (Macedónia)'); INSERT INTO "list" ("id", "value") VALUES (E'hu', E'magyar'); INSERT INTO "list" ("id", "value") VALUES (E'hu_HU', E'magyar (Magyarország)'); INSERT INTO "list" ("id", "value") VALUES (E'ms', E'maláj'); INSERT INTO "list" ("id", "value") VALUES (E'ms_BN', E'maláj (Brunei)'); INSERT INTO "list" ("id", "value") VALUES (E'ms_Latn_BN', E'maláj (Latin, Brunei)'); INSERT INTO "list" ("id", "value") VALUES (E'ms_Latn_MY', E'maláj (Latin, Malajzia)'); INSERT INTO "list" ("id", "value") VALUES (E'ms_Latn_SG', E'maláj (Latin, Szingapúr)'); INSERT INTO "list" ("id", "value") VALUES (E'ms_Latn', E'maláj (Latin)'); INSERT INTO "list" ("id", "value") VALUES (E'ms_MY', E'maláj (Malajzia)'); INSERT INTO "list" ("id", "value") VALUES (E'ms_SG', E'maláj (Szingapúr)'); INSERT INTO "list" ("id", "value") VALUES (E'ml', E'malajálam'); INSERT INTO "list" ("id", "value") VALUES (E'ml_IN', E'malajálam (India)'); INSERT INTO "list" ("id", "value") VALUES (E'mg', E'málgas'); INSERT INTO "list" ("id", "value") VALUES (E'mg_MG', E'málgas (Madagaszkár)'); INSERT INTO "list" ("id", "value") VALUES (E'mt', E'máltai'); INSERT INTO "list" ("id", "value") VALUES (E'mt_MT', E'máltai (Málta)'); INSERT INTO "list" ("id", "value") VALUES (E'gv', E'man-szigeti'); INSERT INTO "list" ("id", "value") VALUES (E'gv_IM', E'man-szigeti (Man-sziget)'); INSERT INTO "list" ("id", "value") VALUES (E'mr', E'marathi'); INSERT INTO "list" ("id", "value") VALUES (E'mr_IN', E'marathi (India)'); INSERT INTO "list" ("id", "value") VALUES (E'mn', E'mongol'); INSERT INTO "list" ("id", "value") VALUES (E'mn_Cyrl_MN', E'mongol (Cirill, Mongólia)'); INSERT INTO "list" ("id", "value") VALUES (E'mn_Cyrl', E'mongol (Cirill)'); INSERT INTO "list" ("id", "value") VALUES (E'mn_MN', E'mongol (Mongólia)'); INSERT INTO "list" ("id", "value") VALUES (E'de', E'német'); INSERT INTO "list" ("id", "value") VALUES (E'de_AT', E'német (Ausztria)'); INSERT INTO "list" ("id", "value") VALUES (E'de_BE', E'német (Belgium)'); INSERT INTO "list" ("id", "value") VALUES (E'de_LI', E'német (Liechtenstein)'); INSERT INTO "list" ("id", "value") VALUES (E'de_LU', E'német (Luxemburg)'); INSERT INTO "list" ("id", "value") VALUES (E'de_DE', E'német (Németország)'); INSERT INTO "list" ("id", "value") VALUES (E'de_CH', E'német (Svájc)'); INSERT INTO "list" ("id", "value") VALUES (E'ne', E'nepáli'); INSERT INTO "list" ("id", "value") VALUES (E'ne_IN', E'nepáli (India)'); INSERT INTO "list" ("id", "value") VALUES (E'ne_NP', E'nepáli (Nepál)'); INSERT INTO "list" ("id", "value") VALUES (E'no', E'norvég'); INSERT INTO "list" ("id", "value") VALUES (E'no_NO', E'norvég (Norvégia)'); INSERT INTO "list" ("id", "value") VALUES (E'nb', E'norvég bokmal'); INSERT INTO "list" ("id", "value") VALUES (E'nb_NO', E'norvég bokmal (Norvégia)'); INSERT INTO "list" ("id", "value") VALUES (E'nb_SJ', E'norvég bokmal (Spitzbergák és Jan Mayen-szigetek)'); INSERT INTO "list" ("id", "value") VALUES (E'nn', E'norvég nynorsk'); INSERT INTO "list" ("id", "value") VALUES (E'nn_NO', E'norvég nynorsk (Norvégia)'); INSERT INTO "list" ("id", "value") VALUES (E'it', E'olasz'); INSERT INTO "list" ("id", "value") VALUES (E'it_IT', E'olasz (Olaszország)'); INSERT INTO "list" ("id", "value") VALUES (E'it_SM', E'olasz (San Marino)'); INSERT INTO "list" ("id", "value") VALUES (E'it_CH', E'olasz (Svájc)'); INSERT INTO "list" ("id", "value") VALUES (E'or', E'orija'); INSERT INTO "list" ("id", "value") VALUES (E'or_IN', E'orija (India)'); INSERT INTO "list" ("id", "value") VALUES (E'om', E'oromói'); INSERT INTO "list" ("id", "value") VALUES (E'om_ET', E'oromói (Etiópia)'); INSERT INTO "list" ("id", "value") VALUES (E'om_KE', E'oromói (Kenya)'); INSERT INTO "list" ("id", "value") VALUES (E'ru', E'orosz'); INSERT INTO "list" ("id", "value") VALUES (E'ru_BY', E'orosz (Fehéroroszország)'); INSERT INTO "list" ("id", "value") VALUES (E'ru_KZ', E'orosz (Kazahsztán)'); INSERT INTO "list" ("id", "value") VALUES (E'ru_KG', E'orosz (Kirgizisztán)'); INSERT INTO "list" ("id", "value") VALUES (E'ru_MD', E'orosz (Moldova)'); INSERT INTO "list" ("id", "value") VALUES (E'ru_RU', E'orosz (Oroszország)'); INSERT INTO "list" ("id", "value") VALUES (E'ru_UA', E'orosz (Ukrajna)'); INSERT INTO "list" ("id", "value") VALUES (E'os', E'oszét'); INSERT INTO "list" ("id", "value") VALUES (E'os_GE', E'oszét (Grúzia)'); INSERT INTO "list" ("id", "value") VALUES (E'os_RU', E'oszét (Oroszország)'); INSERT INTO "list" ("id", "value") VALUES (E'hy', E'örmény'); INSERT INTO "list" ("id", "value") VALUES (E'hy_AM', E'örmény (Örményország)'); INSERT INTO "list" ("id", "value") VALUES (E'pa', E'pandzsábi'); INSERT INTO "list" ("id", "value") VALUES (E'pa_Arab_PK', E'pandzsábi (Arab, Pakisztán)'); INSERT INTO "list" ("id", "value") VALUES (E'pa_Arab', E'pandzsábi (Arab)'); INSERT INTO "list" ("id", "value") VALUES (E'pa_Guru_IN', E'pandzsábi (Gurmuki, India)'); INSERT INTO "list" ("id", "value") VALUES (E'pa_Guru', E'pandzsábi (Gurmuki)'); INSERT INTO "list" ("id", "value") VALUES (E'pa_IN', E'pandzsábi (India)'); INSERT INTO "list" ("id", "value") VALUES (E'pa_PK', E'pandzsábi (Pakisztán)'); INSERT INTO "list" ("id", "value") VALUES (E'ps', E'pastu'); INSERT INTO "list" ("id", "value") VALUES (E'ps_AF', E'pastu (Afganisztán)'); INSERT INTO "list" ("id", "value") VALUES (E'fa', E'perzsa'); INSERT INTO "list" ("id", "value") VALUES (E'fa_AF', E'perzsa (Afganisztán)'); INSERT INTO "list" ("id", "value") VALUES (E'fa_IR', E'perzsa (Irán)'); INSERT INTO "list" ("id", "value") VALUES (E'pt', E'portugál'); INSERT INTO "list" ("id", "value") VALUES (E'pt_AO', E'portugál (Angola)'); INSERT INTO "list" ("id", "value") VALUES (E'pt_BR', E'portugál (Brazília)'); INSERT INTO "list" ("id", "value") VALUES (E'pt_GW', E'portugál (Guinea-Bissau)'); INSERT INTO "list" ("id", "value") VALUES (E'pt_TL', E'portugál (Kelet-Timor)'); INSERT INTO "list" ("id", "value") VALUES (E'pt_MO', E'portugál (Makaó SAR Kína)'); INSERT INTO "list" ("id", "value") VALUES (E'pt_MZ', E'portugál (Mozambik)'); INSERT INTO "list" ("id", "value") VALUES (E'pt_PT', E'portugál (Portugália)'); INSERT INTO "list" ("id", "value") VALUES (E'pt_ST', E'portugál (Sao Tomé és Príncipe)'); INSERT INTO "list" ("id", "value") VALUES (E'pt_CV', E'portugál (Zöld-foki Köztársaság)'); INSERT INTO "list" ("id", "value") VALUES (E'rm', E'réto-román'); INSERT INTO "list" ("id", "value") VALUES (E'rm_CH', E'réto-román (Svájc)'); INSERT INTO "list" ("id", "value") VALUES (E'ro', E'román'); INSERT INTO "list" ("id", "value") VALUES (E'ro_MD', E'román (Moldova)'); INSERT INTO "list" ("id", "value") VALUES (E'ro_RO', E'román (Románia)'); INSERT INTO "list" ("id", "value") VALUES (E'gd', E'skót gael'); INSERT INTO "list" ("id", "value") VALUES (E'gd_GB', E'skót gael (Egyesült Királyság)'); INSERT INTO "list" ("id", "value") VALUES (E'sn', E'sona'); INSERT INTO "list" ("id", "value") VALUES (E'sn_ZW', E'sona (Zimbabwe)'); INSERT INTO "list" ("id", "value") VALUES (E'es', E'spanyol'); INSERT INTO "list" ("id", "value") VALUES (E'es_AR', E'spanyol (Argentína)'); INSERT INTO "list" ("id", "value") VALUES (E'es_BO', E'spanyol (Bolívia)'); INSERT INTO "list" ("id", "value") VALUES (E'es_EA', E'spanyol (Ceuta és Melilla)'); INSERT INTO "list" ("id", "value") VALUES (E'es_CL', E'spanyol (Chile)'); INSERT INTO "list" ("id", "value") VALUES (E'es_CR', E'spanyol (Costa Rica)'); INSERT INTO "list" ("id", "value") VALUES (E'es_DO', E'spanyol (Dominikai Köztársaság)'); INSERT INTO "list" ("id", "value") VALUES (E'es_EC', E'spanyol (Ecuador)'); INSERT INTO "list" ("id", "value") VALUES (E'es_GQ', E'spanyol (Egyenlítői-Guinea)'); INSERT INTO "list" ("id", "value") VALUES (E'es_US', E'spanyol (Egyesült Államok)'); INSERT INTO "list" ("id", "value") VALUES (E'es_PH', E'spanyol (Fülöp-szigetek)'); INSERT INTO "list" ("id", "value") VALUES (E'es_GT', E'spanyol (Guatemala)'); INSERT INTO "list" ("id", "value") VALUES (E'es_HN', E'spanyol (Honduras)'); INSERT INTO "list" ("id", "value") VALUES (E'es_IC', E'spanyol (Kanári-szigetek)'); INSERT INTO "list" ("id", "value") VALUES (E'es_CO', E'spanyol (Kolumbia)'); INSERT INTO "list" ("id", "value") VALUES (E'es_CU', E'spanyol (Kuba)'); INSERT INTO "list" ("id", "value") VALUES (E'es_MX', E'spanyol (Mexikó)'); INSERT INTO "list" ("id", "value") VALUES (E'es_NI', E'spanyol (Nicaragua)'); INSERT INTO "list" ("id", "value") VALUES (E'es_PA', E'spanyol (Panama)'); INSERT INTO "list" ("id", "value") VALUES (E'es_PY', E'spanyol (Paraguay)'); INSERT INTO "list" ("id", "value") VALUES (E'es_PE', E'spanyol (Peru)'); INSERT INTO "list" ("id", "value") VALUES (E'es_PR', E'spanyol (Puerto Rico)'); INSERT INTO "list" ("id", "value") VALUES (E'es_SV', E'spanyol (Salvador)'); INSERT INTO "list" ("id", "value") VALUES (E'es_ES', E'spanyol (Spanyolország)'); INSERT INTO "list" ("id", "value") VALUES (E'es_UY', E'spanyol (Uruguay)'); INSERT INTO "list" ("id", "value") VALUES (E'es_VE', E'spanyol (Venezuela)'); INSERT INTO "list" ("id", "value") VALUES (E'sv', E'svéd'); INSERT INTO "list" ("id", "value") VALUES (E'sv_AX', E'svéd (Åland-szigetek)'); INSERT INTO "list" ("id", "value") VALUES (E'sv_FI', E'svéd (Finnország)'); INSERT INTO "list" ("id", "value") VALUES (E'sv_SE', E'svéd (Svédország)'); INSERT INTO "list" ("id", "value") VALUES (E'sg', E'szangó'); INSERT INTO "list" ("id", "value") VALUES (E'sg_CF', E'szangó (Közép-afrikai Köztársaság)'); INSERT INTO "list" ("id", "value") VALUES (E'ii', E'szecsuán ji'); INSERT INTO "list" ("id", "value") VALUES (E'ii_CN', E'szecsuán ji (Kína)'); INSERT INTO "list" ("id", "value") VALUES (E'sr', E'szerb'); INSERT INTO "list" ("id", "value") VALUES (E'sr_BA', E'szerb (Bosznia-Hercegovina)'); INSERT INTO "list" ("id", "value") VALUES (E'sr_Cyrl_BA', E'szerb (Cirill, Bosznia-Hercegovina)'); INSERT INTO "list" ("id", "value") VALUES (E'sr_Cyrl_XK', E'szerb (Cirill, Koszovó)'); INSERT INTO "list" ("id", "value") VALUES (E'sr_Cyrl_ME', E'szerb (Cirill, Montenegró)'); INSERT INTO "list" ("id", "value") VALUES (E'sr_Cyrl_RS', E'szerb (Cirill, Szerbia)'); INSERT INTO "list" ("id", "value") VALUES (E'sr_Cyrl', E'szerb (Cirill)'); INSERT INTO "list" ("id", "value") VALUES (E'sr_XK', E'szerb (Koszovó)'); INSERT INTO "list" ("id", "value") VALUES (E'sr_Latn_BA', E'szerb (Latin, Bosznia-Hercegovina)'); INSERT INTO "list" ("id", "value") VALUES (E'sr_Latn_XK', E'szerb (Latin, Koszovó)'); INSERT INTO "list" ("id", "value") VALUES (E'sr_Latn_ME', E'szerb (Latin, Montenegró)'); INSERT INTO "list" ("id", "value") VALUES (E'sr_Latn_RS', E'szerb (Latin, Szerbia)'); INSERT INTO "list" ("id", "value") VALUES (E'sr_Latn', E'szerb (Latin)'); INSERT INTO "list" ("id", "value") VALUES (E'sr_ME', E'szerb (Montenegró)'); INSERT INTO "list" ("id", "value") VALUES (E'sr_RS', E'szerb (Szerbia)'); INSERT INTO "list" ("id", "value") VALUES (E'sh', E'szerbhorvát'); INSERT INTO "list" ("id", "value") VALUES (E'sh_BA', E'szerbhorvát (Bosznia-Hercegovina)'); INSERT INTO "list" ("id", "value") VALUES (E'si', E'szingaléz'); INSERT INTO "list" ("id", "value") VALUES (E'si_LK', E'szingaléz (Srí Lanka)'); INSERT INTO "list" ("id", "value") VALUES (E'sk', E'szlovák'); INSERT INTO "list" ("id", "value") VALUES (E'sk_SK', E'szlovák (Szlovákia)'); INSERT INTO "list" ("id", "value") VALUES (E'sl', E'szlovén'); INSERT INTO "list" ("id", "value") VALUES (E'sl_SI', E'szlovén (Szlovénia)'); INSERT INTO "list" ("id", "value") VALUES (E'so', E'szomáliai'); INSERT INTO "list" ("id", "value") VALUES (E'so_DJ', E'szomáliai (Dzsibuti)'); INSERT INTO "list" ("id", "value") VALUES (E'so_ET', E'szomáliai (Etiópia)'); INSERT INTO "list" ("id", "value") VALUES (E'so_KE', E'szomáliai (Kenya)'); INSERT INTO "list" ("id", "value") VALUES (E'so_SO', E'szomáliai (Szomália)'); INSERT INTO "list" ("id", "value") VALUES (E'sw', E'szuahéli'); INSERT INTO "list" ("id", "value") VALUES (E'sw_KE', E'szuahéli (Kenya)'); INSERT INTO "list" ("id", "value") VALUES (E'sw_TZ', E'szuahéli (Tanzánia)'); INSERT INTO "list" ("id", "value") VALUES (E'sw_UG', E'szuahéli (Uganda)'); INSERT INTO "list" ("id", "value") VALUES (E'tl', E'tagalog'); INSERT INTO "list" ("id", "value") VALUES (E'tl_PH', E'tagalog (Fülöp-szigetek)'); INSERT INTO "list" ("id", "value") VALUES (E'ta', E'tamil'); INSERT INTO "list" ("id", "value") VALUES (E'ta_IN', E'tamil (India)'); INSERT INTO "list" ("id", "value") VALUES (E'ta_MY', E'tamil (Malajzia)'); INSERT INTO "list" ("id", "value") VALUES (E'ta_LK', E'tamil (Srí Lanka)'); INSERT INTO "list" ("id", "value") VALUES (E'ta_SG', E'tamil (Szingapúr)'); INSERT INTO "list" ("id", "value") VALUES (E'te', E'telugu'); INSERT INTO "list" ("id", "value") VALUES (E'te_IN', E'telugu (India)'); INSERT INTO "list" ("id", "value") VALUES (E'th', E'thai'); INSERT INTO "list" ("id", "value") VALUES (E'th_TH', E'thai (Thaiföld)'); INSERT INTO "list" ("id", "value") VALUES (E'bo', E'tibeti'); INSERT INTO "list" ("id", "value") VALUES (E'bo_IN', E'tibeti (India)'); INSERT INTO "list" ("id", "value") VALUES (E'bo_CN', E'tibeti (Kína)'); INSERT INTO "list" ("id", "value") VALUES (E'ti', E'tigrinja'); INSERT INTO "list" ("id", "value") VALUES (E'ti_ER', E'tigrinja (Eritrea)'); INSERT INTO "list" ("id", "value") VALUES (E'ti_ET', E'tigrinja (Etiópia)'); INSERT INTO "list" ("id", "value") VALUES (E'to', E'tonga'); INSERT INTO "list" ("id", "value") VALUES (E'to_TO', E'tonga (Tonga)'); INSERT INTO "list" ("id", "value") VALUES (E'tr', E'török'); INSERT INTO "list" ("id", "value") VALUES (E'tr_CY', E'török (Ciprus)'); INSERT INTO "list" ("id", "value") VALUES (E'tr_TR', E'török (Törökország)'); INSERT INTO "list" ("id", "value") VALUES (E'ug', E'ujgur'); INSERT INTO "list" ("id", "value") VALUES (E'ug_Arab_CN', E'ujgur (Arab, Kína)'); INSERT INTO "list" ("id", "value") VALUES (E'ug_Arab', E'ujgur (Arab)'); INSERT INTO "list" ("id", "value") VALUES (E'ug_CN', E'ujgur (Kína)'); INSERT INTO "list" ("id", "value") VALUES (E'uk', E'ukrán'); INSERT INTO "list" ("id", "value") VALUES (E'uk_UA', E'ukrán (Ukrajna)'); INSERT INTO "list" ("id", "value") VALUES (E'ur', E'urdu'); INSERT INTO "list" ("id", "value") VALUES (E'ur_IN', E'urdu (India)'); INSERT INTO "list" ("id", "value") VALUES (E'ur_PK', E'urdu (Pakisztán)'); INSERT INTO "list" ("id", "value") VALUES (E'uz', E'üzbég'); INSERT INTO "list" ("id", "value") VALUES (E'uz_AF', E'üzbég (Afganisztán)'); INSERT INTO "list" ("id", "value") VALUES (E'uz_Arab_AF', E'üzbég (Arab, Afganisztán)'); INSERT INTO "list" ("id", "value") VALUES (E'uz_Arab', E'üzbég (Arab)'); INSERT INTO "list" ("id", "value") VALUES (E'uz_Cyrl_UZ', E'üzbég (Cirill, Üzbegisztán)'); INSERT INTO "list" ("id", "value") VALUES (E'uz_Cyrl', E'üzbég (Cirill)'); INSERT INTO "list" ("id", "value") VALUES (E'uz_Latn_UZ', E'üzbég (Latin, Üzbegisztán)'); INSERT INTO "list" ("id", "value") VALUES (E'uz_Latn', E'üzbég (Latin)'); INSERT INTO "list" ("id", "value") VALUES (E'uz_UZ', E'üzbég (Üzbegisztán)'); INSERT INTO "list" ("id", "value") VALUES (E'vi', E'vietnami'); INSERT INTO "list" ("id", "value") VALUES (E'vi_VN', E'vietnami (Vietnam)'); INSERT INTO "list" ("id", "value") VALUES (E'cy', E'walesi'); INSERT INTO "list" ("id", "value") VALUES (E'cy_GB', E'walesi (Egyesült Királyság)'); INSERT INTO "list" ("id", "value") VALUES (E'zu', E'zulu'); INSERT INTO "list" ("id", "value") VALUES (E'zu_ZA', E'zulu (Dél-afrikai Köztársaság)');
Python
UTF-8
9,866
2.59375
3
[]
no_license
#!/usr/bin/python3 # Author : GMFTBY # Time : 2017.12.26 ''' 本文件是对中文的垃圾邮件分类系统,使用朴素贝叶斯算法作为分类器 对于中文的分词使用jieba等包进行相关处理 1. 忽略未登录词造成的影响 2. 邮件前缀加入消除操作 3. 标点符号过滤,特殊符号过滤 ''' import jieba import glob import numpy as np def loaddataset(): filte = [',', '.', ' ', '\n', '\t', '?', '!', '(', ')', '{', '}', '[', ']', '/', '-', '=', '+', '%', '#', '@', '~', '$', '^', '&', '*', '_', ':', ';', '\'', '"', '!', '。', ',', '(', ')', ':', '?', '¥', '@', '&', '‘', '“', ';', '{', '}', '-' ,'+', '=', '─', '》', '《', '☆', '、', '…', '\\', '|', '━', '/', 'ノ', '⌒', '〃', '⌒', 'ヽ', '”', '◇', '\u3000', '~', '╭', '╮', '〒', '失敗', '〒', '╭', '╮', 'Ω', '≡', 'ξ', '◤', 'μ', 'Θ', '◥', '█', '敗', '◤', '▎', 'υ', 'Φ', '│', '╰', '╯', '【'] postinglist = [] en_zh_filter = 'abcdefghigklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQSTUVWXYZ' # 数据集加载 classvec = [] # 加载训练集 spam = glob.glob('data/new/train/spam/*') for ii in spam: with open(ii, 'r') as f: content = [] meet = 0 for i in f.readlines(): if 'X-Mailer' in i or 'Content-Type' in i or 'X-MimeOLE' in i or 'Errors-To' in i or 'Content-Transfer-Encoding' in i or 'Message-Id' in i or 'Subject' in i: meet = 1 continue elif meet != 0: line = jieba.lcut(i, HMM=True) for p in line: if p not in filte and p.isnumeric() == False: for k in p: if k in en_zh_filter: break else: content.append(p) postinglist.append(content) classvec.append(1) ham = glob.glob('data/new/train/ham/*') for ii in ham: with open(ii, 'r') as f: content = [] meet = 0 for i in f.readlines(): if 'X-Mailer' in i or 'Content-Type' in i or 'X-MimeOLE' in i or 'Errors-To' in i or 'Content-Transfer-Encoding' in i or 'Message-Id' in i or 'Subject' in i: meet = 1 continue elif meet != 0: line = jieba.lcut(i, HMM=True) for p in line: if p not in filte and p.isnumeric() == False: for k in p: if k in en_zh_filter: break else: content.append(p) postinglist.append(content) classvec.append(0) return postinglist, classvec def createvocablist(dataset): vocabset = set([]) for i in dataset: vocabset = vocabset | set(i) return list(vocabset) def bagofwords2vec(vocablist, inputset): # 返回文档的词袋模型 returnvec = [0] * len(vocablist) for word in inputset: if word in vocablist: returnvec[vocablist.index(word)] += 1 else: print('[%s] 不在词汇特征表中,自动忽略未登录词词' % word) return returnvec def trainNB(trainndarray, traincategory): # 训练朴素贝叶斯分类器 numtraindocs = len(trainndarray) numwords = len(trainndarray[0]) pab = sum(traincategory) * 1.0 / numtraindocs # P(c) p0num = np.zeros(numwords) p1num = np.zeros(numwords) p0denom = 0.0 p1denom = 0.0 for i in range(numtraindocs): # 广播运算 if traincategory[i] == 1: p1num += trainndarray[i] p1denom += sum(trainndarray[i]) else: p0num += trainndarray[i] p0denom += sum(trainndarray[i]) p1vect = np.zeros(numwords) p0vect = np.zeros(numwords) for ind, i in enumerate(p1num): if i == 0 : p1vect[ind] = 0 else: p1vect[ind] = i * 1.0 / p1denom for ind, i in enumerate(p0num): if i == 0: p0vect[ind] = 0 else: p0vect[ind] = i * 1.0 /p0denom return p0vect, p1vect, pab def classify(vec2classify, p0vect, p1vect, pclass1): # 朴素贝叶斯分类器 p1 = sum(vec2classify * p1vect) + np.log(pclass1) p0 = sum(vec2classify * p0vect) + np.log(1 - pclass1) if p1 > p0: # 分类为垃圾邮件 return 1 else: # 分类为正常邮件 return 0 def train_error_count(): # 检测训练集错误率,正确率 data, label = loaddataset() vocablist = createvocablist(data) sum_count = len(data) error_count = 0 right_count = 0 zhaohui_count = 0 trainndarray = [] for ind, i in enumerate(data): trainndarray.append(bagofwords2vec(vocablist, i)) print('训练集加载 :', ind / sum_count, end = '\r') p0v, p1v, pab = trainNB(np.array(trainndarray), np.array(label)) for ind, i in enumerate(data): thisdoc = np.array(bagofwords2vec(vocablist, i)) ans = classify(thisdoc, p0v, p1v, pab) if ans == 0 and label[ind] == 0 : right_count += 1 if ans == 1 and label[ind] == 1 : zhaohui_count += 1 print('训练集测试 :', ind / sum_count, end='\r') return right_count * 1.0 / (len(data) / 2), zhaohui_count * 1.0 / (len(data) / 2) def loaddatatest(): # 加载测试集 filte = [',', '.', ' ', '\n', '\t', '?', '!', '(', ')', '{', '}', '[', ']', '/', '-', '=', '+', '%', '#', '@', '~', '$', '^', '&', '*', '_', ':', ';', '\'', '"', '!', '。', ',', '(', ')', ':', '?', '¥', '@', '&', '‘', '“', ';', '{', '}', '-' ,'+', '=', '─', '》', '《', '☆', '、', '…', '\\', '|', '━', '/', 'ノ', '⌒', '〃', '⌒', 'ヽ', '”', '◇', '\u3000', '~', '╭', '╮', '〒', '失敗', '〒', '╭', '╮', 'Ω', '≡', 'ξ', '◤', 'μ', 'Θ', '◥', '█', '敗', '◤', '▎', 'υ', 'Φ', '│', '╰', '╯', '【'] postinglist = [] en_zh_filter = 'abcdefghigklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQSTUVWXYZ' tests = glob.glob('data/new/test/*') tests.sort() for ii in tests: with open(ii, 'r') as f: content = [] meet = 0 for i in f.readlines(): if 'X-Mailer' in i or 'Content-Type' in i or 'X-MimeOLE' in i or 'Errors-To' in i or 'Content-Transfer-Encoding' in i or 'Message-Id' in i or 'Subject' in i: meet = 1 continue elif meet != 0: line = jieba.lcut(i, HMM=True) for p in line: if p not in filte and p.isnumeric() == False: for k in p: if k in en_zh_filter: break else: content.append(p) postinglist.append(content) label = [] with open('test_label', 'r') as f: for i in f.readlines(): if 'spam' in i : label.append(1) else : label.append(0) return postinglist, label def test_error_count(): # 检测测试集错误率 data, label = loaddataset() vocablist = createvocablist(data) testdata, testlabel = loaddatatest() sum_count = len(testdata) error_count = 0 right_count = 0 zhaohui_count = 0 trainndarray = [] lenp = len(data) for ind, i in enumerate(data): trainndarray.append(bagofwords2vec(vocablist, i)) print('测试集加载 :', ind / lenp, end = '\r') p0v, p1v, pab = trainNB(np.array(trainndarray), np.array(label)) for ind, i in enumerate(testdata): thisdoc = np.array(bagofwords2vec(vocablist, i)) ans = classify(thisdoc, p0v, p1v, pab) if ans == 0 and testlabel[ind] == 0 : right_count += 1 if ans == 1 and testlabel[ind] == 1 : zhaohui_count += 1 print('测试集测试 :', ind / sum_count, end= '\r') if ind == 10 : break return right_count * 1.0 / (sum_count / 2), zhaohui_count * 1.0 / (sum_count / 2) def save_model(p0v, p1v, pab): # 模型序列化 with open('model', 'w') as f: f.write(str(p0v) + '\n') f.write(str(p1v) + '\n') f.write(str(pab) + '\n') def load_model(): with open('model', 'r') as f: p0v = float(f.readline()) p1v = float(f.readline()) pab = float(f.readline()) print(p0v, p1v, pab) return p0v, p1v, pab if __name__ == "__main__": ''' data, label = loaddataset() vocablist = createvocablist(data) a = ['我','真','的','是','非常','抱歉','啊','我'] trainndarray = [] length = len(data) for ind, i in enumerate(data): trainndarray.append(bagofwords2vec(vocablist, i)) print('训练集加载 :', ind / length, end='\r') p0v, p1v, pab = trainNB(np.array(trainndarray), np.array(label)) thisdoc = np.array(bagofwords2vec(vocablist, a)) ans = classify(thisdoc, p0v, p1v, pab) if ans == 0: ans = '正常邮件' else : ans = '垃圾邮件' print('朴素贝叶斯分类器归类邮件为 :', ans) ''' print() ans2, ans3 = train_error_count() print('训练集正确率,召回率 :', ans2, ans3)
Ruby
UTF-8
1,255
3.265625
3
[]
no_license
require_relative './model/parse' def display(accounts) sorted_accounts = Hash[accounts.sort] puts '**********' puts sorted_accounts.each_value do |card| if card.card_num puts "#{card.name}: $#{card.balance}" else puts "#{card.name}: error" end end puts puts '**********' end puts "Enter file name" file = gets.chomp customer_accounts = {} File.open(file).each_line do |line| line.strip! line.downcase! parser = Parser.new(line) case parser.command when 'add' raise ArgumentError.new('Invalid inputs') unless parser.command && parser.name && parser.limit card_num = parser.card_num validator = LuhnValidator.new(card_num) if validator.luhn_check card = Card.new(name: parser.name, card_num: parser.card_num, limit: parser.limit) customer_accounts[card.name] = card else # if it fails luhn, card_num is not assigned (nil) card = Card.new(name: parser.name) customer_accounts[card.name] = card end when 'charge' card = customer_accounts[parser.name] card.charge(parser.amount) if card.card_num when 'credit' card = customer_accounts[parser.name] card.credit(parser.amount) if card.card_num end end display(customer_accounts)
C#
UTF-8
11,498
2.515625
3
[]
no_license
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.Data.SqlClient; using System.IO; using System.Text.RegularExpressions; namespace Transport_mgmt { public partial class Update__Employees : Form { public Update__Employees() { InitializeComponent(); } SqlConnection con = new SqlConnection(@"Data Source=SANKET\SANKET;Initial Catalog=Transport_Mgmt_System;Integrated Security=True;Pooling=False"); private void Edit__Employees_Load(object sender, EventArgs e) { // TODO: This line of code loads data into the 'transport_Mgmt_SystemDataSet3.Employees' table. You can move, or remove it, as needed. this.employeesTableAdapter.Fill(this.transport_Mgmt_SystemDataSet3.Employees); con.Open(); SqlCommand sc = new SqlCommand("SELECT Emp_ID FROM Employees", con); SqlDataReader dr = sc.ExecuteReader(); while (dr.Read()) { Emp_ID.Items.Add(dr[0]); } con.Close(); } private void SEARCH_Click(object sender, EventArgs e) { if (Status.Text == "" || Emp_ID.Text == "") { MessageBox.Show("PLZ_FILL_THE_RECOMMENDED_DATA___!!"); } else { con.Open(); SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM Employees WHERE Status='" + Status.Text + "' and Emp_ID='" + Emp_ID.Text + "'", con); DataTable dt = new DataTable(); sda.Fill(dt); F_Name.Text = dt.Rows[0][2].ToString(); M_Name.Text = dt.Rows[0][3].ToString(); L_Name.Text = dt.Rows[0][4].ToString(); DOB.Text = dt.Rows[0][5].ToString(); Gender.Text = dt.Rows[0][6].ToString(); Religion.Text = dt.Rows[0][7].ToString(); BG.Text = dt.Rows[0][8].ToString(); A_No.Text = dt.Rows[0][9].ToString(); DLC.Text = dt.Rows[0][10].ToString(); P_No.Text = dt.Rows[0][11].ToString(); Present_Add.Text = dt.Rows[0][12].ToString(); State.Text = dt.Rows[0][13].ToString(); District.Text = dt.Rows[0][14].ToString(); City.Text = dt.Rows[0][15].ToString(); Pincode.Text = dt.Rows[0][16].ToString(); Phone_No.Text = dt.Rows[0][17].ToString(); Mob_No.Text = dt.Rows[0][18].ToString(); E_ID.Text = dt.Rows[0][19].ToString(); A_E_ID.Text = dt.Rows[0][20].ToString(); Entry_Date.Text = dt.Rows[0][21].ToString(); byte[] mydata = new byte[0]; mydata = (byte[])dt.Rows[0][22]; MemoryStream ms = new MemoryStream(mydata); pictureBox1.Image = Image.FromStream(ms); con.Close(); MessageBox.Show("SEARCH_SUCCESSFULLY!!"); } } private void UPDATE_Click(object sender, EventArgs e) { if (Present_Add.Text == "" || State.Text == "" || District.Text == "" || City.Text == "" || Pincode.Text == "" || Phone_No.Text == "" || Mob_No.Text == "" || E_ID.Text == "" || A_E_ID.Text == ""||Status.Text==""||Emp_ID.Text==""||Gender.Text=="") { MessageBox.Show("PLZ_FILL_UP_ALL_DATA__!!"); } else { con.Open(); SqlDataAdapter sda = new SqlDataAdapter("UPDATE Employees SET Present_Address='" + Present_Add.Text + "',State='" + State.Text + "',District='" + District.Text + "',City='" + City.Text + "',Pincode='" + Pincode.Text + "',Phone_No='" + Phone_No.Text + "',Mobile_No='" + Mob_No.Text + "',Email_ID='" + E_ID.Text + "',Alternative_Email_ID='" + A_E_ID.Text + "' WHERE Status='" + Status.Text + "' and Emp_ID='" + Emp_ID.Text + "'", con); sda.SelectCommand.ExecuteNonQuery(); con.Close(); Status.Text = ""; Emp_ID.Text = ""; F_Name.Text = ""; M_Name.Text = ""; L_Name.Text = ""; DOB.Text = ""; Gender.Text = ""; Religion.Text = ""; BG.Text = ""; A_No.Text = ""; DLC.Text = ""; P_No.Text = ""; Present_Add.Text = ""; State.Text = ""; District.Text = ""; City.Text = ""; Pincode.Text = ""; Phone_No.Text = ""; Mob_No.Text = ""; E_ID.Text = ""; A_E_ID.Text = ""; Entry_Date.Text = ""; Status.Focus(); MessageBox.Show("UPDATED SUCCESSFULLY!!!"); } } private void CLEAR_Click(object sender, EventArgs e) { Status.Text = ""; Emp_ID.Text = ""; F_Name.Text = ""; M_Name.Text = ""; L_Name.Text = ""; DOB.Text = ""; Gender.Text = ""; Religion.Text = ""; BG.Text = ""; A_No.Text = ""; DLC.Text = ""; P_No.Text = ""; Present_Add.Text = ""; State.Text = ""; District.Text = ""; City.Text = ""; Pincode.Text = ""; Phone_No.Text = ""; Mob_No.Text = ""; E_ID.Text = ""; A_E_ID.Text = ""; Entry_Date.Text = ""; Status.Focus(); MessageBox.Show("ALL_CLEARED___"); } private void CANCEL_Click(object sender, EventArgs e) { this.Close(); } private void CHOOSE_PATH_Click(object sender, EventArgs e) { } private void panel3_Paint(object sender, PaintEventArgs e) { } private void panel5_Paint(object sender, PaintEventArgs e) { } private void Present_Add_KeyPress(object sender, KeyPressEventArgs e) { if (e.Handled = !(char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back || e.KeyChar == (char)Keys.Space)) { if (e.KeyChar != (char)96) { MessageBox.Show("This_entry_can_contain_only_alphabets__!!!"); } } } private void State_KeyPress(object sender, KeyPressEventArgs e) { if (e.Handled = !(char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back || e.KeyChar == (char)Keys.Space)) { if (e.KeyChar != (char)96) { MessageBox.Show("This_entry_can_contain_only_alphabets__!!!"); } } } private void District_KeyPress(object sender, KeyPressEventArgs e) { if (e.Handled = !(char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back || e.KeyChar == (char)Keys.Space)) { if (e.KeyChar != (char)96) { MessageBox.Show("This_entry_can_contain_only_alphabets__!!!"); } } } private void City_KeyPress(object sender, KeyPressEventArgs e) { if (e.Handled = !(char.IsLetter(e.KeyChar) || e.KeyChar == (char)Keys.Back || e.KeyChar == (char)Keys.Space)) { if (e.KeyChar != (char)96) { MessageBox.Show("This_entry_can_contain_only_alphabets__!!!"); } } } private void Pincode_KeyPress(object sender, KeyPressEventArgs e) { Pincode.MaxLength = 6; if (Pincode.TextLength == 6) { //MessageBox.Show("Maximum Length is 6 number only"); } if (/*e.KeyChar < '0' ||*/ e.KeyChar > '9') { MessageBox.Show("This Entry can only contain numbers"); e.KeyChar = (char)0; } } private void Pincode_Leave(object sender, EventArgs e) { if (Pincode.TextLength < 6) { MessageBox.Show("PLEASE_FILL_UP_CORRECTLY__!!"); } } private void Phone_No_KeyPress(object sender, KeyPressEventArgs e) { Phone_No.MaxLength = 10; if (Phone_No.TextLength == 10) { //MessageBox.Show("Maximum Length is 10 number only"); } if (/*e.KeyChar < '0' ||*/ e.KeyChar > '9') { MessageBox.Show("This Entry can only contain numbers"); e.KeyChar = (char)0; } } private void Phone_No_Leave(object sender, EventArgs e) { if (Phone_No.TextLength < 10) { MessageBox.Show("PLEASE_FILL_UP_CORRECTLY__!!"); } } private void Mob_No_KeyPress(object sender, KeyPressEventArgs e) { Mob_No.MaxLength = 10; if (Mob_No.TextLength == 10) { //MessageBox.Show("Maximum Length is 10 number only"); } if (/*e.KeyChar < '0' ||*/ e.KeyChar > '9') { MessageBox.Show("This Entry can only contain numbers"); e.KeyChar = (char)0; } } private void Mob_No_Leave(object sender, EventArgs e) { if (Mob_No.TextLength < 10) { MessageBox.Show("PLEASE_FILL_UP_CORRECTLY__!!"); } } private void E_ID_Leave(object sender, EventArgs e) { if (!string.IsNullOrWhiteSpace(E_ID.Text)) { Regex reg1 = new Regex(@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"); if (!reg1.IsMatch(E_ID.Text)) { MessageBox.Show("EMAIL_IS_NOT_VALID__!!"); } } } private void A_E_ID_Leave(object sender, EventArgs e) { if (!string.IsNullOrWhiteSpace(E_ID.Text)) { Regex reg1 = new Regex(@"\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*"); if (!reg1.IsMatch(E_ID.Text)) { MessageBox.Show("EMAIL_IS_NOT_VALID__!!"); } } } private void refresh_Click(object sender, EventArgs e) { con.Open(); SqlDataAdapter sda = new SqlDataAdapter("SELECT * FROM Employees", con); DataTable dt = new DataTable(); sda.Fill(dt); dataGridView1.DataSource = dt; con.Close(); } } }
JavaScript
UTF-8
1,344
2.546875
3
[ "MIT" ]
permissive
"use strict" // Lib const PartyClass = require('../lib/party/'); const PokedexClass = require('../lib/pokedex'); const Pokedex = new PokedexClass(); module.exports = { index : (req, res) => { var partyID = req.params.partyId; if(!PartyClass.Object.hasOwnProperty(partyID)) return res.redirect("/"); var party = PartyClass.Object[partyID]; Pokedex.Generation(party.generation.id, (error, pokedex) => { if(error) return res.redirect("/"); return res.render('party/index', { title: "Party", party: party, pokedex: pokedex }); }); }, update : (data, callback) => { if(!PartyClass.Object.hasOwnProperty(data.ID)) return callback(true); var party = PartyClass.Object[data.ID]; party.Set(data.slots); return callback(false, party); }, show : (req, res) => { var partyID = req.params.partyId; if(!PartyClass.Object.hasOwnProperty(partyID)) return res.redirect("/"); var party = PartyClass.Object[partyID]; return res.render('party/show', { party: party }); }, delete : (req, res) => { var partyID = req.params.partyId; if(!PartyClass.Object.hasOwnProperty(partyID)) return res.redirect("/"); var party = PartyClass.Object[partyID]; party.Remove(); return res.redirect("/"); } }
Java
UTF-8
733
2.125
2
[]
no_license
package com.luidmyla.zahumna.tea.catalog.dao; import com.luidmyla.zahumna.tea.catalog.service.TeaCatalogService; import java.util.HashSet; /** * DAO * * @author lzahumna * since 20/05/2018. */ public interface TeaDAO { enum Condition { MIN, MAX, LENGTH } HashSet<String> getTeaTypesByCountry(String country); String getPopularTeaByCountry(String country, Condition condition); String getFamousTeaInWorldByCondition(Condition condition); Double getNumberOfPeopleEnjoyTea(String teaType); String getCountryWithUniqueTeaByCondition(Condition condition); Integer countUniqueTeaTypes(); Double getNumberOfPeopleByTeaAndCountry(String teaType, String country); }
Python
UTF-8
4,168
3.125
3
[]
no_license
def _get_owner_from_details(details, default=None): result = default if details.get('owner_slackid') is not None: return '<@{}>'.format(details.get('owner_slackid')) elif details.get('owner_name') is not None: return details.get('owner_name') return result command_car_usage = 'Lookup car details including the owner (if known):\n' \ '`AA-12-BB` _(dashes are optional)_\n' \ '`tag AA-12-BB` _(register your car)_\n' \ '`tag AA-12-BB @slackid` _(register someone else)_\n' \ '`tag AA-12-BB "Jack Sparrow"` _(register someone on name)_\n' \ '`untag AA-12-BB` _(remove this entry)_\n' \ command_tag_usage = 'Register or unregister the owner of a car:\n' \ ' `tag AA-12-BB` _(you are the owner)_\n' \ ' `tag AA-12-BB @thatguy` _(or someone else with a slack handle)_\n' \ ' `tag AA-12-BB "The great pirate"` _(or a quoted string defining the owner)_\n' \ ' `untag AA-12-BB` _(removes this car)_' def command_invalid_owner(owner): return 'Invalid owner "{}" _(must be double-quoted, between 3 - 32 chars and normal text chars)_'.format(owner) def command_invalid_usage(nr_arguments): return 'Invalid nr of arguments. Expects at most 3, given {}.\nUsage:\n{}'.format( nr_arguments, command_car_usage) def command_invalid_licence_plate(text): return 'Input ({}) does not look like a valid licence plate (NL-patterns)'.format(text) def command_tag_added(plate, user_id=None, owner=None): if owner: return 'Added {} to "{}"'.format(plate, owner) else: return 'Added {} to <{}>'.format(plate, user_id) def command_untag(plate): return 'Removed the licence plate {}'.format(plate) lookup_no_details_found = 'No details found...' def lookup_found_with_details(plate, details): car_type = details.get('handelsbenaming') or '-' car_brand = details.get('merk') or '-' owner = _get_owner_from_details(details) or '- _(Use `/car tag` to add the owner)_' apk = details.get('vervaldatum_apk') or '-' price = details.get('catalogusprijs') or '-' if isinstance(price, int): price = '€ {:,d}'.format(price).replace(',', '.') return '''Lookup of {plate}: *{car_type}* of brand *{car_brand}* • Owner: {owner} • Price: {price} • APK expires: {apk}'''.format(plate=plate, car_type=car_type, car_brand=car_brand, owner=owner, price=price, apk=apk) comment_no_plate_found = "No plates were found. Try `/car [license plate]` " \ "if _you_ can OCR a license plate from that image." def comment_found_with_details(plate, confidence, details): car_type = details.get('handelsbenaming') or '-' car_brand = details.get('merk') or '-' owner = _get_owner_from_details(details) or '- _(Use `/car tag` to add the owner)_' apk = details.get('vervaldatum_apk') or '-' price = details.get('catalogusprijs') or '-' if isinstance(price, int): price = '€ {:,d}'.format(price).replace(',', '.') return ''':mega: Found *{plate}*, it's a *{car_type}* of brand *{car_brand}*! _(confidence {confidence:.2f})_ • Owner: {owner} • Price: {price} • APK expires: {apk}'''.format(plate=plate, confidence=confidence, car_type=car_type, owner=owner, car_brand=car_brand, price=price, apk=apk) def comment_found_no_details(plate, confidence): return 'I found *{plate}* _(confidence {confidence:.2f})_, but no extra info associated with it...'.format( plate=plate, confidence=confidence) def comment_found_but_skipping(plate, confidence, threshold, is_valid): if not is_valid: return "Skipping licence plate '{plate}', it's NOT a valid NL pattern _(confidence {confidence:.2f})_".format( plate=plate, confidence=confidence) return "Skipping licence plate '{plate}', too low confidence ({confidence:.2f} < {threshold:.2f})".format( plate=plate, confidence=confidence, threshold=threshold)
Java
UTF-8
106
2.328125
2
[]
no_license
package com.learning.design.patterns.structural.composite; public interface IElement { void print(); }
C#
UTF-8
5,153
2.640625
3
[ "MIT" ]
permissive
using CurrieTechnologies.Razor.SweetAlert2; using Marketplace.Client.Models; using Marketplace.Shared; using Microsoft.AspNetCore.Components; using Microsoft.AspNetCore.Components.Authorization; using Microsoft.JSInterop; using System; using System.Net; using System.Net.Http; using System.Threading.Tasks; namespace Marketplace.Client.Services { public class OrderState { private HttpClient HttpClient { get; set; } private IJSRuntime JsRuntime { get; set; } private AuthenticationStateProvider AuthenticationStateProvider { get; set; } private SweetAlertService Swal { get; set; } public OrderState(HttpClient httpClient, IJSRuntime jsRuntime, AuthenticationStateProvider authenticationStateProvider, SweetAlertService swal) { HttpClient = httpClient; JsRuntime = jsRuntime; AuthenticationStateProvider = authenticationStateProvider; Swal = swal; } public MarketItem InfoItem { get; set; } public async Task ShowInfoModalAsync(MarketItem marketItem) { InfoItem = marketItem; await JsRuntime.InvokeVoidAsync("ToggleModal", "infoModal"); } public async Task CloseInfoModalAsync() { await JsRuntime.InvokeVoidAsync("ToggleModal", "infoModal"); InfoItem = null; } public async Task BuyMarketItemAsync(MarketItem marketItem, Action<MarketItem> onSuccessfullBuy = null) { if (!(await AuthenticationStateProvider.GetAuthenticationStateAsync()).User.Identity.IsAuthenticated) { await Swal.FireAsync("Unauthorized", $"You have to sign in to be able to buy!", SweetAlertIcon.Error); return; } var response = await HttpClient.PostAsync($"api/marketitems/{marketItem.Id}/buy", null); switch (response.StatusCode) { case HttpStatusCode.NotFound: await Swal.FireAsync("Not Found", "The item you were trying to buy could not be found", SweetAlertIcon.Error); break; case HttpStatusCode.Unauthorized: await Swal.FireAsync("Unauthorized", "You are the seller of this item", SweetAlertIcon.Error); break; case HttpStatusCode.NoContent: await Swal.FireAsync("No Content", "The item you are trying to buy was already sold", SweetAlertIcon.Error); break; case HttpStatusCode.BadRequest: await Swal.FireAsync("Bad Request", "You cannot afford buying this item", SweetAlertIcon.Error); break; case HttpStatusCode.Conflict: await Swal.FireAsync("Conflict", "You have already reached the maximum number of active shoppings", SweetAlertIcon.Error); break; } if (response.StatusCode == HttpStatusCode.OK) { if (onSuccessfullBuy != null) { onSuccessfullBuy.Invoke(marketItem); } await Swal.FireAsync("OK", $"You successfully bought {marketItem.ItemName}({marketItem.ItemId}) for ${marketItem.Price}!", SweetAlertIcon.Success); } await CloseInfoModalAsync(); } public async Task ChangePrice(MarketItem item) { await Swal.FireAsync(new SweetAlertOptions { Title = $"Change Price", Text = $"Input new price for listing {item.Id} [{item.ItemName}]", Icon = SweetAlertIcon.Warning, Input = SweetAlertInputType.Number, //InputPlaceholder = item.Price.ToString(), ShowCancelButton = true, ConfirmButtonText = "Submit", ShowLoaderOnConfirm = true, }).ContinueWith(async (swalTask) => { var result = swalTask.Result; if (!string.IsNullOrEmpty(result.Value) && decimal.TryParse(result.Value, out decimal price)) { var msg = new HttpRequestMessage(new HttpMethod("PATCH"), $"api/marketitems/{item.Id}"); msg.Content = new StringContent(price.ToString()); var response = await HttpClient.SendAsync(msg); item.Price = price; await Swal.FireAsync("Success", $"Successfully changed the price of listing {item.Id} [{item.ItemName}] to {price}!", SweetAlertIcon.Success); } else { await Swal.FireAsync("Cancel", $"Changing price for listing {item.Id} canceled.", SweetAlertIcon.Error); } }); } public async Task ShowClaim(MarketItem item) { await Swal.FireAsync("Claim Information", $"To claim your {item.ItemName}, use in-game: <code>/claim {item.Id}</code>", SweetAlertIcon.Info); } } }
C#
UTF-8
5,891
2.96875
3
[]
no_license
using System; using System.Text.RegularExpressions; using FileParser.Properties; using FileParser.Exceptions; namespace FileParser { /// <summary> /// This class helps to provent errors. /// </summary> public static class FPHelper { /// <summary> /// The max length of Windows 2000 is 254 /// </summary> public const int MaxFileLenght_Windows2000 = 254; /// <summary> /// The max length of Windows Xp is 255 /// </summary> public const int MaxFileLenght_WindowsXP = 255; /// <summary> /// The max length of Windows Vista is 260 /// </summary> public const int MaxFileLenght_WindowsVista = 260; /// <summary> /// The max length of Windows 7 is 260 /// </summary> public const int MaxFileLength_Windows7 = 260; /// <summary> /// This regex contain all legal caracters. /// </summary> public static readonly Regex LegalCharacter = new Regex(@"[\w\$#&\+@!\(\)\{\}\.'`~, ]*"); /// <summary> /// Look for invalid file name characters and check the length with 255. /// </summary> /// <param name="path">This string get tested.</param> /// <returns>true if everything is ok, false if not.</returns> public static bool IsPathValid(string path) { return path.Length <= 255 && LegalCharacter.IsMatch(path); } /// <summary> /// Look for invalid file name characters in the parameter string. /// </summary> /// <param name="path">This string get tested.</param> /// <param name="ex">return an <see cref="FPException"/> object that can be thrown.</param> /// <returns>true if everything is ok, false if not.</returns> public static bool IsPathValid(string path, out FPException ex) { int length = 255; if (path.Length > length) { ex = new FPPathLengthException(String.Format(Resources.helperPathLenght, length.ToString(), path) + "\n" + Resources.exceptionMoreInformation, DiagnosticEvents.HelperErrorPathLength); ex.Data.Add("path", path); ex.Data.Add("maxLength", length); return false; } else ex = null; return LegalCharacter.IsMatch(path); } /// <summary> /// Look if extension is valid. /// </summary> /// <param name="extension">Not null, only letters and at least 3 characters.</param> /// <returns>true if extension is valid, else false</returns> public static bool IsExtentionValid(string extension) { return String.IsNullOrEmpty(extension) && Regex.IsMatch(extension, @"[\w]") && extension.Length >= 3 && extension.Length > 5; } /// <summary> /// Look if extension is valid. /// </summary> /// <param name="extension">Not null, only letters, minimum 3 characters and not more than 5.</param> /// <param name="ex">return an <see cref="FPException"/> object that can be thrown.</param> /// <returns>true if extension is valid, else false</returns> public static bool IsExtentionValid(string extension, out FPException ex) { string pattern = @"[\w]"; int minLength = 3; int maxLength = 5; if (String.IsNullOrEmpty(extension)) { if (Regex.IsMatch(extension, pattern)) { if (extension.Length < minLength) { ex = new FPExtensionException(String.Format(Resources.ErrorHelperLengthShort, minLength) + "\n" + Resources.exceptionMoreInformation, DiagnosticEvents.HelperErrorExtensionTooShort); ex.Data.Add("extension", extension); ex.Data.Add("minLength", minLength); } else { if (extension.Length > maxLength) { ex = new FPExtensionException(String.Format(Resources.ErrorHelperLengthLong, maxLength) + "\n" + Resources.exceptionMoreInformation, DiagnosticEvents.HelperErrorExtensionTooLong); ex.Data.Add("extension", extension); ex.Data.Add("maxLength", maxLength); } else { ex = null; return true; } } } else { ex = new FPExtensionException(Resources.ErrorHelperLetter + "\n" + Resources.exceptionMoreInformation, DiagnosticEvents.HelperErrorExtensionNonLetterCharacters); ex.Data.Add("regex", pattern); } } else ex = new FPExtensionException(Resources.ErrorHelperNull, DiagnosticEvents.HelperErrorExtensionNull); return false; } /// <summary> /// This method can be used to set the extensions for the parser. /// It returns the extension if everything is ok, otherwise it throw an excetion and notify the observer. /// </summary> /// <param name="extension">this string get checked</param> /// <returns>Returns the <paramref name="extension"/> if it is valid.</returns> public static string SetExtenstionManager(string extension) { FPException ex; if (IsExtentionValid(extension, out ex)) { return extension; } else { throw ex; } } } }
JavaScript
UTF-8
639
2.65625
3
[]
no_license
import { handleActions } from 'redux-actions'; const initialState = []; for(let i=1;i<10;i++){ initialState.push({ text: 'Testing on React Redux architecture', completed: false, id: i }) } export default handleActions({ 'add todo'(state, action) { return [ { id: state.reduce((maxId, todo) => Math.max(todo.id, maxId), -1) + 1, completed: false, text: action.payload }, ...state ] }, 'clear complete'(state, action) { return state.filter(todo => todo.completed === false) } }, initialState)
TypeScript
UTF-8
1,080
2.6875
3
[]
no_license
import { TestScheduler } from 'rxjs/testing'; import { interval } from 'rxjs'; import { reduce, scan, take } from 'rxjs/operators'; describe('src/book/dissecting-rxjs/08/06/01/01.ts', () => { let scheduler: TestScheduler; beforeEach(() => { scheduler = new TestScheduler((actual, expected) => { expect(actual).toEqual(expected); }); }); // scan() 类似 reduce(), 用来对数据进行规约, // 区别在于: // reduce() 会对所有的数据进行规约, 最终吐出一个结果数据, // scan() 会在上游每吐出一个数据就进行一次规约, 并把规约结果吐出 it('should work', () => { scheduler.run(({ expectObservable }) => { const source$ = interval(500).pipe(take(5)); expectObservable(source$.pipe(reduce((acc, value) => acc + value, 0))).toBe('2500ms (a|)', { a: 10 }); expectObservable(source$.pipe(scan((acc, value) => acc + value, 0))).toBe('500ms a 499ms b 499ms c 499ms d 499ms (e|)', { a: 0, b: 1, c: 3, d: 6, e: 10, }); }); }); });
C#
UTF-8
557
2.734375
3
[]
no_license
using System.Collections; using System.Collections.Generic; using UnityEngine; public class StaticVariables : MonoBehaviour { public static int faith = 30; public static ChoicesClass lastChoice = null; public static List<ChoicesClass> current = null; public int changeFaith(int change){ faith += change; return faith; } //public int getFaith(){ // return faith; //} public ChoicesClass getLastChoice(){ return lastChoice; //or return an error saying it is null } public void setLastChoice(ChoicesClass a){ lastChoice = a; } }
Python
UTF-8
802
3.28125
3
[]
no_license
#!/usr/local/bin/python # #19 counting sundays import getopt, sys # start with december since we are interested in the first day of the month normal = [31, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30] leap = [31, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30] def main(): day = -30 # 2 Dec 1899 count = 0 for i in range(101): if (i % 4 == 0 and i % 100 != 0): calendar = leap #print "{}: leap".format(i) else: calendar = normal #print "{}: normal".format(i) for j in range (len(calendar)): day = day + calendar[j] if day % 7 == 0 and i != 0: # Skip 1900 #print "{}: {}".format(i, j) count = count + 1 print count if __name__ == "__main__": main()
Python
UTF-8
829
2.921875
3
[]
no_license
#!/usr/bin/env python3 import requests from time import sleep import Adafruit_DHT as dht import random url = "https://api.thingspeak.com/update.json" api_key = "PGDU2UY4RHZ06G3D" def get_data(): return dht.read_retry(dht.DHT11, 23) # return random.randrange(20, 30), random.randrange(20, 30) def send_data(url, data): return requests.post(url, data) if __name__ == "__main__": while True: try: humidity, temperature = get_data() print(f"Humidity: {humidity}\nTemperature: {temperature}") data = {"api_key": api_key, "field1": humidity, "field2": temperature} response = send_data(url, data) print(response) print(response.text) sleep(15) except KeyboardInterrupt: print("OK, exiting!") break
C
UTF-8
5,228
2.953125
3
[ "MIT" ]
permissive
#include <stdio.h> #include "zdssKeys.h" #include "zdssMessages.h" #include "hecdssInternal.h" /** * Function: zgetFileSpace * * Use: Private (Internal) * * Description: Whenever new file space is needed (the file is lengthened), this function is called * to get it or add to the end of the file. Space might include reclaimed space. * For example, if a new write request for space (at end of file), this will create it * and return the address to that space. * * Declaration: long long zgetFileSpace(long long *ifltab, int sizeNeeded, int boolReclaimedOK, int *atEOF); * * Parameters: long long ifltab * An integer array dimensioned to int*8 [250] that contains file specific information. * This should be considered as a "handle" array and must be passed to any function that accesses that file. * * int sizeNeeded * The total space needed, in int*8 words. * * int boolReclaimedOK * A boolean flag indicating if it is okay to use reclaimed space or not (0 = do not use, 1 = okay to use.) * Generally, reclaimed space is not used for address tables and similar. * * int *atEOF * A boolean return parameter indicating if the space is at the end of the file (by extending the file size.) * If so, generally an EOF flag is written after the space, indicating the end of file. * * Returns: long long address * The address of the space to use. * * Remarks: No error or error code is returned. If reclaimed space is not available, then space from the end of * the file is given. If the file cannot be extended, or written to, or some other error, this routine * will not report it. It will show up during a write operation (not here!) * * * * Author: Bill Charley * Date: 2013 * Organization: US Army Corps of Engineers, Hydrologic Engineering Center (USACE HEC) * All Rights Reserved * **/ long long zgetFileSpace(long long *ifltab, int sizeNeeded, int boolReclaimedOK, int *atEOF) { char messageString[80]; long long address; long long add; long long *reclaimArray; long long *fileHeader; int iarrayNumber; int sizeHave; int i; int loc; int ipos; int diff; address = 0; // If we don't have any reclaimed space available, just get it from EOF if (ifltab[zdssKeys.kreclaimLevel] <= 1) { boolReclaimedOK = 0; } fileHeader = (long long *)ifltab[zdssKeys.kfileHeader]; sizeHave = 0; if ((boolReclaimedOK) && (fileHeader[zdssFileKeys.kreclaimSize] > 0) && (sizeNeeded >= fileHeader[zdssFileKeys.kreclaimMin]) && (sizeNeeded <= fileHeader[zdssFileKeys.kreclaimMaxAvailable])) { iarrayNumber = 0; while (reclaimArray = zreclaimRead(ifltab, &iarrayNumber, 0)) { // Walk down reclaimed space array, looking for smallest space // that is equal or larger than what we need // We want the smallest space so that larger chunks can be used // with larger needs. for (i=0; i<(int)fileHeader[zdssFileKeys.kreclaimNumber]; i++) { ipos = numberIntsInLongs(i); if (reclaimArray[ipos] >= sizeNeeded) { if ((sizeHave == 0) || (reclaimArray[ipos] < sizeHave)) { sizeHave = (int)reclaimArray[ipos]; loc = i; if (sizeHave == sizeNeeded) { break; } } } } if (sizeHave > 0) { ipos = numberIntsInLongs(loc); address = reclaimArray[ipos+1]; diff = sizeHave - sizeNeeded; if (diff > fileHeader[zdssFileKeys.kreclaimMin]) { // Reduce the space available reclaimArray[ipos] = diff; // Move the available address to after the number reclaimed. reclaimArray[ipos+1] = reclaimArray[ipos+1] + sizeNeeded; } else { reclaimArray[ipos] = 0; reclaimArray[ipos+1] = 0; } fileHeader[zdssFileKeys.kdead] -= sizeNeeded; fileHeader[zdssFileKeys.kreclaimTotal] -= sizeNeeded; if (fileHeader[zdssFileKeys.kreclaimTotal] < 0) fileHeader[zdssFileKeys.kreclaimTotal] = 0; fileHeader[zdssFileKeys.kreclaimedSpace]++; // save reclaim Array zreclaimWrite(ifltab); break; } else { iarrayNumber++; } } } // Either EOF requested, or reclaimed space of the size required not available. // Just get from EOF if (address == 0) { // Use the EOF address and say the file size is that much larger. address = fileHeader[zdssFileKeys.kfileSize]; fileHeader[zdssFileKeys.kfileSize] += sizeNeeded; *atEOF = 1; } if (zmessageLevel(ifltab, MESS_METHOD_GET_ID, MESS_LEVEL_INTERNAL_DIAG_2)) { _snprintf_s(messageString, sizeof(messageString), _TRUNCATE, "%lld, size: %d",address, sizeNeeded); zmessageDebug(ifltab, DSS_FUNCTION_zgetFileSpace_ID, "Address ", messageString); if (*atEOF == 1) { add = fileHeader[zdssFileKeys.kfileSize] - sizeNeeded; _snprintf_s(messageString, sizeof(messageString), _TRUNCATE, "%lld", add); zmessageDebug(ifltab, DSS_FUNCTION_zgetFileSpace_ID, "Space from EOF at address ", messageString); } else { diff = sizeHave - sizeNeeded; _snprintf_s(messageString, sizeof(messageString), _TRUNCATE, "%d, Sized needed: %d, difference: %d", sizeHave, sizeNeeded, diff); zmessageDebug(ifltab, DSS_FUNCTION_zgetFileSpace_ID, "Reclaimed space, sized available", messageString); } } return address; }
C++
UTF-8
2,604
2.828125
3
[]
no_license
// GCJ2012Round1B.cpp : Defines the entry point for the console application. // #include "stdafx.h" #include "iostream" #include "string" #include "string.h" #include "stdio.h" #include "vector" #include "queue"; #include "algorithm" using namespace std; int mx[]={0,1,0,-1}; int my[]={1,0,-1,0}; int C[105][105]; int F[105][105]; int visited[105][105]; struct status { int t; int x; int y; }; bool operator < (const status &lhs, const status &rhs) { return lhs.t > rhs.t; } void dfs(priority_queue<status> & queue, int x, int y, int N, int M, int H) { for(int r=0;r<4;r++) { int xx=x+mx[r]; int yy=y+my[r]; if(xx>=0 && xx<N && yy>=0 && yy<M) { if(F[x][y]<=C[xx][yy]-50 && F[xx][yy]<=C[x][y]-50 && F[xx][yy]<=C[xx][yy]-50 && H<=C[xx][yy]-50) { if(visited[xx][yy]==-1) { visited[xx][yy]=0; status next={0,xx,yy}; queue.push(next); dfs(queue,xx,yy,N,M,H); } } } } } int main() { int T; cin>>T; for(int tc=0;tc<T;tc++) { int H,N,M; cin>>H>>N>>M; memset(visited,-1,sizeof(visited)); memset(C,0,sizeof(C)); memset(F,0,sizeof(F)); for(int i=0;i<N;i++) for(int j=0;j<M;j++) cin>>C[i][j]; for(int i=0;i<N;i++) for(int j=0;j<M;j++) cin>>F[i][j]; priority_queue<status, vector<status>, less<status> > queue; status start={0,0,0}; visited[0][0]=0; queue.push(start); dfs(queue,0,0,N,M,H); while(!queue.empty()) { status cur=queue.top(); queue.pop(); if(cur.x==N-1 && cur.y==M-1) { printf("Case #%d: %.1lf\n",tc+1,0.1*cur.t); break; } for(int r=0;r<4;r++) { int xx=cur.x+mx[r]; int yy=cur.y+my[r]; if(xx>=0 && xx<N && yy>=0 && yy<M) { if(F[cur.x][cur.y]<=C[xx][yy]-50 && F[xx][yy]<=C[cur.x][cur.y]-50 && F[xx][yy]<=C[xx][yy]-50) { int startt=max(H-(C[xx][yy]-50),cur.t); int w=max(H-startt,0); int endt=startt+10; if(w-F[cur.x][cur.y]<20) endt=startt+100; if(visited[xx][yy]==-1 || visited[xx][yy]>endt) { visited[xx][yy]=endt; status next={endt,xx,yy}; queue.push(next); } } } } } } return 0 ; } // //int main() //{ // int T; // cin>>T; // for(int tc=0;tc<T;tc++) // { // int N; // cin>>N; // s.clear(); // for(int i=0;i<N;i++) // { // int t; // cin>>t; // s.push_back(t); // } // vector<int> g(N); // cout<<"Case #"<<tc+1<<":"<<endl;; // if(dfs(g,0,N)==0) // cout<<"Impossible"<<endl; // } // return 0; //}
Java
UTF-8
1,731
3.171875
3
[]
no_license
package com.algo.bootcamp.questions; import org.junit.Assert; import org.junit.Before; import org.junit.Test; public class FibonacciTest { private FibonacciNaive naive; private FibonacciMemoized memo; @Before public void setUp() throws Exception { naive = new FibonacciNaive(); memo = new FibonacciMemoized(); } @Test public void Naive(){ //Fib 1 Assert.assertEquals(0, naive.fib1(0)); Assert.assertEquals(1, naive.fib1(1)); Assert.assertEquals(1, naive.fib1(2)); Assert.assertEquals(2, naive.fib1(3)); Assert.assertEquals(3, naive.fib1(4)); Assert.assertEquals(5, naive.fib1(5)); Assert.assertEquals(8, naive.fib1(6)); Assert.assertEquals(13, naive.fib1(7)); Assert.assertEquals(21, naive.fib1(8)); //Fib 2 Assert.assertEquals(0, naive.fib2(0)); Assert.assertEquals(1, naive.fib2(1)); Assert.assertEquals(1, naive.fib2(2)); Assert.assertEquals(2, naive.fib2(3)); Assert.assertEquals(3, naive.fib2(4)); Assert.assertEquals(5, naive.fib2(5)); Assert.assertEquals(8, naive.fib2(6)); Assert.assertEquals(13, naive.fib2(7)); Assert.assertEquals(21, naive.fib2(8)); } @Test public void Memoized(){ Assert.assertEquals(0, memo.fib(0)); Assert.assertEquals(1, memo.fib(1)); Assert.assertEquals(1, memo.fib(2)); Assert.assertEquals(2, memo.fib(3)); Assert.assertEquals(3, memo.fib(4)); Assert.assertEquals(5, memo.fib(5)); Assert.assertEquals(8, memo.fib(6)); Assert.assertEquals(13, memo.fib(7)); Assert.assertEquals(21, memo.fib(8)); } }
Python
UTF-8
613
3.40625
3
[]
no_license
""" このファイルに解答コードを書いてください """ fin = open('input.txt','r') #fin = open('sample1.txt','r') lines = fin.readlines() fin.close() data = list() #データの読み込み for line in lines: if ':' in line: i, s = line.split(':') data.append((int(i),s)) else: m = int(line) break #iについて昇順ソート data.sort(key=lambda x: x[0]) #条件を満たす文字列を保存 res = "" for d in data: i, s = d if m % i == 0: res += s[:-1] #出力(空の時 m を出力) if res != "": print(res) else: print(m)
Java
UTF-8
1,935
2.328125
2
[]
no_license
package com.example.study3.api; import com.example.study3.model.Board; import com.example.study3.model.DefaultRes; import com.example.study3.service.BoardService; import lombok.extern.slf4j.Slf4j; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; @Slf4j @RestController public class BoardController { private final BoardService boardService; public BoardController(BoardService boardService) { this.boardService = boardService; } @GetMapping("/board") public ResponseEntity findAllBoards() { try { return new ResponseEntity<>(boardService.findAll(), HttpStatus.OK); } catch (Exception e) { e.printStackTrace(); DefaultRes<Board> ISR = new DefaultRes<>(HttpStatus.INTERNAL_SERVER_ERROR,"서버 내부 오류" ); return new ResponseEntity<>(ISR, HttpStatus.INTERNAL_SERVER_ERROR); } } @GetMapping("/board/{boardIdx}") public ResponseEntity findIdxBoard(@PathVariable int boardIdx) { try { return new ResponseEntity<>(boardService.findIdx(boardIdx), HttpStatus.OK); } catch (Exception e) { e.printStackTrace(); DefaultRes<Board> ISR = new DefaultRes<>(HttpStatus.INTERNAL_SERVER_ERROR,"서버 내부 오류" ); return new ResponseEntity<>(ISR, HttpStatus.INTERNAL_SERVER_ERROR); } } @PostMapping("/board") public ResponseEntity findAllBoards(@RequestBody Board board) { try { return new ResponseEntity<>(boardService.insert(board), HttpStatus.OK); } catch (Exception e) { e.printStackTrace(); DefaultRes<Board> ISR = new DefaultRes<>(HttpStatus.INTERNAL_SERVER_ERROR,"서버 내부 오류" ); return new ResponseEntity<>(ISR, HttpStatus.INTERNAL_SERVER_ERROR); } } }
Python
UTF-8
5,531
2.578125
3
[]
no_license
# This is the flask api it loads the pickle saved model and get the features in input and output the prediction either stressed or not stressed # Import Libraries from flask import Flask, request, jsonify, render_template import joblib import traceback import pandas as pd import numpy as np import serial import time import subprocess import os from ecgdetectors import Detectors import scipy.signal as signal app = Flask(__name__) ExtraTreesClassifier = joblib.load("static/models/ExtraTreesClassifier.pkl") print('Model loaded') @app.route("/") def index(): return render_template('home.html') @app.route('/predict', methods=['POST']) def predict(): data = [request.form['HR'], request.form['IIS'], request.form['AVNN'], request.form['RMSSD'], request.form['pNN50'], request.form['TP'], request.form['ULF'], request.form['VLF'], request.form['LF'], request.form['HF'], request.form['LF_HF']] data = np.array([np.asarray(data, dtype=float)]) predictions = ExtraTreesClassifier.predict(data) print('INFO Predictions: {}'.format(predictions)) if predictions[0] == 1: class_ = 'stressed' else: class_ = 'not stressed' return render_template('index.html', pred=class_) @app.route('/predictfromjson', methods=['POST']) def predictfromjson(): data = request.get_json() df = pd.json_normalize(data) # print(df) predictions = ExtraTreesClassifier.predict(df) print('INFO Predictions: {}'.format(predictions)) if predictions[0] == 1: class_ = 'stressed' else: class_ = 'not stressed' print(class_) return jsonify({'Prediction': class_}) @app.route("/home") def home(): return render_template('home.html') sp = 0 @app.route("/startmeasuring", methods=['POST']) def startmeasuring(): proc = subprocess.Popen(["python", "datareading.py"], shell=True,creationflags=subprocess.CREATE_NEW_PROCESS_GROUP) global sp sp = proc.pid print("subprocess started ", sp) print("subprocess started with id ", proc.pid) return str(proc.pid) @app.route("/stopmeasuring", methods=['POST']) def stopmeasuring(): global sp print('killing process with id: ', sp) os.system("taskkill /f /t /pid "+str(sp)) print("subprocess stopped") df = pd.read_csv('data.csv', index_col=None, header=0) ecg_signal = df['ECG']*1000 sr = 60 time = np.linspace(0, len(ecg_signal) / sr, len(ecg_signal)) detectors = Detectors(sr) r_peaks = detectors.pan_tompkins_detector(ecg_signal) peaks = np.array(time)[r_peaks] RRinterval = np.diff(peaks) median=np.median(RRinterval) RRinterval=np.append(RRinterval,median) df=df.iloc[r_peaks] df["RRinterval"]=RRinterval df["RRinterval"] = np.where(df["RRinterval"]<0.5, median,df["RRinterval"]) df["RRinterval"] = np.where(df["RRinterval"]>1.5, median,df["RRinterval"]) df["RRinterval"]=signal.medfilt(df["RRinterval"], 5) rri=df['RRinterval'] diff_rri = np.diff(rri) NNRR=round(len(np.diff(rri))/len(rri),6) RMSSD=np.sqrt(np.mean(diff_rri ** 2)) SDNN = np.nanstd(rri, ddof=1) AVNN = np.nanmean(rri) nn50 = np.sum(np.abs(diff_rri) > 0.05) pNN50 = nn50 / len(rri) df['NNRR']=NNRR df['RMSSD']=RMSSD df['SDNN']=SDNN df['AVNN']=AVNN df['pNN50']=pNN50 print(df.describe()) df = df.replace([np.inf, -np.inf], np.nan) df['HR'].fillna((df['HR'].mean()), inplace=True) df['HR'] = signal.medfilt(df['HR'],5) df['RESP'].fillna((df['RESP'].mean()), inplace=True) df['RESP'] = signal.medfilt(df['RESP'],5) df['EMG'].fillna((df['EMG'].mean()), inplace=True) df['EMG'] = signal.medfilt(df['EMG'],5) df['ECG'].fillna((df['ECG'].mean()), inplace=True) df['ECG'] = signal.medfilt(df['ECG'],5) df=df.fillna(df.mean()) df.to_csv('test_data2.csv', index=False) df=df.drop(['time'], axis=1) predictions = ExtraTreesClassifier.predict(df) print('predictions: ',predictions) c=(predictions == 0).sum() c1=(predictions == 1).sum() if c<c1: class_ = 'stressed' return render_template('stressed.html', pred=class_) else: class_ = 'not stressed' return render_template('notstressed.html', pred=class_) print(class_) @app.route("/chart") def chart(): return render_template('data.html') @app.route("/data") def data(): data = pd.read_csv('data.csv', index_col=None, header=0) if data.empty: return str(0) else: return str(data.iloc[-1][1]) @app.route("/ecgdata") def ecgdata(): data = pd.read_csv('data.csv', index_col=None, header=0) if data.empty: return str(0) else: return str(data.iloc[-1][1]) @app.route("/emgdata") def emgdata(): data = pd.read_csv('data.csv', index_col=None, header=0) if data.empty: return str(0) else: return str(data.iloc[-1][2]) @app.route("/hrdata") def hrdata(): data = pd.read_csv('data.csv', index_col=None, header=0) if data.empty: return str(0) else: return str(data.iloc[-1][3]) @app.route("/respdata") def respdata(): data = pd.read_csv('data.csv', index_col=None, header=0) if data.empty: return str(0) else: return str(data.iloc[-1][4]) def main(): """Run the app.""" app.run(host='0.0.0.0', port=8000, debug=True) if __name__ == '__main__': main()
Java
UTF-8
12,148
2.171875
2
[]
no_license
package com.p6e.germ.video; import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext; import io.netty.handler.codec.ByteToMessageDecoder; import java.io.ByteArrayOutputStream; import java.util.ArrayList; import java.util.Arrays; import java.util.List; /** * RTMP 协议的解码器 * @author lidashuang * @version 1.0 */ public class RtmpDecoder extends ByteToMessageDecoder { public static boolean b = false; /** * RTMP 握手协议对象 */ private final RtmpHandshake handshake; /** * 分包长度 */ private byte[] subpackage = null; private int subpackageIndex = 0; private int subpackageLength = 0; /** * 缓存的上一次的消息的头部 */ private RtmpMessage.Header cacheHeader = null; /** * 默认构造函数 */ public RtmpDecoder() { this.handshake = new RtmpHandshake(); } /** * 默认的构造函数,自定义 RTMP 握手协议对象 * @param handshake RTMP 握手协议对象 */ public RtmpDecoder(RtmpHandshake handshake) { this.handshake = handshake; } int a = 0; ByteArrayOutputStream byteArrayOutputStream = null; @Override protected void decode(ChannelHandlerContext context, ByteBuf byteBuf, List<Object> list) throws Exception { // 读取数据 final byte[] bytes = new byte[byteBuf.readableBytes()]; byteBuf.readBytes(bytes); // System.out.println("收到数据 ---> " + Utils.bytesToHex(bytes)); if (b) { RtmpJX.run(bytes); return; } // 判断握手是否成功 if (this.handshake.isSuccess()) { list.addAll(this.decodeBytesToMessage(bytes)); } else { // 字节码发送给握手的对象 final byte[] result = this.handshake.execute(context, bytes); // 不为空表示存在需要解析的消息 if (result != null) { // 解析消息 list.addAll(this.decodeBytesToMessage(result)); } } } private boolean is = true; /** * 解码字节码转为消息对象列表 * @param bytes 字节码对象 * @return 消息对象列表 */ @SuppressWarnings("all") public List<RtmpMessage> decodeBytesToMessage(byte[] bytes) { final List<RtmpMessage> result = new ArrayList<>(); try { if (bytes != null) { int index = 0; // 是否分包 if (subpackageLength > 0) { if (cacheHeader == null) { throw new RuntimeException("[ 解码失败 ] 不存在之前的头文件 ~"); } else { final int interval = subpackageLength - subpackageIndex; if (bytes.length >= interval) { System.arraycopy(bytes, 0, subpackage, subpackageIndex, interval); result.add(createRtmpMessage(subpackage)); result.addAll(decodeBytesToMessage(Utils.bytesArrayIntercept(bytes, interval, bytes.length - interval))); subpackage = null; subpackageIndex = 0; subpackageLength = 0; } else { System.arraycopy(bytes, 0, subpackage, subpackageIndex, bytes.length); subpackageIndex = subpackageIndex + bytes.length; } } } else { while (index + 1 < bytes.length) { int csId; final int ct = bytes[index] & 0x3F; final int fmt = (bytes[index] >> 6) & 0xFF; switch (ct) { case 0x00: csId = 64 + bytes[++index]; break; case 0x3F: index += 2; csId = 64 + bytes[++index] + 256 * bytes[++index]; break; default: csId = ct; break; } final int timestamp, messageLength, messageTypeId, messageStreamId; switch (fmt) { case 0: if (index + 11 < bytes.length) { timestamp = Utils.bytesToIntLittle(new byte[] { 0, bytes[++index], bytes[++index], bytes[++index], }); messageLength = Utils.bytesToIntLittle(new byte[] { 0, bytes[++index], bytes[++index], bytes[++index], }); messageTypeId = bytes[++index]; messageStreamId = Utils.bytesToIntBig(new byte[] { bytes[++index], bytes[++index], bytes[++index], bytes[++index], }); } else { throw new RuntimeException("[ 解码失败 ] 解析头文部数据,消息异常 ~"); } break; case 1: if (index + 7 < bytes.length) { if (cacheHeader == null) { throw new RuntimeException("[ 解码失败 ] 不存在之前的头文件 ~"); } else { timestamp = Utils.bytesToIntLittle(new byte[] { 0, bytes[++index], bytes[++index], bytes[++index], }); messageLength = Utils.bytesToIntLittle(new byte[] { 0, bytes[++index], bytes[++index], bytes[++index], }); messageTypeId = bytes[++index]; messageStreamId = cacheHeader.getMessageStreamId(); } } else { throw new RuntimeException("[ 解码失败 ] 解析头文部数据,消息异常 ~"); } break; case 2: if (index + 3 < bytes.length) { if (cacheHeader == null) { throw new RuntimeException("[ 解码失败 ] 不存在之前的头文件 ~"); } else { timestamp = Utils.bytesToIntLittle(new byte[] { 0, bytes[++index], bytes[++index], bytes[++index], }); messageLength = cacheHeader.getMessageLength(); messageTypeId = cacheHeader.getMessageTypeId(); messageStreamId = cacheHeader.getMessageStreamId(); } } else { throw new RuntimeException("[ 解码失败 ] 解析头文部数据,消息异常 ~"); } break; case 3: if (cacheHeader == null) { throw new RuntimeException("[ 解码失败 ] 不存在之前的头文件 ~"); } else { timestamp = cacheHeader.getTimestamp(); messageLength = cacheHeader.getMessageLength(); messageTypeId = cacheHeader.getMessageTypeId(); messageStreamId = cacheHeader.getMessageStreamId(); } break; default: throw new RuntimeException("[ 解码失败 ] FMT 异常 ~"); } cacheHeader = new RtmpMessage.Header(fmt, csId, timestamp, messageLength, messageTypeId, messageStreamId); if (index + messageLength + 1 <= bytes.length) { if (is) { byte[] cs = Utils.bytesArrayIntercept(bytes, index + 1, bytes.length - index - 1); for (int i = cs.length - 1; i >= 0; i--) { if (cs[i] == -61) { System.arraycopy(cs, 0, cs, 0, i); System.arraycopy(cs, i + 1, cs, i, cs.length - i - 1); cs = Arrays.copyOf(cs, cs.length - 1); break; } } result.add(createRtmpMessage(cs)); index = bytes.length - 1; } else { result.add(createRtmpMessage(Utils.bytesArrayIntercept(bytes, index + 1, messageLength))); index = index + messageLength + 1; } } else { subpackageLength = messageLength; subpackage = new byte[subpackageLength]; System.arraycopy(bytes, index + 1, subpackage, 0, bytes.length - index - 1); subpackageIndex = bytes.length - index - 1; index = bytes.length; } is = false; } } } else { // 43 // 00 00 00 // 00 00 1e // 14 // 02 00 0d 72 // 656c6561736553747265616d00400000000000000005020001314300000000001a1402000946435075626c6973680040080000000000000502000131430000000000191402000c63726561746553747265616d00401000000000000005 throw new RuntimeException("[ 解码失败 ] 字节码长度异常 ~"); } } catch (Exception e) { subpackage = null; subpackageIndex = 0; subpackageLength = 0; e.printStackTrace(); } return result; } /** * 创建 RTMP 消息的对象 * @return 消息的对象 */ private RtmpMessage createRtmpMessage(byte[] bytes) { return RtmpRegistry.getMessageCore(cacheHeader.getMessageTypeId()).decode(cacheHeader, bytes); } }
Java
UTF-8
628
1.90625
2
[]
no_license
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.bridj.cpp.mfc; import org.bridj.Pointer; import org.bridj.ann.Library; import org.bridj.ann.Runtime; import org.bridj.cpp.CPPObject; @Library(value="mfc90u.dll", versionPattern = "mfc(?:(\\d)(\\d))?u") @Runtime(MFCRuntime.class) public class MFCObject extends CPPObject { protected MFCObject() {} protected MFCObject(Pointer<? extends MFCObject> peer) { super(peer); } protected MFCObject(Void voidArg, int constructorId, Object... args) { super(voidArg, constructorId, args); } }
C#
UTF-8
577
2.71875
3
[ "MIT" ]
permissive
using System; using System.Collections.Generic; using System.Reflection; using System.Text; namespace LaughingWaffle.PropertyLoaders { /// <summary> /// Define the contract of the property loader /// </summary> public interface IPropertyLoader { /// <summary> /// Determine and filter (as appropriate) the list of properties for an instance of <see cref="ISqlGenerator"/>. /// </summary> /// <param name="tType"></param> /// <returns></returns> IEnumerable<PropertyInfo> GetProperties(Type tType); } }
Markdown
UTF-8
3,010
3.484375
3
[]
no_license
## Token A lexical token or simply token is a string with an assigned and thus identified meaning. It is structured as a pair consisting of a token name and an optional token value. ``` C++ // non terminals #define EMPTY "EMPTY" #define SEMI "SEMI" #define COMMA "COMMA" #define LPAREN "LPAREN" #define RPAREN "RPAREN" #define LBRACKET "LBRACKET" #define RBRACKET "RBRACKET" #define LBRACE "LBRACE" #define RBRACE "RBRACE" #define CODE_BLOCK "CODE_BLOCK" #define ASSIGN "ASSIGN" #define PLUS "ADD" #define INC "INC" #define MINUS "SUB" #define DEC "DEC" #define MUL "MUL" #define DIV "DIV" #define MOD "MOD" #define EQ "EQ" #define NEQ "NEQ" #define LT "LT" #define GT "GT" #define LEQ "LEQ" #define GEQ "GEQ" #define POW "POW" #define AND "AND" #define OR "OR" // terminals #define IDENTIFIER "IDENTIFIER" #define VARIABLE "VARIABLE" #define INTEGER "INTEGER" class Token { private: std::string type; std::string value; public: Token() { type = ""; value = ""; } Token(std::string _type, std::string _value) { type = _type; value = _value; } ~Token(){}; std::string _value() { return value; } std::string _type() { return type; } std::string str() { return ("Token("+type+","+value+")"); } }; ``` ## AST Tree A AST tree or parse tree is an ordered, rooted tree that represents the syntactic structure of a program. A parse tree is made up of tokens (nodes and branches). Nodes can also be referred to as parent nodes and child nodes. A parent node is one which has at least one other node linked by a branch under it. A child node is one which has at least one node directly above it to which it is linked by a branch of the tree. ``` C++ class ASTNode { public: std::vector<ASTNode*> child; Token token; ASTNode() {}; ASTNode(Token _token) { token = _token; } ~ASTNode() {}; void make_child(ASTNode _node) { ASTNode *temp = new ASTNode(_node._token()); temp->child = _node.child; child.push_back(temp); } Token _token() { return token; } void show(int level) { if(level < 2 && level != 0) std::cout << std::string(level*2, ' ') << "Token('" << token._type() << "', '" << token._value() << "')\n"; else std::cout << std::string(level*2, ' ') << "Token('" << token._type() << "', '" << token._value() << "')\n"; for(auto it = child.begin(); it != child.end(); it++) (*it)->show(level+1); } }; ```
Python
UTF-8
10,625
2.765625
3
[]
no_license
import os import random import numpy as np import tensorflow as tf import hyperparameters as hp from lab_funcs import rgb_to_lab, lab_to_rgb from sklearn.cluster import KMeans, MiniBatchKMeans import pickle from scipy.spatial.distance import cdist import numpy as np from matplotlib import pyplot as plt AUTOTUNE = tf.data.experimental.AUTOTUNE class Datasets(): """ Class for containing the training and test sets as well as other useful data-related information. Contains the functions for preprocessing. """ def __init__(self, data_path): assert(hp.img_size % 4 == 0) self.q_init = False self.train_path = os.path.join(data_path, "train") self.test_path = os.path.join(data_path, "test") self.file_list = self.get_file_list() # Mean and std for standardization self.mean = np.zeros((3,)) self.std = np.ones((3,)) self.calc_mean_and_std() self.cc = self.quantize_colors() # Setup data generators self.train_data = self.get_data(self.train_path) self.test_data = self.get_data(self.test_path) self.file_list = None '''Network output back into RGB image ''' def test_pipeline(self, path): self.init_q_conversion() # Convert to L and quantised colour values l, q = self.process_path(path) # Convert from quantised back to ab ab = tf.reshape(self.get_img_ab_from_q_color(q), [hp.img_size // 4, hp.img_size // 4, 2]) # Upscale ab to img_size ab = tf.image.resize(ab, [hp.img_size, hp.img_size], method="bicubic") # Reverse standardisation lab = tf.concat([l, ab], axis=2) * self.std + self.mean rgb = lab_to_rgb(lab) plt.imshow(rgb) plt.show() return rgb '''Takes output in q colors to a rank-4 tensor of ab colors q - 3136x313 output of our network l - 224x224x1 lightness ''' def model_output_to_tensorboard(self, l, q): ab = tf.reshape(self.get_img_ab_from_q_color(q), [hp.img_size // 4, hp.img_size // 4, 2]) # Upscale ab to img_size ab = tf.image.resize(ab, [hp.img_size, hp.img_size], method="bicubic") # Reverse standardisation lab = tf.concat([l, ab], axis=2) * self.std + self.mean rgb = lab_to_rgb(lab) # reshaped = tf.reshape(rgb, (-1, 224, 224, 3)) return rgb def get_file_list(self): file_list = [] for root, _, files in os.walk(self.train_path): for name in files: down = name.lower() if down.endswith("jpg") or down.endswith("jpeg") or down.endswith("png"): file_list.append(os.path.join(root, name)) random.shuffle(file_list) return file_list ''' This is the first step in getting a loss function that accounts for color rarity. We will have to reweight each pixel based on pixel color rarity. This function gets the probabilities for each of 313 Q colors. Q colors are the quantized ab values which are "in-gamut" for RGB -- (Values are [-110, 110] for CIELAB. For a given L, we break the CIELAB space into boxes of different colors to make the task easier (i.e. smaller than 220*220 possible colors). Only some of these are visible in RGB space, so we have 313 left. ''' def quantize_colors(self): if os.path.isfile('qcolors_cc.pkl'): # Q colors are the cluster centers cc = pickle.load(open("qcolors_cc.pkl", "rb")) else: # Randomly choose 5000*2 ab values from the input images num_samples = 5000 pixels_per_im = 3 ab_list = [] # Import images for i, file_path in enumerate(self.file_list[:int(num_samples/2)]): img = tf.io.read_file(file_path) # img now in LAB img = self.convert_img(img) # get img to just Ab ab_image = img[:, :, 1:] for j in range(pixels_per_im): ab_list.append(ab_image[random.randrange(0, hp.img_size)][random.randrange(0, hp.img_size)].numpy()) rand_abs = np.stack(ab_list) cc = self.gen_q_cc(rand_abs) return cc ''' From available images generate 313 cluster centers of ab colors''' def gen_q_cc(self, ab_colors): print('Generating q colors through kmeans!') kmeans = MiniBatchKMeans(n_clusters=313, init_size=313, max_iter=300).fit(ab_colors) pickle.dump(kmeans.cluster_centers_, open("qcolors_cc.pkl", "wb")) print('...Done.') return kmeans.cluster_centers_ ''' Goes from Y (224 x 224 x 2) to Z (56 x 56 x 313) This gets Z, i.e. the true Q distribution, for each pixel from Y, an ab color image''' def get_img_q_color_from_ab(self, ab_img): if not self.q_init: print("get_img_q_color_from_ab: Q conversion not initialised") exit(1) # Downscale to 56x56 and reshape abs_reshaped = tf.reshape(ab_img[::4, ::4, :], (-1, 2)) dists, closest_qs = self.nearest_neighbours(abs_reshaped, self.cc, hp.n_neighbours) # weight the dists using Gaussian kernel sigma = 5 # got these 2 lines from /colorization/resources/caffe_traininglayers.py wts = tf.exp(-dists**2/(2*5**2)) wts = wts/tf.math.reduce_sum(wts, axis=1)[:, tf.newaxis] indices = tf.concat([self.q_indices, tf.reshape(closest_qs, [-1, 1])], axis=1) # Add weights to appropriate positions return tf.tensor_scatter_nd_add( tf.zeros((abs_reshaped.shape[0], 313)), indices, tf.reshape(wts, [-1])) ''' A tensorflow implementation of nearest neighbours to be used when computing ground truth data for the loss function. ''' def nearest_neighbours(self, points, centers, k): cents = tf.cast(centers, tf.float32) # adapted from https://gist.github.com/mbsariyildiz/34cdc26afb630e8cae079048eef91865 p_x = tf.reshape(points[:, 0], (-1, 1)) p_y = tf.reshape(points[:, 1], (-1, 1)) c_x = tf.reshape(cents[:, 0], (-1, 1)) c_y = tf.reshape(cents[:, 1], (-1, 1)) p_x2 = tf.reshape(tf.square(p_x), (-1, 1)) p_y2 = tf.reshape(tf.square(p_y), (-1, 1)) c_x2 = tf.reshape(tf.square(c_x), (1, -1)) c_y2 = tf.reshape(tf.square(c_y), (1, -1)) dist_px_cx = p_x2 + c_x2 - 2*tf.matmul(p_x, c_x, False, True) dist_py_cy = p_y2 + c_y2 - 2*tf.matmul(p_y, c_y, False, True) dist = tf.sqrt(dist_px_cx + dist_py_cy) dists, inds = tf.nn.top_k(-dist, hp.n_neighbours) return -dists, tf.cast(inds, tf.int32) ''' Goes from Z hat (58x58x313) to Y hat (58x58x2) Gets the annealed mean or mode. See https://github.com/richzhang/colorization/blob/815b3f7808f8f2d9d683e9ed6c5b0a39bec232fb/colorization/demo/colorization_demo_v2.ipynb Then upscale from 58x58x2 to 224 x 224 After the neural network -> can use NP functions ''' def get_img_ab_from_q_color(self, q_img): # Determine degree of annealed mean vs pure mean vs mode temp = 0.38 nom = tf.math.exp(tf.math.log(q_img)/temp) denom = tf.reshape(tf.tile(tf.reduce_sum(tf.math.exp(tf.math.log( tf.reshape(tf.math.top_k(q_img, 5)[0], [-1, 5])/temp)), 1), [313]), [-1, 313]) # Annealed function f = nom/denom mean = tf.reduce_mean(tf.reshape(tf.math.top_k(q_img, 5)[0], (-1, 5)), 1) ab_img = self.cc[tf.expand_dims(tf.math.argmin(tf.math.abs( f - tf.reshape(tf.tile(mean, [313]), [-1, 313])), axis=1), 1)] return ab_img def calc_mean_and_std(self): # just for testing! if os.path.isfile('mean.pkl'): # Q colors are the cluster centers self.mean = pickle.load(open("mean.pkl", "rb")) self.std = pickle.load(open("std.pkl", "rb")) else: # Allocate space in memory for images data_sample = np.zeros( (hp.preprocess_sample_size, hp.img_size, hp.img_size, 3)) # Import images for i, file_path in enumerate(self.file_list[:hp.preprocess_sample_size]): img = self.process_path(file_path, False, quantise=False) data_sample[i] = img self.mean = np.mean(data_sample, axis=(0, 1, 2)) self.std = np.std(data_sample, axis=(0, 1, 2)) print("Dataset mean: [{0:.4f}, {1:.4f}, {2:.4f}]".format( self.mean[0], self.mean[1], self.mean[2])) print("Dataset std: [{0:.4f}, {1:.4f}, {2:.4f}]".format( self.std[0], self.std[1], self.std[2])) # delete later, just for testing! pickle.dump(self.mean, open("mean.pkl", "wb")) pickle.dump(self.std, open("std.pkl", "wb")) ''' Perform preprocessing for image path. To be used by Dataset to prepare ground truth for the loss function. Process: rgb => lab => l,ab => l,q ''' def process_path(self, path, split=True, quantise=True): img = tf.io.read_file(path) img = self.convert_img(img) if split: # Gets Q colours downsized if required. return (img[:, :, 0:1], self.get_img_q_color_from_ab(img[:, :, 1:3]) if quantise else img[:, :, 1:3]) else: return img ''' Resizes, standardises and converts image from rgb to lab. ''' def convert_img(self, img, standardize=True): img = tf.image.decode_image(img, channels=3, expand_animations=False, dtype="float32") img = tf.image.resize(img, [hp.img_size, hp.img_size]) img = rgb_to_lab(img) return ((img - self.mean) / self.std) if standardize else img ''' Precompute constants to minimise memory usage when quantising images ''' def init_q_conversion(self): if not self.q_init: self.q_indices = tf.repeat( tf.reshape(tf.range((hp.img_size // 4) ** 2, dtype="int32"), [-1, 1]), hp.n_neighbours, axis=0) self.q_init = True def get_data(self, path): imgs = tf.data.Dataset.list_files([path + "/*/*.JPEG", path + "/*/*.jpg", path + "/*/*.jpeg", path + "/*/*.png"]) self.init_q_conversion() cnn_ds = imgs.map(self.process_path, num_parallel_calls=AUTOTUNE) cnn_ds = cnn_ds.batch(hp.batch_size) cnn_ds = cnn_ds.prefetch(buffer_size=AUTOTUNE) return cnn_ds
Python
UTF-8
5,827
2.71875
3
[ "MIT" ]
permissive
from queue import Queue from threading import Lock from ipcbroker.broker import Broker from ipcbroker.message import Message from ipcbroker.threaded import Threaded class Client(Threaded): POLL_TIMEOUT = 0.1 def __init__(self, broker: Broker, name=None): if name is None: super().__init__() else: super().__init__(name) if not isinstance(broker, Broker): raise TypeError('broker is not a Broker: {}'.format(type(broker))) self.__broker_con = broker.register_client() self.__message_queue = Queue() self.__registered_funcs = dict() self.__connection_lock = Lock() def __call__(self, name, *args, **kwargs): if name not in self.__registered_funcs: return self.__remote_call(name)(*args, **kwargs) func = self.__registered_funcs[name] return func(*args, **kwargs) def __getattr__(self, item): # check if method is locally registered if item in self.__registered_funcs: return self.__registered_funcs[item] # if not do a remote call via the broker return self.__remote_call(item) def work(self): # check if new message has arrived try: with self.__connection_lock: while self.__broker_con.poll(self.POLL_TIMEOUT): message = self.__broker_con.recv() self.__message_queue.put(message) except (EOFError, OSError): pass # process messages in message queue while not self.__message_queue.empty(): message = self.__message_queue.get() self.__process_message(message) def register_function(self, name, callback, long_running=False): # check if the function is already locally registered if name in self.__registered_funcs: raise KeyError('Function already locally registered') # check if the callback is a callable if not callable(callback): raise TypeError('Callback is not callable') with self.__connection_lock: if long_running: message = Message('register_function', name, flags=['long_running']) else: message = Message('register_function', name) # send register request to broker self.__broker_con.send(message) # wait for response return_message = self.__broker_con.recv() while ( return_message.com_id != message.com_id and return_message.action != 'return' ): self.__message_queue.put(return_message) return_message = self.__broker_con.recv() # if response says OK return True otherwise False if return_message.payload == 'OK': self.__registered_funcs[name] = callback return True else: return False def __remote_call(self, name): """ Return a function to call a remote client method :param name: name of the method :return: remote handler """ def func(*args, **kwargs): # fill the dictionary with the args and kwargs for # the remote method payload_dict = {'args': args, 'kwargs': kwargs} with self.__connection_lock: # send request to broker message = Message(name, payload_dict) self.__broker_con.send(message) # wait for response return_message = self.__broker_con.recv() while ( return_message.action != 'return' and return_message.com_id != message.com_id ): self.__message_queue.put(return_message) return_message = self.__broker_con.recv() # return the payload return return_message.payload return func def __process_message(self, message: Message): # check if the message payload is dict with arguments # args and kwargs # if not required use empty dict if not isinstance(message.payload, dict): exc = TypeError('Payload is not argument dict') return_message = Message('return', exc, message.com_id) self.__broker_con.send(return_message) return # check if requested method is registered if message.action not in self.__registered_funcs: exc = KeyError('Function not known') return_message = Message('return', exc, message.com_id) self.__broker_con.send(return_message) return # if args not in payload dict add it if 'args' not in message.payload: message.payload['args'] = tuple() # if kwargs not in payload dict add it if 'kwargs' not in message.payload: message.payload['kwargs'] = dict() # call method action_func = getattr(self, message.action) return_value = action_func(*message.payload['args'], **message.payload['kwargs']) # and return result return_message = Message('return', return_value, message.com_id) self.__broker_con.send(return_message)
Python
UTF-8
4,700
2.71875
3
[]
no_license
""" Unit tests for the water-regulation module """ import unittest from unittest.mock import MagicMock from pump import Pump from sensor import Sensor from .controller import Controller from .decider import Decider class DeciderTests(unittest.TestCase): """ Unit tests for the Decider class """ actions = {'PUMP_IN': 1, 'PUMP_OUT': -1, 'PUMP_OFF': 0} def test_pump_off_h_below_margin(self): """ test PUMP_OFF + height below lower margin = PUMP_IN """ decider = Decider(10, .1) action = decider.decide(8, self.actions['PUMP_OFF'], self.actions) self.assertEqual(self.actions['PUMP_IN'], action) def test_pump_off_h_at_low_margin(self): """ test PUMP_OFF + height at lower margin = PUMP_OFF """ decider = Decider(10, .1) action = decider.decide(9, self.actions['PUMP_OFF'], self.actions) self.assertEqual(self.actions['PUMP_OFF'], action) def test_pump_off_h_at_target(self): """ test PUMP_OFF + height at target = PUMP_OFF """ decider = Decider(10, .1) action = decider.decide(10, self.actions['PUMP_OFF'], self.actions) self.assertEqual(self.actions['PUMP_OFF'], action) def test_pump_off_h_at_high_margin(self): """ test PUMP_OFF + height at upper margin = PUMP_OFF """ decider = Decider(10, .1) action = decider.decide(11, self.actions['PUMP_OFF'], self.actions) self.assertEqual(self.actions['PUMP_OFF'], action) def test_pump_off_h_above_margin(self): """ test PUMP_OFF + height above upper margin = PUMP_OUT """ decider = Decider(10, .1) action = decider.decide(12, self.actions['PUMP_OFF'], self.actions) self.assertEqual(self.actions['PUMP_OUT'], action) def test_pump_in_h_below_target(self): """ test PUMP_IN + height below target = PUMP_IN """ decider = Decider(10, .1) action = decider.decide(9, self.actions['PUMP_IN'], self.actions) self.assertEqual(self.actions['PUMP_IN'], action) def test_pump_in_h_at_target(self): """ test PUMP_IN + height at target = PUMP_IN """ decider = Decider(10, .1) action = decider.decide(10, self.actions['PUMP_IN'], self.actions) self.assertEqual(self.actions['PUMP_IN'], action) def test_pump_in_h_above_target(self): """ test PUMP_IN + height above target = PUMP_OFF """ decider = Decider(10, .1) action = decider.decide(11, self.actions['PUMP_IN'], self.actions) self.assertEqual(self.actions['PUMP_OFF'], action) def test_pump_out_h_below_target(self): """ test PUMP_OUT + height below target = PUMP_OFF """ decider = Decider(10, .1) action = decider.decide(9, self.actions['PUMP_OUT'], self.actions) self.assertEqual(self.actions['PUMP_OFF'], action) def test_pump_out_h_at_target(self): """ test PUMP_OUT + height below target = PUMP_OUT """ decider = Decider(10, .1) action = decider.decide(10, self.actions['PUMP_OUT'], self.actions) self.assertEqual(self.actions['PUMP_OUT'], action) def test_pump_out_h_above_target(self): """ test PUMP_OUT + height above target = PUMP_OUT """ decider = Decider(10, .1) action = decider.decide(11, self.actions['PUMP_OUT'], self.actions) self.assertEqual(self.actions['PUMP_OUT'], action) class ControllerTests(unittest.TestCase): """ Unit tests for the Controller class """ def test_tick_true(self): """ Test that tick return True if pump.set_state returns True """ sensor = Sensor('127.0.0.1', 8000) pump = Pump('127.0.0.1', 8000) decider = Decider(10, .1) controller = Controller(sensor, pump, decider) sensor.measure = MagicMock(return_value=10) pump.get_state = MagicMock(return_value=pump.PUMP_OFF) pump.set_state = MagicMock(return_value=True) self.assertTrue(controller.tick()) def test_tick_false(self): """ Test that tick return False if pump.set_state returns False """ sensor = Sensor('127.0.0.1', 8000) pump = Pump('127.0.0.1', 8000) decider = Decider(10, .1) controller = Controller(sensor, pump, decider) sensor.measure = MagicMock(return_value=10) pump.get_state = MagicMock(return_value=pump.PUMP_OFF) pump.set_state = MagicMock(return_value=False) self.assertFalse(controller.tick())
JavaScript
UTF-8
7,304
2.546875
3
[]
no_license
import * as helpers from './helpers.js'// workers import { activateStartButton } from './main.js' // this is called when model is loaded. Physijs.scripts.worker = './lib/physijs_worker.js' const camera_angle_worker = new Worker('./js/worker.js') const container = document.querySelector('#three-container') const one_bar = 8000 // clips are 120bpm; 4:4; one bar is 8000 seconds const number_of_clips = 24 const clips = new Array(number_of_clips) const player_queue = [] const camera = new THREE.PerspectiveCamera(45, window.innerWidth / window.innerHeight, 1, 10000) const scene = new Physijs.Scene() const renderer = new THREE.WebGLRenderer({ antialias: false }) const player_material = new THREE.MeshBasicMaterial({ color: 0x999999 }) let bar_counter = 0 let count = 0 for (const [i, v] of clips.entries()) { clips[i] = i + 1 + '.mp4' } camera.position.set(155, 1250, 500) /* Pick a random video clip and create a video element in the DOM */ const createVideoClipElement = async function () { try { const next_pending_clip = {} const video_choice = helpers.randFromArray(clips) const element = document.createElement('video') const configured_element = configureVideoClipElement(element, video_choice) next_pending_clip['element'] = configured_element next_pending_clip['id'] = configured_element.id next_pending_clip['video_choice'] = configured_element.video_choice return (next_pending_clip); } catch (rejectedValue) { Error('Unable to preload next video clip; please check connection.') } } /* Set the size and id of the video element, as called in createVideoClipElement() */ const configureVideoClipElement = (element, video_choice) => { element.id = count element.style.border = '0px' element.style.width = '560px' element.style.height = '315px' element.src = './videos/small/' + video_choice element.preload = 'auto'; return element } /* Create the 3D mesh and assign the video element to one of its sides as a texture */ const create3dPlayerModel = async function (clip_object) { try { const vid_texture = new THREE.VideoTexture(clip_object.element) /* Blank dummy material assigned to the non-video texture sides of the mesh */ const dummyMaterialArray = Array.from({ length: 5 }).map((val, index, arr) => { if (index == 4) { return new THREE.MeshBasicMaterial({ map: vid_texture, side: THREE.FrontSide }) } else { return player_material } }) const material = new THREE.MeshFaceMaterial(dummyMaterialArray) const geometry = new THREE.BoxGeometry(560, 315, 17) const object_model = new Physijs.BoxMesh(geometry, material) const object_model_with_video_texture = { video_clip: clip_object, object: configure3dPlayerModelPosition(object_model) } return (object_model_with_video_texture) } catch (rejectedValue) { Error('Unable to preload next 3d object; please check connection.') } } /* Place the 3d model behind the camera Y position, so it loads out of frame */ const configure3dPlayerModelPosition = (this_3d_object) => { const camera_height = camera.position.y this_3d_object.position.x = helpers.randNum(-400, 400) this_3d_object.position.y = Math.random() * 400 + 800 + camera_height this_3d_object.position.z = helpers.randNum(-400, 400) this_3d_object.rotation.x = 180 this_3d_object.rotation.z = helpers.randNum(0, 360) this_3d_object.doubleSided = true; return (this_3d_object) } const addPlayerToQueue = (player_object) => { player_queue.push(player_object) count += 1 } /* Main function for creating 3D video meshes; asynchronously creates video DOM element, then the 3d model, then finally adds it to the queue of completed 3D video meshes */ const createNextVideoObject = () => { createVideoClipElement() .then(video_clip_element => create3dPlayerModel(video_clip_element)) .then(player_3d_object => addPlayerToQueue(player_3d_object)) } /* Triggers the playing of the next 3D video mesh objedt, called in time from startMainTrackInterval() */ const activateNextVideoObject = () => { const next_object = player_queue.shift() next_object['video_clip']['element'].play() scene.add(next_object['object']) createNextVideoObject() } const createGroundMaterial = () => { const material = new THREE.MeshBasicMaterial({ color: 0x000000, side: THREE.DoubleSide }) const physics_material = Physijs.createMaterial(material, 1, 0) const ground_material = Physijs.createMaterial(new THREE.MeshLambertMaterial({ map: THREE.ImageUtils.loadTexture('./img/tile.png') }), 1, 0) ground_material.map.wrapS = THREE.RepeatWrapping ground_material.map.wrapT = THREE.RepeatWrapping ground_material.map.repeat.set(100, 100) const ground = new Physijs.BoxMesh(new THREE.CubeGeometry(10000, 10, 10000), ground_material, 0) // 1 == mass ground.position.y = -100 return (ground) } const loadGroundModel = (scene) => { const loader = new THREE.GLTFLoader() loader.load('./models/untitled_seperated_pink.glb', (gltf) => { const materials = [] const players_mesh = gltf.scene.children[1] var material = new THREE.MeshBasicMaterial({ color: 0xffffff, transparent: true, opacity: 0 }) const object = new Physijs.BoxMesh(players_mesh.children[0].geometry, material, 0) players_mesh.children[0].material = new THREE.MeshBasicMaterial({ color: 0x999999 }) object.rotation.x = Math.PI / 2 scene.add(object) scene.add(gltf.scene) }, (xhr) => { if (xhr.loaded % xhr.total == 0) { // Once this model has loaded, activate the start button in main.js after waiting 1500ms. setTimeout(function () { activateStartButton() }, 1500) } }, (error) => { console.log(error) console.log('Error loading model') } ) } /* Worker for the camera, which slowly rotates around the scene while rising upwards */ const startWorker = () => { camera_angle_worker.addEventListener('message', function (e) { const data = e.data camera.position.x = data.x if (data.y) { camera.position.y = data.y } camera.position.z = data.z }, false) } /* Main track loop; a new piece of the composition is introduced every bar, as assigned on line 7 */ export const startMainTrackInterval = () => { setInterval(function () { // To keep sense of musical pace, only drop object is it is first bar, or from then on if bar count is divisible by two if (bar_counter == 1 || ((bar_counter % 2 !== 0))) { activateNextVideoObject() }; bar_counter += 1 }, one_bar) activateNextVideoObject() } /* Scene init function */ export const initThreeWorld = () => { scene.setGravity(new THREE.Vector3(0, -500, 0)) scene.add(createGroundMaterial()) scene.add(new THREE.AmbientLight(0xffffff)) renderer.setPixelRatio(window.devicePixelRatio / 1) renderer.setSize(container.offsetWidth, container.offsetHeight) container.appendChild(renderer.domElement) createNextVideoObject() loadGroundModel(scene) startWorker() } const animate = () => { camera_angle_worker.postMessage({ x: camera.position.x, y: camera.position.y, z: camera.position.z }) camera.lookAt(scene.position) renderer.render(scene, camera) requestAnimationFrame(animate) scene.simulate() } animate()
Python
UTF-8
8,425
2.6875
3
[ "MIT" ]
permissive
##ELECTRONICS SHOP MANAGEMENT SYSTEM## ##MAIN.py## import sys from datetime import datetime import mysql.connector as a d=a.connect(host='localhost',user='root',passwd='admin') e=d.cursor() e.execute('use ESMS;') print('WELCOME') def pg_1(): print('1_LOGIN') print('2_CREATE ID') print('3_VIEW USERS') print('4_EXIT') b=int(input('PLEASE ENTER OPTION:')) if b==1: login() elif b==2: cid() elif b==3: vu() elif b==4: sys.exit() else: print('##INVALID OPTION##') pg_1() def login(): b=input('Enter your username:') c=input('Enter your password:') e.execute('select Password from user where U_Name="{}";'.format(b)) f=e.fetchall() print(f) if f[0][0]==c: pg_2() else: print('##INCORRECT USERNAME OR PASSWORD##') print('##PLEASE RETRY##') login() def cid(): u=input('Enter username:') e.execute('select U_Name from user;') k=e.fetchall() e.execute('select count(U_Name) from user;') m=e.fetchall() j=int(m[0][0]) l=[] for i in range(0,j): o=list(k[0][i]) l=l+o if u in l : print('##USERNAME ALREADY EXISTS##') print('##PLEASE LOGIN##') pg_1() else: b=input('Enter password:') c=input('Enter your name:') f=eval(input('Enter your phone number:')) n=str(f) if 999999999<f<10000000000: com='insert into user values ("'+u+'","'+b+'","'+c+'",'+n+')' e.execute(com) d.commit() print('##PLEASE LOGIN TO CONTINUE##') login() else: print('##INVALID PHONE NUMBER##') print('##PLEASE RETRY##') cid() def vu(): e.execute('select Name,Ph_No from user;') f=e.fetchall() print(f) pg_1() def pg_2(): print('HELLO') print('1_BILLING') print('2_STOCK') print('3_LOGOUT') b=int(input('PLEASE ENTER OPTION:')) if b==1: bill() elif b==2: stock() elif b==3: pg_1() else: print('##INVALID OPTION##') pg_2() def bill(): e.execute('use BILLS;') m=datetime.now() z=m.strftime("%d%m%y_%H%M") e.execute('create table BILLED{}(Prod_ID varchar(10),Prod_Name varchar(30),Quantity int,Price int,Amount int)'.format(z)) newitem(z) def newitem(z): e.execute('use ESMS;') w=input('Enter product ID:') e.execute('select * from products where Prod_ID="{}";'.format(w)) y=e.fetchall() if y==[]: print('##Invalid Product ID##') print('##Please retry##') newitem(z) else: f=int(input('Enter Quantity:')) e.execute('select Quantity from products where Prod_ID="{}";'.format(w)) t=e.fetchall() num=int(t[0][0]) if num<f: print('##Insufficient Quantity##') print('Please try again') newitem(z) g=int(input('Are you sure?(YES=1\\NO=2):')) if g==1: e.execute('use BILLS;') e.execute('insert into BILLED{} values("{}","{}",{},{},{});'.format(z,w,y[0][1],f,y[0][3],f*y[0][3])) d.commit() e.execute('use ESMS;') e.execute('update products set Quantity=Quantity-{} where Prod_ID="{}";'.format(f,w)) k=int(input('Do you want to add more products?(YES=1\\NO=2')) if k==1: newitem(z) elif k==2: e.execute('use BILLS;') e.execute('select * from BILLED{};'.format(z)) print(e.fetchall()) e.execute('select sum(Amount) from BILLED{}'.format(z)) at=e.fetchall() am=at[0][0] print('Total Amount is '+str(am)) print('Thanks.....Come Again') e.execute('use esms;') pg_2() else: print('##Invalid option##') print('##Please retry##') newitem(z) elif g==2: newitem() else: print('##Invalid option##') print('##Please retry##') newitem() def stock(): print('1_VIEW') print('2_EDIT') print('3_BACK') z=int(input('Enter choice:')) if z==1: view() if z==2: edit() if z==3: pg_2() def edit(): print('1_ADD') print('2_MODIFY') print('3_DELETE') print('4_BACK') z=int(input('Enter choice:')) if z==1: add() if z==2: modi() if z==3: dele() if z==4: stock() def view(): e.execute('select * from products;') print(e.fetchall()) stock() def add(): z=input('Enter Product ID:') e.execute('select * from products where Prod_ID = "{}";'.format(z)) v=e.fetchall() if v!=[]: print('##Product ID already Exists##') print('##Please Retry##') add() else: z=z y=input("Enter Product name:") x=input('Enter Quantity:') w=input('Enter Price:') e.execute('insert into products values("{}","{}",{},{});'.format(z,y,x,w)) d.commit() e.execute('select * from products;') print(e.fetchall()) print('Sucessfully Added') edit() def dele(): z=input('Enter product ID to be deleted:') e.execute('select * from products where Prod_ID = "{}";'.format(z)) v=e.fetchall(); if v!=[]: print(v) x=int(input('Are you sure to delete this entry?(YES 1/NO 0):')) if x==1: e.execute('delete from products where Prod_ID ="{}";'.format(z)) d.commit() e.execute('select * from products;') print(e.fetchall()) print('Entry with Product ID ',z,' deleted sucessfully') else: print('No entries deleted') edit() else: print('No entries found...') print('##Please retry##') dele() def modi(): z=input('Enter product ID to be modified:') e.execute('select * from products where Prod_ID = "{}";'.format(z)) v=e.fetchall(); if v!=[]: print('1_Change product name:') print('2_Change price') print('3_Change Quantity') print('4_Back') x=int(input('Enter the option:')) if x==1: cpn(z) elif x==2: cp(z) elif x==3: cq(z) elif x==4: edit() else: print('Enter valid option...') modi() else: print('Invalid Product ID') modi() def cpn(ID): e.execute('select * from products where Prod_ID="{}";'.format(ID)) print(e.fetchall()) z=input('Enter new Product Name:') x=eval(input('Confirm Edit?(YES=1\\NO=2):')) if x==1: e.execute('update products set Prod_Name="{}" where Prod_ID = "{}";'.format(z,ID)) d.commit() e.execute('select * from products where Prod_ID="{}";'.format(ID)) print(e.fetchall()) print('Successfully updated') modi() else: modi() def cp(ID): e.execute('select * from products where Prod_ID="{}";'.format(ID)) print(e.fetchall()) z=int(input('Enter new Price:')) x=int(input('Confirm Edit?(YES=1\\NO=2):')) if x==1: e.execute('update products set Price={} where Prod_ID = "{}";'.format(z,ID)) e.execute('select * from products where Prod_ID="{}";'.format(ID)) d.commit(); print(e.fetchall()) print('Successfully updated') modi() else: modi() def cq(ID): e.execute('select * from products where Prod_ID="{}";'.format(ID)) print(e.fetchall()) z=int(input('Enter new Quantity:')) x=int(input('Confirm Edit?(YES=1\\NO=2):')) if x==1: e.execute('update products set Quantity={} where Prod_ID = "{}";'.format(z,ID)) e.execute('select * from products where Prod_ID="{}";'.format(ID)) print(e.fetchall()) d.commit() print('Successfully updated') modi() else: modi() pg_1()
Java
UTF-8
669
3.859375
4
[]
no_license
package com.springboot.study.streams.newstreams.repeat; import static com.springboot.study.streams.newstreams.repeat.Repeat.repeat; public class Looping { /** * 此方法再用方法引用时就类似实现了Runable接口 */ static void hi(){ System.out.println("Hi!"); } public static void main(String[] args) { //此时用Lambda表达式实现了Runable接口 repeat(3,() -> System.out.println("Looping")); //通过方法引用,使hi()方法类似于实现了Runable接口,因为该类中也只有一个方法,且方法参数和返回值与Runable接口一致 repeat(2,Looping::hi); } }