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
holidays.js
angular.module('bhima.controllers') .controller('HolidayManagementController', HolidayManagementController); HolidayManagementController.$inject = [ 'HolidayService', 'ModalService', 'NotifyService', 'uiGridConstants', '$state', ]; /** * Holiday Management Controller * * This controller is about the Holiday mana...
(title) { ModalService.confirm('FORM.DIALOGS.CONFIRM_DELETE') .then(function (bool) { if (!bool) { return; } Holidays.delete(title.id) .then(function () { Notify.success('FORM.LABELS.DELETED'); loadHolidays(); }) .catch(Notify.handleError); }); } // update...
deleteHoliday
identifier_name
holidays.js
angular.module('bhima.controllers') .controller('HolidayManagementController', HolidayManagementController); HolidayManagementController.$inject = [ 'HolidayService', 'ModalService', 'NotifyService', 'uiGridConstants', '$state', ]; /** * Holiday Management Controller * * This controller is about the Holiday mana...
loadHolidays(); }
{ $state.go('holidays.edit', { id : title.id }); }
identifier_body
DataTexture.ts
import { Texture } from './Texture'; import { NearestFilter } from '../Constants'; import { UVMapping, MirroredRepeatWrapping, ClampToEdgeWrapping, RepeatWrapping, LinearEncoding, UnsignedByteType, RGBAFormat, LinearMipMapLinearFilter, LinearFilter } from '../Constants'; export class DataTexture extends Texture ...
super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding); this.image = { data: data, width: width, height: height }; this.magFilter = magFilter; this.minFilter = minFilter; this.generateMipmaps = false; this.flipY = false; this.unpackAlignment = 1; } ...
anisotropy: number = 1, encoding: number = LinearEncoding ) {
random_line_split
DataTexture.ts
import { Texture } from './Texture'; import { NearestFilter } from '../Constants'; import { UVMapping, MirroredRepeatWrapping, ClampToEdgeWrapping, RepeatWrapping, LinearEncoding, UnsignedByteType, RGBAFormat, LinearMipMapLinearFilter, LinearFilter } from '../Constants'; export class DataTexture extends Texture ...
( data, width: number, height: number, format: number = RGBAFormat, type: number = UnsignedByteType, mapping: number = Texture.DEFAULT_MAPPING, wrapS: number = ClampToEdgeWrapping, wrapT: number = ClampToEdgeWrapping, magFilter: number = NearestFilter, minFilter: number = NearestFilter, ...
constructor
identifier_name
DataTexture.ts
import { Texture } from './Texture'; import { NearestFilter } from '../Constants'; import { UVMapping, MirroredRepeatWrapping, ClampToEdgeWrapping, RepeatWrapping, LinearEncoding, UnsignedByteType, RGBAFormat, LinearMipMapLinearFilter, LinearFilter } from '../Constants'; export class DataTexture extends Texture ...
}
{ super(null, mapping, wrapS, wrapT, magFilter, minFilter, format, type, anisotropy, encoding); this.image = { data: data, width: width, height: height }; this.magFilter = magFilter; this.minFilter = minFilter; this.generateMipmaps = false; this.flipY = false; this.unpackAlignment = 1; ...
identifier_body
try_catch_finally.js
'use strict'; process.stdin.resume(); process.stdin.setEncoding('utf-8'); let inputString = ''; let currentLine = 0; process.stdin.on('data', inputStdin => { inputString += inputStdin; }); process.stdin.on('end', _ => { inputString = inputString.trim().split('\n').map(string => { return string.trim(...
/* * Complete the reverseString function * Use console.log() to print to stdout. */ function reverseString(s) { try { var splitString = s.split(""); var reverseArray = splitString.reverse(); var joinArray = reverseArray.join(""); console.log(joinArray); } catch (error) ...
{ return inputString[currentLine++]; }
identifier_body
try_catch_finally.js
'use strict'; process.stdin.resume(); process.stdin.setEncoding('utf-8'); let inputString = ''; let currentLine = 0; process.stdin.on('data', inputStdin => { inputString += inputStdin; }); process.stdin.on('end', _ => { inputString = inputString.trim().split('\n').map(string => { return string.trim(...
() { const s = eval(readLine()); reverseString(s); }
main
identifier_name
try_catch_finally.js
'use strict'; process.stdin.resume(); process.stdin.setEncoding('utf-8'); let inputString = ''; let currentLine = 0; process.stdin.on('data', inputStdin => {
inputString += inputStdin; }); process.stdin.on('end', _ => { inputString = inputString.trim().split('\n').map(string => { return string.trim(); }); main(); }); function readLine() { return inputString[currentLine++]; } /* * Complete the reverseString function * Use console.log(...
random_line_split
db.js
import util from 'util' import mongoose from 'mongoose' import seedData from '../seedData' const debug = require('debug')('api:server:db') mongoose.Promise = require('bluebird') const host = process.env.MONGO_HOST || 'localhost' const database = process.env.MONGO_DATABASE || 'admin' const port = process.env.MONGO_POR...
} export default configureMongo
{ mongoose.set('debug', (collectionName, method, query, doc) => { debug(`${collectionName}.${method}`, util.inspect(query, false, 20), doc); }); }
conditional_block
db.js
import util from 'util' import mongoose from 'mongoose' import seedData from '../seedData' const debug = require('debug')('api:server:db') mongoose.Promise = require('bluebird') const host = process.env.MONGO_HOST || 'localhost' const database = process.env.MONGO_DATABASE || 'admin' const port = process.env.MONGO_POR...
() => seedData(), err => { debug(`unable to connect to database: ${err}`) setTimeout(configureMongo, 5000) } ) if (process.env.MONGO_DEBUG) { mongoose.set('debug', (collectionName, method, query, doc) => { debug(`${collectionName}.${method}`, u...
random_line_split
it.js
/* Copyright (c) 2003-2016, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */
alt: 'Testo alternativo', border: 'Bordo', btnUpload: 'Invia al server', button2Img: 'Vuoi trasformare il bottone immagine selezionato in un\'immagine semplice?', hSpace: 'HSpace', img2Button: 'Vuoi trasferomare l\'immagine selezionata in un bottone immagine?', infoTab: 'Informazioni immagine', linkTab: ...
CKEDITOR.plugins.setLang( 'image', 'it', {
random_line_split
google.js
'use strict'; var User = require('./user.model.js'); var config = require('../config'); var request = require('request'); var jwt = require('jwt-simple'); var authUtils = require('./authUtils'); exports.authenticate = function (req, res) { var accessTokenUrl = 'https://accounts.google.com/o/oauth2/token'; var pe...
var token = authUtils.createJWT(user); res.send({ token: token }); }); }); }); } else { // Step 3b. Create a new user account or return an existing one. User.findOne({ google: profile.sub }, function(err, existingUser) { if (exist...
} user.google = profile.sub; user.picture = user.picture || profile.picture.replace('sz=50', 'sz=200'); user.displayName = user.displayName || profile.name; user.save(function() {
random_line_split
google.js
'use strict'; var User = require('./user.model.js'); var config = require('../config'); var request = require('request'); var jwt = require('jwt-simple'); var authUtils = require('./authUtils'); exports.authenticate = function (req, res) { var accessTokenUrl = 'https://accounts.google.com/o/oauth2/token'; var pe...
}); }); }
{ // Step 3b. Create a new user account or return an existing one. User.findOne({ google: profile.sub }, function(err, existingUser) { if (existingUser) { return res.send({ token: authUtils.createJWT(existingUser) }); } var user = new User(); user.goog...
conditional_block
main.rs
#[macro_use] extern crate lazy_static; extern crate regex; extern crate rand; mod parser; mod eval; mod error; mod common_util; mod syntax_tree; use std::io::prelude::*; use std::io; use parser::*; use eval::*; /// Works like the println macro, but prints to the stderr instead of stdout. macro_rules! println_to_std...
let token_res = tokenize(&input as &str); //println!("Tokens: {:?} ", token_res); // DEBUG match token_res { Ok(tk_vec) => { let ast_res = parse_cmd(&tk_vec); match ast_res { Ok(cmd) => { //println!("AST: {:?} ", exp); // TODO let val_res = eval_cmd(&cmd, &mut env); match val...
else { input = temp; } } }
random_line_split
main.rs
#[macro_use] extern crate lazy_static; extern crate regex; extern crate rand; mod parser; mod eval; mod error; mod common_util; mod syntax_tree; use std::io::prelude::*; use std::io; use parser::*; use eval::*; /// Works like the println macro, but prints to the stderr instead of stdout. macro_rules! println_to_std...
() { let mut input; let max_call_depth = 100; let mut env = RollerEnv::new(max_call_depth); // The REP loop // Currently there is no way to exit other than the interrupt signal (ctrl + c) loop { print!("> "); // flush so our prompt is visible io::stdout().flush().ok().expect("Couldn't flush stdout"); l...
main
identifier_name
main.rs
#[macro_use] extern crate lazy_static; extern crate regex; extern crate rand; mod parser; mod eval; mod error; mod common_util; mod syntax_tree; use std::io::prelude::*; use std::io; use parser::*; use eval::*; /// Works like the println macro, but prints to the stderr instead of stdout. macro_rules! println_to_std...
}, // EOF encountered Ok(0) => break, // Read some bytes Ok(_) => { if temp.trim().is_empty() { // ignore empty lines continue; } else { input = temp; } } } let token_res = tokenize(&input as &str); //println!("Tokens: {:?} ", token_res); // DEBUG match token_r...
{ let mut input; let max_call_depth = 100; let mut env = RollerEnv::new(max_call_depth); // The REP loop // Currently there is no way to exit other than the interrupt signal (ctrl + c) loop { print!("> "); // flush so our prompt is visible io::stdout().flush().ok().expect("Couldn't flush stdout"); let ...
identifier_body
event.ts
undefined; } /** * For the public to allow to subscribe * to events from this Emitter */ get event(): Event<T> { if (!this._event) { this._event = (listener: (e: T) => any, thisArgs?: any, disposables?: IDisposable[] | DisposableStore) => { if (!this._listeners) { this._listeners = new LinkedLi...
bufferEvents
identifier_name
event.ts
let handle: any = undefined; let numDebouncedCalls = 0; const emitter = new Emitter<O>({ leakWarningThreshold, onFirstListenerAdd() { subscription = event(cur => { numDebouncedCalls++; output = merge(output, cur); if (leading && !handle) { emitter.fire(output); output = undef...
}); return emitter.event; } export interface IChainableEvent<T> { event: Event<T>; map<O>(fn: (i: T) => O): IChainableEvent<O>; forEach(fn: (i: T) => void): IChainableEvent<T>; filter(fn: (e: T) => boolean): IChainableEvent<T>; filter<R>(fn: (e: T | R) => e is R): IChainableEvent<R>; reduce<R>(merg...
{ if (listener) { listener.dispose(); } listener = null; }
identifier_body
event.ts
itter: DOMEventEmitter, eventName: string, map: (...args: any[]) => T = id => id): Event<T> { const fn = (...args: any[]) => result.fire(map(...args)); const onFirstListenerAdd = () => emitter.addEventListener(eventName, fn); const onLastListenerRemove = () => emitter.removeEventListener(eventName, fn); const r...
{ if (this._mergeFn) { // use the merge function to create a single composite // event. make a copy in case firing pauses this emitter const events = this._eventQueue.toArray(); this._eventQueue.clear(); super.fire(this._mergeFn(events)); } else { // no merging, fire each event individual...
conditional_block
event.ts
ableEvent<R>; reduce<R>(merge: (last: R | undefined, event: T) => R, initial?: R): IChainableEvent<R>; latch(): IChainableEvent<T>; debounce(merge: (last: T | undefined, event: T) => T, delay?: number, leading?: boolean, leakWarningThreshold?: number): IChainableEvent<T>; debounce<R>(merge: (last: R | undefined...
this._listeners = new LinkedList(); }
random_line_split
twitch.d.ts
declare module "twitch" { export interface Links { next?: string; self: string; last?: string; channel?: string; } export interface FollowsResponse { _links: Links; _total: number; follows: Follow[]; } export interface Follow { ...
url: string, views: number; followers: number; } export interface StreamsResponse { _links: Links; _total: number; streams: Stream[]; } export interface Stream { _links: Links; game: string, viewers: number, ...
profile_banner_background_color: string, partner: true,
random_line_split
get_nc_BGrid_GFDL.py
import numpy as np import pyroms from pyroms_toolbox.BGrid_GFDL import BGrid_GFDL def get_nc_BGrid_GFDL(grdfile, name='GFDL_CM2.1_North_Pacific', \ # xrange=(80,189), yrange=(96,198)): xrange=(60,175), yrange=(120, 190)): """ Bgrd = get_nc_BGrid_GFDL(gr...
name, xrange=xrange, yrange=yrange)
mask_uv[:, j,i] = 0 return BGrid_GFDL(lon_t, lat_t, lon_uv, lat_uv, \ mask_t, mask_uv, h, z_t, z_t_edges, \ z_uv, z_uv_edges, f, \
random_line_split
get_nc_BGrid_GFDL.py
import numpy as np import pyroms from pyroms_toolbox.BGrid_GFDL import BGrid_GFDL def get_nc_BGrid_GFDL(grdfile, name='GFDL_CM2.1_North_Pacific', \ # xrange=(80,189), yrange=(96,198)): xrange=(60,175), yrange=(120, 190)):
kmu = nc.variables['kmu'][:] z_uv = nc.variables['sw_ocean'][:] z_uv_edges = nc.variables['sw_edges_ocean'][:] # compute mask at t-point M_t, L_t = kmt.shape N_t = z_t.shape[0] mask_t = np.zeros((N_t, M_t, L_t)) for j in range(M_t): for i in range(L_t): try: ...
""" Bgrd = get_nc_BGrid_GFDL(grdfile) Load B-Grid grid object for GFDL CM2.1 from netCDF grid file """ nc = pyroms.io.Dataset(grdfile) lon_t = nc.variables['geolon_t'][:] lat_t = nc.variables['geolat_t'][:] lon_uv = nc.variables['geolon_c'][:] lat_uv = nc.variables['geolat_c'][:] ...
identifier_body
get_nc_BGrid_GFDL.py
import numpy as np import pyroms from pyroms_toolbox.BGrid_GFDL import BGrid_GFDL def get_nc_BGrid_GFDL(grdfile, name='GFDL_CM2.1_North_Pacific', \ # xrange=(80,189), yrange=(96,198)): xrange=(60,175), yrange=(120, 190)): """ Bgrd = get_nc_BGrid_GFDL(gr...
# compute mask at uv-point M_uv, L_uv = kmu.shape N_uv = z_uv.shape[0] mask_uv = np.zeros((N_uv, M_uv, L_uv)) for j in range(M_uv): for i in range(L_uv): try: mask_uv[0:kmu[j,i], j,i] = 1 except: mask_uv[:, j,i] = 0 return BGrid_...
try: mask_t[0:kmt[j,i], j,i] = 1 except: mask_t[:, j,i] = 0
conditional_block
get_nc_BGrid_GFDL.py
import numpy as np import pyroms from pyroms_toolbox.BGrid_GFDL import BGrid_GFDL def
(grdfile, name='GFDL_CM2.1_North_Pacific', \ # xrange=(80,189), yrange=(96,198)): xrange=(60,175), yrange=(120, 190)): """ Bgrd = get_nc_BGrid_GFDL(grdfile) Load B-Grid grid object for GFDL CM2.1 from netCDF grid file """ nc = pyroms.io.Data...
get_nc_BGrid_GFDL
identifier_name
simple.py
from pymander.exceptions import CantParseLine from pymander.handlers import LineHandler, RegexLineHandler, ArgparseLineHandler from pymander.contexts import StandardPrompt from pymander.commander import Commander from pymander.decorators import bind_command class DeeperLineHandler(LineHandler): def try_execute(se...
(ArgparseLineHandler): @bind_command('play', [ ['game', {'type': str, 'default': 'nothing'}], ['--well', {'action': 'store_true'}], ]) def play(self, game, well): self.context.write('I play {0}{1}\n'.format(game, ' very well' if well else '')) @bind_command('win') def win(se...
GameLineHandler
identifier_name
simple.py
from pymander.exceptions import CantParseLine from pymander.handlers import LineHandler, RegexLineHandler, ArgparseLineHandler from pymander.contexts import StandardPrompt from pymander.commander import Commander from pymander.decorators import bind_command class DeeperLineHandler(LineHandler): def try_execute(se...
raise CantParseLine(line) class RaynorLineHandler(LineHandler): def try_execute(self, line): if line.strip() == 'kerrigan': self.context.write('Oh, Sarah...\n') return raise CantParseLine(line) class BerryLineHandler(RegexLineHandler): @bind_command(r'pick a ...
random_line_split
simple.py
from pymander.exceptions import CantParseLine from pymander.handlers import LineHandler, RegexLineHandler, ArgparseLineHandler from pymander.contexts import StandardPrompt from pymander.commander import Commander from pymander.decorators import bind_command class DeeperLineHandler(LineHandler): def try_execute(se...
raise CantParseLine(line) class RaynorLineHandler(LineHandler): def try_execute(self, line): if line.strip() == 'kerrigan': self.context.write('Oh, Sarah...\n') return raise CantParseLine(line) class BerryLineHandler(RegexLineHandler): @bind_command(r'pick ...
deeper_context = self.context.clone() deeper_context.name = '{0} / ctx {1}'.format(self.context.name, id(deeper_context)) self.context.write('Going deeper!\nNow in: {0}\n'.format(deeper_context)) return deeper_context
conditional_block
simple.py
from pymander.exceptions import CantParseLine from pymander.handlers import LineHandler, RegexLineHandler, ArgparseLineHandler from pymander.contexts import StandardPrompt from pymander.commander import Commander from pymander.decorators import bind_command class DeeperLineHandler(LineHandler): def try_execute(se...
class RaynorLineHandler(LineHandler): def try_execute(self, line): if line.strip() == 'kerrigan': self.context.write('Oh, Sarah...\n') return raise CantParseLine(line) class BerryLineHandler(RegexLineHandler): @bind_command(r'pick a (?P<berry_kind>\w+)') def pic...
if line.strip() == 'deeper': deeper_context = self.context.clone() deeper_context.name = '{0} / ctx {1}'.format(self.context.name, id(deeper_context)) self.context.write('Going deeper!\nNow in: {0}\n'.format(deeper_context)) return deeper_context raise CantParseL...
identifier_body
Button.js
// @flow import React from 'react' import classNames from 'classnames' import { Link } from 'next/link' type Props = { children?: React$Element<*>, className?: ?string,
submit?: boolean } const Button = (props: Props) => { const { type, icons, submit, ...otherProps } = props const className = classNames('button', props.className, { 'is-primary': props.type === 'primary', 'is-warning': props.type === 'warning', 'is-danger': props.type === 'danger', 'is-success': ...
icons?: string, href?: ?string, type?: 'primary' | 'danger' | 'warning' | 'link' | 'close' | 'success',
random_line_split
Button.js
// @flow import React from 'react' import classNames from 'classnames' import { Link } from 'next/link' type Props = { children?: React$Element<*>, className?: ?string, icons?: string, href?: ?string, type?: 'primary' | 'danger' | 'warning' | 'link' | 'close' | 'success', submit?: boolean } const Button ...
else { return ( <button {...otherProps} className={className} type={buttonType}> { icons ? ( <span className='icon'> <i className={`fa fa-${icons}`} /> </span> ) : null } { props.children } </button> ) } } export d...
{ return ( <Link {...otherProps} className={className}> <a> { props.children } </a> </Link> ) }
conditional_block
en-us.ts
export const locale = { "default": "This field is invalid", "required": "This field is required", "date": (value: any) => `This field contains "${value}" which is not a valid date`, "decimal": (value: any) => `This field contains ${value} which is not a decimal value`, "equal": (value: any, optionsO...
import {IModelResolver} from "../resolvers/imodel-resolver";
random_line_split
CCLoaders.js
/**************************************************************************** Copyright (c) 2011-2012 cocos2d-x.org Copyright (c) 2013-2014 Chukong Technologies Inc. http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation...
} }; cc.loader.register(["font", "eot", "ttf", "woff", "svg", "ttc"], cc._fontLoader); cc._binaryLoader = { load : function(realUrl, url, res, cb){ cc.loader.loadBinary(realUrl, cb); } }; cc._csbLoader = { load: function(realUrl, url, res, cb){ cc.loader.loadCsb(realUrl, cb); } };...
{ cb(null, true); }
conditional_block
CCLoaders.js
/**************************************************************************** Copyright (c) 2011-2012 cocos2d-x.org Copyright (c) 2013-2014 Chukong Technologies Inc. http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation...
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONN...
all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
random_line_split
Data.ts
import * as d3 from 'd3'; import * as Factory from '../factories/_index'; import * as Options from '../options/_index'; import { IPoint } from './IPoint'; import { Dataset } from './Dataset'; export class Data { public sets: any; constructor(js: any) { if (js) { this.fromJS(js); } } fromJS(j...
} }
}) );
random_line_split
Data.ts
import * as d3 from 'd3'; import * as Factory from '../factories/_index'; import * as Options from '../options/_index'; import { IPoint } from './IPoint'; import { Dataset } from './Dataset'; export class Data { public sets: any; constructor(js: any) { if (js) { this.fromJS(js); } } fromJS(j...
} this.sets = sets; } getDatasets(series: Options.ISeriesOptions[], options: Options.Options): IPoint[][] { return series.map((d: Options.ISeriesOptions) => this.getDatasetValues(d, options)); } getDatasetValues(series: Options.ISeriesOptions, options: Options.Options): IPoint[] { if (!this....
{ sets[key] = new Dataset(js[key], key); }
conditional_block
Data.ts
import * as d3 from 'd3'; import * as Factory from '../factories/_index'; import * as Options from '../options/_index'; import { IPoint } from './IPoint'; import { Dataset } from './Dataset'; export class Data { public sets: any; constructor(js: any) { if (js) { this.fromJS(js); } }
(js: any) { var sets = {}; for (var key in js) { if (js.hasOwnProperty(key)) { sets[key] = new Dataset(js[key], key); } } this.sets = sets; } getDatasets(series: Options.ISeriesOptions[], options: Options.Options): IPoint[][] { return series.map((d: Options.ISeriesOptions) ...
fromJS
identifier_name
miniboa.py
INARY", ECHO: "ECHO", RECON: "RECON", SGA: "SGA", TTYPE: "TTYPE", NAWS: "NAWS", LINEMODE: "LINEMODE", } class ConnectionLost(Exception): """Custom exception to signal a lost connection to the Telnet Server.""" pass def strip_caret_codes(text): """Strip out any caret codes from a ...
(self): """Tell the client that we would like to echo their text. See RFC 857. """ self._iac_will(ECHO) self._note_reply_pending(ECHO, True) self.telnet_echo = True def request_wont_echo(self): """Tell the client that we would like to stop echoing their tex...
request_will_echo
identifier_name
miniboa.py
:returns str: The found command or None """ cmd = None count = len(self.command_list) if count > 0: cmd = self.command_list.pop(0) # If that was the last line, turn off lines_pending if count == 1: self.cmd_ready = False return cmd d...
random_line_split
miniboa.py
INARY", ECHO: "ECHO", RECON: "RECON", SGA: "SGA", TTYPE: "TTYPE", NAWS: "NAWS", LINEMODE: "LINEMODE", } class ConnectionLost(Exception): """Custom exception to signal a lost connection to the Telnet Server.""" pass def strip_caret_codes(text): """Strip out any caret codes from a ...
def request_will_echo(self): """Tell the client that we would like to echo their text. See RFC 857. """ self._iac_will(ECHO) self._note_reply_pending(ECHO, True) self.telnet_echo = True def request_wont_echo(self): """Tell the client that we would lik...
"""Request client to Suppress Go-Ahead. See RFC 858. """ self._iac_do(SGA) self._note_reply_pending(SGA, True)
identifier_body
miniboa.py
, in seconds """ return time.time() - self.connect_time def request_do_sga(self): """Request client to Suppress Go-Ahead. See RFC 858. """ self._iac_do(SGA) self._note_reply_pending(SGA, True) def request_will_echo(self): """Tell the client th...
if self._check_local_option(option) is UNKNOWN: self._note_local_option(option, False) self._iac_wont(option)
conditional_block
dependencyHighlighter.js
/** * User: Jomaras * Date: 26.09.12. * Time: 17:24 */ FBL.ns(function() { with (FBL) { /*************************************************************************************/ Firecrow.DependencyGraph.DependencyHighlighter = function(htmlContainer, dependencyGraph) { (function establishConnection() ...
(className) { var elements = htmlContainer.querySelectorAll("." + className); for(var i = 0; i < elements.length; i++) { elements[i].classList.remove(className); } } var codeElements = htmlContainer.querySelectorAll(".node"); for(var i = 0, leng...
removeClass
identifier_name
dependencyHighlighter.js
/** * User: Jomaras * Date: 26.09.12. * Time: 17:24 */ FBL.ns(function() { with (FBL) { /*************************************************************************************/ Firecrow.DependencyGraph.DependencyHighlighter = function(htmlContainer, dependencyGraph) { (function establishConnection() ...
var codeElements = htmlContainer.querySelectorAll(".node"); for(var i = 0, length = codeElements.length; i < length; i++) { codeElements[i].onclick = function(eventArgs) { if(this.id.indexOf("node") == 0) { eventArgs.stopPropagation(); ...
{ var elements = htmlContainer.querySelectorAll("." + className); for(var i = 0; i < elements.length; i++) { elements[i].classList.remove(className); } }
identifier_body
dependencyHighlighter.js
/** * User: Jomaras * Date: 26.09.12. * Time: 17:24 */ FBL.ns(function() { with (FBL) { /*************************************************************************************/ Firecrow.DependencyGraph.DependencyHighlighter = function(htmlContainer, dependencyGraph) { (function establishConnection() ...
var dependencies = modelNode.graphNode.dataDependencies; for(var j = 0, jLength = dependencies.length; j < jLength; j++) { var dependent = dependencies[j]; var htmlDependent = htmlContainer.querySelector("#node" + FBL.Firecr...
{ return; }
conditional_block
dependencyHighlighter.js
/** * User: Jomaras * Date: 26.09.12. * Time: 17:24 */ FBL.ns(function() { with (FBL) { /*************************************************************************************/ Firecrow.DependencyGraph.DependencyHighlighter = function(htmlContainer, dependencyGraph) { (function establishConnection() ...
if(modelNode == null) { return; } var dependencies = modelNode.graphNode.dataDependencies; for(var j = 0, jLength = dependencies.length; j < jLength; j++) { var dependent = dependencies[j]; var htmlDependent...
var modelNode = this.model;
random_line_split
errorHandler.ts
/**
await next(); } catch (err) { // 所有的异常都在 app 上触发一个 error 事件,框架会记录一条错误日志 ctx.app.emit('error', err, ctx); const code = parseInt(err.code) || -1; const status = err.status || (code >= 0 ? 400 : 500); // 生产环境时 500 错误的详细错误内容不返回给客户端,因为可能包含敏感信息 const error = status === 500 && c...
* 错误处理中间件 */ export default () => { return async function errorHandler(ctx, next) { try {
random_line_split
errorHandler.ts
/** * 错误处理中间件 */ export default () => { return async function errorHandler(ctx, next) { try { await next(); } catch (err) { // 所有的异常都在 app 上触发一个 error 事件,框架会记录一条错误日志 ctx.app.emit('error', err, ctx); const code = parseInt(err.code) || -1; const status = err.status || (code >= 0...
conditional_block
animation.py
#!/usr/bin/python # -*- coding: utf-8 -*- __author__ = "Stefan Mauerberger" __copyright__ = "Copyright (C) 2017 Stefan Mauerberger" __license__ = "GPLv3" import numpy as np from sys import stdout from matplotlib import pyplot as plt from matplotlib import animation from plotting import prepare_map, lllat, lllon,...
return tpc_mu, tpc_sd frames = mu_C.shape[0] duration = 30. # s interval = 1000.*duration/frames # ms anim = animation.FuncAnimation(fig, animate, save_count=0, \ frames=frames, interval=interval, blit=False) # Save video anim.save('../animation.avi', dpi=dpi, extra_args=['-vcod...
stdout.write('\n')
conditional_block
animation.py
#!/usr/bin/python # -*- coding: utf-8 -*- __author__ = "Stefan Mauerberger" __copyright__ = "Copyright (C) 2017 Stefan Mauerberger" __license__ = "GPLv3" import numpy as np from sys import stdout from matplotlib import pyplot as plt from matplotlib import animation from plotting import prepare_map, lllat, lllon,...
global mu_C, cov_CC tpc_mu.set_array(mu_C[i,:]) tpc_sd.set_array(sd_C[i,:]) # Screen output; a very basic progress bar p = int(100.*(i+1)/mu_C.shape[0]) # Progress stdout.write('\r[' + p*'#' + (100-p)*'-' + '] %3i' % p + '%' ) if (i+1) == mu_C.shape[0]: stdout.write('\n') retur...
# First frame; Necessary for LaTeX beamer plt.savefig('../animation_pri.png', dpi=dpi) def animate(i):
random_line_split
animation.py
#!/usr/bin/python # -*- coding: utf-8 -*- __author__ = "Stefan Mauerberger" __copyright__ = "Copyright (C) 2017 Stefan Mauerberger" __license__ = "GPLv3" import numpy as np from sys import stdout from matplotlib import pyplot as plt from matplotlib import animation from plotting import prepare_map, lllat, lllon,...
frames = mu_C.shape[0] duration = 30. # s interval = 1000.*duration/frames # ms anim = animation.FuncAnimation(fig, animate, save_count=0, \ frames=frames, interval=interval, blit=False) # Save video anim.save('../animation.avi', dpi=dpi, extra_args=['-vcodec', 'msmpeg4v2']) # Last ...
global mu_C, cov_CC tpc_mu.set_array(mu_C[i,:]) tpc_sd.set_array(sd_C[i,:]) # Screen output; a very basic progress bar p = int(100.*(i+1)/mu_C.shape[0]) # Progress stdout.write('\r[' + p*'#' + (100-p)*'-' + '] %3i' % p + '%' ) if (i+1) == mu_C.shape[0]: stdout.write('\n') return tp...
identifier_body
animation.py
#!/usr/bin/python # -*- coding: utf-8 -*- __author__ = "Stefan Mauerberger" __copyright__ = "Copyright (C) 2017 Stefan Mauerberger" __license__ = "GPLv3" import numpy as np from sys import stdout from matplotlib import pyplot as plt from matplotlib import animation from plotting import prepare_map, lllat, lllon,...
(i): global mu_C, cov_CC tpc_mu.set_array(mu_C[i,:]) tpc_sd.set_array(sd_C[i,:]) # Screen output; a very basic progress bar p = int(100.*(i+1)/mu_C.shape[0]) # Progress stdout.write('\r[' + p*'#' + (100-p)*'-' + '] %3i' % p + '%' ) if (i+1) == mu_C.shape[0]: stdout.write('\n') ...
animate
identifier_name
ObjectSeq.ts
///<reference path='../resources/jest.d.ts'/> ///<reference path='../dist/immutable.d.ts'/> jest.autoMockOff(); import { Seq } from 'immutable'; describe('ObjectSequence', () => { it('maps', () => { var i = Seq({'a': 'A', 'b': 'B', 'c': 'C'}); var m = i.map(x => x + x).toObject(); expect(m).toEqual({'...
expect(entries.next()).toEqual({ value: undefined, done: true }); }); it('cannot be mutated after calling toObject', () => { var seq = Seq({ a: 1, b: 2, c: 3 }); var obj = seq.toObject(); obj['c'] = 10; var seq2 = Seq(obj); expect(seq.get('c')).toEqual(3); expect(seq2.get('c')).toEqua...
random_line_split
reducer.d.ts
import { Reducer } from "redux"; import { FieldType } from "../index"; export interface FormReducer extends Reducer<FormStateMap> { plugin(reducers: FormReducerMapObject): Reducer<FormStateMap>; } export const reducer: FormReducer; export interface FormReducerMapObject { // and `<any>` to make it compatible ...
export interface FieldState { active?: boolean; touched?: boolean; visited?: boolean; } export default reducer;
type: FieldType; count: number; }
random_line_split
async-test.ts
(function() { class AsyncTestZoneSpec implements ZoneSpec { _finishCallback: Function; _failCallback: Function; _pendingMicroTasks: boolean = false; _pendingMacroTasks: boolean = false; _alreadyErrored: boolean = false; runZone = Zone.current; constructor(finishCallback: Function, failCal...
(parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, delegate: Function, applyThis: any, applyArgs: any[], source: string): any { try { return parentZoneDelegate.invoke(targetZone, delegate, applyThis, applyArgs, source); } finally { this._finishCallbackIfDone(); ...
onInvoke
identifier_name
async-test.ts
(function() { class AsyncTestZoneSpec implements ZoneSpec { _finishCallback: Function; _failCallback: Function; _pendingMicroTasks: boolean = false; _pendingMacroTasks: boolean = false; _alreadyErrored: boolean = false; runZone = Zone.current; constructor(finishCallback: Function, failCal...
_finishCallbackIfDone() { if (!(this._pendingMicroTasks || this._pendingMacroTasks)) { // We do this because we would like to catch unhandled rejected promises. this.runZone.run(() => { setTimeout(() => { if (!this._alreadyErrored && !(this._pendingMicroTasks || this._p...
{ this._finishCallback = finishCallback; this._failCallback = failCallback; this.name = 'asyncTestZone for ' + namePrefix; }
identifier_body
async-test.ts
(function() { class AsyncTestZoneSpec implements ZoneSpec { _finishCallback: Function; _failCallback: Function; _pendingMicroTasks: boolean = false; _pendingMacroTasks: boolean = false; _alreadyErrored: boolean = false; runZone = Zone.current; constructor(finishCallback: Function, failCal...
} } // Export the class so that new instances can be created with proper // constructor params. Zone['AsyncTestZoneSpec'] = AsyncTestZoneSpec; })();
}
random_line_split
async-test.ts
(function() { class AsyncTestZoneSpec implements ZoneSpec { _finishCallback: Function; _failCallback: Function; _pendingMicroTasks: boolean = false; _pendingMacroTasks: boolean = false; _alreadyErrored: boolean = false; runZone = Zone.current; constructor(finishCallback: Function, failCal...
return delegate.scheduleTask(targetZone, task); } onHasTask(delegate: ZoneDelegate, current: Zone, target: Zone, hasTaskState: HasTaskState) { delegate.hasTask(target, hasTaskState); if (hasTaskState.change == 'microTask') { this._pendingMicroTasks = hasTaskState.microTask; ...
{ this._failCallback('Cannot use setInterval from within an async zone test.'); return; }
conditional_block
progressbardemo.ts
import {Component,OnInit} from '@angular/core'; import {Messages} from '../../../components/messages/messages'; import {TabView} from '../../../components/tabview/tabview'; import {TabPanel} from '../../../components/tabview/tabpanel'; import {ProgressBar} from '../../../components/progressbar/progressbar'; import {Cod...
} }, 2000); } }
this.value = 100; this.msgs = [{severity: 'info', summary: 'Success', detail: 'Process Completed'}]; clearInterval(interval);
random_line_split
progressbardemo.ts
import {Component,OnInit} from '@angular/core'; import {Messages} from '../../../components/messages/messages'; import {TabView} from '../../../components/tabview/tabview'; import {TabPanel} from '../../../components/tabview/tabpanel'; import {ProgressBar} from '../../../components/progressbar/progressbar'; import {Cod...
}, 2000); } }
{ this.value = 100; this.msgs = [{severity: 'info', summary: 'Success', detail: 'Process Completed'}]; clearInterval(interval); }
conditional_block
progressbardemo.ts
import {Component,OnInit} from '@angular/core'; import {Messages} from '../../../components/messages/messages'; import {TabView} from '../../../components/tabview/tabview'; import {TabPanel} from '../../../components/tabview/tabpanel'; import {ProgressBar} from '../../../components/progressbar/progressbar'; import {Cod...
}
{ let interval = setInterval(() => { this.value = this.value + Math.floor(Math.random() * 10) + 1; if(this.value >= 100) { this.value = 100; this.msgs = [{severity: 'info', summary: 'Success', detail: 'Process Completed'}]; clearInterval(in...
identifier_body
progressbardemo.ts
import {Component,OnInit} from '@angular/core'; import {Messages} from '../../../components/messages/messages'; import {TabView} from '../../../components/tabview/tabview'; import {TabPanel} from '../../../components/tabview/tabpanel'; import {ProgressBar} from '../../../components/progressbar/progressbar'; import {Cod...
{ value: number = 0; msgs: Message[]; ngOnInit() { let interval = setInterval(() => { this.value = this.value + Math.floor(Math.random() * 10) + 1; if(this.value >= 100) { this.value = 100; this.msgs = [{severity: 'info', summary: 'Success'...
ProgressBarDemo
identifier_name
admin.py
from __future__ import unicode_literals from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.comments.models import Comment from django.utils.translation import ugettext_lazy as _, ungettext_lazy from django.contrib.comments import get_model from django.contrib.comments.v...
remove_comments.short_description = _("Remove selected comments") def _bulk_flag(self, request, queryset, action, done_message): """ Flag, approve, or remove some comments from an admin action. Actually calls the `action` argument to perform the heavy lifting. """ n_com...
self._bulk_flag(request, queryset, perform_delete, ungettext_lazy('%d comment was successfully removed', '%d comments were successfully removed'))
identifier_body
admin.py
from __future__ import unicode_literals from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.comments.models import Comment from django.utils.translation import ugettext_lazy as _, ungettext_lazy from django.contrib.comments import get_model from django.contrib.comments.v...
""" def __str__(self): return 'user__%s' % get_user_model().USERNAME_FIELD class CommentsAdmin(admin.ModelAdmin): fieldsets = ( (None, {'fields': ('content_type', 'object_pk', 'site')} ), (_('Content'), {'fields': ('user', 'user_name', 'user_email', 'u...
class UsernameSearch(object): """The User object may not be auth.User, so we need to provide a mechanism for issuing the equivalent of a .filter(user__username=...) search in CommentAdmin.
random_line_split
admin.py
from __future__ import unicode_literals from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.comments.models import Comment from django.utils.translation import ugettext_lazy as _, ungettext_lazy from django.contrib.comments import get_model from django.contrib.comments.v...
if 'remove_comments' in actions: actions.pop('remove_comments') return actions def flag_comments(self, request, queryset): self._bulk_flag(request, queryset, perform_flag, ungettext_lazy('%d comment was successfully flagged', ...
actions.pop('approve_comments')
conditional_block
admin.py
from __future__ import unicode_literals from django.contrib import admin from django.contrib.auth import get_user_model from django.contrib.comments.models import Comment from django.utils.translation import ugettext_lazy as _, ungettext_lazy from django.contrib.comments import get_model from django.contrib.comments.v...
(self, request, queryset, action, done_message): """ Flag, approve, or remove some comments from an admin action. Actually calls the `action` argument to perform the heavy lifting. """ n_comments = 0 for comment in queryset: action(request, comment) ...
_bulk_flag
identifier_name
utils.py
# -*- coding: utf-8 -*- """Utility functions. """ from collections import OrderedDict from .bsd_checksum import bsd_checksum # make name available from this module def n_(s, replacement='_'):
def split_string(s, *ndxs): """String sub-class with a split() method that splits a given indexes. Usage: >>> print split_string('D2008022002', 1, 5, 7, 9) ['D', '2008', '02', '20', '02'] """ if len(ndxs) == 0: return [s] if len(ndxs) == 1: i = ndxs[0] ...
"""Make binary fields more readable. """ if isinstance(s, (str, unicode, bytearray)): return s.replace('\0', replacement) return s
identifier_body
utils.py
# -*- coding: utf-8 -*- """Utility functions. """ from collections import OrderedDict from .bsd_checksum import bsd_checksum # make name available from this module def n_(s, replacement='_'): """Make binary fields more readable. """ if isinstance(s, (str, unicode, bytearray)): return s.replace('...
res = [] b = 0 while ndxs: a, b, ndxs = b, ndxs[0], ndxs[1:] res.append(s[a:b]) res.append(s[b:]) return res def split_fields(s, sizes): """Split a string into fields based on field `sizes`. """ slen = len(s) if None in sizes: nonesize = slen - sum(v for ...
i = ndxs[0] return [s[:i], s[i:]]
conditional_block
utils.py
# -*- coding: utf-8 -*- """Utility functions. """ from collections import OrderedDict from .bsd_checksum import bsd_checksum # make name available from this module def
(s, replacement='_'): """Make binary fields more readable. """ if isinstance(s, (str, unicode, bytearray)): return s.replace('\0', replacement) return s def split_string(s, *ndxs): """String sub-class with a split() method that splits a given indexes. Usage: >>> print sp...
n_
identifier_name
utils.py
# -*- coding: utf-8 -*- """Utility functions. """ from collections import OrderedDict from .bsd_checksum import bsd_checksum # make name available from this module def n_(s, replacement='_'): """Make binary fields more readable. """ if isinstance(s, (str, unicode, bytearray)):
"""String sub-class with a split() method that splits a given indexes. Usage: >>> print split_string('D2008022002', 1, 5, 7, 9) ['D', '2008', '02', '20', '02'] """ if len(ndxs) == 0: return [s] if len(ndxs) == 1: i = ndxs[0] return [s[:i], s[i:]] ...
return s.replace('\0', replacement) return s def split_string(s, *ndxs):
random_line_split
arena.py
#!/usr/bin/python # -*- coding: utf-8 -*- ''' PyChess arena tournament script. This script executes a tournament between the engines installed on your system. The script is executed from a terminal with the usual environment. ''' import os import sys ######################################################...
elif results[i][j] == WHITEWON: print("1-0", end=' ') elif results[i][j] == BLACKWON: print("0-1", end=' ') else: print(" . ", end=' ') print() def printResults(): scores = [] for i in range(len(engines)): points = sum(2 for j in range(len(engines)) if results...
print("½-½", end=' ')
conditional_block
arena.py
#!/usr/bin/python # -*- coding: utf-8 -*- ''' PyChess arena tournament script. This script executes a tournament between the engines installed on your system. The script is executed from a terminal with the usual environment. ''' import os import sys ######################################################...
(discoverer, binnames): print("Wait a moment while we discover %d engines" % len(binnames)) def cb_gotone (discoverer, binname, engine): sys.stdout.write(".") ############################################################################### # Ask the user for details engines = [] results = [] minutes = 0 curren...
cb_started
identifier_name
arena.py
#!/usr/bin/python # -*- coding: utf-8 -*- ''' PyChess arena tournament script. This script executes a tournament between the engines installed on your system. The script is executed from a terminal with the usual environment. ''' import os import sys ######################################################...
print("[%s] %s" % (name[:3], name)) print("The total amount of fights will be %d" % (n*(n-1))) print() minutes = int(input("Please enter the clock minutes for each game [n]: ")) print("The games will last up to %d minutes." % (2*n*(n-1)*minutes)) print("You will be informed of the progress a...
for i, engine in enumerate(engines): name = discoverer.getName(engine)
random_line_split
arena.py
#!/usr/bin/python # -*- coding: utf-8 -*- ''' PyChess arena tournament script. This script executes a tournament between the engines installed on your system. The script is executed from a terminal with the usual environment. ''' import os import sys ######################################################...
def cb_started(discoverer, binnames): print("Wait a moment while we discover %d engines" % len(binnames)) def cb_gotone (discoverer, binname, engine): sys.stdout.write(".") ############################################################################### # Ask the user for details engines = [] results = [] mi...
print("Discovering engines", end=' ') discoverer.connect('discovering_started', cb_started) discoverer.connect('engine_discovered', cb_gotone) discoverer.connect('all_engines_discovered', start) discoverer.discover()
identifier_body
file_reader_spout.ts
import * as intf from "../topology_interfaces"; import * as fs from "fs"; import * as rl from "readline"; import * as log from "../util/logger"; import { Utils, CsvParser } from "./parsing_utils"; const high_water = 5000; const low_water = 50; /** This spout reads input file in several supported formats and emits tup...
const data = this.tuples[0]; this.tuples = this.tuples.slice(1); setImmediate(() => { callback(null, data, this.stream_id); }); } }
{ return callback(null, null, null); }
conditional_block
file_reader_spout.ts
import * as intf from "../topology_interfaces"; import * as fs from "fs"; import * as rl from "readline"; import * as log from "../util/logger"; import { Utils, CsvParser } from "./parsing_utils"; const high_water = 5000; const low_water = 50; /** This spout reads input file in several supported formats and emits tup...
Utils.readRawFile(line, this.tuples); } if (this.tuples.length > high_water && !this.line_reader_paused) { this.line_reader.pause(); this.line_reader_paused = true; } }); this.line_reader.on("close", () => { ...
{ this.stream_id = config.stream_id; this.file_name = config.file_name; this.file_format = config.file_format || "json"; this.tuples = []; if (this.file_format == "csv") { config.separator = config.separator || ","; this.csv_parser = new CsvParser(config);...
identifier_body
file_reader_spout.ts
import * as intf from "../topology_interfaces"; import * as fs from "fs"; import * as rl from "readline"; import * as log from "../util/logger"; import { Utils, CsvParser } from "./parsing_utils"; const high_water = 5000; const low_water = 50; /** This spout reads input file in several supported formats and emits tup...
implements intf.ISpout { private stream_id: string; private file_format: string; private file_name: string; private csv_parser: CsvParser; private tuples: any[]; private should_run: boolean; private line_reader: rl.ReadLine; private line_reader_paused: boolean; private own_exit: bo...
FileReaderSpout
identifier_name
file_reader_spout.ts
import * as intf from "../topology_interfaces"; import * as fs from "fs"; import * as rl from "readline"; import * as log from "../util/logger"; import { Utils, CsvParser } from "./parsing_utils"; const high_water = 5000; const low_water = 50; /** This spout reads input file in several supported formats and emits tup...
public run() { this.should_run = true; } public pause() { this.should_run = false; } public next(callback: intf.SpoutNextCallback) { if (!this.should_run) { return callback(null, null, null); } if (this.tuples.length < low_water && this.line_read...
}
random_line_split
lib.rs
//! // Then pass it into pipeline builder //! let tracer = opentelemetry_otlp::new_pipeline() //! .tracing() //! .with_exporter(otlp_exporter) //! .install_simple()?; //! //! tracer.in_span("doing_work", |cx| { //! // Traced app logic here... //! }); //! //! ...
} /// Create a new pipeline builder with the recommended configuration. /// /// ## Examples /// /// ```no_run /// fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync +
{ HttpExporterBuilder::default() }
identifier_body
lib.rs
ampler::AlwaysOn) //! .with_id_generator(RandomIdGenerator::default()) //! .with_max_events_per_span(64) //! .with_max_attributes_per_span(16) //! .with_max_events_per_span(16) //! .with_resource(Resource::new(vec![KeyValue::new("service.na...
{ "".to_string() }
conditional_block
lib.rs
timeout: Duration::from_secs(3), //! protocol: Protocol::Grpc //! }; //! //! let meter = opentelemetry_otlp::new_pipeline() //! .metrics(tokio::spawn, tokio_interval_stream) //! .with_exporter( //! opentelemetry_otlp::new_exporter() //! .tonic() //! ...
to_nanos
identifier_name
lib.rs
//! Prometheus, etc.) sending to multiple open-source or commercial back-ends. //! //! Currently, this crate only support sending tracing data or metrics in OTLP //! via grpc and http(in binary format). Supports for other format and protocol //! will be added in the future. The details of what's currently offering in t...
//! to receive, process, and export telemetry data. In addition, it removes //! the need to run, operate, and maintain multiple agents/collectors in //! order to support open-source telemetry data formats (e.g. Jaeger,
random_line_split
webpack.config.js
const path = require('path');
// env const buildDirectory = './dist/'; module.exports = { entry: './lib/main.jsx', devServer: { hot: true, inline: true, port: 7700, historyApiFallback: true, }, resolve: { extensions: ['*', '.js', '.jsx'], }, output: { path: path.resolve(buildDirectory), filename: 'app.js', ...
const webpack = require('webpack');
random_line_split
train_simple_network.py
import os import argparse import datetime import yaml import api.src.common.initial_environment_config from ..models.dense import create_model from ..data_processing.data_generator import DataGenerator from ..common.config import TrainingConfig, DataConfig, Config from ..common.utils import print_info, ensure_dir from...
if __name__ == '__main__': argparser = argparse.ArgumentParser(description='Script performing training') argparser.add_argument('--num_epochs', default=TrainingConfig.NB_EPOCHS, type=int, help='Number of training epochs') argparser.add_argument('--num_workers', type=int, default=TrainingConfig.NUM_WORKER...
print_info("Training") train(args.num_epochs, args.batch_size, args.input_size, args.num_workers) print_info("Finished")
identifier_body
train_simple_network.py
import os import argparse import datetime import yaml import api.src.common.initial_environment_config from ..models.dense import create_model from ..data_processing.data_generator import DataGenerator from ..common.config import TrainingConfig, DataConfig, Config from ..common.utils import print_info, ensure_dir from...
(args): print_info("Training") train(args.num_epochs, args.batch_size, args.input_size, args.num_workers) print_info("Finished") if __name__ == '__main__': argparser = argparse.ArgumentParser(description='Script performing training') argparser.add_argument('--num_epochs', default=TrainingConfig.NB...
main
identifier_name
train_simple_network.py
import os import argparse import datetime import yaml import api.src.common.initial_environment_config from ..models.dense import create_model from ..data_processing.data_generator import DataGenerator from ..common.config import TrainingConfig, DataConfig, Config from ..common.utils import print_info, ensure_dir from...
callbacks = [ ModelCheckpoint(os.path.join(TrainingConfig.PATHS['MODELS'], RUNNING_TIME, 'weights.h5'), save_best_only=True, monitor=TrainingConfig.callbacks_monitor), CSVLogger(os.path.join(TrainingConfig.PATHS['MODELS'], RUNNING_TIME, 'history.csv')), LearningRateScheduler(TrainingConfig.s...
def train(num_epochs, batch_size, input_size, num_workers): if not Config.NO_SAVE: ensure_dir(os.path.join(TrainingConfig.PATHS['MODELS'], RUNNING_TIME)) model = create_model((2592,))
random_line_split
train_simple_network.py
import os import argparse import datetime import yaml import api.src.common.initial_environment_config from ..models.dense import create_model from ..data_processing.data_generator import DataGenerator from ..common.config import TrainingConfig, DataConfig, Config from ..common.utils import print_info, ensure_dir from...
model = create_model((2592,)) callbacks = [ ModelCheckpoint(os.path.join(TrainingConfig.PATHS['MODELS'], RUNNING_TIME, 'weights.h5'), save_best_only=True, monitor=TrainingConfig.callbacks_monitor), CSVLogger(os.path.join(TrainingConfig.PATHS['MODELS'], RUNNING_TIME, 'history.csv')), Le...
ensure_dir(os.path.join(TrainingConfig.PATHS['MODELS'], RUNNING_TIME))
conditional_block
mpe.ts
import { ModuleTitle, ModuleCode } from './modules';
export type MpePreference = { rank?: number; moduleTitle?: ModuleTitle; moduleCredits?: number; moduleCode: ModuleCode; moduleType: '01' | '02' | '03' | '04'; }; export type MpeSubmission = { nusExchangeId?: string; intendedMCs: number; preferences: Array<MpePreference>; }; export type MpeModule = { ...
random_line_split
nb.js
not move \"{file}\", target exists" : "Klarte ikke å flytte \"{file}\", målfilen finnes", "Could not move \"{file}\"" : "Klarte ikke å flytte \"{file}\"", "No compatible server found at {remote}" : "Ingen kompatibel tjener ble funnet på {remote}", "Invalid server url" : "Ugyldig tjeneradresse", "Could ...
"Play" : "Spill", "Pause" : "Pause", "Previous" : "Forrige", "Close" : "Lukk", "Download" : "Last ned", "Toggle background" : "Bytt bakgrunn", "Delete" : "Slett", "Share" : "Del", "Could not create file \"{file}\" because it already exists" : "Klarte ikke å opprette fil \"{file}\" fo...
"Hide Album" : "Skjul album", "Could not hide album" : "Kunne ikke skjule album", "Error loading slideshow template" : "Feil ved lasting av mal for lysbildevisning", "<strong>Error!</strong> Could not generate a preview of this file.<br>Please go to the next slide while we remove this image from the sli...
random_line_split
mac_producer.py
import os import json import time import threading import requests class MAC_Map: def __init__(self): self.lock = threading.Lock() self.mac_producer = {} self._read_mac_producer_table() @staticmethod def _load_broken_json(self, text): if text[0] != '{': raise Va...
producer = self._get_producer_online(mac_prefix + ':22:22:22') self.lock.acquire() self.mac_producer[mac_prefix] = producer self.save() self.lock.release() def save(self): with open('./mac_producer.txt', 'w', encoding='utf-8') as f: for mac_pre in self.m...
return
conditional_block
mac_producer.py
import os import json import time import threading import requests class MAC_Map: def __init__(self): self.lock = threading.Lock() self.mac_producer = {} self._read_mac_producer_table() @staticmethod def _load_broken_json(self, text): if text[0] != '{': raise Va...
try: response = json.loads(r.text) break except json.JSONDecodeError as e: try: response = self._load_broken_json(r.text) break except ValueError: return 'Null' if ...
print(e) except requests.ConnectTimeout as e: print(e) print("Please Check the network condition")
random_line_split
mac_producer.py
import os import json import time import threading import requests class
: def __init__(self): self.lock = threading.Lock() self.mac_producer = {} self._read_mac_producer_table() @staticmethod def _load_broken_json(self, text): if text[0] != '{': raise ValueError() left_num, end = 1, 0 for i in range(1, len(text)): ...
MAC_Map
identifier_name
mac_producer.py
import os import json import time import threading import requests class MAC_Map: def __init__(self): self.lock = threading.Lock() self.mac_producer = {} self._read_mac_producer_table() @staticmethod def _load_broken_json(self, text): if text[0] != '{': raise Va...
return response['result']['mac_producer'] else: return 'Null' def find_producer_online(self, mac_prefix): if mac_prefix in self.mac_producer: return producer = self._get_producer_online(mac_prefix + ':22:22:22') self.lock.acquire() self.m...
while True: try: r = requests.get( "http://www.imfirewall.com/ip-mac-lookup/get_mac_info.php?mac=%s&_=%d" % (mac, int(time.time() * 1000)) ) except requests.ConnectionError as e: print(e) except requests.ConnectTimeo...
identifier_body
export_fragments.py
# -*- coding: utf-8 -*- from django.core.management.base import BaseCommand, CommandError from annotations.models import Corpus from annotations.exports import export_fragments from core.utils import CSV, XLSX class Command(BaseCommand): help = 'Exports existing Fragments for the given Corpus and Languages' ...
(self, *args, **options): # Retrieve the Corpus from the database try: corpus = Corpus.objects.get(title=options['corpus']) except Corpus.DoesNotExist: raise CommandError('Corpus with title {} does not exist'.format(options['corpus'])) format_ = XLSX if options['...
handle
identifier_name
export_fragments.py
# -*- coding: utf-8 -*- from django.core.management.base import BaseCommand, CommandError from annotations.models import Corpus from annotations.exports import export_fragments from core.utils import CSV, XLSX class Command(BaseCommand): help = 'Exports existing Fragments for the given Corpus and Languages' ...
raise CommandError('Language {} does not exist'.format(language)) filename = 'fragments_{lang}.{ext}'.format(lang=language, ext=format_) export_fragments(filename, format_, corpus, language, document=options['document'], ...
raise CommandError('Corpus with title {} does not exist'.format(options['corpus'])) format_ = XLSX if options['format_xlsx'] else CSV for language in options['languages']: if not corpus.languages.filter(iso=language):
random_line_split
export_fragments.py
# -*- coding: utf-8 -*- from django.core.management.base import BaseCommand, CommandError from annotations.models import Corpus from annotations.exports import export_fragments from core.utils import CSV, XLSX class Command(BaseCommand): help = 'Exports existing Fragments for the given Corpus and Languages' ...
filename = 'fragments_{lang}.{ext}'.format(lang=language, ext=format_) export_fragments(filename, format_, corpus, language, document=options['document'], add_lemmata=options['add_lemmata'], add_indices=opti...
raise CommandError('Language {} does not exist'.format(language))
conditional_block
export_fragments.py
# -*- coding: utf-8 -*- from django.core.management.base import BaseCommand, CommandError from annotations.models import Corpus from annotations.exports import export_fragments from core.utils import CSV, XLSX class Command(BaseCommand): help = 'Exports existing Fragments for the given Corpus and Languages' ...
try: corpus = Corpus.objects.get(title=options['corpus']) except Corpus.DoesNotExist: raise CommandError('Corpus with title {} does not exist'.format(options['corpus'])) format_ = XLSX if options['format_xlsx'] else CSV for language in options['languages']: i...
identifier_body
paramify.js
afe'); /* * Internal functions */ // Returns sections of the comment header grouped by new-lines function
(string) { let stringBlocks = string.split(/(?:\r\n|\r|\n){3,}/gm); // We don't want the comment notations in the blocks stringBlocks = stringBlocks.map(block => { return block .replace('/*{', '') .replace('}*/', ''); }); // Remove empty blocks stringBlocks = st...
makeStringBlocks
identifier_name
paramify.js
/safe'); /* * Internal functions */ // Returns sections of the comment header grouped by new-lines
stringBlocks = stringBlocks.map(block => { return block .replace('/*{', '') .replace('}*/', ''); }); // Remove empty blocks stringBlocks = stringBlocks.filter(block => { return block !== ''; }); // Sort into keyed and unkeyed parameters const isExpl...
function makeStringBlocks(string) { let stringBlocks = string.split(/(?:\r\n|\r|\n){3,}/gm); // We don't want the comment notations in the blocks
random_line_split
paramify.js
afe'); /* * Internal functions */ // Returns sections of the comment header grouped by new-lines function makeStringBlocks(string) { let stringBlocks = string.split(/(?:\r\n|\r|\n){3,}/gm); // We don't want the comment notations in the blocks stringBlocks = stringBlocks.map(block => { return...
// Default values for types function getDefault(type) { switch(type) { case 'string': return ''; case 'number': return 0; case 'boolean': return false; case 'color': return '#000'; case 'array': return []; ...
{ return string.replace(/^([?@]+)|(:\s)+$|[?]/g, '').toLowerCase(); }
identifier_body
paramify.js
afe'); /* * Internal functions */ // Returns sections of the comment header grouped by new-lines function makeStringBlocks(string) { let stringBlocks = string.split(/(?:\r\n|\r|\n){3,}/gm); // We don't want the comment notations in the blocks stringBlocks = stringBlocks.map(block => { return...
curObj[key] = { type, value, options, nullable, description, }; }); }); return obj; } // Promise helper function fetchHeader(path, resolve, reject) { fs.readFile(path, 'utf8', (err, data) => ...
{ let placeholder = rawValue; groups.forEach(g => placeholder = placeholder.replace(g, '')); description = placeholder.trim(); }
conditional_block