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
twinkle_twinkle.rs
extern crate portmidi as pm; extern crate docopt; extern crate rustc_serialize; use std::thread; use std::time::Duration; use pm::MidiMessage; static CHANNEL: u8 = 0; static MELODY: [(u8, u32); 42] = [ (60, 1), (60, 1), (67, 1), (67, 1), (69, 1), (69, 1), (67, 2), (65, 1), (65, 1...
(mut out_port: pm::OutputPort, verbose: bool) -> pm::Result<()> { for &(note, dur) in MELODY.iter().cycle() { let note_on = MidiMessage { status: 0x90 + CHANNEL, data1: note, data2: 100, data3: 0, }; if verbose { println!("{}", note...
play
identifier_name
twinkle_twinkle.rs
extern crate portmidi as pm; extern crate docopt; extern crate rustc_serialize; use std::thread; use std::time::Duration; use pm::MidiMessage; static CHANNEL: u8 = 0; static MELODY: [(u8, u32); 42] = [ (60, 1), (60, 1), (67, 1), (67, 1), (69, 1), (69, 1), (67, 2), (65, 1), (65, 1...
}; if verbose { println!("{}", note_off); } out_port.write_message(note_off)?; // short pause thread::sleep(Duration::from_millis(100)); } Ok(()) }
{ for &(note, dur) in MELODY.iter().cycle() { let note_on = MidiMessage { status: 0x90 + CHANNEL, data1: note, data2: 100, data3: 0, }; if verbose { println!("{}", note_on) } out_port.write_message(note_on)?; ...
identifier_body
twinkle_twinkle.rs
extern crate portmidi as pm; extern crate docopt; extern crate rustc_serialize; use std::thread; use std::time::Duration; use pm::MidiMessage; static CHANNEL: u8 = 0; static MELODY: [(u8, u32); 42] = [ (60, 1), (60, 1), (67, 1), (67, 1), (69, 1), (69, 1), (67, 2), (65, 1), (65, 1...
Options: -h --help Show this screen. -v --verbose Print what's being done Omitting <device-id> will list the available devices. "#; #[derive(Debug, RustcDecodable)] struct Args { arg_device_id: i32, flag_verbose: bool, } fn print_devices(pm: &pm::PortMidi) { for dev in pm.devices().unwra...
random_line_split
twinkle_twinkle.rs
extern crate portmidi as pm; extern crate docopt; extern crate rustc_serialize; use std::thread; use std::time::Duration; use pm::MidiMessage; static CHANNEL: u8 = 0; static MELODY: [(u8, u32); 42] = [ (60, 1), (60, 1), (67, 1), (67, 1), (69, 1), (69, 1), (67, 2), (65, 1), (65, 1...
out_port.write_message(note_on)?; // note hold time before sending note off thread::sleep(Duration::from_millis(dur as u64 * 400)); let note_off = MidiMessage { status: 0x80 + CHANNEL, data1: note, data2: 100, data3: 0, }; ...
{ println!("{}", note_on) }
conditional_block
NLopt.py
''' Nonlinear optimization by use of Affine DualAveraging @author: Maximilian Balandat @date: May 13, 2015 ''' import numpy as np from .Domains import nBox class
(): """ Basic class describing a Nonlinear Optimization problem. """ def __init__(self, domain, objective): """ Constructor for the basic problem class. Here objective is a callable that provides val and grad methods for computing value and gradient, respectively. """ if not isi...
NLoptProblem
identifier_name
NLopt.py
''' Nonlinear optimization by use of Affine DualAveraging
import numpy as np from .Domains import nBox class NLoptProblem(): """ Basic class describing a Nonlinear Optimization problem. """ def __init__(self, domain, objective): """ Constructor for the basic problem class. Here objective is a callable that provides val and grad methods for c...
@author: Maximilian Balandat @date: May 13, 2015 '''
random_line_split
NLopt.py
''' Nonlinear optimization by use of Affine DualAveraging @author: Maximilian Balandat @date: May 13, 2015 ''' import numpy as np from .Domains import nBox class NLoptProblem(): """ Basic class describing a Nonlinear Optimization problem. """ def __init__(self, domain, objective): """ Construct...
self.domain, self.objective = domain, objective def run_minimization(self, etas, N, **kwargs): """ Runs the minimization of the objective function based on interpreting the value/gradient at the current iterate as an affine loss function and applying dual averaging...
raise Exception('For now only nBoxes are supported!')
conditional_block
NLopt.py
''' Nonlinear optimization by use of Affine DualAveraging @author: Maximilian Balandat @date: May 13, 2015 ''' import numpy as np from .Domains import nBox class NLoptProblem():
t += 1 return actions def quicksample(bounds, A, eta): """ Function returning actions sampled from the solution of the Dual Averaging update on an Box with Affine losses, Exponential Potential. """ C1, C2 = np.exp(-eta*A*bounds[:,0]), np.exp(-eta*A*bou...
""" Basic class describing a Nonlinear Optimization problem. """ def __init__(self, domain, objective): """ Constructor for the basic problem class. Here objective is a callable that provides val and grad methods for computing value and gradient, respectively. """ if not isinstance(...
identifier_body
indicator-sectors.component.ts
import {Component, Input, OnChanges, SimpleChanges} from '@angular/core'; import {Utils} from '../../../model/utils'; import {IChartBar} from '../../../thirdparty/ngx-charts-universal/chart.interface'; import {ISeriesProvider, IStatsPcCpvs} from '../../../app.interfaces'; import {Router} from '@angular/router'; import ...
return {id: code.id, name: code.name, value: code.percent}; }).sort((a, b) => { if (a.value < b.value) { return -1; } if (a.value > b.value) { return 1; } return 0; }); let othergroup = null; let othergroupcount = 0; while (this.cpvs_codes_average.data.length - 8 > 2) { ...
}); this.cpvs_codes_average.data = codes.map((code) => {
random_line_split
indicator-sectors.component.ts
import {Component, Input, OnChanges, SimpleChanges} from '@angular/core'; import {Utils} from '../../../model/utils'; import {IChartBar} from '../../../thirdparty/ngx-charts-universal/chart.interface'; import {ISeriesProvider, IStatsPcCpvs} from '../../../app.interfaces'; import {Router} from '@angular/router'; import ...
if (othergroup) { this.cpvs_codes_average.data.unshift(othergroup); } this.cpvs_codes_absolute.data = codes.map((code) => { return {id: code.id, name: code.name, value: code.value}; }).sort((a, b) => { if (a.value < b.value) { return -1; } if (a.value > b.value) { return 1; ...
{ if (!othergroup) { othergroup = {name: '', value: 0}; } let item = this.cpvs_codes_average.data.shift(); othergroup.value = item.value; othergroupcount++; othergroup.name = this.i18n.getFormat('[{{count}} other sectors with less than {{value}}]', [{key: 'count', value: othergroupcount}, {...
conditional_block
indicator-sectors.component.ts
import {Component, Input, OnChanges, SimpleChanges} from '@angular/core'; import {Utils} from '../../../model/utils'; import {IChartBar} from '../../../thirdparty/ngx-charts-universal/chart.interface'; import {ISeriesProvider, IStatsPcCpvs} from '../../../app.interfaces'; import {Router} from '@angular/router'; import ...
(changes: SimpleChanges): void { this.cpvs_codes_average.data = null; this.cpvs_codes_absolute.data = null; if (this.data) { let codes = Object.keys(this.data).map((key) => { return {id: key, name: this.data[key].name, value: this.data[key].value, percent: this.data[key].percent}; }); this.cpvs_codes...
ngOnChanges
identifier_name
reducers.js
'use strict'; const constants = require('./constants.js'); const deviceList = {}; function deviceHandlers(type, data) { switch (type) { case constants.DEVICE_ADDED: deviceList[data.id] = data; break; case constants.DEVICE_UPDATED: if (deviceList[data.id]) { ...
() { return deviceList; } module.exports = { deviceHandlers, watcherHandlers, getDevices, };
getDevices
identifier_name
reducers.js
'use strict'; const constants = require('./constants.js'); const deviceList = {}; function deviceHandlers(type, data) { switch (type) { case constants.DEVICE_ADDED: deviceList[data.id] = data; break; case constants.DEVICE_UPDATED: if (deviceList[data.id])
break; case constants.DEVICE_REMOVED: if (deviceList[data.id]) { delete deviceList[data.id]; } break; default: return null; } return deviceList; } function watcherHandlers(type, data) { const response = { w...
{ deviceList[data.id].update(data); }
conditional_block
reducers.js
'use strict'; const constants = require('./constants.js'); const deviceList = {}; function deviceHandlers(type, data) { switch (type) { case constants.DEVICE_ADDED: deviceList[data.id] = data; break; case constants.DEVICE_UPDATED: if (deviceList[data.id]) { ...
return null; } return response; } function getDevices() { return deviceList; } module.exports = { deviceHandlers, watcherHandlers, getDevices, };
{ const response = { watcher: data.name, error: false, }; switch (type) { case constants.WATCHER_DONE: case constants.WATCHER_WATCH: response.running = true; break; case constants.WATCHER_STOPPED: case constants.WATCHER_DONE: ...
identifier_body
reducers.js
'use strict'; const constants = require('./constants.js'); const deviceList = {}; function deviceHandlers(type, data) { switch (type) { case constants.DEVICE_ADDED: deviceList[data.id] = data; break; case constants.DEVICE_UPDATED: if (deviceList[data.id]) { ...
return null; } return response; } function getDevices() { return deviceList; } module.exports = { deviceHandlers, watcherHandlers, getDevices, };
response.error = data.error; break; default:
random_line_split
aaaa.rs
/* * Copyright (C) 2015 Benjamin Fry <benjaminfry@me.com> * * 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 *
* See the License for the specific language governing permissions and * limitations under the License. */ //! Parser for AAAA text form use std::net::Ipv6Addr; use std::str::FromStr; use crate::error::*; /// Parse the RData from a set of Tokens pub fn parse<'i, I: Iterator<Item = &'i str>>(mut tokens: I) -> Pars...
* 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.
random_line_split
aaaa.rs
/* * Copyright (C) 2015 Benjamin Fry <benjaminfry@me.com> * * 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 ap...
{ let address: Ipv6Addr = tokens .next() .ok_or_else(|| ParseError::from(ParseErrorKind::MissingToken("ipv6 address".to_string()))) .and_then(|s| Ipv6Addr::from_str(s).map_err(Into::into))?; Ok(address) }
identifier_body
aaaa.rs
/* * Copyright (C) 2015 Benjamin Fry <benjaminfry@me.com> * * 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 ap...
<'i, I: Iterator<Item = &'i str>>(mut tokens: I) -> ParseResult<Ipv6Addr> { let address: Ipv6Addr = tokens .next() .ok_or_else(|| ParseError::from(ParseErrorKind::MissingToken("ipv6 address".to_string()))) .and_then(|s| Ipv6Addr::from_str(s).map_err(Into::into))?; Ok(address) }
parse
identifier_name
cache.py
# Copyright (c) 2015 Sachi King # # 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...
def headersContentLength(self, uri): if uri not in self.objects.keys(): self.objects[uri] = CacheObject(uri) return [('Content-Length', str(self.objects[uri].object_size))] def getIterator(self, uri, headers, start=0, end=None): if uri not in self.objects.keys(): ...
if uri not in self.objects.keys(): self.objects[uri] = CacheObject(uri) return [('Content-Type', self.objects[uri].content_type)]
identifier_body
cache.py
# Copyright (c) 2015 Sachi King # # 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...
(self, object_path): # TODO: Directory transversal paths = [''] if object_path != '': paths.extend(object_path.strip('/').split('/')) path = CONF.chunk_storage_path for p in paths: path = ("%s/%s" % (path, p)) if not os.path.exists(path): ...
_ensurePathsExist
identifier_name
cache.py
# Copyright (c) 2015 Sachi King # # 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...
import math import os import re #from oslo_config import cfg from smashcache.cache import filler from smashcache.pages import errors opts = [ cfg.StrOpt('chunk_storage_path', default='/tmp/smashcache', help="Location to download chunked target data"), cfg.IntOpt('chunk_size', ...
import eventlet
random_line_split
cache.py
# Copyright (c) 2015 Sachi King # # 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...
def getOrWaitChunk(self, chunk_number): if not self.chunks[chunk_number] and not self.chunk_load[chunk_number]: self.chunk_load[chunk_number] = True self._fetchChunk(chunk_number) self.chunks[chunk_number] = True elif self.chunks[chunk_number]: pass ...
if remaining_bytes == 0: break self.getOrWaitChunk(current_chunk) with open(self._chunk_path(current_chunk), 'rb') as f: if current_chunk == initial_chunk: f.seek(start_offset) while True: if remaining_bytes ...
conditional_block
Alert.js
window.hideAlert = function () { $('#alertMessage').addClass("hidden"); $('#alertMessage').text(""); }; window.showAlert = function (msg) { $('#alertMessage').text(msg); $('#alertMessage').addClass("alert-danger"); $('#alertMessage').removeClass("hidden"); $('#alertMessage').fadeOut(100).fadeI...
case "InvalidPassword": showAlert(Resources["UnlockInvalidPassword"]); break; default: showAlert(data.idError); break; } }; window.handleError = function (xhr, exception) { hideLoader(); $('#workButton').removeClass("hidden"); var msg = '...
showAlert(Resources["WrongRegExpMessage"]); break; case "NotFound": showAlert(Resources["NoSearchResultsMessage"]); break;
random_line_split
Alert.js
window.hideAlert = function () { $('#alertMessage').addClass("hidden"); $('#alertMessage').text(""); }; window.showAlert = function (msg) { $('#alertMessage').text(msg); $('#alertMessage').addClass("alert-danger"); $('#alertMessage').removeClass("hidden"); $('#alertMessage').fadeOut(100).fadeI...
lse if (exception === 'timeout') { msg = 'Time out error.'; } else if (exception === 'abort') { msg = 'Ajax request aborted.'; } else { msg = 'Uncaught Error.\n' + xhr.responseText; } showAlert(msg); };
msg = 'Requested JSON parse failed.'; } e
conditional_block
_view.py
__future__ import unicode_literals from builtins import str from builtins import object import datalab.context from . import _query from . import _table # Query import is at end to avoid issues with circular dependencies. class View(object): """ An implementation of a BigQuery View. """ # Views in BigQuery a...
will be set to your project default. This can also be used to override your project-wide default billing tier on a per-query basis. Returns: A QueryJob for the materialization Raises: Exception (KeyError) if View could not be materialized. """ return self._materialization...
'legacy' : Use BigQuery's legacy SQL dialect. 'standard' : Use BigQuery's standard SQL (beta), which is compliant with the SQL 2011 standard. billing_tier: Limits the billing tier for this job. Queries that have resource usage beyond this tier will fail (without incurring a...
random_line_split
_view.py
or a 3-part tuple (projectid, datasetid, name). If a string, it must have the form '<project>:<dataset>.<view>' or '<dataset>.<view>'. context: an optional Context object providing project_id and credentials. If a specific project id or credentials are unspecified, the default ones ...
"""Materialize the View synchronously. Args: table_name: the result table name; if None, then a temporary table will be used. table_mode: one of 'create', 'overwrite' or 'append'. If 'create' (the default), the request will fail if the table exists. use_cache: whether to use past query ...
identifier_body
_view.py
future__ import unicode_literals from builtins import str from builtins import object import datalab.context from . import _query from . import _table # Query import is at end to avoid issues with circular dependencies. class View(object): """ An implementation of a BigQuery View. """ # Views in BigQuery are ...
raise Exception("View %s could not be created as it already exists" % str(self)) def sample(self, fields=None, count=5, sampling=None, use_cache=True, dialect=None, billing_tier=None): """Retrieves a sampling of data from the view. Args: fields: an optional list of field names to ret...
return self
conditional_block
_view.py
future__ import unicode_literals from builtins import str from builtins import object import datalab.context from . import _query from . import _table # Query import is at end to avoid issues with circular dependencies. class View(object): """ An implementation of a BigQuery View. """ # Views in BigQuery are ...
(self, fields=None, count=5, sampling=None, use_cache=True, dialect=None, billing_tier=None): """Retrieves a sampling of data from the view. Args: fields: an optional list of field names to retrieve. count: an optional count of rows to retrieve which is used if a specific sam...
sample
identifier_name
index.tsx
/** * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import {events, client, Item, jsKeyCodes} from 'camelot-unchained'; import * as React from 'react'; import * ...
}); } private removeItem = (id: string) => { this.setState((state, props) => { const items = {...this.state.items}; const stacks = {...this.state.stacks}; if (!items[id]) return; const stackId = items[id].name + items[id].gearSlot; delete items[id]; if (stacks[stackId]....
random_line_split
index.tsx
/** * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import {events, client, Item, jsKeyCodes} from 'camelot-unchained'; import * as React from 'react'; import * ...
(props: InventoryWindowProps) { super(props); this.state = { items: {}, stacks: {}, visible: false, }; } public render() { if (this.state.visible) { return ( <div className='inventory-container cu-window'> <div className='cu-window-header cu-window-bg-brown...
constructor
identifier_name
index.tsx
/** * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import {events, client, Item, jsKeyCodes} from 'camelot-unchained'; import * as React from 'react'; import * ...
} public componentWillMount() { client.SubscribeInventory(true); client.OnInventoryAdded(this.addItem); client.OnInventoryRemoved(this.removeItem); } public componentDidMount() { events.on('hudnav--navigate', (name: string) => { if (name === 'inventory') { if (this.state.visible...
{ if (this.state.visible) { return ( <div className='inventory-container cu-window'> <div className='cu-window-header cu-window-bg-brown'> <div className='cu-window-title'>Inventory</div> <div className='cu-window-actions'> <a onClick={this.hideWindow} c...
identifier_body
index.tsx
/** * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import {events, client, Item, jsKeyCodes} from 'camelot-unchained'; import * as React from 'react'; import * ...
} private dropItem = (stackId: string) => { const itemId = this.state.stacks[stackId][0]; const item = this.state.items[itemId]; if (item && item.gearSlot !== 'NONE') { client.DropItem(itemId); } } private simDblClick(onDblClick: any, ...args : any[]) { const now:number = Date.now()...
{ client.EquipItem(itemId); }
conditional_block
NumberControllerSlider.js
/** * dat-gui JavaScript Controller Library * http://code.google.com/p/dat-gui * * Copyright 2011 Data Arts Team, Google Creative Lab * * 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 ...
() { onChange(); if (_this.__onFinishChange) { _this.__onFinishChange.call(_this, _this.getValue()); } } //dom.bind(this.__background, 'mousedown', onMouseDown); // //dom.addClass(this.__background, 'sl...
onBlur
identifier_name
NumberControllerSlider.js
/** * dat-gui JavaScript Controller Library * http://code.google.com/p/dat-gui * * Copyright 2011 Data Arts Team, Google Creative Lab * * 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 ...
// //} // //function onMouseUp() { // dom.unbind(window, 'mousemove', onMouseDrag); // dom.unbind(window, 'mouseup', onMouseUp); // if (_this.__onFinishChange) { // _this.__onFinishChange.call(_this, _this.getValue());...
// map(e.clientX, offset.left, offset.left + width, _this.__min, _this.__max) // ); // // return false;
random_line_split
NumberControllerSlider.js
/** * dat-gui JavaScript Controller Library * http://code.google.com/p/dat-gui * * Copyright 2011 Data Arts Team, Google Creative Lab * * 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 ...
function onBlur() { onChange(); if (_this.__onFinishChange) { _this.__onFinishChange.call(_this, _this.getValue()); } } //dom.bind(this.__background, 'mousedown', onMouseDown); // //dom.ad...
{ var attempted = parseFloat(_this.__input.value); if (!common.isNaN(attempted)) _this.setValue(attempted); }
identifier_body
NumberControllerSlider.js
/** * dat-gui JavaScript Controller Library * http://code.google.com/p/dat-gui * * Copyright 2011 Data Arts Team, Google Creative Lab * * 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 ...
} //dom.bind(this.__background, 'mousedown', onMouseDown); // //dom.addClass(this.__background, 'slider'); //dom.addClass(this.__foreground, 'slider-fg'); // //function onMouseDown(e) { // // dom.bind(window,...
{ _this.__onFinishChange.call(_this, _this.getValue()); }
conditional_block
release.spec.ts
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { TestBed } from '@angular/core/testing'; import { AppProvider } from '../../providers/app/app'; import { Logger } from '../../providers/logger/logger'; import { ReleaseProvider } from './release'; describe('Relea...
{ public info; constructor() { this.info = { version: currentAppVersion }; } } beforeEach(() => { TestBed.configureTestingModule({ imports: [HttpClientTestingModule], providers: [ ReleaseProvider, Logger, { provide: AppProvider, useClass: AppProviderMock }...
AppProviderMock
identifier_name
release.spec.ts
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing'; import { TestBed } from '@angular/core/testing'; import { AppProvider } from '../../providers/app/app'; import { Logger } from '../../providers/logger/logger'; import { ReleaseProvider } from './release'; describe('Relea...
const bwsReq = httpMock.expectOne( 'https://bws.bitpay.com/bws/api/latest-version' ); expect(bwsReq.request.method).toEqual('GET'); bwsReq.flush({ version: latestAppVersion }); }); it('should check unsuccessfully the latest app version format', () => { const result = releaseProvider.newRe...
random_line_split
browse.js
function(head, req) { var ddoc = this; var Mustache = require("vendor/couchapp/lib/mustache"), path = require("vendor/couchapp/lib/path").init(req), Atom = require("vendor/couchapp/lib/atom"); var templates = ddoc.templates; var assetPath = path.asset(), browse...
provides("html", function() { var firstRow = getRow(), firstKey = firstRow.key, endKey = [], browseKey = req.query.startkey[0], prevKey = req.query.prevKey || [], viewName = req.path[req.path.length-1], limit = req.query.limit || 0; ...
{ var doc = row.doc; var summary = ''; if (doc.Summary && doc.Summary.length <= 350) { summary = doc.Summary; } else { summary = (doc.Summary.replace(/<(.|\n)*?>/g, '').substring(0,350) + '...'); } doc.Summary = summary; send(Mustache.to_ht...
identifier_body
browse.js
function(head, req) { var ddoc = this; var Mustache = require("vendor/couchapp/lib/mustache"), path = require("vendor/couchapp/lib/path").init(req), Atom = require("vendor/couchapp/lib/atom"); var templates = ddoc.templates;
startkey: [req.query.startkey[0]], endkey: [req.query.startkey[0], {}], include_docs:true, limit: 10, descending: true}); function sendRow(row) { var doc = row.doc; ...
var assetPath = path.asset(), browsePath = path.list("browse", req.path[req.path.length-1], {
random_line_split
browse.js
function(head, req) { var ddoc = this; var Mustache = require("vendor/couchapp/lib/mustache"), path = require("vendor/couchapp/lib/path").init(req), Atom = require("vendor/couchapp/lib/atom"); var templates = ddoc.templates; var assetPath = path.asset(), browse...
(row) { var doc = row.doc; var summary = ''; if (doc.Summary && doc.Summary.length <= 350) { summary = doc.Summary; } else { summary = (doc.Summary.replace(/<(.|\n)*?>/g, '').substring(0,350) + '...'); } doc.Summary = summary; send(Mustache...
sendRow
identifier_name
task.ts
import {AbstractTask} from './abstractTask'; import {BacklogItemType} from './backlogItemType'; import {BacklogItem} from './backlogItem'; import {plainToClass} from 'class-transformer'; import {CheckItem} from './checkItem'; export class Task extends AbstractTask { static path = 'task/'; progressInfo: any; pu...
constructor(id?: string, title?: string, createDate?: Date, keywords?: Array<string>, description?: string, assignee?: Array<string>, complexity?: any, depending?: Array<string>, status?: any, progressInfo?: any, checkList?: Array<CheckItem>) { super(id, title, createDate, keywords, ...
{ const task: Task = plainToClass(Task, <BacklogItem>object); task.type = BacklogItemType.TASK; return task; }
identifier_body
task.ts
import {AbstractTask} from './abstractTask'; import {BacklogItemType} from './backlogItemType'; import {BacklogItem} from './backlogItem'; import {plainToClass} from 'class-transformer'; import {CheckItem} from './checkItem'; export class Task extends AbstractTask { static path = 'task/'; progressInfo: any; pu...
(object: any): Task { const task: Task = plainToClass(Task, <BacklogItem>object); task.type = BacklogItemType.TASK; return task; } constructor(id?: string, title?: string, createDate?: Date, keywords?: Array<string>, description?: string, assignee?: Array<string>, complexity?: any, depend...
instantiate
identifier_name
task.ts
import {AbstractTask} from './abstractTask'; import {BacklogItemType} from './backlogItemType'; import {BacklogItem} from './backlogItem'; import {plainToClass} from 'class-transformer'; import {CheckItem} from './checkItem'; export class Task extends AbstractTask { static path = 'task/'; progressInfo: any; pu...
assignee?: Array<string>, complexity?: any, depending?: Array<string>, status?: any, progressInfo?: any, checkList?: Array<CheckItem>) { super(id, title, createDate, keywords, description, assignee, complexity, depending, status, BacklogItemType.TASK, checkList); this.progressInfo = ...
return task; } constructor(id?: string, title?: string, createDate?: Date, keywords?: Array<string>, description?: string,
random_line_split
warpnet_experiment_structs.py
# WARPnet Client<->Server Architecture # WARPnet Parameter Definitions # # Author: Siddharth Gupta import struct, time from warpnet_common_params import * from warpnet_client_definitions import * from twisted.internet import reactor import binascii # Struct IDs STRUCTID_CONTROL = 0x13 STRUCTID_CONTROL_ACK = 0x14 STR...
#Client struct for collecting BER updates from the ber_processor program # Matching C code struct: # typedef struct { # unsigned char structID; # unsigned char nodeID; # unsigned short sequenceNumber; # unsigned char nodeID_tx; # unsigned char nodeID_rx; # unsigned short mac_seqNum; # unsigned char ma...
dataTuple = struct.unpack('!2B 2B 4I', rawData[0:20]) self.reqNum = dataTuple[2] self.reqType = dataTuple[3] self.numPkts_tx = dataTuple[4] self.numPkts_rx_good = dataTuple[5] self.numPkts_rx_goodHdrBadPyld = dataTuple[6] self.numPkts_rx_badHdr = dataTuple[7]
identifier_body
warpnet_experiment_structs.py
# WARPnet Client<->Server Architecture # WARPnet Parameter Definitions # # Author: Siddharth Gupta import struct, time from warpnet_common_params import * from warpnet_client_definitions import * from twisted.internet import reactor import binascii # Struct IDs STRUCTID_CONTROL = 0x13 STRUCTID_CONTROL_ACK = 0x14 STR...
(self, nodeID): self.updateDone = False return struct.pack('!6BHII', self.structID, nodeID, self.txPower, self.channel, self.modOrderHeader, self.modOrderPayload, self.reserved, self.packetGeneratorPeriod, self.packetGeneratorLength) def updateFromNode(self, rawData, pcapts): dataTuple = struct.unpack('!BBH',...
prepToSend
identifier_name
warpnet_experiment_structs.py
# WARPnet Client<->Server Architecture # WARPnet Parameter Definitions # # Author: Siddharth Gupta import struct, time from warpnet_common_params import * from warpnet_client_definitions import * from twisted.internet import reactor import binascii # Struct IDs STRUCTID_CONTROL = 0x13 STRUCTID_CONTROL_ACK = 0x14 STR...
def __init__(self, logger=None): ClientStruct.__init__(self, logger) self.structID = STRUCTID_OBSERVE_PER_REQ self.expectedReturnStructID = STRUCTID_OBSERVE_PER self.numPkts_tx = 0 self.numPkts_rx_good = 0 self.numPkts_rx_goodHdrBadPyld = 0 self.numPkts_rx_badHdr = 0 self.reqNum = 0 self.reqType ...
numPkts_rx_badHdr = -1 reqNum = -1 reqType = -1
random_line_split
slidedown.js
// JavaScript Document /************************************************************************************************************ Show hide content with slide effect Copyright (C) August 2010 DTHMLGoodies.com, Alf Magne Kalleland This library is free software; you can redistribute it and/or modify it under the ter...
slideContent(numericId,dhtmlgoodies_slideSpeed); } }else{ slideContent(numericId,(dhtmlgoodies_slideSpeed*-1)); dhtmlgoodies_activeId = false; } } function slideContent(inputId,direction) { var obj =document.getElementById('dhtmlgoodies_a' + inputId); var contentObj = document.getElementById('dhtmlgoodi...
{ if(dhtmlgoodies_slideInProgress)return; dhtmlgoodies_slideInProgress = true; if(!inputId)inputId = this.id; inputId = inputId + ''; var numericId = inputId.replace(/[^0-9]/g,''); var answerDiv = document.getElementById('dhtmlgoodies_a' + numericId); objectIdToSlideDown = false; if(!answerDiv.style.display ...
identifier_body
slidedown.js
// JavaScript Document /************************************************************************************************************ Show hide content with slide effect Copyright (C) August 2010 DTHMLGoodies.com, Alf Magne Kalleland This library is free software; you can redistribute it and/or modify it under the ter...
dhtmlgoodies_slideInProgress = false; } }else{ dhtmlgoodies_activeId = inputId; dhtmlgoodies_slideInProgress = false; } } } function initShowHideDivs() { var divs = document.getElementsByTagName('DIV'); var divCounter = 1; for(var no=0;no<divs.length;no++){ if(divs[no].className=='dhtmlgoodies...
random_line_split
slidedown.js
// JavaScript Document /************************************************************************************************************ Show hide content with slide effect Copyright (C) August 2010 DTHMLGoodies.com, Alf Magne Kalleland This library is free software; you can redistribute it and/or modify it under the ter...
} function slideContent(inputId,direction) { var obj =document.getElementById('dhtmlgoodies_a' + inputId); var contentObj = document.getElementById('dhtmlgoodies_ac' + inputId); height = obj.clientHeight; if(height==0)height = obj.offsetHeight; height = height + direction; rerunFunction = true; if(height>cont...
{ slideContent(numericId,(dhtmlgoodies_slideSpeed*-1)); dhtmlgoodies_activeId = false; }
conditional_block
slidedown.js
// JavaScript Document /************************************************************************************************************ Show hide content with slide effect Copyright (C) August 2010 DTHMLGoodies.com, Alf Magne Kalleland This library is free software; you can redistribute it and/or modify it under the ter...
() { var divs = document.getElementsByTagName('DIV'); var divCounter = 1; for(var no=0;no<divs.length;no++){ if(divs[no].className=='dhtmlgoodies_question'){ divs[no].onclick = showHideContent; divs[no].id = 'dhtmlgoodies_q'+divCounter; var answer = divs[no].nextSibling; while(answer && answer.tagName!...
initShowHideDivs
identifier_name
integration_test.rs
// Copyright 2020 The Tink-Rust Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or ag...
() { tink_daead::init(); let kh = tink_core::keyset::Handle::new(&tink_daead::aes_siv_key_template()).unwrap(); // NOTE: save the keyset to a safe location. DO NOT hardcode it in source code. // Consider encrypting it with a remote key in Cloud KMS, AWS KMS or HashiCorp Vault. // See https://github...
example
identifier_name
integration_test.rs
// Copyright 2020 The Tink-Rust Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or ag...
// Consider encrypting it with a remote key in Cloud KMS, AWS KMS or HashiCorp Vault. // See https://github.com/google/tink/blob/master/docs/GOLANG-HOWTO.md#storing-and-loading-existing-keysets. let d = tink_daead::new(&kh).unwrap(); let msg = b"this data needs to be encrypted"; let aad = b"this da...
random_line_split
integration_test.rs
// Copyright 2020 The Tink-Rust Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or ag...
assert_eq!(msg, &pt[..]); } #[test] fn test_deterministic_aead_init() { // Check for AES-SIV key manager. tink_daead::init(); assert!(tink_core::registry::get_key_manager(tink_tests::AES_SIV_TYPE_URL).is_ok()); }
{ tink_daead::init(); let kh = tink_core::keyset::Handle::new(&tink_daead::aes_siv_key_template()).unwrap(); // NOTE: save the keyset to a safe location. DO NOT hardcode it in source code. // Consider encrypting it with a remote key in Cloud KMS, AWS KMS or HashiCorp Vault. // See https://github.co...
identifier_body
dag.rs
use daggy::{PetGraph, Dag, Walker, NodeIndex, EdgeIndex, WouldCycle}; use daggy::petgraph::graph::IndexType; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Edge { pub source: u32, pub target: u32, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Port<Ix: IndexType> { pub node: NodeIndex<...
else { None } } } pub struct Children<'a, N: 'a, Ix: IndexType>(&'a Dag<N, Edge, Ix>, ::daggy::Children<N, Edge, Ix>); impl<'a, N: 'a, Ix: IndexType> Iterator for Children<'a, N, Ix> { type Item = (u32, Port<Ix>); fn next(&mut self) -> Option<Self::Item> { if let Some((edge, n...
{ let edge = self.0.edge_weight(edge).unwrap(); Some((port(node, edge.source), edge.target)) }
conditional_block
dag.rs
use daggy::{PetGraph, Dag, Walker, NodeIndex, EdgeIndex, WouldCycle}; use daggy::petgraph::graph::IndexType; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Edge { pub source: u32, pub target: u32, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Port<Ix: IndexType> { pub node: NodeIndex<...
} pub fn remove_outgoing_edges(&mut self, node: NodeIndex<Ix>) { let mut walker = self.dag.children(node); while let Some(e) = walker.next_edge(&self.dag) { self.dag.remove_edge(e); } } } impl<N, Ix: IndexType> PortNumbered<N, Ix> { pub fn add_node(&mut self, weight...
random_line_split
dag.rs
use daggy::{PetGraph, Dag, Walker, NodeIndex, EdgeIndex, WouldCycle}; use daggy::petgraph::graph::IndexType; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Edge { pub source: u32, pub target: u32, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Port<Ix: IndexType> { pub node: NodeIndex<...
} pub struct Edges<'a, Ix: IndexType>(::daggy::RawEdges<'a, Edge, Ix>, usize); impl<'a, Ix: IndexType> Iterator for Edges<'a, Ix> { type Item = (Port<Ix>, Port<Ix>); fn next(&mut self) -> Option<Self::Item> { if self.1 < self.0.len() { let e = &self.0[self.1]; self.1 += 1; ...
{ WouldBreak::WouldCycle }
identifier_body
dag.rs
use daggy::{PetGraph, Dag, Walker, NodeIndex, EdgeIndex, WouldCycle}; use daggy::petgraph::graph::IndexType; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Edge { pub source: u32, pub target: u32, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Port<Ix: IndexType> { pub node: NodeIndex<...
(&mut self, node: NodeIndex<Ix>) { let mut walker = self.dag.children(node); while let Some(e) = walker.next_edge(&self.dag) { self.dag.remove_edge(e); } } } impl<N, Ix: IndexType> PortNumbered<N, Ix> { pub fn add_node(&mut self, weight: N) -> NodeIndex<Ix> { self.da...
remove_outgoing_edges
identifier_name
sensor.py
"""Support for Freedompro sensor.""" from homeassistant.components.sensor import ( SensorDeviceClass, SensorEntity, SensorStateClass, ) from homeassistant.config_entries import ConfigEntry from homeassistant.const import LIGHT_LUX, PERCENTAGE, TEMP_CELSIUS from homeassistant.core import HomeAssistant, callb...
super()._handle_coordinator_update() async def async_added_to_hass(self) -> None: """When entity is added to hass.""" await super().async_added_to_hass() self._handle_coordinator_update()
state = device["state"] self._attr_native_value = state[DEVICE_KEY_MAP[self._type]]
conditional_block
sensor.py
"""Support for Freedompro sensor.""" from homeassistant.components.sensor import ( SensorDeviceClass, SensorEntity, SensorStateClass, ) from homeassistant.config_entries import ConfigEntry from homeassistant.const import LIGHT_LUX, PERCENTAGE, TEMP_CELSIUS from homeassistant.core import HomeAssistant, callb...
UNIT_MAP = { "temperatureSensor": TEMP_CELSIUS, "humiditySensor": PERCENTAGE, "lightSensor": LIGHT_LUX, } DEVICE_KEY_MAP = { "temperatureSensor": "currentTemperature", "humiditySensor": "currentRelativeHumidity", "lightSensor": "currentAmbientLightLevel", } SUPPORTED_SENSORS = {"temperatureSenso...
"lightSensor": None, }
random_line_split
sensor.py
"""Support for Freedompro sensor.""" from homeassistant.components.sensor import ( SensorDeviceClass, SensorEntity, SensorStateClass, ) from homeassistant.config_entries import ConfigEntry from homeassistant.const import LIGHT_LUX, PERCENTAGE, TEMP_CELSIUS from homeassistant.core import HomeAssistant, callb...
"""When entity is added to hass.""" await super().async_added_to_hass() self._handle_coordinator_update()
identifier_body
sensor.py
"""Support for Freedompro sensor.""" from homeassistant.components.sensor import ( SensorDeviceClass, SensorEntity, SensorStateClass, ) from homeassistant.config_entries import ConfigEntry from homeassistant.const import LIGHT_LUX, PERCENTAGE, TEMP_CELSIUS from homeassistant.core import HomeAssistant, callb...
(self, device, coordinator): """Initialize the Freedompro sensor.""" super().__init__(coordinator) self._attr_name = device["name"] self._attr_unique_id = device["uid"] self._type = device["type"] self._attr_device_info = DeviceInfo( identifiers={ ...
__init__
identifier_name
MenuLayoutComponent.tsx
import * as React from "react"; import * as weavejs from "weavejs"; import * as _ from "lodash"; import HBox = weavejs.ui.flexbox.HBox; import VBox = weavejs.ui.flexbox.VBox; import HSlider from "weaveapp/ui/slider/HSlider"; import VSlider from "weaveapp/ui/slider/VSlider"; import ComboBox = weavejs.ui.ComboBox; ...
}
return null; } }
random_line_split
MenuLayoutComponent.tsx
import * as React from "react"; import * as weavejs from "weavejs"; import * as _ from "lodash"; import HBox = weavejs.ui.flexbox.HBox; import VBox = weavejs.ui.flexbox.VBox; import HSlider from "weaveapp/ui/slider/HSlider"; import VSlider from "weaveapp/ui/slider/VSlider"; import ComboBox = weavejs.ui.ComboBox; ...
(props:IMenuLayoutComponentProps) { super(props); } render():JSX.Element { var options = this.props.options.map((option) => { return { label: _.isString(option.label) ? Weave.lang(option.label) : option.label, value: option.value }; }); let button = this.props.playToggle ? <C...
constructor
identifier_name
MenuLayoutComponent.tsx
import * as React from "react"; import * as weavejs from "weavejs"; import * as _ from "lodash"; import HBox = weavejs.ui.flexbox.HBox; import VBox = weavejs.ui.flexbox.VBox; import HSlider from "weaveapp/ui/slider/HSlider"; import VSlider from "weaveapp/ui/slider/VSlider"; import ComboBox = weavejs.ui.ComboBox; ...
render():JSX.Element { var options = this.props.options.map((option) => { return { label: _.isString(option.label) ? Weave.lang(option.label) : option.label, value: option.value }; }); let button = this.props.playToggle ? <CenteredIcon onClick={this.props.playToggle} iconProps={{cl...
{ super(props); }
identifier_body
contract-service.ts
/* * Copyright 2020 * SRDC - Software Research & Development Consultancy; Ankara; Turkey In collaboration with * SRFG - Salzburg Research Forschungsgesellschaft mbH; Salzburg; Austria Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with th...
limitations under the License. */ import { Injectable } from '@angular/core'; import { Headers, Http } from '@angular/http'; import 'rxjs/add/operator/toPromise'; import { CookieService } from 'ng2-cookies'; import {BPDataService} from './bp-data-service'; import {BPEService} from '../bpe.service'; import...
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 gover...
random_line_split
contract-service.ts
/* * Copyright 2020 * SRDC - Software Research & Development Consultancy; Ankara; Turkey In collaboration with * SRFG - Salzburg Research Forschungsgesellschaft mbH; Salzburg; Austria Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with th...
{ constructor(private http: Http, private bpDataService: BPDataService, private bpeService: BPEService, private catalogueService: CatalogueService, private cookieService: CookieService) { } getDefaultTermsAndConditions(catalogueUuids:str...
ContractService
identifier_name
contract-service.ts
/* * Copyright 2020 * SRDC - Software Research & Development Consultancy; Ankara; Turkey In collaboration with * SRFG - Salzburg Research Forschungsgesellschaft mbH; Salzburg; Austria Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with th...
tradingTerm.value.valueCode[0].value = sellerNegotiationSettings.paymentTerms[0]; } else if (tradingTerm.id.includes("$seller_id")){ tradingTerm.value.value[0].value = sellerNegotiationSettings.company....
{ let contractForCatalogue = catalogueContractMap[catalogueUuids[i]]; // use the catalogue terms if(contractForCatalogue && contractForCatalogue.length > 0){ termsAndConditions.push(copy(contractForCatalogue)); } /...
conditional_block
limit.py
from .util import bucket as tokenbucket from . import wrappers class Limit(object): def __init__(self, command_limiting_initial_tokens, command_limiting_message_cost, command_limiting_restore_rate, override, permissions): """limit(20, 4, 0.13, ["admin"], {"admin": "user!*@*"}) Limits the use of c...
if info.nick not in self.buckets: bucket = tokenbucket.TokenBucket(self.command_limiting_initial_tokens, self.command_limiting_restore_rate) self.buckets[info.nick] = bucket else: bucket = self.buckets[info.nick] if bucket.consume(self.command_limiting_messa...
return True
conditional_block
limit.py
from .util import bucket as tokenbucket from . import wrappers class Limit(object): def
(self, command_limiting_initial_tokens, command_limiting_message_cost, command_limiting_restore_rate, override, permissions): """limit(20, 4, 0.13, ["admin"], {"admin": "user!*@*"}) Limits the use of commands Arguments: command_limiting_initial_tokens {Integer} -- Initial tokens fo...
__init__
identifier_name
limit.py
from .util import bucket as tokenbucket from . import wrappers class Limit(object): def __init__(self, command_limiting_initial_tokens, command_limiting_message_cost, command_limiting_restore_rate, override, permissions):
def command_limiter(self, info): #Check if admin/whatever specified if self.permissions.check(self.override, info.mask): return True if info.nick not in self.buckets: bucket = tokenbucket.TokenBucket(self.command_limiting_initial_tokens, self.command_limiting_restor...
"""limit(20, 4, 0.13, ["admin"], {"admin": "user!*@*"}) Limits the use of commands Arguments: command_limiting_initial_tokens {Integer} -- Initial tokens for tokenbucket command_limiting_message_cost {Integer} -- Message cost for tokenbucket command_limiting_restore...
identifier_body
limit.py
from .util import bucket as tokenbucket from . import wrappers class Limit(object): def __init__(self, command_limiting_initial_tokens, command_limiting_message_cost, command_limiting_restore_rate, override, permissions): """limit(20, 4, 0.13, ["admin"], {"admin": "user!*@*"})
command_limiting_message_cost {Integer} -- Message cost for tokenbucket command_limiting_restore_rate {Integer} -- Restore rate for token bucket override {List} -- List of permissions to override the limit permissions {Dict} -- All of the bots permissions. """ ...
Limits the use of commands Arguments: command_limiting_initial_tokens {Integer} -- Initial tokens for tokenbucket
random_line_split
boot.ts
import * as Phaser from 'phaser' import * as WebFont from 'webfontloader' export class BootState extends Phaser.State { stage: Phaser.Stage fontsReady: boolean init () { this.stage.backgroundColor = '#EDEEC9' this.fontsReady = false this.fontsLoaded = this.fontsLoaded.bind(this) } preload () { ...
} fontsLoaded () { this.fontsReady = true } }
{ this.game.state.start('Splash') }
conditional_block
boot.ts
import * as Phaser from 'phaser' import * as WebFont from 'webfontloader' export class BootState extends Phaser.State { stage: Phaser.Stage fontsReady: boolean init () { this.stage.backgroundColor = '#EDEEC9' this.fontsReady = false this.fontsLoaded = this.fontsLoaded.bind(this) } preload () { ...
let text = this.add.text(this.world.centerX, this.world.centerY, 'loading fonts', { font: '16px Arial', fill: '#dddddd', align: 'center' }) text.anchor.setTo(0.5, 0.5) this.load.image('loaderBg', './assets/images/loader-bg.png') this.load.image('loaderBar', './assets/images/loader-bar.png') } rend...
})
random_line_split
boot.ts
import * as Phaser from 'phaser' import * as WebFont from 'webfontloader' export class BootState extends Phaser.State { stage: Phaser.Stage fontsReady: boolean init () { this.stage.backgroundColor = '#EDEEC9' this.fontsReady = false this.fontsLoaded = this.fontsLoaded.bind(this) } preload () { ...
}
{ this.fontsReady = true }
identifier_body
boot.ts
import * as Phaser from 'phaser' import * as WebFont from 'webfontloader' export class BootState extends Phaser.State { stage: Phaser.Stage fontsReady: boolean
() { this.stage.backgroundColor = '#EDEEC9' this.fontsReady = false this.fontsLoaded = this.fontsLoaded.bind(this) } preload () { WebFont.load({ google: { families: ['Nunito'] }, active: this.fontsLoaded }) let text = this.add.text(this.world.centerX, this.world....
init
identifier_name
_fine_cal.py
# -*- coding: utf-8 -*- # Authors: Eric Larson <larson.eric.d@gmail.com> # License: BSD (3-clause) import numpy as np from ..utils import check_fname, _check_fname def read_fine_calibration(fname):
imb_cals = list() with open(fname, 'r') as fid: for line in fid: if line[0] in '#\n': continue vals = line.strip().split() if len(vals) not in [14, 16]: raise RuntimeError('Error parsing fine calibration file, ' ...
"""Read fine calibration information from a .dat file. The fine calibration typically includes improved sensor locations, calibration coefficients, and gradiometer imbalance information. Parameters ---------- fname : str The filename. Returns ------- calibration : dict ...
identifier_body
_fine_cal.py
# -*- coding: utf-8 -*- # Authors: Eric Larson <larson.eric.d@gmail.com> # License: BSD (3-clause) import numpy as np from ..utils import check_fname, _check_fname def read_fine_calibration(fname): """Read fine calibration information from a .dat file. The fine calibration typically includes improved sens...
"""Write fine calibration information to a .dat file. Parameters ---------- fname : str The filename to write out. calibration : dict Fine calibration information. """ fname = _check_fname(fname, overwrite=True) check_fname(fname, 'cal', ('.dat',)) with open(fname, ...
locs = np.array(locs) return dict(ch_names=ch_names, locs=locs, imb_cals=imb_cals) def write_fine_calibration(fname, calibration):
random_line_split
_fine_cal.py
# -*- coding: utf-8 -*- # Authors: Eric Larson <larson.eric.d@gmail.com> # License: BSD (3-clause) import numpy as np from ..utils import check_fname, _check_fname def read_fine_calibration(fname): """Read fine calibration information from a .dat file. The fine calibration typically includes improved sens...
# `vals` contains channel number ch_name = vals[0] if len(ch_name) in (3, 4): # heuristic for Neuromag fix try: ch_name = int(ch_name) except ValueError: # something other than e.g. 113 or 2642 pass ...
raise RuntimeError('Error parsing fine calibration file, ' 'should have 14 or 16 entries per line ' 'but found %s on line:\n%s' % (len(vals), line))
conditional_block
_fine_cal.py
# -*- coding: utf-8 -*- # Authors: Eric Larson <larson.eric.d@gmail.com> # License: BSD (3-clause) import numpy as np from ..utils import check_fname, _check_fname def read_fine_calibration(fname): """Read fine calibration information from a .dat file. The fine calibration typically includes improved sens...
(fname, calibration): """Write fine calibration information to a .dat file. Parameters ---------- fname : str The filename to write out. calibration : dict Fine calibration information. """ fname = _check_fname(fname, overwrite=True) check_fname(fname, 'cal', ('.dat',)) ...
write_fine_calibration
identifier_name
store.js
import { createStore } from '@utils/store.utils'; import placeholderImage from '../images/placeholder.jpeg'; import { getPhotoUrl, getPrefetchedPhotoForDisplay } from './api'; import { getLocalPhotoPath, getRandomLocalPhoto } from './photos.local'; import Settings from './settings'; export const getStateObject = (forc...
export default createStore();
random_line_split
store.js
import { createStore } from '@utils/store.utils'; import placeholderImage from '../images/placeholder.jpeg'; import { getPhotoUrl, getPrefetchedPhotoForDisplay } from './api'; import { getLocalPhotoPath, getRandomLocalPhoto } from './photos.local'; import Settings from './settings'; export const getStateObject = (forc...
// or a fallback placeholder photo if (!photoUrl) { photoMeta = null; photoUrl = placeholderImage; } // get a random image as placeholder // to handle offline network scenarios placeholderPhotoMeta = getRandomLocalPhoto(); placeholderPhotoUrl = getLocalPhotoPath(placeholder...
{ photoMeta = getRandomLocalPhoto(); photoUrl = getLocalPhotoPath(photoMeta); }
conditional_block
hero.service.ts
import { Injectable } from '@angular/core'; import { Hero } from './hero'; import {Http, Headers} from "@angular/http"; import 'rxjs/add/operator/toPromise'; @Injectable() export class HeroService { private heroesUrl = 'app/heroes'; // URL to web api constructor(private http: Http) { } getHeroes(): Promise...
return this.post(hero); } private handleError(error: any) { console.error('An error occurred', error); return Promise.reject(error.message || error); } }
{ return this.put(hero); }
conditional_block
hero.service.ts
import { Injectable } from '@angular/core'; import { Hero } from './hero'; import {Http, Headers} from "@angular/http"; import 'rxjs/add/operator/toPromise'; @Injectable() export class HeroService { private heroesUrl = 'app/heroes'; // URL to web api constructor(private http: Http) { } getHeroes(): Promise...
(id: number) { return this.getHeroes() .then(heroes => heroes.filter(hero => hero.id === id)[0]); } // Add new Hero private post(hero: Hero): Promise<Hero> { let headers = new Headers({ 'Content-Type': 'application/json'}); return this.http .post(this.heroesUrl, JSON.stringify(he...
getHero
identifier_name
hero.service.ts
import { Injectable } from '@angular/core'; import { Hero } from './hero'; import {Http, Headers} from "@angular/http"; import 'rxjs/add/operator/toPromise'; @Injectable() export class HeroService { private heroesUrl = 'app/heroes'; // URL to web api constructor(private http: Http) { } getHeroes(): Promise...
getHero(id: number) { return this.getHeroes() .then(heroes => heroes.filter(hero => hero.id === id)[0]); } // Add new Hero private post(hero: Hero): Promise<Hero> { let headers = new Headers({ 'Content-Type': 'application/json'}); return this.http .post(this.heroesUrl, JSON.s...
{ return new Promise<Hero[]>(resolve => setTimeout(() => this.getHeroes(), 1000) // 1 seconds ); }
identifier_body
hero.service.ts
import { Injectable } from '@angular/core'; import { Hero } from './hero'; import {Http, Headers} from "@angular/http"; import 'rxjs/add/operator/toPromise'; @Injectable() export class HeroService { private heroesUrl = 'app/heroes'; // URL to web api constructor(private http: Http) { } getHeroes(): Promise...
getHeroesSlowly() { return new Promise<Hero[]>(resolve => setTimeout(() => this.getHeroes(), 1000) // 1 seconds ); } getHero(id: number) { return this.getHeroes() .then(heroes => heroes.filter(hero => hero.id === id)[0]); } // Add new Hero private post(hero: Hero): Promise<Hero> { ...
.toPromise() .then(response => response.json().data) .catch(this.handleError); }
random_line_split
ClosedDialogScrollTest.ts
import { Chain, Keys, Pipeline, RawAssertions, Step } from '@ephox/agar'; import { UnitTest } from '@ephox/bedrock'; import { TinyActions, TinyApis, TinyLoader } from '@ephox/mcagar'; import LinkPlugin from 'tinymce/plugins/link/Plugin'; import InliteTheme from 'tinymce/themes/inlite/Theme'; import Toolbar from '../m...
}, { theme: 'inlite', plugins: 'link', insert_toolbar: 'quickimage media quicktable', selection_toolbar: 'bold italic | quicklink h1 h2 blockquote', inline: true, skin_url: '/project/js/tinymce/skins/lightgray' }, success, failure); });
}) ], onSuccess, onFailure);
random_line_split
GeodesicActiveContourImageFilterTest.py
#========================================================================== # # Copyright NumFOCUS # # 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/l...
(filter, fileName): caster = itk.RescaleIntensityImageFilter[ InternalImageType, OutputImageType].New( filter, OutputMinimum=0, OutputMaximum=255) itk.imwrite(caster, os.path.join(outputDirectory, fileName)) rescaleAndWrite(smoothing, "Geo...
rescaleAndWrite
identifier_name
GeodesicActiveContourImageFilterTest.py
#========================================================================== # # Copyright NumFOCUS # # 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/l...
main()
conditional_block
GeodesicActiveContourImageFilterTest.py
#========================================================================== # # Copyright NumFOCUS # # 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/l...
rescaleAndWrite(smoothing, "GeodesicActiveContourImageFilterOutput1.png") rescaleAndWrite( gradientMagnitude, "GeodesicActiveContourImageFilterOutput2.png") rescaleAndWrite(sigmoid, "GeodesicActiveContourImageFilterOutput3.png") rescaleAndWrite( fastMarching, "GeodesicA...
caster = itk.RescaleIntensityImageFilter[ InternalImageType, OutputImageType].New( filter, OutputMinimum=0, OutputMaximum=255) itk.imwrite(caster, os.path.join(outputDirectory, fileName))
identifier_body
GeodesicActiveContourImageFilterTest.py
#========================================================================== # # Copyright NumFOCUS # # 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/l...
writer = itk.ImageFileWriter[OutputImageType].New( thresholder, FileName=argv[2]) def rescaleAndWrite(filter, fileName): caster = itk.RescaleIntensityImageFilter[ InternalImageType, OutputImageType].New( filter, OutputMinimum=0, ...
random_line_split
DigitalMainParamsView.js
Ext.define("W2B.view.mis.costcenter.digitequip.DigitalMainParamsView", { extend: 'Ext.panel.Panel', xtype: 'digitmainparams', controller: 'digitalview', viewModel: { type: 'missystem' }, bodyPadding: 5, layout: 'anchor', defaults: { anchor: '100%', labelWidth: 250 }, items: [ { xtype: 'textfi...
}, { xtype: 'combobox', name: "digit_catprodaj", fieldLabel: 'Кат. продаж', editable: false, queryMode: 'local' }, { xtype: 'radiogroup', vertical: true, fieldLabel: 'Бумага', columns: 1, items: [ { boxLabel: 'Листы (листовая печать)', name: 'paperType', inpu...
queryMode: 'local'
random_line_split
FireUser.js
','FireUserConfig',function (FireUserDefault,FireUserConfig) { if(!FireUserConfig.url) throw "No config Url. Please Add your URL."; FireUserConfig = angular.extend(FireUserDefault,FireUserConfig); return FireUserConfig; }]) .run(['$rootScope', '$location', '$fireUser', '$state','FireUserValues','waitForAuth', ...
(err) { if($rootScope.auth) { $rootScope.auth.error = err instanceof Error? err.toString() : null; } for(var i=0; i < subs.length; i++) { subs[i](); } $timeout(function() { // force $scope.$apply to be re-run after login resolves def.resolve(); }); } var...
fn
identifier_name
FireUser.js
','FireUserConfig',function (FireUserDefault,FireUserConfig) { if(!FireUserConfig.url) throw "No config Url. Please Add your URL."; FireUserConfig = angular.extend(FireUserDefault,FireUserConfig); return FireUserConfig; }]) .run(['$rootScope', '$location', '$fireUser', '$state','FireUserValues','waitForAuth', ...
var def = $q.defer(), subs = []; subs.push($rootScope.$on('$firebaseSimpleLogin:login', fn)); subs.push($rootScope.$on('$firebaseSimpleLogin:logout', fn)); subs.push($rootScope.$on('$firebaseSimpleLogin:error', fn)); return def.promise; }) .controller('fireuserloginCtrl',['$scope','$fireUser',...
{ if($rootScope.auth) { $rootScope.auth.error = err instanceof Error? err.toString() : null; } for(var i=0; i < subs.length; i++) { subs[i](); } $timeout(function() { // force $scope.$apply to be re-run after login resolves def.resolve(); }); }
identifier_body
FireUser.js
','FireUserConfig',function (FireUserDefault,FireUserConfig) { if(!FireUserConfig.url) throw "No config Url. Please Add your URL."; FireUserConfig = angular.extend(FireUserDefault,FireUserConfig); return FireUserConfig; }]) .run(['$rootScope', '$location', '$fireUser', '$state','FireUserValues','waitForAuth', ...
else{ checked = toState.name; $state.go(toState.name,toParams) }; }); } else { // clear the flag and don't prevent the default if the state change // was just triggered by this watch checked = false; } }) }; }]) .service('...
{ $state.go(FireUserValues.routeRedirect) }
conditional_block
FireUser.js
,FireUserConfig) { if(!FireUserConfig.url) throw "No config Url. Please Add your URL."; FireUserConfig = angular.extend(FireUserDefault,FireUserConfig); return FireUserConfig; }]) .run(['$rootScope', '$location', '$fireUser', '$state','FireUserValues','waitForAuth', function($rootScope, $location, $fireUser, $...
'<input class="form-control" placeholder="Представься" type="name" name="name" ng-model="mtd.userName" required/>' + '<select class="form-control" ng-model="mtd.userGender" name="пол" required ng-options="gender.gender as gender.title for gender in genders"></select>'+
random_line_split
gas_co2_s8.py
import mraa import time from multiprocessing import Queue,Process import move_avge CO2_BYTE = 9 NUM_INCOME_BYTE = 13 S8_message = b"\xFE\x04\x00\x00\x00\x04\xE5\xC6" class sensor(Process): def __init__(self, q): Process.__init__(self) self.q = q self.u=mraa.Uart(1) self.u.setBaudRate(9600) self.u.setMod...
(self): while True: self.u.writeStr(S8_message) self.u.flush() if self.u.dataAvailable(): time.sleep(0.05) getstr = self.u.readStr(NUM_INCOME_BYTE) if len(getstr) == NUM_INCOME_BYTE: self.data_log(getstr) g = self.get_data() self.q.put(g) time.sleep(5) if __name__ == ...
run
identifier_name
gas_co2_s8.py
import mraa import time from multiprocessing import Queue,Process import move_avge CO2_BYTE = 9 NUM_INCOME_BYTE = 13 S8_message = b"\xFE\x04\x00\x00\x00\x04\xE5\xC6" class sensor(Process): def __init__(self, q): Process.__init__(self) self.q = q self.u=mraa.Uart(1) self.u.setBaudRate(9600) self.u.setMod...
def checksum(self, dstr): return True def get_data(self): CO2 = self.co2_avg.get() ret = { 'CO2': CO2 } return ret def run(self): while True: self.u.writeStr(S8_message) self.u.flush() if self.u.dataAvailable(): time.sleep(0.05) getstr = self.u.readStr(NUM_INCOME_BYTE) if len...
bytedata = bytearray(dstr) if self.checksum(dstr) is True: CO2 = bytedata[CO2_BYTE]*256 + bytedata[CO2_BYTE+1] self.co2_avg.add(CO2) else: return
identifier_body
gas_co2_s8.py
import mraa import time from multiprocessing import Queue,Process import move_avge CO2_BYTE = 9 NUM_INCOME_BYTE = 13 S8_message = b"\xFE\x04\x00\x00\x00\x04\xE5\xC6" class sensor(Process): def __init__(self, q): Process.__init__(self) self.q = q self.u=mraa.Uart(1) self.u.setBaudRate(9600) self.u.setMod...
time.sleep(5) if __name__ == '__main__': q = Queue(maxsize=5) p = sensor(q) p.start() while True: print('co2: '+ str(q.get()))
self.data_log(getstr) g = self.get_data() self.q.put(g)
conditional_block
gas_co2_s8.py
import mraa import time from multiprocessing import Queue,Process import move_avge CO2_BYTE = 9 NUM_INCOME_BYTE = 13 S8_message = b"\xFE\x04\x00\x00\x00\x04\xE5\xC6" class sensor(Process): def __init__(self, q): Process.__init__(self) self.q = q self.u=mraa.Uart(1) self.u.setBaudRate(9600) self.u.setMod...
def run(self): while True: self.u.writeStr(S8_message) self.u.flush() if self.u.dataAvailable(): time.sleep(0.05) getstr = self.u.readStr(NUM_INCOME_BYTE) if len(getstr) == NUM_INCOME_BYTE: self.data_log(getstr) g = self.get_data() self.q.put(g) time.sleep(5) if __na...
random_line_split