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
scratchcard.min.js
Name[1]) > -1) { eventName = x; for(var o = 0; o < this.events[eventName].length; o++) { this.events[eventName][o].callback.apply(this.events[eventName][o].instance, args); } } } ...
if(isTouch) { mouseX = evt.targetTouches[0].pageX - (config.canvas.offsetLeft); mouseY = evt.targetTouches[0].pageY - (config.canvas.offsetTop); }else {
random_line_split
scratchcard.min.js
(){ this.events = {}; } EventEmitter.prototype.on = function(eventName, callback, instance) { if(!this.events[eventName]) { this.events[eventName] = []; } this.events[eventName].push({callback : callback, instance : instance}); }; EventEmitter.prototype.tr...
EventEmitter
identifier_name
map.js
/* * This class provides access to native mapping applications on the device. */ function Map()
; /* * Shows a native map on the device with pins at the given positions. * @param {Array} positions */ Map.prototype.show = function(positions) { var jsonPos = {}; var pos = null; if (typeof positions == 'object') { // If positions is an array, then get the first only, since google's query // can't take mo...
{ }
identifier_body
map.js
/* * This class provides access to native mapping applications on the device. */ function Map() { }; /* * Shows a native map on the device with pins at the given positions. * @param {Array} positions */ Map.prototype.show = function(positions) { var jsonPos = {}; var pos = null; if (typeof positions == 'obj...
}); }; if (typeof navigator.map == "undefined") navigator.map = new Map();
id: 'com.palm.app.maps', params: { query: "@" + pos.coords.latitude + "," + pos.coords.longitude } }
random_line_split
map.js
/* * This class provides access to native mapping applications on the device. */ function
() { }; /* * Shows a native map on the device with pins at the given positions. * @param {Array} positions */ Map.prototype.show = function(positions) { var jsonPos = {}; var pos = null; if (typeof positions == 'object') { // If positions is an array, then get the first only, since google's query // can't...
Map
identifier_name
delegate.rs
// Copyleft (ↄ) meh. <meh@schizofreni.co> | http://meh.schizofreni.co // // This file is part of cancer. // // cancer is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (a...
use cocoa::appkit::{NSWindow, NSView}; use platform::cocoa::IdRef; use platform::Event; #[derive(Debug)] pub struct Delegate { state: Box<State>, this: IdRef, } #[derive(Debug)] pub struct State { manager: Sender<Event>, window: IdRef, view: IdRef, } impl Delegate { unsafe fn class() -> *const Class { ...
use objc::runtime::{Class, Object, Sel, BOOL, YES}; use objc::declare::ClassDecl; use cocoa::base::{id, nil};
random_line_split
delegate.rs
// Copyleft (ↄ) meh. <meh@schizofreni.co> | http://meh.schizofreni.co // // This file is part of cancer. // // cancer is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (a...
his: &Object, _: Sel, _: id) { unsafe { let state: *mut c_void = *this.get_ivar("state"); let state = state as *mut State; let _ = (*state).manager.send(Event::Focus(false)); } } let mut decl = ClassDecl::new("CancerDelegate", Class::get("NSObject").unwrap()).unwrap(); decl.add_ivar::<*mut c_...
ndow_did_resign_key(t
identifier_name
sbfDoxygen.py
# SConsBuildFramework - Copyright (C) 2013, Nicolas Papier. # Distributed under the terms of the GNU General Public License (GPL) # as published by the Free Software Foundation. # Author Nicolas Papier import os from src.sbfRsync import createRsyncAction from src.SConsBuildFramework import stringFormatter ...
shutil.rmtree( destinationPath, True ) if ( os.path.isdir( os.path.dirname(destinationPath) ) == False ): os.makedirs( os.path.dirname(destinationPath) ) shutil.copytree( sourcePath, destinationPath ) def configureDoxTarget( env ): # @todo improves output message sbf = env.sbf if ( ('dox_...
print 'sbfError: Try to use %s as an installation/desinstallation directory. Stop action to prevent any unwanted file destruction' return None
conditional_block
sbfDoxygen.py
# SConsBuildFramework - Copyright (C) 2013, Nicolas Papier. # Distributed under the terms of the GNU General Public License (GPL) # as published by the Free Software Foundation. # Author Nicolas Papier import os from src.sbfRsync import createRsyncAction from src.SConsBuildFramework import stringFormatter ...
( target, source, localenv ) : return '\n' + stringFormatter( localenv, "Install doxygen documentation" ) # Creates a custom doxyfile def doxyfileAction( target, source, env ) : sbf = env.sbf # Compute inputList, examplePath and imagePath parameters of doxyfile inputList = '' examplePath = '' imageP...
printDoxygenInstall
identifier_name
sbfDoxygen.py
# SConsBuildFramework - Copyright (C) 2013, Nicolas Papier. # Distributed under the terms of the GNU General Public License (GPL) # as published by the Free Software Foundation. # Author Nicolas Papier import os from src.sbfRsync import createRsyncAction from src.SConsBuildFramework import stringFormatter ...
if os.path.exists( newPathEntry ) : inputList += newPathEntry newPathEntry = os.path.join(projectPathName, 'doc', 'example') + ' ' if os.path.exists( newPathEntry ) : examplePath += newPathEntry newPathEntry = os.path.join(projectPathName, 'doc', 'image') + ' ' if os.path.exists( newPathEntry ...
sbf = env.sbf # Compute inputList, examplePath and imagePath parameters of doxyfile inputList = '' examplePath = '' imagePath = '' for projectName in sbf.myParsedProjects : localenv = sbf.myParsedProjects[projectName] projectPathName = localenv['sbf_projectPathName'] newPathEntry = os.path.join...
identifier_body
sbfDoxygen.py
# SConsBuildFramework - Copyright (C) 2013, Nicolas Papier. # Distributed under the terms of the GNU General Public License (GPL) # as published by the Free Software Foundation. # Author Nicolas Papier import os from src.sbfRsync import createRsyncAction from src.SConsBuildFramework import stringFormatter ...
shutil.copyfile(sourceName, targetName) # or env.Execute( Copy(targetName, sourceName) ) with open( targetName, 'a' ) as file: file.write( '\n### Added by SConsBuildFramework\n' ) file.write( 'LAYOUT_FILE = "%s"\n' % os.path.join(sbf.mySCONS_BUILD_FRAMEWORK, 'DoxygenLayout.xml') ) file.write( 'P...
print 'Generating {}'.format( targetName )
random_line_split
company.service.ts
import { Injectable } from '@angular/core'; import { Headers, Http, Response } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; import 'rxjs/add/operator/toPromise'; import { Company } from '../_ent...
private handleError(error: any): Promise<any> { console.error('An error occurred', error); return Promise.reject(error.message || error); } }
{ return this.http .get(this.heroesUrl + `?name=${term}`) .map((r: Response) => r.json().data as Company[]) .catch((error: any) => { console.error('An friendly error occurred', error); return Observable.throw(error.message || error); }); }
identifier_body
company.service.ts
import { Injectable } from '@angular/core'; import { Headers, Http, Response } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; import 'rxjs/add/operator/toPromise'; import { Company } from '../_ent...
{ private heroesUrl = Config.rootApiUrl + 'api/companies'; // URL to web api constructor(private http: Http) { } getCompanies(): Promise<Company[]> { return this.http .get(this.heroesUrl) .toPromise() .then(response => response.json().data as Company[]) .catch(this.handleError); ...
CompanyService
identifier_name
company.service.ts
import { Injectable } from '@angular/core'; import { Headers, Http, Response } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; import 'rxjs/add/operator/toPromise'; import { Company } from '../_ent...
.catch((error: any) => { console.error('An friendly error occurred', error); return Observable.throw(error.message || error); }); } private handleError(error: any): Promise<any> { console.error('An error occurred', error); return Promise.reject(error.message || error); } }
.map((r: Response) => r.json().data as Company[])
random_line_split
pfs.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
return unlink(path); } }, (err: NodeJS.ErrnoException) => { if (err.code === 'ENOENT') { return; } return TPromise.wrapError<void>(err); }); } export function realpath(path: string): TPromise<string> { return nfcall(fs.realpath, path, null); } export function stat(path: string): TPromise<fs.Stats> {...
} else {
random_line_split
pfs.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
}, (err: NodeJS.ErrnoException) => { if (err.code === 'ENOENT') { return; } return TPromise.wrapError<void>(err); }); } export function realpath(path: string): TPromise<string> { return nfcall(fs.realpath, path, null); } export function stat(path: string): TPromise<fs.Stats> { return nfcall(fs.stat, pa...
{ return unlink(path); }
conditional_block
pfs.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
export function chmod(path: string, mode: number): TPromise<boolean> { return nfcall(fs.chmod, path, mode); } export function mkdirp(path: string, mode?: number): TPromise<boolean> { const mkdir = () => nfcall(fs.mkdir, path, mode) .then(null, (err: NodeJS.ErrnoException) => { if (err.code === 'EEXIST') { ...
{ return new Promise(c => fs.exists(path, c)); }
identifier_body
pfs.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
(path: string, mode?: number): TPromise<boolean> { const mkdir = () => nfcall(fs.mkdir, path, mode) .then(null, (err: NodeJS.ErrnoException) => { if (err.code === 'EEXIST') { return nfcall(fs.stat, path) .then((stat: fs.Stats) => stat.isDirectory ? null : Promise.wrapError(new Error(`'${ path...
mkdirp
identifier_name
pokemon_model.rs
use super::enums; use super::stats; use enum_primitive::FromPrimitive; /// Basic values for Pokemon species. Equal for every instance of the given Pokemon. #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct PokemonModel { pokedex_id: usize, name: String, height: u8, weight: u16, gender_rate: ...
None } // Setter methods // /// Sets a type of the pokemon pub fn set_type(&mut self, type_id: i32, slot: u16) { match slot { 1 => self.type_one = enums::Types::from_i32(type_id).unwrap(), 2 => self.type_two = enums::Types::from_i32(type_id).unwrap(), ...
{ return Some(self.clone().mega_evolution.unwrap()); }
conditional_block
pokemon_model.rs
use super::enums; use super::stats; use enum_primitive::FromPrimitive; /// Basic values for Pokemon species. Equal for every instance of the given Pokemon. #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct PokemonModel { pokedex_id: usize, name: String, height: u8, weight: u16, gender_rate: ...
/// Gets the height of the pokemon pub fn get_height(&self) -> u8 { self.clone().height } /// Gets the weight of the pokemon pub fn get_weight(&self) -> u16 { self.clone().weight } /// Gets the gender rate of the pokemon pub fn get_gender_rate(&self) -> i8 { self...
{ self.name.clone() }
identifier_body
pokemon_model.rs
use super::enums; use super::stats; use enum_primitive::FromPrimitive; /// Basic values for Pokemon species. Equal for every instance of the given Pokemon. #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct PokemonModel { pokedex_id: usize, name: String, height: u8, weight: u16, gender_rate: ...
(&self) -> i8 { self.clone().gender_rate } /// Gets the description for the pokemon which is readable by the user of the program aswell pub fn get_description(&self) -> String { self.clone().description } /// Gets the types of the pokemon pub fn get_types(&self) -> (enums::Types,...
get_gender_rate
identifier_name
pokemon_model.rs
use super::enums; use super::stats; use enum_primitive::FromPrimitive; /// Basic values for Pokemon species. Equal for every instance of the given Pokemon. #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub struct PokemonModel { pokedex_id: usize, name: String, height: u8, weight: u16, gender_rate: ...
self.clone().description } /// Gets the types of the pokemon pub fn get_types(&self) -> (enums::Types, enums::Types) { (self.clone().type_one, self.clone().type_two) } /// Gets the base stats of the pokemon pub fn get_stats(&self) -> stats::Stats { self.clone().base_stats...
self.clone().gender_rate } /// Gets the description for the pokemon which is readable by the user of the program aswell pub fn get_description(&self) -> String {
random_line_split
process2.rs
(&mut self) { self.env = Some(HashMap::new()) } pub fn cwd(&mut self, dir: &OsStr) { self.cwd = Some(dir.to_cstring().unwrap()) } } //////////////////////////////////////////////////////////////////////////////// // Processes /////////////////////////////////////////////////////////////////...
{ /// Normal termination with an exit code. Code(i32), /// Termination by signal, with the signal number. /// /// Never generated on Windows. Signal(i32), } impl ExitStatus { pub fn success(&self) -> bool { *self == ExitStatus::Code(0) } pub fn code(&self) -> Option<i32> {...
ExitStatus
identifier_name
process2.rs
(&mut self) { self.env = Some(HashMap::new()) } pub fn cwd(&mut self, dir: &OsStr) { self.cwd = Some(dir.to_cstring().unwrap()) } } //////////////////////////////////////////////////////////////////////////////// // Processes /////////////////////////////////////////////////////////////////...
unsafe fn getdtablesize() -> c_int { libc::funcs::bsd44::getdtablesize() } let dirp = cfg.cwd.as_ref().map(|c| c.as_ptr()).unwrap_or(ptr::null()); with_envp(cfg.env.as_ref(), |envp: *const c_void| { with_argv(&cfg.program, &cfg.args, |argv: *const *const libc::c...
{ use libc::funcs::posix88::unistd::{fork, dup2, close, chdir, execvp}; mod rustrt { extern { pub fn rust_unset_sigprocmask(); } } unsafe fn set_cloexec(fd: c_int) { let ret = c::ioctl(fd, c::FIOCLEX); assert_eq!(ret, 0); ...
identifier_body
process2.rs
= b"NOEX"; impl Process { pub unsafe fn kill(&self) -> io::Result<()> { try!(cvt(libc::funcs::posix88::signal::kill(self.pid, libc::SIGKILL))); Ok(()) } pub fn spawn(cfg: &Command, in_fd: Option<AnonPipe>, out_fd: Option<AnonPipe>, err_fd: Option<AnonPipe>) ...
{ fail(&mut output); }
conditional_block
process2.rs
(&mut self) { self.env = Some(HashMap::new()) } pub fn cwd(&mut self, dir: &OsStr) { self.cwd = Some(dir.to_cstring().unwrap()) } } //////////////////////////////////////////////////////////////////////////////// // Processes /////////////////////////////////////////////////////////////////...
in_fd: Option<AnonPipe>, out_fd: Option<AnonPipe>, err_fd: Option<AnonPipe>) -> io::Result<Process> { use libc::funcs::posix88::unistd::{fork, dup2, close, chdir, execvp}; mod rustrt { extern { pub fn rust_unset_sigprocmask(); ...
try!(cvt(libc::funcs::posix88::signal::kill(self.pid, libc::SIGKILL))); Ok(()) } pub fn spawn(cfg: &Command,
random_line_split
chaskeyrng.rs
. ["Chaskey: An //! Efficient MAC Algorithm for 32-bit //! Microcontrollers."](https://eprint.iacr.org/2014/386.pdf) //! Cryptology ePrint Archive, Report 2014/386. //! * Claessen, Koen and Michał H. Pałka. 2013. ["Splittable //! Pseudorandom Number Generators using Cryptographic //! Hashing."](http://pub...
let result = self.buf[self.i]; self.i += 1; result } } impl SeedableRng<[u32; 4]> for ChaskeyRng { fn reseed(&mut self, seed: [u32; 4]) { ChaskeyRng::reseed(self, seed); } fn from_seed(seed: [u32; 4]) -> ChaskeyRng { ChaskeyRng::new(seed) } } im...
self.advance(); }
conditional_block
chaskeyrng.rs
. ["Chaskey: An //! Efficient MAC Algorithm for 32-bit //! Microcontrollers."](https://eprint.iacr.org/2014/386.pdf) //! Cryptology ePrint Archive, Report 2014/386. //! * Claessen, Koen and Michał H. Pałka. 2013. ["Splittable //! Pseudorandom Number Generators using Cryptographic //! Hashing."](http://pub...
permute4(state); permute4(state); } #[inline(always)] fn permute4(state: &mut [u32; 4]) { round(state); round(state); round(state); round(state); } /// The Chaskey round function. #[inline(always)] fn round(v: &mut [u32; 4]) { v[0] = v[0].wrapping_add(v[1]); v[2] = v[2].wrapping_add(v[3]); v[1]...
random_line_split
chaskeyrng.rs
. ["Chaskey: An //! Efficient MAC Algorithm for 32-bit //! Microcontrollers."](https://eprint.iacr.org/2014/386.pdf) //! Cryptology ePrint Archive, Report 2014/386. //! * Claessen, Koen and Michał H. Pałka. 2013. ["Splittable //! Pseudorandom Number Generators using Cryptographic //! Hashing."](http://pub...
fn reseed(&mut self, seed: [u32; 4]) { self.state = seed; self.k1 = times_two(seed); self.ctr = 0; self.buf = [0u32; 4]; self.i = 0; self.advance(); } fn clone(&self) -> ChaskeyRng { ChaskeyRng { state: self.state, ...
let mut result = ChaskeyRng { state: seed, k1: times_two(seed), ctr: 0, // We keep a buffer of the most recent words we generated // so that we don't call the MAC as often. buf: [0u32; 4], // Current position within `buf...
identifier_body
chaskeyrng.rs
13: Proceedings of the 2013 ACM SIGPLAN symposium on //! Haskell*, pp. 47-58. use rand::{Rand, Rng, SeedableRng}; use super::{SplitRng, SplitPrf}; use std::u32; /// A splittable pseudorandom generator based on Chaskey. pub struct ChaskeyRng { // The state of the splittable RNG, properly speaking. state: [...
_seed()
identifier_name
map.ts
/** * Copyright 2019 Google LLC. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by appli...
fitBounds = jest .fn() .mockImplementation( ( bounds: google.maps.LatLngBounds | google.maps.LatLngBoundsLiteral, padding?: number | google.maps.Padding ): void => {} ); getBounds = jest .fn() .mockImplementation( (): google.maps.LatLngBounds | null | undefined...
{ super(); }
identifier_body
map.ts
/** * Copyright 2019 Google LLC. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by appli...
extends MVCObject implements google.maps.Map { controls: Array<google.maps.MVCArray<Node>>; data: google.maps.Data; mapTypes: google.maps.MapTypeRegistry; overlayMapTypes: google.maps.MVCArray<google.maps.MapType>; constructor(mapDiv: Element | null, opts?: google.maps.MapOptions) { super(); } fitBo...
Map_
identifier_name
map.ts
/** * Copyright 2019 Google LLC. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by appli...
fitBounds = jest .fn() .mockImplementation( ( bounds: google.maps.LatLngBounds | google.maps.LatLngBoundsLiteral, padding?: number | google.maps.Padding ): void => {} ); getBounds = jest .fn() .mockImplementation( (): google.maps.LatLngBounds | null | undefined ...
overlayMapTypes: google.maps.MVCArray<google.maps.MapType>; constructor(mapDiv: Element | null, opts?: google.maps.MapOptions) { super(); }
random_line_split
d3-format-tests.ts
/** * Typescript definition tests for d3/d3-format module * * Note: These tests are intended to test the definitions only * in the sense of typing and call signature consistency. They * are not intended as functional tests. */ import * as d3Format from 'd3-format'; // -------------------------------------------...
// ---------------------------------------------------------------------- // Test Precision Suggestors // ---------------------------------------------------------------------- num = d3Format.precisionFixed(0.0005); num = d3Format.precisionPrefix(0.0005, 1000); num = d3Format.precisionRound(0.0005, 3000); // ------...
const formatString: string = specifier.toString();
random_line_split
page-section-element.ts
/* global HTMLElement CustomEvent pageSections */ 'use strict' declare const ShadyCSS // eslint-disable-line no-unused-vars let template = document.createElement('template') template.innerHTML = `<style> :host{ position: relative; display: flex; flex-direction: column; flex: 0 1 auto; ...
if (this._maxwidth !== null && this._maxwidth !== 'none') { contentElement.style.maxWidth = maxwidth this.setAttribute('maxWidth', maxwidth) } else { contentElement.style.maxWidth = 'auto' this.removeAttribute('maxWidth') } } /** * @method getter maxwidth * @description ge...
set maxwidth (maxwidth: string) { if (this._maxwidth === maxwidth) return this._maxwidth = maxwidth let contentElement = this.shadowRoot.querySelector('#content') as HTMLElement
random_line_split
page-section-element.ts
/* global HTMLElement CustomEvent pageSections */ 'use strict' declare const ShadyCSS // eslint-disable-line no-unused-vars let template = document.createElement('template') template.innerHTML = `<style> :host{ position: relative; display: flex; flex-direction: column; flex: 0 1 auto; ...
(fullscreen: boolean) { if (this._fullscreen === this._isTruthy(fullscreen)) return this._fullscreen = this._isTruthy(fullscreen) if (this._fullscreen) { this.setAttribute('fullscreen', '') } else { this.removeAttribute('fullscreen') } } /** * @method getter fullscreen * @des...
fullscreen
identifier_name
page-section-element.ts
/* global HTMLElement CustomEvent pageSections */ 'use strict' declare const ShadyCSS // eslint-disable-line no-unused-vars let template = document.createElement('template') template.innerHTML = `<style> :host{ position: relative; display: flex; flex-direction: column; flex: 0 1 auto; ...
/** * @method getter minwidth * @description get the minwidth property */ get minwidth () { return this._minwidth } /** * @method setter width * @description set the width property */ set width (width: string) { if (this._width === width) return this._width = width let conten...
{ if (this._minwidth === minwidth) return this._minwidth = minwidth let contentElement = this.shadowRoot.querySelector('#content') as HTMLElement if (this._minwidth !== null && this._minwidth !== 'none') { contentElement.style.minWidth = minwidth this.setAttribute('minWidth', minwidth) ...
identifier_body
test_common_fields.py
import socket import pytest import mock from pygelf import GelfTcpHandler, GelfUdpHandler, GelfHttpHandler, GelfTlsHandler, GelfHttpsHandler from tests.helper import logger, get_unique_message, log_warning, log_exception SYSLOG_LEVEL_ERROR = 3 SYSLOG_LEVEL_WARNING = 4 @pytest.fixture(params=[ GelfTcpHandler(hos...
def test_formatted_message(logger): message = get_unique_message() template = message + '_%s_%s' graylog_response = log_warning(logger, template, args=('hello', 'gelf')) assert graylog_response['message'] == message + '_hello_gelf' assert graylog_response['level'] == SYSLOG_LEVEL_WARNING asse...
message = get_unique_message() graylog_response = log_warning(logger, message) assert graylog_response['message'] == message assert graylog_response['level'] == SYSLOG_LEVEL_WARNING assert 'full_message' not in graylog_response assert 'file' not in graylog_response assert 'module' not in graylog...
identifier_body
test_common_fields.py
import socket import pytest import mock from pygelf import GelfTcpHandler, GelfUdpHandler, GelfHttpHandler, GelfTlsHandler, GelfHttpsHandler from tests.helper import logger, get_unique_message, log_warning, log_exception
SYSLOG_LEVEL_ERROR = 3 SYSLOG_LEVEL_WARNING = 4 @pytest.fixture(params=[ GelfTcpHandler(host='127.0.0.1', port=12201), GelfUdpHandler(host='127.0.0.1', port=12202), GelfUdpHandler(host='127.0.0.1', port=12202, compress=False), GelfHttpHandler(host='127.0.0.1', port=12203), GelfHttpHandler(host='...
random_line_split
test_common_fields.py
import socket import pytest import mock from pygelf import GelfTcpHandler, GelfUdpHandler, GelfHttpHandler, GelfTlsHandler, GelfHttpsHandler from tests.helper import logger, get_unique_message, log_warning, log_exception SYSLOG_LEVEL_ERROR = 3 SYSLOG_LEVEL_WARNING = 4 @pytest.fixture(params=[ GelfTcpHandler(hos...
(logger): message = get_unique_message() template = message + '_%s_%s' graylog_response = log_warning(logger, template, args=('hello', 'gelf')) assert graylog_response['message'] == message + '_hello_gelf' assert graylog_response['level'] == SYSLOG_LEVEL_WARNING assert 'full_message' not in gray...
test_formatted_message
identifier_name
commit_sync_config_utils.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use metaconfig_types::{DefaultSmallToLargeCommitSyncPathAction, SmallRepoCommitSyncConfig}; use mononoke_types::MPath; use std::collections...
( from: SmallRepoCommitSyncConfig, to: SmallRepoCommitSyncConfig, ) -> SmallRepoCommitSyncConfigDiff { let default_action_change = if from.default_action == to.default_action { None } else { Some((from.default_action, to.default_action)) }; let mut mapping_added = HashMap::new(...
diff_small_repo_commit_sync_configs
identifier_name
commit_sync_config_utils.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */
pub struct SmallRepoCommitSyncConfigDiff { pub default_action_change: Option<( DefaultSmallToLargeCommitSyncPathAction, DefaultSmallToLargeCommitSyncPathAction, )>, pub mapping_added: HashMap<MPath, MPath>, pub mapping_changed: HashMap<MPath, (MPath, MPath)>, pub mapping_removed: Has...
use metaconfig_types::{DefaultSmallToLargeCommitSyncPathAction, SmallRepoCommitSyncConfig}; use mononoke_types::MPath; use std::collections::HashMap;
random_line_split
commit_sync_config_utils.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use metaconfig_types::{DefaultSmallToLargeCommitSyncPathAction, SmallRepoCommitSyncConfig}; use mononoke_types::MPath; use std::collections...
; let mut mapping_added = HashMap::new(); let mut mapping_changed = HashMap::new(); let mut mapping_removed = HashMap::new(); for (from_small, from_large) in &from.map { match to.map.get(from_small) { Some(to_large) if from_large != to_large => { mapping_changed.in...
{ Some((from.default_action, to.default_action)) }
conditional_block
NamedNodeMap.js
/** * Objects implementing the NamedNodeMap interface are used to represent collections of nodes that can be accessed by name. Note that NamedNodeMap does not inherit from NodeList; NamedNodeMaps are not maintained in any particular order. Objects contained in an object implementing NamedNodeMap may also be accessed b...
/* returns Node */ removeNamedItem: function(key) { var node = this.getNamedItem(key); if (node) { this._removeItem(node); } else { throw DOMException(DOMException.NOT_FOUND_ERR, new Error()) } }, // raises: NOT_FOUND_ERR,NO_MODIFICATION_ALLOWED_ERR //for level2 getNamedItemNS: function(namespaceU...
},
random_line_split
NamedNodeMap.js
/** * Objects implementing the NamedNodeMap interface are used to represent collections of nodes that can be accessed by name. Note that NamedNodeMap does not inherit from NodeList; NamedNodeMaps are not maintained in any particular order. Objects contained in an object implementing NamedNodeMap may also be accessed b...
Class('tesla.xml.NamedNodeMap', NodeList, { getNamedItem: function(key) { var i = this.length; while (i--) { var node = this[i]; if (node.nodeName == key) return node; } }, setNamedItem: function(node) { var old = this.getNamedItem(node.nodeName); return add(this, node, old); }, /* retur...
{ if (old) { _this[findNodeIndex(_this, old)] = node; } else { _this[_this.length++] = node; } var el = _this._ownerElement; var doc = el && el.ownerDocument; if (doc) node.ownerElement = el; return old || null; }
identifier_body
NamedNodeMap.js
/** * Objects implementing the NamedNodeMap interface are used to represent collections of nodes that can be accessed by name. Note that NamedNodeMap does not inherit from NodeList; NamedNodeMaps are not maintained in any particular order. Objects contained in an object implementing NamedNodeMap may also be accessed b...
(_this, node, old) { if (old) { _this[findNodeIndex(_this, old)] = node; } else { _this[_this.length++] = node; } var el = _this._ownerElement; var doc = el && el.ownerDocument; if (doc) node.ownerElement = el; return old || null; } Class('tesla.xml.NamedNodeMap', NodeList, { getNamedItem: function(ke...
add
identifier_name
NamedNodeMap.js
/** * Objects implementing the NamedNodeMap interface are used to represent collections of nodes that can be accessed by name. Note that NamedNodeMap does not inherit from NodeList; NamedNodeMaps are not maintained in any particular order. Objects contained in an object implementing NamedNodeMap may also be accessed b...
}, /* returns Node */ removeNamedItem: function(key) { var node = this.getNamedItem(key); if (node) { this._removeItem(node); } else { throw DOMException(DOMException.NOT_FOUND_ERR, new Error()) } }, // raises: NOT_FOUND_ERR,NO_MODIFICATION_ALLOWED_ERR //for level2 getNamedItemNS: function(names...
{ var c = this[i]; if (node === c) { var old = c; while (i < lastIndex) { this[i] = this[++i] } this.length = lastIndex; node.ownerElement = null; var el = this._ownerElement; var doc = el && el.ownerDocument; return old; } }
conditional_block
adminStoreApi.service.spec.js
(function (angular) { 'use strict'; describe('adminStoreApi', function () { var $firebaseObjectMock; var firebaseObjectResult; var firebaseRef; var adminStoreApi; beforeEach(module('movieClub')); beforeEach(function () { firebaseObjectResult = {'$l...
adminStoreApi = _adminStoreApi_; })); describe('get', function () { it('should get a firebase adminStore object', function () { spyOn(firebaseRef, 'child'); adminStoreApi.get(); expect(firebaseRef.child).toHaveBeenCalledWith('adm...
random_line_split
grpc_connection.js
5.0 Build: rev-f49c8b5 Terms: https://firebase.google.com/terms/ */ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.GrpcConnection = undefined; var _app = require('../../app'); var _app2 = _interopRequireDefault(_app); var _stream_bridge = require('../remote/stream_bridge')...
(builder, databaseInfo) { this.databaseInfo = databaseInfo; // We cache stubs for the most-recently-used token. this.cachedStub = null; var protos = grpc.loadObject(builder.ns); this.firestore = protos.google.firestore.v1beta1; } GrpcConnection.prototype.sameToken = funct...
GrpcConnection
identifier_name
grpc_connection.js
5.0 Build: rev-f49c8b5 Terms: https://firebase.google.com/terms/ */ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.GrpcConnection = undefined; var _app = require('../../app'); var _app2 = _interopRequireDefault(_app); var _stream_bridge = require('../remote/stream_bridge')...
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var SDK_VERSION = _app2.default.SDK_VERSION; // Trick the TS compiler & Google closure compiler into executing normal require // statements, not using goog.require to import modules at compile time /** * Copyright 2017 G...
{ if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }
identifier_body
grpc_connection.js
.5.0 Build: rev-f49c8b5 Terms: https://firebase.google.com/terms/ */ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.GrpcConnection = undefined; var _app = require('../../app'); var _app2 = _interopRequireDefault(_app); var _stream_bridge = require('../remote/stream_bridge'...
callback(new _error.FirestoreError((0, _rpc_error.mapCodeFromRpcCode)(grpcError.code), grpcError.message)); } else { callback(undefined, value); } }); }); }; // TODO(mikelehen): This "method" is a monster. Should be refa...
random_line_split
grpc_connection.js
5.0 Build: rev-f49c8b5 Terms: https://firebase.google.com/terms/ */ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.GrpcConnection = undefined; var _app = require('../../app'); var _app2 = _interopRequireDefault(_app); var _stream_bridge = require('../remote/stream_bridge')...
}); grpcStream.on('end', function () { log.debug(LOG_TAG, 'GRPC stream ended.'); // The server closed the remote end. Close our side too (which will // trigger the 'finish' event). remoteEnded = true; grpcStream.end(); }); grp...
{ log.debug(LOG_TAG, 'GRPC stream received: ', util.inspect(msg, { depth: 100 })); stream.callOnMessage(msg); }
conditional_block
decode_raw_op_test.py
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
(tf.test.TestCase): def testToUint8(self): with self.test_session(): in_bytes = tf.placeholder(tf.string, shape=[2]) decode = tf.decode_raw(in_bytes, out_type=tf.uint8) self.assertEqual([2, None], decode.get_shape().as_list()) result = decode.eval(feed_dict={in_bytes: ["A", "a"]}) ...
DecodeRawOpTest
identifier_name
decode_raw_op_test.py
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
from __future__ import print_function import numpy as np import tensorflow as tf class DecodeRawOpTest(tf.test.TestCase): def testToUint8(self): with self.test_session(): in_bytes = tf.placeholder(tf.string, shape=[2]) decode = tf.decode_raw(in_bytes, out_type=tf.uint8) self.assertEqual([2, ...
from __future__ import absolute_import from __future__ import division
random_line_split
decode_raw_op_test.py
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
tf.test.main()
conditional_block
decode_raw_op_test.py
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applica...
in_bytes = tf.placeholder(tf.string, shape=[None]) decode = tf.decode_raw(in_bytes, out_type=tf.int16) self.assertEqual([None, None], decode.get_shape().as_list()) result = decode.eval(feed_dict={in_bytes: ["AaBC"]}) self.assertAllEqual([[ord("A") + ord("a") * 256, ...
def testToUint8(self): with self.test_session(): in_bytes = tf.placeholder(tf.string, shape=[2]) decode = tf.decode_raw(in_bytes, out_type=tf.uint8) self.assertEqual([2, None], decode.get_shape().as_list()) result = decode.eval(feed_dict={in_bytes: ["A", "a"]}) self.assertAllEqual([[o...
identifier_body
yearpicker.ts
import { Component, View, Host, OnInit, EventEmitter, ElementRef, ViewContainerRef, Self, Renderer } from 'angular2/core'; import {CORE_DIRECTIVES, FORM_DIRECTIVES, DefaultValueAccessor, NgIf, NgClass, NgModel } from 'angular2/common'; import {Ng2BootstrapConfig} from '../ng2-bootstrap-config'; import {Date...
() { let self = this; this.datePicker.stepYear = {years: this.datePicker.yearRange}; this.datePicker.setRefreshViewHandler(function () { let years:Array<any> = new Array(this.yearRange); let date:Date; for (let i = 0, start = self.getStartingYear(this.activeDate.getFullYear()); i < this...
ngOnInit
identifier_name
yearpicker.ts
import { Component, View, Host, OnInit, EventEmitter, ElementRef, ViewContainerRef, Self, Renderer } from 'angular2/core'; import {CORE_DIRECTIVES, FORM_DIRECTIVES, DefaultValueAccessor, NgIf, NgClass, NgModel } from 'angular2/common'; import {Ng2BootstrapConfig} from '../ng2-bootstrap-config'; import {Date...
YEAR_BUTTON: ` <button type="button" style="min-width:100%;" class="btn btn-default" [ngClass]="{'btn-info': dtz.selected, 'btn-link': !dtz.selected && !datePicker.isActive(dtz), 'btn-info': !dtz.selected && datePicker.isActive(dtz), disabled: dtz.disabled}" [disabled]="dtz.d...
const TEMPLATE_OPTIONS:any = { bs4: {
random_line_split
yearpicker.ts
import { Component, View, Host, OnInit, EventEmitter, ElementRef, ViewContainerRef, Self, Renderer } from 'angular2/core'; import {CORE_DIRECTIVES, FORM_DIRECTIVES, DefaultValueAccessor, NgIf, NgClass, NgModel } from 'angular2/common'; import {Ng2BootstrapConfig} from '../ng2-bootstrap-config'; import {Date...
self.title = [years[0].label, years[this.yearRange - 1].label].join(' - '); self.rows = this.split(years, 5); }, 'year'); this.datePicker.setCompareHandler(function (date1:Date, date2:Date) { return date1.getFullYear() - date2.getFullYear(); }, 'year'); this.datePicker.refreshView(...
{ date = new Date(start + i, 0, 1); this.fixTimeZone(date); years[i] = this.createDateObject(date, this.formatYear); years[i].uid = this.uniqueId + '-' + i; }
conditional_block
yearpicker.ts
import { Component, View, Host, OnInit, EventEmitter, ElementRef, ViewContainerRef, Self, Renderer } from 'angular2/core'; import {CORE_DIRECTIVES, FORM_DIRECTIVES, DefaultValueAccessor, NgIf, NgClass, NgModel } from 'angular2/common'; import {Ng2BootstrapConfig} from '../ng2-bootstrap-config'; import {Date...
private getStartingYear(year:number) { // todo: parseInt return ((year - 1) / this.datePicker.yearRange) * this.datePicker.yearRange + 1; } ngOnInit() { let self = this; this.datePicker.stepYear = {years: this.datePicker.yearRange}; this.datePicker.setRefreshViewHandler(function () { ...
{ }
identifier_body
mod.rs
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MI...
"Eq" => expand!(eq::expand_deriving_eq), "TotalEq" => expand!(totaleq::expand_deriving_totaleq), "Ord" => expand!(ord::expand_deriving_ord), "TotalOrd" => expand!(totalord::expand_deriving_totalord), ...
"Decodable" => expand!(decodable::expand_deriving_decodable),
random_line_split
type.py
# type command prints file contents from lib.utils import * def _help():
def main(argv): if len(argv) < 1 or '-h' in argv: _help() return # The shell doesnt send the # command name in the arg list # so the next line is not needed # anymore # argv.pop(0) # The shell does the work of replacing # vars already. Code segment below # is not ...
usage = ''' Usage: type (file) Print content of (file) Use '%' in front of global vars to use value as file name. ''' print(usage)
identifier_body
type.py
# type command prints file contents from lib.utils import * def _help(): usage = ''' Usage: type (file) Print content of (file) Use '%' in front of global vars to use value as file name. ''' print(usage) def main(argv): if len(argv) < 1 or '-h' in argv: _help() return # The shell ...
return elif os.path.isdir(path): err(3, add=argv + ' is a directory') else: err(2, path)
print(make_s2(data)) print('__________________<END>__________________\n')
random_line_split
type.py
# type command prints file contents from lib.utils import * def _help(): usage = ''' Usage: type (file) Print content of (file) Use '%' in front of global vars to use value as file name. ''' print(usage) def main(argv): if len(argv) < 1 or '-h' in argv: _help() return # The shell ...
else: err(2, path)
err(3, add=argv + ' is a directory')
conditional_block
type.py
# type command prints file contents from lib.utils import * def _help(): usage = ''' Usage: type (file) Print content of (file) Use '%' in front of global vars to use value as file name. ''' print(usage) def
(argv): if len(argv) < 1 or '-h' in argv: _help() return # The shell doesnt send the # command name in the arg list # so the next line is not needed # anymore # argv.pop(0) # The shell does the work of replacing # vars already. Code segment below # is not required an...
main
identifier_name
issue-19404.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(&mut self, env: &Env) { let engine = env.get_component::<Engine>(); } } fn main() {}
init
identifier_name
issue-19404.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
struct Engine; trait Component: 'static {} impl Component for Engine {} trait Env { fn get_component_type_id(&self, type_id: TypeId) -> Option<Fp<Component>>; } impl<'a> Env+'a { fn get_component<T: Component>(&self) -> Option<Fp<T>> { let x = self.get_component_type_id(TypeId::of::<T>()); No...
use std::rc::Rc; type Fp<T> = Rc<T>;
random_line_split
signin.js
// ERRORS_KEY = 'signinErrors' Template.signin.onCreated(function() { // Session.set(ERRORS_KEY, {}) }); Template.signin.helpers({ userName: function() { // if (!$('input[name="name"]').val()) { // return ; // } else { return "guest"; // } }, avator: fun...
ogining..."); Meteor.loginWithPassword(userName, password, function(error) { if (error) { // var phoneAccount = PhonesColl.findOne({phoneNum: userName}); // if (phoneAccount) { /*** need hack ***/ // Meteor.call("isExistUser", u...
template.$('.submit').val("l
conditional_block
signin.js
// ERRORS_KEY = 'signinErrors' Template.signin.onCreated(function() {
Template.signin.helpers({ userName: function() { // if (!$('input[name="name"]').val()) { // return ; // } else { return "guest"; // } }, avator: function() { return "/images/avator.png"; } // errorMessages: function() { // return _.val...
// Session.set(ERRORS_KEY, {}) });
random_line_split
best-feats.py
import sys import os import pandas as pd from collections import defaultdict import numpy as np dirname = sys.argv[1] path = os.path.join(dirname, "weights.tsv") with open(path ,"r") as f: df = pd.read_csv(f, sep="\t") df = df[df["iter"] == 5] fc2r = defaultdict(list)
event_df.loc[event_df["class"] == "SELECT", "rank"] = pos_df["weight"].argsort() for _, row in event_df.loc[event_df["class"] == "SELECT"][["name", "weight", "rank"]].iterrows(): clazz = "SELECT" feature = row["name"] rank = row["rank"] fc2r[(feature, clazz)].append(rank) ...
features = set() for event, event_df in df.groupby("event"): pos_df = event_df[event_df["class"] == "SELECT"]
random_line_split
best-feats.py
import sys import os import pandas as pd from collections import defaultdict import numpy as np dirname = sys.argv[1] path = os.path.join(dirname, "weights.tsv") with open(path ,"r") as f: df = pd.read_csv(f, sep="\t") df = df[df["iter"] == 5] fc2r = defaultdict(list) features = set() for event, event_df in df....
neg_df = event_df[event_df["class"] == "NEXT"] event_df.loc[event_df["class"] == "NEXT", "rank"] = neg_df["weight"].argsort() for _, row in event_df.loc[event_df["class"] == "NEXT"][["name", "weight", "rank"]].iterrows(): clazz = "NEXT" feature = row["name"] rank = row["rank"]...
clazz = "SELECT" feature = row["name"] rank = row["rank"] fc2r[(feature, clazz)].append(rank) features.add(feature)
conditional_block
builder.rs
use std::rc::Rc; use std::cell::RefCell; use progress::timestamp::RootTimestamp; use progress::{Timestamp, Scope, Subgraph}; use progress::nested::{Source, Target}; use progress::nested::product::Product; use progress::nested::scope_wrapper::ScopeWrapper; use communication::{Communicator, Data, Pullable}; use communic...
<T:Data+Serializable, D:Data+Serializable>(&mut self) -> (Vec<BoxedObserver<T, D>>, Box<Pullable<T, D>>) { self.communicator.borrow_mut().new_channel() } } impl<C: Communicator> Clone for GraphRoot<C> { fn clone(&self) -> Self { GraphRoot { communicator: self.communicator.clone(), graph: self.graph.clo...
new_channel
identifier_name
builder.rs
use std::rc::Rc; use std::cell::RefCell; use progress::timestamp::RootTimestamp; use progress::{Timestamp, Scope, Subgraph}; use progress::nested::{Source, Target};
use communication::{Communicator, Data, Pullable}; use communication::observer::BoxedObserver; use serialization::Serializable; /// The fundamental operations required to add and connect operators in a timely dataflow graph. /// /// Importantly, this is often a *shared* object, backed by a `Rc<RefCell<>>` wrapper. Eac...
use progress::nested::product::Product; use progress::nested::scope_wrapper::ScopeWrapper;
random_line_split
builder.rs
use std::rc::Rc; use std::cell::RefCell; use progress::timestamp::RootTimestamp; use progress::{Timestamp, Scope, Subgraph}; use progress::nested::{Source, Target}; use progress::nested::product::Product; use progress::nested::scope_wrapper::ScopeWrapper; use communication::{Communicator, Data, Pullable}; use communic...
} } impl<C: Communicator> GraphBuilder for GraphRoot<C> { type Timestamp = RootTimestamp; fn name(&self) -> String { format!("Worker[{}]", self.communicator.borrow().index()) } fn add_edge(&self, _source: Source, _target: Target) { panic!("GraphRoot::connect(): root doesn't maintain edges; wh...
{ panic!("GraphRoot::step(): empty; make sure to add a subgraph!") }
conditional_block
builder.rs
use std::rc::Rc; use std::cell::RefCell; use progress::timestamp::RootTimestamp; use progress::{Timestamp, Scope, Subgraph}; use progress::nested::{Source, Target}; use progress::nested::product::Product; use progress::nested::scope_wrapper::ScopeWrapper; use communication::{Communicator, Data, Pullable}; use communic...
} impl<G: GraphBuilder, T: Timestamp> Communicator for SubgraphBuilder<G, T> { fn index(&self) -> u64 { self.parent.index() } fn peers(&self) -> u64 { self.parent.peers() } fn new_channel<T2:Data+Serializable, D:Data+Serializable>(&mut self) -> (Vec<BoxedObserver<T2, D>>, Box<Pullable<T2, D>>) { s...
{ let index = self.subgraph.borrow().children() as u64; let path = format!("{}", self.subgraph.borrow().path); Subgraph::new_from(self, index, path) }
identifier_body
evalBlockValidator.ts
import { EvalBlock } from './evalBlock'; const MATH_RANDOM_RE = /\bMath\.random\(\)/; const PROVIDE_RE = /\bprovide\(/; function checkForMathRandom(code: string) { if (MATH_RANDOM_RE.test(code)) { console.warn('Eval block appears to use Math.random(); ' + 'use bml.randomInt or bml.randomFloat instead. ' ...
{ checkForMathRandom(evalBlock.contents); checkForProvide(evalBlock.contents); }
identifier_body
evalBlockValidator.ts
import { EvalBlock } from './evalBlock'; const MATH_RANDOM_RE = /\bMath\.random\(\)/; const PROVIDE_RE = /\bprovide\(/; function checkForMathRandom(code: string) {
+ 'See https://bml-lang.org/docs/the-language/eval-api/') } } function checkForProvide(code: string) { if (!PROVIDE_RE.test(code)) { console.warn('Eval block appears to never call `provide({})`. ' + 'This is needed to expose your code to the BML interpreter. ' + 'See https://bml-lang.org/docs...
if (MATH_RANDOM_RE.test(code)) { console.warn('Eval block appears to use Math.random(); ' + 'use bml.randomInt or bml.randomFloat instead. '
random_line_split
evalBlockValidator.ts
import { EvalBlock } from './evalBlock'; const MATH_RANDOM_RE = /\bMath\.random\(\)/; const PROVIDE_RE = /\bprovide\(/; function checkForMathRandom(code: string) { if (MATH_RANDOM_RE.test(code)) { console.warn('Eval block appears to use Math.random(); ' + 'use bml.randomInt or bml.randomFloat instead. ' ...
(code: string) { if (!PROVIDE_RE.test(code)) { console.warn('Eval block appears to never call `provide({})`. ' + 'This is needed to expose your code to the BML interpreter. ' + 'See https://bml-lang.org/docs/the-language/eval-api/'); } } /** * Run basic sanity checks on an eval block. * * Curren...
checkForProvide
identifier_name
evalBlockValidator.ts
import { EvalBlock } from './evalBlock'; const MATH_RANDOM_RE = /\bMath\.random\(\)/; const PROVIDE_RE = /\bprovide\(/; function checkForMathRandom(code: string) { if (MATH_RANDOM_RE.test(code)) { console.warn('Eval block appears to use Math.random(); ' + 'use bml.randomInt or bml.randomFloat instead. ' ...
} /** * Run basic sanity checks on an eval block. * * Currently validates that blocks: * - Do not access Math.random * - Call `provide()` at least once * * Validation failures result in warnings logged to console; * errors are not thrown. */ export function validateEvalBlock(evalBlock: EvalBlock) { checkFo...
{ console.warn('Eval block appears to never call `provide({})`. ' + 'This is needed to expose your code to the BML interpreter. ' + 'See https://bml-lang.org/docs/the-language/eval-api/'); }
conditional_block
modifiers.rs
use modifier::Modifier; use image_lib::FilterType; use super::Image; #[derive(Debug, Clone, Copy)] /// Resize Modifier for `Image` pub struct Resize { /// The resized width of the new Image pub width: u32, /// The resized heigt of the new Image pub height: u32, } impl Modifier<Image> for Resize { ...
(self, image: &mut Image) { image.value = image.value.crop(self.x, self.y, self.width, self.height) } } #[derive(Debug, Clone, Copy)] /// Grayscale Modifier for `Image` pub struct Grayscale; impl Modifier<Image> for Grayscale { fn modify(self, image: &mut Image) { image.value = image.value.gra...
modify
identifier_name
modifiers.rs
use modifier::Modifier; use image_lib::FilterType; use super::Image; #[derive(Debug, Clone, Copy)] /// Resize Modifier for `Image` pub struct Resize { /// The resized width of the new Image pub width: u32, /// The resized heigt of the new Image pub height: u32, } impl Modifier<Image> for Resize { ...
}
random_line_split
audit.ts
import { Operator } from '../Operator'; import { Subscriber } from '../Subscriber'; import { Observable, SubscribableOrPromise } from '../Observable'; import { Subscription, TeardownLogic } from '../Subscription'; import { tryCatch } from '../util/tryCatch'; import { errorObject } from '../util/errorObject'; import { ...
if (hasValue) { this.value = null; this.hasValue = false; this.destination.next(value); } } notifyNext(outerValue: T, innerValue: R, outerIndex: number, innerIndex: number): void { this.clearThrottle(); } notifyComplete(): void { this.clearThrottle(); } }
{ this.remove(throttled); this.throttled = null; throttled.unsubscribe(); }
conditional_block
audit.ts
import { Operator } from '../Operator'; import { Subscriber } from '../Subscriber'; import { Observable, SubscribableOrPromise } from '../Observable'; import { Subscription, TeardownLogic } from '../Subscription'; import { tryCatch } from '../util/tryCatch'; import { errorObject } from '../util/errorObject'; import { ...
(): void { this.clearThrottle(); } }
notifyComplete
identifier_name
audit.ts
import { Operator } from '../Operator'; import { Subscriber } from '../Subscriber'; import { Observable, SubscribableOrPromise } from '../Observable'; import { Subscription, TeardownLogic } from '../Subscription'; import { tryCatch } from '../util/tryCatch'; import { errorObject } from '../util/errorObject'; import { ...
this.hasValue = false; this.destination.next(value); } } notifyNext(outerValue: T, innerValue: R, outerIndex: number, innerIndex: number): void { this.clearThrottle(); } notifyComplete(): void { this.clearThrottle(); } }
if (hasValue) { this.value = null;
random_line_split
main.rs
collada; extern crate dev_menu; extern crate env_logger; extern crate gfx; extern crate gfx_text; extern crate gfx_debug_draw; extern crate piston; extern crate piston_window; extern crate sdl2_window; extern crate shader_version; extern crate skeletal_animation; extern crate vecmath; use std::collections::HashMap; u...
let mut projection = CameraPerspective { fov: 90.0f32, near_clip: 0.1, far_clip: 1000.0, aspect_ratio: (win_width as f32) / (win_height as f32) }.projection(); let mut orbit_zoom_camera: OrbitZoomCamera<f32> = OrbitZoomCamera::new( [0.0, 0.0, 0.0], OrbitZoomC...
{ env_logger::init().unwrap(); let (win_width, win_height) = (640, 480); let mut window: PistonWindow<Sdl2Window> = WindowSettings::new("Skeletal Animation Demo", [win_width, win_height]) .exit_on_esc(true) .opengl(shader_version::OpenGL::V3_2) .build() ...
identifier_body
main.rs
collada; extern crate dev_menu; extern crate env_logger; extern crate gfx; extern crate gfx_text; extern crate gfx_debug_draw; extern crate piston; extern crate piston_window; extern crate sdl2_window; extern crate shader_version; extern crate skeletal_animation; extern crate vecmath; use std::collections::HashMap; u...
else { 0.01 }; menu.add_item(dev_menu::MenuItem::slider_item( &format!("Param[{}] = ", param)[..], range, rate, Box::new( move |ref settings| { settings.params[&param_copy_1[..]] }), Box::new( move |ref...
{ 0.1 }
conditional_block
main.rs
collada; extern crate dev_menu; extern crate env_logger; extern crate gfx; extern crate gfx_text; extern crate gfx_debug_draw; extern crate piston; extern crate piston_window; extern crate sdl2_window; extern crate shader_version; extern crate skeletal_animation; extern crate vecmath; use std::collections::HashMap; u...
() { env_logger::init().unwrap(); let (win_width, win_height) = (640, 480); let mut window: PistonWindow<Sdl2Window> = WindowSettings::new("Skeletal Animation Demo", [win_width, win_height]) .exit_on_esc(true) .opengl(shader_version::OpenGL::V3_2) .build() ...
main
identifier_name
main.rs
ada; extern crate dev_menu; extern crate env_logger; extern crate gfx; extern crate gfx_text; extern crate gfx_debug_draw; extern crate piston; extern crate piston_window; extern crate sdl2_window; extern crate shader_version; extern crate skeletal_animation; extern crate vecmath; use std::collections::HashMap; use pi...
let camera_projection = model_view_projection( model, camera_view, projection ); // Draw IK target... let target = [settings.params["target-x"], settings.params["target-y"], ...
let camera_view = orbit_zoom_camera.camera(args.ext_dt).orthogonal();
random_line_split
util.ts
/** * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info. * * @author Alexander Rose <alexander.rose@weirdbyte.de> */ /** Set canvas size taking `devicePixelRatio` into account */ export function setCanvasSize(canvas: HTMLCanvasElement, width: number, height: number, scale = 1...
/** Resize canvas to container element taking `devicePixelRatio` into account */ export function resizeCanvas(canvas: HTMLCanvasElement, container: HTMLElement, scale = 1) { let width = window.innerWidth; let height = window.innerHeight; if (container !== document.body) { // fixes issue #molstar/m...
{ canvas.width = Math.round(window.devicePixelRatio * scale * width); canvas.height = Math.round(window.devicePixelRatio * scale * height); Object.assign(canvas.style, { width: `${width}px`, height: `${height}px` }); }
identifier_body
util.ts
/** * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info. * * @author Alexander Rose <alexander.rose@weirdbyte.de> */ /** Set canvas size taking `devicePixelRatio` into account */ export function setCanvasSize(canvas: HTMLCanvasElement, width: number, height: number, scale = 1...
}
random_line_split
util.ts
/** * Copyright (c) 2018 mol* contributors, licensed under MIT, See LICENSE file for more info. * * @author Alexander Rose <alexander.rose@weirdbyte.de> */ /** Set canvas size taking `devicePixelRatio` into account */ export function setCanvasSize(canvas: HTMLCanvasElement, width: number, height: number, scale = 1...
(canvas: HTMLCanvasElement, callback: BlobCallback, type?: string, quality?: any) { const bin = atob(canvas.toDataURL(type, quality).split(',')[1]); const len = bin.length; const len32 = len >> 2; const a8 = new Uint8Array(len); const a32 = new Uint32Array(a8.buffer, 0, len32); let j = 0; f...
_canvasToBlob
identifier_name
nb.py
import sys from csv_data import Data from csv_utilities import readIntegerCSV from csv_utilities import convertToZeroOne from statistics import mean from math import log def dotProduct( arr1, arr2 ): return sum( [ arr1[idx] * arr2[idx] for idx in range( len( arr1 ) ) ] ) # def dataSubsetWithY( data, y ): return [ r...
def main( argv ): try: training_data = Data( argv[ 0 ], readIntegerCSV, convertToZeroOne ) testing_data = Data( argv[ 1 ], readIntegerCSV, convertToZeroOne ) beta = int ( argv[ 2 ] ) model = open( argv[ 3 ], 'w+' ) b = findBias( training_data, beta ) W = findWeights( training_data, beta ) re...
model_stream.write( "{}\n".format( round( b, 4 ) ) ) for idx, attr in enumerate( attrs ): model_stream.write( "{:16}\t{}\n".format( attr, round( W[ idx ], 4 ) ) )
identifier_body
nb.py
import sys from csv_data import Data from csv_utilities import readIntegerCSV from csv_utilities import convertToZeroOne from statistics import mean from math import log def dotProduct( arr1, arr2 ): return sum( [ arr1[idx] * arr2[idx] for idx in range( len( arr1 ) ) ] ) # def dataSubsetWithY( data, y ): return [ r...
def main( argv ): try: training_data = Data( argv[ 0 ], readIntegerCSV, convertToZeroOne ) testing_data = Data( argv[ 1 ], readIntegerCSV, convertToZeroOne ) beta = int ( argv[ 2 ] ) model = open( argv[ 3 ], 'w+' ) b = findBias( training_data, beta ) W = findWeights( training_data, beta ) re...
model_stream.write( "{:16}\t{}\n".format( attr, round( W[ idx ], 4 ) ) )
conditional_block
nb.py
import sys from csv_data import Data from csv_utilities import readIntegerCSV from csv_utilities import convertToZeroOne from statistics import mean from math import log def dotProduct( arr1, arr2 ): return sum( [ arr1[idx] * arr2[idx] for idx in range( len( arr1 ) ) ] ) # def dataSubsetWithY( data, y ): return [ ro...
def main( argv ): try: training_data = Data( argv[ 0 ], readIntegerCSV, convertToZeroOne ) testing_data = Data( argv[ 1 ], readIntegerCSV, convertToZeroOne ) beta = int ( argv[ 2 ] ) model = open( argv[ 3 ], 'w+' ) b = findBias( training_data, beta ) W = findWeights( training_data, beta ) rez ...
random_line_split
nb.py
import sys from csv_data import Data from csv_utilities import readIntegerCSV from csv_utilities import convertToZeroOne from statistics import mean from math import log def dotProduct( arr1, arr2 ): return sum( [ arr1[idx] * arr2[idx] for idx in range( len( arr1 ) ) ] ) # def dataSubsetWithY( data, y ): return [ r...
( data, beta ): return ( mean( ( [ 1, 0 ] * ( beta - 1 ) ) + [ row.Y for row in data.rows ] ) ) # def findBias( data, beta ): return ( log( probabilityYisZero( data, beta ) / probabilityYisOne( data, beta ), 2 ) + sum( [ log( probabilityXY( data, 0, idx, 1, beta ) / probabilityXY( data, 0, idx, 0, beta ), 2 ) fo...
probabilityYisOne
identifier_name
date-validator.directive.js
import moment from 'moment'; var DATE_REGEX = /^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$/; function
() { return { restrict: 'A', require: 'ngModel', // TODO don't use scope scope: { minDate: '=', maxDate: '=' }, link: function(scope, element, attrs, ngModelCtrl) { ngModelCtrl.$parsers.push(function(viewValue) { var valid; var modelValue; if (viewVal...
dateValidator
identifier_name
date-validator.directive.js
import moment from 'moment'; var DATE_REGEX = /^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$/; function dateValidator() { return { restrict: 'A', require: 'ngModel', // TODO don't use scope scope: { minDate: '=', maxDate: '=' }, link: function(scope, element, attrs, ngModelCtrl) { ngModel...
modelValue = null; } } ngModelCtrl.$setValidity('date', valid); if (scope.minDate && modelValue && moment(modelValue) < moment(scope.minDate)) { ngModelCtrl.$setValidity('minDate', false); modelValue = null; } else { ngModelCtrl.$setV...
valid = false; modelValue = null; } } else { valid = false;
random_line_split
date-validator.directive.js
import moment from 'moment'; var DATE_REGEX = /^[0-9]{2}\/[0-9]{2}\/[0-9]{4}$/; function dateValidator()
if (modelValue === '') { valid = true; modelValue = null; } else if (DATE_REGEX.test(modelValue)) { var date = moment(viewValue, 'DD/MM/YYYY'); if (date.isValid()) { valid = true; modelValue = date.format('YYYY-MM-DD'); ...
{ return { restrict: 'A', require: 'ngModel', // TODO don't use scope scope: { minDate: '=', maxDate: '=' }, link: function(scope, element, attrs, ngModelCtrl) { ngModelCtrl.$parsers.push(function(viewValue) { var valid; var modelValue; if (viewValue ...
identifier_body
batch_analyze_nematic_R8a.py
# # Active Particles on Curved Spaces (APCS) # # Author: Silke Henkes # # ICSMB, Department of Physics # University of Aberdeen # Author: Rastko Sknepnek # # Division of Physics # School of Engineering, Physics and Mathematics # University of Dundee # # (c) 2013, 2014 # # ...
# ################################################################
random_line_split
batch_analyze_nematic_R8a.py
# ################################################################ # # Active Particles on Curved Spaces (APCS) # # Author: Silke Henkes # # ICSMB, Department of Physics # University of Aberdeen # Author: Rastko Sknepnek # # Division of Physics # School of Engineering, Physics and Mathem...
outfile2=outfolder + 'defects_v0_' + v0 + '_R_'+ r+ '.dat' np.savetxt(outfile2,np.concatenate((ndefect,defects),axis=1),fmt='%12.6g', header='ndefect defects')
files = sorted(glob(basefolder+'R_'+ r+ '/v0_' + v0 + '/sphere_*.dat'))[skip:] defects=np.zeros((len(files),12)) ndefect=np.zeros((len(files),1)) u=0 for f in files: print f outname =outfolder +'R_'+ r+ '/v0_' + v0 + '/frame_data' + str(u)+'.vtk' defects0,ndefect0=getDefects(f,float(r),sigma,outname,Fa...
conditional_block