file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
12.1k
suffix
large_stringlengths
0
12k
middle
large_stringlengths
0
7.51k
fim_type
large_stringclasses
4 values
code_stats.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
{ pub name: Option<String>, pub kind: SizeKind, pub size: u64, pub align: u64, pub fields: Vec<FieldInfo>, } #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] pub enum SizeKind { Exact, Min, } #[derive(Clone, PartialEq, Eq, Hash, Debug)] pub struct FieldInfo { pub name: String, p...
VariantInfo
identifier_name
code_stats.rs
// Copyright 2016 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
pub struct VariantInfo { pub name: Option<String>, pub kind: SizeKind, pub size: u64, pub align: u64, pub fields: Vec<FieldInfo>, } #[derive(Copy, Clone, PartialEq, Eq, Hash, Debug)] pub enum SizeKind { Exact, Min, } #[derive(Clone, PartialEq, Eq, Hash, Debug)] pub struct FieldInfo { p...
use rustc_target::abi::{Align, Size}; use rustc_data_structures::fx::{FxHashSet}; use std::cmp::{self, Ordering}; #[derive(Clone, PartialEq, Eq, Hash, Debug)]
random_line_split
normal.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } } impl IndependentSample<f64> for Normal { fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 { let StandardNormal(n) = rng.gen::<StandardNormal>(); self.mean + self.std_dev * n } } /// The log-normal distribution `ln N(mean, std_d...
sample
identifier_name
normal.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
else { ziggurat_tables::ZIG_NORM_R - x } } StandardNormal(ziggurat( rng, true, // this is symmetric &ziggurat_tables::ZIG_NORM_X, &ziggurat_tables::ZIG_NORM_F, pdf, zero_case)) } } /// The normal distribution `N(mean, std_dev**2)`. /// /...
{ x - ziggurat_tables::ZIG_NORM_R }
conditional_block
normal.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
#[cfg(test)] mod bench { extern crate test; use std::prelude::*; use self::test::Bencher; use std::mem::size_of; use distributions::{Sample}; use super::Normal; #[bench] fn rand_normal(b: &mut Bencher) { let mut rng = ::test::weak_rng(); let mut normal = Normal::new(-2.7...
}
random_line_split
normal.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} impl Sample<f64> for LogNormal { fn sample<R: Rng>(&mut self, rng: &mut R) -> f64 { self.ind_sample(rng) } } impl IndependentSample<f64> for LogNormal { fn ind_sample<R: Rng>(&self, rng: &mut R) -> f64 { self.norm.ind_sample(rng).exp() } } #[cfg(test)] mod tests { use std::prelude::*; u...
{ assert!(std_dev >= 0.0, "LogNormal::new called with `std_dev` < 0"); LogNormal { norm: Normal::new(mean, std_dev) } }
identifier_body
aarch64-modifiers.rs
// min-llvm-version: 10.0.1 // assembly-output: emit-asm // compile-flags: -O // compile-flags: --target aarch64-unknown-linux-gnu // needs-llvm-components: aarch64 #![feature(no_core, lang_items, rustc_attrs)] #![crate_type = "rlib"] #![no_core] #![allow(asm_sub_register)] #[rustc_builtin_macro] macro_rules! asm { ...
check!(vreg_low16_s vreg_low16 "ldr {:s}, [x0]"); // CHECK-LABEL: vreg_low16_d: // CHECK: //APP // CHECK: ldr d0, [x0] // CHECK: //NO_APP check!(vreg_low16_d vreg_low16 "ldr {:d}, [x0]"); // CHECK-LABEL: vreg_low16_q: // CHECK: //APP // CHECK: ldr q0, [x0] // CHECK: //NO_APP check!(vreg_low16_q vreg_low16 "ldr {:q}, ...
// CHECK-LABEL: vreg_low16_s: // CHECK: //APP // CHECK: ldr s0, [x0] // CHECK: //NO_APP
random_line_split
batch_account.py
from utils import common, database from TestCase.MVSTestCase import * class TestAccount(MVSTestCaseBase): roles = () need_mine = False def test_0_new_account(self):
def test_1_new_address(self): '''new address for Zac''' max_duration = 0.01 avg_duration = 0.002 round = 5000 Zac.create() account_table_file = '/home/%s/.metaverse/mainnet/account_table' % common.get_username() try: origin_payload_size = data...
'''create new account * 5000''' account_table_file = '/home/%s/.metaverse/mainnet/account_table' % common.get_username() origin_payload_size = database.get_payload_size(account_table_file) batch_amount = 5000 lastwords = [] for i in range(batch_amount): ec, message =...
identifier_body
batch_account.py
from utils import common, database from TestCase.MVSTestCase import * class
(MVSTestCaseBase): roles = () need_mine = False def test_0_new_account(self): '''create new account * 5000''' account_table_file = '/home/%s/.metaverse/mainnet/account_table' % common.get_username() origin_payload_size = database.get_payload_size(account_table_file) batch_am...
TestAccount
identifier_name
batch_account.py
from utils import common, database from TestCase.MVSTestCase import * class TestAccount(MVSTestCaseBase): roles = () need_mine = False def test_0_new_account(self): '''create new account * 5000''' account_table_file = '/home/%s/.metaverse/mainnet/account_table' % common.get_username() ...
self.assertLess(sum(durations), avg_duration*round) current_payload_size = database.get_payload_size(account_table_file) # each simple account record size < 300 self.assertGreater(300 * round, current_payload_size - origin_payload_size, "...
duration, ret = common.duration_call(mvs_rpc.new_address, Zac.name, Zac.password) self.assertEqual(ret[0], 0, "mvs_rpc.new_address failed!") self.assertLess(duration, max_duration) durations.append(duration)
conditional_block
batch_account.py
from utils import common, database from TestCase.MVSTestCase import * class TestAccount(MVSTestCaseBase): roles = () need_mine = False def test_0_new_account(self): '''create new account * 5000''' account_table_file = '/home/%s/.metaverse/mainnet/account_table' % common.get_username() ...
duration, ret = common.duration_call(mvs_rpc.new_address, Zac.name, Zac.password) self.assertEqual(ret[0], 0, "mvs_rpc.new_address failed!") self.assertLess(duration, max_duration) durations.append(duration) self.assertLess(sum(durations), avg_...
random_line_split
webpack.config.js
const CaseSensitivePathsPlugin = require('case-sensitive-paths-webpack-plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const WatchMissingNodeModulesPlugin = require('react-dev-utils/WatchMissingNodeModulesPlugin'); const webpack = require('webpack'); const paths = require('./tools/paths'); const en...
{ test: /\.svg$/, use: [{ loader: 'file-loader', options: { name: 'static/media/[name].[hash:8].[ext]' } }] } ] }, plugins: [ new HtmlWebpackPlugin({ inject: true, template: paths.appHtml }), new webpack.DefinePlugin(env), new webpack.HotModuleReplacementPlugin()...
] },
random_line_split
utils.ts
import _ from 'lodash'; import shallowEqual from '../utils/shallowEqual'; import { CheckTreePickerProps } from './CheckTreePicker.d'; interface Props { childrenKey?: string; } export interface Node { uncheckable?: boolean; refKey?: string; check?: boolean; parentNode?: Node; checkAll?: boolean; visible?...
eePickerProps) { const { disabledItemValues = [], valueKey } = props; return disabledItemValues.some((value: any) => shallowEqual(nodes[node.refKey][valueKey], value)); }
rNode = nodes[node.refKey]; if (curNode) { formatted.check = curNode.check; formatted.expand = curNode.expand; formatted.uncheckable = curNode.uncheckable; formatted.parentNode = curNode.parentNode; if (node[childrenKey]?.length > 0) { formatted[childrenKey] = getFormattedTree(...
identifier_body
utils.ts
import _ from 'lodash'; import shallowEqual from '../utils/shallowEqual'; import { CheckTreePickerProps } from './CheckTreePicker.d'; interface Props { childrenKey?: string; } export interface Node { uncheckable?: boolean; refKey?: string; check?: boolean; parentNode?: Node; checkAll?: boolean; visible?...
return isEveryChildChecked(child, nodes, props); } return nodes[child.refKey].check; }); } return nodes[node.refKey].check; } export function isSomeChildChecked(node: Node, nodes: Nodes, props: Props): boolean { const { childrenKey } = props; if (!node[childrenKey]) { return false; ...
return children.every(child => { if (child[childrenKey]?.length) {
random_line_split
utils.ts
import _ from 'lodash'; import shallowEqual from '../utils/shallowEqual'; import { CheckTreePickerProps } from './CheckTreePicker.d'; interface Props { childrenKey?: string; } export interface Node { uncheckable?: boolean; refKey?: string; check?: boolean; parentNode?: Node; checkAll?: boolean; visible?...
ing): boolean { return data.some((node: Node) => node[childrenKey]); } /** * 获取该节点的兄弟节点是否都为 uncheckable * @param {*} node */ export function getSiblingNodeUncheckable(node: Node, nodes: Nodes): boolean { const list = []; const parentNodeRefkey = node.parentNode ? node.parentNode.refKey : ''; Object.keys(no...
y[], childrenKey: str
identifier_name
utils.ts
import _ from 'lodash'; import shallowEqual from '../utils/shallowEqual'; import { CheckTreePickerProps } from './CheckTreePicker.d'; interface Props { childrenKey?: string; } export interface Node { uncheckable?: boolean; refKey?: string; check?: boolean; parentNode?: Node; checkAll?: boolean; visible?...
{ list.push(curNode); } }); return list.every(node => node.uncheckable); } /** * 获取第一层节点是否全部都为 uncheckable */ export function getEveryFisrtLevelNodeUncheckable(nodes: Nodes) { const list = []; Object.keys(nodes).forEach((refKey: string) => { const curNode = nodes[refKey]; if (!curNode.par...
ode?.refKey === parentNodeRefkey)
conditional_block
test-scripts.ts
import { writeMultipleFiles } from '../../utils/fs'; import { ng } from '../../utils/process'; import { updateJsonFile } from '../../utils/project'; import { expectToFail } from '../../utils/utils'; import { stripIndent } from 'common-tags'; export default function () { return Promise.resolve() .then(() => ng('...
}); ` })) // should fail because the global scripts were not added to scripts array .then(() => expectToFail(() => ng('test', '--single-run'))) .then(() => updateJsonFile('.angular-cli.json', configJson => { const app = configJson['apps'][0]; app['scripts'] = [ 'string-...
it('should have access to input-script.js', async(() => { expect(inputScriptGlobal).toBe('input-scripts.js'); }));
random_line_split
test.js
var assert = require('assert') var parse = require('../') // test parser assert.equal(parse('***foo***'), '<p><strong><em>foo</em></strong></p>\n') assert.equal(parse('# **blah**'), '<h1><a name="--blah--"></a><strong>blah</strong></h1>\n') assert.equal(parse('Blah blah\n-----'),...
assert.equal(parse('```sh\n$ test\n```'), '<pre><code class="lang-sh">$ <span class="hljs-built_in">test</span>\n</code></pre>\n') assert.equal(parse('```\n-----\n```'), '<pre><code>-----\n</code></pre>\n') // metadata assert.equal(parse('---\naaa: 123\nbbb: "*456*"\n---\n\n*foo*...
// highlighter assert.equal(parse('```js\nvar foo = "bar";\n```'), '<pre><code class="lang-js"><span class="hljs-keyword">var</span> foo = <span class="hljs-string">&quot;bar&quot;</span>;\n</code></pre>\n')
random_line_split
order.service.ts
import { Injectable } from '@angular/core'; import { Customer, CustomerService } from '../customer-manage/customer.service'; import { Material, MaterialService, Category } from '../material-manage/material.service'; import { copy } from '../common'; import { IndexedDBService, DynamicConfiguration } from '../common.serv...
: MaterialService, private _customer_service: CustomerService ) { super('order'); } getOrdersCount = this.getCount getOrders(start_index = 0, num = 10 , dynamic_configuration?: DynamicConfiguration): Promise<Order[]> { return this.getList<Order>(start_index, num, dynamic_...
rial_service
identifier_name
order.service.ts
import { Injectable } from '@angular/core'; import { Customer, CustomerService } from '../customer-manage/customer.service'; import { Material, MaterialService, Category } from '../material-manage/material.service'; import { copy } from '../common'; import { IndexedDBService, DynamicConfiguration } from '../common.serv...
area: 0, }; export const ORDERNODE_DEFAULT: OrderNode = { size_list: [SIZE_DEFAULT], machining_remark: "", machining_price: 0, calcType: CalcType.面积 }; export const ORDER_DEFAULT: Order = { customer: { name: "", phone: "", address: "", }, nodes: [copy(ORDERNODE_DE...
} export const SIZE_DEFAULT: Size = { width: 0, height: 0,
random_line_split
order.service.ts
import { Injectable } from '@angular/core'; import { Customer, CustomerService } from '../customer-manage/customer.service'; import { Material, MaterialService, Category } from '../material-manage/material.service'; import { copy } from '../common'; import { IndexedDBService, DynamicConfiguration } from '../common.serv...
= 10 , dynamic_configuration: DynamicConfiguration): Promise<Order[]> { return this.getListByFilter<Order>(filter, before_num, num, dynamic_configuration); } getOrderById(id): Promise<Order> { return this.getById<Order>(id) } // async wrapFullOrder(order: Order): Promise<Order> {...
} getOrdersByFilter(filter: (order: Order) => boolean, before_num = 0, num
identifier_body
order.service.ts
import { Injectable } from '@angular/core'; import { Customer, CustomerService } from '../customer-manage/customer.service'; import { Material, MaterialService, Category } from '../material-manage/material.service'; import { copy } from '../common'; import { IndexedDBService, DynamicConfiguration } from '../common.serv...
er) } deleteOrder = this.remove }
stomer_service.addCustomer(new_order.customer)); } return this.add(new_order); } updateOrder(id, order: Order): Promise<number> { return this.update(id, ord
conditional_block
account-list.component.ts
import { OnInit, Component, } from 'angular2/core'; import 'rxjs/Rx'; import {RouteParams, RouteData, Router } from 'angular2/router'; import {RankComponent } from '../rank/rank.component'; import {PaginationComponent, PagingParam } from '../pagination/pagination.component'; import {JSONPService} from '../../...
this.pageTurning(this.queryParams); this._pubsub.stream.subscribe(qp => this.pageTurning(qp)); } pageTurning(qp: QueryParams) { this.queryParams = qp; let url = `${this._url}?start=${qp.start}&count=${qp.count}`; //console.log(url); //this.movies = "loading data from douban, pleas...
{ this._url = "http://api.douban.com/v2/movie/top250"; }
conditional_block
account-list.component.ts
import { OnInit, Component,
import {RouteParams, RouteData, Router } from 'angular2/router'; import {RankComponent } from '../rank/rank.component'; import {PaginationComponent, PagingParam } from '../pagination/pagination.component'; import {JSONPService} from '../../services/jsonp/jsonp.service'; import {PubSubService, QueryParams} from '../../...
} from 'angular2/core'; import 'rxjs/Rx';
random_line_split
account-list.component.ts
import { OnInit, Component, } from 'angular2/core'; import 'rxjs/Rx'; import {RouteParams, RouteData, Router } from 'angular2/router'; import {RankComponent } from '../rank/rank.component'; import {PaginationComponent, PagingParam } from '../pagination/pagination.component'; import {JSONPService} from '../../...
( private _routeData: RouteData, private _router: Router, private _jsonp: JSONPService, private _pubsub: PubSubService) { this.pagingParams = new PagingParam(250, 20, 0, 10); } ngOnInit(){ this._url = this._routeData.get('link'); if (!this._url) { this._url = "http://api.douban.com/v2/movie/top25...
constructor
identifier_name
bogus-tag.rs
// -*- rust -*- // Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // ...
{ let red: color = rgb(255, 0, 0); match red { rgb(r, g, b) => { debug!("rgb"); } hsl(h, s, l) => { debug!("hsl"); } } }
identifier_body
bogus-tag.rs
// -*- rust -*- // Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // ...
{ rgb(int, int, int), rgba(int, int, int, int), } fn main() { let red: color = rgb(255, 0, 0); match red { rgb(r, g, b) => { debug!("rgb"); } hsl(h, s, l) => { debug!("hsl"); } } }
color
identifier_name
bogus-tag.rs
// -*- rust -*- // Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // ...
} }
match red { rgb(r, g, b) => { debug!("rgb"); } hsl(h, s, l) => { debug!("hsl"); }
random_line_split
bogus-tag.rs
// -*- rust -*- // Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // ...
hsl(h, s, l) => { debug!("hsl"); } } }
{ debug!("rgb"); }
conditional_block
dropdown.js
'use strict'; angular.module('mgcrea.ngStrap.dropdown', ['mgcrea.ngStrap.tooltip'])
var defaults = this.defaults = { animation: 'am-fade', prefixClass: 'dropdown', prefixEvent: 'dropdown', placement: 'bottom-left', template: 'dropdown/dropdown.tpl.html', trigger: 'click', container: false, keyboard: true, html: false, delay: 0 }; ...
.provider('$dropdown', function() {
random_line_split
dropdown.js
'use strict'; angular.module('mgcrea.ngStrap.dropdown', ['mgcrea.ngStrap.tooltip']) .provider('$dropdown', function() { var defaults = this.defaults = { animation: 'am-fade', prefixClass: 'dropdown', prefixEvent: 'dropdown', placement: 'bottom-left', template: 'dropdown/dropdown.t...
(evt) { if(evt.target === element[0]) return; return evt.target !== element[0] && $dropdown.hide(); } return $dropdown; } return DropdownFactory; }; }) .directive('bsDropdown', function($window, $sce, $dropdown) { return { restrict: 'EAC', s...
onBodyClick
identifier_name
dropdown.js
'use strict'; angular.module('mgcrea.ngStrap.dropdown', ['mgcrea.ngStrap.tooltip']) .provider('$dropdown', function() { var defaults = this.defaults = { animation: 'am-fade', prefixClass: 'dropdown', prefixEvent: 'dropdown', placement: 'bottom-left', template: 'dropdown/dropdown.t...
if(!items.length) return; var index; angular.forEach(items, function(el, i) { if(matchesSelector && matchesSelector.call(el, ':focus')) index = i; }); // Navigate with keyboard if(evt.keyCode === 38 && index > 0) index--; else if(evt.key...
{ var $dropdown = {}; // Common vars var options = angular.extend({}, defaults, config); var scope = $dropdown.$scope = options.scope && options.scope.$new() || $rootScope.$new(); $dropdown = $tooltip(element, options); var parentEl = element.parent(); // Prot...
identifier_body
aqicn.js
/** * @fileOverview * @name aqicn.js * @author ctgnauh <huangtc@outlook.com> * @license MIT */ var request = require('request'); var cheerio = require('cheerio'); var info = require('./info.json'); /** * 从 aqicn.org 上获取空气信息 * @module aqicn */ module.exports = { // 一些多余的信息 info: info, /** * fetchWeb...
rg/city/all/) * @param {string} lang - 语言:cn、en、jp、es、kr、ru、hk、fr、pl(但当前只有 cn 和 en) * @param {module:aqicn~getAQIsCallback} callback */ getAQIs: function (city, lang, callback) { 'use strict'; var self = this; self.fetchWebPage(city, function (err, body) { if (err) { callback(err); ...
,详见[全部地区](http://aqicn.o
conditional_block
aqicn.js
/** * @fileOverview * @name aqicn.js * @author ctgnauh <huangtc@outlook.com> * @license MIT */ var request = require('request'); var cheerio = require('cheerio'); var info = require('./info.json'); /** * 从 aqicn.org 上获取空气信息 * @module aqicn */ module.exports = { // 一些多余的信息 info: info, /** * fetchWeb...
result.time = self.selectUpdateTime(body); // 全部 AQI 值 self.info.species.forEach(function (name) { var aqi = self.selectAQIText(body, name); aqis.push(aqi); result[name] = aqi; }); // 主要 AQI 值 result.aqi = self.calculateAQI(aqis); // AQI 等级及其它 var ...
var aqis = []; // 城市代码 result.city = city; // 数据提供时间
random_line_split
Product.ts
import { observable, } from 'mobx' import { IProduct, IProductClient, } from './types' import { log, } from './utils' /** * Product is something that goes in a cart, we sync these from the server but * only keep the fields we care about */ export default class Product implements IProduct { @observable ...
log('loadProduct error', err) throw err }) } }
{ this.client = client this.id = raw.id ?? '' this.productId = raw.productId ?? '' this.slug = raw.slug ?? '' this.productSlug = raw.productSlug ?? '' this.name = raw.name ?? '' this.productName = raw.productName ?? '' this.price = raw.price ?? 0 this.listPrice = raw.listPrice ?? 0 ...
identifier_body
Product.ts
import { observable, } from 'mobx' import { IProduct, IProductClient, } from './types' import { log, } from './utils' /** * Product is something that goes in a cart, we sync these from the server but * only keep the fields we care about */ export default class
implements IProduct { @observable id: string @observable productId: string @observable slug: string @observable productSlug: string @observable name: string @observable productName: string @observable price: number @observable listPrice: number @observable description: strin...
Product
identifier_name
Product.ts
import { observable, } from 'mobx' import { IProduct, IProductClient, } from './types' import { log, } from './utils' /** * Product is something that goes in a cart, we sync these from the server but * only keep the fields we care about */ export default class Product implements IProduct { @observable ...
constructor(raw: any, client: IProductClient) { this.client = client this.id = raw.id ?? '' this.productId = raw.productId ?? '' this.slug = raw.slug ?? '' this.productSlug = raw.productSlug ?? '' this.name = raw.name ?? '' this.productName = raw.productName ?? '' this.price = raw.pr...
@observable client: IProductClient
random_line_split
actor.rs
use store::Store; use middleware::Middleware; use empty_state::EmptyState; pub type ActorState<A> where A: Actor = EmptyState<A::Action>; pub type ActorStore<A> where A: Actor = Store<ActorState<A>>; pub trait Actor { type Action; fn receive(&mut self, action: Self::Action); } struct ActorMiddleware<A> { ...
} pub fn spawn_actor<A: Actor>(actor: A) -> ActorStore<A> where A: Send + Sync + 'static, A::Action: Clone + Send + Sync { let state: EmptyState<A::Action> = EmptyState::new(); let mut store = Store::new(state); let middleware = ActorMiddleware { actor: actor }; store.add_middleware...
next(action); }
random_line_split
actor.rs
use store::Store; use middleware::Middleware; use empty_state::EmptyState; pub type ActorState<A> where A: Actor = EmptyState<A::Action>; pub type ActorStore<A> where A: Actor = Store<ActorState<A>>; pub trait Actor { type Action; fn receive(&mut self, action: Self::Action); } struct ActorMiddleware<A> { ...
} pub fn spawn_actor<A: Actor>(actor: A) -> ActorStore<A> where A: Send + Sync + 'static, A::Action: Clone + Send + Sync { let state: EmptyState<A::Action> = EmptyState::new(); let mut store = Store::new(state); let middleware = ActorMiddleware { actor: actor }; store.add_middlewar...
{ let action_ = action.clone(); self.actor.receive(action_); next(action); }
identifier_body
actor.rs
use store::Store; use middleware::Middleware; use empty_state::EmptyState; pub type ActorState<A> where A: Actor = EmptyState<A::Action>; pub type ActorStore<A> where A: Actor = Store<ActorState<A>>; pub trait Actor { type Action; fn receive(&mut self, action: Self::Action); } struct ActorMiddleware<A> { ...
(&mut self, _store: &mut Store<EmptyState<A::Action>>, next: &mut FnMut(A::Action), action: A::Action) { let action_ = action.clone(); self.actor.receive(action_); next(action); } } pub fn spawn_actor<A: Actor>(actor: A) -> ActorStore<A> where A: Send + Sync + 'static, A::Action: Cl...
dispatch
identifier_name
index.ts
/** * libjass * * https://github.com/Arnavion/libjass * * Copyright 2013 Arnav Singh * * 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...
{ // This is a web worker. Set up a channel to talk back to the main thread. /* tslint:disable-next-line:no-unused-expression */ new WorkerChannelImpl(global); }
conditional_block
index.ts
/** * libjass * * https://github.com/Arnavion/libjass * * Copyright 2013 Arnav Singh * * Licensed under the Apache License, Version 2.0 (the "License");
* 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....
* 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 *
random_line_split
index.ts
/** * libjass * * https://github.com/Arnavion/libjass * * Copyright 2013 Arnav Singh * * 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...
(scriptPath?: string): WorkerChannel { if (scriptPath === undefined) { if (_scriptNode === null) { throw new Error("Could not auto-detect path of libjass.js, and explicit path was not passed in."); } scriptPath = _scriptNode.src; } return new WorkerChannelImpl(new Worker(scriptPath)); } if (global.Worker...
createWorker
identifier_name
index.ts
/** * libjass * * https://github.com/Arnavion/libjass * * Copyright 2013 Arnav Singh * * 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...
if (global.WorkerGlobalScope !== undefined && global instanceof global.WorkerGlobalScope) { // This is a web worker. Set up a channel to talk back to the main thread. /* tslint:disable-next-line:no-unused-expression */ new WorkerChannelImpl(global); }
{ if (scriptPath === undefined) { if (_scriptNode === null) { throw new Error("Could not auto-detect path of libjass.js, and explicit path was not passed in."); } scriptPath = _scriptNode.src; } return new WorkerChannelImpl(new Worker(scriptPath)); }
identifier_body
quickstart.js
// // 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 // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distribu...
const cwd = path.join(__dirname, '..'); const project = process.env.GCLOUD_PROJECT; describe('Quickstart', () => { it('should run quickstart', async () => { const output = execSync(`node ./quickstart.js ${project} us-west1-b`, { cwd, }); assert.match(output, /instance: projects/); }); });
const cp = require('child_process'); const {describe, it} = require('mocha'); const execSync = cmd => cp.execSync(cmd, {encoding: 'utf-8'});
random_line_split
ship_module_ancillary_remote_shield_booster.py
# ============================================================================== # Copyright (C) 2011 Diego Duclos # Copyright (C) 2011-2018 Anton Vorobyov # # This file is part of Eos. # # Eos is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as publi...
EffectFactory.register_class_by_id( ShipModuleAncillaryRemoteShieldBooster, EffectId.ship_module_ancillary_remote_shield_booster)
def get_cycles_until_reload(self, item): return get_cycles_until_reload_generic(item, default=math.inf) def get_rep_amount(self, item): return item.attrs.get(AttrId.shield_bonus, 0)
identifier_body
ship_module_ancillary_remote_shield_booster.py
# ============================================================================== # Copyright (C) 2011 Diego Duclos # Copyright (C) 2011-2018 Anton Vorobyov # # This file is part of Eos. # # Eos is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as publi...
from eos.eve_obj.effect.helper_func import get_cycles_until_reload_generic from .base import RemoteShieldRepairEffect class ShipModuleAncillaryRemoteShieldBooster(RemoteShieldRepairEffect): def get_cycles_until_reload(self, item): return get_cycles_until_reload_generic(item, default=math.inf) def ge...
from eos.const.eve import EffectId from eos.eve_obj.effect import EffectFactory
random_line_split
ship_module_ancillary_remote_shield_booster.py
# ============================================================================== # Copyright (C) 2011 Diego Duclos # Copyright (C) 2011-2018 Anton Vorobyov # # This file is part of Eos. # # Eos is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as publi...
(self, item): return item.attrs.get(AttrId.shield_bonus, 0) EffectFactory.register_class_by_id( ShipModuleAncillaryRemoteShieldBooster, EffectId.ship_module_ancillary_remote_shield_booster)
get_rep_amount
identifier_name
frameelementmethodtransport.d.ts
declare module goog { function require(name: 'goog.net.xpc.FrameElementMethodTransport'): typeof goog.net.xpc.FrameElementMethodTransport; } declare module goog.net.xpc { /** * Frame-element method transport. * * Firefox allows a document within an iframe to call methods on the * iframe-el...
* @constructor * @extends {goog.net.xpc.Transport} * @final */ class FrameElementMethodTransport extends goog.net.xpc.Transport { constructor(channel: goog.net.xpc.CrossPageChannel, opt_domHelper?: goog.dom.DomHelper); /** * The transport type. * @type ...
* * @param {goog.net.xpc.CrossPageChannel} channel The channel this transport * belongs to. * @param {goog.dom.DomHelper=} opt_domHelper The dom helper to use for finding * the correct window.
random_line_split
frameelementmethodtransport.d.ts
declare module goog { function require(name: 'goog.net.xpc.FrameElementMethodTransport'): typeof goog.net.xpc.FrameElementMethodTransport; } declare module goog.net.xpc { /** * Frame-element method transport. * * Firefox allows a document within an iframe to call methods on the * iframe-el...
extends goog.net.xpc.Transport { constructor(channel: goog.net.xpc.CrossPageChannel, opt_domHelper?: goog.dom.DomHelper); /** * The transport type. * @type {number} * @protected * @override */ transportType: number; /** ...
FrameElementMethodTransport
identifier_name
index.js
'use strict'; import v1 from './v1' import v2 from './v2' import v3 from './v3' import v4 from './v4' import ugc from './ugc' import bos from './bos' import eus from './eus' import admin from './admin' import payapi from './payapi' import statis from './statis'
export default app => { // app.get('/', (req, res, next) => { // res.redirect('/'); // }); app.use('/v1', v1); app.use('/v2', v2); app.use('/v3', v3); app.use('/v4', v4); app.use('/ugc', ugc); app.use('/bos', bos); app.use('/eus', eus); app.use('/admin', admin); app.use('/payapi', payapi); app.use('/membe...
import member from './member' import shopping from './shopping' import promotion from './promotion'
random_line_split
tls_input.rs
use super::*; use crate::flowgger::config::Config; use crate::flowgger::decoder::Decoder; use crate::flowgger::encoder::Encoder; #[cfg(feature = "capnp-recompile")] use crate::flowgger::splitter::CapnpSplitter; use crate::flowgger::splitter::{LineSplitter, NulSplitter, Splitter, SyslenSplitter}; use std::io::{stderr, B...
} } } #[cfg(feature = "capnp-recompile")] pub fn get_capnp_splitter<T>() -> Box<dyn Splitter<T>> where T: std::io::Read, { Box::new(CapnpSplitter) as Box<dyn Splitter<_>> } #[cfg(not(feature = "capnp-recompile"))] pub fn get_capnp_splitter() -> ! { panic!("Support for CapNProto is not compile...
{ let _ = client.set_read_timeout(self.timeout); let tx = tx.clone(); let (decoder, encoder) = (decoder.clone_boxed(), encoder.clone_boxed()); let tls_config = self.tls_config.clone(); thread::spawn(move || { handle_clie...
conditional_block
tls_input.rs
use super::*; use crate::flowgger::config::Config; use crate::flowgger::decoder::Decoder; use crate::flowgger::encoder::Encoder; #[cfg(feature = "capnp-recompile")] use crate::flowgger::splitter::CapnpSplitter; use crate::flowgger::splitter::{LineSplitter, NulSplitter, Splitter, SyslenSplitter}; use std::io::{stderr, B...
}
{ if let Ok(peer_addr) = client.peer_addr() { println!("Connection over TLS from [{}]", peer_addr); } let sslclient = match tls_config.acceptor.accept(client) { Err(_) => { let _ = writeln!(stderr(), "SSL handshake aborted by the client"); return; } Ok...
identifier_body
tls_input.rs
use super::*; use crate::flowgger::config::Config; use crate::flowgger::decoder::Decoder; use crate::flowgger::encoder::Encoder; #[cfg(feature = "capnp-recompile")] use crate::flowgger::splitter::CapnpSplitter; use crate::flowgger::splitter::{LineSplitter, NulSplitter, Splitter, SyslenSplitter}; use std::io::{stderr, B...
#[cfg(not(feature = "capnp-recompile"))] pub fn get_capnp_splitter() -> ! { panic!("Support for CapNProto is not compiled in") } fn handle_client( client: TcpStream, tx: SyncSender<Vec<u8>>, decoder: Box<dyn Decoder>, encoder: Box<dyn Encoder>, tls_config: TlsConfig, ) { if let Ok(peer_addr...
random_line_split
tls_input.rs
use super::*; use crate::flowgger::config::Config; use crate::flowgger::decoder::Decoder; use crate::flowgger::encoder::Encoder; #[cfg(feature = "capnp-recompile")] use crate::flowgger::splitter::CapnpSplitter; use crate::flowgger::splitter::{LineSplitter, NulSplitter, Splitter, SyslenSplitter}; use std::io::{stderr, B...
( client: TcpStream, tx: SyncSender<Vec<u8>>, decoder: Box<dyn Decoder>, encoder: Box<dyn Encoder>, tls_config: TlsConfig, ) { if let Ok(peer_addr) = client.peer_addr() { println!("Connection over TLS from [{}]", peer_addr); } let sslclient = match tls_config.acceptor.accept(clie...
handle_client
identifier_name
static-mut-not-pat.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
static mut STATIC_MUT_FOO: Foo = Foo { bar: Some(West), baz: NEW_FALSE }; fn mutable_statics() { match (Foo { bar: Some(North), baz: NewBool(true) }) { Foo { bar: None, baz: NewBool(true) } => (), STATIC_MUT_FOO => (), //~^ ERROR static variables cannot be referenced in a pattern Fo...
}
random_line_split
static-mut-not-pat.rs
// Copyright 2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(bool); enum Direction { North, East, South, West } const NEW_FALSE: NewBool = NewBool(false); struct Foo { bar: Option<Direction>, baz: NewBool } static mut STATIC_MUT_FOO: Foo = Foo { bar: Some(West), baz: NEW_FALSE }; fn mutable_statics() { match (Foo { bar: Some(North), baz: NewBool(tr...
NewBool
identifier_name
stats.py
# uncompyle6 version 2.9.10 # Python bytecode 2.7 (62211) # Decompiled from: Python 3.6.0b2 (default, Oct 11 2016, 05:27:10) # [GCC 6.2.0 20161005] # Embedded file name: stats.py """Statistics analyzer for HotShot.""" import profile import pstats import hotshot.log from hotshot.log import ENTER, EXIT def load(filenam...
: def __init__(self, filename, firstlineno, funcname): self.co_filename = filename self.co_firstlineno = firstlineno self.co_name = self.__name__ = funcname class FakeFrame: def __init__(self, code, back): self.f_back = back self.f_code = code def _brokentimer(): ...
FakeCode
identifier_name
stats.py
# uncompyle6 version 2.9.10 # Python bytecode 2.7 (62211) # Decompiled from: Python 3.6.0b2 (default, Oct 11 2016, 05:27:10) # [GCC 6.2.0 20161005] # Embedded file name: stats.py """Statistics analyzer for HotShot.""" import profile import pstats import hotshot.log from hotshot.log import ENTER, EXIT def load(filenam...
def _brokentimer(): raise RuntimeError, 'this timer should not be called'
self.f_back = back self.f_code = code
random_line_split
stats.py
# uncompyle6 version 2.9.10 # Python bytecode 2.7 (62211) # Decompiled from: Python 3.6.0b2 (default, Oct 11 2016, 05:27:10) # [GCC 6.2.0 20161005] # Embedded file name: stats.py """Statistics analyzer for HotShot.""" import profile import pstats import hotshot.log from hotshot.log import ENTER, EXIT def load(filenam...
if what == ENTER: frame = self.new_frame(filename, lineno, funcname) p.trace_dispatch_call(frame, taccum * 1e-06) taccum = 0 elif what == EXIT: frame = self.pop_frame() p.trace_dispatch_return(frame, taccum * 1e-06)...
taccum += tdelta
conditional_block
stats.py
# uncompyle6 version 2.9.10 # Python bytecode 2.7 (62211) # Decompiled from: Python 3.6.0b2 (default, Oct 11 2016, 05:27:10) # [GCC 6.2.0 20161005] # Embedded file name: stats.py """Statistics analyzer for HotShot.""" import profile import pstats import hotshot.log from hotshot.log import ENTER, EXIT def load(filenam...
class FakeCode: def __init__(self, filename, firstlineno, funcname): self.co_filename = filename self.co_firstlineno = firstlineno self.co_name = self.__name__ = funcname class FakeFrame: def __init__(self, code, back): self.f_back = back self.f_code = code def _...
pass
identifier_body
BackHomeButton.test.js
import React from 'react'; import { mount } from 'enzyme'; import { Link, HashRouter as Router } from 'react-router-dom'; import { Button } from 'react-bootstrap';
it('<BackHomeButton /> should render <Router/>', () => { const component = mount(<BackHomeButton />); expect(component.find(Router)).toHaveLength(1); }); it('<BackHomeButton /> should render <Link/> with correct props', () => { const component = mount(<BackHomeButton />); expect(component.find(Ro...
import BackHomeButton from '../BackHomeButton'; describe('<BackHomeButton/>', () => {
random_line_split
plot_raw_read_alignment.py
"""Plot information needed file""" ######################################################################## # File: plot_raw_read_alignment.py # executable: plot_raw_read_alignment.py # # Author: Andrew Bailey # History: Created 12/01/17 ######################################################################## from __...
def main(): """Main docstring""" start = timer() minknow_params = dict(window_lengths=(5, 10), thresholds=(2.0, 1.1), peak_height=1.2) speedy_params = dict(min_width=5, max_width=30, min_gain_per_sample=0.008, window_width=800) dna_reads = "/Users/andrewbailey/CLionProjects/nanopore-RNN/test_fil...
start_time = fast5_handle.raw_attributes["start_time"] sampling_freq = fast5_handle.sample_rate plot_raw_reads(signal, events, resegment=None, dna=True, sampling_freq=sampling_freq, start_time=start_time, window_size=window_size)
conditional_block
plot_raw_read_alignment.py
"""Plot information needed file""" ######################################################################## # File: plot_raw_read_alignment.py # executable: plot_raw_read_alignment.py # # Author: Andrew Bailey # History: Created 12/01/17 ######################################################################## from __...
panel1.axvline(label_data.start[i]) panel1.axvline(label_data.start[i] + label_data.length[i]) plt.show() # plt.savefig(outpath) def raw_scatter_plot_with_events(signal_data, label_data, outpath, interval, events): """plot accuracy distribution of reads""" # define figure si...
"""plot accuracy distribution of reads""" # define figure size size = (interval[1] - interval[0]) / 100 plt.figure(figsize=(size, 4)) panel1 = plt.axes([0.01, 0.1, .95, .9]) # longest = max(data[0]) + data[1]) # panel1.set_xlim(0, 1000) mean = np.mean(signal_data) stdv = np.std(signal_da...
identifier_body
plot_raw_read_alignment.py
"""Plot information needed file""" ######################################################################## # File: plot_raw_read_alignment.py # executable: plot_raw_read_alignment.py # # Author: Andrew Bailey # History: Created 12/01/17 ########################################################################
import matplotlib.pyplot as plt import matplotlib.patches as mplpatches import numpy as np import scipy.stats as stats import seaborn as sns from py3helpers.utils import list_dir from PyPore.parsers import SpeedyStatSplit from nanonet.eventdetection.filters import minknow_event_detect from nanotensor.fast5 import Fast5...
from __future__ import print_function import sys import os from timeit import default_timer as timer import pysam
random_line_split
plot_raw_read_alignment.py
"""Plot information needed file""" ######################################################################## # File: plot_raw_read_alignment.py # executable: plot_raw_read_alignment.py # # Author: Andrew Bailey # History: Created 12/01/17 ######################################################################## from __...
(): """Main docstring""" start = timer() minknow_params = dict(window_lengths=(5, 10), thresholds=(2.0, 1.1), peak_height=1.2) speedy_params = dict(min_width=5, max_width=30, min_gain_per_sample=0.008, window_width=800) dna_reads = "/Users/andrewbailey/CLionProjects/nanopore-RNN/test_files/minion-r...
main
identifier_name
page.rs
use std::convert; use std::fmt; use std::path::{Path, PathBuf}; use serde_json::{self, Value}; #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct Slug { slug: String, } impl Slug { pub fn new(slug: String) -> Self { Slug { slug: slug } } pub fn create_output_path(&self, prefix: &Path, pr...
} impl fmt::Display for Slug { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", &self.slug) } } pub struct Page { pub source_path: PathBuf, pub slug: Slug, pub body: String, pub theme_config: serde_json::map::Map<String, Value>, } impl Page { pub fn title(&s...
{ &self.slug }
identifier_body
page.rs
use std::convert; use std::fmt; use std::path::{Path, PathBuf}; use serde_json::{self, Value}; #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct Slug { slug: String, } impl Slug { pub fn new(slug: String) -> Self { Slug { slug: slug } } pub fn create_output_path(&self, prefix: &Path, pr...
else { 0 }; self.slug.matches('/').count() + modifier } pub fn path_to(&self, dest: &str, pretty_url: bool) -> String { let slug_prefix = "../".repeat(self.depth(pretty_url)); format!("{}{}", slug_prefix, dest) } } impl convert::AsRef<str> for Slug { fn as...
{ 1 }
conditional_block
page.rs
use std::convert; use std::fmt; use std::path::{Path, PathBuf}; use serde_json::{self, Value}; #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct Slug { slug: String, } impl Slug { pub fn new(slug: String) -> Self { Slug { slug: slug } } pub fn create_output_path(&self, prefix: &Path, pr...
(&self, dest: &str, pretty_url: bool) -> String { let slug_prefix = "../".repeat(self.depth(pretty_url)); format!("{}{}", slug_prefix, dest) } } impl convert::AsRef<str> for Slug { fn as_ref(&self) -> &str { &self.slug } } impl fmt::Display for Slug { fn fmt(&self, f: &mut fmt:...
path_to
identifier_name
page.rs
use std::convert; use std::fmt; use std::path::{Path, PathBuf}; use serde_json::{self, Value}; #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct Slug { slug: String, } impl Slug { pub fn new(slug: String) -> Self { Slug { slug: slug } } pub fn create_output_path(&self, prefix: &Path, pr...
&self.slug } } impl fmt::Display for Slug { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { write!(f, "{}", &self.slug) } } pub struct Page { pub source_path: PathBuf, pub slug: Slug, pub body: String, pub theme_config: serde_json::map::Map<String, Value>, } impl Pa...
impl convert::AsRef<str> for Slug { fn as_ref(&self) -> &str {
random_line_split
udpsrc_benchmark_sender.rs
// Copyright (C) 2018 Sebastian Dröge <sebastian@centricular.com> // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Library General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later ...
} }
thread::sleep(wait - elapsed); }
conditional_block
udpsrc_benchmark_sender.rs
// Copyright (C) 2018 Sebastian Dröge <sebastian@centricular.com> // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Library General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later ...
use std::net; use std::net::{IpAddr, Ipv4Addr, SocketAddr}; use std::{env, thread, time}; fn main() { let args = env::args().collect::<Vec<_>>(); assert_eq!(args.len(), 2); let n_streams: u16 = args[1].parse().unwrap(); let buffer = [0; 160]; let socket = net::UdpSocket::bind("0.0.0.0:0").unwrap(...
// You should have received a copy of the GNU Library General Public // License along with this library; if not, write to the // Free Software Foundation, Inc., 51 Franklin Street, Suite 500, // Boston, MA 02110-1335, USA.
random_line_split
udpsrc_benchmark_sender.rs
// Copyright (C) 2018 Sebastian Dröge <sebastian@centricular.com> // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Library General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later ...
) { let args = env::args().collect::<Vec<_>>(); assert_eq!(args.len(), 2); let n_streams: u16 = args[1].parse().unwrap(); let buffer = [0; 160]; let socket = net::UdpSocket::bind("0.0.0.0:0").unwrap(); let ipaddr = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)); let destinations = (40000..(40000 ...
ain(
identifier_name
udpsrc_benchmark_sender.rs
// Copyright (C) 2018 Sebastian Dröge <sebastian@centricular.com> // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Library General Public // License as published by the Free Software Foundation; either // version 2 of the License, or (at your option) any later ...
for dest in &destinations { socket.send_to(&buffer, dest).unwrap(); } let elapsed = now.elapsed(); if elapsed < wait { thread::sleep(wait - elapsed); } } }
let args = env::args().collect::<Vec<_>>(); assert_eq!(args.len(), 2); let n_streams: u16 = args[1].parse().unwrap(); let buffer = [0; 160]; let socket = net::UdpSocket::bind("0.0.0.0:0").unwrap(); let ipaddr = IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)); let destinations = (40000..(40000 + n...
identifier_body
project3.py
# -*- coding: utf-8 -*- """ ------------------------------------- N A C S P Y T H O N S C R I P T ------------------------------------- NACS version: 2.0.2745 - pre3 NACS architecture: CENTOS 5.11 (X86_64) File generated at Tue Jan 20 16:55:05 2015 On host 'lse86' by 'cae42' """ from __future__ import division ...
# ================= simulation = NacsSimulation() simulation.setGrid(u'project3.nmf', 'plane') simulation.addOutput(Output.Nacs()) text = Output.Text() simulation.addOutput(text) simulation.addOutput(Output.GiD()) # ===================== # MATERIAL DEFINITION # ===================== copper = Material('Copper') copp...
# ================= # NACS SIMULATION
random_line_split
ssd1306.py
VERT_AND_LEFT_HORIZ_SCROLL = 0x2A DEACTIVATE_SCROLL = 0x2E ACTIVATE_SCROLL = 0x2F SET_START_LINE = 0x40 SET_CONTRAST = 0x81 CHARGE_PUMP = 0x8D SEG_REMAP = 0xA0 SET_VERT_SCROLL_AREA = 0xA3 DISPLAY_ALL_ON_RESUME = 0xA4 DISPLAY_ALL_O...
x += size x += space def clear_block(self, x0, y0, dx, dy): self.bitmap.clear_block(x0, y0, dx, dy) def draw
mask >>= 1
random_line_split
ssd1306.py
DISPLAY_ALL_ON = 0xA5 NORMAL_DISPLAY = 0xA6 INVERT_DISPLAY = 0xA7 DISPLAY_OFF = 0xAE DISPLAY_ON = 0xAF COM_SCAN_INC = 0xC0 COM_SCAN_DEC = 0xC8 SET_DISPLAY_OFFSET = 0xD3 SET_COM_PINS = 0xDA SET_VCOM_DETECT ...
EXTERNAL_VCC = 0x1 SWITCH_CAP_VCC = 0x2 SET_LOW_COLUMN = 0x00 SET_HIGH_COLUMN = 0x10 SET_MEMORY_MODE = 0x20 SET_COL_ADDRESS = 0x21 SET_PAGE_ADDRESS = 0x22 RIGHT_HORIZ_SCROLL = 0x26 LEFT_HORIZ_SCROLL = 0x27 VERT_AND_RIGHT_HORIZ_SCROLL = 0x29 ...
identifier_body
ssd1306.py
0, start_col, count, self.col_offset) # Transfers data from the passed bitmap (instance of ssd1306.Bitmap) # starting at row <row> col <col>. # Both row and bitmap.rows will be divided by 8 to get page addresses, # so both must divide evenly by 8 to avoid surprises. # # bitmap: instance of...
if i > 0 and delay > 0: time.sleep(delay) self.scroll(sign)
conditional_block
ssd1306.py
VERT_AND_LEFT_HORIZ_SCROLL = 0x2A DEACTIVATE_SCROLL = 0x2E ACTIVATE_SCROLL = 0x2F SET_START_LINE = 0x40 SET_CONTRAST = 0x81 CHARGE_PUMP = 0x8D SEG_REMAP = 0xA0 SET_VERT_SCROLL_AREA = 0xA3 DISPLAY_ALL_ON_RESUME = 0xA4 DISPLAY_ALL_ON...
(self, bytes): self.gpio.output(self.dc_pin, self.gpio.HIGH) # chunk data to work around 255 byte limitation in adafruit implementation of writebytes # revisit - change to 1024 when Adafruit_BBIO is fixed. max_xfer = 255 if gaugette.platform.isBeagleBoneBlack else 1024 start = 0...
data
identifier_name
mod.rs
// Gibbs MySQL Spyglass // Copyright (C) 2016 AgilData // // This file is part of Gibbs MySQL Spyglass. // // Gibbs MySQL Spyglass is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the Lice...
() { debug!("deleting capture file {}", CAP_FILE); let _ = fs::remove_file(CAP_FILE); } pub fn set_cap(on: bool) { CAP_ON.store(on, Ordering::SeqCst) } pub fn chk_cap() -> bool { CAP_ON.load(Ordering::SeqCst) } fn write_cap(cap: &mut File, msg: &str) { let bytes = match cap.write(msg.as_bytes()) { ...
clear_cap
identifier_name
mod.rs
// Gibbs MySQL Spyglass // Copyright (C) 2016 AgilData // // This file is part of Gibbs MySQL Spyglass. // // Gibbs MySQL Spyglass is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the Lice...
pub fn cap_size() -> usize { FILE_SIZE.load(Ordering::SeqCst) } fn inc_qry() { QRY_CNT.fetch_add(1, Ordering::SeqCst); } pub fn qry_cnt() -> usize { QRY_CNT.load(Ordering::SeqCst) }
{ let bytes = match cap.write(msg.as_bytes()) { Ok(cnt) => cnt, Err(e) => panic!(e), }; if FILE_SIZE.fetch_add(bytes, Ordering::SeqCst) + bytes > MAX_CAPTURE { set_cap(false); } }
identifier_body
mod.rs
// Gibbs MySQL Spyglass // Copyright (C) 2016 AgilData // // This file is part of Gibbs MySQL Spyglass. //
// Gibbs MySQL Spyglass is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public Li...
// Gibbs MySQL Spyglass is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. //
random_line_split
31-2.rs
/* Problem 31: Coin sums * * In England the currency is made up of pound, £, and pence, p, and there are eight coins in * general circulation: * * 1p, 2p, 5p, 10p, 20p, 50p, £1 (100p) and £2 (200p). * * It is possible to make £2 in the following way: * * 1×£1 + 1×50p + 2×20p + 1×5p + 1×2p + 3×1p * * ...
ntln!("{}", ways_to_make(200, DENOMINATIONS)); } // Dynamic programming solution, adapted from the overview PDF fn ways_to_make(value: usize, denominations: &[usize]) -> usize { let mut ways: Vec<usize> = repeat(0).take(value + 1).collect(); ways[0] = 1; for &denom in denominations.iter() { for cu...
pri
identifier_name
31-2.rs
/* Problem 31: Coin sums * * In England the currency is made up of pound, £, and pence, p, and there are eight coins in * general circulation: * * 1p, 2p, 5p, 10p, 20p, 50p, £1 (100p) and £2 (200p). * * It is possible to make £2 in the following way: * * 1×£1 + 1×50p + 2×20p + 1×5p + 1×2p + 3×1p * * ...
programming solution, adapted from the overview PDF fn ways_to_make(value: usize, denominations: &[usize]) -> usize { let mut ways: Vec<usize> = repeat(0).take(value + 1).collect(); ways[0] = 1; for &denom in denominations.iter() { for current in denom..value + 1 { ways[current] += way...
n!("{}", ways_to_make(200, DENOMINATIONS)); } // Dynamic
identifier_body
31-2.rs
/* Problem 31: Coin sums * * In England the currency is made up of pound, £, and pence, p, and there are eight coins in * general circulation: * * 1p, 2p, 5p, 10p, 20p, 50p, £1 (100p) and £2 (200p). * * It is possible to make £2 in the following way:
use std::iter::repeat; const DENOMINATIONS: &'static [usize] = &[200, 100, 50, 20, 10, 5, 2, 1]; fn main() { println!("{}", ways_to_make(200, DENOMINATIONS)); } // Dynamic programming solution, adapted from the overview PDF fn ways_to_make(value: usize, denominations: &[usize]) -> usize { let mut ways: Vec<u...
* * 1×£1 + 1×50p + 2×20p + 1×5p + 1×2p + 3×1p * * How many different ways can £2 be made using any number of coins? */
random_line_split
exception.py
from __future__ import unicode_literals class MorfessorException(Exception): """Base class for exceptions in this module.""" pass
class InvalidCategoryError(MorfessorException): """Attempt to load data using a different categorization scheme.""" def __init__(self, category): super(InvalidCategoryError, self).__init__( self, 'This model does not recognize the category {}'.format( category)) class Inv...
class ArgumentException(Exception): """Exception in command line argument parsing.""" pass
random_line_split
exception.py
from __future__ import unicode_literals class MorfessorException(Exception): """Base class for exceptions in this module.""" pass class ArgumentException(Exception): """Exception in command line argument parsing.""" pass class InvalidCategoryError(MorfessorException): """Attempt to load data u...
def __init__(self, reason): super(UnsupportedConfigurationError, self).__init__( self, ('This operation is not supported in this program ' + 'configuration. Reason: {}.').format(reason))
identifier_body
exception.py
from __future__ import unicode_literals class MorfessorException(Exception): """Base class for exceptions in this module.""" pass class
(Exception): """Exception in command line argument parsing.""" pass class InvalidCategoryError(MorfessorException): """Attempt to load data using a different categorization scheme.""" def __init__(self, category): super(InvalidCategoryError, self).__init__( self, 'This model does n...
ArgumentException
identifier_name
router.js
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */ import React from 'react'; import Router from 'react-routing/src/Router'; import http from './core/http'; import App from './components/App'; import ContentPage from './components/ContentPage'; import ContactPage from './components/ContactPage'; ...
}); on('/contact', async () => <ContactPage />); on('/nsn', async () => <NsnPage />); on('/login', async () => <LoginPage />); on('/register', async () => <RegisterPage />); on('*', async (state) => { const content = await http.get(`/api/content?path=${state.path}`); return content && <ContentP...
const component = await next(); return component && <App context={state.context}>{component}</App>;
random_line_split
_9_3_normal_visualization.rs
#![allow(non_upper_case_globals)] #![allow(non_snake_case)] use std::ffi::CStr; extern crate glfw; use self::glfw::Context; extern crate gl; use cgmath::{Matrix4, Deg, vec3, Point3, perspective}; use common::{process_events, processInput}; use shader::Shader; use camera::Camera; use model::Model; // settings cons...
glfw.window_hint(glfw::WindowHint::OpenGlForwardCompat(true)); // glfw window creation // -------------------- let (mut window, events) = glfw.create_window(SCR_WIDTH, SCR_HEIGHT, "LearnOpenGL", glfw::WindowMode::Windowed) .expect("Failed to create GLFW window"); window.make_current(); ...
{ let mut camera = Camera { Position: Point3::new(0.0, 0.0, 3.0), ..Camera::default() }; let mut firstMouse = true; let mut lastX: f32 = SCR_WIDTH as f32 / 2.0; let mut lastY: f32 = SCR_HEIGHT as f32 / 2.0; // timing let mut deltaTime: f32; // time between current frame and...
identifier_body
_9_3_normal_visualization.rs
#![allow(non_upper_case_globals)] #![allow(non_snake_case)] use std::ffi::CStr; extern crate glfw; use self::glfw::Context; extern crate gl; use cgmath::{Matrix4, Deg, vec3, Point3, perspective}; use common::{process_events, processInput}; use shader::Shader; use camera::Camera; use model::Model; // settings cons...
gl::Enable(gl::DEPTH_TEST); // build and compile shaders // ------------------------- let shader = Shader::new( "src/_4_advanced_opengl/shaders/9.3.default.vs", "src/_4_advanced_opengl/shaders/9.3.default.fs", ); let normalShader = Shader::with_ge...
let (shader, normalShader, nanoSuit) = unsafe { // configure global opengl state // -----------------------------
random_line_split
_9_3_normal_visualization.rs
#![allow(non_upper_case_globals)] #![allow(non_snake_case)] use std::ffi::CStr; extern crate glfw; use self::glfw::Context; extern crate gl; use cgmath::{Matrix4, Deg, vec3, Point3, perspective}; use common::{process_events, processInput}; use shader::Shader; use camera::Camera; use model::Model; // settings cons...
() { let mut camera = Camera { Position: Point3::new(0.0, 0.0, 3.0), ..Camera::default() }; let mut firstMouse = true; let mut lastX: f32 = SCR_WIDTH as f32 / 2.0; let mut lastY: f32 = SCR_HEIGHT as f32 / 2.0; // timing let mut deltaTime: f32; // time between current frame ...
main_4_9_3
identifier_name
basic_chatbot.rs
extern crate discord; use discord::Discord; use discord::model::Event; use std::env; fn main()
Ok(_) => {} Err(discord::Error::Closed(code, body)) => { println!("Gateway closed on us with code {:?}: {}", code, body); break } Err(err) => println!("Receive error: {:?}", err) } } }
{ // Log in to Discord using a bot token from the environment let discord = Discord::from_bot_token( &env::var("DISCORD_TOKEN").expect("Expected token"), ).expect("login failed"); // Establish and use a websocket connection let (mut connection, _) = discord.connect().expect("connect failed"); println!("Ready."...
identifier_body
basic_chatbot.rs
extern crate discord; use discord::Discord; use discord::model::Event; use std::env; fn main() { // Log in to Discord using a bot token from the environment let discord = Discord::from_bot_token( &env::var("DISCORD_TOKEN").expect("Expected token"), ).expect("login failed"); // Establish and use a websocket con...
Err(discord::Error::Closed(code, body)) => { println!("Gateway closed on us with code {:?}: {}", code, body); break } Err(err) => println!("Receive error: {:?}", err) } } }
println!("Quitting."); break } } Ok(_) => {}
random_line_split
basic_chatbot.rs
extern crate discord; use discord::Discord; use discord::model::Event; use std::env; fn
() { // Log in to Discord using a bot token from the environment let discord = Discord::from_bot_token( &env::var("DISCORD_TOKEN").expect("Expected token"), ).expect("login failed"); // Establish and use a websocket connection let (mut connection, _) = discord.connect().expect("connect failed"); println!("Read...
main
identifier_name
Popup.js
ignoreWidth = options.ignoreWidth; if(typeof type == "undefined") type = ""; Popup.create(type, name, title, options, ignoreWidth); Popup.update(transport, type, name, options); }, sidePanel: function(targetPlugin, targetPluginID, targetPluginMethod, targetPluginMethodParameters, popupName){ if(typ...
if(typeof options.top != "undefined") top = options.top; if(options.left) left = options.left; if(options.right) right = options.right; if(options.absolute) absolute = options.absolute; if(options.persistent) persistent = options.persistent; if(options.blackout) ...
{ if(options.position == "left"){ left = $j('#contentLeft').offset().left + $j('#contentLeft').width(); top = $j('#contentLeft').offset().top + parseInt($j('#contentLeft').css('padding-top')); if(contentManager.layout == "desktop") top = $j('#wrapper').offset().top + parseInt($j('#contentLeft')...
conditional_block
Popup.js
Popup.update(transport, type, name, options); }, sidePanel: function(targetPlugin, targetPluginID, targetPluginMethod, targetPluginMethodParameters, popupName){ if(typeof popupName == "undefined") popupName = "edit"; targetPluginContainer = popupName+"Details"+targetPlugin; if($j('#'+targetPluginCont...
var element = "<div id=\""+type+'Details'+ID+"\" style=\""+(absolute ? "position:absolute;" : "")+'display:none;top:'+top+'px;'+(right != null ? 'right:'+right : 'left:'+left)+'px;width:'+width+(width.toString().indexOf("%") > -1 ? "" : "px")+';z-index:'+Popup.zIndex+"\" class=\"popup\">\n\ <div class=\"backgrou...
random_line_split
runtests.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # https://github.com/swistakm/django-rest-framework/blob/master/rest_framework/runtests/runtests.py import os import sys # fix sys path so we don't need to setup PYTHONPATH sys.path.append(os.path.join(os.path.dirname(__file__), "../..")) os.environ['DJANGO_SETTINGS_MODUL...
if __name__ == '__main__': main()
sys.exit(failures)
random_line_split
runtests.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # https://github.com/swistakm/django-rest-framework/blob/master/rest_framework/runtests/runtests.py import os import sys # fix sys path so we don't need to setup PYTHONPATH sys.path.append(os.path.join(os.path.dirname(__file__), "../..")) os.environ['DJANGO_SETTINGS_MODUL...
else: print(usage()) sys.exit(1) patch_for_test_db_setup() failures = test_runner.run_tests(['tests' + test_case]) sys.exit(failures) if __name__ == '__main__': main()
test_case = ''
conditional_block
runtests.py
#!/usr/bin/env python # -*- coding: utf-8 -*- # https://github.com/swistakm/django-rest-framework/blob/master/rest_framework/runtests/runtests.py import os import sys # fix sys path so we don't need to setup PYTHONPATH sys.path.append(os.path.join(os.path.dirname(__file__), "../..")) os.environ['DJANGO_SETTINGS_MODUL...
(): return """ Usage: python runtests.py [UnitTestClass].[method] You can pass the Class name of the `UnitTestClass` you want to test. Append a method name if you only want to test a specific method of that class. """ def main(): TestRunner = get_runner(settings) test_runner = TestRunner...
usage
identifier_name