language
stringclasses
15 values
src_encoding
stringclasses
34 values
length_bytes
int64
6
7.85M
score
float64
1.5
5.69
int_score
int64
2
5
detected_licenses
listlengths
0
160
license_type
stringclasses
2 values
text
stringlengths
9
7.85M
Java
UTF-8
817
2.21875
2
[]
no_license
package com.progressoft.jip.social.messaging; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; @XmlRootElement(name = "post-result") @XmlAccessorType(XmlAccessType.FIELD) public class PostMessageResult { public static enum Status { SUCCESS, FAILED; } @XmlElement(name = "status", nillable = false) private Status status; @XmlElement(name = "details") private String details; public Status getStatus() { return status; } public void setStatus(Status status) { this.status = status; } public String getDetails() { return details; } public void setDetails(String details) { this.details = details; } }
JavaScript
UTF-8
5,448
2.515625
3
[ "BSD-3-Clause", "GPL-1.0-or-later", "LGPL-2.0-or-later", "Apache-2.0", "MIT" ]
permissive
/* * Copyright 2018 The Chromium Authors. All rights reserved. * Use of this source code is governed by a BSD-style license that can be * found in the LICENSE file. */ Sources.BreakpointEditDialog = class extends UI.Widget { /** * @param {number} editorLineNumber * @param {string} oldCondition * @param {boolean} preferLogpoint * @param {function({committed: boolean, condition: string})} onFinish */ constructor(editorLineNumber, oldCondition, preferLogpoint, onFinish) { super(true); this.registerRequiredCSS('sources/breakpointEditDialog.css'); this._onFinish = onFinish; this._finished = false; /** @type {?UI.TextEditor} */ this._editor = null; this.element.tabIndex = -1; const logpointPrefix = Sources.BreakpointEditDialog.LogpointPrefix; const logpointSuffix = Sources.BreakpointEditDialog._LogpointSuffix; this._isLogpoint = oldCondition.startsWith(logpointPrefix) && oldCondition.endsWith(logpointSuffix); if (this._isLogpoint) { oldCondition = oldCondition.substring(logpointPrefix.length, oldCondition.length - logpointSuffix.length); } this._isLogpoint = this._isLogpoint || preferLogpoint; this.element.classList.add('sources-edit-breakpoint-dialog'); const toolbar = new UI.Toolbar('source-frame-breakpoint-toolbar', this.contentElement); toolbar.appendText(`Line ${editorLineNumber + 1}:`); this._typeSelector = new UI.ToolbarComboBox(this._onTypeChanged.bind(this), ls`Breakpoint type`); this._typeSelector.createOption(ls`Breakpoint`, Sources.BreakpointEditDialog.BreakpointType.Breakpoint); const conditionalOption = this._typeSelector.createOption( ls`Conditional breakpoint`, Sources.BreakpointEditDialog.BreakpointType.Conditional); const logpointOption = this._typeSelector.createOption(ls`Logpoint`, Sources.BreakpointEditDialog.BreakpointType.Logpoint); this._typeSelector.select(this._isLogpoint ? logpointOption : conditionalOption); toolbar.appendToolbarItem(this._typeSelector); self.runtime.extension(UI.TextEditorFactory).instance().then(factory => { const editorOptions = {lineNumbers: false, lineWrapping: true, mimeType: 'javascript', autoHeight: true}; this._editor = factory.createEditor(editorOptions); this._updatePlaceholder(); this._editor.widget().element.classList.add('condition-editor'); this._editor.configureAutocomplete(ObjectUI.JavaScriptAutocompleteConfig.createConfigForEditor(this._editor)); if (oldCondition) { this._editor.setText(oldCondition); } this._editor.widget().markAsExternallyManaged(); this._editor.widget().show(this.contentElement); this._editor.setSelection(this._editor.fullRange()); this._editor.widget().focus(); this._editor.widget().element.addEventListener('keydown', this._onKeyDown.bind(this), true); this.contentElement.addEventListener('blur', event => { if (event.relatedTarget && !event.relatedTarget.isSelfOrDescendant(this.element)) { this._finishEditing(true); } }, true); }); } /** * @param {string} condition * @return {string} */ static _conditionForLogpoint(condition) { return `${Sources.BreakpointEditDialog.LogpointPrefix}${condition}${Sources.BreakpointEditDialog._LogpointSuffix}`; } _onTypeChanged() { const value = this._typeSelector.selectedOption().value; this._isLogpoint = value === Sources.BreakpointEditDialog.BreakpointType.Logpoint; this._updatePlaceholder(); if (value === Sources.BreakpointEditDialog.BreakpointType.Breakpoint) { this._editor.setText(''); this._finishEditing(true); } } _updatePlaceholder() { const selectedValue = this._typeSelector.selectedOption().value; if (selectedValue === Sources.BreakpointEditDialog.BreakpointType.Conditional) { this._editor.setPlaceholder(ls`Expression to check before pausing, e.g. x > 5`); this._typeSelector.element.title = ls`Pause only when the condition is true`; } else if (selectedValue === Sources.BreakpointEditDialog.BreakpointType.Logpoint) { this._editor.setPlaceholder(ls`Log message, e.g. 'x is', x`); this._typeSelector.element.title = ls`Log a message to Console, do not break`; } } /** * @param {boolean} committed */ _finishEditing(committed) { if (this._finished) { return; } this._finished = true; this._editor.widget().detach(); let condition = this._editor.text(); if (this._isLogpoint) { condition = Sources.BreakpointEditDialog._conditionForLogpoint(condition); } this._onFinish({committed, condition}); } /** * @param {!Event} event */ async _onKeyDown(event) { if (isEnterKey(event) && !event.shiftKey) { event.consume(true); const expression = this._editor.text(); if (event.ctrlKey || await ObjectUI.JavaScriptAutocomplete.isExpressionComplete(expression)) { this._finishEditing(true); } else { this._editor.newlineAndIndent(); } } if (isEscKey(event)) { this._finishEditing(false); } } }; Sources.BreakpointEditDialog.LogpointPrefix = '/** DEVTOOLS_LOGPOINT */ console.log('; Sources.BreakpointEditDialog._LogpointSuffix = ')'; Sources.BreakpointEditDialog.BreakpointType = { Breakpoint: 'Breakpoint', Conditional: 'Conditional', Logpoint: 'Logpoint', };
Python
UTF-8
3,794
3.375
3
[ "Apache-2.0" ]
permissive
from typing import List from overrides import overrides from allennlp.data.tokenizers.token import Token from allennlp.data.tokenizers.tokenizer import Tokenizer from allennlp.data.tokenizers.word_filter import WordFilter, PassThroughWordFilter from allennlp.data.tokenizers.word_splitter import WordSplitter, SpacyWordSplitter from allennlp.data.tokenizers.word_stemmer import WordStemmer, PassThroughWordStemmer @Tokenizer.register("word") class WordTokenizer(Tokenizer): """ A ``WordTokenizer`` handles the splitting of strings into words as well as any desired post-processing (e.g., stemming, filtering, etc.). Note that we leave one particular piece of post-processing for later: the decision of whether or not to lowercase the token. This is for two reasons: (1) if you want to make two different casing decisions for whatever reason, you won't have to run the tokenizer twice, and more importantly (2) if you want to lowercase words for your word embedding, but retain capitalization in a character-level representation, we need to retain the capitalization here. Parameters ---------- word_splitter : ``WordSplitter``, optional The :class:`WordSplitter` to use for splitting text strings into word tokens. The default is to use the ``SpacyWordSplitter`` with default parameters. word_filter : ``WordFilter``, optional The :class:`WordFilter` to use for, e.g., removing stopwords. Default is to do no filtering. word_stemmer : ``WordStemmer``, optional The :class:`WordStemmer` to use. Default is no stemming. start_tokens : ``List[str]``, optional If given, these tokens will be added to the beginning of every string we tokenize. end_tokens : ``List[str]``, optional If given, these tokens will be added to the end of every string we tokenize. """ def __init__(self, word_splitter: WordSplitter = None, word_filter: WordFilter = PassThroughWordFilter(), word_stemmer: WordStemmer = PassThroughWordStemmer(), start_tokens: List[str] = None, end_tokens: List[str] = None) -> None: self._word_splitter = word_splitter or SpacyWordSplitter() self._word_filter = word_filter self._word_stemmer = word_stemmer self._start_tokens = start_tokens or [] # We reverse the tokens here because we're going to insert them with `insert(0)` later; # this makes sure they show up in the right order. self._start_tokens.reverse() self._end_tokens = end_tokens or [] @overrides def tokenize(self, text: str) -> List[Token]: """ Does whatever processing is required to convert a string of text into a sequence of tokens. At a minimum, this uses a ``WordSplitter`` to split words into text. It may also do stemming or stopword removal, depending on the parameters given to the constructor. """ words = self._word_splitter.split_words(text) return self._filter_and_stem(words) @overrides def batch_tokenize(self, texts: List[str]) -> List[List[Token]]: batched_words = self._word_splitter.batch_split_words(texts) return [self._filter_and_stem(words) for words in batched_words] def _filter_and_stem(self, words: List[Token]) -> List[Token]: filtered_words = self._word_filter.filter_words(words) stemmed_words = [self._word_stemmer.stem_word(word) for word in filtered_words] for start_token in self._start_tokens: stemmed_words.insert(0, Token(start_token, 0)) for end_token in self._end_tokens: stemmed_words.append(Token(end_token, -1)) return stemmed_words
Python
UTF-8
2,166
3.265625
3
[]
no_license
import time from Adafruit_LED_Backpack import AlphaNum4 #I guess I got the tempProbe class form Adafruit. Don't really remember, but I sure didn't write it myself import tempProbe #This is for the relay stuff, which probably won't work anyway so who cares. #import RPi.GPIO as GPIO #GPIO.setmode(GPIO.BCM) #Create an instance of the 14-segment LED Backpack thing, and also the temperature probe dealie display = Alphanum4.ALphaNum4() probe = tempProbe.tempProbe() #Have to run the display thing once, and also going to clean up the GPIO crap. Makes sure it's set to off initially. #I think 22 is the bottom plug and 27 is the top plug. Only need one for now; no heater. Ignoring 27 I guess. display.begin() #GPIO.cleanup() #GPIO.setup(22, GPIO.OUT) #GPIO.setup(27, GPIO.OUT) #GPIO.output(22, GPIO.LOW) #GPIO.output(27, GPIO.LOW) #Variables I might use below tempF = 0 tempstr = "" + tempF while True: #Get the temperature tempF = probe.read_tempF() tempstr = "" + tempF #This parts prints the temp in degrees F on the stupid LED thing. Wrote this way so it's right-aligned? #I doubt this is a good way to do it or whether it even works. who cares. if tempF >= 100: display.clear() display.print_number_str(tempF[0:4]) elif tempF <= 10: display.clear() display.print_number_str(" " + tempf[0:2]) else: display.clear() display.print_number_str(" " + tempF[0:3]) display.write_display() #This part actually controls the temperature? It SHOULD flip the relay and turn the cooler on if the beer temp # gets above 74. Again, I doubt this even works who cares. #if tempF > 74: # GPIO.output(22, GPIO.HIGH) #elif tempF < 70: # GPIO.output(22, GPIO.LOW) #Ideally, I'd want to set this to check multiple times. One reading of 74 could be a fluke (especially given #how shitty the probe was when i tested it.) I'd want it to stay off until it gets 6-10 readings above 74. #Similarly, it shouldn't kick off until it reads below 70 several times. Doubt what I have works anyway so who cares. #Pause before the loop. No need to update everything all that frequently. time.sleep(1)
C++
UTF-8
301
2.796875
3
[]
no_license
#ifndef _SINGLETON_ #define _SINGLETON_ template<class T> class Singleton { Singleton( const Singleton& ); Singleton& operator=( const Singleton& ); protected: Singleton() {} virtual ~Singleton() {} public : static T& instance() { static T instance; return instance; } }; #endif
Markdown
UTF-8
3,502
2.890625
3
[]
no_license
+++ title = "Tentang Blog dan Mengapa" date = "2017-06-24T20:47:30+07:00" tags = [ "editorial" ] draft = false +++ Blog ini adalah sebuah pencapaian baru untuk saya. Seperti sebuah pencapaian yang lainnya, saya ingin membagikannya kepada para pembaca. Dua bulan dalam masa pembuatan blog ini, saya belajar banyak hal. Yang paling saya ingat adalah membuat sesuatu yang berurusan dengan Internet itu sangat merepotkan. Saya bertanya pada diri saya sendiri, "Mengapa membuat Blog?" Di saat banyak orang yang beralih melakukan *Video Blog* (Vlog), mengapa saya ingin menulis sesuatu? Jawabannya selalu saja saya merasa karya tulis seperti blog ini lebih dapat diterima dan diapresiasi dengan baik. ![Typing Blog](https://source.unsplash.com/o7BP1GRKk1s/720x405) Bulat tekad saya, saya mulai mencari bagaimana sih membuat blog sendiri, dengan nama domain sendiri (nama domain saya keren, kan?) :smile:. Ternyata membuat blog sendiri dan mengaturnya sendiri itu sulit. Hal yang paling menyulitkan mungkin adalah keinginan saya untuk memiliki alamat surel dengan domain sendiri juga. Di bulan pertama, saya menghabiskan 300 ribu rupiah untuk pembelian domain `yurizal-san.com` dan juga penyewaan VPS (*Virtual Private Server*) dengan sistem operasi Linux. Saya belajar mengatur VPS saya sendiri, mengatur *Web Server*, dan mengatur DNS supaya VPS saya dapat diakses dari lautan Internet. Hal yang paling mudah hanyalah saya tidak asing dengan sistem operasi berbasis Linux, tapi saya juga tidak tahu apa-apa tentang Linux dalam server. Saya merasa VPS bukanlah untuk saya, karena banyak hal kecil seperti pengaturan keamanan VPS yang saya belum bisa memahaminya. Lagipula situs yang saya buat juga merupakan situs yang statis dan tidak perlu melakukan banyak proses. Karena itu di bulan kedua saya berganti mencari layanan yang bisa menyimpan file HTML saya, dan menampilkannya ke Internet. ![Jangan menyerah](https://source.unsplash.com/XzUMBNmQro0/720x405) Ingat dengan keinginan saya yang ingin memiliki alamat surel dengan domain sendiri? Saya melihat tentang penyedia layanan surel [Fastmail](https://www.fastmail.com/) dari sebuah seri blog yang diterbitkan oleh [DuckDuckGo](https://duckduckgo.com/). Fastmail adalah penyedia layanan surel berbayar yang memberikan banyak fitur dan tidak menampilkan iklan. Hal ini, beserta keinganan saya untuk berhenti berketergantungan dengan penyedia layanan besar seperti Google, membuat saya dengan mudahnya memilih Fastmail. Lalu, apa hubungannya dengan Blog ini? Untuk menggunakan domain sendiri, saya harus membayar paket penggunaan Fastmail seharga $5 USD (sebenarnya ada sesi percobaan 30 hari). Saat saya melihat keuntungan lainnya dari Fastmail, saya melihat bahwa Fastmail dapat membuat *website* dari kumpulan file HTML statis. Bingo! Saya langsung membuat file HTML sederhana untuk mencoba fitur tersebut. Hanya dengan kata *"Hello World"* dalam file percobaan tersebut, saya berseru kegirangan karena dapat mengaksesnya di `www.yurizal-san.com/` pada waktu itu. Karena membuat HTML sendiri itu melelahkan, saya akhirnya memilih menggunakan *Static Site Generator* bernama [Hugo](http://gohugo.io/) untuk membantu saya. Mungkin lain kali saya akan membuat blog tentang Hugo. Itu adalah perjalanan saya dalam membangun Blog ini, mungkin tidak terlalu menarik. Tapi keinginan saya membuat blog adalah berbagi cerita dengan orang lain. Sebelum berakhir jangan lupa untuk [mensubskripsi](http://yurizal-san.com/index.xml) blog ini. *Adiós!*
Java
UTF-8
962
3.375
3
[ "MIT" ]
permissive
package com.BitJunkies.RTS.src; public class Timer{ private int framesToWait; private int actualFrame; private boolean active; private int fps; public Timer(int fps){ this.active = false; this.fps = fps; } //setup method to start the timer public void setUp(double seconds){ //calculating the frames to wait framesToWait = (int)Math.floor(seconds * fps); actualFrame = 0; active = true; } //done waiting method to ask the timer if the time is up public boolean doneWaiting(){ //updating the frames actualFrame ++; //checking if we reached the desired frame if(actualFrame >= framesToWait){ active = false; return true; } return false; } public boolean isActive(){ return active; } public float getPercentage(){ return (float) actualFrame / framesToWait; } }
PHP
UTF-8
2,455
2.59375
3
[]
no_license
<?php namespace Hongyukeji\PhpSms\Gateways; use Hongyukeji\PhpSms\Gateways\Gateway; use GuzzleHttp\Psr7; use GuzzleHttp\Client; use GuzzleHttp\Exception\RequestException; use Psr\Http\Message\ResponseInterface; /** * 云之讯短信 * @version v1.0 * @see http://docs.ucpaas.com/doku.php * * Class YunzhixunGateway * @package Hongyukeji\PhpSms\Gateways */ class YunzhixunGateway extends Gateway { const REQUEST_HOST = 'https://open.ucpaas.com'; const REQUEST_SINGLE_URI = '/ol/sms/sendsms'; const REQUEST_MANY_URI = '/ol/sms/sendsms_batch'; const REQUEST_TIMEOUT = 0; protected $config; protected $sid; protected $token; protected $appid; public function __construct($config) { parent::__construct($config); $this->sid = $config['sid']; $this->token = $config['token']; $this->appid = $config['appid']; } public function send($mobile_number, $template_code, $template_params) { $request_url = self::REQUEST_HOST . self::REQUEST_SINGLE_URI; $form_params = [ 'sid' => $this->sid, 'token' => $this->token, 'appid' => $this->appid, 'mobile' => $mobile_number, 'templateid' => $template_code, 'param' => implode(',', $template_params), ]; $headers = []; // 多个手机号码,群发处理 if (is_array($mobile_number)) { $request_url = self::REQUEST_HOST . self::REQUEST_MANY_URI; $form_params['mobile'] = implode(',', $mobile_number); } try { $client = new Client(); $response = $client->request('POST', $request_url, [ 'form_params' => $form_params, 'headers' => $headers, 'verify' => false, 'timeout' => self::REQUEST_TIMEOUT, ]); $result = \Hongyukeji\PhpSms\Sms::formatResponse($response); } catch (RequestException $e) { $result = \Hongyukeji\PhpSms\Sms::formatResponse($e->getResponse()); } if ($result['code'] == '0' || $result['code'] == '000000') { return \Hongyukeji\PhpSms\Sms::result(\Hongyukeji\PhpSms\Constants\SmsConstant::SMS_STATUS_SUCCESS); } else { return \Hongyukeji\PhpSms\Sms::result(\Hongyukeji\PhpSms\Constants\SmsConstant::SMS_STATUS_FAIL, $result['message'], $result); } } }
TypeScript
UTF-8
1,321
3.5
4
[]
no_license
export class HashGuard<T> { private data: { [key: string]: T }; public constructor( public lenght: number = 10, public chars: string = 'ASDFGQWERTZXCVBYUIOPHJKLNMasdfgqwertzxcvbyuiophjklnm0123456789' ) { this.data = {}; } public generate(): string { var tr = ''; do { tr = this.genOne(); } while (this.data[tr]); return tr; } private genOne(): string { var tr = ''; for (var i = 0; i < this.lenght; i++) { tr += this.chars[Math.floor(Math.random() * this.chars.length)]; } return tr; } public set(key: string, item: T): void { if (this.data[key]) { throw 'Invalid key!'; } this.data[key] = item; } public aset(item: T): string { let key = this.generate(); this.set(key, item); return key; } public get(key: string): T { return this.data[key]; } public has(key: string): boolean { return !!this.data[key]; } public delete(key: string): T { let tr = this.data[key]; delete this.data[key]; return tr; } public toList(): Array<T> { return Object .keys(this.data) .map(e => this.data[e]); } }
Markdown
UTF-8
11,944
3.046875
3
[]
no_license
--- layout: post title: "类型定义转换组件props描述文档" author: "Qizheng Han" --- 维护组件库的过程总是充满惊喜的。 但有时候随着频繁的操作一些流程内的东西,会发现很多低效的事情。 今天想说一下的,就是在开发组件的同时,必不可少的一步 - 编写组件说明文档。 而编写文档中,特别特别特别繁琐的一件事就是 编写 props 说明表格。 # 什么是 props 说明表格? 这里就拿 `ant-design` 里面的 props 说明来看一下。 ![](/assets/img/2022-12-28/props.png) > 图片源于:https://ant.design/components/breadcrumb-cn 对,就是这个,每次在维护文档的时候都要写,是一件繁琐且需要细心的事情。 # 可以可以自动生成呢? 其实有遇到过一些可以自动生成 props 说明文档的框架,很好奇怎么实现的。 至少说明一件事情,答案一定可以的。 # 类型定义 首先,组件库得是 `TypeScript` 写的。 类型的定义没有什么可以展开说的,如果不是特别了解 TS 建议先学习一下再来这里~ ```ts interface BreadcrumbProps { prefixCls?: string; routes?: Route[]; params?: any; separator?: React.ReactNode; itemRender?: ( route: Route, params: any, routes: Array<Route>, paths: Array<string>, ) => React.ReactNode; style?: React.CSSProperties; className?: string; children?: React.ReactNode; } ``` > 代码段来自:https://github.com/ant-design/ant-design/blob/master/components/breadcrumb/Breadcrumb.tsx # 解析类型 自动生成文档的第一步,就是要解析组件的类型定义,能够识别出哪个是 prop 的名字,哪个是 prop 对应的类型。 这个涉及到`语法解析`。靠自己来造轮子有点太复杂了,如果时间允许可以研究,既然现在是想提效,那就借助一下3方库`typedoc`。 这个库可其实很强大,可以直接生成具体类型的描述网页,仅需运行即可。 但是因为组件库一般都有自己的官方网站,我们需要的只是解析出来的信息。这里我选择了 json 数据结构 ## 入口 typedoc 需要一个入口配置,告诉它从哪里开始查找类型,解析类型。 默认是自动寻找`tsconfig.json`中的配置,但是 **每个组件都有自己所属的文件夹,类型文件又都在每个具体的文件夹中,所以入口就变成多个了**。 typedoc 如果在项目中 找到了 `typedoc.json` 这个文件,则会`优先`按照这个文件的配置来 ```json // typedoc.json { "entryPoints": ["./src/index.ts", "./src/secondary-entry.ts"], "out": "doc" } ``` 多入口给 `entryPoints` 传递一个数组即可。 wait wait 胃特 胃 难不成我得手动维护这个配置文件?有新的组件加一个入口? 拒绝! ## 自动生成typedoc.json `typedoc.json` 这个配置文件,其实就 2 个配置,一个入口,一个出口。 入口是存在动态改变的可能性,那我们就去动态读目录,获取所有组件的文件夹,拼接好入口数组即可 这个需要的先决条件: - 存放组件的若干文件夹在一个特定的目录下。 (栗子中是 lib/components) - 每一个组件需要构建文档的类型在特定文件内定义。 (栗子中选择了 type.ts) ```js async function generateTypeJsonFile() { const COMPONENT_DIR_PATH = `${ROOT_PATH}/lib/components`; try { const files = await fs.readdirSync(COMPONENT_DIR_PATH); const tempEntryPoints = []; // 构建typedoc需要的多入口 for (const file of files) { const isExistTypeFile = await fs.existsSync(`${COMPONENT_DIR_PATH}/${file}/type.ts`); if (isExistTypeFile) { tempEntryPoints.push(`"lib/components/${file}/type.ts"`); } else { console.log(`[ ${file} ] 没有找到对应类型文件,请检查。\n`); } } // 将构建好的配置内容写入文件 await fs.writeFileSync( './typedoc.json', ['{', ` "entryPoints": [${tempEntryPoints.join(', ')}],`, ' "out": "type-docs"', '}'].join('\n') ); } catch (err) { console.error(err); return '读取组件文档失败!'; } } ``` ## 生成类型描述的 json 文件 这个在配置好配置文件之后很简单,只需要运行命令 ``` $ npx typedoc --json [typedoc.json path] ``` 这个也要自动化运行 ```js shell.exec(`npx typedoc --json ${TYPE_JSON_DOC_PATH}`); ``` 会得到一个类型描述的json文件,类似下面这样 ```json { "id": 8, "name": "Separator", "kind": 4194304, "kindString": "Type alias", "flags": {}, "sources": [ { "fileName": "packages/sugar-design/lib/components/Breadcrumb/type.ts", "line": 13, "character": 12 } ], "type": { "type": "union", "types": [ { "type": "reference", "typeArguments": [ { "type": "query", "queryType": { "type": "reference", "name": "BUILT_IN_SEPARATOR" } } ], "name": "ValueOf", "qualifiedName": "ValueOf", "package": "type-fest" }, { "type": "reference", "name": "React.ReactNode", "qualifiedName": "React.ReactNode", "package": "@types/react" } ] } } ``` ## 读取描述 json 文件 读取 json 文件是整个环节里最重要,也是主要的开发量。 读取,其实就是解析,TS的所有类型写法都会以一种不同的type来展示 ```ts const TYPE_MAP = { // 基础类型 INTRINSIC: 'intrinsic', // 定义一个对象的具体类型(暂时这么认为) REFLECTION: 'reflection', // 引用别的类型 REFERENCE: 'reference', // 联合类型 UNION: 'union', // 交叉类型 INTERSECTION: 'intersection', // 数组 ARRAY: 'array', // 条件类型 CONDITIONAL: 'conditional', }; ``` 通过递归去解析拼凑字符串 ```js function propTypeIdentify(argumentType) { if (argumentType.type === ARGUMENT_TYPE.INTRINSIC) { /** * 基础类型 */ return argumentType.name; } else if (argumentType.type === ARGUMENT_TYPE.LITERAL) { /** * 字面量类型 * type A = 'a' / interface Test { a: true; b: '11'; c: 12 } 等 */ return argumentType.value; } else if (argumentType.type === ARGUMENT_TYPE.REFERENCE) { /** * 类型引用 */ return argumentType.name; } else if (argumentType.type === ARGUMENT_TYPE.UNION) { /** * 联合类型 */ return argumentType?.types?.map((type) => propTypeIdentify(type)); } else if (argumentType.type === ARGUMENT_TYPE.QUERY) { /** * TODO: 暂时理解成ValueOf类似的第三方包提供的范型 */ return `${argumentType.name}\\<typeof ${argumentType?.queryType?.name}\\>`; } else if (argumentType.type === ARGUMENT_TYPE.REFLECTION && argumentType?.declaration?.children) { /** * 对象类型 */ const objectType = argumentType?.declaration?.children?.map( // 这里因为数据结构与props的reflection类型数据结构相同,直接复用 (typeItem) => `${typeItem.name}: ${propTypeIdentify(typeItem)}` ); return `{ ${objectType.join(', ')} }`; } else if (argumentType.type === ARGUMENT_TYPE.REFLECTION && argumentType?.declaration?.signatures) { /** * 函数类型 */ const params = argumentType?.declaration?.signatures?.[0]?.parameters?.map( (param) => `${param.name}: ${propTypeIdentify(param)}` ); const returnType = argumentType?.declaration?.signatures?.[0]?.type?.name; return `\\(${params ? params?.join(', ') : ''}\\) => ${returnType}`; } else if (argumentType.type === ARGUMENT_TYPE.ARRAY) { /** * 数组类型 */ return `${simpleTypeObjectIdentify(argumentType?.elementType)}\\[\\]`; } else { return 'TestArgument'; } } ``` # 拼凑 然后,我们解析出的每一个类型都会被拼接成字符串 ```js // 类型文档拼接 function typeDocConcat(componentTypeJson) { let typeDocTemplate = []; const templateHeader = ['| 参数 | 说明 | 类型 | 必填 | 默认值 |', '| ----- | ------ | ------ | ---- | ------ |']; for (const componentType of componentTypeJson?.children || []) { if (canBuildDoc(componentType)) { typeDocTemplate.push(`\n### ${componentType.name}\n`); // interface类型 if (componentType.kindString === TYPE_DEFINITION_WAY.INTERFACE) { const resultString = reflectionTypeStringConcat(componentType.children || []); typeDocTemplate.push(...templateHeader, ...resultString); } else if ( componentType.kindString === TYPE_DEFINITION_WAY.TYPE && componentType?.type?.type === TYPE_MAP.REFERENCE ) { // type 方式定义的类型引用场景 (type A = B) typeDocTemplate.push(`\n请参考${componentType?.type?.name}`); } else if ( componentType.kindString === TYPE_DEFINITION_WAY.TYPE && componentType?.type?.type === TYPE_MAP.REFLECTION ) { /** * type 方式定义的对象类型 * type A = { a: string; b: number }; */ const resultString = reflectionTypeStringConcat(componentType?.type?.declaration?.children || []); typeDocTemplate.push(...templateHeader, ...resultString); } else if ( componentType.kindString === TYPE_DEFINITION_WAY.TYPE && componentType?.type?.type === TYPE_MAP.INTERSECTION ) { /** * type 方式定义的交叉类型 * type A = B & C; */ typeDocTemplate.push(...templateHeader); componentType?.type?.types.forEach((aliasItem) => { if (aliasItem.type === TYPE_MAP.REFLECTION) { const resultString = reflectionTypeStringConcat(aliasItem?.declaration?.children || []); typeDocTemplate.push(...resultString); } else if (aliasItem.type === TYPE_MAP.REFERENCE) { typeDocTemplate.push( `|${aliasItem.name}| 请参考 ${aliasItem.name} 组成交叉类型 | ${aliasItem.name} | - | - |` ); } }); } else if ( componentType.kindString === TYPE_DEFINITION_WAY.TYPE && componentType?.type?.type === TYPE_MAP.UNION ) { /** * type 方式定义的联合类型 * type A = B | C; */ componentType?.type?.types.forEach((aliasItem) => { typeDocTemplate.push(...templateHeader); if (aliasItem.type === TYPE_MAP.REFLECTION) { const resultString = reflectionTypeStringConcat(aliasItem?.declaration?.children || []); typeDocTemplate.push(...resultString); } else if (aliasItem.type === TYPE_MAP.REFERENCE) { typeDocTemplate.push( `|${aliasItem.name}| 请参考 ${aliasItem.name} 组成联合类型 | ${aliasItem.name} | - | - |` ); } }); } } } } ``` # 结果 拼凑的字符串会被写入特定文件 ```md ### BreadcrumbProps | 参数 | 说明 | 类型 | 必填 | 默认值 | | ----- | ------ | ------ | ---- | ------ | |activeId|activeId|T|否|-| |className|className|string|否|-| |clickLastOption|当前节点是否可以点击(仅影响末尾节点,对手动active节点无效)|boolean|否|-| |onChange|onChange|\(id: T, event: MouseEvent\<HTMLElement, MouseEvent\>\) => void|否|-| |options|options|BreadcrumbItem\[\]|否|-| |separator|自定义分隔符|Separator|否|-| |size|size|BreadcrumbSize|否|-| |style|style|CSSProperties|否|-| |withEllipsis|withEllipsis|boolean|否|-| ### DefaultBreadcrumbProps | 参数 | 说明 | 类型 | 必填 | 默认值 | | ----- | ------ | ------ | ---- | ------ | |separator|separator|Separator|是|-| |size|size|BreadcrumbSize|是|-| ``` 这样就大功告成了。 # 参考 - [typedoc](https://typedoc.org/)
Java
UTF-8
3,272
2.6875
3
[]
no_license
package com.demo.repository; import com.demo.entity.Employee; import com.demo.util.MongoDbConnectionUtil; import com.mongodb.MongoClient; import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCollection; import com.mongodb.client.model.Filters; import org.bson.Document; import org.bson.types.ObjectId; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class EmployeeDAO { public static final String COLLECTION_NAME = "Employee"; private MongoClient mongoClient; private List<Employee> findAllEmployees() { List<Employee> employees = new ArrayList<>(); MongoClient mongoClient = null; try { mongoClient = MongoDbConnectionUtil.getMongoClient(); MongoCollection<Document> collectionEmployee = MongoDbConnectionUtil.getMongoCollection(mongoClient, COLLECTION_NAME); FindIterable<Document> documents = collectionEmployee.find(); Iterator<Document> it = documents.iterator(); while (it.hasNext()) { employees.add(getDocumentMapper(it.next())); } } catch (Exception e) { e.printStackTrace(); } finally { if (mongoClient != null) { mongoClient.close(); } } return employees; } private Employee findOneByFullName(String fullName) { Employee employee = null; try { MongoCollection<Document> collectionEmployee = MongoDbConnectionUtil.getMongoCollection(COLLECTION_NAME); FindIterable<Document> documents = collectionEmployee.find(Filters.eq("Full_Name", fullName)); Iterator<Document> it = documents.iterator(); if (it.hasNext()) { employee = getDocumentMapper(it.next()); } } catch (Exception e) { e.printStackTrace(); } finally { } return employee; } private Employee getDocumentMapper(Document doc) { Employee employee = null; employee = new Employee( //doc.getLong("_id"), null, doc.getString("Emp_No"), doc.getString("Full_Name"), doc.getDate("Hire_Date") ); return employee; } private Document getDocumentFromEmployee(Employee employee) { Document doc = new Document(); doc.put("_id", new ObjectId().toString()); doc.put("Emp_No", new ObjectId().toString()); doc.put("Full_Name", employee.getFullName()); doc.put("Hire_Date", employee.getHireDate()); return doc; } private Long insertEmployee(Employee employee) { try { MongoCollection<Document> collectionEmployee = MongoDbConnectionUtil.getMongoCollection(COLLECTION_NAME); collectionEmployee.insertOne(getDocumentFromEmployee(employee)); } catch (Exception e) { e.printStackTrace(); } finally { } return 1L; } public static void main(String[] args) { // MongoClient mongoClient = getMongoClient(); // // get list db names // for (String databaseName : mongoClient.listDatabaseNames()) { // System.out.println(databaseName); // } // mongoClient.close(); //List<Employee> employees = findAllEmployees(); //Employee e = new Employee(null, null, "sonthh", new Date()); //insertEmployee(e); EmployeeDAO dao = new EmployeeDAO(); Employee employee = dao.findOneByFullName("sonthh"); System.out.println(""); } }
JavaScript
UTF-8
323
2.921875
3
[ "MIT" ]
permissive
/** * Simple Assertion function * @param {anything} test Anything that will evaluate to true of false. * @param {string} message The error message to send if `test` is false */ function kotoAssert(test, message) { if (test) { return; } throw new Error(`[koto] ${message}`); } export default kotoAssert;
C++
UTF-8
383
2.78125
3
[]
no_license
#ifndef DECK_H #define DECK_H #include "data_structures.h" class Deck { public: // Initializes deck in order and full Deck(); // Refills deck and shuffles it void shuffle(); // draws num_cards cards std::deque<card_t> draw(int num_cards); // draws one card card_t draw(); private: std::deque<card_t> cards; void reset(); }; #endif
Java
UTF-8
924
1.617188
2
[]
no_license
package io.zjl.checkinout0531.controller; import io.zjl.checkinout0531.api.WechatApi; import io.zjl.checkinout0531.api.WechatMPSNSApi; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * @Author:meng * @Date:2019/5/300851 * @description */ @RestController @RequestMapping("/temp") public class TempController { @Autowired private WechatMPSNSApi wechatMPSNSApi; @Autowired private WechatApi wechatApi; @GetMapping("/token") public void test_token(){ //wechatApi.getTicket("22_akhV5itjD1zwmXFuS0ODidmbv03qfFVx62D-UzwfsVpqz5RSFZgk7V9SdRw3GNXGucLMBCjk_fwTFjxVDXWbyrErq2S2RIQdBTSzKNG4sibGHBJcMLuL0cWrrG_3kqUP6wLipXczZ6_oCJ5iUXOeAFAYBS","jsapi"); wechatApi.getUserInfo("aaa","vvvv","zh"); //JSONObject userAccessToken = wechatMPSNSApi.getUserAccessToken(appId, appSecret, code, WechatConstant.AUTHORIZATION_CODE); } }
Markdown
UTF-8
1,735
3.21875
3
[]
no_license
# mentalnote MentalNote is a simple command line program for entering messages that will be stored in a Slack group. The messages of the group can be retrieved by using the -l option. ### Usage ### ``` $ mentalnote -h ``` MentalNote will show you the help text. ``` $ mentalnote ``` MentalNote will let you enter a multi line message. Input is terminated by Ctrl-D or an . on a single line. ``` $ mentalnote -m "TEXT MESSAGE" ``` The string TEXT MESSAGE will be stored. ``` $ mentalnote -l ``` A listing of (at the moment) all messages will be displayed. ### Set up ### * Clone this repository * Create a configuration file, `~/.mn.json`, and enter the following: * `api-token`, the token generated by Slack for your team. * `channel-id`, the identifier (not name) for the channel to use. * `username`, an optional name to display on the posts. Bot is the default. * `icon-url`, an optional URL to the avatar icon used for the messages. The config file can be overridden by setting the environment variable `MENTALNOTE_CONFIG`. ### Building ### * Run "go build mn.go" to create the executable file * mn for Unix systems * mn.exe for Windows ### Running ### Make sure there is a correct config.json file in the current working directory. ### Binary Versions ### If you are lucky you might find a suitable binary in the download section. *Note:* You need a config.json file in the same directory as the executable. Copy the config.json.example and fill in your Slack parameters. ### Future ### Next up is to limit the content when running in list mode (-l). Now it returns all messages. Later, searching would be a nice feature. ### Contact ### Questions are welcome to [calle@upset.se](mailto:calle@upset.se)
PHP
UTF-8
5,825
2.6875
3
[]
no_license
<?php /** * wechat php test */ //define your token define("TOKEN", "dlwebs"); $wechatObj = new wechatCallbackapiTest(); //$wechatObj->valid(); $wechatObj->responseMsg(); class wechatCallbackapiTest { public function valid() { $echoStr = $_GET["echostr"]; //valid signature , option if($this->checkSignature()){ echo $echoStr; exit; } } public function responseMsg() { //get post data, May be due to the different environments $postStr = $GLOBALS["HTTP_RAW_POST_DATA"]; $this->logger($postStr); $this->logger("----------------------------!!!!!!!!!!!!!!!!!-----------------------"); // $re= $this->send_post('http://print.wx.dlwebs.com/wx.php',$postStr); $ch = curl_init('http://print.wx.dlwebs.com/wx.php'); curl_setopt($ch, CURLOPT_MUTE, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: text/xml')); curl_setopt($ch, CURLOPT_POSTFIELDS, "$postStr"); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $output = curl_exec($ch); curl_close($ch); $this->logger($output); echo $output ; exit; //extract post data if (!empty($postStr)){ $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA); $fromUsername = $postObj->FromUserName; $toUsername = $postObj->ToUserName; $keyword = trim($postObj->Content); $time = time(); $textTpl = "<xml> <ToUserName><![CDATA[%s]]></ToUserName> <FromUserName><![CDATA[%s]]></FromUserName> <CreateTime>%s</CreateTime> <MsgType><![CDATA[%s]]></MsgType> <Content><![CDATA[%s]]></Content> <FuncFlag>0</FuncFlag> </xml>"; if(!empty( $keyword )) { $msgType = "text"; $contentStr = "Welcome to wechat world!"; $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr); echo $resultStr; }else{ echo "Input something..."; } }else { echo ""; exit; } } private function checkSignature() { $signature = $_GET["signature"]; $timestamp = $_GET["timestamp"]; $nonce = $_GET["nonce"]; $token = TOKEN; $tmpArr = array($token, $timestamp, $nonce); sort($tmpArr, SORT_STRING); $tmpStr = implode( $tmpArr ); $tmpStr = sha1( $tmpStr ); if( $tmpStr == $signature ){ return true; }else{ return false; } } //日志记录 private function logger($log_content) { if(isset($_SERVER['HTTP_APPNAME'])){ //SAE sae_set_display_errors(false); sae_debug($log_content); sae_set_display_errors(true); }else if($_SERVER['REMOTE_ADDR'] != "127.0.0.1"){ //LOCAL $max_size = 10000; $log_filename = "log.xml"; if(file_exists($log_filename) and (abs(filesize($log_filename)) > $max_size)){unlink($log_filename);} file_put_contents($log_filename, date('H:i:s')." ".$log_content."\r\n", FILE_APPEND); } } /** * 发送post请求 * @param string $url 请求地址 * @param array $post_data post键值对数据 * @return string */ public function send_post($url, $post_data) { $postdata = http_build_query($post_data); $options = array( 'http' => array( 'method' => 'POST', 'content' => $postdata, 'timeout' => 15 * 60 // 超时时间(单位:s) ) ); $context = stream_context_create($options); $result = file_get_contents($url, false, $context); return $result; } /** * Socket版本 * 使用方法: * $post_string = "app=socket&version=beta"; * request_by_socket('facebook.cn','/restServer.php',$post_string); */ function request_by_socket($remote_server, $remote_path, $post_string, $port = 80, $timeout = 30) { $socket = fsockopen($remote_server, $port, $errno, $errstr, $timeout); if (!$socket) die("$errstr($errno)"); fwrite($socket, "POST $remote_path HTTP/1.0\r\n"); fwrite($socket, "User-Agent: Socket Example\r\n"); fwrite($socket, "HOST: $remote_server\r\n"); fwrite($socket, "Content-type: application/x-www-form-urlencoded\r\n"); fwrite($socket, "Content-length: " . (strlen($post_string) + 8) . '\r\n'); fwrite($socket, "Accept:*/*\r\n"); fwrite($socket, "\r\n"); fwrite($socket, "mypost=$post_string\r\n"); fwrite($socket, "\r\n"); $header = ""; while ($str = trim(fgets($socket, 4096))) { $header .= $str; } $data = ""; while (!feof($socket)) { $data .= fgets($socket, 4096); } return $data; } } ?>
JavaScript
UTF-8
2,337
3.8125
4
[]
no_license
/* * @lc app=leetcode.cn id=1143 lang=javascript * * [1143] 最长公共子序列 * * https://leetcode-cn.com/problems/longest-common-subsequence/description/ * * algorithms * Medium (62.40%) * Likes: 540 * Dislikes: 0 * Total Accepted: 117.2K * Total Submissions: 187.8K * Testcase Example: '"abcde"\n"ace"' * * 给定两个字符串 text1 和 text2,返回这两个字符串的最长 公共子序列 的长度。如果不存在 公共子序列 ,返回 0 。 * * 一个字符串的 子序列 * 是指这样一个新的字符串:它是由原字符串在不改变字符的相对顺序的情况下删除某些字符(也可以不删除任何字符)后组成的新字符串。 * * * 例如,"ace" 是 "abcde" 的子序列,但 "aec" 不是 "abcde" 的子序列。 * * * 两个字符串的 公共子序列 是这两个字符串所共同拥有的子序列。 * * * * 示例 1: * * * 输入:text1 = "abcde", text2 = "ace" * 输出:3 * 解释:最长公共子序列是 "ace" ,它的长度为 3 。 * * * 示例 2: * * * 输入:text1 = "abc", text2 = "abc" * 输出:3 * 解释:最长公共子序列是 "abc" ,它的长度为 3 。 * * * 示例 3: * * * 输入:text1 = "abc", text2 = "def" * 输出:0 * 解释:两个字符串没有公共子序列,返回 0 。 * * * * * 提示: * * * 1 * text1 和 text2 仅由小写英文字符组成。 * * */ // @lc code=start /** * @param {string} text1 * @param {string} text2 * @return {number} */ var longestCommonSubsequence = function(text1, text2) { const dp = new Array(text1.length + 1).fill(0).map(() => new Array(text2.length + 1).fill(0)) if (!text1 || !text2) return 0 for (let i = 1; i <= text1.length; i++) { for (let j = 1; j <= text2.length; j++) { if (i === 0 && j === 0) { dp[i][j] = text1[i - 1] === text2[j - 1] ? 1 : 0 } else { dp[i][j] = text1[i - 1] === text2[j - 1] ? dp[i - 1][j - 1] + 1 : Math.max(dp[i - 1][j], dp[i][j - 1]) } } } return dp[text1.length][text2.length] }; // @lc code=end // console.log(longestCommonSubsequence("abcde", "ace" )) // console.log(longestCommonSubsequence("abc", "abc" )) // console.log(longestCommonSubsequence("abc", "def" ))
Markdown
UTF-8
596
2.859375
3
[]
no_license
# Controller Controllers allow you to communicate with external apps (Postman or front end etc). They use HTTP methods with specified return values, to do certain things when certain HTTP requests are sent GET PUT POST DELETE PATCH Requires use of @RestController above class # Tutorial Create a new class called demoController @RestController above class @GetMapping("/") method{ return "something" } Pasting this into the search will print some text http://localhost:8080/hello ## Exercise Create 2 different methods that returns a string when you paste the mapping in the url
Java
UTF-8
513
2.25
2
[]
no_license
package org.daum.library.fakeDemo.pojos; import java.util.ArrayList; import java.util.List; public class SitacModel { private List<Intervention> interventions = new ArrayList<Intervention>(); private List<InterventionType> interventionTypes = new ArrayList<InterventionType>(); public SitacModel() { } public List<Intervention> getInterventions() { return interventions; } public List<InterventionType> getInterventionTypes() { return interventionTypes; } }
Java
UTF-8
907
1.625
2
[ "Apache-2.0" ]
permissive
package net.openhft.chronicle.map.fromdocs.acid.revelations; import org.junit.Assert; //import static org.junit.jupiter.api.Assertions.*; import org.junit.*; public class ChronicleStampedLockTest { @Test public void tryOptimisticRead() { Assert.assertEquals(Boolean.TRUE, Boolean.TRUE); } @Test public void validate() { } @Test public void tryWriteLock() { } @Test public void tryReadLock() { } @Test public void writeLock() { } @Test public void readLock() { } @Test public void unlock() { } @Test public void unlockRead() { } @Test public void unlockWrite() { } @Test public void getReadLockCount() { } @Test public void isReadLocked() { } @Test public void offHeapLock() { } @Test public void offHeapLockReaderCount() { } }
C++
UTF-8
993
2.828125
3
[]
no_license
// 08/01/2020 #include<bits/stdc++.h> using namespace std; int t, n; deque<int> dq; bool fun(deque<int> dq, int st) { deque<int> dest; if (st==0) dest.push_back(dq.front()), dq.pop_front(); else dest.push_back(dq.back()), dq.pop_back(); while(!dq.empty()) { if(dq.front() == dest.front()-1) dest.push_front(dq.front()), dq.pop_front(); else if (dq.front() == dest.back()+1) dest.push_back(dq.front()), dq.pop_front(); else if(dq.back() == dest.front()-1) dest.push_front(dq.back()), dq.pop_back(); else if(dq.back() == dest.back()+1) dest.push_back(dq.back()), dq.pop_back(); else return false; } return true; } int main() { scanf("%d", &t); for (int T=1;T<=t;T++) { scanf("%d", &n); dq.clear(); for(int i=1,x;i<=n;i++) cin >> x, dq.push_back(x); printf("Case #%d: %s\n", T, (fun(dq, 0)||fun(dq, 1))? "yes":"no"); } }
Java
UTF-8
1,105
3.71875
4
[]
no_license
public class Solution451 { /* * 451. Sort Characters By Frequency: * Given a string, sort it in decreasing order based on the frequency of characters. * * Input: "tree", Output: "eert" * Input: "cccaaa", Output: "cccaaa" * Input: "Aabb", Output: "bbAa" */ public String frequencySort(String s){ if(s.length() < 3){ return s; } int max = 0; int[] map = new int[128]; for(char ch : s.toCharArray()){ map[ch]++; max = Math.max(max, map[ch]); } String[] buckets = new String[max + 1]; for(int i = 0; i < 128; i++){ String str = buckets[map[i]]; if(map[i] > 0){ buckets[map[i]] = (str == null) ? "" + (char)i : (str + (char) i); } } StringBuilder sb = new StringBuilder(); for(int i = max; i >= 0; i--){ if(buckets[i] != null){ for(char ch : buckets[i].toCharArray()){ for(int j = 0; j < i; j++){ sb.append(ch); } } } } return sb.toString(); } public static void main(String[] args){ String s = "aaacccc"; Solution451 res = new Solution451(); System.out.println(res.frequencySort(s)); } }
PHP
UTF-8
2,703
3.03125
3
[ "MIT" ]
permissive
<?php /* * This file is part of rg\broker. * * (c) ResearchGate GmbH <bastian.hofmann@researchgate.net> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace rg\broker\customizations; /** * This is just a small extension to the PHP supplied ZipArchive class. It adds * a recursive add function and the possibility to exclude directories. * * @author Baldur Rensch <baldur.rensch@hautelook.com> */ class ZipArchive extends \ZipArchive { /** * Array containing directory names to exclude * @var array */ protected $excludeDirectories = array(); /** * Contains the "base path" of the archive. This means that files will be * added relative to this base path, instead of with absolute paths. * @var string */ public $archiveBaseDir = ""; /** * Add directories recursively * * @param String $path */ public function addDir($path) { $archiveDirName = str_replace($this->archiveBaseDir, "", $path); if (!empty($archiveDirName)) { $this->addEmptyDir(ltrim($archiveDirName, "/")); } $nodes = glob($path . '/*'); foreach ($nodes as $node) { if (is_dir($node)) { foreach ($this->excludeDirectories as $dir) { if (strpos($node, $dir) !== false) { continue 2; } } $this->addDir($node); } else if (is_file($node)) { $archiveFileName = str_replace($this->archiveBaseDir . "/", "", $node); $this->addFile($node, $archiveFileName); } } } /** * Add a directory name to the list of directories to exclude * * @param [type] $dir [description] */ public function addExcludeDirectory($dir) { $this->excludeDirectories []= $dir; } /** * @return array */ public function getExcludeDirectories() { return $this->excludeDirectories; } /** * @param array $excludeDirectories * @return ZipArchive */ public function setExcludeDirectories(array $newExcludeDirectories) { $this->excludeDirectories = $newExcludeDirectories; return $this; } /** * @return String */ public function getArchiveBaseDir() { return $this->archiveBaseDir; } /** * @param String $archiveBaseDir * @return ZipArchive */ public function setArchiveBaseDir($newArchiveBaseDir) { $this->archiveBaseDir = $newArchiveBaseDir; return $this; } }
Java
UTF-8
4,053
1.929688
2
[ "MIT" ]
permissive
/** * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for * license information. * * Code generated by Microsoft (R) AutoRest Code Generator. */ package com.microsoft.azure.management.sql.v2014_04_01.implementation; import com.microsoft.azure.management.sql.v2014_04_01.BackupLongTermRetentionVault; import com.microsoft.azure.arm.model.implementation.CreatableUpdatableImpl; import rx.Observable; class BackupLongTermRetentionVaultImpl extends CreatableUpdatableImpl<BackupLongTermRetentionVault, BackupLongTermRetentionVaultInner, BackupLongTermRetentionVaultImpl> implements BackupLongTermRetentionVault, BackupLongTermRetentionVault.Definition, BackupLongTermRetentionVault.Update { private final SqlManager manager; private String resourceGroupName; private String serverName; private String crecoveryServicesVaultResourceId; private String urecoveryServicesVaultResourceId; BackupLongTermRetentionVaultImpl(String name, SqlManager manager) { super(name, new BackupLongTermRetentionVaultInner()); this.manager = manager; // Set resource name this.serverName = name; // } BackupLongTermRetentionVaultImpl(BackupLongTermRetentionVaultInner inner, SqlManager manager) { super(inner.name(), inner); this.manager = manager; // Set resource name this.serverName = inner.name(); // set resource ancestor and positional variables this.resourceGroupName = IdParsingUtils.getValueFromIdByName(inner.id(), "resourceGroups"); this.serverName = IdParsingUtils.getValueFromIdByName(inner.id(), "servers"); // } @Override public SqlManager manager() { return this.manager; } @Override public Observable<BackupLongTermRetentionVault> createResourceAsync() { BackupLongTermRetentionVaultsInner client = this.manager().inner().backupLongTermRetentionVaults(); return client.createOrUpdateAsync(this.resourceGroupName, this.serverName, this.crecoveryServicesVaultResourceId) .map(innerToFluentMap(this)); } @Override public Observable<BackupLongTermRetentionVault> updateResourceAsync() { BackupLongTermRetentionVaultsInner client = this.manager().inner().backupLongTermRetentionVaults(); return client.createOrUpdateAsync(this.resourceGroupName, this.serverName, this.urecoveryServicesVaultResourceId) .map(innerToFluentMap(this)); } @Override protected Observable<BackupLongTermRetentionVaultInner> getInnerAsync() { BackupLongTermRetentionVaultsInner client = this.manager().inner().backupLongTermRetentionVaults(); return client.getAsync(this.resourceGroupName, this.serverName); } @Override public boolean isInCreateMode() { return this.inner().id() == null; } @Override public String id() { return this.inner().id(); } @Override public String location() { return this.inner().location(); } @Override public String name() { return this.inner().name(); } @Override public String recoveryServicesVaultResourceId() { return this.inner().recoveryServicesVaultResourceId(); } @Override public String type() { return this.inner().type(); } @Override public BackupLongTermRetentionVaultImpl withExistingServer(String resourceGroupName, String serverName) { this.resourceGroupName = resourceGroupName; this.serverName = serverName; return this; } @Override public BackupLongTermRetentionVaultImpl withRecoveryServicesVaultResourceId(String recoveryServicesVaultResourceId) { if (isInCreateMode()) { this.crecoveryServicesVaultResourceId = recoveryServicesVaultResourceId; } else { this.urecoveryServicesVaultResourceId = recoveryServicesVaultResourceId; } return this; } }
Java
UTF-8
956
2.265625
2
[]
no_license
package a2.m.a.b; import android.util.Range; import com.otaliastudios.cameraview.engine.Camera2Engine; import java.util.Comparator; public class c implements Comparator<Range<Integer>> { public final /* synthetic */ boolean a; public c(Camera2Engine camera2Engine, boolean z) { this.a = z; } /* JADX DEBUG: Method arguments types fixed to match base method, original types: [java.lang.Object, java.lang.Object] */ @Override // java.util.Comparator public int compare(Range<Integer> range, Range<Integer> range2) { Range<Integer> range3 = range; Range<Integer> range4 = range2; if (this.a) { return (range3.getUpper().intValue() - range3.getLower().intValue()) - (range4.getUpper().intValue() - range4.getLower().intValue()); } return (range4.getUpper().intValue() - range4.getLower().intValue()) - (range3.getUpper().intValue() - range3.getLower().intValue()); } }
PHP
UTF-8
2,102
3.046875
3
[ "Beerware" ]
permissive
<?php /* * This part is a bit of a hack job. * Please don't hate me for it :D */ function list_issues_func(){ $url = "https://api.github.com/repos/finlaydag33k/Wordpress-Theme/issues"; // Hash the URL $cachetime = 300; // Cache expiry time in seconds $where = "cache"; // Directory for cache // Check if $where is a directory if ( ! is_dir($where)) { mkdir($where); } $hash = md5($url); // hash the url $file = "$where/$hash.cache"; // the complete cache location // check the bloody cache $mtime = 0; if (file_exists($file)) { $mtime = filemtime($file); } $filetimemod = $mtime + $cachetime; // if the renewal date is smaller than now, return true; else false (no need for update) if ($filetimemod < time()) { $ch = curl_init($url); curl_setopt_array($ch, array( CURLOPT_HEADER => FALSE, CURLOPT_RETURNTRANSFER => TRUE, CURLOPT_USERAGENT => "FinlayDaG33k Wordpress", CURLOPT_FOLLOWLOCATION => TRUE, CURLOPT_MAXREDIRS => 5, CURLOPT_CONNECTTIMEOUT => 15, CURLOPT_TIMEOUT => 30, )); $data = curl_exec($ch); curl_close($ch); // save the file if there's data, or else, do nothing if ($data) { file_put_contents($file, $data); // save cache to file } } else { $data = file_get_contents($file); // load up the cached file } // We can now display the issues $issues = json_decode($data,true); // load the issues from JSON into an array // check if the amount of issues is bigger than 0 if(count($issues) > 0){ // more than 0 issues have been found! $issuesList = "<ul>"; // loop through all issues foreach($issues as $issue => $value){ $issuesList .= "<li><a href=\"".htmlentities($value['html_url'])."\" target=\"_blank\">#".htmlentities($value['number'])."</a>: ".htmlentities($value['title'])." (by ".htmlentities($value['user']['login']).")</li>"; // add the issue to the list } $issuesList .= "</ul>"; return $issuesList; // return all issues }else{ // No issues have been found return "No issues found! (whoop!)"; } } add_shortcode( 'list_issues', 'list_issues_func' );
C
UTF-8
276
3
3
[]
no_license
#include<stdio.h> int main() { int i,j,m,n,s=1; printf("enter a number: "); scanf("%d",&n); for(i=1;i<=n;i++) { for(j=1;j<=i;j++) { printf("%d\t",s*s); s++; } printf("\n"); } return 0; }
Java
UTF-8
4,542
3.484375
3
[]
no_license
import edu.duke.*; import org.apache.commons.csv.*; public class Exports1 { public String countryInfo(CSVParser parser, String country){ for (CSVRecord record : parser) { String exports = record.get("Exports"); String value = record.get("Value (dollars)"); if (record.get("Country").contains(country)){ return (country+": "+exports+": "+value); } } return "NOT FOUND"; } public void listExportersTwoProducts(CSVParser parser, String exportItem1,String exportItem2){ /*Write a void method named listExportersTwoProducts that has three * parameters, parser is a CSVParser, exportItem1 is a String and * exportItem2 is a String. This method prints the names of all the * countries that have both exportItem1 and exportItem2 as export * items. For example, using the file exports_small.csv, this method * called with the items “gold” and “diamonds” would print the * countries Namibia South Africa */ for (CSVRecord record : parser) { String exports = record.get("Exports"); String country = record.get("Country"); if (record.get("Exports").contains(exportItem1) && record.get("Exports").contains(exportItem2) ){ System.out.println(country); } } } public int numberOfExporters(CSVParser parser, String exportItem){ /* Write a method named numberOfExporters, which has two parameters, parser is a CSVParser, and exportItem is a String. This method returns the number of countries that export exportItem. For example, using the file exports_small.csv, this method called with the item “gold” would return 3.*/ int exportNumber = 0; for (CSVRecord record : parser) { if (record.get("Exports").contains(exportItem)){ exportNumber++; } } //return number of countries that export exportItem return exportNumber; } public void bigExporters(CSVParser parser, String amount) { /*Write a void method named bigExporters that has two parameters, * parser is a CSVParser, and amount is a String in the format of a * dollar sign, followed by an integer number with a comma separator * every three digits from the right. An example of such a string * might be “$400,000,000”. * * This method prints the names of countries * and their Value amount for all countries whose Value (dollars) * string is longer than the amount string. * You do not need to parse * either string value as an integer, just compare the lengths of the * strings. For example, if bigExporters is called with the file * exports_small.csv and amount with the string $999,999,999, then * this method would print eight countries and their export values * shown here: Germany $1,547,000,000,000 Macedonia $3,421,000,000 Malawi $1,332,000,000 Malaysia $231,300,000,000 Namibia $4,597,000,000 Peru $36,430,000,000 South Africa $97,900,000,000 United States $1,610,000,000,000 */ for (CSVRecord record : parser) { String country = record.get("Country"); String value = record.get("Value (dollars)"); if (record.get("Country").contains(country)){ if (amount.length() < value.length()){ System.out.println(country+" "+value); } } } } public void tester(){ FileResource fr = new FileResource(); CSVParser parser = fr.getCSVParser(); //System.out.println(countryInfo(parser,"Nauru")); //listExportersTwoProducts(parser,"cotton","flowers"); //System.out.println(numberOfExporters(parser,"cocoa")); bigExporters(parser,"$999,999,999,999"); } public static void main (String[] args) { Exports1 e1 = new Exports1(); System.out.println("*** Program start... ***"); // e1.tester(); System.out.println("*** Program finish! ***"); } }
C#
UTF-8
2,346
2.875
3
[ "MIT-0", "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
using System.Collections; using System.Collections.Generic; using UnityEngine; /// <summary> /// A simple camera controller script. /// </summary> public class CameraController : MonoBehaviour { // Camera orbit parameters] private bool rotating = false; public float orbitSpeed = 1; private Vector3 lastMousePosition = Vector3.zero; private Vector3 lastLocalEulerAngles = Vector3.zero; // Camera move parameters public float moveSpeed = 1; private Vector3 moveDir = Vector3.zero; // Update is called once per frame void Update() { rotate(); move(); } /// <summary> /// Manage orbit style rotation using click-and-drag. /// </summary> private void rotate() { // Determine whether or not the camera is rotating if (!rotating) { if (Input.GetMouseButtonDown(0)) { rotating = true; lastLocalEulerAngles = transform.eulerAngles; lastMousePosition = Input.mousePosition; } } // If the camera is rotating if (rotating) { if (Input.GetMouseButtonUp(0)) { rotating = false; } { // Use mouseDelta to rotate camera Vector3 mouseDelta = Input.mousePosition - lastMousePosition; Vector3 eulerAnglesOffset = new Vector3(mouseDelta.y, -mouseDelta.x, 0); transform.eulerAngles = lastLocalEulerAngles + orbitSpeed * eulerAnglesOffset; } } } /// <summary> /// Manage movement using the W, S, A, and D keys. /// </summary> private void move() { if (Input.GetKey(KeyCode.W)) { moveDir = transform.forward; } else if (Input.GetKey(KeyCode.S)) { moveDir = -transform.forward; } else if (Input.GetKey(KeyCode.D)) { moveDir = transform.right; } else if (Input.GetKey(KeyCode.A)) { moveDir = -transform.right; } else { moveDir = Vector3.zero; } moveDir = Vector3.ProjectOnPlane(moveDir, Vector3.up); transform.position += moveSpeed * Time.deltaTime * moveDir; } }
PHP
UTF-8
252
3.0625
3
[]
no_license
<?php class Player { public function get_chosen_letter($letters_number, $letters) { $random_letter_index = rand(0, $letters_number -1); $chosen_letter = $letters[$random_letter_index]; return $chosen_letter; } }
PHP
UTF-8
1,521
3.03125
3
[]
no_license
<?php /** * splitString * * Divide string into multiple sections, based on a delimiter. * * If used as a regular snippet, each part is output to a separate placeholder. * * If used as output modifier, you need to specify the number of the part you * want to get. For example, if your string is: * * 'Ubuntu|300,700,300italic,700italic|latin' * * Then [[+placeholder:splitString=`1`]] will return 'Ubuntu'. * * @var modX $modx * @var array $scriptProperties * @var string $input * @var string $options */ $input = $modx->getOption('input', $scriptProperties, $input); $options = $modx->getOption('options', $scriptProperties, $options); $delimiter = $modx->getOption('delimiter', $scriptProperties, '|'); $prefix = $modx->getOption('prefix', $scriptProperties, 'snippet'); // Output filters are also processed when the input is empty, so check for that if ($input == '') { return ''; } // Break up the string $output = explode($delimiter,$input); $idx = 0; // If snippet is used as output modifier, return matching section if ($options) { return $output[$options - 1]; } // Process each section individually foreach ($output as $value) { $idx++; $modx->toPlaceholder($idx, trim($value), $prefix); // Additional first and last placeholders if ($idx == 1) { $modx->toPlaceholder('first', trim($value), $prefix); } $modx->toPlaceholder('last', trim($value), $prefix); } // Return placeholder with total idx $modx->toPlaceholder('total', $idx, $prefix); return '';
Swift
UTF-8
1,654
2.96875
3
[ "MIT" ]
permissive
// // SCNVector3+Codable.swift // Pods // // Created by Alexander Skorulis on 14/8/18. // import SceneKit extension SCNVector3: Codable { enum CodingKeys: String, CodingKey { case x case y case z } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(x, forKey: .x) try container.encode(y, forKey: .y) try container.encode(z, forKey: .z) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) let x = try values.decode(Float.self, forKey: .x) let y = try values.decode(Float.self, forKey: .y) let z = try values.decode(Float.self, forKey: .z) self.init(x, y, z) } public func jsonDict() -> [String:CGFloat] { return [CodingKeys.x.rawValue:CGFloat(x), CodingKeys.y.rawValue:CGFloat(y), CodingKeys.z.rawValue:CGFloat(z), ] } } extension vector_int2: Codable { enum CodingKeys: String, CodingKey { case x case y } public func encode(to encoder: Encoder) throws { var container = encoder.container(keyedBy: CodingKeys.self) try container.encode(x, forKey: .x) try container.encode(y, forKey: .y) } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) let x = try values.decode(Int32.self, forKey: .x) let y = try values.decode(Int32.self, forKey: .y) self.init(x, y) } }
Markdown
UTF-8
2,298
2.625
3
[ "Apache-2.0" ]
permissive
## Office Hours kOps maintainers set aside one hour every week for **public** office hours. This time is used to gather with community members interested in kOps. This session is open to both developers and users. The time and date for the office hours can be found in the [sig-cluster-lifecycle calendar](https://calendar.google.com/calendar/u/0/embed?src=u5822lrl4q68ic1iakuvcpe7b4@group.calendar.google.com). The office hourse are hosted in a [zoom video chat](https://zoom.us/j/97072789944?pwd=VVlUR3dhN2h5TEFQZHZTVVd4SnJUdz09). ### Regular office hours The regular office hours are typically more formal and tend to focus on discussons. They are typically recorded. ### Bonus meetings Since the regular office hours do not fit everyones schedule, kOps maintainers also host additional office hours with a more loose agenda. These are typically not recorded. ### Office Hours Topics We do maintain an [agenda](https://docs.google.com/document/d/12QkyL0FkNbWPcLFxxRGSPt_tNPBHbmni3YLY-lHny7E/edit) and stick to it as much as possible. If you want to hold the floor, put your item in this doc. Bullet/note form is fine. Even if your topic gets in late, we do our best to cover it. Our office hours call is recorded, but the tone tends to be casual. First-timers are always welcome. Typical areas of discussion can include: - Contributors with a feature proposal seeking feedback, assistance, etc - Members planning for what we want to get done for the next release - Strategizing for larger initiatives, such as those that involve more than one sig or potentially more moving pieces - Help wanted requests - Demonstrations of cool stuff. PoCs. Fresh ideas. Show us how you use kOps to go beyond the norm- help us define the future! Office hours are designed for ALL of those contributing to kOps or the community. Contributions are not limited to those who commit source code. There are so many important ways to be involved: - helping in the slack channels - triaging/writing issues - thinking about the topics raised at office hours and forming and advocating for your good ideas forming opinions - testing pre-(and official) releases Although not exhaustive, the above activities are extremely important to our continued success and are all worth contributions. If you want to talk about kOps and you have doubt, just come.
JavaScript
UTF-8
6,308
2.5625
3
[]
no_license
import React, { useState, useEffect, useCallback } from "react" import Box from "@material-ui/core/Box" import { DragDropContext } from 'react-beautiful-dnd' import PlayerInfo from "./PlayerInfo" import Splay from "./Splay" import PassTarget from "./PassTarget" import ActionBar from "./ActionBar" import Hand0 from "./Hand0" function insertIntoArray(array, value, index) { const a = Array.from(array) a.splice(index, 0, value) return a } function reorderArray(array, source_index, dest_index) { const a = Array.from(array) const [removed] = a.splice(source_index, 1) a.splice(dest_index, 0, removed) return a } function swapWithArray(array, index, card) { const a = Array.from(array) if (card) { a[index] = card } else { a.splice(index, 1) } return a } export default function Player0({gameState, socket}) { const [ hand, setHand ] = useState(Array.from(gameState.players[0].hand)) const [ selection, setSelection ] = useState({}) const [ passLeft, setPassLeft ] = useState('') const [ passAcross, setPassAcross ] = useState('') const [ passRight, setPassRight ] = useState('') const deselectCards = useCallback((cards) => { let newSelection = {...selection} cards.forEach(card => delete newSelection[card]) setSelection(newSelection) }, [selection]) // reconcile hand state with the server const server_cards = Array.from(gameState.players[0].hand) useEffect(() => { let client_cards = [...hand] if (passLeft) client_cards.push(passLeft) if (passAcross) client_cards.push(passAcross) if (passRight) client_cards.push(passRight) // new hand, probably (or back 6, which I want to be sorted into the existing 8) if (server_cards.some(card => !client_cards.includes(card))) { setHand(server_cards) setSelection({}) setPassLeft('') setPassAcross('') setPassRight('') console.log('refreshed hand from server') return } // cards passed or played. remove them from the hand, keeping the player's dragged order intact const extra_cards = client_cards.filter(card => !server_cards.includes(card)) if (extra_cards.length) { console.log(`reconciling client cards: removing ${extra_cards.length} extra cards`) if (extra_cards.includes(passLeft)) setPassLeft('') if (extra_cards.includes(passAcross)) setPassAcross('') if (extra_cards.includes(passRight)) setPassRight('') setHand(hand.filter(card => !extra_cards.includes(card))) deselectCards(extra_cards) } }, [server_cards]) const onDragEnd = ({source, destination, draggableId}) => { if (!destination) { return } // reorder if (destination.droppableId === source.droppableId) { switch(destination.droppableId) { case 'hand': setHand(reorderArray(hand, source.index, destination.index)) break } return } // hoo boy, this is in dire need of refactoring // but the behavior I want (swapping an existing card in the pass area with the source) is not exactly trivial switch(destination.droppableId) { case 'hand': switch(source.droppableId) { case 'passLeft': setPassLeft('') break case 'passAcross': setPassAcross('') break case 'passRight': setPassRight('') break } setHand(insertIntoArray(hand, draggableId, destination.index)) break case 'passLeft': switch(source.droppableId) { case 'hand': setHand(swapWithArray(hand, source.index, passLeft)) break case 'passAcross': setPassAcross(passLeft) break case 'passRight': setPassRight(passLeft) break } setPassLeft(draggableId) break case 'passAcross': switch(source.droppableId) { case 'hand': setHand(swapWithArray(hand, source.index, passAcross)) break case 'passLeft': setPassLeft(passAcross) break case 'passRight': setPassRight(passAcross) break } setPassAcross(draggableId) break case 'passRight': switch(source.droppableId) { case 'hand': setHand(swapWithArray(hand, source.index, passRight)) break case 'passLeft': setPassLeft(passRight) break case 'passAcross': setPassAcross(passRight) break } setPassRight(draggableId) break } } const toggleSelect = useCallback((card) => { if (gameState.state === 'playing') { let newSelection = {...selection} if (newSelection[card]) { delete newSelection[card] } else { newSelection[card] = 1 } setSelection(newSelection) } }, [gameState.state, selection]) const selectCards = useCallback((cards) => { let newSelection = {} cards.forEach((card) => { newSelection[card] = 1 }) setSelection(newSelection) }, [selection]) return <div className='player0' style={{display: 'flex', alignItems: 'flex-end'}}> <div style={{flexGrow: 1}}/> <PlayerInfo data={gameState.players[0]} turn={gameState.turn === 0} trickWinner={gameState.trick_winner === 0 || gameState.dealer === 0}/> <Box width={5} height={5}/> <DragDropContext onDragEnd={onDragEnd}> <div style={{display: 'flex', flexDirection: 'column-reverse'}}> <Hand0 hand={hand} selection={selection} toggleSelect={toggleSelect}/> <ActionBar gameState={gameState} socket={socket} cards={Object.keys(selection)} passLeft={passLeft} passAcross={passAcross} passRight={passRight} selectCards={selectCards}/> { gameState.state === 'passing' ? (gameState.players[0].passed_cards ? <Splay vertical={false} align='left' size={3} angle={120} flip={true}/> : ((gameState.players[0].hand_size === 14) ? <PassTarget passLeft={passLeft} passAcross={passAcross} passRight={passRight}/> : null)) : null } </div> </DragDropContext> <div style={{flexGrow: 1}}/> </div> }
C++
UTF-8
417
2.546875
3
[]
no_license
/* * PointQueue.h * * Created on: 15 Jul 2015 * Author: cameron */ #ifndef VISION_POINTQUEUE_H_ #define VISION_POINTQUEUE_H_ class PointQueue { private: int *xArray; int *yArray; int maxSize; int start, end; int length; public: PointQueue(int initSize); virtual ~PointQueue(); void append(int x, int y); int getX(); int getY(); void pop(); int size(); }; #endif /* VISION_POINTQUEUE_H_ */
Python
UTF-8
1,127
3.796875
4
[]
no_license
# Programa que realiza diversos cálculos, para isso criamos várias funções #Separar em arquivos diferentes # Para que um scrip consiga enxergar o outro, utilizamos o comando (import) # Dois ou mais arquivos que estão na mesma página, se enxeguem, um podendo acessar o conteúdo do outro from calculadora import * # Este código está fora da função op = -1 while op!=5: print("1 - Somar dois valores ") print("2 - Subtrair dois valores ") print("3 - Dividir dois valores ") print("4 - Multiplicar dois valores ") print("5 - Sair ") op = int(input("Digite sua opção! ")) if (op == 1): print(somar(float(input("Digite o primeiro valor")) , float(input("Digite o segundo valor")))) elif (op == 2): print(subtrair(float(input("Digite o primeiro valor")) , float(input("Digite o segundo valor")))) elif (op == 3): print(dividir(float(input("Digite o primeiro valor")), float(input("Digite o segundo valor")))) elif (op == 4): print(multiplicar(float(input("Digite o primeiro valor")), float(input("Digite o segundo valor"))))
Python
UTF-8
95
2.875
3
[]
no_license
s = raw_input(">>>> ").split(" ") j = sorted(set(s)) for sent in j: print "".join(sent),
Java
UTF-8
444
1.992188
2
[]
no_license
package com.zjezyy.entity.im; import lombok.Data; @Data public class TMessage { public TMessage(String groupname,String telephone, String message) { this.groupname=groupname; this.telephone = telephone; this.message = message; } private int id; private String groupname; private String telephone; private String message; private String credate; private String flagerr;//发送失败 0成功 其他失败 }
Java
UTF-8
1,148
2.03125
2
[]
no_license
package com.dbware.mysql.filter; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.handler.codec.frame.FrameDecoder; import com.dbware.listener.PubVars; import com.dbware.mysql.packet.HeaderPacket; /** * @Copyright 2012-2013 donnie(donnie4w@gmail.com) * @date 2012-12-7 * @verion 1.0 */ public class Decoder extends FrameDecoder { private volatile int length = 0; private PubVars vars; public Decoder(PubVars vars) { this.vars = vars; } @Override protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer) throws Exception { if (length == 0 && buffer.readableBytes() < 4) { return null; } if (length == 0) { byte[] headBytes = new byte[4]; buffer.readBytes(headBytes); HeaderPacket head = new HeaderPacket(); head.putBytes(headBytes); length = head.getLength(); vars.setSequenceId(head.getSequenceId()); } if (buffer.readableBytes() < length) { return null; } byte[] decoded = new byte[length]; buffer.readBytes(decoded); length = 0; return decoded; } }
C
UTF-8
1,215
3.296875
3
[]
no_license
#include<stdlib.h> #include<stdio.h> #include<string.h> /* Design an efficient algorithm to find all anagrams in a dictionary file EX: 1)ate = tea = eat 2)conversation = voice rants on */ char * sort(char * a) { int n = strlen(a); for(int i = 0; i < n; i++) { for(int j = 0; j < n-1; j++) { if(a[j]>a[j+1]) { int temp = a[j+1]; a[j+1] = a[j]; a[j] = temp; } } } return a; } int strmatch(char * f , char * b) { int n= strlen(f); for(int i = 0; i<n; ++i) { if(f[i] != b[i]) return 0; } return 1; } void anagram(char *str,char a[][1000]) { int n= strlen(str); for(int i = 0;i<6; ++i) { int m = strlen(a[i]); if(m == n) { char c[n]; strcpy(c,a[i]); char * f = sort(str); char * b = sort(c); int d = strmatch(f,b); if(d) printf("%s\n",a[i]); } } } int main() { char a[7][1000] = {"ate","eat","tea","dog","god","cat","act"}; char b[3][1000] = {"eat","dog"};//,"cat"}; int n = 3; for(int i = 0; i < n; ++i) { printf("\n%dst Anagram\n=============\n",i+1); anagram(b[i],a); } }
Java
UTF-8
918
2.375
2
[]
no_license
package ru.radom.kabinet.dto.news; import ru.askor.blagosfera.domain.listEditor.ListEditorItem; public class NewsListItemCategoryDto { public Long id; public String text; public NewsListItemCategoryDto parent; public NewsListItemCategoryDto() { } public static NewsListItemCategoryDto toDto(ListEditorItem listEditorItem) { NewsListItemCategoryDto result = new NewsListItemCategoryDto(); result.id = listEditorItem.getId(); result.text = listEditorItem.getText(); if (listEditorItem.getParent() != null) { result.parent = toDto(listEditorItem.getParent()); } return result; } public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getText() { return text; } public void setText(String text) { this.text = text; } }
Java
UTF-8
2,573
2.21875
2
[]
no_license
package cn.jungu009.mynews.ui; import android.database.Cursor; import android.os.AsyncTask; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.widget.LinearLayoutManager; import android.support.v7.widget.RecyclerView; import android.support.v7.widget.Toolbar; import android.view.MenuItem; import java.util.ArrayList; import java.util.List; import cn.jungu009.mynews.R; import cn.jungu009.mynews.adapter.NewsListAdapter; import cn.jungu009.mynews.dao.INewsDao; import cn.jungu009.mynews.dao.INewsDaoImpl; import cn.jungu009.mynews.model.News; public class FavoriteActivity extends AppCompatActivity { private RecyclerView favoriteList; private INewsDao newsDao; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); newsDao = new INewsDaoImpl(this); setContentView(R.layout.activity_favorite); initToolbar(); favoriteList = (RecyclerView)findViewById(R.id.favorite_list); new LoadFavoriteAsyncTask().execute(); } private void initToolbar() { Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); toolbar.setBackgroundColor(0xF00); toolbar.setContentInsetStartWithNavigation(0); setSupportActionBar(toolbar); ActionBar actionBar = getSupportActionBar(); if (actionBar != null) { actionBar.setDisplayHomeAsUpEnabled(true); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case android.R.id.home: this.finish(); break; default: break; } return true; } class LoadFavoriteAsyncTask extends AsyncTask<Void, Void, Void> { List<News> allNews = new ArrayList<>(); @Override protected Void doInBackground(Void... params) { Cursor newses = newsDao.queryAllNews(); while(newses.moveToNext()) { News news = new News(newses); allNews.add(news); } return null; } @Override protected void onPostExecute(Void v) { super.onPostExecute(v); favoriteList.setLayoutManager(new LinearLayoutManager(FavoriteActivity.this)); RecyclerView.Adapter adapter = new NewsListAdapter(allNews, null, FavoriteActivity.this); favoriteList.setAdapter(adapter); } } }
Rust
UTF-8
15,445
3.25
3
[]
no_license
use std::fmt; use std::fmt::Debug; use tui::buffer::{Buffer, Cell}; use tui::style::Style; #[derive(Clone)] pub struct Canvas { width: u16, cells: Vec<Cell>, line_full: bool, } impl Canvas { pub fn new(width: u16) -> Canvas { Canvas { width: width, cells: Vec::new(), line_full: false, } } pub fn width(&self) -> u16 { self.width } pub fn height(&self) -> u16 { self.cells.len() as u16 / self.width } #[cfg(test)] pub fn get_pos(&self, x: u16, y: u16) -> Option<&Cell> { self.get_index(x, y).and_then(|i| self.cells.get(i)) } pub fn add_string_wrapped(&mut self, string: &str, style: Style) { for chr in string.chars() { self.add_char(chr, style, true); } } pub fn add_string_truncated(&mut self, string: &str, style: Style) { for chr in string.chars() { self.add_char(chr, style, false); } } pub fn render_viewport(&self, viewport_options: ViewportOptions) -> Buffer { use tui::layout::Rect; let rect = Rect::new( viewport_options.rect_x, viewport_options.rect_y, self.width, viewport_options.height, ); let mut cells: Vec<Cell> = self .cells .iter() .skip(viewport_options.offset as usize * self.width as usize) .take(viewport_options.height as usize * self.width as usize) .map(Cell::clone) .collect(); cells.resize(rect.area() as usize, Cell::default()); Buffer { area: rect, content: cells, } } #[cfg(test)] pub fn render_to_string<'a>(&self, eol_marker: Option<&'a str>) -> String { let mut s = String::with_capacity(self.cells.len() + self.height() as usize); let mut total_chars = 0; let width = self.width as usize; for (i, chr) in self .cells .iter() .flat_map(|c| c.symbol.chars().next()) .enumerate() { if i > 0 && i % width == 0 { if let &Some(marker) = &eol_marker { s.push_str(marker); } s.push('\n'); } s.push(chr); total_chars += 1; } // File the last line with spaces. If a full line is needed, then we don't need to add // anything. let characters_left = width - (total_chars % width); if characters_left < width { for _ in 0..characters_left { s.push(' '); } } if let &Some(marker) = &eol_marker { s.push_str(marker); } s } #[cfg(test)] fn get_index(&self, x: u16, y: u16) -> Option<usize> { if x < self.width { let index = y as usize * self.width as usize + x as usize; if index < self.cells.len() { return Some(index); } } None } fn total_characters_on_last_line(&self) -> u16 { (self.cells.len() % self.width as usize) as u16 } fn add_char(&mut self, chr: char, style: Style, wrapping: bool) { match chr { '\n' => { // If line was full when a new line should start, treat it as normal wrapping and // just begin on the new line. // If the line was not full, complete it by adding whitespace. if self.line_full { self.line_full = false; } else { self.complete_line(style) } } '\r' => {} // TODO: Treat \t and \b differently. _ => { if self.line_full && wrapping { self.line_full = false; } if !self.line_full { self.add_cell(chr, style); self.line_full = self.total_characters_on_last_line() == 0; } } } } fn complete_line(&mut self, style: Style) { let remaining = self.width - self.total_characters_on_last_line(); for _ in 0..remaining { self.add_cell(' ', style); } self.line_full = false; } fn add_cell(&mut self, chr: char, style: Style) { let mut cell = Cell::default(); cell.set_char(chr).set_style(style); self.cells.push(cell); } } impl ::std::ops::AddAssign<Canvas> for Canvas { fn add_assign(&mut self, rhs: Canvas) { assert!( self.width == rhs.width, "Tried to add_assign (+=) two canvases with different width! LHS={}, RHS={}", self.width, rhs.width ); let mut rhs = rhs; self.cells.append(&mut rhs.cells); } } impl Debug for Canvas { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use std::fmt::Write; write!( f, "Canvas (width={}, height={})\n", self.width(), self.height() )?; for (i, cell) in self.cells.iter().enumerate() { if i > 0 && i as u16 % self.width == 0 { f.write_char('\n')?; } f.write_char(cell.symbol.chars().next().unwrap())?; } Ok(()) } } #[derive(Default, Debug, PartialEq, Clone, Copy, Eq)] pub struct ViewportOptions { height: u16, offset: u16, rect_x: u16, rect_y: u16, } #[allow(dead_code)] impl ViewportOptions { pub fn new(height: u16) -> Self { ViewportOptions { height, ..Default::default() } } pub fn with_height(mut self, height: u16) -> Self { self.height = height; self } pub fn with_offset(mut self, offset: u16) -> Self { self.offset = offset; self } pub fn with_rect_position(mut self, x: u16, y: u16) -> Self { self.rect_x = x; self.rect_y = y; self } } #[cfg(test)] mod tests { use super::*; use tui::layout::Rect; use tui::style::Color; fn cell(chr: char, style: Style) -> Cell { let mut cell = Cell::default(); cell.set_char(chr).set_style(style); cell } macro_rules! assert_eq_buffer { ($a:ident, $b:ident) => { match (&$a, &$b) { (ref a, ref b) => { use util::render_buffer; assert_eq!(a.area, b.area, "Expected buffer areas to be equal"); assert_eq!( a.content.len(), b.content.len(), "Expected buffer content sizes to be equal" ); if a.content != b.content { panic!( "Expected cells to be equal:\n{}\n\n-=-=-=-=-=-=-=-=-\n\n{}", render_buffer(a), render_buffer(b) ); } } } }; } #[test] fn it_writes_characters_to_grow() { let red = Style::default().bg(Color::Red); let green = Style::default().bg(Color::Green); let mut canvas = Canvas::new(3); assert_eq!(canvas.height(), 0); canvas.add_string_wrapped("Foobar", red); assert_eq!(&canvas.render_to_string(None), "Foo\nbar"); assert_eq!(canvas.height(), 2); assert_eq!(canvas.cells.len(), 6); canvas.add_string_truncated("\nGoodbye!", green); assert_eq!(&canvas.render_to_string(None), "Foo\nbar\nGoo"); assert_eq!(canvas.height(), 3); assert_eq!(canvas.cells.len(), 9); // Adding a newline means "fill rest of line with spaces", except when added to the end of // a full line. canvas.add_string_truncated("\n!\n", green); assert_eq!(canvas.height(), 4); assert_eq!(canvas.cells.len(), 9 + 1 + 2); assert_eq!( format!("{:?}", canvas), "Canvas (width=3, height=4)\nFoo\nbar\nGoo\n! ", ); assert_eq!(canvas.get_pos(0, 0), Some(&cell('F', red))); assert_eq!(canvas.get_pos(1, 0), Some(&cell('o', red))); assert_eq!(canvas.get_pos(0, 1), Some(&cell('b', red))); assert_eq!(canvas.get_pos(0, 2), Some(&cell('G', green))); assert_eq!(canvas.get_pos(3, 0), None); assert_eq!(canvas.get_pos(0, 8), None); assert_eq!(canvas.get_pos(3, 8), None); } #[test] fn it_continues_on_last_line() { let style = Style::default(); let mut canvas = Canvas::new(10); canvas.add_string_truncated("123", style); assert_eq!(canvas.render_to_string(None), "123 "); // Rest of line is cut off since it's the _truncated variant canvas.add_string_truncated("1234567890", style); assert_eq!(canvas.render_to_string(None), "1231234567"); // Keeps line truncated since we still have not added a newline. canvas.add_string_truncated("123", style); assert_eq!(canvas.render_to_string(None), "1231234567"); // Start a new line; the explicit "\n" breaks the line. canvas.add_string_truncated("\n123", style); assert_eq!(canvas.render_to_string(None), "1231234567\n123 "); // Start a new line with two calls work; the explicit "\n" will break the line for the next // call. canvas.add_string_truncated("\n", style); assert_eq!(canvas.render_to_string(None), "1231234567\n123 "); canvas.add_string_truncated("!!!", style); assert_eq!( canvas.render_to_string(None), "1231234567\n123 \n!!! " ); } #[test] fn it_wraps_existing_lines() { let style = Style::default(); let mut canvas = Canvas::new(10); canvas.add_string_wrapped("123", style); assert_eq!(canvas.render_to_string(None), "123 "); // Rest of line is wrapped since it's the _wrapped variant canvas.add_string_wrapped("1234567890", style); assert_eq!(canvas.render_to_string(None), "1231234567\n890 "); // Line is continued canvas.add_string_wrapped("123", style); assert_eq!(canvas.render_to_string(None), "1231234567\n890123 "); // Start a new line canvas.add_string_wrapped("\n123", style); assert_eq!( canvas.render_to_string(None), "1231234567\n890123 \n123 " ); // Ending line when line is full has no immediately visible effect canvas.add_string_wrapped("4567890\n", style); assert_eq!( canvas.render_to_string(None), "1231234567\n890123 \n1234567890" ); // but it is visible when continuiong on the line canvas.add_string_truncated("!", style); assert_eq!( canvas.render_to_string(None), "1231234567\n890123 \n1234567890\n! " ); } #[test] fn it_appends_canvases() { let mut top = Canvas::new(3); let mut bottom = Canvas::new(3); let style = Style::default(); top.add_string_truncated("Foo", style); bottom.add_string_truncated("bar", style); top += bottom; assert_eq!(top.width(), 3); assert_eq!(top.height(), 2); } #[test] #[should_panic] fn it_panics_when_adding_different_widths() { let mut top = Canvas::new(3); let bottom = Canvas::new(5); top += bottom; } #[test] fn it_renders_into_tui_buffer_viewports() { let red = Style::default().fg(Color::Red); let green = Style::default().fg(Color::Green); let mut canvas = Canvas::new(6); canvas.add_string_wrapped("Foobar------", green); canvas.add_string_wrapped("Here I am", red); // Render top let render_options = ViewportOptions::new(2); let expected_rect = Rect::new(0, 0, 6, 2); let mut expected_buffer = Buffer::empty(expected_rect); expected_buffer.set_string(0, 0, "Foobar", &green); expected_buffer.set_string(0, 1, "------", &green); let top_viewport = canvas.render_viewport(render_options); assert_eq_buffer!(top_viewport, expected_buffer); // Render middle let render_options = ViewportOptions::new(2).with_offset(1); let expected_rect = Rect::new(0, 0, 6, 2); let mut expected_buffer = Buffer::empty(expected_rect); expected_buffer.set_string(0, 0, "------", &green); expected_buffer.set_string(0, 1, "Here I", &red); let middle_viewport = canvas.render_viewport(render_options); assert_eq_buffer!(middle_viewport, expected_buffer); // Render bottom part let render_options = ViewportOptions::new(3).with_offset(1); let expected_rect = Rect::new(0, 0, 6, 3); let mut expected_buffer = Buffer::empty(expected_rect); expected_buffer.set_string(0, 0, "------", &green); expected_buffer.set_string(0, 1, "Here I", &red); expected_buffer.set_string(0, 2, " am", &red); let bottom_viewport = canvas.render_viewport(render_options); assert_eq_buffer!(bottom_viewport, expected_buffer); // Rendering out-of-bounds is filled with spaces let render_options = ViewportOptions::new(5).with_offset(1); let expected_rect = Rect::new(0, 0, 6, 5); let mut expected_buffer = Buffer::empty(expected_rect); expected_buffer.set_string(0, 0, "------", &green); expected_buffer.set_string(0, 1, "Here I", &red); expected_buffer.set_string(0, 2, " am", &red); expected_buffer.set_string(0, 3, "", &Style::default()); // Only for expected_buffer.set_string(0, 4, "", &Style::default()); // illustration let out_of_bounds_viewport = canvas.render_viewport(render_options); assert_eq_buffer!(out_of_bounds_viewport, expected_buffer); // Rendering with an Rect x/y offset let render_options = ViewportOptions::new(2) .with_offset(1) .with_rect_position(15, 62); let expected_rect = Rect::new(15, 62, 6, 2); let mut expected_buffer = Buffer::empty(expected_rect); expected_buffer.set_string(15, 62, "------", &green); expected_buffer.set_string(15, 63, "Here I", &red); let rect_offset_viewport = canvas.render_viewport(render_options); assert_eq_buffer!(rect_offset_viewport, expected_buffer); } #[test] fn it_renders_to_string() { let mut canvas = Canvas::new(3); let style = Style::default(); canvas.add_string_wrapped("Foobar yay!", style); assert_eq!(&canvas.render_to_string(None), "Foo\nbar\n ya\ny! "); assert_eq!( &canvas.render_to_string(Some("|")), "Foo|\nbar|\n ya|\ny! |" ); let mut canvas = Canvas::new(10); canvas.add_string_wrapped("\n12345\n1234567890 67890\n", style); assert_eq!( &canvas.render_to_string(Some("|")), " | 12345 | 1234567890| 67890|" ); } }
Swift
UTF-8
2,667
2.84375
3
[]
no_license
// // ViewController.swift // chessKnight // // Created by Konstantinos Nikoloutsos on 9/12/20. // import UIKit class ViewController: UIViewController { @IBOutlet weak var chessSizeSlider: UISlider! @IBOutlet weak var chessSizeLabel: UILabel! @IBOutlet weak var startButton: UIButton! @IBOutlet weak var clearButton: UIButton! @IBOutlet weak var chessBoardUIView: ChessBoardUIView! lazy var presenter = ViewControllerPresenter(with: self) override func viewDidLoad() { super.viewDidLoad() chessBoardUIView.delegate = presenter let config = Configuration(sizeOfChessBoard: 8) chessBoardUIView.applyConfiguration(conf: config) presenter.initGame(conf: config) chessSizeSlider.value = 8 } @IBAction func onStartButtonPressed(_ sender: UIButton) { presenter.onStartButtonPressed() } @IBAction func onClearButtonPressed(_ sender: Any) { let config = Configuration(sizeOfChessBoard: 8) chessBoardUIView.applyConfiguration(conf: config) presenter.changeChessBoardConfiguration(conf: config) chessSizeSlider.value = 8 onChessSizeSliderValueChanged(chessSizeSlider) } @IBAction func onReconfigureButtonPressed(_ sender: Any) { let config = Configuration(sizeOfChessBoard: Int(chessSizeSlider.value)) chessBoardUIView.applyConfiguration(conf: config) presenter.changeChessBoardConfiguration(conf: config) } @IBAction func onChessSizeSliderValueChanged(_ sender: UISlider) { let value = Int(sender.value) chessSizeLabel.text = "N = \(value)" } } extension ViewController : ViewControllerPresenterView{ func showPathFound(pathList: [Path]) { let storyboard = UIStoryboard(name: "Main", bundle: nil) let pathDisplayVC = storyboard.instantiateViewController(withIdentifier: "pathDisplayVC") as!PathsDisplayViewController pathDisplayVC.pathsToBeShown = pathList navigationController?.pushViewController(pathDisplayVC, animated: true) } func showNoPathFound() { let alert = UIAlertController(title: "Oups no paths found", message: "Tip: try again by dragging the pieces into other squares", preferredStyle: UIAlertController.Style.alert) alert.addAction(UIAlertAction(title: "Got it", style: UIAlertAction.Style.default, handler: nil)) self.present(alert, animated: true, completion: nil) } func reRenderChessBoard() { chessBoardUIView.setNeedsDisplay() } }
PHP
UTF-8
711
2.703125
3
[]
no_license
<?php /* * ZFE – платформа для построения редакторских интерфейсов. */ /** * Укоротитель текста до определенного размера. */ class ZFE_View_Helper_ShortenText extends Zend_View_Helper_Abstract { /** * Укоротить текст до определенного размера. * * @param string $text исходный текст * @param int $max_len максимальная длина * * @return string сокращенный текст */ public function shortenText($text, $max_len = 100) { return ZFE_Utilities::shortenText($text, $max_len); } }
Java
UTF-8
3,270
2.859375
3
[]
no_license
package edu.uiuc.cs.cs425.mp1.server.delivery; import edu.uiuc.cs.cs425.mp1.data.Message; import edu.uiuc.cs.cs425.mp1.server.OperationalStore; import static edu.uiuc.cs.cs425.mp1.util.ServerUtils.incrementMap; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import java.util.*; /** * class that handles Causally ordered messages */ public class CausalDeliverer extends Deliverer { private static final Logger logger = LogManager.getLogger(CausalDeliverer.class.getName()); private final List<Message> holdbackQueue = new LinkedList<>(); @Override protected void handleMessage(Message m) { synchronized (OperationalStore.INSTANCE.vectorClock) { if (m.isDirectMessage()) { deliverMessage(m); return; } //get vector clock from shared memory Map<Integer, Integer> currentVectorClock = OperationalStore.INSTANCE.getVectorClock(); //check if ready for delivery if (isReadyForCODelivery(m.getSourceId(), m.getVectorTimestamp(), currentVectorClock)) { // Message is received in correct order. Deliver. deliverMessage(m); // Update local registry. incrementMap(m.getSourceId(), currentVectorClock); // check for local messages available to deliver. deliverPendingLocalMessages(currentVectorClock); OperationalStore.INSTANCE.updateVectorClock(currentVectorClock); } else { pushToHoldbackQueue(m); } } } /** * * @param sourceId * @param messageClock * @param currentVectorClock * @return whether message can be delivered or not */ private boolean isReadyForCODelivery(int sourceId, Map<Integer, Integer> messageClock, Map<Integer, Integer> currentVectorClock) { if (messageClock.get(sourceId) == (currentVectorClock.get(sourceId) + 1)) { for (Map.Entry<Integer, Integer> entry : messageClock.entrySet()) { int procId = entry.getKey(); int processMessageNumber = entry.getValue(); if (procId != sourceId && processMessageNumber > currentVectorClock.get(procId)) { return false; } } return true; } return false; } /** * deliver pending local messages * @param currentVectorClock */ private void deliverPendingLocalMessages(Map<Integer, Integer> currentVectorClock) { Iterator<Message> holdbackQueueIter = holdbackQueue.iterator(); while(holdbackQueueIter.hasNext()) { Message m = holdbackQueueIter.next(); //TODO: don't think we need this check for readiness since we check before this function if (isReadyForCODelivery(m.getSourceId(), m.getVectorTimestamp(), currentVectorClock)) { deliverMessage(m); holdbackQueueIter.remove(); incrementMap(m.getSourceId(), currentVectorClock); } } } private void pushToHoldbackQueue(Message m) { holdbackQueue.add(m); } }
Python
UTF-8
4,785
2.75
3
[]
no_license
import matplotlib import datetime as dt, itertools, pandas as pd, matplotlib.pyplot as plt, numpy as np import math import torch from torch import nn from torch.autograd import Variable from models.LSTMPredictor import * from torch import optim csvFile = '../data/IBM.csv' CloseIndex = 3 def getCSVDataValuesWithLabel(fileName, label): """ Get the CSV file as value and labels :param fileName: the csv file name :param label: the column name for the label :return: ValueMatrix, label Vector """ dat = pd.read_csv(fileName).dropna() X = dat.loc[:, [x for x in dat.columns.tolist() if x != label]].as_matrix() Label = dat.loc[:, [x for x in dat.columns.tolist() if x == label]].as_matrix() return X, Label def getCSVDataValuesWithoutLabel(fileName, label): """ Get the CSV file as value and labels :param fileName: the csv file name :param label: the column name for the label :return: ValueMatrix, label Vector """ dat = pd.read_csv(fileName).dropna() X = dat.loc[:, [x for x in dat.columns.tolist() if x != label]].as_matrix() return X def getCSVDataValues(fileName): dat = pd.read_csv(fileName) X = dat.loc[:, [x for x in dat.columns.tolist() ]].as_matrix() return X def Normalize(data): for index in range(data.shape[1]): col = data[:,index] max_value = np.max(col) min_value = np.min(col) scalar = max_value - min_value data[:,index] = col / scalar def create_DataAndTarget(dataset,look_back=2): data, history,target = [], [], [] for i in range(len(dataset) - look_back): a = dataset[i:(i + look_back), :] h = dataset[i:(i + look_back -1), :] l = dataset[i + look_back -1, CloseIndex] data.append(a) history.append(h) target.append(l) return np.array(data), np.array(history),np.array(target) def train(model, criterion, optimizer, data, label): x = Variable(torch.from_numpy(data).float()) y = Variable(torch.from_numpy(label).float()) out = model(x) loss = criterion(out, y) # backward optimizer.zero_grad() loss.backward() optimizer.step() return loss def val(model, data, label): model.eval() correct = 0 for i in range(len(data)): x = data[i] y = label[i] x = Variable(torch.from_numpy(x).float()) x = x.view(-1,1,input_size) score = model(x) score = score.view(-1,3) _, pred = score.max(1) if(y == pred.data.numpy()): correct += 1 model.train() print("correct: {}, total: {}".format(correct, len(data))) acc = correct / float(len(data)) return acc def predict(model, data): model.eval() res = [] for i in range(len(data)): x = data[i,:] x = Variable(torch.from_numpy(x).float()) x = x.unsqueeze(1) out = model(x) out = out.view(-1) res.append(out.data.numpy()[0]) model.train() return res window = 10 hidden_size = 24 batch_size = 8 train_rate = 0.7 data = getCSVDataValuesWithoutLabel(csvFile,'Date') input_size = data.shape[1] print("Raw data shape: {}".format(data.shape)) all, value, target = create_DataAndTarget(data, window) # print(all.shape) # print(value.shape) # print(target.shape) # for i in range(all.shape[0]): # print(all[i,:,CloseIndex]) # print(value[i,:,CloseIndex]) # print(target[i]) train_size = int(len(data)*train_rate) test_size = len(data) - train_size train_data = value[:train_size, :] train_target = target[:train_size] test_data = value[train_size:, :] test_target = target[train_size:] print("data: {}, target: {}".format(data.shape, target.shape)) print("train data: {}, train label: {}".format(len(train_data), len(train_target))) print("test data: {}, test label: {}".format(len(test_data), len(test_target))) # set up the model net = LSTMPredictorWithHidden(input_size, 36) criterion = nn.MSELoss() optimizer = optim.SGD(net.parameters(), lr=0.01) for i in range(10): perm_idx = np.random.permutation(int(train_size)) j = 0 while j < train_size: batch_idx = perm_idx[j:(j+batch_size)] XValue = np.zeros(((window-1),len(batch_idx), input_size)) YTarget = np.zeros((len(batch_idx))) for k in range(len(batch_idx)): XValue[:,k,:] = train_data[batch_idx[k],:] loss = train(net,criterion, optimizer, XValue, YTarget) if j % 100*batch_size == 0: print("epoch: {}, loss: {}".format(i, loss.data[0])) j += batch_size val_Pred = predict(net, value) plt.figure() plt.plot(range(0, len(target)), target, 'b', label='real') plt.plot(range(0, len(val_Pred)), val_Pred, 'r', label='predict') plt.legend(loc='best') plt.show()
Java
UTF-8
12,858
1.804688
2
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/* * Copyright (c) 2016-2019 VMware, Inc. All Rights Reserved. * * This product is licensed to you under the Apache License, Version 2.0 (the "License"). * You may not use this product except in compliance with the License. * * This product may include a number of subcomponents with separate copyright notices * and license terms. Your use of these subcomponents is subject to the terms and * conditions of the subcomponent's license, as noted in the LICENSE file. */ package com.vmware.mangle.unittest.services.service; import static org.mockito.Matchers.any; import static org.mockito.Matchers.anyString; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.UUID; import lombok.extern.log4j.Log4j2; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.testng.Assert; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import com.vmware.mangle.cassandra.model.scheduler.SchedulerSpec; import com.vmware.mangle.model.enums.SchedulerStatus; import com.vmware.mangle.services.SchedulerService; import com.vmware.mangle.services.mockdata.SchedulerControllerMockData; import com.vmware.mangle.services.repository.SchedulerRepository; /** * * * @author chetanc */ @Log4j2 public class SchedulerServiceTest { @Mock private SchedulerRepository schedulerRepository; @InjectMocks private SchedulerService schedulerService; private SchedulerControllerMockData mockData = new SchedulerControllerMockData(); @BeforeMethod public void initMocks() { MockitoAnnotations.initMocks(this); } @Test public void testGetActiveSchedulesForIds() { log.debug("Exeucting testGetActiveSchedulesForIds on method SchedulerService#getActiveSchedulesForIds"); String taskId = UUID.randomUUID().toString(); SchedulerSpec spec = mockData.getMangleSchedulerSpecScheduled(); Set<SchedulerSpec> specs = new HashSet<>(Arrays.asList(spec)); List<String> tasks = new ArrayList<>(Arrays.asList(taskId)); when(schedulerRepository.findByIds(tasks)).thenReturn(specs); List<SchedulerSpec> persistedSchedules = schedulerService.getActiveSchedulesForIds(tasks); Assert.assertEquals(1, persistedSchedules.size()); Assert.assertEquals(spec.getId(), persistedSchedules.get(0).getId()); Assert.assertEquals(spec.getStatus(), persistedSchedules.get(0).getStatus()); verify(schedulerRepository, times(1)).findByIds(any()); } @Test public void testGetActiveSchedulesForIdsPausedJob() { log.debug( "Exeucting testGetActiveSchedulesForIdsPausedJob on method SchedulerService#getActiveSchedulesForIds"); String taskId = UUID.randomUUID().toString(); SchedulerSpec spec = mockData.getMangleSchedulerSpecScheduled(); spec.setStatus(SchedulerStatus.PAUSED); Set<SchedulerSpec> specs = new HashSet<>(Arrays.asList(spec)); List<String> tasks = new ArrayList<>(Arrays.asList(taskId)); when(schedulerRepository.findByIds(tasks)).thenReturn(specs); List<SchedulerSpec> persistedSchedules = schedulerService.getActiveSchedulesForIds(tasks); Assert.assertEquals(1, persistedSchedules.size()); Assert.assertEquals(spec.getId(), persistedSchedules.get(0).getId()); Assert.assertEquals(spec.getStatus(), persistedSchedules.get(0).getStatus()); verify(schedulerRepository, times(1)).findByIds(any()); } @Test public void testGetActiveSchedulesForIdsInitializingJob() { log.debug( "Exeucting testGetActiveSchedulesForIdsInitializingJob on method SchedulerService#getActiveSchedulesForIds"); String taskId = UUID.randomUUID().toString(); SchedulerSpec spec = mockData.getMangleSchedulerSpecScheduled(); spec.setStatus(SchedulerStatus.INITIALIZING); Set<SchedulerSpec> specs = new HashSet<>(Arrays.asList(spec)); List<String> tasks = new ArrayList<>(Arrays.asList(taskId)); when(schedulerRepository.findByIds(tasks)).thenReturn(specs); List<SchedulerSpec> persistedSchedules = schedulerService.getActiveSchedulesForIds(tasks); Assert.assertEquals(1, persistedSchedules.size()); Assert.assertEquals(spec.getId(), persistedSchedules.get(0).getId()); Assert.assertEquals(spec.getStatus(), persistedSchedules.get(0).getStatus()); verify(schedulerRepository, times(1)).findByIds(any()); } @Test public void testGetActiveSchedulesForIdsCancelledJob() { log.debug( "Exeucting testGetActiveSchedulesForIdsCancelledJob on method SchedulerService#getActiveSchedulesForIds"); String taskId = UUID.randomUUID().toString(); SchedulerSpec spec = mockData.getMangleSchedulerSpecScheduled(); spec.setStatus(SchedulerStatus.CANCELLED); Set<SchedulerSpec> specs = new HashSet<>(Arrays.asList(spec)); List<String> tasks = new ArrayList<>(Arrays.asList(taskId)); when(schedulerRepository.findByIds(tasks)).thenReturn(specs); List<SchedulerSpec> persistedSchedules = schedulerService.getActiveSchedulesForIds(tasks); Assert.assertEquals(0, persistedSchedules.size()); verify(schedulerRepository, times(1)).findByIds(any()); } @Test public void testGetActiveScheduleJobsPausedJob() { log.debug("Exeucting testGetActiveScheduleJobsPausedJob on method SchedulerService#getActiveScheduleJobs"); SchedulerSpec spec = mockData.getMangleSchedulerSpecScheduled(); spec.setStatus(SchedulerStatus.PAUSED); List<SchedulerSpec> specs = new ArrayList<>(Arrays.asList(spec)); when(schedulerRepository.findAll()).thenReturn(specs); List<String> persistedSchedules = schedulerService.getActiveScheduleJobs(); Assert.assertEquals(1, persistedSchedules.size()); verify(schedulerRepository, times(1)).findAll(); } @Test public void testGetAllScheduledJobByStatusNullSchedule() { log.debug( "Exeucting testGetAllScheduledJobByStatusNullSchedule on method SchedulerService#getAllScheduledJobByStatus"); List<SchedulerSpec> schedulerSpecs = schedulerService.getAllScheduledJobByStatus(null); Assert.assertEquals(schedulerSpecs.size(), 0); } @Test public void testGetScheduledJobByIdandStatusEmptySchedule() { log.debug( "Exeucting testGetScheduledJobByIdandStatusEmptySchedule on method SchedulerService#getScheduledJobByIdandStatus"); String jobId = UUID.randomUUID().toString(); Optional<SchedulerSpec> optional = Optional.empty(); when(schedulerRepository.findByIdAndStatus(jobId, SchedulerStatus.SCHEDULED)).thenReturn(optional); SchedulerSpec schedulerSpec = schedulerService.getScheduledJobByIdandStatus(jobId, SchedulerStatus.SCHEDULED); Assert.assertNull(schedulerSpec); } @Test public void testGetScheduledJobByIdandStatus() { log.debug("Exeucting testGetScheduledJobByIdandStatus on method SchedulerService#getScheduledJobByIdandStatus"); String jobId = UUID.randomUUID().toString(); Optional<SchedulerSpec> optional = Optional.of(new SchedulerSpec()); when(schedulerRepository.findByIdAndStatus(jobId, SchedulerStatus.SCHEDULED)).thenReturn(optional); SchedulerSpec schedulerSpec = schedulerService.getScheduledJobByIdandStatus(jobId, SchedulerStatus.SCHEDULED); Assert.assertNotNull(schedulerSpec); verify(schedulerRepository, times(1)).findByIdAndStatus(anyString(), any()); } @Test public void testGetScheduledJobByIdandStatusNullJobId() { log.debug( "Exeucting testGetScheduledJobByIdandStatusNullJobId on method SchedulerService#getScheduledJobByIdandStatus"); SchedulerSpec schedulerSpec = schedulerService.getScheduledJobByIdandStatus(null, SchedulerStatus.SCHEDULED); Assert.assertNull(schedulerSpec); } @Test public void testGetSchedulerDetailsByIdEmptySchedule() { log.debug( "Exeucting testGetSchedulerDetailsByIdEmptySchedule on method SchedulerService#getSchedulerDetailsById"); String jobId = UUID.randomUUID().toString(); Optional<SchedulerSpec> optional = Optional.empty(); when(schedulerRepository.findById(jobId)).thenReturn(optional); SchedulerSpec schedulerSpec = schedulerService.getSchedulerDetailsById(jobId); Assert.assertNull(schedulerSpec); verify(schedulerRepository, times(1)).findById(anyString()); } @Test public void testGetSchedulerDetailsById() { log.debug("Exeucting testGetSchedulerDetailsById on method SchedulerService#getScheduledJobByIdandStatus"); String jobId = UUID.randomUUID().toString(); Optional<SchedulerSpec> optional = Optional.of(new SchedulerSpec()); when(schedulerRepository.findById(jobId)).thenReturn(optional); SchedulerSpec schedulerSpec = schedulerService.getSchedulerDetailsById(jobId); Assert.assertNotNull(schedulerSpec); verify(schedulerRepository, times(1)).findById(anyString()); } @Test public void testGetSchedulerDetailsByIdNullJobId() { log.info( "Exeucting testGetSchedulerDetailsByIdNullJobId on method SchedulerService#getScheduledJobByIdandStatus"); SchedulerSpec schedulerSpec = schedulerService.getSchedulerDetailsById(null); Assert.assertNull(schedulerSpec); } @Test public void testGetAllSchedulerDetails() { log.info("Exeucting testGetAllSchedulerDetails on method SchedulerService#getAllSchedulerDetails"); SchedulerSpec schedulerSpec = new SchedulerSpec(); when(schedulerService.getAllSchedulerDetails()).thenReturn(Collections.singletonList(schedulerSpec)); List<SchedulerSpec> schedulerSpecs = schedulerService.getAllSchedulerDetails(); Assert.assertNotNull(schedulerSpecs); Assert.assertEquals(schedulerSpecs.size(), 1); Assert.assertEquals(schedulerSpecs.get(0), schedulerSpec); } @Test public void testAddOrUpdateSchedulerDetailsNullSpec() { log.info( "Exeucting testAddOrUpdateSchedulerDetailsNullSpec on method SchedulerService#addOrUpdateSchedulerDetails"); SchedulerSpec schedulerSpec = new SchedulerSpec(); schedulerSpec.setId(null); when(schedulerRepository.save(any())).thenReturn(schedulerSpec); SchedulerSpec persistedSpec = schedulerService.addOrUpdateSchedulerDetails(schedulerSpec); Assert.assertNull(persistedSpec); verify(schedulerRepository, times(1)).save(any()); verify(schedulerRepository, times(0)).findById(anyString()); } @Test public void testAddOrUpdateSchedulerDetails() { log.info("Executing testAddOrUpdateSchedulerDetails on method SchedulerService#addOrUpdateSchedulerDetails"); SchedulerSpec schedulerSpec = new SchedulerSpec(); Optional<SchedulerSpec> optional = Optional.of(schedulerSpec); when(schedulerRepository.save(any())).thenReturn(schedulerSpec); when(schedulerRepository.findById(any())).thenReturn(optional); SchedulerSpec persistedSpec = schedulerService.addOrUpdateSchedulerDetails(schedulerSpec); Assert.assertEquals(persistedSpec, schedulerSpec); verify(schedulerRepository, times(1)).save(any()); verify(schedulerRepository, times(1)).findById(anyString()); } @Test public void testUpdateSchedulerStatus() { log.info("Exeucting testUpdateSchedulerStatus on method SchedulerService#updateSchedulerStatus"); SchedulerSpec schedulerSpec = new SchedulerSpec(); Optional<SchedulerSpec> optional = Optional.of(schedulerSpec); when(schedulerRepository.save(any())).thenReturn(schedulerSpec); when(schedulerRepository.findById(any())).thenReturn(optional); SchedulerSpec persistedSpec = schedulerService.updateSchedulerStatus(schedulerSpec.getId(), SchedulerStatus.SCHEDULED); Assert.assertNotNull(persistedSpec); Assert.assertEquals(persistedSpec.getStatus(), SchedulerStatus.SCHEDULED); } }
Rust
UTF-8
32,589
3.875
4
[]
no_license
//! There is no From<u8> or any other types. //! The problem is that it's possible that the conversion is not doable //! and according to the documentation, the From trait cannot fail. //! //! Use TryFrom<> inst extern crate num; use core::ops::{BitAnd, BitAndAssign}; // use num::traits::Unsigned; use std::cmp::max; use std::cmp::PartialEq; use std::convert::From; use std::convert::TryFrom; // use std::convert::TryInto; // use std::default::Default; use std::fmt; // use std::fmt::Display; use std::mem::size_of; // use std::ops::Add; use std::string::ToString; use itertools::{ EitherOrBoth::{Both, Left, Right}, Itertools, }; /// A simple placeholder for calculating the place where a bit is stored. struct BitPosition { block_number: usize, block_position: usize, } #[derive(Debug, PartialEq)] // Allow the use of "{:?}" format specifier enum BitSetError { EnlargeError { from: usize, to: usize }, } // Allow the use of "{}" format specifier impl fmt::Display for BitSetError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { BitSetError::EnlargeError { from, to } => write!( f, "Cannot enlarge the bitset to a smaller size {} -> {}.", from, to ), } } } #[derive(Debug)] pub struct BitSet { /// list of blocks with data blocks: Vec<usize>, /// number of bits allowed to use size: usize, } // A couple of private functions impl BitSet { /// Returns the number of blocks needed for the specified number of bits. /// There is always at least one bit, so at least one block is needed. fn blocks_number(size: usize) -> usize { let div = size / Self::block_size(); let rem = size % Self::block_size(); if rem == 0 { div } else { div + 1 } } /// Returns the size of one block in bits. fn block_size() -> usize { size_of::<usize>() * 8 } /// Panic if the passed position argument is outside the range [0; self.size) fn assert_position(&self, position: usize) { if position >= self.size { panic!(format!( "Bit position [{}] is outside available range: [0, {}]", position, self.size - 1 )); } } /// Finds the bit position and block number fn get_bit_position(position: usize) -> BitPosition { BitPosition { block_number: position / Self::block_size(), block_position: position % Self::block_size(), } } /// Calculates the bitmask with just the one bit set. fn make_bitmask(position: usize) -> usize { 1 << position } } // Constructors impl BitSet { /// Creates a new BitSet with the given amount of allowed bits. /// /// Plenty of BitSet implementations allow for a zero length set. /// This is fine as long as this bitset is able to enlarge. /// I this case, the number of bits is set at the creation time, /// so a BitSet of zero length is useless, as you won't be able to /// do anything with that. /// /// This is the reason why there is no `default()` or `with_capacity()` functions /// and you should use `new()` instead. /// /// For the same reason, this function panics when you would try to create /// a BitSet with zero bits. This simiplifies the code in other places. /// /// Panics: /// - when size=0 /// pub fn new(size: usize) -> Self { if size == 0 { panic!("Creating BitSet with zero bits is not allowed."); } let blocks_number = Self::blocks_number(size); let mut blocks = Vec::with_capacity(blocks_number); for _ in 0..blocks_number { blocks.push(0); } BitSet { blocks, size } } } // Basic functions impl BitSet { /// Gets the bit from the position. /// /// Panics: /// - if the position is larger than the max bit number (which is size-1) /// pub fn get(&self, position: usize) -> bool { self.assert_position(position); let bit_position = Self::get_bit_position(position); let bitmask = Self::make_bitmask(bit_position.block_position); self.blocks[bit_position.block_number] & bitmask != 0 } /// Sets the bit value at the position.Add /// /// Panics: /// - if the position is larger than the max bit number (which is size-1) /// pub fn set(&mut self, position: usize, value: bool) { self.assert_position(position); let bit_position = Self::get_bit_position(position); let bitmask = Self::make_bitmask(bit_position.block_position); if value == true { self.blocks[bit_position.block_number] = self.blocks[bit_position.block_number] | bitmask; } else { self.blocks[bit_position.block_number] = self.blocks[bit_position.block_number] & !bitmask; } } } // utility functions impl BitSet { /// Returns true if all bits are set. False if any is not set. fn all(&self) -> bool { for block in &self.blocks { if *block != usize::MAX { return false; } } return true; } /// Returns true if all none bit is set. False if all are not set. fn any(&self) -> bool { for block in &self.blocks { if *block != 0 { return true; } } return false; } /// Returns number of bits set to true. fn count(&self) -> u32 { let mut res = 0; for block in &self.blocks { res += block.count_ones(); } res } /// Enlarges the bitset to the required size. /// /// All the new bits are set to false. /// /// The error is returned when /// fn enlarge(&mut self, new_size: usize) -> Result<(), BitSetError> { if new_size <= self.size { return Err(BitSetError::EnlargeError { from: self.size, to: new_size, }); } // let's create new blocks, if needed let required_new_blocks = Self::blocks_number(new_size); if required_new_blocks > self.blocks.len() { for _ in 1..required_new_blocks - self.blocks.len() { self.blocks.push(0); } } self.size = new_size; return Ok(()); } } macro_rules! add_from_uint_trait { ($t:ty) => { impl From<$t> for BitSet { fn from(value: $t) -> Self { // number of bytes we need in memory for the value let required_size = size_of::<$t>(); // number of blocks needed for the values let blocks_number = Self::blocks_number(required_size); // now we need to slice the blocks in groups as every block // contains a couple of bytes (depending on the machine) let bytes_per_block = size_of::<usize>(); // if we need more blocks, then we need to convert the bits // we store Little Endian in the list of blocks let value_bytes = value.to_be_bytes(); let mut blocks: Vec<usize> = Vec::with_capacity(blocks_number); // it is possible that we convert e.g. u16 -> usize(u64) // in this case, there are only 2 bytes and the compiler is not happy about // so, let's add some more bytes println! {"value {}", value} for chunk in value_bytes.chunks(bytes_per_block) { let mut block: usize = 0; for byte in chunk { block = block << 8; block = block | usize::from(*byte); } blocks.push(block); } blocks.reverse(); Self { blocks: blocks, size: size_of::<$t>() * 8, } } } }; } impl From<u8> for BitSet { fn from(value: u8) -> Self { // This implementation is simple. I don't care about the number of blocks here, // as it's impossible to have something smaller than u8. Self { blocks: vec![usize::from(value)], size: size_of::<u8>() * 8, } } } add_from_uint_trait! {u16} add_from_uint_trait! {u32} add_from_uint_trait! {u64} add_from_uint_trait! {u128} add_from_uint_trait! {usize} impl fmt::Display for BitSet { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let mut res = String::with_capacity(Self::block_size() * self.blocks.len()); let block_size = Self::block_size(); for block in (&self.blocks).iter().rev() { res += &format!("{:0width$b}", block, width = block_size); } res = res[(res.len() - self.size)..].to_string(); write!(f, "{}", res) } } macro_rules! add_try_from_uint_trait { ($t:ty) => { impl TryFrom<BitSet> for $t { type Error = &'static str; fn try_from(value: BitSet) -> Result<Self, Self::Error> { let block_size = size_of::<usize>(); let output_bytes = size_of::<$t>(); let blocks_needed: usize = max(output_bytes / block_size, 1); // When the type is smaller than usize if blocks_needed == 1 { match <$t>::try_from(value.blocks[0]) { Ok(number) => return Ok(number), Err(_) => return Err("Value stored in BitSet cannot be converted to u8."), }; } // The type is bigger than usize, e.g. u128 on 64bit machine, // this way we need to have at least two blocks, and conversion // should be fine. // if any of the not used blocks contains any bit set, then the conversion is not doable for block in &value.blocks[blocks_needed - 1..] { if *block != 0 { return Err("Value stored in BitSet cannot be converted to u8."); } } let mut output: $t = 0; for block in &value.blocks[0..blocks_needed - 1] { output = output << BitSet::block_size(); output = output | (*block) as $t; } return Ok(output); } } }; } add_try_from_uint_trait! {u8} add_try_from_uint_trait! {u16} add_try_from_uint_trait! {u32} add_try_from_uint_trait! {u64} add_try_from_uint_trait! {u128} add_try_from_uint_trait! {usize} #[cfg(test)] mod test_private_functions { use super::*; #[test] fn check_getting_number_of_blocks() { let block_size = size_of::<usize>() * 8; assert_eq!(BitSet::blocks_number(1), 1); assert_eq!(BitSet::blocks_number(10), 1); assert_eq!(BitSet::blocks_number(block_size), 1); assert_eq!(BitSet::blocks_number(block_size + 1), 2); assert_eq!(BitSet::blocks_number(2 * block_size), 2); assert_eq!(BitSet::blocks_number(2 * block_size + 1), 3); } #[test] fn check_getting_number_of_bits_in_block() { assert_eq!(BitSet::block_size(), size_of::<usize>() * 8); } } #[cfg(test)] mod test_constructors { use super::*; #[test] #[should_panic(expected = "Creating BitSet with zero bits is not allowed.")] fn check_creating_bitset_with_zero_bits() { BitSet::new(0); } #[test] fn check_creating_new_bitset() { let block_size = size_of::<usize>() * 8; // for 1 bit we should have 1 block let a = BitSet::new(1); assert_eq!(a.blocks.len(), 1); assert_eq!(a.size, 1); // for max bits in one block, we should have one block let b = BitSet::new(block_size); assert_eq!(b.blocks.len(), 1); assert_eq!(b.size, block_size); // for 1 + max bits in one block, we should have two block let c = BitSet::new(block_size + 1); assert_eq!(c.blocks.len(), 2); assert_eq!(c.size, block_size + 1); } } #[cfg(test)] #[macro_use] mod test_conversions_to_types { use super::*; #[test] fn check_string_conversion() { let b = BitSet::new(1); assert_eq!(b.to_string(), "0"); let mut c = BitSet::new(1); c.set(0, true); assert_eq!(c.to_string(), "1"); let mut d = BitSet::new(66); d.set(0, true); d.set(5, true); d.set(64, true); // 60 50 40 30 20 10 0 // 543210987654321098765432109876543210987654321098765432109876543210 let expected_d = "010000000000000000000000000000000000000000000000000000000000100001"; assert_eq!(d.to_string(), expected_d); } /// Checks conversion from different values macro_rules! check_type_conversion { ($func:ident, $from:ty, $to:ty) => { #[quickcheck] fn $func(value: $from) -> bool { let bitset = BitSet::from(value); let new_value = <$to>::try_from(bitset); if value as $from <= <$to>::MAX as $from { // conversion should be fine assert_eq!(value as $to, new_value.unwrap()); } else { // in this case the value is too large assert_eq!( new_value, Err("Value stored in BitSet cannot be converted to u8.") ); } true } }; } check_type_conversion! {check_conversion_from_u8_to_u8, u8, u8} check_type_conversion! {check_conversion_from_u16_to_u8, u16, u8} check_type_conversion! {check_conversion_from_u32_to_u8, u32, u8} check_type_conversion! {check_conversion_from_u64_to_u8, u64, u8} check_type_conversion! {check_conversion_from_u128_to_u8, u128, u8} check_type_conversion! {check_conversion_from_usize_to_u8, usize, u8} check_type_conversion! {check_conversion_from_u8_to_u16, u8, u16} check_type_conversion! {check_conversion_from_u16_to_u16, u16, u16} check_type_conversion! {check_conversion_from_u32_to_u16, u32, u16} check_type_conversion! {check_conversion_from_u64_to_u16, u64, u16} check_type_conversion! {check_conversion_from_u128_to_u16, u128, u16} check_type_conversion! {check_conversion_from_usize_to_u16, usize, u16} check_type_conversion! {check_conversion_from_u8_to_u32, u8, u32} check_type_conversion! {check_conversion_from_u16_to_u32, u16, u32} check_type_conversion! {check_conversion_from_u32_to_u32, u32, u32} check_type_conversion! {check_conversion_from_u64_to_u32, u64, u32} check_type_conversion! {check_conversion_from_u128_to_u32, u128, u32} check_type_conversion! {check_conversion_from_usize_to_u32, usize, u32} check_type_conversion! {check_conversion_from_u8_to_u64, u8, u64} check_type_conversion! {check_conversion_from_u16_to_u64, u16, u64} check_type_conversion! {check_conversion_from_u32_to_u64, u32, u64} check_type_conversion! {check_conversion_from_u64_to_u64, u64, u64} check_type_conversion! {check_conversion_from_u128_to_u64, u128, u64} check_type_conversion! {check_conversion_from_usize_to_u64, usize, u64} check_type_conversion! {check_conversion_from_u8_to_u128, u8, u128} check_type_conversion! {check_conversion_from_u16_to_u128, u16, u128} check_type_conversion! {check_conversion_from_u32_to_u128, u32, u128} check_type_conversion! {check_conversion_from_u64_to_u128, u64, u128} check_type_conversion! {check_conversion_from_u128_to_u128, u128, u128} check_type_conversion! {check_conversion_from_usize_to_u128, usize, u128} check_type_conversion! {check_conversion_from_u8_to_usize, u8, usize} check_type_conversion! {check_conversion_from_u16_to_usize, u16, usize} check_type_conversion! {check_conversion_from_u32_to_usize, u32, usize} check_type_conversion! {check_conversion_from_u64_to_usize, u64, usize} check_type_conversion! {check_conversion_from_u128_to_usize, u128, usize} check_type_conversion! {check_conversion_from_usize_to_usize, usize, usize} } #[cfg(test)] #[macro_use] mod test_conversions_from_types { use super::*; /// Checks conversion from different values macro_rules! check_type_conversion { ($func:ident, $t:ty) => { #[quickcheck] fn $func(value: $t) -> bool { let bitset = BitSet::from(value); let value_bits_count = size_of::<$t>() * 8; // the bitset should have the same number of bits as the initial value assert_eq!(bitset.size, value_bits_count); // converting both to a string should give the same result let value_bits = format!("{:0width$b}", value, width = value_bits_count); let bitset_bits = bitset.to_string(); assert_eq! {value_bits, bitset_bits} // also, check bit by bit that everything is the same for bit in 0..value_bits_count - 1 { let bit_from_value: bool = (value & (1 << bit) != 0); assert_eq! {bit_from_value, bitset.get(bit)} } true } }; } #[test] fn check_conversion_from_u8_value() { let b = BitSet::from(0 as u8); assert_eq!(b.size, 8); assert_eq!(b.blocks.len(), 1); assert_eq!(b.to_string(), "00000000"); let b = BitSet::from(u8::MAX); assert_eq!(b.size, 8); assert_eq!(b.blocks.len(), 1); assert_eq!(b.to_string(), "11111111"); let b = BitSet::from(u8::from(170)); assert_eq!(b.size, 8); assert_eq!(b.blocks.len(), 1); assert_eq!(b.to_string(), "10101010"); } // // Test converting from different values; check_type_conversion! {check_conversion_from_u8, u8} check_type_conversion! {check_conversion_from_u16, u16} check_type_conversion! {check_conversion_from_u32, u32} check_type_conversion! {check_conversion_from_u64, u64} check_type_conversion! {check_conversion_from_u128, u128} check_type_conversion! {check_conversion_from_usize, usize} } #[cfg(test)] mod test_basic_getter_and_setter { use super::*; #[test] #[should_panic(expected = "Bit position [256] is outside available range: [0, 255]")] fn check_using_setter_for_too_large_position() { let mut b = BitSet::new(256); b.set(256, false); } #[test] #[should_panic(expected = "Bit position [256] is outside available range: [0, 255]")] fn check_using_getter_for_too_large_position() { let b = BitSet::new(256); b.get(256); } #[test] fn check_simple_operations() { let mut b = BitSet::new(4); assert_eq!(b.get(0), false); assert_eq!(b.get(1), false); assert_eq!(b.get(2), false); assert_eq!(b.get(3), false); b.set(0, true); assert_eq!(b.get(0), true); assert_eq!(b.get(1), false); assert_eq!(b.get(2), false); assert_eq!(b.get(3), false); b.set(3, true); assert_eq!(b.get(0), true); assert_eq!(b.get(1), false); assert_eq!(b.get(2), false); assert_eq!(b.get(3), true); b.set(1, false); b.set(3, false); assert_eq!(b.get(0), true); assert_eq!(b.get(1), false); assert_eq!(b.get(2), false); assert_eq!(b.get(3), false); } } #[cfg(test)] #[macro_use] mod test_utitily_functions { use super::*; #[test] fn check_all_function() { let mut b = BitSet::new(300); assert_eq! {b.all(), false} b.set(10, true); assert_eq! {b.all(), false} let mut b = BitSet::from(u128::MAX); assert_eq! {b.all(), true} b.set(10, false); assert_eq! {b.all(), false} } #[test] fn check_any_function() { let mut b = BitSet::new(300); assert_eq! {b.any(), false} b.set(10, true); assert_eq! {b.any(), true} let mut b = BitSet::from(u128::MAX); assert_eq! {b.any(), true} b.set(10, false); assert_eq! {b.any(), true} } #[test] fn check_count_function() { let mut b = BitSet::new(300); assert_eq! {b.count(), 0} b.set(10, true); assert_eq! {b.count(), 1} let mut b = BitSet::from(u128::MAX); assert_eq! {b.count(), 128} b.set(10, false); assert_eq! {b.count(), 127} } /// Checks conversion from different values macro_rules! check_enlarge_function { ($func:ident, $t:ty) => { #[quickcheck] fn $func(value: $t) -> bool { let initial_size = size_of::<$t>() * 8; let new_size = value as usize; let mut b = BitSet::from(value); assert_eq!(b.size, initial_size); let res: Result<(), BitSetError> = b.enlarge(new_size as usize); if new_size <= initial_size { let expected = BitSetError::EnlargeError { from: initial_size, to: new_size, }; let error = res.err().unwrap(); assert_eq!(expected, error); } else { assert!(res.is_ok()); assert_eq!(b.size, new_size); assert_eq!($t::try_from(b).unwrap(), value); } true } }; } check_enlarge_function! {check_enlarge_function_for_u8, u8} check_enlarge_function! {check_enlarge_function_for_u16, u16} check_enlarge_function! {check_enlarge_function_for_u32, u32} check_enlarge_function! {check_enlarge_function_for_u64, u64} check_enlarge_function! {check_enlarge_function_for_u128, u128} check_enlarge_function! {check_enlarge_function_for_usize, usize} } /// The returned bitset has the size of the larger one. /// However, it assumes the smaller has zeros when enlarged impl BitAnd for BitSet { type Output = BitSet; fn bitand(self, rhs: BitSet) -> Self::Output { let lhs = self; let output_size = max(lhs.size, rhs.size); let mut blocks: Vec<usize> = vec![]; for item in lhs.blocks.iter().zip_longest(rhs.blocks.iter()) { match item { Both(l, r) => { blocks.push(l & r); } Left(_) | Right(_) => blocks.push(0), } } BitSet { blocks, size: output_size, } } } impl BitAnd for &BitSet { type Output = BitSet; fn bitand(self, rhs: &BitSet) -> Self::Output { let lhs = self; let output_size = max(lhs.size, rhs.size); let mut blocks: Vec<usize> = vec![]; for item in lhs.blocks.iter().zip_longest(rhs.blocks.iter()) { match item { Both(l, r) => { blocks.push(l & r); } Left(_) | Right(_) => blocks.push(0), } } BitSet { blocks, size: output_size, } } } impl BitAndAssign for BitSet { fn bitand_assign(&mut self, rhs: Self) { let lhs = self; let output_size = max(lhs.size, rhs.size); let mut blocks: Vec<usize> = vec![]; for item in lhs.blocks.iter().zip_longest(rhs.blocks.iter()) { match item { Both(l, r) => { blocks.push(l & r); } Left(_) | Right(_) => blocks.push(0), } } lhs.blocks = blocks; } } #[cfg(test)] #[macro_use] mod test_operators { use super::*; /// Checks logical and function converting between bitsets of different sizes macro_rules! check_logical_bit_and { ($func:ident, $left:ty, $right:ty) => { #[quickcheck] fn $func(left: $left, right: $right) -> bool { let left_size = size_of::<$left>() * 8; let right_size = size_of::<$right>() * 8; let a = BitSet::from(left); let b = BitSet::from(right); let c = a & b; assert_eq!(c.size, max(left_size, right_size)); assert_eq!( u128::try_from(c).unwrap(), u128::from(left as u128 & right as u128) ); true } }; } /// Checks logical and function converting between bitsets of different sizes macro_rules! check_logical_bit_and_for_refs { ($func:ident, $left:ty, $right:ty) => { #[quickcheck] fn $func(left: $left, right: $right) -> bool { let left_size = size_of::<$left>() * 8; let right_size = size_of::<$right>() * 8; let a = BitSet::from(left); let b = BitSet::from(right); let c = &a & &b; assert_eq!(c.size, max(left_size, right_size)); assert_eq!( u128::try_from(c).unwrap(), u128::from(left as u128 & right as u128) ); true } }; } check_logical_bit_and!(check_logical_bit_and_u8_u8, u8, u8); check_logical_bit_and!(check_logical_bit_and_u8_u16, u8, u16); check_logical_bit_and!(check_logical_bit_and_u8_u32, u8, u32); check_logical_bit_and!(check_logical_bit_and_u8_u64, u8, u64); check_logical_bit_and!(check_logical_bit_and_u8_u128, u8, u128); check_logical_bit_and!(check_logical_bit_and_u8_usize, u8, usize); check_logical_bit_and!(check_logical_bit_and_u16_u8, u16, u8); check_logical_bit_and!(check_logical_bit_and_u16_u16, u16, u16); check_logical_bit_and!(check_logical_bit_and_u16_u32, u16, u32); check_logical_bit_and!(check_logical_bit_and_u16_u64, u16, u64); check_logical_bit_and!(check_logical_bit_and_u16_u128, u16, u128); check_logical_bit_and!(check_logical_bit_and_u16_usize, u16, usize); check_logical_bit_and!(check_logical_bit_and_u32_u8, u32, u8); check_logical_bit_and!(check_logical_bit_and_u32_u16, u32, u16); check_logical_bit_and!(check_logical_bit_and_u32_u32, u32, u32); check_logical_bit_and!(check_logical_bit_and_u32_u64, u32, u64); check_logical_bit_and!(check_logical_bit_and_u32_u128, u32, u128); check_logical_bit_and!(check_logical_bit_and_u32_usize, u32, usize); check_logical_bit_and!(check_logical_bit_and_u64_u8, u64, u8); check_logical_bit_and!(check_logical_bit_and_u64_u16, u64, u16); check_logical_bit_and!(check_logical_bit_and_u64_u32, u64, u32); check_logical_bit_and!(check_logical_bit_and_u64_u64, u64, u64); check_logical_bit_and!(check_logical_bit_and_u64_u128, u64, u128); check_logical_bit_and!(check_logical_bit_and_u64_usize, u64, usize); check_logical_bit_and!(check_logical_bit_and_u128_u8, u128, u8); check_logical_bit_and!(check_logical_bit_and_u128_u16, u128, u16); check_logical_bit_and!(check_logical_bit_and_u128_u32, u128, u32); check_logical_bit_and!(check_logical_bit_and_u128_u64, u128, u64); check_logical_bit_and!(check_logical_bit_and_u128_u128, u128, u128); check_logical_bit_and!(check_logical_bit_and_u128_usize, u128, usize); check_logical_bit_and!(check_logical_bit_and_usize_u8, usize, u8); check_logical_bit_and!(check_logical_bit_and_usize_u16, usize, u16); check_logical_bit_and!(check_logical_bit_and_usize_u32, usize, u32); check_logical_bit_and!(check_logical_bit_and_usize_u64, usize, u64); check_logical_bit_and!(check_logical_bit_and_usize_u128, usize, u128); check_logical_bit_and!(check_logical_bit_and_usize_usize, usize, usize); check_logical_bit_and_for_refs!(check_logical_bit_and_for_refs_u8_u8, u8, u8); check_logical_bit_and_for_refs!(check_logical_bit_and_for_refs_u8_u16, u8, u16); check_logical_bit_and_for_refs!(check_logical_bit_and_for_refs_u8_u32, u8, u32); check_logical_bit_and_for_refs!(check_logical_bit_and_for_refs_u8_u64, u8, u64); check_logical_bit_and_for_refs!(check_logical_bit_and_for_refs_u8_u128, u8, u128); check_logical_bit_and_for_refs!(check_logical_bit_and_for_refs_u8_usize, u8, usize); check_logical_bit_and_for_refs!(check_logical_bit_and_for_refs_u16_u8, u16, u8); check_logical_bit_and_for_refs!(check_logical_bit_and_for_refs_u16_u16, u16, u16); check_logical_bit_and_for_refs!(check_logical_bit_and_for_refs_u16_u32, u16, u32); check_logical_bit_and_for_refs!(check_logical_bit_and_for_refs_u16_u64, u16, u64); check_logical_bit_and_for_refs!(check_logical_bit_and_for_refs_u16_u128, u16, u128); check_logical_bit_and_for_refs!(check_logical_bit_and_for_refs_u16_usize, u16, usize); check_logical_bit_and_for_refs!(check_logical_bit_and_for_refs_u32_u8, u32, u8); check_logical_bit_and_for_refs!(check_logical_bit_and_for_refs_u32_u16, u32, u16); check_logical_bit_and_for_refs!(check_logical_bit_and_for_refs_u32_u32, u32, u32); check_logical_bit_and_for_refs!(check_logical_bit_and_for_refs_u32_u64, u32, u64); check_logical_bit_and_for_refs!(check_logical_bit_and_for_refs_u32_u128, u32, u128); check_logical_bit_and_for_refs!(check_logical_bit_and_for_refs_u32_usize, u32, usize); check_logical_bit_and_for_refs!(check_logical_bit_and_for_refs_u64_u8, u64, u8); check_logical_bit_and_for_refs!(check_logical_bit_and_for_refs_u64_u16, u64, u16); check_logical_bit_and_for_refs!(check_logical_bit_and_for_refs_u64_u32, u64, u32); check_logical_bit_and_for_refs!(check_logical_bit_and_for_refs_u64_u64, u64, u64); check_logical_bit_and_for_refs!(check_logical_bit_and_for_refs_u64_u128, u64, u128); check_logical_bit_and_for_refs!(check_logical_bit_and_for_refs_u64_usize, u64, usize); check_logical_bit_and_for_refs!(check_logical_bit_and_for_refs_u128_u8, u128, u8); check_logical_bit_and_for_refs!(check_logical_bit_and_for_refs_u128_u16, u128, u16); check_logical_bit_and_for_refs!(check_logical_bit_and_for_refs_u128_u32, u128, u32); check_logical_bit_and_for_refs!(check_logical_bit_and_for_refs_u128_u64, u128, u64); check_logical_bit_and_for_refs!(check_logical_bit_and_for_refs_u128_u128, u128, u128); check_logical_bit_and_for_refs!(check_logical_bit_and_for_refs_u128_usize, u128, usize); check_logical_bit_and_for_refs!(check_logical_bit_and_for_refs_usize_u8, usize, u8); check_logical_bit_and_for_refs!(check_logical_bit_and_for_refs_usize_u16, usize, u16); check_logical_bit_and_for_refs!(check_logical_bit_and_for_refs_usize_u32, usize, u32); check_logical_bit_and_for_refs!(check_logical_bit_and_for_refs_usize_u64, usize, u64); check_logical_bit_and_for_refs!(check_logical_bit_and_for_refs_usize_u128, usize, u128); check_logical_bit_and_for_refs!(check_logical_bit_and_for_refs_usize_usize, usize, usize); // Checks =& function converting between bitsets of different sizes // macro_rules! check_bit_and_assign { // ($func:ident, $left:ty, $right:ty) => { // #[quickcheck] // fn $func(left: $left, right: $right) -> bool { // let left_size = size_of::<$left>() * 8; // let right_size = size_of::<$right>() * 8; // let mut a = BitSet::from(left); // let b = BitSet::from(right); // let a &= b; // assert_eq!(a.size, max(left_size, right_size)); // assert_eq!( // u128::try_from(a).unwrap(), // u128::from(left as u128 & right as u128) // ); // true // } // }; // } // check_bit_and_assign!(check_logical_bit_and_assign_u8_u8, u8, u8); }
Python
UTF-8
285
2.71875
3
[]
no_license
with open('latex.log', 'r', encoding='utf-8') as f: lines=0 words=0 for line in f: line = line.replace("\n","") if len(line)<2: continue lines+=1 words+=len(line) f.close() print(int(round(words/lines,0)))
Swift
UTF-8
863
3
3
[]
no_license
// // ViewController.swift // iOSEngineerNight // // Created by Koji Murata on 2015/10/21. // Copyright © 2015年 Koji Murata. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } @IBOutlet weak var progressView: UIProgressView! @IBAction func push() { progressView.progress += 0.1 if progressView.progress == 1 { progressView.progress = 0 } } // MARK: - guard enum Error: ErrorType { case Nil } private func foo(hoge: String?) throws -> String { if let h = hoge { return h } throw Error.Nil } private func bar(hoge: String?) throws -> String { guard let hoge = hoge else { throw Error.Nil } return hoge } // MARK: - デフォルト引数 private func baz(hoge: String? = nil) { print(hoge) } }
Markdown
UTF-8
2,098
2.640625
3
[ "MIT" ]
permissive
# Migration `20191117175022-project-setup` This migration has been generated by maticzav at 11/17/2019, 5:50:22 PM. You can check out the [state of the schema](./schema.prisma) after the migration. ## Database Steps ```sql CREATE TABLE "public"."Starter" ( "createdAt" timestamp(3) NOT NULL DEFAULT '1970-01-01 00:00:00' , "description" text , "id" text NOT NULL , "name" text NOT NULL DEFAULT '' , "owner" text NOT NULL DEFAULT '' , "path" text NOT NULL DEFAULT '' , "ref" text NOT NULL DEFAULT '' , "repo" text NOT NULL DEFAULT '' , "signature" text NOT NULL DEFAULT '' , "updatedAt" timestamp(3) NOT NULL DEFAULT '1970-01-01 00:00:00' , PRIMARY KEY ("id") ); CREATE TABLE "public"."Starter_dependencies" ( "nodeId" text REFERENCES "public"."Starter"("id") ON DELETE CASCADE, "position" integer NOT NULL , "value" text NOT NULL , PRIMARY KEY ("nodeId","position") ); CREATE UNIQUE INDEX "Starter.signature" ON "public"."Starter"("signature") ``` ## Changes ```diff diff --git datamodel.mdl datamodel.mdl migration ..20191117175022-project-setup --- datamodel.dml +++ datamodel.dml @@ -1,0 +1,27 @@ +datasource pg { + provider = "postgres" + url = env("POSTGRESQL_URL") +} + +generator photon { + provider = "photonjs" + output = "./node_modules/@generated/photon" +} + +model Starter { + // System + id String @id @default(cuid()) + createdAt DateTime @default(now()) + updatedAt DateTime @updatedAt + // Meta + signature String @unique + repo String + owner String + // Info + path String + ref String + // Search + name String + description String? + dependencies String[] +} ``` ## Photon Usage You can use a specific Photon built for this migration (20191117175022-project-setup) in your `before` or `after` migration script like this: ```ts import Photon from '@generated/photon/20191117175022-project-setup' const photon = new Photon() async function main() { const result = await photon.users() console.dir(result, { depth: null }) } main() ```
C#
UTF-8
2,622
2.703125
3
[]
no_license
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using PhoneBookBackEnd.Models; using PhoneBookBackEnd.ViewModels; namespace PhoneBookBackEnd.Controllers { [Route("api/[controller]")] // localhost:5000/api/values [ApiController] public class PeopleController : ControllerBase { //GET that returns all People //GET /api/people [HttpGet] public ActionResult<IEnumerable<People>> GetAction() { // query my database var db = new PhoneBookDbContext(); //SELECT * FROM People var results = db.People.OrderBy(people => people.FirstName); //return the results return results.ToList(); } [HttpPost] public ActionResult<People> AddPeople([FromBody] People incomingPeople) { var db = new PhoneBookDbContext(); db.People.Add(incomingPeople); db.SaveChanges(); return incomingPeople; } [HttpDelete("{id}")] public ActionResult<Object> DeletePeople([FromRoute]int id) { var db = new PhoneBookDbContext(); var peopleToDelete = db.People.FirstOrDefault(people => people.Id == id); if (peopleToDelete != null) { db.People.Remove(peopleToDelete); db.SaveChanges(); return peopleToDelete; } else { return new { message = "Person or people not found" }; } } // Delete people by List select checkbox. [HttpDelete("list")] public ActionResult DeleteGroupOfEmployees([FromBody]DeletePeopleViewModel vm) { var db = new PhoneBookDbContext(); var peopleIDsSelectedForDelete = db.People.Where(people => vm.PeopleIds.Contains(people.Id)); if (peopleIDsSelectedForDelete != null) { db.People.RemoveRange(peopleIDsSelectedForDelete); db.SaveChanges(); return Ok(); } else { return Ok(vm); } } // [HttpPut("{id}")] public ActionResult<object> UpdatePeople([FromRoute]int id, [FromBody] People newInformation) { var db = new PhoneBookDbContext(); var peopleToUpdate = db.People.FirstOrDefault(people => people.Id == id); if (peopleToUpdate != null) { peopleToUpdate.FirstName = newInformation.FirstName; peopleToUpdate.LastName = newInformation.LastName; peopleToUpdate.PhoneNumber = newInformation.PhoneNumber; peopleToUpdate.Email = newInformation.Email; db.SaveChanges(); return Ok(peopleToUpdate); } else { return NotFound(); } } } }
Markdown
UTF-8
2,340
2.515625
3
[ "MIT" ]
permissive
# tcjudge: Judges TopCoder solutions locally tcjudge is a simple command line tool that judges TopCoder solutions within local environment. [日本語はこちら](https://github.com/peryaudo/tcjudge/blob/master/README.ja.md) ## Features * Creates scaffold files * Executes faster than official * Does not mess up your local directory * Highly configurable through Ruby * Supports multiple languages (C++, Java, C#, Haskell, Python) and compilers (GCC, clang, VC++, Mono, VC#, GHC) * Score calculation ## Usage If the name of a problem you want to solve is BallsConverter, you can create a scaffold file by tcjudge create BallsConverter.cpp . Then you can run the judgement by tcjudge judge BallsConverter.cpp or tcjudge BallsConverter.cpp . tcjudge automatically detects the language by its extension. Also, you can cut out from "CUT begin" to "CUT end" by tcjudge clean BallsConverter.cpp . It emits the source code to stdout. It is especially useful when used like tcjudge clean BallsConverter.cpp | pbcopy ## Prerequisites * Ruby >= 1.9.3 ## Installation gem install tcjudge ## Configuration See .tcjudgerc file for detail. Defaults will be used if you don't create one. You can use cl.exe for C++ compiler too. ## License The MIT License (MIT) Copyright (c) 2013-2015 peryaudo. 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.
Python
UTF-8
3,571
2.671875
3
[]
no_license
import pandas as pd import numpy as np import os from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.cluster import KMeans from sklearn.externals import joblib from assistant.training.preprocess.preprocess import filter_question, preprocess_question from assistant.settings import BASE_DIR class AssistantTrainer: base_data_path = "data/base_data_vk.csv" prepared_data_path = os.path.join(BASE_DIR, "assistant/training/data/processed_data_vk.csv") prepared_field_name = 'process' def preprocess_query(self, query): preprocess_string = preprocess_question(query) return preprocess_string def prepare_data(self): data_frame = pd.read_csv(self.base_data_path) data_frame = data_frame.dropna() data_frame['is_accepted'] = data_frame['question'].apply(lambda x: filter_question(x)) data_frame = data_frame[data_frame['is_accepted'] == True] data_frame.drop(['is_accepted'], axis=1, inplace=True) # Preprocess data_frame[self.prepared_field_name] = data_frame['question'].apply(lambda x: preprocess_question(x)) data_frame = data_frame[data_frame[self.prepared_field_name].apply(lambda x: len(x.split()) > 0)] data_frame.reset_index(drop=True, inplace=True) data_frame.to_csv("processed_df.csv") return data_frame def load_prepared_data(self): data_frame = pd.read_csv(self.prepared_data_path) return data_frame def prepare_vectorizer(self): data_frame = self.load_prepared_data() vectorizer = TfidfVectorizer(max_features=10000, max_df=0.5, norm='l2', ngram_range=(1, 2)) transform_matrix = vectorizer.fit_transform(data_frame[self.prepared_field_name]) np.savez(os.path.join(BASE_DIR, "assistant/prepared_modules/laws_tf_idf.npz", data=transform_matrix.data, indices=transform_matrix.indices, indptr=transform_matrix.indptr, shape=transform_matrix.shape)) joblib.dump(vectorizer, os.path.join(BASE_DIR, "assistant/prepared_modules/tfidf_vectorizer_10000_ngram_12.pkl")) return vectorizer def load_transform_matrix(self): return self.vectorizer.transform(self.load_prepared_data()[self.prepared_field_name]) def load_vectorizer(self): vectorizer = joblib.load(os.path.join(BASE_DIR, "assistant/prepared_modules/tfidf_vectorizer_10000_ngram_12.pkl")) return vectorizer def vectorize_query(self, query): preprocessed_query = preprocess_question(query) vector = self.vectorizer.transform([preprocessed_query]) return vector def get_train_vectors(self): data_frame = self.load_prepared_data() vectorizer = self.load_vectorizer() return vectorizer.transform(data_frame[self.prepared_field_name]) def prepare_clustering(self): num_clusters = 60 clf = KMeans(init='k-means++', max_iter=1000, n_clusters=num_clusters, n_init=15, n_jobs=2, random_state=241) vectors = self.get_train_vectors() clf.fit(vectors) joblib.dump(clf, os.path.join(BASE_DIR, "assistant/prepared_modules/kmeans_60.pkl")) return clf def load_clustering(self): clf = joblib.load(os.path.join(BASE_DIR, "assistant/prepared_modules/kmeans_60.pkl")) return clf def __init__(self): self.vectorizer = self.load_vectorizer() self.clf = self.load_clustering() print("Ready!") if __name__ == "__main__": assistant = AssistantTrainer() vect = assistant.load_vectorizer()
Python
UTF-8
1,354
3.609375
4
[ "MIT" ]
permissive
import sqlite3 # create connection sl_conn = sqlite3.connect('/Users/Elizabeth/sql/demo_data.sqlite3') sl_curs = sl_conn.cursor() # create table schema create_table = """ CREATE TABLE demo ( s VARCHAR(1), x INT, y INT ); """ sl_curs.execute(create_table) # data demo_data = [('g', 3, 9), ('v', 5, 7), ('f', 8, 7)] # insert data for data in demo_data: demo_insert = """ INSERT INTO demo ( s, x, y) VALUES """ + str(data) + ';' sl_curs.execute(demo_insert) # commit data sl_curs.close() sl_conn.commit() # create new cursor sl_curs = sl_conn.cursor() # Check how many rows query = """ SELECT COUNT(*) FROM demo; """ answer = sl_curs.execute(query).fetchall()[0][0] print('There are {} rows'.format(answer)) # How many rows are there where both x and y are at least 5? query = """ SELECT COUNT(*) FROM demo WHERE x>=5 AND y>=5; """ answer = sl_curs.execute(query).fetchall()[0][0] print('There are {} rows where x and y are at least 5'.format(answer)) # How many unique values of y are there (hint - COUNT() can accept a keyword DISTINCT)? query = """ SELECT COUNT(DISTINCT y) FROM demo; """ answer = sl_curs.execute(query).fetchall()[0][0] print('There are {} distinct values of y'.format(answer))
Python
UTF-8
1,300
3.03125
3
[]
no_license
import pygame class Block(object): def loadResources(): Block.wall1Img = pygame.image.load("Resources/Wall1.png") Block.wall2Img = pygame.image.load("Resources/Wall2.png") Block.playerStartImg = pygame.image.load("Resources/playerstart.png") Block.playerStartImg = pygame.transform.scale(Block.playerStartImg, (Block.playerStartImg.get_width()//2, Block.playerStartImg.get_height()//2)) Block.playerEndImg = pygame.image.load("Resources/goal.png") Block.playerEndImg = pygame.transform.scale(Block.playerEndImg, (Block.playerEndImg.get_width() // 2, Block.playerEndImg.get_height() // 2)) Block.enemyImg = pygame.image.load("Resources/enemy.png") def draw(screen, cell, coordinates, sizePx): cellRect = (coordinates[0], coordinates[1], sizePx, sizePx) if cell == 1: screen.blit(Block.wall2Img, coordinates) if cell == 2: screen.blit(Block.wall1Img, coordinates) if cell == 3: screen.blit(Block.playerStartImg, coordinates) if cell == 4: screen.blit(Block.playerEndImg, coordinates) if cell == 5: screen.blit(Block.enemyImg, coordinates) if cell == 200: pygame.draw.rect(screen, (60, 60, 60), cellRect)
Markdown
UTF-8
4,152
2.8125
3
[]
no_license
## Analysis of COVID-19 (SARS-CoV-2) Check back for weekly updates as this is very much a work in progress. {r} [Also see the full project on Kaggle] (https://www.kaggle.com/mcnamamj/covid-19-graphing-and-mapping) ### Date Parsing and Formatting Including the code below as it's nearly boilerplate for date formatting. In some cases the strsplit will need to be adjusted, but I find it much more efficient to parse and reformat a date each time than try to accomodate different date formats across datasets. ```r # Date to char for parsing and conversion data$date <- as.character(data$date) # Parse the date data$year<-sapply(data$date, function(x) as.numeric(strsplit(x,"/")[[1]][3])) data$month<-sapply(data$date, function(x) as.numeric(strsplit(x,"/")[[1]][1])) data$day<-sapply(data$date, function(x) as.numeric(strsplit(x,"/")[[1]][2])) # Put us back in the year 2000 data$year <- (data$year + 2000) # Reformat date into y-m-d data$date<-as.Date(paste0(data$year,'-',data$month,'-',data$day), format="%Y-%m-%d") # Add some weekdays for good measure data$weekday <- weekdays(as.Date(data$date)) # Put weekdays in order data$weekday <- ordered(data$weekday, levels=c("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday")) # Set X axis limits ------------------------------------------------------------------------------- Must update with data refresh time <- as.POSIXct(strptime(c("2020-01-22","2020-03-15"), format = "%y-%m-%d")) ``` ## Time Series Heat Plot At present, with China as a large confirmed case outlier (over 80,000), I rescaled the confirmed cases using a limit of 10,000 to give greater visibility to lower and emerging counts. ![](COVID19_Git_files/figure-html/unnamed-chunk-4-1.png)<!-- --> <br> <br> ## Confirmed Cases Trend Using ggplotly for an interactive plot, here are the Country/Region's in the top 20 for confirmed cases plotted since the pandemic started. ![](COVID19_Git_files/figure-html/unnamed-chunk-6-1.png)<!-- --> <br> <br> ## COVID-19 Death Trend Time series plot of top 20 County/Region's with COVID-19 related deaths ![](COVID19_Git_files/figure-html/unnamed-chunk-8-1.png)<!-- --> <br> <br> ## COVID-19 Confirmed Cases and Deaths {.tabset .tabset-fade} Graphs of relationship between confirmed cases and death for highly impacted countries. ### China Example code included, overlaying two area plots from seperate data frames. I wasn't able to identify a straightforward method to include a plot legend-- comment below if you have one! ```r ggplot() + geom_area(data=(data %>% filter(`Country/Region` %in% "China") %>% group_by(date, count)), aes(x=as.POSIXct(date),y=count), color='red', alpha=0.4, fill = 'red') + geom_area(data=(death %>% filter(`Country/Region` %in% "China") %>% group_by(date, count)), aes(x=as.POSIXct(date),y=count), color='black') + labs(title="China Confirmed Cases and Deaths", subtitle = " Red is confirmed cases \n Black is number of deaths") + xlab("Date") + ylab("Count of Cases / Deaths") ``` ![](COVID19_Git_files/figure-html/unnamed-chunk-9-1.png)<!-- --> ### US ![](COVID19_Git_files/figure-html/unnamed-chunk-10-1.png)<!-- --> ### Italy ![](COVID19_Git_files/figure-html/unnamed-chunk-11-1.png)<!-- --> ## World Map of COVID-19 {.tabset .tabset-fade} Point size reflects number of cases / deaths ### Worldwide Confirmed Cases ![](COVID19_Git_files/figure-html/unnamed-chunk-13-1.png)<!-- --> ### Worldwide COVID-19 Deaths ![](COVID19_Git_files/figure-html/unnamed-chunk-14-1.png)<!-- --> ## US Map of COVID-19 {.tabset .tabset-fade} ### US Confirmed Cases ![](COVID19_Git_files/figure-html/unnamed-chunk-16-1.png)<!-- --> ### US COVID-19 Deaths ![](COVID19_Git_files/figure-html/unnamed-chunk-17-1.png)<!-- -->
C#
UTF-8
899
3.40625
3
[]
no_license
using System; using System.Linq; using Microsoft.EntityFrameworkCore; using System.Data.SqlClient; namespace ConsoleApp { class Program { static void Main(string[] args) { Console.WriteLine("Hello World!"); var context = new UniversityDbContext(); Console.WriteLine("Enter a student name: "); // Insert new student var name = Console.ReadLine(); context.Database.ExecuteSqlCommand("INSERT INTO Students (Name) VALUES (@Name)", new SqlParameter("@Name", name)); // Print all students var students = context.Students.FromSql("SELECT * FROM Students").ToList(); foreach (var student in students) { Console.WriteLine(String.Format("ID: {0}, Name: {1}", student.ID, student.Name)); } } } }
Python
UTF-8
1,120
4.03125
4
[]
no_license
""" Module used to calculate distance between two GPS coordinates """ import math def deg_to_rad(deg): """ Converts degree to radian Arguments: deg {[float]} -- [value of degree] Returns: [float] -- [the radian value of degree] """ return deg * math.pi / 180 def distance(lat1, long1, lat2, long2): """ Calculates the distance between two GPS co-ordinates Arguments: lat1 {float} -- [Latitude of the first coordinate] long1 {float} -- [Longitude of the first coordinate] lat2 {float} -- [Latitude of the second coordinate] long2 {float} -- [Longitude of the second coordinate] Returns: {float} -- [Distance in KM between the two coordinates] """ radius = 6371 dlat = deg_to_rad(lat2 - lat1) dlong = deg_to_rad(long2 - long1) lat1 = deg_to_rad(lat1) lat2 = deg_to_rad(lat2) angle = (math.sin(dlat / 2) * math.sin(dlat / 2) + math.sin(dlong / 2) * math.sin(dlong / 2) * math.cos(lat1) * math.cos(lat2)) return radius * 2 * math.atan2(math.sqrt(angle), math.sqrt(1 - angle))
Swift
UTF-8
313
2.640625
3
[]
no_license
// // User.swift // TaskShare // // Created by 鈴木友也 on 2019/09/24. // Copyright © 2019 tomoya.suzuki. All rights reserved. // import Foundation class UserModel { let id: String let name: String init(id: String, name: String) { self.id = id self.name = name } }
Markdown
UTF-8
895
2.53125
3
[]
no_license
# Mantis layers and dashboard Those files have been written for BibLibre Mantis customer support platform. There are some informations that are specific to our usage of Mantis. - all BibLibre accounts start with an _ Somme of our staff are dedicated to support. In the layer, the field "pôle assignataire" is based on this: if user start with a _ then he/she is from BibLibre. Members of the support team are hardcoded in the field definition - our project are organised with parents. For example we have a "maintenance Koha", each Koha customer project being a sub-project of this one. The "Projet pôle support" (in the folder "projet") uses this information - we have some local values for status, see ("statut" field in "Ticket" folder) - the field "hébergé ou non" (under "Projet" folder) is calculated from the project name. If it has a "(h)" then it's a customer we're hosting.
Python
UTF-8
2,596
2.953125
3
[ "MIT" ]
permissive
import django.forms as forms class ResultsSortingForm(forms.Form): """Allows the user to select a key and ordering for sorting results.""" sort_key = forms.fields.ChoiceField( choices=[ ("start_time", "Date"), ("name_tag", "Name"), ("progress", "Status"), ("spatial_reference_configuration_id__dataset__pretty_name", "Reference dataset"), ], required=False, ) sort_order = forms.fields.ChoiceField( choices=[ ("desc", "descending"), ("asc", "ascending"), ], required=False, ) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # set initial values on field level too for field in self.fields: self.fields[field].initial = self.get_initial_for_field( self.fields[field], field ) def clean(self): """Clean the data and replace missing by initial.""" cleaned_data = super().clean() # replace missing/invalid values with initial values for field in self.fields: if field not in self.data or field not in cleaned_data: cleaned_data[field] = self.get_initial_for_field( self.fields[field], field ) @classmethod def get_sorting( cls, request, initial_key="start_time", initial_order="desc" ): """ Create a sorting form from the given request. Parameters ---------- request : request initial_key : str, optional Options are: "start_time" (default), "name_tag", "progress", "spatial_reference_configuration_id__dataset__pretty_name". initial_order : str, optional Options are: "desc" (default), "asc" Returns ------- sorting_form : ResultsSortingForm order : str String for use in ``order_by``, including key and ordering direction. """ key, order = initial_key, initial_order form = cls( request.GET, initial={"sort_key": initial_key, "sort_order": initial_order} ) if form.is_valid(): key = form.cleaned_data["sort_key"] order = form.cleaned_data["sort_order"] order_string = {"asc": "", "desc": "-"}[order] + key # set attributes on form to access in html form.key = key form.order = order return form, order_string
Java
UTF-8
1,745
2
2
[ "Apache-2.0" ]
permissive
/* * Copyright 2015-present Milos Gligoric * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.ekstazi.check; import java.util.Set; import org.ekstazi.data.RegData; import org.ekstazi.data.Storer; import org.ekstazi.hash.Hasher; import org.ekstazi.log.Log; /** * This class is only used in debug mode. The class should not change * behavior of the superclass but only print debug info of interest. */ final class DebugNameCheck extends NameBasedCheck { /** * Constructor. */ public DebugNameCheck(Storer storer, Hasher hasher, String extension) { super(storer, hasher, extension); } @Override protected boolean isAffected(String dirName, String className, String methodName) { Log.d("Checking::Class::", className); return super.isAffected(dirName, className, methodName); } @Override protected boolean isAffected(Set<RegData> regData) { for (RegData el: regData) { if (hasHashChanged(mHasher, el)) { Log.d("Checking::Diff::", el.getURLExternalForm()); } else { Log.d("Checking::Same::", el.getURLExternalForm()); } } return super.isAffected(regData); } }
Java
UTF-8
6,442
3.578125
4
[]
no_license
package com.company; import java.util.ArrayDeque; import java.util.Stack; public class MyBST { public Node root; public void add(Object itemToAdd) { Node newNode = new Node(itemToAdd); if(root == null) { root = newNode; } else { Node current = root; Node parent; while(true) { parent = current; if((Integer)(itemToAdd) < (Integer)(current.val)) { current = current.leftChild; if(current == null) { parent.leftChild = newNode; return; } } else { current = current.rightChild; if(current == null) { parent.rightChild = newNode; return; } } }// end of while(true) } } public void remove(Object value) { Node current = root; Node parent = root; boolean isLeft = false; boolean isRight = false; while(current.val != value) { parent = current; isLeft = false; isRight = false; if((Integer)value < (Integer)current.val) { current = current.leftChild; isLeft = true; } else { current = current.rightChild; isRight = true; } } if((current.leftChild == null) && (current.rightChild == null)) { System.out.println("It's a leaf node, there are no child nodes"); if(isLeft) { parent.leftChild = null; } else if(isRight) { parent.rightChild = null; } } else if((current.leftChild != null) && (current.rightChild == null)) { System.out.println("It's not a leaf node, there are left child nodes"); if(isLeft) { parent.leftChild = current.leftChild; } else if(isRight) { parent.rightChild = current.leftChild; } current = null; } else if((current.leftChild == null) && (current.rightChild != null)) { System.out.println("It's not a leaf node, there are right child nodes"); if(isLeft) { parent.leftChild = current.rightChild; } else if(isRight) { parent.rightChild = current.rightChild; } current = null; } else { System.out.println("It's not a leaf node, there are left and right child nodes"); if(isLeft) { parent.leftChild = current.rightChild; Node currentLeft = current.rightChild; Node parentLeft = currentLeft; while(currentLeft != null) { parentLeft = currentLeft; currentLeft = currentLeft.leftChild; } parentLeft.leftChild = current.leftChild; current = null; } else if(isRight) { parent.rightChild = current.rightChild; Node currentLeft = current.rightChild; Node parentLeft = currentLeft; while(currentLeft != null) { parentLeft = currentLeft; currentLeft = currentLeft.leftChild; } parentLeft.leftChild = current.leftChild; current = null; } } } public void preOrderTraversal(Node localNode) { if(localNode != null) { System.out.println(localNode.val); preOrderTraversal(localNode.leftChild); preOrderTraversal(localNode.rightChild); } } public Node find(Object objectToFind) { Node current = root; while(current.val != (Integer)objectToFind) { if((Integer)objectToFind < (Integer)current.val) { current = current.leftChild; } else { current = current.rightChild; } if(current == null) { return null; } } return current; } public void inOrderTraversal(Node localNode) { if(localNode != null) { inOrderTraversal(localNode.leftChild); System.out.println(localNode.val); inOrderTraversal(localNode.rightChild); } } public void postOrderTraversal(Node localNode) { if(localNode != null) { postOrderTraversal(localNode.leftChild); postOrderTraversal(localNode.rightChild); System.out.println(localNode.val); } } public void breadthFirstSearch(Node node) { if(node==null){ System.out.print("empty tree"); return; } ArrayDeque<Node> deque = new ArrayDeque<Node>(); deque.add(node); while(!deque.isEmpty()){ Node rnode = deque.remove(); System.out.print(rnode.val+" "); if(rnode.leftChild!=null){ deque.add(rnode.leftChild); } if(rnode.rightChild!=null){ deque.add(rnode.rightChild); } } } public void clear(Node root) { if (root==null) return ; if (root.leftChild != null) clear(root.leftChild); if (root.rightChild != null) clear(root.rightChild); root.leftChild = null; root.rightChild = null; this.root=null; } public int size(Node root) { if(root==null){ return 0; } return 1+size(root.leftChild)+size(root.rightChild); } public class Node { Object val; Node leftChild; Node rightChild; Node(Object val) { this.val = val; } public void printNode() { System.out.println(val); } } }
Markdown
UTF-8
996
2.53125
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
--- layout: post title: "Efficient Search Not Good for Research?" description: Originally published on mobblog.cs.ucl.ac.uk categories: [research] --- I read a a curious article posted on <a href="http://blog.wired.com/wiredscience/2008/07/is-the-internet.html">wired</a>: based on a recent study of journal citation patterns between '98 and '05 (that is to appear in Science), the authors claim that as the Internet provides researchers with efficient search of journal papers, "the breadth of scholarship" is being lost. Here is a quote: > "As more journal issues came online, the articles referenced tended to be more recent, fewer journals and articles were cited, and more of the citations were to fewer journals and articles." So, is this google scholar's fault? Is this a new trend in research? Or maybe this means that as the wealth of published research explodes, the truly cite-able papers are still few (i.e., is citation breadth a measure of quality (or not)?) What do you think?
C#
UTF-8
1,549
2.625
3
[]
no_license
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.EventSystems; public class DifficultyHoverButton : MonoBehaviour, IPointerEnterHandler, IPointerExitHandler { public bool isActive; //keeps track of whether the button is held public DifficultyManager diffMan; //the active DifficultyManager public float time; //time the button has been held for public Text dText; //the text box of the button public Toggle tog; // Start is called before the first frame update void Start() { isActive = false; time = 0.0f; } // Update is called once per frame void Update() { if (isActive) //if button is held { time += Time.deltaTime; //subtract the time since the last frame from the time limit //Debug.Log(time); if (time >= PlayerControl.clickSpeed) //if n seconds have passed, "click" the button { time = 0.0f; tog.isOn = true; OnClick(); isActive = false; } } } public void OnPointerEnter(PointerEventData eventData) { isActive = true; //Debug.Log("Button held"); //dText.text = "Hovering over button for " + time + "seconds"; } public void OnPointerExit(PointerEventData eventData) { isActive = false; time = 0.0f; } public void OnClick() { diffMan.changeDifficulty(dText.text); } }
JavaScript
UTF-8
607
2.546875
3
[]
no_license
import React from 'react'; class SearchForm extends React.Component{ state = { query: '' }; handleInput = (e) => { // console.log(e.target.value); this.setState({ query: e.target.value }) }; handleSubmit = (e) => { e.preventDefault(); // console.log(this.state.query); this.props.onSearch(this.state.query); }; render() { return( <div> <form onSubmit={this.handleSubmit}> <input type="text" onChange={this.handleInput} /> <button>Search</button> </form> </div> ); } } export default SearchForm;
C++
UTF-8
1,358
3.234375
3
[]
no_license
#ifndef KLONDIKE_CARDPROPERTY_H #define KLONDIKE_CARDPROPERTY_H #include <string> class CardProperty { public: CardProperty(const int& value, const std::string& propertyString) : value_(value), propertyString_(propertyString) {} protected: int getValue() const { return value_; } std::string getPropertyString() const { return propertyString_; } private: int value_; std::string propertyString_; friend bool operator<(const CardProperty& l, const CardProperty& r); friend bool operator==(const CardProperty& l, const CardProperty& r); friend std::ostream& operator<<(std::ostream& os, const CardProperty& obj); }; inline bool operator<(const CardProperty& lhs, const CardProperty& rhs) { return lhs.value_ < rhs.value_; } inline bool operator>(const CardProperty& lhs, const CardProperty& rhs) { return rhs < lhs; } inline bool operator<=(const CardProperty& lhs, const CardProperty& rhs) { return !(lhs > rhs); } inline bool operator>=(const CardProperty& lhs, const CardProperty& rhs) { return !(lhs < rhs); } inline bool operator==(const CardProperty& lhs, const CardProperty& rhs) { return lhs.value_ == rhs.value_; } inline bool operator!=(const CardProperty& lhs, const CardProperty& rhs) { return !(lhs == rhs); } #endif //KLONDIKE_CARDPROPERTY_H
JavaScript
UTF-8
3,522
2.53125
3
[]
no_license
import constants from "./constants.js"; import selectors from './selectors.js'; import utils from './utils.js'; function update(state, action) { const { type } = action; switch (type) { case constants.CHANGE_CURRENT_INPUT: const searchString = utils.replaceAccentuatedChars(action.value); return Object.assign({}, state, { activeCommandIndex: 0, currentValue: action.value, displayedCommands: selectors.getCurrentCommandsForSelection(state, state.selection) .filter(cmd => utils.replaceAccentuatedChars(cmd.text).includes(searchString)) }); case constants.EXPAND: const expandedState = Object.assign({}, state, { activeCommandIndex: 0, focused: true }); return Object.assign({}, expandedState, { displayedCommands: selectors.getCurrentCommandsForSelection(state, state.selection) }); case constants.BLUR_INPUT: return Object.assign({}, state, { activeCommandIndex: 0, focused: false, currentValue: "", history: [], displayedCommands: [], selection: [] }); case constants.SET_LOADER: return Object.assign({}, state, { loading: true }); case constants.RECEIVE_COMMAND_RESULTS: const nextState = Object.assign({}, state, { activeCommandIndex: 0, currentValue: "", loading: false, focused: true, history: [...state.history, { command: action.command, selection: selectors.getSelection(state), results: action.results }], selection: [] }); return Object.assign({} ,nextState, { displayedCommands: selectors.getCurrentCommandsForSelection(nextState) }); case constants.NAVIGATE_BACKWARD: const history = selectors.getHistory(state); const newHistory = history.slice(0, history.length - 1); const previousState = Object.assign({}, state, { activeCommandIndex: 0, currentValue: "", loading: false, history: newHistory, selection: newHistory[newHistory.length - 1] ? newHistory[newHistory.length - 1].selection : [] }); return Object.assign({} ,previousState, { displayedCommands: selectors.getCurrentCommandsForSelection(previousState) }); case constants.SET_ACTIVE_ITEM_INDEX: const maxIndex = selectors.getDisplayedCommands(state).length - 1; const newIndex = action.value; return Object.assign({}, state, { activeCommandIndex: Math.min(Math.max(0, newIndex), maxIndex), focused: true, }); case constants.ADD_ACTIVE_ITEM_TO_SELECTION: const command = selectors.getDisplayedCommandAt(state, state.activeCommandIndex); if (!command.group) { return state; } const newSelection = [...state.selection, command]; return Object.assign({}, state, { activeCommandIndex: 0, currentValue: "", displayedCommands: selectors.getCurrentCommandsForSelection(state, newSelection), selection: newSelection }); default: } return state; } export default function (options) { const initialState = { activeCommandIndex: null, currentValue: "", focused: false, loading: false, getCommands: options.getCommands, displayedCommands: [], selection: [], history: [] }; return (state = initialState, action) => update(state, action); };
JavaScript
UTF-8
1,914
3.46875
3
[]
no_license
window.onload = function(){ var now = new Date(); // 현재 날짜 var nowmonth = new Date(now.getFullYear(),now.getMonth()); // 21년 6월 1일 changehead(nowmonth); // 현재 년월을 기록 buildCalendar(nowmonth); // 달력 작성하는 함수 }; function selectMonth(){ var yearMonth = document.getElementById('selectMonth').value; var selectYearMonth = new Date(yearMonth); changehead(selectYearMonth); // 입력된 년월을 기록 buildCalendar(selectYearMonth); } function changehead(selectDate){ // 작성된 년월 표기 document.getElementById('head').innerHTML = selectDate.getFullYear()+'년'+(selectDate.getMonth()+1)+'월' } function buildCalendar(selectDate){ //alert('달력작성'); var calendar = document.getElementById('calendarBody'); calendar.innerHTML=''; var monthLastDay = lastDate(selectDate); // 마지막 날짜 var weekInfo = selectDate.getDay(); // 주 정보를 가져오기 일요일0, 월1~토6 var dateCnt = selectDate.getDate()-weekInfo; while(true){ // 주간 반복 : 행 var weekLine = document.createElement('tr'); for(var weekCnt=0;weekCnt<7;weekCnt++){// 날짜 반복(7번 반복) var weekDay = document.createElement('td'); if(0<dateCnt && dateCnt<=monthLastDay){ weekDay.innerHTML = dateCnt; // 날짜를 기록 } dateCnt++; weekLine.appendChild(weekDay); } calendar.appendChild(weekLine); if(dateCnt>monthLastDay){ break; } } } function lastDate(selectDate){ //각 달의 마지막 날짜 var year = selectDate.getFullYear(); var month = selectDate.getMonth(); var monthArr = [31,28,31,30,31,30,31,31,30,31,30,31]; if(((year%4==0) && (year%100!=0)) || (year%400==0)){ monthArr[1] = 29; } return monthArr[month]; }
C++
UTF-8
933
2.75
3
[]
no_license
int IN1=9; int IN2=8; int IN3=11; int IN4=10; int ECHO=12; int TRIG=13; void setup() { Serial.begin(9600); pinMode(TRIG,OUTPUT); pinMode(ECHO,INPUT); pinMode(IN1,OUTPUT); pinMode(IN2,OUTPUT); pinMode(IN3,OUTPUT); pinMode(IN4,OUTPUT); } void loop() { horario(IN1,IN2); antihorario(IN1,IN2); sensor_distancia(ECHO,TRIG); horario(IN3,IN4); antihorario(IN3,IN4); } int horario (int m, int n){ digitalWrite(m,HIGH); digitalWrite(n,LOW); } int antihorario (int m, int n){ digitalWrite(m,LOW); digitalWrite(n,HIGH); } int sensor_distancia(int x, int y){ digitalWrite(y, LOW); delayMicroseconds(2); digitalWrite(y, HIGH); delayMicroseconds(10); digitalWrite(y, LOW); float distancia; unsigned long tiempo; tiempo=pulseIn(x, HIGH); distancia= float(0.017*tiempo); Serial.print("Distancia :"); Serial.print(distancia); Serial.println(" cm"); return distancia; delay(1000); }
Markdown
UTF-8
2,828
3.90625
4
[]
no_license
- A graph is **a collection of nodes with edges between (some of) them** - Can be **directed** (one-way street) \***\*or **undirected\*\* (two-way street). ## Basics --- ```python # Simple definition of a tree node class Node: def __init__(self): self.val = None # value of the node self.children = None # a list of nodes ``` **Binary Tree:** A tree in which each node has up to two children **Binary Search Tree:** A binary tree in which every node fits a specific ordering property: **all left descendents ≤ n < all right decendents** for each node n You should clarify the definition with the interviewer, e.g. **for BST, what will duplicate input behave ?** **Balanced vs. Unbalanced:** balanced trees are "not terribly imbalanced", it's balanced enough to ensure O( log n ) time for insert and find, not necessarily "perfectly balanced" ## Binary Tree traversal --- ```python # Binary tree node definition class TreeNode: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right root = TreeNode(12) root.left = TreeNode(7) ``` **Three types of traversal:** in-order, post-order, and pre-order ```python **# In-order traversal** # visit the left branch, then the current node, and finally the right node def inOrderTraversal(node): if node: inOrderTraversal(node.left) visit(node) inOrderTraversal(node.right) # when performed on a binary search tree, it visits the nodes in ascending order (in-order) ``` ```python **# Post-order traversal** # visit the current node after its child nodes (post-order) def postOrderTraversal(node): if node: postOrderTraversal(node.left) postOrderTraversal(node.right) visit(node) # the root is always the last node visited ``` ```python **# Pre-order traversal** # visit the current node before its child nodes (post-order) def postOrderTraversal(node): if node: visit(node) postOrderTraversal(node.left) postOrderTraversal(node.right) # the root is always the first node visited ``` ## Graphs --- - A tree is a type of graph, a tree is a **connected graph without cycles** **2 common ways to represent a graph:** adjacency list & adjacency matrices ```python **# Adjacency List** # Most common way to represent a graph, each vertex (node) stores a list of adjacent nodes class Graph: # Graph class is used because, unlike in a tree, you can't necessarily reach all the nodes from a single node def __init__(self, nodes = None): self.nodes = nodes # a list of adjacent nodes class Node: def __init__(self, name = None, children = None): self.name = name self.children = children ``` **Adjacent Matrices (explore later)** ## Graph Search --- 2 most common ways to search a graph: **depth-first search & breadth-first search** ## Extra --- - **Binary Heaps & Tries**
Markdown
UTF-8
665
2.75
3
[ "MIT" ]
permissive
# react-text-annotate [![NPM](https://img.shields.io/npm/v/react-text-annotate)](https://www.npmjs.com/package/react-text-annotate) A React component for interactively highlighting parts of text. ## Usage React `16.8.0` or higher is required as a peer dependency of this package. ``` npm install --save react-text-annotate ``` [Docs](https://mcamac.github.io/react-text-annotate/) ## Examples A simple controlled annotation. ```tsx import {TokenAnnotator, TextAnnotator} from 'react-text-annotate' <TokenAnnotator tokens={['My', 'text', 'needs', 'annotating', 'for', 'NLP', 'training']} value={[{start: 5, end: 6, tag: 'TOPIC', color: '#EEE'}]} /> ```
Python
UTF-8
2,220
4.34375
4
[]
no_license
""" Find LCA for Binary tree 1. Using O(N) 2. No parent pointers Option 1 : How about generating all the paths from the root to leaf and finding the intersecting node from the leaf node or the last intersecting node from the root. - step 1: find the path from the root to node1 - step 2: find the path from the root to node2 - step 3: traverse the path, until you find the mismatch and store the previous matching value. https://www.geeksforgeeks.org/lowest-common-ancestor-binary-tree-set-1/ """ def findLCA(root, n1, n2): if root is None: return None path1 = [] path2 = [] if not find_path(root, n1, path1) or not find_path(root, n2, path2): return None i = 0 while i < len(path1) and i < len(path2): if path1[i] != path2[i]: break i += 1 return path1[i - 1][0] def find_path(root, k, path=[]): """ Returns True/False, if a path exists between root and node k. Also, populates the path if it exists :param root: :param k: :param path: :return: """ if root is None: return None # path.append(root.val) < if you just need to return the value path.append((root, root.val)) if root.val == k: return True # find k in the left or right subtree if (root.left != None and find_path(root.left, k, path)) or (root.right != None and find_path(root.right, k, path)): return True # If not present in subtree rooted with root, remove # root from path and return False path.pop() return False # Driver Program to test # Driver program to test above function # Let's create the Binary Tree shown in above diagram # A binary tree node class Node: # Constructor to create a new binary node def __init__(self, key): self.key = key self.left = None self.right = None root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) root.right.left = Node(6) root.right.right = Node(7) print "LCA(4, 5) = %d" % (findLCA(root, 4, 5, )) print "LCA(4, 6) = %d" % (findLCA(root, 4, 6)) print "LCA(3, 4) = %d" % (findLCA(root, 3, 4)) print "LCA(2, 4) = %d" % (findLCA(root, 2, 4))
Python
UTF-8
465
3.015625
3
[]
no_license
# -*- coding: utf-8 -*- # @Time : 2020/1/3 8:55 # @Author : Aiopr # @Email : 5860034@qq.com class C4: s = 66 t = 99 def __init__(self): pass def test(self): a = 1 b = 2 c = a + b + self.__class__.t return c @classmethod def plus_sum(self): e = C4.t + C4.s return e print(test.__dict__) st = C4() print(C4.__dict__) print('\n<<<') print(st.test()) print(st.plus_sum()) print('\n>>>')
Java
UTF-8
1,501
3.96875
4
[]
no_license
/** 编写一个函数,以字符串作为输入,反转该字符串中的元音字母。 示例 1: 给定 s = "hello", 返回 "holle". 示例 2: 给定 s = "leetcode", 返回 "leotcede". 注意: 元音字母不包括 "y". */ class Solution_345 { public String reverseVowels(String s) { // 从两端反转字符串中的字符,很容易会想到 碰撞指针方法 int l=0, r = s.length()-1; // 涉及到交换字符串元素,所以转换为字符数组 char[] sChar = s.toCharArray(); while( l < r){ while(!isVowels(sChar[l]) && l < r){ // 从前向后定位元音 l++; } while(!isVowels(sChar[r]) && l < r){ // 从后向前定位元音 r--; } if(l < r){ char t = sChar[l]; sChar[l] = sChar[r]; sChar[r] = t; l++; r--; } } return String.copyValueOf(sChar); } // 判断是否为元音字符 private boolean isVowels(char c){ switch(c){ case 'a': case 'e': case 'i': case 'o': case 'u': case 'A': case 'E': case 'I': case 'O': case 'U': return true; default : return false; } } }
Python
UTF-8
680
2.953125
3
[ "MIT" ]
permissive
""" Checks that Pylint does not complain about a fairly standard Django Model """ # pylint: disable=missing-docstring from django.db import models class SomeModel(models.Model): class Meta: pass some_field = models.CharField(max_length=20) other_fields = models.ManyToManyField('AnotherModel') def stuff(self): try: print(self._meta) print(self.other_fields.all()[0]) except self.DoesNotExist: print('does not exist') except self.MultipleObjectsReturned: print('lala') print(self.get_some_field_display()) class SubclassModel(SomeModel): class Meta: pass
C
UTF-8
1,521
2.6875
3
[]
no_license
/* ** EPITECH PROJECT, 2019 ** MUL_my_rpg_2019 ** File description: ** new_score.c */ #include "fight.h" #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> static int get_score(char *path) { int score = 0; int fd = open(path, O_RDONLY); char *scr = NULL; if (fd == -1) return -1; scr = get_next_line(fd); if (scr == NULL) return -1; score = my_getnbr(scr); free(scr); close(fd); return score; } static int fill_score(int scr, char *path) { int fd = open(path, O_WRONLY); char *score = int_str((int)scr); if (fd == -1 || score == NULL) return 84; if (write(fd, score, my_strlen(score)) == -1) return 84; free(score); close(fd); return 0; } int new_score(game_t *game, fight_t *fight) { int last_score = get_score("src/menu/highscore/lastscore.txt"); int high_score = get_score("src/menu/highscore/highscore.txt"); if (last_score == -1 || high_score == -1) return 84; if (fight->hp_boss > 0) return 0; game->time->time = sfClock_getElapsedTime(game->time->clock); game->time->seconds = sfTime_asMilliseconds(game->time->time); if (fill_score(game->time->seconds, "src/menu/highscore/lastscore.txt") == 84) return 84; if (high_score == 0 || (int)(game->time->seconds) < high_score) { if (fill_score(game->time->seconds, "src/menu/highscore/highscore.txt") == 84) return 84; } return 0; }
TypeScript
UTF-8
21,429
3.25
3
[]
no_license
// @flow import isEqual from 'lodash/isEqual'; import pickBy from 'lodash/pickBy'; import qs from 'query-string'; import { useCallback, useEffect, useMemo, useReducer, useRef } from 'react'; type Decode = (value: string, paramName: string) => any; type Encode = (value: any, paramName: string) => string; type EncodeDecode = [Decode, Encode]; type ParamsEncodeDecode = Record<string, EncodeDecode | Decode>; /** * @expandproperties */ export type UseUrlQueryStateOptions = { /** * An object mapping a key name to either a 2-tuple of a decode & encode function or * a single decode function. * * The decode function is used to parse query values to transform them to a certain type or shape. * * The encode function is used stringify a value to be stored in the URL. When using the * single function form (just the decode function) then the encode function is the equivalent * of calling the toString() method on the value. * * Both decode and encode are passed 2 arguments; the value to transform and the name of the parameter. * * A special key '*' can be set to define the fallback behaviour for all keys not explicitly defined. */ params?: ParamsEncodeDecode; /** * A value to prefix query param keys with. The returned state object * contains the un-prefixed keys. * * If not specified all query params are sync'd. To make this work nicely * with other usages of the hook on the same page consider setting * `controlledKeys` */ prefix?: string; /** * If specified only these keys will be synced to and read from the request * URL. Any other keys will be ignored. If `true` is passed then all the fields specified in `params` * will be used as the value (`params` must be supplied in this case).` */ controlledKeys?: Array<string> | true; /** * The current location. This depends on your router integration. */ location?: { search: string; pathname: string; }; /** * A function that replaces the current url. This depends on your router integration. */ replaceUrl?: (url: string) => void; }; // Wildcard used to indicate all fields in `params` option const WILDCARD = '*'; /** * Create new object from `obj` without keys `withoutKeys` */ const pickWithoutKeys = ( obj: Record<string, any>, withoutKeys: Array<string> ): Record<string, any> => pickBy(obj, (value: any, key: string) => !withoutKeys.includes(key)); function encode(key: string, value: any, params: ParamsEncodeDecode): string { const p = params[key] || params[WILDCARD]; if (!p || !Array.isArray(p)) { return value == null ? value : value.toString(); } return p[1](value, key); } function decode(key: string, value: any, params: ParamsEncodeDecode): string { const p = params[key] || params[WILDCARD]; if (!p) { return value; } if (Array.isArray(p)) { return p[0](value, key); } return p(value, key); } /** * Build query params object to set in URL. * * Prefixes all keys in `obj` with `prefix` and set value to value returned * by `stringify` */ const buildQueryForUrl = ( obj: {}, prefix: string, params: ParamsEncodeDecode, controlledKeys?: string[] | true ): Record<string, string> => { return Object.entries(obj).reduce((acc, [key, value]) => { if ( !controlledKeys || (Array.isArray(controlledKeys) ? controlledKeys.includes(key) : key in params) ) { acc[prefix + key] = encode(key, value, params); } return acc; }, {}); }; /** * Build query param object for use by consumer of hook. * * Removes prefix `prefix` from all keys in `obj` and sets the value to the * value returned by `parse` */ const buildQueryForState = ( obj: Record<string, any>, prefix: string, params: ParamsEncodeDecode, controlledKeys?: string[] | true ): Record<string, any> => { return Object.entries(obj).reduce((acc, [key, value]) => { if (key.startsWith(prefix)) { const unprefixedKey = key.substring(prefix.length); if ( !controlledKeys || (Array.isArray(controlledKeys) ? controlledKeys.includes(unprefixedKey) : unprefixedKey in params) ) { acc[unprefixedKey] = decode(key, value, params); } } return acc; }, {}); }; // TODO: Should the default parse actually do something special here? eg. if it's // 'true' or 'false' transform to bool? if it looks like a number convert to number? // Date handling? // TODO: Should stringify have any special cases? Dates? Arrays? Nested objects? const DEFAULT_PARAMS = {}; /** * Use URL query string as state. This is like `useState` except the state value * is always an object and the state is stored in the URL. * * This hook parses the query string and returns that as an object along with a * setter function to transition state values. The setter will transition the * URL to match the query params specified. * * As different router integrations handle history and navigation differently you * can pass the current location and a function to replace the current URL to options. * * By default it will work with `window.location` and the [History API](https://developer.mozilla.org/en-US/docs/Web/API/History_API) * * For react-router: * * ```js * import { useLocation, useHistory } from 'react-router'; * * function useRouterUrlQueryState(initialState = {}, options = {}) { * const location = useLocation(); * const history = useHistory(); * return useUrlQueryState({}, { location, replaceUrl: history.replace }); * } * ``` * * For navi: * * ```js * import { useUrlQueryState } from '@prestojs/routing'; * import { useCallback } from 'react'; * import { useCurrentRoute, useNavigation } from 'react-navi'; * * export default function useNaviUrlQueryState(initialState = {}, options = {}) { * const { url } = useCurrentRoute(); * const navigation = useNavigation(); * const replaceUrl = useCallback(nextUrl => navigation.navigate(nextUrl, { replace: true }), [ * navigation, * ]); * return useUrlQueryState(initialState, { * ...options, * url, * replaceUrl, * }); * } * ``` * * NOTE: Due to the fact that everything in the URL is represented as a string * the returned values in the state object will all be strings. Use `options.parse` * to do any transforms required on these values. * * @param {Object} initialState The initial state values. If any of the specified * keys don't exist in the URL already the URL will be changed such that they * do. If all the keys do exist in the URL already this option has no effect. * * @example * * ```jslive * # OPTIONS: {"fakeBrowser": true} * function ExampleUrlSync() { * const parse = (c) => Number(c); * const [urlState, setUrlState] = useUrlQueryState({ count: 1 }, { parse }); * const onClick = () => setUrlState(s => ({ count: s.count + 1 })); * return ( * <Button onClick={onClick}>{urlState.count} Increment</Button> * ); * } * <ExampleUrlSync /> * ``` * * Same thing but with a prefix: * * ```jslive * # OPTIONS: {"fakeBrowser": true} * function ExampleUrlSync() { * const parse = (c) => Number(c); * const [urlState, setUrlState] = useUrlQueryState( * { count: 1 }, * { parse, prefix: 'test_' } * ); * const onClick = () => setUrlState(s => ({ count: s.count + 1 })); * return ( * <Button onClick={onClick}>{urlState.count} Increment</Button> * ); * } * <ExampleUrlSync prefix="p_" /> * ``` * * Partially control URL query params when no prefix is set * ```jslive * # OPTIONS: {"fakeBrowser": "/?name=test&page=1&count=5"} * function ExampleUrlSyncControlled() { * const parse = (c) => Number(c); * const [urlState, setUrlState] = useUrlQueryState( * { count: 1 }, * { parse, controlledKeys: ['count'] } * ); * const onClick = () => setUrlState(s => ({ count: s.count + 1 })); * return ( * <Button onClick={onClick}>{urlState.count} Increment</Button> * ); * } * <ExampleUrlSyncControlled /> * ``` * * Advanced parse & stringify * * ```jslive * # OPTIONS: {"fakeBrowser": true } * function ExampleUrlSyncControlled() { * const [urlState, setUrlState] = useUrlQueryState( * { data: { name: 'Dave', email: '' }, count: 1 }, * { * params: { * count: value => Number(value), * data: [value => JSON.parse(value), value => JSON.stringify(value)], * }, * } * ); * const onClick = () => setUrlState(s => ({ ...s, count: s.count + 1 })); * const { data = {} } = urlState; * return ( * <div> * <input * value={data.name} * onChange={({ target: { value }}) => setUrlState(s => ({ * ...s, * data: { ...s.data, name: value }, * }))} * /> * <input * value={data.email} * onChange={({ target: { value }}) => setUrlState(s => ({ * ...s, * data: { ...s.data, email: value }, * }))} * /> * <Button onClick={onClick}>{urlState.count} Increment</Button> * <hr /> * State: * <pre> * {JSON.stringify(urlState, null, 2)} * </pre> * </div> * ); * } * <ExampleUrlSyncControlled /> * ``` * * @extractdocs */ export default function useUrlQueryState( initialState: {} = {}, options: UseUrlQueryStateOptions = {} ): [ /** * The current query state * * If `options.prefix` is specified this contains only query param keys that * start with the prefix otherwise it contains _all_ query params. */ Record<string, any>, /** * State transition function. Accepts either the state object to transition * to OR a transition function. * * A transition function should accept the current state and return the new * state (eg. same as `useState`). * * The state specified always replaces the current state - it is not merged * except with the caveats noted below. * * As the URL could be used by multiple hooks or other components the following * are the rules that are applied when determining what to keep in the URL: * * If `options.controlledKeys` is not specified then any query param keys * that match the specified list will be removed if not included in the new * state object. Any keys not in the specified list will be retained. * * If `options.controlledKeys` is not specified and `options.prefix` is specified * then any query param keys that start with the prefix will be removed if * not included in the new state object. Any keys not starting with `prefix` will * be retained. * * If `options.controlledKeys` and `options.prefix` are not specified then * query param keys not included in the new state object will be removed. * * @example * * Pass object directly * * ```js * const [urlState, setUrlState] = useUrlQueryState(); * const onPaginationChange = (page, pageSize) => { * setUrlState({ page, pageSize}); * }; * ``` * * Pass callback that gets current state * ```js * const [urlState, setUrlState] = useUrlQueryState({ page: 1 }); * const onNextPage = () => { * setUrlState(currentState => ({ * ...currentState, * page: currentState.page + 1, * }); * }; * ``` */ ( value: Record<string, any> | ((currentQuery: Record<string, any>) => Record<string, any>) ) => void ] { const { prefix = '', params = DEFAULT_PARAMS, controlledKeys, location = typeof window != 'undefined' && window.location, } = options; if ( !location || (!options.replaceUrl && typeof window !== 'undefined' && location !== window.location) ) { throw new Error('The url and replaceUrl options must be provided'); } if (controlledKeys === true && params[WILDCARD]) { throw new Error('controlledKeys=true cannot be used with a wildcard in `params`'); } // Only used when using window.location to force render on change const [, forceRender] = useReducer(s => !s, false); const replaceUrl = useMemo(() => { if (options.replaceUrl) { return options.replaceUrl; } if (typeof window !== 'undefined' && location === window.location) { return (url: string): void => { window.history.pushState(null, '', url); forceRender(); }; } // This should never happen; we check above throw new Error('replaceUrl must be specified'); }, [options.replaceUrl, location]); // When using window.location we need to handle back/forward navigation. When this occurs update // query params. This is a no-op when not using window.location. useEffect(() => { if (typeof window !== 'undefined' && location === window.location) { const listener = (): void => { forceRender(); }; window.addEventListener('popstate', listener); return (): void => window.removeEventListener('popstate', listener); } }, [location]); const { search, pathname } = location; const isFirstRender = useRef(true); // Starts as `true` // - If no `initialState` or there's no keys in `initialState` that aren't in URL it gets set to false // - Otherwise it gets set to the initial `query` parameters based on current query string and `initialState` // - This triggers a `replaceUrl` which we want to wait for before setting it to false // - Once the location `search` matches the stored value here we set it to false // This is used to track whether or not we need to return the `initialValues` explicitly or whether // we know it's included in the URL. This is to avoid the issue where the returned query parameters don't // include `initialState` until after the `replaceUrl` is called to add them to the URL. We specifically // track the query rather than assuming the second render is due to the `replaceUrl` because we don't control // the implementation of `replaceUrl` - if something happens that causes another render to occur before // `replaceUrl` propagates then the second render may not include the `initialState`. const pendingInitialState = useRef<boolean | Record<string, any>>(true); const initialStateRef = useRef<Record<string, any>>({}); const previousStateRef = useRef<Record<string, any>>(); if (pendingInitialState.current && typeof pendingInitialState.current === 'object') { if (isEqual(qs.parse(search), pendingInitialState.current)) { pendingInitialState.current = false; } } if (isFirstRender.current) { // Only in first render do we validate keys in initialState. Any subsequent // changes to initialState are ignored. isFirstRender.current = false; const invalidKeys = Object.keys(initialState).filter(key => { return ( controlledKeys && !(Array.isArray(controlledKeys) ? controlledKeys.includes(key) : key in params) ); }); if (invalidKeys.length) { // eslint-disable-next-line no-console console.warn( `'controlledKeys' is specified but you passed keys to initialState that aren't valid: ${invalidKeys.join( ',' )}\nEither remove these keys from initialState or add them to 'controlledKeys'` ); } initialStateRef.current = Object.keys(initialState).reduce((acc, key) => { if (invalidKeys.includes(key)) { return acc; } acc[key] = initialState[key]; return acc; }, {}); } // This effect is used to update URL to include any missing keys that are // specified in initialState. It only runs once - any subsequent changes to // initialState have no effect. const hasRunAddMissingKeysEffect = useRef(false); useEffect(() => { // Protect with a ref as has imperative side effect (changing the URL) that should // only apply once (eg. in StrictMode this runs twice) if (hasRunAddMissingKeysEffect.current) { return; } hasRunAddMissingKeysEffect.current = true; const query = qs.parse(search); const missingKeys = Object.keys(initialState).filter(key => { // Exclude invalid keys if ( controlledKeys && !(Array.isArray(controlledKeys) ? controlledKeys.includes(key) : key in params) ) { return false; } return !(prefix + key in query); }); if (missingKeys.length > 0) { const nextQuery = { ...buildQueryForUrl(initialState, prefix, params, missingKeys), ...query, }; replaceUrl(`${pathname}?${qs.stringify(nextQuery)}`); pendingInitialState.current = nextQuery; } else { pendingInitialState.current = false; } // eslint-disable-next-line react-hooks/exhaustive-deps }, []); // This effect is used to handle a change in prefix. It updates any query // params with old prefix to have new prefix. const prefixCache = useRef(prefix); useEffect(() => { // If prefix hasn't changed then don't do anything. This will always be // the case the first render. Subsequent renders we bail out if hasn't // changed. We use this rather than the dependency array as even with // the dep array it will still run the first time - we have to handle it // anyway. if (prefixCache.current === prefix) { return; } const query = qs.parse(search); const existingQuery = buildQueryForState(query, prefixCache.current, params); const keys = Object.keys(query).filter(key => key.startsWith(prefixCache.current)); replaceUrl( `${pathname}?${qs.stringify({ ...pickWithoutKeys(query, keys), ...buildQueryForUrl(existingQuery, prefix, params), })}` ); prefixCache.current = prefix; }); // Return the current query params without the prefix const unPrefixedQueryObject = useMemo(() => { const state = {}; if (pendingInitialState.current) { // Assign pending first so that current query state in URL overrides any conflicts Object.assign(state, initialStateRef.current); } Object.assign(state, buildQueryForState(qs.parse(search), prefix, params, controlledKeys)); // If state hasn't changed return the same object if (previousStateRef.current && isEqual(previousStateRef.current, state)) { return previousStateRef.current; } return state; }, [controlledKeys, search, params, prefix]); previousStateRef.current = unPrefixedQueryObject; // Build the state transition callback. This will make sure the URL matches // the state specified including removing any values no included in the next // state value. const setUrlState = useCallback( (nextQuery: {}) => { const query = qs.parse(search); if (typeof nextQuery === 'function') { nextQuery = nextQuery(unPrefixedQueryObject); } let keys; if (controlledKeys === true) { keys = Object.keys(params).filter(k => k !== WILDCARD); } else if (Array.isArray(controlledKeys)) { keys = controlledKeys; } if (!keys) { keys = Object.keys(query).filter(key => key.startsWith(prefix)); } if (Array.isArray(controlledKeys)) { const invalidKeys = Object.keys(nextQuery).filter( key => !controlledKeys.includes(key) ); if (invalidKeys.length > 0) { // eslint-disable-next-line no-console console.warn( `'controlledKeys' is specified but you passed keys to setUrlState that aren't valid: ${invalidKeys.join( ',' )}\nEither remove these keys or add them to 'controlledKeys'` ); } } const finalQuery = { ...pickWithoutKeys(query, keys), ...buildQueryForUrl(nextQuery, prefix, params, controlledKeys), }; if (!isEqual(finalQuery, query)) { replaceUrl(`${pathname}?${qs.stringify(finalQuery)}`); } }, [search, controlledKeys, prefix, params, unPrefixedQueryObject, replaceUrl, pathname] ); return [unPrefixedQueryObject, setUrlState]; }
Shell
UTF-8
428
2.875
3
[]
no_license
#!/bin/bash [ $USER == "root" ] && echo "You should not install this for the root account." && exit 1 export CURRENT=${HOME}/Config [ -f ~/.gitignore_global ] || ln -s ${CURRENT}/git/gitignore_global ~/.gitignore_global [ -f ~/.bash_profile ] || ln -s ${CURRENT}/profile ~/.bash_profile [ -f ~/.tmux.conf ] || ln -s ${CURRENT}/mixture/tmux.conf ~/.tmux.conf [ -f ~/.ssh/key.map ] || cp ${CURRENT}/ssh/key.map ~/.ssh/key.map
Python
UTF-8
991
3.921875
4
[]
no_license
"""Problem 102. Binary Tree Level Order Traversal https://leetcode.com/problems/binary-tree-level-order-traversal/ Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). """ # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def level_order(self, root: TreeNode) -> List[List[int]]: if not root: return [] queue = [root] result = [] while queue: parent, children = [], [] for node in queue: parent.append(node.val) if node.left: children.append(node.left) if node.right: children.append(node.right) result.append(parent) queue = children return result
Python
UTF-8
21,555
2.734375
3
[]
no_license
from keras.applications.vgg16 import VGG16 from keras.applications.resnet50 import ResNet50 import tensorflow as tf import numpy as np import keras.backend as K class EAST: """ Building TF Graph & Session for Text Detection Model, EAST Order 1. _attach_stem_network() 2. _attach_branch_network() 3. _attach_output_network() 4. _attach_decode_network() 4. _attach_loss_network() 5. _attach_optimizer() """ def __init__(self): """ east = EAST() Building Order 1. east._attach_stem_network() 2. east._attach_branch_network() 3. east._attach_output_network() 4. east._attach_decode_network() 4. east._attach_loss_network() 5. east._attach_optimizer() Intializing Variable east.initialize_variable() """ K.clear_session() self.session = K.get_session() # Keras Pretrained Model을 쓰기 위함 self.graph = self.session.graph # Layer을 쌓는 순서를 결정해줌 self._to_build = ['stem', 'branch', 'output', 'decode', 'loss', 'optimizer'] self._built = [] self._initialize_placeholders() def build_graph(self): """ EAST의 Tensorflow Graph를 구성함 :return: self """ return (self._attach_stem_network() ._attach_branch_network() ._attach_output_network() ._attach_decode_network() ._attach_loss_network() ._attach_optimizer()) def initialize_variables(self): with self.graph.as_default(): global_vars = tf.global_variables() is_not_initialized = self.session.run( [tf.is_variable_initialized(var) for var in global_vars]) not_initialized_vars = [ v for ( v, f) in zip( global_vars, is_not_initialized) if not f] if len(not_initialized_vars): self.session.run( tf.variables_initializer(not_initialized_vars)) def _initialize_placeholders(self): with self.graph.as_default(): self._x = None # setup After building stem network self._is_train = tf.placeholder_with_default(False, (), name='is_train') self._y_true_cls = tf.placeholder(tf.float32, shape=(None, None, None, 1), name='y_true_cls') self._y_true_geo = tf.placeholder(tf.float32, shape=(None, None, None, 5), name='y_true_geo') self._lr = tf.placeholder_with_default(0.001, (), name='learning_rate') tf.add_to_collection('inputs', self._y_true_cls) tf.add_to_collection('inputs', self._y_true_geo) tf.add_to_collection('inputs', self._lr) def _attach_stem_network(self, base_model='vgg'): if 'stem' in self._built: print("stem network is already built") return self with tf.variable_scope('stem'): if base_model == "vgg": vgg16 = VGG16(include_top=False) with self.graph.as_default(): self._x = vgg16.input self.feature_maps = [] for i in range(5, 1, -1): feature_map = vgg16.get_layer('block{}_pool'.format(i)) feature_tensor = tf.identity(feature_map.output, "f{}".format(6 - i)) self.feature_maps.append(feature_tensor) elif base_model == "resnet": resnet = ResNet50(include_top=False) """ RESNET에 있는 Batch Normalization의 Mean & Average은 ImageNet의 데이터셋에 학습된 Mean & Average. 이를 Training 단계와 Test 단계로 나누어서 학습하게 되면, 기존 데이터셋과 충돌나게 됨. 즉, 성능이 굉장히 드랍되는 효과가 발생함. reference : https://github.com/keras-team/keras/issues/7177 """ with self.graph.as_default(): self._x = resnet.input self.feature_maps = [] for i, layer_idx in zip(range(5, 1, -1), [49, 40, 22, 10]): feature_map = resnet.get_layer( 'activation_{}'.format(layer_idx)) feature_tensor = tf.identity(feature_map.output, "f{}".format(6 - i)) # Version에 따라서 # keras._version__ <= 2.2 인경우, # stem/f4:0에 # tf.keras.backend.spatial_2d_padding # 으로 padding을 붙여주어야 함 self.feature_maps.append(feature_tensor) else: raise ValueError("stem network should be one of them, 'vgg' or 'resnet'") self.graph.add_to_collection('inputs', self._x) self.graph.add_to_collection('inputs', self._is_train) self._built.append(self._to_build.pop(0)) return self def _attach_branch_network(self, num_layers=(128, 64, 32, 32)): if 'branch' in self._built: print("branch network is already built") return self elif not 'branch' == self._to_build[0]: raise IndexError( "you should build {} network".format( self._to_build[0])) def unpool(tensor): with tf.variable_scope('unpool'): shape = tf.shape(tensor) return tf.image.resize_bilinear( tensor, size=[shape[1] * 2, shape[2] * 2]) with self.graph.as_default(): conv2d = tf.layers.Conv2D batch_norm = tf.layers.BatchNormalization with tf.variable_scope('branch'): for i, f in enumerate(self.feature_maps): num_layer = num_layers[i] with tf.variable_scope('block{}'.format(i + 1)): if i == 0: h = f else: concat = tf.concat([g, f], axis=-1) s = conv2d(num_layer, (1, 1), padding='same', activation=tf.nn.relu, name='conv_1x1')(concat) s = batch_norm()(s, training=self._is_train) h = conv2d(num_layer, (3, 3), padding='same', activation=tf.nn.relu, name='conv_3x3')(s) h = batch_norm()(h, training=self._is_train) if i <= 2: g = unpool(h) else: g = conv2d(num_layer, (3, 3), padding='same', activation=tf.nn.relu)(h) g = batch_norm()(g, training=self._is_train) self._branch_map = tf.identity(g, name='branch_map') self._built.append(self._to_build.pop(0)) return self def _attach_output_network(self, text_scale=512): if 'output' in self._built: print("output network is already built") return self elif not 'output' == self._to_build[0]: raise IndexError( "you should build {} network".format( self._to_build[0])) with self.graph.as_default(): conv2d = tf.layers.Conv2D with tf.variable_scope('output'): score_map = conv2d(1, (1, 1), activation=tf.nn.sigmoid, name='score')(self._branch_map) loc_map = conv2d(4, (1, 1), activation=tf.nn.sigmoid)(self._branch_map) loc_map = tf.identity(text_scale * loc_map, name='location') with tf.variable_scope('angle'): # angle should be in [-45, 45] angle_map = conv2d(1, (1, 1), activation=tf.nn.sigmoid)(self._branch_map) angle_map = (angle_map - 0.5) * np.pi / 2 self._y_pred_cls = tf.identity(score_map, name='score') self._y_pred_geo = tf.concat([loc_map, angle_map], axis=-1, name='geometry') self.graph.add_to_collection('outputs', self._y_pred_cls) self.graph.add_to_collection('outputs', self._y_pred_geo) self._built.append(self._to_build.pop(0)) return self def _attach_decode_network(self, fm_scale=4): if 'decode' in self._built: print("decode network is already built") return self elif not 'decode' == self._to_build[0]: raise IndexError( "you should build {} network".format( self._to_build[0])) with self.graph.as_default(): threshold = tf.placeholder_with_default(0.5, (), name='threshold') def decode_result(result_map): score_map, geo_map = tf.split(result_map, [1, 5], axis=2) score_map = score_map[:, :, 0] with tf.variable_scope('decoder'): h, w, _ = tf.split(tf.shape(geo_map), 3) h = tf.squeeze(h) w = tf.squeeze(w) xs, ys = tf.meshgrid(tf.range(0, w * fm_scale, fm_scale), tf.range(0, h * fm_scale, fm_scale), ) coords = tf.stack([ys, xs], axis=-1) coords = tf.cast(coords, tf.float32) indices = tf.where(score_map >= threshold) exist_score_map = tf.gather_nd(score_map, indices) exist_coords = tf.gather_nd(coords, indices) exist_geo_map = tf.gather_nd(geo_map, indices) p_y, p_x = tf.split(exist_coords, 2, axis=1) top, right, bottom, left, theta = tf.split(exist_geo_map, 5, axis=1) top_y = p_y - top bot_y = p_y + bottom left_x = p_x - left right_x = p_x + right tl = tf.concat([left_x, top_y], axis=1) tr = tf.concat([right_x, top_y], axis=1) br = tf.concat([right_x, bot_y], axis=1) bl = tf.concat([left_x, bot_y], axis=1) center_x = tf.reduce_mean([left_x, right_x], axis=0) center_y = tf.reduce_mean([top_y, bot_y], axis=0) center = tf.concat([center_x, center_y], axis=1) shift_tl = tl - center shift_tr = tr - center shift_bl = bl - center shift_br = br - center theta = theta[:, 0] x_rot_matrix = tf.stack([tf.cos(theta), -tf.sin(theta)], axis=1) y_rot_matrix = tf.stack([tf.sin(theta), tf.cos(theta)], axis=1) rotated_tl_x = (tf.reduce_sum(x_rot_matrix * shift_tl, axis=1) + center[:, 0]) rotated_tl_y = (tf.reduce_sum(y_rot_matrix * shift_tl, axis=1) + center[:, 1]) rotated_tr_x = (tf.reduce_sum(x_rot_matrix * shift_tr, axis=1) + center[:, 0]) rotated_tr_y = (tf.reduce_sum(y_rot_matrix * shift_tr, axis=1) + center[:, 1]) rotated_br_x = (tf.reduce_sum(x_rot_matrix * shift_br, axis=1) + center[:, 0]) rotated_br_y = (tf.reduce_sum(y_rot_matrix * shift_br, axis=1) + center[:, 1]) rotated_bl_x = (tf.reduce_sum(x_rot_matrix * shift_bl, axis=1) + center[:, 0]) rotated_bl_y = (tf.reduce_sum(y_rot_matrix * shift_bl, axis=1) + center[:, 1]) rotated_tl = tf.stack([rotated_tl_x, rotated_tl_y], axis=-1) rotated_tr = tf.stack([rotated_tr_x, rotated_tr_y], axis=-1) rotated_bl = tf.stack([rotated_bl_x, rotated_bl_y], axis=-1) rotated_br = tf.stack([rotated_br_x, rotated_br_y], axis=-1) rotated_polys = tf.stack([rotated_tl, rotated_tr, rotated_br, rotated_bl], axis=1) rotated_polys = tf.identity(rotated_polys, name="selected_polys") exist_score_map = tf.identity(exist_score_map, name='selected_scores') rotated_polys = tf.reshape(rotated_polys, (-1, 8)) exist_score_map = tf.expand_dims(exist_score_map, axis=1) result_map = tf.concat([rotated_polys, exist_score_map], axis=-1) return result_map results = tf.concat([self._y_pred_cls, self._y_pred_geo], axis=-1) decode = tf.map_fn(decode_result, results, name='decode') self.graph.add_to_collection('decode', decode) self._built.append(self._to_build.pop(0)) return self def _attach_loss_network(self, loss_type='bcse', iou_smooth=1e-5, alpha_theta=10, alpha_geo=1): if 'loss' in self._built: print("loss network is already built") return self elif not 'loss' == self._to_build[0]: raise IndexError( "you should build {} network".format( self._to_build[0])) epsilon = 1e-7 with self.graph.as_default(): with tf.variable_scope("losses"): with tf.variable_scope('score'): if loss_type == "bcse": with tf.variable_scope('balance_factor'): num_pos = tf.count_nonzero(self._y_true_cls, axis=[1, 2, 3], dtype=tf.float32) num_tot = tf.reduce_prod( tf.shape(self._y_true_cls)[1:]) beta = 1 - num_pos / tf.cast(num_tot, tf.float32) beta = tf.reshape(beta, shape=(-1, 1, 1, 1)) with tf.variable_scope('balanced_cross_entropy'): bcse = -(beta * self._y_true_cls * tf.log(epsilon + self._y_pred_cls) + (1. - beta) * (1. - self._y_true_cls) * tf.log(epsilon + 1. - self._y_pred_cls)) bcse = tf.reduce_sum(bcse, axis=[1, 2, 3]) score_loss = tf.reduce_mean(bcse, name='score_loss') elif loss_type == "dice": with tf.variable_scope('dice_coefficient'): intersection = tf.reduce_sum( self._y_true_cls * self._y_pred_cls) union = tf.reduce_sum( self._y_true_cls) + tf.reduce_sum(self._y_pred_cls) + epsilon dice = 1 - 2 * intersection / union score_loss = tf.identity(dice, name='score_loss') else: raise ValueError( "loss_type should be one, 'dice', 'bcse'") with tf.variable_scope('geometry'): geo_mask = tf.identity(self._y_true_cls, name='geo_mask') with tf.variable_scope('split_tensor'): top_true, right_true, bottom_true, left_true, theta_true = tf.split( self._y_true_geo, 5, axis=3) top_pred, right_pred, bottom_pred, left_pred, theta_pred = tf.split( self._y_pred_geo, 5, axis=3) with tf.variable_scope('aabb'): with tf.variable_scope("area"): area_true = (top_true + bottom_true) * \ (right_true + left_true) area_pred = (top_pred + bottom_pred) * \ (right_pred + left_pred) w_intersect = (tf.minimum(right_true, right_pred) + tf.minimum(left_true, left_pred)) h_intersect = (tf.minimum(top_true, top_pred) + tf.minimum(bottom_true, bottom_pred)) area_intersect = w_intersect * h_intersect area_union = area_true + area_pred - area_intersect with tf.variable_scope('iou_loss'): area_loss = -tf.log((area_intersect + iou_smooth) / (area_union + iou_smooth)) # geo_mask에서 1인 부분들만 학습에 들어감 area_loss = tf.reduce_sum( area_loss * geo_mask, axis=[1, 2, 3]) area_loss = tf.reduce_mean(area_loss, name='area_loss') with tf.variable_scope('theta'): angle_loss = (1 - tf.cos(theta_pred - theta_true)) # geo_mask에서 1인 부분들만 학습에 들어감 angle_loss = tf.reduce_sum( angle_loss * geo_mask, axis=[1, 2, 3]) angle_loss = tf.reduce_mean(angle_loss, name='angle_loss') with tf.variable_scope('aabb_theta'): geo_loss = area_loss + alpha_theta * angle_loss geo_loss = tf.identity(geo_loss, name='geo_loss') with tf.variable_scope('total_loss'): loss = score_loss + alpha_geo * geo_loss self._loss = tf.identity(loss, name='loss') tf.add_to_collection(tf.GraphKeys.LOSSES, self._loss) tf.add_to_collection(tf.GraphKeys.LOSSES, score_loss) tf.add_to_collection(tf.GraphKeys.LOSSES, geo_loss) tf.add_to_collection(tf.GraphKeys.LOSSES, area_loss) tf.add_to_collection(tf.GraphKeys.LOSSES, angle_loss) tf.summary.scalar('loss', self._loss) tf.summary.scalar('area_loss', area_loss) tf.summary.scalar('angle_loss', angle_loss) tf.summary.scalar('geo_loss', geo_loss) tf.summary.scalar('score_loss', score_loss) self._built.append(self._to_build.pop(0)) return self def _attach_optimizer(self, weight_decay=1e-5): if 'optimizer' in self._built: print("optimizer network is already built") return self elif not 'optimizer' == self._to_build[0]: raise IndexError( "you should build {} network".format( self._to_build[0])) with self.graph.as_default(): with tf.variable_scope("optimizer"): update_ops = tf.get_collection(tf.GraphKeys.UPDATE_OPS) without_stem_variables = tf.get_collection( tf.GraphKeys.TRAINABLE_VARIABLES, scope='^((?!stem).)*$') with tf.variable_scope("l2_loss"): weights = [var for var in tf.trainable_variables() if not "bias" in var.name] l2_losses = tf.add_n([tf.nn.l2_loss(var) for var in weights], name='l2_losses') with tf.control_dependencies(update_ops): loss = self._loss + weight_decay * l2_losses self._headtune_op = (tf.train .AdamOptimizer(self._lr) .minimize(loss, var_list=without_stem_variables, name='headtune_op')) self._finetune_op = (tf.train .AdamOptimizer(self._lr) .minimize(loss, name='finetune_op')) self._built.append(self._to_build.pop(0)) return self
Java
UTF-8
1,368
2.890625
3
[]
no_license
package command.impl.client; import command.impl.Command; import service.ClientService; import service.exception.ServiceException; import service.impl.ServiceFactory; import javax.servlet.http.HttpServletRequest; import java.util.InputMismatchException; import java.util.Scanner; public class AddProductToBasketCommand implements Command { @Override public String execute(HttpServletRequest req) { Scanner scanner = new Scanner(System.in); try { ServiceFactory serviceFactory = ServiceFactory.getInstance(); ClientService clientService = serviceFactory.getClientService(); System.out.println("введите id заказа"); Integer idOrder = scanner.nextInt(); System.out.println("введите id продукта"); Integer idProduct = scanner.nextInt(); boolean answer = clientService.addProductToBasket(idOrder, idProduct); if (answer) System.out.println("product successfully added to basket"); else System.out.println("product can't added to basket"); } catch (ServiceException e) { System.out.println(e.getMessage()); } catch (InputMismatchException e) { System.out.println("incorect type input"); } return null; } }
C
UTF-8
254
3.265625
3
[]
no_license
#include <stdio.h> #include <stdlib.h> int mySum(int, int); int main() { int i = mySum(1, 2); char *myName = (char *)malloc(10 * sizeof(char)); myName = "Hello"; printf("%s, %d\n", myName, mySum(1, 2)); } int mySum(int a, int b) { return a + b; }
JavaScript
UTF-8
10,605
3.046875
3
[ "MIT" ]
permissive
import { fen2array, array2fen } from './fen' import * as helpers from './helpers' const whitePieces = ["K", "Q", "R", "B", "N", "P"]; const blackPieces = ["k", "q", "r", "b", "n", "p"]; /* do not check for check when checking for check, lest check for check ad infinitum */ function validLocations(fen, start, checkForCheck) { const fenParts = fen.split(" "); const state = fen2array(fen); const turn = fenParts[1]; const castle = fenParts[2]; const enPassant = (!fenParts[3] || fenParts[3] === "-") ? null : helpers.square2position(fenParts[3]); const piece = state[start]; if (piece === "" || (turn === "w" && !whitePieces.includes(piece)) || turn === "b" && !blackPieces.includes(piece)) return []; if (["P", "p"].includes(piece)) { return pawnCheck(state, turn, start, enPassant, checkForCheck); } else if (["N", "n"].includes(piece)) { if (checkForCheck) { const testState = state.slice(); testState[start] = ""; // knight move opens all lines through a point if (isCheck(testState, turn)) { return []; } else { return multiplicativeCheck(state, turn, start, [6, 10], 1, 1).concat(multiplicativeCheck(state, turn, start, [15, 17], 2, 1)); } } else return multiplicativeCheck(state, turn, start, [6, 10], 1, 1).concat(multiplicativeCheck(state, turn, start, [15, 17], 2, 1)); } else if (["B", "b"].includes(piece)) { if (checkForCheck) return excludeBlockingCheck(state, turn, start, [7, 9]); else return multiplicativeCheck(state, turn, start, [7, 9], 1); } else if (["R", "r"].includes(piece)) { if (checkForCheck) return excludeBlockingCheck(state, turn, start, [1, 8]); else return multiplicativeCheck(state, turn, start, [1], 0).concat(multiplicativeCheck(state, turn, start, [8], 1)); } else if (["Q", "q"].includes(piece)) { if (checkForCheck) return excludeBlockingCheck(state, turn, start, [1, 7, 8, 9]); else return multiplicativeCheck(state, turn, start, [1], 0).concat(multiplicativeCheck(state, turn, start, [7, 8, 9], 1)); } else if (["K", "k"].includes(piece)) { const grossValid = multiplicativeCheck(state, turn, start, [1], 0, 1).concat(multiplicativeCheck(state, turn, start, [7, 8, 9], 1, 1)); let testStateA; let testStateB; const valid = []; // castling if (castle) { if (piece === "k" && start === 4) { if (castle.includes("k")) { if (state[5] === "" && state[6] === "") { testStateA = state.slice(); testStateA[4] = ""; testStateA[5] = "k"; testStateB = state.slice(); testStateB[4] = ""; testStateB[6] = "k"; if (!isCheck(testStateA, turn) && !isCheck(testStateB, turn)) valid.push(6); } } if (castle.includes("q")) { if (state[3] === "" && state[2] === "" && state[1] === "") { testStateA = state.slice(); testStateA[4] = ""; testStateA[3] = "k"; testStateB = state.slice(); testStateB[4] = ""; testStateB[2] = "k"; if (!isCheck(testStateA, turn) && !isCheck(testStateB, turn)) valid.push(2); } } } else if (piece === "K" && start === 60) { if (castle.includes("K")) { if (state[61] === "" && state[62] === "") { testStateA = state.slice(); testStateA[60] = ""; testStateA[61] = "K"; testStateB = state.slice(); testStateB[60] = ""; testStateB[62] = "K"; if (!isCheck(testStateA, turn) && !isCheck(testStateB, turn)) valid.push(62); } } if (castle.includes("Q")) { if (state[59] === "" && state[58] === "" && state[57] === "") { testStateA = state.slice(); testStateA[60] = ""; testStateA[59] = "K"; testStateB = state.slice(); testStateB[60] = ""; testStateB[58] = "K"; if (!isCheck(testStateA, turn) && !isCheck(testStateB, turn)) valid.push(58); } } } } // filter out checks if (checkForCheck) { for (let i = 0, l = grossValid.length; i < l; i++) { testStateA = state.slice(); testStateA[start] = ""; testStateA[grossValid[i]] = piece; if (!isCheck(testStateA, turn)) valid.push(grossValid[i]) } return valid; } else return grossValid; } } /** * @private * * check if moving a piece along a path results in check * unlike multiplicativeCheck, encapsulates its own wrap conditions */ function excludeBlockingCheck(state, turn, start, paths) { const piece = state[start]; let valid = []; for (const p in paths) { const destinations = multiplicativeCheck(state, turn, start, [paths[p]], (paths[p] === 1 ? 0 : 1)); if (destinations.length > 0) { const testState = state.slice(); // assign by value testState[destinations[0]] = piece; testState[start] = ""; if (!isCheck(testState, turn)) { valid = valid.concat(destinations); } } } return valid; } // handles edge cases for pawn movement function pawnCheck(state, turn, start, ep, checkForCheck) { const grossValid = []; if (turn === "b") { var comp = (a, b) => parseInt(a) + parseInt(b); var pieces = blackPieces; var startRank = [7, 16]; } else if (turn === "w") { var comp = (a, b) => a - b; var pieces = whitePieces; var startRank = [47, 56]; } // forward movement if (!state[comp(start, 8)]) grossValid.push(comp(start, 8)); if (start > startRank[0] && start < startRank[1] && !state[comp(start, 8)] && !state[comp(start, 16)]) grossValid.push(comp(start, 16)); // capture if (state[comp(start, 7)] && !pieces.includes(state[comp(start, 7)]) && Math.abs(helpers.position2row(start) - helpers.position2row(comp(start, 7))) === 1) grossValid.push(comp(start, 7)); if (state[comp(start, 9)] && !pieces.includes(state[comp(start, 9)]) && Math.abs(helpers.position2row(start) - helpers.position2row(comp(start, 9))) === 1) grossValid.push(comp(start, 9)); // en passant if (ep && (comp(start, 7) === ep || comp(start, 9) === ep)) grossValid.push(ep); // filter out checks if (checkForCheck) { const valid = []; for (let i = 0, l = grossValid.length; i < l; i++) { const testState = state.slice(); testState[grossValid[i]] = testState[start]; testState[start] = ""; if (!isCheck(testState, turn)) valid.push(grossValid[i]) } return valid; } else return grossValid; } /** * @private * @function multiplicativeCheck * * returns valid indices from the board array to which a piece can move * * takes into account the need for a knight to travel multiple ranks in a given move, * blocking by other pieces, en prise for any move with a regular pattern * * mult here stands for multiplicative, since, by default, the search will search at all multiples of a distance within array bounds * * the main idea here is: when numbering the pieces of a chess board from 0 to 63, all pieces move multiples of certain integers from their starting position, * and cannot wrap around the board, except in the case of the knight which *must* appear to wrap into the next rank or the one after */ function multiplicativeCheck(state, turn, start, distances, wrap, depth) { const valid = []; const iter = (start < 32) ? (cur, dist) => start + (dist * cur) < 64 : (cur, dist) => start - (dist * cur) >= 0; for (const d in distances) { const distance = distances[d]; const blocked = [false, false]; let current = 1; do { // traversing an array; indices is literal; equidistant from start position; target locations const indices = [start + (distance * current), start - (distance * current)]; // do: [start, start] const prevIndices = [start + (distance * (current - 1)), start - (distance * (current - 1))]; for (const i in indices) { const index = indices[i]; const prevIndex = prevIndices[i]; const rowDiff = Math.abs(helpers.position2row(prevIndex) - helpers.position2row(index)); if (index < 64 && index >= 0 && !blocked[i]) { // if exact number of wraps is not met, ignore location (accounts for edge wrapping and knight minimums) if (rowDiff !== wrap) blocked[i] = true; if (!blocked[i]) { const targetPiece = state[index]; if (!targetPiece) valid.push(index); else { // allow capture on first block if opposing piece in way if (turn === "w" && blackPieces.includes(targetPiece) || turn === "b" && whitePieces.includes(targetPiece)) valid.push(index); blocked[i] = true; } } } } current++; } while(iter(current, distance) && (!depth || current <= depth) && !(blocked[0] && blocked[1])) } return valid; } /** * @private * @method findPieces * * finds all the pieces for a givne player, and passes the piece ascii value * and position to a callback. * * - state Array state array * - player String "w" or "b" * - callback Function * - piece String ascii representation of the piece * - position Number the position of the piece in the state array */ function findPieces(state, player, callback) { const pieceChecker = piece => { const ascii = piece.charCodeAt(0); return (player === "w" && ascii > 64 && ascii < 91) || (player === "b" && ascii > 96 && ascii < 123); }; for (let i = 0; i < 64; i++) { const piece = state[i]; if (piece !== "" && pieceChecker(piece)) { callback(piece, i); } } } /** * @private * @method isCheck * * determine whether the given state is check for the player * * - state Array state array * - whom String "w" or "b" - player whose possibility of check is in question * * returns Boolean */ function isCheck(state, whom) { const turn = (whom === "w") ? "b" : "w"; let kingPosition = null; for (let i = 0; i < 64 && !kingPosition; i++) { if ((whom === "b" && state[i] === "k") || (whom === "w" && state[i] === "K")) { kingPosition = i; } } let isCheck = false; findPieces(state, turn, (piece, position) => { const valid = validLocations(`${array2fen(state)} ${turn}`, position, false); if (valid.includes(kingPosition)) { isCheck = true; } }); return isCheck; } export { validLocations, findPieces, isCheck }
C#
UTF-8
1,829
2.671875
3
[]
no_license
using SampleMapper; using SampleWebApi.Models.CountryModel; using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; namespace SampleWebApi.Controllers.CountryCnrl { [RoutePrefix("api/CountryApi")] public class CountryApiController : ApiController { static readonly ICountry Counobj = new Country(); [Route("SaveCountry")] [HttpPost] public HttpResponseMessage SaveCountry(CountryDTO obj) { obj = Counobj.SaveCountry(obj); var Responce = Request.CreateResponse<CountryDTO>(HttpStatusCode.Created, obj); return Responce; } [Route("UpdateCountry")] [HttpPut] public HttpResponseMessage UpdateCountry(CountryDTO obj) { if (!Counobj.UpdateCountry(obj)) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Sorry"); } else { var response = Request.CreateResponse(HttpStatusCode.OK); response.ReasonPhrase = Convert.ToString(obj.CID); // Return the output Id of the procedure in response. return response; } } [Route("GetCountry")] public IEnumerable<CountryDTO> GetCountry() { return Counobj.GetAll(); } [Route("GetCountry/{id}")] public HttpResponseMessage GetCountry(int id) { CountryDTO ObjCon = Counobj.Get(id); if (ObjCon == null) { return Request.CreateErrorResponse(HttpStatusCode.NotFound, "Sorry"); } else { return Request.CreateResponse<CountryDTO>(ObjCon); } } } }
C#
UTF-8
2,112
3.203125
3
[]
no_license
namespace ValidateUrl { using System; using System.Net; using System.Text.RegularExpressions; public class Program { static void Main(string[] args) { string inputUrl = Console.ReadLine(); string decodedUrl = WebUtility.UrlDecode(inputUrl); Regex protocolRegex = new Regex(@"\b(http)\b|\b(https)\b|\b(ftp)\b"); Regex hostRegex = new Regex(@"(?<=\/\/)([a-zA-Z.]+)"); Regex portRegex = new Regex(@"(?<=:)(\d+)"); Regex pathRegex = new Regex(@"(\/\w+)(?=\?)|\/$|(\/\w+)$"); Regex queryStringRegex = new Regex(@"(?<=\?)(.+)(?=#)|(?<=\?)([a-zA-Z=&]+)$"); Regex fragmentRegex = new Regex(@"(?<=#)\w+$"); string protocol = protocolRegex.Match(decodedUrl).ToString(); string host = hostRegex.Match(decodedUrl).ToString(); string port = portRegex.Match(decodedUrl).ToString(); string path = pathRegex.Match(decodedUrl).ToString(); string queryString = queryStringRegex.Match(decodedUrl).ToString(); string fragment = fragmentRegex.Match(decodedUrl).ToString(); if (port == "" && protocol == "http") port = "80"; else if(port == "" && protocol == "https") port = "433"; if (protocol == "http" && port != "80"){ Console.WriteLine("Invalid URL"); return; } else if (protocol == "https" && port != "443"){ Console.WriteLine("Invalid URL"); return; } Console.WriteLine(decodedUrl); Console.WriteLine("Protocol: " + protocol); Console.WriteLine("Host: " + host); Console.WriteLine("Port: " + port); Console.WriteLine("Path: " + path); if(queryString != "") Console.WriteLine("Query: " + queryString); if (fragment != "") Console.WriteLine("Fragment: " + fragment); } } }
Java
UTF-8
1,600
2.484375
2
[]
no_license
package com.hfad.astreoidsgl.input; import android.annotation.SuppressLint; import android.util.Log; import android.view.MotionEvent; import android.view.View; import com.hfad.astreoidsgl.R; import com.hfad.astreoidsgl.Utils; public class VirtualJoystick extends InputManager { final String TAG = ""; public VirtualJoystick(View view) { view.findViewById(R.id.joystick_region) .setOnTouchListener(new JoystickTouchListener()); Log.d(TAG, "MaxDistance (pixels): " + _maxDistance); } private class JoystickTouchListener implements View.OnTouchListener { @SuppressLint("ClickableViewAccessibility") @Override public boolean onTouch(View v, MotionEvent event) { int action = event.getActionMasked(); if (action == MotionEvent.ACTION_DOWN) { _startingPositionX = event.getX(0); _startingPositionY = event.getY(0); } else if (action == MotionEvent.ACTION_UP) { _horizontalFactor = 0.0f; _verticalFactor = 0.0f; } else if (action == MotionEvent.ACTION_MOVE) { //get the proportion to the maxDistance _horizontalFactor = (event.getX(0) - _startingPositionX) / _maxDistance; _horizontalFactor = Utils.clamp(_horizontalFactor, -1.0f, 1.0f); _verticalFactor = (event.getY(0) - _startingPositionY) / _maxDistance; _verticalFactor = Utils.clamp(_verticalFactor, -1.0f, 1.0f); } return true; } } }
PHP
UTF-8
423
2.53125
3
[ "MIT" ]
permissive
<?php namespace KushyApi\Services; use KushyApi\UserActivity; class AddUserActivity { /** * Execute the job. * * @return void */ public function create($user_id, $section, $item_id) { $newActivity = UserActivity::create([ 'user_id' => $user_id, 'section' => $section, 'item_id' => $item_id, ]); return $newActivity; } }
TypeScript
UTF-8
666
2.625
3
[]
no_license
import { PackageJson } from "../src/models/PackageJson"; describe("When adding a package", () => { it("Should add package when not existing", () => { const packageJson = new PackageJson({ dependencies: {}, devDependencies: {} }); packageJson.InstallDevDependency("typescript", "3.6.4"); expect(packageJson.devDependencies["typescript"]) .toBe("3.6.4"); }); it("should not add package when existing", () => { const packageJson = new PackageJson({ dependencies: {}, devDependencies: { typescript: "3.4.3"} }); packageJson.InstallDevDependency("typescript", "3.6.4"); expect(packageJson.devDependencies["typescript"]) .toBe("3.4.3"); }); });
Python
UTF-8
364
3.484375
3
[]
no_license
# class Solution: # def search(self, nums: List[int], target: int) -> int: # if target in nums: # return (nums.index(target)); # else: # return (-1); nums=[4,5,6,7,0,1,2] target=-1; arr=set(nums); print(arr) if target in arr: print(nums.index(target)); else: print(-1);
PHP
UTF-8
5,787
3.140625
3
[]
no_license
<?php /** * Created by PhpStorm. * User: frank * Date: 09.01.19 * Time: 19:54 */ namespace Frank2022\CartesianSpace; use Frank2022\CartesianSpace\interfaces\CoordinateInterface; use Frank2022\CartesianSpace\exceptions\DimensionException; use Frank2022\CartesianSpace\exceptions\SpaceException; /** * Class Space * Represents multidimentional cartesian space * @package Frank2022\CartesianSpace */ class Space { const VECTOR_ADDITION = 'vector-addition'; const VECTOR_DIFFERENCE = 'vector-difference'; const VECTOR_PRODUCT = 'vector-product'; protected $dimensionNumber; /** * Space constructor. * @param int $dimensionNumber * @throws DimensionException */ public function __construct(int $dimensionNumber = 2) { if ($dimensionNumber < 1) { throw new DimensionException('Space should have at least one dimension'); } $this->dimensionNumber = $dimensionNumber; } /** * @return int */ public function getDimension(): int { return $this->dimensionNumber; } /** * @param Point $pointOne * @param Point $pointTwo * @return float * @throws DimensionException * @throws SpaceException */ public function getDistance(Point $pointOne, Point $pointTwo): float { $vectorCoordinates = $this->calculateVectorOperation($pointOne, $pointTwo, self::VECTOR_DIFFERENCE); return sqrt(array_reduce($vectorCoordinates, function(float $carry, float $item) { $carry += $item**2; return $carry; }, 0)); } /** * @param Point $pointOne * @param Point $pointTwo * @return Vector * @throws DimensionException * @throws SpaceException */ public function getVector(Point $pointOne, Point $pointTwo): Vector { $vectorCoordinates = $this->calculateVectorOperation($pointTwo, $pointOne, self::VECTOR_DIFFERENCE); return new Vector(...$vectorCoordinates); } /** * @param Vector $vectorOne * @param Vector $vectorTwo * @return Vector * @throws DimensionException * @throws SpaceException */ public function getVectorAddition(Vector $vectorOne, Vector $vectorTwo): Vector { $vectorCoordinates = $this->calculateVectorOperation($vectorOne, $vectorTwo, self::VECTOR_ADDITION); return new Vector(...$vectorCoordinates); } /** * @param Vector $vectorOne * @param Vector $vectorTwo * @return Vector * @throws DimensionException * @throws SpaceException */ public function getVectorDifference(Vector $vectorOne, Vector $vectorTwo): Vector { $vectorCoordinates = $this->calculateVectorOperation($vectorOne, $vectorTwo, self::VECTOR_DIFFERENCE); return new Vector(...$vectorCoordinates); } /** * @param Vector $vectorOne * @param Vector $vectorTwo * @return float * @throws DimensionException * @throws SpaceException */ public function getVectorProduct(Vector $vectorOne, Vector $vectorTwo): float { $vectorCoordinates = $this->calculateVectorOperation($vectorOne, $vectorTwo, self::VECTOR_PRODUCT); return array_sum($vectorCoordinates); } /** * @param Vector $vectorOne * @param Vector $vectorTwo * @return float * @throws DimensionException * @throws SpaceException */ public function getVectorAngle(Vector $vectorOne, Vector $vectorTwo): float { $numerator = $this->getVectorProduct($vectorOne, $vectorTwo); $denominator = $vectorOne->getLength() * $vectorTwo->getLength(); return acos($numerator / $denominator); } /** * @param CoordinateInterface $coordinateObjectOne * @param CoordinateInterface $coordinateObjectTwo * @throws DimensionException */ private function checkDimension(CoordinateInterface $coordinateObjectOne, CoordinateInterface $coordinateObjectTwo) { if ($coordinateObjectOne->getDimension() != $this->getDimension()) { throw new DimensionException('coordinateObjectOne has wrong dimension for this space'); } if ($coordinateObjectTwo->getDimension() != $this->getDimension()) { throw new DimensionException('coordinateObjectTwo has wrong dimension for this space'); } } /** * @param CoordinateInterface $coordinateObjectOne * @param CoordinateInterface $coordinateObjectTwo * @param string $operation * @return array * @throws DimensionException * @throws SpaceException */ private function calculateVectorOperation(CoordinateInterface $coordinateObjectOne, CoordinateInterface $coordinateObjectTwo, string $operation): array { $this->checkDimension($coordinateObjectOne, $coordinateObjectTwo); $vectorCoordinates = []; for ($n = 0; $n < $this->getDimension(); $n++) { $coordinateOne = $coordinateObjectOne->getCoordinate($n); $coordinateTwo = $coordinateObjectTwo->getCoordinate($n); switch ($operation) { case self::VECTOR_ADDITION: $vectorCoordinates[$n] = $coordinateOne + $coordinateTwo; break; case self::VECTOR_DIFFERENCE: $vectorCoordinates[$n] = $coordinateOne - $coordinateTwo; break; case self::VECTOR_PRODUCT: $vectorCoordinates[$n] = $coordinateOne * $coordinateTwo; break; default: throw new SpaceException('Wrong vector operation'); break; } } return $vectorCoordinates; } }
PHP
UTF-8
2,398
2.71875
3
[]
no_license
<?php declare(strict_types=1); namespace Product\Tests\Repository; use Money\Money; use PHPUnit\Framework\Assert; use PHPUnit\Framework\TestCase; use Product\Model\Product; use Product\Repository\FileSystem; use Product\Repository\ProductRepository; class ProductRepositoryTest extends TestCase { /** * @test */ public function find_product_by_id() { $filesystem = $this->prophesize(FileSystem::class); $filesystem->getFileContent('filename.json') ->willReturn( ' { "items": [ { "id": 1, "name": "Product 1", "price": 1000 }, { "id": 2, "name": "Product 2", "price": 9.90 } ] } ' ); $productRepository = new ProductRepository('filename.json', $filesystem->reveal()); Assert::assertEquals( new Product('1', 'Product 1', Money::EUR(100000)), $productRepository->find('1') ); Assert::assertEquals( new Product('2', 'Product 2', Money::EUR('990')), $productRepository->find('2') ); } /** * @test */ public function find_all_products() { $filesystem = $this->prophesize(FileSystem::class); $filesystem->getFileContent('filename.json') ->willReturn( ' { "items": [ { "id": 1, "name": "Product 1", "price": 1000 }, { "id": 2, "name": "Product 2", "price": 9.90 } ] } ' ); $productRepository = new ProductRepository('filename.json', $filesystem->reveal()); Assert::assertEquals([ new Product('1', 'Product 1', Money::EUR(100000)), new Product('2', 'Product 2', Money::EUR('990')), ], $productRepository->findAll()); } }
C
WINDOWS-1252
12,982
2.875
3
[ "MIT" ]
permissive
#include <std.h> #include <pc.h> unsigned long *p239; unsigned long i239; unsigned long *p57; unsigned long i57; unsigned long *p18; unsigned long i18; unsigned long *temp; unsigned long *pihex; unsigned long indice = 1; signed char signe = 1; unsigned long nbdec; unsigned long t0, t1; int resume; main(int argc, char *argv[]) { register int i; printf("Calcul des dcimales de par la formule de Gauss\n" " = 48Arctan 1/18 + 32Arctan 1/57 - 20Arctan 1/239\n" "(c) Ren DEVICHI 1991-93 GCC\n\n"); nbdec = 0; if (argc > 1) { if (strcmp(argv[1], "continue")==0) resume=1; else resume=0; sscanf(argv[1], "%d", &nbdec); } if (nbdec < 5) nbdec = 100; if (resume) charge_etat(); else { printf("\nCalcul de hxadcimal avec %d tranches de 8 chiffres\n", nbdec); /* * allocation de la mmoire et initialisation des rels * (initialiastion normale) */ p239 = malloc(sizeof(unsigned long)*(nbdec+1)); for (i=1; i<=nbdec; p239[i++]=0L); *p239 = 20*239; i239=0; p57 = malloc(sizeof(unsigned long)*(nbdec+1)); for (i=1; i<=nbdec; p57[i++]=0L); *p57 = 32*57; i57=0; p18 = malloc(sizeof(unsigned long)*(nbdec+1)); for (i=1; i<=nbdec; p18[i++]=0L); *p18 = 48*18; i18=0; temp = malloc(sizeof(unsigned long)*(nbdec+1)); for (i=0; i<=nbdec; temp[i++]=0L); pihex = malloc(sizeof(unsigned long)*(nbdec+1)); for (i=0; i<=nbdec; pihex[i++]=0L); if (!p239 || !p57 || !p18 || !temp || !pihex) { printf("out of memory\n"); exit(3); } t0 = time(NULL); } /* * boucle principal du calcul de pi */ do { /* * teste si on a appuy sur une touche * ESC sauvegarde l'tat du calcul et arrte le programme */ if (kbhit()) { int c=getkey(); switch (c) { case 0x1b : sauve_etat(); exit(2); break; case 0x0d : putchar('\n'); break; case 0x09 : { int x, y; ScreenGetCursor(&y,&x); printf(" i18=%6d indice=%6d\n", i18, indice); ScreenSetCursor(y,0); break; } } } asm(" /* * test de l'utilit de chaque calcul de puissance * (rsultat dans bx) */ xorw %bx,%bx /* bx = 0 */ movl _nbdec,%eax cmpl _i57, %eax jb LR10 orw $1,%bx /* si i57<nbdec alors bx=.1 */ LR10: cmpl _i239,%eax jb LR11 orw $2,%bx /* si i239<nb4ec alors bx=1. */ LR11: cld /* stosl va incrmenter edi */ /* on teste s'il est ncessaire de calculer p239 */ cmpw $3,%bx /* si bx!=11b on ne calcule plus p239 */ jne LR2 /* * calcul de p239 */ movl $57121,%ebx /* diviseur */ movl _nbdec,%ecx subl _i239,%ecx incl %ecx /* ecx=(nbdec-i239+1) */ movl _p239,%edi movl _i239,%eax leal (%edi,%eax,4),%edi /* edi=p239+i239*4 */ xorl %edx,%edx /* premire retenue nulle */ /* nota: la retenue est sur 64 bits avec les */ /* 32 bits de poids faible nuls */ /* d'o l'astuce fantastique qui suit!!!!! */ LR1: movl (%edi),%eax /* %eax=p239[i] */ divl %ebx /* edx:eax/57151, reste dans edx, quotient dans eax */ /* le quotient on le stocke dans p239[i] */ /* le (reste << 32) est la retenue */ stosl loop LR1 movl _i239,%eax movl _p239,%edx cmpl $0,(%edx,%eax,4) jne LR2 incl _i239 LR2: /* * on teste si le calcul de p57 est ncessaire */ cmpw $0,%bx /* si bx=0 on ne calcule plus p57 */ je LR4 /* * calcul de p57 */ movl $3249,%ebx /* diviseur */ movl _nbdec,%ecx subl _i57,%ecx incl %ecx /* ecx=(nbdec-i57+1) */ movl _p57,%edi movl _i57,%eax leal (%edi,%eax,4),%edi /* edi=p57+i57*4 */ xorl %edx,%edx /* retenue nulle */ LR3: movl (%edi),%eax /* %eax=p57[i] */ divl %ebx /* edx:eax/3249 */ stosl loop LR3 movl _i57,%eax movl _p57,%edx cmpl $0,(%edx,%eax,4) jne LR4 incl _i57 LR4: /* * calcul de p18 */ movl $324,%ebx /* diviseur */ movl _nbdec,%ecx subl _i18,%ecx incl %ecx /* ecx=(nbdec-i18+1) */ movl _p18,%edi movl _i18,%eax shll $2,%eax addl %eax,%edi /* edi=p18+i18*4 */ xorl %edx,%edx /* retenue nulle */ LR5: movl (%edi),%eax /* %eax=p18[i] */ divl %ebx /* edx:eax/324 */ stosl loop LR5 /* * somme p18+p57-p239 c'est le plus embtant !! * *********************************************************** */ movl _nbdec,%ecx /* ecx:compteur */ subl _i18,%ecx incl %ecx /* ecx=(nbdec-i18+1) */ mov _nbdec,%ebx /* ebx:variable d'index */ mov _temp,%edi xorb %dl,%dl /* pas de retenue au dpart */ LR7: movb %dl,%dh /* dh=retenue prcdente */ movl _p18,%esi movl (%esi,%ebx,4),%eax movl _p57,%esi addl (%esi,%ebx,4),%eax /* eax=p18[i]+pp57[i] */ setb %dl /* dl=retenue(CF) */ movl _p239,%esi subl (%esi,%ebx,4),%eax sbbb $0,%dl /* dl=dl-retenue(CF) */ andb %dh,%dh /* si la retenue prcdente est 0 */ jz LR9 /* on n'a pas de problme ! */ jns LR8 /* si elle est 1, on va LR8 */ /* si SF=0 alors dpl */ subl $1,%eax /* elle vaut -1 */ sbbb $0,%dl /* on a trait la retenue */ jmp LR9 LR8: addl $1,%eax /* retenue=1 */ adcb $0,%dl LR9: movl %eax,(%edi,%ebx,4) decl %ebx loop LR7 /* * calcul de temp/indice */ movl _indice,%ebx /* diviseur */ movl _nbdec,%ecx subl _i18,%ecx incl %ecx /* ecx=(nbdec-i18+1) */ movl _temp,%edi movl _i18,%eax leal (%edi,%eax,4),%edi /* edi=temp+i18*4 */ xorl %edx,%edx /* retenue nulle au dpart */ LR12: movl (%edi),%eax /* eax=temp[i] */ divl %ebx /* edx:eax/indice */ stosl loop LR12 /* * calcul de pihex += signe*temp */ movl _nbdec,%ecx /* ecx:compteur */ subl _i18,%ecx incl %ecx /* ecx=(nbdec-i18+1) */ movl _nbdec,%ebx /* indexe les rels */ movl _temp,%esi /* esi pointe sur temp (la source) */ movl _pihex,%edi /* edi pointe sur pihex (la destination) */ cmpb $1,_signe je LR13 /* signe moins: on soustrait */ xorb %dl,%dl /* retenue nulle au dpart */ LR15: movsbl %dl,%edx movl (%edi,%ebx,4),%eax subl %edx,%eax setb %dl subl (%esi,%ebx,4),%eax /* eax=pihex[i]-temp[i] */ movl %eax,(%edi,%ebx,4) /* pihex[4]=eax */ adcb $0,%dl decl %ebx loop LR15 movb $1,_signe /* on change le signe */ jmp LR14 LR13: /* signe plus: on additionne */ xorb %dl,%dl /* r=0 */ LR16: movsbl %dl,%eax /* eax=r */ addl (%edi,%ebx,4),%eax /* eax=r+pihex[i] */ setb %dl /* dl=nouvelle retenue */ addl (%esi,%ebx,4),%eax /* eax=r+pihex[i]+temp[i] */ adcb $0,%dl /* dl=nouvelle retenue */ /* toujours 0 ou 1 !!!!! */ /* cela signifie que si <setb %dl> a donn dl=1, alors <adcb $0,%dl> est inutile */ movl %eax,(%edi,%ebx,4) /* pihex[i]=r+pihex[i]+temp[i] */ decl %ebx loop LR16 movb $-1,_signe /* on change le signe */ LR14: /* * incrmente indice et ventuellement i18 */ addl $2,_indice movl _i18,%eax movl _p18,%edx cmpl $0,(%edx,%eax,4) jne LR6 incl _i18 LR6: "); } while (i18 <= nbdec); t1=time(NULL); printf("\r%lu secondes\n", t1-t0); /* * libration de la mmoire */ free(p239); free(p57); free(p18); free(temp); sauve(); /* sauve pi hex */ printf(" is done.\n"); } aff(n) unsigned long *n; { register int i; unsigned long *a; for (i=0; i<=nbdec; i++) printf("%08X%c", n[i], i%8==7 ? '\n' : ' '); if ((i-1)%8 != 7) putchar('\n'); } conv(a,b) unsigned long *a, *b; { register unsigned i, j; register signed long r, tmp; unsigned long *c; c = malloc(sizeof(unsigned long)*(nbdec+1)); for (i=0; i<=nbdec; i++) c[i]=a[i]; b[0] = c[0]; for(j=1; j<=nbdec; j++) { r = 0; for (i=nbdec; i>=1; i--) { tmp = r+(signed long)c[i]*10000; c[i] = tmp & 0xFFFF; r = tmp >> 16; } b[j] = r; } free(c); } sauve() { FILE *stream; register int i; /* sauvegarde binaire */ if ((stream = fopen("pihex","wb")) == NULL) { printf("Impossible d'ouvrir le fichier."); exit(3); } fwrite(pihex,sizeof(unsigned long),nbdec+1,stream); fclose(stream); /* sauvegarde en texte */ if ((stream = fopen("pi.hex","wt")) == NULL) { printf("Impossible d'ouvrir le fichier."); exit(3); } for (i=1; i<=nbdec; i++) { fprintf(stream, "%08lX ", pihex[i]); if (i%8 == 0) fputc('\n', stream); } fclose(stream); } sauve_etat() { FILE *stream; t1=time(NULL); printf("\rcalcul interrompu %lu s.\n", t1-t0); printf("i18=%d\n", i18); stream=fopen("sauve/etat","wt"); fprintf(stream,"%d %d %d %d %d %d\n", nbdec, i239, i57, i18, indice, (int)signe); fprintf(stream,"%d", t1-t0); fclose(stream); stream=fopen("sauve/reels","wb"); fwrite(p239,sizeof(unsigned long),nbdec+1,stream); fwrite(p57,sizeof(unsigned long),nbdec+1,stream); fwrite(p18,sizeof(unsigned long),nbdec+1,stream); fwrite(temp,sizeof(unsigned long),nbdec+1,stream); fwrite(pihex,sizeof(unsigned long),nbdec+1,stream); fclose(stream); printf("sauvegarde effectue, tapez <go32 pi continue> pour continuer\n"); } charge_etat() { FILE *stream; int i; printf("\rreprise calcul interrompu\n"); stream=fopen("sauve/etat","rt"); fscanf(stream,"%d %d %d %d %d %d\n", &nbdec, &i239, &i57, &i18, &indice, &i); signe=(signed char)i; fscanf(stream,"%d", &i); fclose(stream); p239 = malloc(sizeof(unsigned long)*(nbdec+1)); p57 = malloc(sizeof(unsigned long)*(nbdec+1)); p18 = malloc(sizeof(unsigned long)*(nbdec+1)); temp = malloc(sizeof(unsigned long)*(nbdec+1)); pihex = malloc(sizeof(unsigned long)*(nbdec+1)); if (!p239 || !p57 || !p18 || !temp || !pihex) { printf("out of memory\n"); exit(3); } stream=fopen("sauve/reels","rb"); fread(p239,sizeof(unsigned long),nbdec+1,stream); fread(p57,sizeof(unsigned long),nbdec+1,stream); fread(p18,sizeof(unsigned long),nbdec+1,stream); fread(temp,sizeof(unsigned long),nbdec+1,stream); fread(pihex,sizeof(unsigned long),nbdec+1,stream); fclose(stream); t0=time(NULL)-i; } 
Go
UTF-8
12,069
2.96875
3
[]
no_license
package frontend import ( "fmt" "os" ) type Parser struct { *TokenSet TU *TranslationUnitAST VariableTable []string PrototypeTable map[string]int FunctionTable map[string]int } func NewParser(filename string) *Parser { tokens := LexicalAnalysis(filename) return &Parser{ TokenSet: tokens, VariableTable: []string{}, PrototypeTable: make(map[string]int), FunctionTable: make(map[string]int)} } func (p *Parser) GetAST() (tu *TranslationUnitAST) { if p.TU != nil { tu = p.TU } else { tu = &TranslationUnitAST{[]*PrototypeAST{}, []*FunctionAST{}} } return } func (p *Parser) DoParse() (result bool) { if p.TokenSet != nil { result = p.visitTranslationUnit() } else { panic("error at lexer\n") } return } func (p *Parser) visitTranslationUnit() bool { p.TU = &TranslationUnitAST{[]*PrototypeAST{}, []*FunctionAST{}} // printnum paramList := []string{"i"} p.TU.Prototypes = append(p.TU.Prototypes, &PrototypeAST{"printnum", paramList}) p.PrototypeTable["printnum"] = 1 for { if !p.visitExternalDeclaration(p.TU) { return false } if p.getCurType() == TOK_EOF { break } } return true } func (p *Parser) visitExternalDeclaration(tunit *TranslationUnitAST) bool { debug("visitExternalDeclaration") proto := p.visitFunctionDeclaration() if proto != nil { tunit.Prototypes = append(tunit.Prototypes, proto) return true } funcDef := p.visitFunctionDefinition() if funcDef != nil { tunit.Functions = append(tunit.Functions, funcDef) return true } return false } func (p *Parser) visitFunctionDeclaration() (result *PrototypeAST) { debug("visitFunctionDeclaration") bkup := p.getCurIndex() proto := p.visitPrototype() if proto == nil { return nil } if p.getCurString() == ";" { _, isInPrototypeTable := p.PrototypeTable[proto.Name] _, isInFunctionTable := p.FunctionTable[proto.Name] if isInPrototypeTable || (isInFunctionTable && p.FunctionTable[proto.Name] != len(proto.Params)) { fmt.Fprintf(os.Stderr, "Function: %s is redefined\n", proto.Name) return nil } p.PrototypeTable[proto.Name] = len(proto.Params) p.getNextToken() result = proto } else { p.applyTokenIndex(bkup) return nil } return } func (p *Parser) visitFunctionDefinition() *FunctionAST { debug("visitFunctionDefinition") proto := p.visitPrototype() if proto == nil { return nil } else { _, isInPrototypeTable := p.PrototypeTable[proto.Name] _, isInFunctionTable := p.FunctionTable[proto.Name] if (isInPrototypeTable && p.PrototypeTable[proto.Name] != len(proto.Params)) || isInFunctionTable { fmt.Fprintf(os.Stderr, "Function: %s is redefined\n", proto.Name) return nil } } p.VariableTable = []string{} funcStmt := p.visitFunctionStatement(proto) if funcStmt == nil { return nil } p.FunctionTable[proto.Name] = len(proto.Params) return &FunctionAST{proto, funcStmt} } func (p *Parser) visitPrototype() *PrototypeAST { debug("visitPrototype") var name string bkup := p.getCurIndex() isFirstParam := true paramList := []string{} if p.getCurType() == TOK_INT { p.getNextToken() } else { p.applyTokenIndex(bkup) return nil } if p.getCurType() == TOK_IDENTIFIER { name = p.getCurString() p.getNextToken() } else { p.applyTokenIndex(bkup) return nil } if p.getCurType() == TOK_SYMBOL && p.getCurString() == "(" { p.getNextToken() } else { p.applyTokenIndex(bkup) return nil } for { if !isFirstParam && p.getCurType() == TOK_SYMBOL && p.getCurString() == "," { p.getNextToken() } if p.getCurType() == TOK_INT { p.getNextToken() } else { break } if p.getCurType() == TOK_IDENTIFIER { for _, param := range paramList { if param == p.getCurString() { p.applyTokenIndex(bkup) return nil } } isFirstParam = false paramList = append(paramList, p.getCurString()) p.getNextToken() } else { p.applyTokenIndex(bkup) return nil } } if p.getCurType() == TOK_SYMBOL && p.getCurString() == ")" { p.getNextToken() } else { p.applyTokenIndex(bkup) return nil } return &PrototypeAST{name, paramList} } func (p *Parser) visitFunctionStatement(proto *PrototypeAST) (funcStmt *FunctionStmtAST) { debug("visitFunctionStatement") bkup := p.getCurIndex() if p.getCurString() == "{" { p.getNextToken() } else { return nil } funcStmt = &FunctionStmtAST{[]*VariableDeclAST{}, []AST{}} for i, _ := range proto.Params { vdecl := &VariableDeclAST{proto.Params[i], Decl_param, &BaseAST{VariableDeclID}} p.VariableTable = append(p.VariableTable, vdecl.Name) funcStmt.VariableDecls = append(funcStmt.VariableDecls, vdecl) } for { if vdecl := p.visitVariableDeclaration(); vdecl != nil { vdecl.Type = Decl_local for _, availableVdecl := range p.VariableTable { if availableVdecl == vdecl.Name { return nil } } p.VariableTable = append(p.VariableTable, vdecl.Name) funcStmt.VariableDecls = append(funcStmt.VariableDecls, vdecl) } else { break } } for { if stmt := p.visitStatement(); stmt != nil { funcStmt.StmtLists = append(funcStmt.StmtLists, stmt) } else { break } } if len(funcStmt.StmtLists) > 0 { lastStmt := funcStmt.StmtLists[len(funcStmt.StmtLists)-1] if lastStmt.GetID() != JumpStmtID { p.applyTokenIndex(bkup) return nil } } if p.getCurString() == "}" { p.getNextToken() return } else { p.applyTokenIndex(bkup) return nil } return } func (p *Parser) visitVariableDeclaration() *VariableDeclAST { debug("visitVariableDeclaration") var name string bkup := p.getCurIndex() if p.getCurType() == TOK_INT { p.getNextToken() } else { return nil } if p.getCurType() == TOK_IDENTIFIER { name = p.getCurString() p.getNextToken() } else { p.applyTokenIndex(bkup) return nil } if p.getCurType() == TOK_SYMBOL && p.getCurString() == ";" { p.getNextToken() } else { p.applyTokenIndex(bkup) return nil } return &VariableDeclAST{Name: name, BaseAST: &BaseAST{VariableDeclID}} } func (p *Parser) visitStatement() (result AST) { debug("visitStatement") bkup := p.getCurIndex() for { if expr := p.visitExpressionStatement(); expr != nil { result = expr return } else if jump := p.visitJumpStatement(); jump != nil { result = jump return } else { p.applyTokenIndex(bkup) return nil } } return } func (p *Parser) visitExpressionStatement() AST { debug("visitExpressionStatement") if p.getCurString() == ";" { p.getNextToken() return &NullExprAST{&BaseAST{NullExprID}} } else if assignExpr := p.visitAssignmentExpression(); assignExpr != nil { if p.getCurString() == ";" { p.getNextToken() return assignExpr } } return nil } func (p *Parser) visitAssignmentExpression() AST { debug("visitAssignmentExpression") bkup := p.getCurIndex() if p.getCurType() == TOK_IDENTIFIER { found := false for _, availableVdecl := range p.VariableTable { if availableVdecl == p.getCurString() { found = true } } if found { lhs := &VariableAST{p.getCurString(), &BaseAST{VariableID}} p.getNextToken() if p.getCurType() == TOK_SYMBOL && p.getCurString() == "=" { p.getNextToken() if rhs := p.visitAdditiveExpression(nil); rhs != nil { return &BinaryExprAST{"=", lhs, rhs, &BaseAST{BinaryExprID}} } else { p.applyTokenIndex(bkup) } } else { p.applyTokenIndex(bkup) } } else { p.applyTokenIndex(bkup) } } addExpr := p.visitAdditiveExpression(nil) if addExpr != nil { return addExpr } return nil } func (p *Parser) visitAdditiveExpression(lhs AST) AST { debug("visitAdditiveExpression") bkup := p.getCurIndex() if lhs == nil { lhs = p.visitMultiplicativeExpression(nil) } if lhs == nil { return nil } if p.getCurType() == TOK_SYMBOL && p.getCurString() == "+" { p.getNextToken() rhs := p.visitMultiplicativeExpression(nil) if rhs != nil { return p.visitMultiplicativeExpression( &BinaryExprAST{"+", lhs, rhs, &BaseAST{BinaryExprID}}) } else { p.applyTokenIndex(bkup) return nil } } if p.getCurType() == TOK_SYMBOL && p.getCurString() == "-" { p.getNextToken() rhs := p.visitMultiplicativeExpression(nil) if rhs != nil { return p.visitMultiplicativeExpression( &BinaryExprAST{"-", lhs, rhs, &BaseAST{BinaryExprID}}) } else { p.applyTokenIndex(bkup) return nil } } return lhs } func (p *Parser) visitMultiplicativeExpression(lhs AST) AST { debug("visitMultiplicativeExpression") bkup := p.getCurIndex() if lhs == nil { lhs = p.visitPostfixExpression() } if lhs == nil { return nil } if p.getCurType() == TOK_SYMBOL && p.getCurString() == "*" { p.getNextToken() rhs := p.visitPostfixExpression() if rhs != nil { return p.visitMultiplicativeExpression( &BinaryExprAST{"*", lhs, rhs, &BaseAST{BinaryExprID}}) } else { p.applyTokenIndex(bkup) return nil } } if p.getCurType() == TOK_SYMBOL && p.getCurString() == "/" { p.getNextToken() rhs := p.visitPostfixExpression() if rhs != nil { return p.visitMultiplicativeExpression( &BinaryExprAST{"/", lhs, rhs, &BaseAST{BinaryExprID}}) } else { p.applyTokenIndex(bkup) return nil } } return lhs } func (p *Parser) visitPostfixExpression() (result AST) { debug("visitPostfixExpression") var paramNum int var isInTable bool bkup := p.getCurIndex() if p.getCurType() == TOK_IDENTIFIER { callee := p.getCurString() p.getNextToken() if paramNum, isInTable = p.PrototypeTable[callee]; !isInTable { if paramNum, isInTable = p.FunctionTable[callee]; !isInTable { p.applyTokenIndex(bkup) if priExpr := p.visitPrimaryExpression(); priExpr != nil { result = priExpr } return } } if p.getCurType() != TOK_SYMBOL || p.getCurString() != "(" { p.applyTokenIndex(bkup) if priExpr := p.visitPrimaryExpression(); priExpr != nil { result = priExpr } return } p.getNextToken() args := []AST{} for { if assignExpr := p.visitAssignmentExpression(); assignExpr != nil { args = append(args, assignExpr) if p.getCurType() == TOK_SYMBOL && p.getCurString() == "," { p.getNextToken() } else { break } } } if len(args) != paramNum { p.applyTokenIndex(bkup) return nil } if p.getCurType() == TOK_SYMBOL && p.getCurString() == ")" { p.getNextToken() result = &CallExprAST{callee, args, &BaseAST{CallExprID}} } else { p.applyTokenIndex(bkup) } } if result == nil { if priExpr := p.visitPrimaryExpression(); priExpr != nil { result = priExpr return } } return } func (p *Parser) visitPrimaryExpression() AST { debug("visitPrimaryExpression") bkup := p.getCurIndex() if p.getCurType() == TOK_IDENTIFIER { found := false for _, availableVdecl := range p.VariableTable { if availableVdecl == p.getCurString() { found = true } } if found { name := p.getCurString() p.getNextToken() return &VariableAST{name, &BaseAST{VariableID}} } else { p.applyTokenIndex(bkup) return nil } } else if p.getCurType() == TOK_DIGIT { val := p.getCurNumVal() p.getNextToken() return &NumberAST{val, &BaseAST{NumberID}} } else if p.getCurType() == TOK_SYMBOL && p.getCurString() == "-" { p.getNextToken() if p.getCurType() == TOK_DIGIT { val := p.getCurNumVal() p.getNextToken() return &NumberAST{-val, &BaseAST{NumberID}} } else { p.applyTokenIndex(bkup) return nil } } return nil } func (p *Parser) visitJumpStatement() AST { debug("visitJumpStatement") bkup := p.getCurIndex() if p.getCurType() == TOK_RETURN { p.getNextToken() if assignExpr := p.visitAssignmentExpression(); assignExpr != nil { if p.getCurType() == TOK_SYMBOL && p.getCurString() == ";" { p.getNextToken() return &JumpStmtAST{assignExpr, &BaseAST{JumpStmtID}} } } } p.applyTokenIndex(bkup) return nil } func debug(msg string) { if os.Getenv("DEBUG") != "" { fmt.Println(msg) } }
Java
UTF-8
1,218
2.84375
3
[]
no_license
package com.song.androidstudy.shell; import android.util.Log; import java.io.BufferedReader; import java.io.InputStreamReader; /** * Created by chensongsong on 2019/3/14. */ public class ShellHelper { private static final String TAG = "ShellHelper"; /** * 执行shell命令 * * @param cmd * @return */ public static String executeShell(String cmd) { try { Process p = Runtime.getRuntime().exec(cmd); String data = null; // BufferedReader ie = new BufferedReader(new InputStreamReader(p.getErrorStream())); BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream())); // String error = null; // while ((error = ie.readLine()) != null // && !error.equals("null")) { // data += error + "\n"; // } String line = null; while ((line = in.readLine()) != null && !"null".equals(line)) { data += line + "\n"; } Log.e(TAG, "cmdShell: " + data); return data; } catch (Exception e) { e.printStackTrace(); } return null; } }
C++
UTF-8
18,484
2.640625
3
[]
no_license
#include "p41class.h" p12class::p12class() { } p12class::~p12class() { } GLuint texplayer, texobstacle, grass, roadtex; char* stages [6] {"grass4.jpg", "dirt.png", "water.jpg", "sand.jpg", "grass5.png", "dry.jpg"}; FILE* fp; GLfloat player [] //the player's initial position. { 230, 175, //centered on x, bottom down on y. 260, 175, 260, 125, 230, 125 }; GLfloat lineleft [] // the line that draws the frontier. { 140, 0, 140, 2500, 0,2500, 0,0 }; GLfloat lineright[] { 380, 0, 380, 2500, 500, 2500, 500, 0 }; GLfloat road [] { 380,0, 380,2500, //5000 140,2500, //5000 140,0 }; GLfloat field [16]; int x=2; int level=0; int multiplier=1; int productdone, countermp, texcounter=0; float speed=3.0; bool paused=false; int distancetolevel=800; int factor=0; GLuint p12class::loadtexture(const char* filename) { int width, height; unsigned char* image= SOIL_load_image(filename, &width, &height, 0, SOIL_LOAD_RGBA); if(image==nullptr) { cerr << "Failed to load the texture" << " " << filename << endl; return 0; } GLuint textureid; glGenTextures(1, &textureid); glBindTexture(GL_TEXTURE_2D, textureid); glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width, height, 0, GL_RGBA, GL_UNSIGNED_BYTE, image); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR); glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_MIRRORED_REPEAT); SOIL_free_image_data(image); return textureid; } SDL_Window* p12class::init() //the function that initialize the game. { SDL_Init(SDL_INIT_EVERYTHING); //initialize SDL. SDL_Window* window; //get a window pointer called "window". window=SDL_CreateWindow("Project12", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 500,500, SDL_WINDOW_OPENGL); //window is creating a window SDL_GLContext context; //get a context called context. context=SDL_GL_CreateContext(window); //the context should be placed on the window. glewInit(); //initialize everything that glew has to offer. if(glewInit()!=GLEW_OK) //is it glew ok? { cerr << "Glew initialization has failed" << endl; } else //if glew was not ok, enter here. { cout << "Glew has been successfully initialized!" << endl; } return window; } void p12class::draw(SDL_Window* window) //function that draw on the window. { fieldrand(); //translating the normalized coordinates into pixel's glViewport(0,0,500,500); glMatrixMode(GL_PROJECTION); glLoadIdentity(); glOrtho(0,500,0,500,-100,100); glMatrixMode(GL_MODELVIEW); glLoadIdentity(); //translating done. int Score=0; //the initial score. int highscore=0; fp=fopen("D:/highscore.txt", "r"); if(fp) //if the file exists. { fscanf(fp, "%d", &highscore); //get the record. cout << "Highscore: " << highscore << endl; //print to the screen. } else //if the file does not exist { cout << "No previous records!" << endl; } cout << "Multiplier: X" << multiplier << endl; cout << "Distance to next level: " << distancetolevel*10 << "m" << endl; cout << "Factor: " << factor*10 << endl; cout << "Level: " << level+1 << "/7" << endl; glEnable(GL_TEXTURE_2D); texplayer=loadtexture("car.png"); texobstacle=loadtexture("car2.png"); grass=loadtexture("grass4.jpg"); roadtex=loadtexture("road3.jpg"); glEnable(GL_BLEND); glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA); while(1) //infinite loop. { if(!paused) { distancetravel(); if(distancetolevel<=0&&level<6) { paused=true; level++; glClear(GL_COLOR_BUFFER_BIT); glLoadIdentity(); grass=loadtexture(stages[level]); cout << "Going to the next level in: " << endl; for(int countback=5; countback>=0; countback--) { cout << countback << endl; SDL_Delay(1000); } SDL_GL_SwapWindow(window); distancetolevel=800+(400*level); countermp=0; multiplier=1; productdone=0; speed-=0.5; paused=false; } movecoords(); if(countermp==1000) { countermp=0; multiplier-=productdone; productdone=0; } if(texcounter==int(500/x)) { texcounter=0; resetcoords(); distancetolevel-=factor; } glClear(GL_COLOR_BUFFER_BIT); //clear the screen each time; glClear(GL_COLOR_BUFFER_BIT); glBindTexture(GL_TEXTURE_2D, roadtex); glBegin(GL_QUADS); glTexCoord2f(10,1.0); glVertex2f(road[0], road[1]); glTexCoord2f(0.0,1.0); glVertex2f(road[2], road[3]); glTexCoord2f(0.0,0.0); glVertex2f(road[4], road[5]); glTexCoord2f(10,0.0); glVertex2f(road[6], road[7]); glEnd(); glBindTexture(GL_TEXTURE_2D, texobstacle); glBegin(GL_QUADS); glTexCoord2f(1.0,1.0); glVertex2f(field[0], field[1]); glTexCoord2f(0.0,1.0); glVertex2f(field[2], field[3]); glTexCoord2f(0.0,0.0); glVertex2f(field[4], field[5]); glTexCoord2f(1.0,0.0); glVertex2f(field[6], field[7]); glTexCoord2f(1.0,1.0); glVertex2f(field[8], field[9]); glTexCoord2f(0.0,1.0); glVertex2f(field[10], field[11]); glTexCoord2f(0.0,0.0); glVertex2f(field[12], field[13]); glTexCoord2f(1.0,0.0); glVertex2f(field[14], field[15]); glEnd(); glBindTexture(GL_TEXTURE_2D, texplayer); glBegin(GL_QUADS); glTexCoord2f(1.0,1.0); glVertex2f(player[0], player[1]); glTexCoord2f(0.0,1.0); glVertex2f(player[2], player[3]); glTexCoord2f(0.0,0.0); glVertex2f(player[4], player[5]); glTexCoord2f(1.0,0.0); glVertex2f(player[6], player[7]); glEnd(); glBindTexture(GL_TEXTURE_2D, grass); glBegin(GL_QUADS); glTexCoord2f(10.0,1.0); glVertex2f(lineleft[0], lineleft[1]); glTexCoord2f(0.0,1.0); glVertex2f(lineleft[2], lineleft[3]); glTexCoord2f(0.0,0.0); glVertex2f(lineleft[4], lineleft[5]); glTexCoord2f(10.0,0.0); glVertex2f(lineleft[6], lineleft[7]); glEnd(); glBegin(GL_QUADS); glTexCoord2f(10.0,1.0); glVertex2f(lineright[0], lineright[1]); glTexCoord2f(0.0,1.0); glVertex2f(lineright[2], lineright[3]); glTexCoord2f(0.0,0.0); glVertex2f(lineright[4], lineright[5]); glTexCoord2f(10.0,0.0); glVertex2f(lineright[6], lineright[7]); glEnd(); SDL_GL_SwapWindow(window); //change the empty window, with the drew one. field[1]-=x/2; //field's y position decreases each time the loop rotates, this make the obstacles move. field[3]-=x/2; //x is an integer, if it's initialized with an odd value, and then divided by 2, it will not work. field[5]-=x/2; field[7]-=x/2; field[9]-=x/2; field[11]-=x/2; field[13]-=x/2; field[15]-=x/2; SDL_Delay(speed); //let there be this delay, to make the game run slower, until the lever increases. scoremultiplier(); frontcollision(); Score=scoreupdate(Score,highscore); if(isgameover(window, Score, highscore)) { break; } collisiondetection(); texcounter++; countermp++; } input(); } } void p12class::input () { SDL_Event a; while(SDL_PollEvent(&a)) //if there is an event set { if(a.type==SDL_KEYDOWN)//verify if at the event is any key pressed switch(a.key.keysym.sym) // if the key was pressed, verify which key that was { case SDL_QUIT: //if the window close button pressed { cout << "Close the console to quit!" << endl; //print this message in the console. } case SDLK_LEFT: //if the left arrow button was pressed { if(player[0]>150&&paused==false) //if the player is on a x position > than 150 { player[0]-=15; //modify player's x position (so the player could mode left). player[2]-=15; player[4]-=15; player[6]-=15; } break; //exit the switch } case SDLK_RIGHT: //if the right arrow button was pressed { if(player[0]<350&&paused==false) //if the player is on a x position < than 350 { player[0]+=15; //modify the player's x position (so the player could move right) player[2]+=15; player[4]+=15; player[6]+=15; } break; // exit the switch } case SDLK_m: { Mix_PauseMusic(); cout << "Sound muted!" << endl; break; } case SDLK_p: { cout << "Sound resumed!" << endl; playtrack(); break; } case SDLK_SPACE: { if(!paused) { cout << "Game Paused!" << endl; paused=true; } else if(paused) { paused=false; cout << "Game Resumed!" << endl; } break; } } } } void p12class::resetcoords() { road[1]=0; road[3]=2500; road[5]=2500; road[7]=0; lineleft[1]=0; lineleft[3]=2500; lineleft[5]=2500; lineleft[7]=0; lineright[1]=0; lineright[3]=2500; lineright[5]=2500; lineright[7]=0; } void p12class::movecoords() { road[1]-=x; road[3]-=x; road[5]-=x; road[7]-=x; lineleft[1]-=x; lineleft[3]-=x; lineleft[5]-=x; lineleft[7]-=x; lineright[1]-=x; lineright[3]-=x; lineright[5]-=x; lineright[7]-=x; } void p12class::fieldrand() { field[0]=((rand()%90)+150); //get another position, in the same way, random on x field[1]=550; //y position always on the top. field[2]=field[0]+30; field[3]=550; field[4]=field[2]; field[5]=500; field[6]=field[0]; field[7]=500; field[8]=((rand()%90)+250); field[9]=550; field[10]=field[8]+30; field[11]=550; field[12]=field[10]; field[13]=500; field[14]=field[8]; field[15]=500; } void p12class::playtrack() { bool pausecheck=false; if(paused==false) { paused=true; pausecheck=true; } char* filename=nullptr; cout << "\nMusic Selector: Press key 1, 2 or 3 to select the music track! "<< endl; cout << "Press any other key to skip!" << endl; char a; cin >> a; switch(a) { case '1': {filename ="t1.wav"; break;} case '2': {filename ="t2.wav"; break;} case '3': {filename ="t3.wav"; break;} default: break; } if(filename!=nullptr) { Mix_OpenAudio(44100, MIX_DEFAULT_FORMAT, 2, 4096); Mix_Music* track1=Mix_LoadMUS(filename); if(track1==nullptr) { cerr << "Unable to load the file: " << filename << endl; } else { Mix_PlayMusic(track1, -1); } } else { cout << "Music Selector Skipped!" << endl; } if(pausecheck==true) { int countback; cout << "Game will resume in: " << endl; for(countback=5; countback>=0; countback--) { cout << countback << endl; SDL_Delay(1000); } paused=false; } } void p12class::collisiondetection() { if(player[7]<field[1]&&player[1]>field[1]) { if(player[4]>field[0] && player[4]<field[2] || player[4]>field[8] && player[4]<field[10])//260 { multiplier-=productdone; productdone=0; player[0]-=15; player[2]-=15; player[4]-=15; player[6]-=15; } if(player[0]<field[2] && player[0]>field[0] || player[0]<field[10] && player[0]>field[8]) { multiplier-=productdone; productdone=0; player[0]+=15; player[2]+=15; player[4]+=15; player[6]+=15; } } } void p12class::frontcollision() { if(player[1]+(x-1)<=field[1]&&player[1]+(x-1)>=field[7] || player[1]+(x-1)<=field[9]&&player[1]+(x-1)>=field[15]) //if the obstacles are on the same y line with the player //player+ (x-1) is there just in case, that x is increased (if x is set greater than 4 collisions won't working). { if( player[0]>=(field[0]-25) && player[2] <= (field[2]+25) || player[0]>=(field[8]-25) && player[2] <= (field[10]+25)) { if(player[2]+5>field[0]-5 && player[2]+5<field[0]+16 || player[2]+5>field[8]-5 && player[2]+5<field[8]+16)//push left //player+5 and field-5 just add there more precision; { player[0]-=20; player[1]-=25; player[2]-=20; player[3]-=25; player[4]-=20; player[5]-=25; player[6]-=20; player[7]-=25; multiplier-=productdone; productdone=0; } if(player[2]-5<field[2]+5 && player[2]-5>field[0]+16 || player[2]-5<field[10]+5 && player[2]-5>field[8]+16)//push right //player-5 and field+5 just add there more precision; { player[0]+=20; player[1]-=25; player[2]+=20; player[3]-=25; player[4]+=20; player[5]-=25; player[6]+=20; player[7]-=25; multiplier-=productdone; productdone=0; } } } } int p12class::scoreupdate(int Score, int highscore) { if(field[1]<=0) //when the field is no longer on the screen { fieldrand(); Score+=(10*multiplier); //if the obstacles run out of the screen, increase the score, because the player wasn't hit. system("cls"); //clear the console each time. cout << "Score: " << Score << endl; //on the empty console, write the new score. cout << "Multiplier: X" << multiplier << endl; cout << "Distance to next level: " << distancetolevel*10 << "m" << endl; cout << "Factor: " << factor*10 << endl; cout << "Level: " << level+1 << "/7" << endl; if(highscore<Score) //if the highest score has been defeated { cout << "Highscore: " << Score << endl; //print the score } else //let the highscore be printed on the console. cout << "Highscore: " << highscore << endl; } return Score; } void p12class::distancetravel() { if(speed<3&&speed>2 || speed<2&&speed>1 || speed<1&&speed>0) { if(speed==2.5) { factor=15; } else if(speed==1.5) { factor=30; } else if(speed==0.5) { factor=60; } } else { switch(int(speed)) { case 3: {factor=10; break;} case 2: {factor=20; break;} case 1: {factor=40; break;} case 0: {factor=80; break;} } } } int p12class::isgameover(SDL_Window* window, int Score, int highscore) { if(player[1]<=0) { cout << "Gameover!" << endl; distancetolevel=800; factor=0; level=0; multiplier=1; speed=3.0; productdone=0; player[0]=230; player[1]=175; player[2]=260; player[3]=175; player[4]=260; player[5]=125; player[6]=230; player[7]=125; glClear(GL_COLOR_BUFFER_BIT); glLoadIdentity(); if(fp) //if the file is already opened by the game { fclose(fp); //close it, because it's opened for reading. if(highscore<Score)//if the highscore has been defetead { fp=fopen("D:/highscore.txt", "w"); //open the file for writing. fprintf(fp,"%d", Score); //write the new highscore on the file. fclose(fp); //close the file. } } else //if the file is not opened, because there was no file. { fclose(fp);//be sure it's closed. fp=fopen("D:/highscore.txt", "w");//then open/create a file for writing. fprintf(fp,"%d", Score); //print there the value of Score. fclose(fp);//close the file. } return 1; } return 0; } void p12class::pushup() { if(multiplier%10==0) //if multiplier is multiple of 10. { cout << "In pushup!" << endl; if(player[1]<200) { cout << "Increasing values!" << endl; player[1]+=10; player[3]+=10; player[5]+=10; player[7]+=10; } } } void p12class::scoremultiplier() { if(player[1]==field[7]) { if( player[0]>=(field[6]-50) && player[2] <= (field[2]+50) || player[0]>=(field[14]-50) && player[2] <= (field[10]+50)) //from the distance 50 below until collision for passing a car, increase the multiplier to increase the score. { countermp=0; multiplier++; productdone++; } pushup(); } }
C#
UTF-8
3,501
2.53125
3
[ "Apache-2.0" ]
permissive
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Diagnostics; namespace SpyUO { public class SelectProcess : System.Windows.Forms.Form { private class ProcessItem : IComparable { private Process m_Process; public Process Process { get { return m_Process; } } public ProcessItem( Process process ) { m_Process = process; } public override string ToString() { return m_Process.ProcessName; } public int CompareTo( object obj ) { ProcessItem pi = obj as ProcessItem; if ( pi == null ) return -1; else return ToString().CompareTo( pi.ToString() ); } } private System.Windows.Forms.Button bOk; private System.Windows.Forms.Button bCancel; private System.Windows.Forms.ListBox lbProcesses; private System.ComponentModel.Container components = null; protected override void Dispose( bool disposing ) { if ( disposing ) { if ( components != null ) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Metodo necessario per il supporto della finestra di progettazione. Non modificare /// il contenuto del metodo con l'editor di codice. /// </summary> private void InitializeComponent() { this.bOk = new System.Windows.Forms.Button(); this.bCancel = new System.Windows.Forms.Button(); this.lbProcesses = new System.Windows.Forms.ListBox(); this.SuspendLayout(); // // bOk // this.bOk.DialogResult = System.Windows.Forms.DialogResult.OK; this.bOk.Location = new System.Drawing.Point(88, 240); this.bOk.Name = "bOk"; this.bOk.TabIndex = 1; this.bOk.Text = "Ok"; // // bCancel // this.bCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.bCancel.Location = new System.Drawing.Point(8, 240); this.bCancel.Name = "bCancel"; this.bCancel.Size = new System.Drawing.Size(72, 23); this.bCancel.TabIndex = 2; this.bCancel.Text = "Cancel"; // // lbProcesses // this.lbProcesses.Name = "lbProcesses"; this.lbProcesses.Size = new System.Drawing.Size(168, 238); this.lbProcesses.TabIndex = 3; // // SelectProcess // this.AcceptButton = this.bOk; this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.CancelButton = this.bCancel; this.ClientSize = new System.Drawing.Size(168, 270); this.Controls.AddRange(new System.Windows.Forms.Control[] { this.lbProcesses, this.bCancel, this.bOk}); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "SelectProcess"; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Select Process"; this.ResumeLayout(false); } #endregion public SelectProcess() { InitializeComponent(); Process[] processes = Process.GetProcesses(); ArrayList list = new ArrayList( processes.Length ); foreach ( Process process in processes ) list.Add( new ProcessItem( process ) ); list.Sort(); lbProcesses.Items.AddRange( list.ToArray() ); } public Process GetSelectedProcess() { ProcessItem pi = lbProcesses.SelectedItem as ProcessItem; if ( pi == null ) return null; else return pi.Process; } } }
C++
UTF-8
2,377
3.140625
3
[]
no_license
#ifndef ADJACENCYBITSET_H #define ADJACENCYBITSET_H #include <vector> #include <algorithm> #include "adjacency.h" namespace graph { class AdjacencyBitSetIterator : public AdjacencyIterator { public: virtual ~AdjacencyBitSetIterator() {} virtual vertex_t destination() const override { assert(isValid()); return pos; } virtual bool advance() override { if (!isValid()) return false; pos = findPopBit(pos + 1); return true; } virtual bool isValid() const override { return pos < bits.size(); } protected: friend class AdjacencyBitSet; AdjacencyBitSetIterator(std::size_t pos, const std::vector<bool> &bits): bits(bits), pos(findPopBit(pos)) {} std::size_t findPopBit(std::size_t start) { while (start < bits.size() && !bits[start]) ++start; return start; } private: const std::vector<bool> &bits; std::size_t pos; }; class AdjacencyBitSet : public Adjacency { public: template<class FwdIter> AdjacencyBitSet(FwdIter begin, FwdIter end): bits(makeBitSet(begin, end)), size_(std::distance(begin, end)) {} explicit AdjacencyBitSet(std::vector<bool> &&bits): bits(bits), size_(std::count(this->bits.cbegin(), this->bits.cend(), true)) {} virtual ~AdjacencyBitSet() {} virtual std::size_t size() const override { return size_; } virtual std::unique_ptr<AdjacencyIterator> makeIterator() const override { return std::unique_ptr<AdjacencyIterator>(new AdjacencyBitSetIterator(0, bits)); } virtual bool adjacentTo(vertex_t vertex) const override { // assert(vertex < bits.size()); return vertex < bits.size() && bits[vertex]; } private: template<class FwdIter> std::vector<bool> makeBitSet(FwdIter begin, FwdIter end) { std::vector<bool> ret; for (; begin != end; ++begin) { if (ret.size() <= *begin) ret.resize(*begin + 1, 0); assert(!ret[*begin]); ret[*begin] = true; } ret.shrink_to_fit(); return ret; } const std::vector<bool> bits; const std::size_t size_; }; } // namespace graph #endif // ADJACENCYBITSET_H