file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
ball.js
function Ball() { // ball id this.ballId = 'B_'+Math.floor(Math.random() * 100000000); // at first - we pick the direction randomlly - // there are 4 possible directions (1,2,3,4) // 1: up left, 2: up right, 3: down right, 4: down left this.direction = Math.floor(Math.random() * 2) + 1; // ball speed this.bal...
case 3: that.getBall().style.left = that.getBall().offsetLeft + that.ballSpeed + 'px'; that.getBall().style.top = that.getBall().offsetTop + that.ballSpeed + 'px'; break; case 4: that.getBall().style.left = that.getBall().offsetLeft - that.ballSpeed + 'px'; that.getBall().style.top = that.getB...
that.getBall().style.top = that.getBall().offsetTop - that.ballSpeed + 'px'; break;
random_line_split
ball.js
function Ball()
Ball.prototype.init = function() { this.appendBall(); } Ball.prototype.getBall = function() { return document.getElementById(this.ballId); } Ball.prototype.appendBall = function() { var b = document.createElement('div'); b.setAttribute('id',this.ballId); b.setAttribute('class',this.ballClass); document.body.a...
{ // ball id this.ballId = 'B_'+Math.floor(Math.random() * 100000000); // at first - we pick the direction randomlly - // there are 4 possible directions (1,2,3,4) // 1: up left, 2: up right, 3: down right, 4: down left this.direction = Math.floor(Math.random() * 2) + 1; // ball speed this.ballSpeed = 1; // ...
identifier_body
ball.js
function
() { // ball id this.ballId = 'B_'+Math.floor(Math.random() * 100000000); // at first - we pick the direction randomlly - // there are 4 possible directions (1,2,3,4) // 1: up left, 2: up right, 3: down right, 4: down left this.direction = Math.floor(Math.random() * 2) + 1; // ball speed this.ballSpeed = 1; ...
Ball
identifier_name
suspicious_splitn.rs
#![warn(clippy::suspicious_splitn)] fn main() { let _ = "a,b,c".splitn(3, ','); let _ = [0, 1, 2, 1, 3].splitn(3, |&x| x == 1); let _ = "".splitn(0, ','); let _ = [].splitn(0, |&x: &u32| x == 1); let _ = "a,b".splitn(0, ',');
let _ = "a,b".rsplitn(0, ','); let _ = "a,b".splitn(1, ','); let _ = [0, 1, 2].splitn(0, |&x| x == 1); let _ = [0, 1, 2].splitn_mut(0, |&x| x == 1); let _ = [0, 1, 2].splitn(1, |&x| x == 1); let _ = [0, 1, 2].rsplitn_mut(1, |&x| x == 1); const X: usize = 0; let _ = "a,b".splitn(X + 1, '...
random_line_split
suspicious_splitn.rs
#![warn(clippy::suspicious_splitn)] fn main()
{ let _ = "a,b,c".splitn(3, ','); let _ = [0, 1, 2, 1, 3].splitn(3, |&x| x == 1); let _ = "".splitn(0, ','); let _ = [].splitn(0, |&x: &u32| x == 1); let _ = "a,b".splitn(0, ','); let _ = "a,b".rsplitn(0, ','); let _ = "a,b".splitn(1, ','); let _ = [0, 1, 2].splitn(0, |&x| x == 1); ...
identifier_body
suspicious_splitn.rs
#![warn(clippy::suspicious_splitn)] fn
() { let _ = "a,b,c".splitn(3, ','); let _ = [0, 1, 2, 1, 3].splitn(3, |&x| x == 1); let _ = "".splitn(0, ','); let _ = [].splitn(0, |&x: &u32| x == 1); let _ = "a,b".splitn(0, ','); let _ = "a,b".rsplitn(0, ','); let _ = "a,b".splitn(1, ','); let _ = [0, 1, 2].splitn(0, |&x| x == 1); ...
main
identifier_name
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! This module contains shared types and messages for use by devtools/script. //! The traits are here instead of ...
/// `ViewportPx` is equal to `DeviceIndependentPixel` times a "page zoom" factor controlled by the user. This is /// the desktop-style "full page" zoom that enlarges content but then reflows the layout viewport /// so it still exactly fits the visible area. /// /// At the default zoom level of 100%, one `PagePx` is eq...
///
random_line_split
lib.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ //! This module contains shared types and messages for use by devtools/script. //! The traits are here instead of ...
{} // In summary, the hierarchy of pixel units and the factors to convert from one to the next: // // DevicePixel // / hidpi_ratio => DeviceIndependentPixel // / desktop_zoom => ViewportPx // / pinch_zoom => PagePx pub mod cursor; #[macro_use] pub mod values; pub mod viewport; pub use values::{ToCss, On...
PagePx
identifier_name
script.js
// requestAnim shim layer by Paul Irish window.requestAnimFrame = (function(){ return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRe...
{ jump = 'ascend'; } // } if (e.keyCode == 40){ // down } if (e.keyCode == 37){ state = 'left'; } if (e.keyCode == 39){ state = 'right'; } }); /////////////////////////////////////////////////////////////////////////////// if (state == 'left') { //x = x-(1 * dirX); /...
// { if (e.keyCode == 38 )
random_line_split
script.js
// requestAnim shim layer by Paul Irish window.requestAnimFrame = (function(){ return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msR...
function draw() { context.fillText( state + ":" , canvas.width / 2 , canvas.height / 2 ); $(document).keyup(function(e) { if (e.keyCode == 37) { state= "stop"; dirX=1; dir=3; } if (e.keyCode == 39) { state= "stop"; dirX=1; dir=4; } if (e.keyCode == 38) { jump = 'descen...
{ y2++; x2++; y3++; x3--; if (y2==400) { y2=0; } if (x2==598) { x2=0; } if (y3==400) { y3=0; } if (x3==0) { x3=598; } }
identifier_body
script.js
// requestAnim shim layer by Paul Irish window.requestAnimFrame = (function(){ return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msR...
() { context.fillText( state + ":" , canvas.width / 2 , canvas.height / 2 ); $(document).keyup(function(e) { if (e.keyCode == 37) { state= "stop"; dirX=1; dir=3; } if (e.keyCode == 39) { state= "stop"; dirX=1; dir=4; } if (e.keyCode == 38) { jump = 'descend'; } }); $(...
draw
identifier_name
script.js
// requestAnim shim layer by Paul Irish window.requestAnimFrame = (function(){ return window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msR...
if (destY > canvas.width || destY < 0) { // dirY =-dirY; } //canvas.width = 8248; context.clearRect(0,0 , canvas.width, canvas.height); context.drawImage(background_obj, backg_x, backg_y); context.save(); context.beginPath(); context.translate( 290,210 ); // rotate the rect ...
{ // dirX =-dirX; }
conditional_block
hammer_gestures.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Inject, Injectable, OpaqueToken} from '@angular/core'; import {EventManagerPlugin} from './event_manager'; ...
} @Injectable() export class HammerGesturesPlugin extends EventManagerPlugin { constructor(@Inject(HAMMER_GESTURE_CONFIG) private _config: HammerGestureConfig) { super(); } supports(eventName: string): boolean { if (!EVENT_NAMES.hasOwnProperty(eventName.toLowerCase()) && !this.isCustomEvent(eventName)) { ...
{ const mc = new Hammer(element); mc.get('pinch').set({enable: true}); mc.get('rotate').set({enable: true}); for (const eventName in this.overrides) { mc.get(eventName).set(this.overrides[eventName]); } return mc; }
identifier_body
hammer_gestures.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Inject, Injectable, OpaqueToken} from '@angular/core'; import {EventManagerPlugin} from './event_manager'; ...
export const HAMMER_GESTURE_CONFIG: OpaqueToken = new OpaqueToken('HammerGestureConfig'); export interface HammerInstance { on(eventName: string, callback: Function): void; off(eventName: string, callback: Function): void; } /** * @experimental */ @Injectable() export class HammerGestureConfig { events: strin...
* Hammer gestures. * * @experimental */
random_line_split
hammer_gestures.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Inject, Injectable, OpaqueToken} from '@angular/core'; import {EventManagerPlugin} from './event_manager'; ...
(eventName: string): boolean { return this._config.events.indexOf(eventName) > -1; } }
isCustomEvent
identifier_name
hammer_gestures.ts
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ import {Inject, Injectable, OpaqueToken} from '@angular/core'; import {EventManagerPlugin} from './event_manager'; ...
return true; } addEventListener(element: HTMLElement, eventName: string, handler: Function): Function { const zone = this.manager.getZone(); eventName = eventName.toLowerCase(); return zone.runOutsideAngular(() => { // Creating the manager bind events, must be done outside of angular ...
{ throw new Error(`Hammer.js is not loaded, can not bind ${eventName} event`); }
conditional_block
parse_args.py
''' argparse.py - this file is part of S3QL. Copyright © 2008 Nikolaus Rath <Nikolaus@rath.org> This work can be distributed under the terms of the GNU GPLv3. This module provides a customized ArgumentParser class. Differences are: * a --version argument is added by default * convenience functions are availabl...
merged = dict() for section in ini_config.sections(): pattern = ini_config[section].get('storage-url', None) if not pattern or not storage_url.startswith(pattern): continue for (key, val) in ini_config[section].items(): if key != 'sto...
ode = os.stat(path).st_mode if mode & (stat.S_IRGRP | stat.S_IROTH): self.exit(12, "%s has insecure permissions, aborting." % path) ini_config.read(path)
conditional_block
parse_args.py
''' argparse.py - this file is part of S3QL. Copyright © 2008 Nikolaus Rath <Nikolaus@rath.org> This work can be distributed under the terms of the GNU GPLv3. This module provides a customized ArgumentParser class. Differences are: * a --version argument is added by default * convenience functions are availabl...
self): self.add_argument("storage_url", metavar='<storage-url>', type=storage_url_type, help='Storage URL of the backend that contains the file system') self.add_argument("--authfile", type=str, metavar='<path>', default=os.path.e...
dd_storage_url(
identifier_name
parse_args.py
''' argparse.py - this file is part of S3QL. Copyright © 2008 Nikolaus Rath <Nikolaus@rath.org> This work can be distributed under the terms of the GNU GPLv3. This module provides a customized ArgumentParser class. Differences are: * a --version argument is added by default * convenience functions are availabl...
super().__init__(*a, **kw) self.register('action', 'parsers', SubParsersAction) def add_version(self): self.add_argument('--version', action='version', help="just print program version and exit", version='S3QL %s' % RELEASE) def add_...
random_line_split
parse_args.py
''' argparse.py - this file is part of S3QL. Copyright © 2008 Nikolaus Rath <Nikolaus@rath.org> This work can be distributed under the terms of the GNU GPLv3. This module provides a customized ArgumentParser class. Differences are: * a --version argument is added by default * convenience functions are availabl...
def add_storage_url(self): self.add_argument("storage_url", metavar='<storage-url>', type=storage_url_type, help='Storage URL of the backend that contains the file system') self.add_argument("--authfile", type=str, metavar='<path>', ...
elf.add_argument("--log", type=str_or_None_type, metavar='<target>', default=default, help='Destination for log messages. Specify ``none`` for standard ' 'output or ``syslog`` for the system logging daemon. ' 'Anything else will be interpreted as...
identifier_body
test_iam2_project_vpc_cascade_delete.py
''' @auther:fangxiao ''' import apibinding.api_actions as api_actions import zstackwoodpecker.test_util as test_util import zstackwoodpecker.test_lib as test_lib import zstackwoodpecker.test_state as test_state import zstackwoodpecker.operations.iam2_operations as iam2_ops import zstackwoodpecker.operations.affini...
if project_uuid: iam2_ops.delete_iam2_project(project_uuid) iam2_ops.expunge_iam2_project(project_uuid) if project_operator_uuid: iam2_ops.delete_iam2_virtual_id(project_operator_uuid) if l2_vxlan_network_uuid: net_ops.delete_l2(l2_vxlan_network_uuid) if vni_range_uuid: ...
identifier_body
test_iam2_project_vpc_cascade_delete.py
''' @auther:fangxiao ''' import apibinding.api_actions as api_actions import zstackwoodpecker.test_util as test_util import zstackwoodpecker.test_lib as test_lib import zstackwoodpecker.test_state as test_state import zstackwoodpecker.operations.iam2_operations as iam2_ops import zstackwoodpecker.operations.affini...
(): if project_uuid: iam2_ops.delete_iam2_project(project_uuid) iam2_ops.expunge_iam2_project(project_uuid) if project_operator_uuid: iam2_ops.delete_iam2_virtual_id(project_operator_uuid) if l2_vxlan_network_uuid: net_ops.delete_l2(l2_vxlan_network_uuid) if vni_range_uui...
error_cleanup
identifier_name
test_iam2_project_vpc_cascade_delete.py
''' @auther:fangxiao ''' import apibinding.api_actions as api_actions import zstackwoodpecker.test_util as test_util import zstackwoodpecker.test_lib as test_lib import zstackwoodpecker.test_state as test_state import zstackwoodpecker.operations.iam2_operations as iam2_ops import zstackwoodpecker.operations.affini...
# 9 delete vni_range_uuid = res_ops.get_resource(res_ops.VNI_RANGE)[0].uuid vxlan_ops.delete_vni_range(vni_range_uuid) net_ops.delete_l2(vxlan_pool_uuid) iam2_ops.delete_iam2_virtual_id(project_operator_uuid) def error_cleanup(): if project_uuid: iam2_ops.delete_iam2_project(pro...
test_util.test_fail( "vpc vr [%s] is still exist after delete and expunge the project [%s]" % (vpc_vr.uuid,project_uuid))
conditional_block
test_iam2_project_vpc_cascade_delete.py
''' @auther:fangxiao ''' import apibinding.api_actions as api_actions import zstackwoodpecker.test_util as test_util import zstackwoodpecker.test_lib as test_lib import zstackwoodpecker.test_state as test_state import zstackwoodpecker.operations.iam2_operations as iam2_ops import zstackwoodpecker.operations.affinit...
test_util.action_logger('[l3:] %s is created' %name) return evt.inventory def AddDnsToL3Network(l3_network_uuid,dns_text,session_uuid = None): action = api_actions.AddDnsToL3NetworkAction() action.sessionUuid = session_uuid action.dns = dns_text action.l3NetworkUuid = l3_network_uuid evt = ...
action.l2NetworkUuid = l2_uuid action.timeout = 300000 action.type = inventory.VPC_L3_NETWORK_TYPE action.sessionUuid = session_uuid evt = acc_ops.execute_action_with_session(action,session_uuid)
random_line_split
bigdigits.py
def bigdigits(line_splitted): line_splitted = list(line_splitted) string_row_one = '-**----*--***--***---*---****--**--****--**---**--' list_row_one = list(string_row_one) string_row_two = '*--*--**-----*----*-*--*-*----*-------*-*--*-*--*-' list_row_two = list(string_row_two) string_row_three = '*--*---*---...
elif(line_splitted[x] >= 48 and line_splitted[x]<=57): pass else: line_splitted.pop(x) x = x-1 line_splitted = [chr(i) for i in line_splitted] for x in range(0,6): current_row = '' for i in range(0,len(line_splitted)): current_number = int(line_splitted[i]) current_row = current_r...
pass
conditional_block
bigdigits.py
def bigdigits(line_splitted): line_splitted = list(line_splitted) string_row_one = '-**----*--***--***---*---****--**--****--**---**--' list_row_one = list(string_row_one) string_row_two = '*--*--**-----*----*-*--*-*----*-------*-*--*-*--*-' list_row_two = list(string_row_two) string_row_three = '*--*---*---...
current_row = current_row + ''.join(rows_formatted[x][current_number*5 : current_number*5+5]) print(current_row) test_cases = open('test_cases','r') for line in test_cases: line_splitted = line.strip() bigdigits(line_splitted)
current_number = int(line_splitted[i])
random_line_split
bigdigits.py
def bigdigits(line_splitted):
test_cases = open('test_cases','r') for line in test_cases: line_splitted = line.strip() bigdigits(line_splitted)
line_splitted = list(line_splitted) string_row_one = '-**----*--***--***---*---****--**--****--**---**--' list_row_one = list(string_row_one) string_row_two = '*--*--**-----*----*-*--*-*----*-------*-*--*-*--*-' list_row_two = list(string_row_two) string_row_three = '*--*---*---**---**--****-***--***----*---**-...
identifier_body
bigdigits.py
def
(line_splitted): line_splitted = list(line_splitted) string_row_one = '-**----*--***--***---*---****--**--****--**---**--' list_row_one = list(string_row_one) string_row_two = '*--*--**-----*----*-*--*-*----*-------*-*--*-*--*-' list_row_two = list(string_row_two) string_row_three = '*--*---*---**---**--****...
bigdigits
identifier_name
index.js
'use strict'; Object.defineProperty(exports, "__esModule", {
}); var _oneLineCommaListsOr = require('./oneLineCommaListsOr'); var _oneLineCommaListsOr2 = _interopRequireDefault(_oneLineCommaListsOr); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = _oneLineCommaListsOr2.default; //# sourceMappingURL=data:applic...
value: true
random_line_split
index.js
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _oneLineCommaListsOr = require('./oneLineCommaListsOr'); var _oneLineCommaListsOr2 = _interopRequireDefault(_oneLineCommaListsOr); function _interopRequireDefault(obj)
exports.default = _oneLineCommaListsOr2.default; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9vbmVMaW5lQ29tbWFMaXN0c09yL2luZGV4LmpzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBOzs7Ozs7QUFFQSIsImZpbGUiOiJpbmRleC5qcyIsInNvdXJjZXNDb250ZW50IjpbIid1c2Ugc3RyaWN0J1xuXG5pbXBvcnQ...
{ return obj && obj.__esModule ? obj : { default: obj }; }
identifier_body
index.js
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _oneLineCommaListsOr = require('./oneLineCommaListsOr'); var _oneLineCommaListsOr2 = _interopRequireDefault(_oneLineCommaListsOr); function
(obj) { return obj && obj.__esModule ? obj : { default: obj }; } exports.default = _oneLineCommaListsOr2.default; //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIi4uLy4uL3NyYy9vbmVMaW5lQ29tbWFMaXN0c09yL2luZGV4LmpzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBOzs7Ozs7QUFFQSIsImZpbGUiOiJpbmR...
_interopRequireDefault
identifier_name
test-dgram-address.js
// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modi...
{ // IPv4 Test const socket = dgram.createSocket('udp4'); socket.on('listening', common.mustCall(() => { const address = socket.address(); assert.strictEqual(address.address, common.localhostIPv4); assert.strictEqual(typeof address.port, 'number'); assert.ok(isFinite(address.port)); assert....
'use strict'; const common = require('../common'); const assert = require('assert'); const dgram = require('dgram');
random_line_split
test-dgram-address.js
// Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modi...
{ // Verify that address() throws if the socket is not bound. const socket = dgram.createSocket('udp4'); assert.throws(() => { socket.address(); }, /^Error: getsockname EINVAL$/); }
{ // IPv6 Test const socket = dgram.createSocket('udp6'); const localhost = '::1'; socket.on('listening', common.mustCall(() => { const address = socket.address(); assert.strictEqual(address.address, localhost); assert.strictEqual(typeof address.port, 'number'); assert.ok(isFinite(address.port...
conditional_block
list1.py
資料 = [1, 2, 3, 4, 5] ''' program: list1.py ''' print(資料[:3]) print(資料[2:]) print(資料[1:2]) a = [3, 5, 7, 11, 13] for x in a: if x == 7: print('list contains 7') break print(list(range(10))) for 索引 in range(-5, 6, 2): print(索引) squares =
in range(0, 11) ] print(squares) a = [10, 'sage', 3.14159] b = a[:] #list.pop([i]) 取出 list 中索引值為 i 的元素,預設是最後一個 print(b.pop()) print(a) 數列 = [0]*10 print(數列) ''' delete 用法 ''' a = [1, 2, 3, 4] print("刪除之前:", a) del a[:2] print("刪除之後:", a)
[ x*x for x
conditional_block
list1.py
資料 = [1, 2, 3, 4, 5] ''' program: list1.py ''' print(資料[:3]) print(資料[2:]) print(資料[1:2]) a = [3, 5, 7, 11, 13] for x in a: if x == 7: print('list contains 7') break print(list(range(10))) for 索引 in range(-5, 6, 2): print(索引) squares = [ x*x for x in range(0, 11) ] print(squares) a = [10, '...
a = [1, 2, 3, 4] print("刪除之前:", a) del a[:2] print("刪除之後:", a)
random_line_split
main.rs
// Copyright 2015-2017 Intecture Developers. // // Licensed under the Mozilla Public License 2.0 <LICENSE or // https://www.tldrlegal.com/l/mpl-2.0>. This file may not be copied, // modified, or distributed except according to those terms. extern crate clap; extern crate env_logger; #[macro_use] extern crate error_cha...
{ remote: Remote, } impl Service for Api { type Request = InMessage; type Response = InMessage; type Error = Error; type Future = Box<Future<Item = Self::Response, Error = Self::Error>>; fn call(&self, req: Self::Request) -> Self::Future { let request = match Request::from_msg(req) ...
NewApi
identifier_name
main.rs
// Copyright 2015-2017 Intecture Developers. // // Licensed under the Mozilla Public License 2.0 <LICENSE or // https://www.tldrlegal.com/l/mpl-2.0>. This file may not be copied, // modified, or distributed except according to those terms. extern crate clap; extern crate env_logger; #[macro_use] extern crate error_cha...
} impl NewService for NewApi { type Request = InMessage; type Response = InMessage; type Error = Error; type Instance = Api; fn new_service(&self) -> io::Result<Self::Instance> { // XXX Danger zone! If we're running multiple threads, this `unwrap()` // will explode. The API require...
{ let request = match Request::from_msg(req) .chain_err(|| "Malformed Request") { Ok(r) => r, Err(e) => return Box::new(future::ok(error_to_msg(e))), }; Box::new(request.exec(&self.host) .chain_err(|| "Failed to execute Request") ...
identifier_body
main.rs
// Copyright 2015-2017 Intecture Developers. // // Licensed under the Mozilla Public License 2.0 <LICENSE or // https://www.tldrlegal.com/l/mpl-2.0>. This file may not be copied, // modified, or distributed except according to those terms. extern crate clap; extern crate env_logger; #[macro_use] extern crate error_cha...
quick_main!(|| -> Result<()> { env_logger::init().chain_err(|| "Could not start logging")?; let matches = clap::App::new("Intecture Agent") .version(env!("CARGO_PKG_VERSION")) .author(env!("CARGO_PKG_AUTHORS")) .about(env!("CAR...
random_line_split
UnsavedChangesPrompt.tsx
import React, { useState, useEffect, SetStateAction } from 'react'; import { Location } from 'history'; import { Prompt, Redirect } from 'react-router'; import { Modal } from './Modal'; import { ModalConfirmation } from "./ModalConfirmation"; export interface UnsavedChangesPromptProps { showModal: boolean; setShow...
if (okConfirmed) { handleConfirm && handleConfirm(); } }, [okConfirmed]); return ( <> <Prompt when={hasUnsavedChanges} message={(nextLocation) => navAwayHandler(nextLocation)} /> <Modal isActive={showModal}> <ModalConfirmation cancelButtonLabel={cancelButtonLabel || 'No, Can...
random_line_split
UnsavedChangesPrompt.tsx
import React, { useState, useEffect, SetStateAction } from 'react'; import { Location } from 'history'; import { Prompt, Redirect } from 'react-router'; import { Modal } from './Modal'; import { ModalConfirmation } from "./ModalConfirmation"; export interface UnsavedChangesPromptProps { showModal: boolean; setShow...
if (!okConfirmed) { setShowModal(true); } setNextLocation(location); return okConfirmed; }; const modalConfirmHandler = () => { setShowModal(false); setOkConfirmed(true); } const modalCancelHandler = () => { setShowModal(false); handleCancel && handleCancel(); } u...
{ return true; }
conditional_block
array.rs
//! Array with SIMD alignment use crate::types::*; use ffi; use num_traits::Zero; use std::ops::{Deref, DerefMut}; use std::os::raw::c_void; use std::slice::{from_raw_parts, from_raw_parts_mut}; /// A RAII-wrapper of `fftw_alloc` and `fftw_free` with the [SIMD alignment]. /// /// [SIMD alignment]: http://www.fftw.or...
(n: usize) -> Self { let ptr = excall! { T::alloc(n) }; let mut vec = AlignedVec { n: n, data: ptr }; for v in vec.iter_mut() { *v = T::zero(); } vec } } impl<T> Drop for AlignedVec<T> { fn drop(&mut self) { excall! { ffi::fftw_free(self.data as *mut ...
new
identifier_name
array.rs
//! Array with SIMD alignment use crate::types::*; use ffi; use num_traits::Zero; use std::ops::{Deref, DerefMut}; use std::os::raw::c_void; use std::slice::{from_raw_parts, from_raw_parts_mut}; /// A RAII-wrapper of `fftw_alloc` and `fftw_free` with the [SIMD alignment]. /// /// [SIMD alignment]: http://www.fftw.or...
} impl AlignedAllocable for f32 { unsafe fn alloc(n: usize) -> *mut Self { ffi::fftwf_alloc_real(n) } } impl AlignedAllocable for c64 { unsafe fn alloc(n: usize) -> *mut Self { ffi::fftw_alloc_complex(n) } } impl AlignedAllocable for c32 { unsafe fn alloc(n: usize) -> *mut Self {...
{ ffi::fftw_alloc_real(n) }
identifier_body
array.rs
//! Array with SIMD alignment use crate::types::*; use ffi; use num_traits::Zero; use std::ops::{Deref, DerefMut}; use std::os::raw::c_void; use std::slice::{from_raw_parts, from_raw_parts_mut}; /// A RAII-wrapper of `fftw_alloc` and `fftw_free` with the [SIMD alignment]. /// /// [SIMD alignment]: http://www.fftw.or...
ffi::fftw_alloc_complex(n) } } impl AlignedAllocable for c32 { unsafe fn alloc(n: usize) -> *mut Self { ffi::fftwf_alloc_complex(n) } } impl<T> AlignedVec<T> { pub fn as_slice(&self) -> &[T] { unsafe { from_raw_parts(self.data, self.n) } } pub fn as_slice_mut(&mut self...
impl AlignedAllocable for c64 { unsafe fn alloc(n: usize) -> *mut Self {
random_line_split
fuzz_one.py
#!/usr/bin/env python # Copyright 2020 the V8 project authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. """ Helper script to execute a single-processed fuzzing session. Creates fuzz tests in workdir/output/dir-<dir number>/fuzz-XXX.js....
with open(os.path.join(path, 'duration.log'), 'w') as f: f.write(str(duration))
random_line_split
RenderableBehavior.ts
import {Node} from '../core/Node.js' /** * Base class for behaviors relating to rendering. This is for any behavior that renders with CSS or WebGL rendering. */ export abstract class RenderableBehavior extends Behavior { requiredElementType() { return [Node] } connectedCallback() { super.connectedCallback() ...
import {Behavior} from './Behavior.js' import {Events} from '../core/Events.js'
random_line_split
RenderableBehavior.ts
import {Behavior} from './Behavior.js' import {Events} from '../core/Events.js' import {Node} from '../core/Node.js' /** * Base class for behaviors relating to rendering. This is for any behavior that renders with CSS or WebGL rendering. */ export abstract class RenderableBehavior extends Behavior { requiredElement...
_cssLoaded = false loadGL(): boolean { if (!this.element.three) return false if (this._glLoaded) return false this._glLoaded = true return true } unloadGL(): boolean { if (!this._glLoaded) return false this._glLoaded = false return true } }
{ return this._cssLoaded }
identifier_body
RenderableBehavior.ts
import {Behavior} from './Behavior.js' import {Events} from '../core/Events.js' import {Node} from '../core/Node.js' /** * Base class for behaviors relating to rendering. This is for any behavior that renders with CSS or WebGL rendering. */ export abstract class RenderableBehavior extends Behavior { requiredElement...
() { return this._cssLoaded } _cssLoaded = false loadGL(): boolean { if (!this.element.three) return false if (this._glLoaded) return false this._glLoaded = true return true } unloadGL(): boolean { if (!this._glLoaded) return false this._glLoaded = false return true } }
cssLoaded
identifier_name
classes.js
var _ = require("lodash"); var Q = require("q"); var utils = require("./utils.js"); _.indexBy = utils.getIndexBy(_); // Craql 4.2 // Each vertex has an ID, a set of // properties, and a set of labelled edges. Vertices are stored in a hash table (dictionary) structure // indexed by the ID for quick lookup. Th...
(vertices, edges) { this.vertices = _.indexBy(vertices, 'id'); this.edges = _.indexBy(edges, 'label'); } Graph.prototype = { addVertex: function(vertex) {this.vertices[vertex.id] = vertex}, addEdge: function(edge) {this.edges[edge.label] = edge} }; function Vertex(id, properties) { this.i...
Graph
identifier_name
classes.js
var _ = require("lodash"); var Q = require("q"); var utils = require("./utils.js"); _.indexBy = utils.getIndexBy(_); // Craql 4.2 // Each vertex has an ID, a set of // properties, and a set of labelled edges. Vertices are stored in a hash table (dictionary) structure // indexed by the ID for quick lookup. Th...
Edge.prototype = {}; module.exports = { Graph: Graph, Vertex: Vertex, Edge: Edge }
{ return { label: label, startId: startId, endId: endId, properties: properties }; }
identifier_body
classes.js
var _ = require("lodash"); var Q = require("q"); var utils = require("./utils.js"); _.indexBy = utils.getIndexBy(_); // Craql 4.2 // Each vertex has an ID, a set of // properties, and a set of labelled edges. Vertices are stored in a hash table (dictionary) structure // indexed by the ID for quick lookup. Th...
Vertex: Vertex, Edge: Edge }
module.exports = { Graph: Graph,
random_line_split
mod.rs
mod api; use gcrypt; use hyper; use rustc_serialize::base64; use rustc_serialize::hex; use rustc_serialize::json; use crypto; use std::fmt; use std::io; use rustc_serialize::base64::FromBase64; use rustc_serialize::hex::FromHex; use rustc_serialize::hex::ToHex; #[derive(Debug)] pub enum KeybaseError { Http(St...
(err: gcrypt::error::Error) -> KeybaseError { KeybaseError::Gcrypt(err) } } impl From<hyper::Error> for KeybaseError { fn from(err: hyper::Error) -> KeybaseError { KeybaseError::Hyper(err) } } impl From<io::Error> for KeybaseError { fn from(err: io::Error) -> KeybaseError { Keyb...
from
identifier_name
mod.rs
mod api; use gcrypt; use hyper; use rustc_serialize::base64; use rustc_serialize::hex; use rustc_serialize::json; use crypto; use std::fmt; use std::io; use rustc_serialize::base64::FromBase64; use rustc_serialize::hex::FromHex; use rustc_serialize::hex::ToHex; #[derive(Debug)] pub enum KeybaseError { Http(St...
} } impl From<json::DecoderError> for KeybaseError { fn from(err: json::DecoderError) -> KeybaseError { KeybaseError::Json(err) } } impl fmt::Display for KeybaseError { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match *self { KeybaseError::Http(ref msg) => write...
impl From<io::Error> for KeybaseError { fn from(err: io::Error) -> KeybaseError { KeybaseError::Io(err)
random_line_split
event.js
/* ***** BEGIN LICENSE BLOCK ***** * Distributed under the BSD license: * * Copyright (c) 2010, Ajax.org B.V. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of sou...
return result; }); addListener(el, "keypress", function(e) { if (lastDefaultPrevented && (e.ctrlKey || e.altKey || e.shiftKey || e.metaKey)) { exports.stopEvent(e); lastDefaultPrevented = null; } }); addListener(el, "k...
lastDefaultPrevented = e.defaultPrevented;
random_line_split
event.js
/* ***** BEGIN LICENSE BLOCK ***** * Distributed under the BSD license: * * Copyright (c) 2010, Ajax.org B.V. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of sou...
(e) { eventHandler && eventHandler(e); releaseCaptureHandler && releaseCaptureHandler(e); exports.removeListener(document, "mousemove", eventHandler, true); exports.removeListener(document, "mouseup", onMouseUp, true); exports.removeListener(document, "dragstart", onMouseUp, tru...
onMouseUp
identifier_name
event.js
/* ***** BEGIN LICENSE BLOCK ***** * Distributed under the BSD license: * * Copyright (c) 2010, Ajax.org B.V. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of sou...
else { var lastDefaultPrevented = null; addListener(el, "keydown", function(e) { pressedKeys[e.keyCode] = (pressedKeys[e.keyCode] || 0) + 1; var result = normalizeCommandKeys(callback, e, e.keyCode); lastDefaultPrevented = e.defaultPrevented; return resu...
{ // Old versions of Gecko aka. Firefox < 4.0 didn't repeat the keydown // event if the user pressed the key for a longer time. Instead, the // keydown event was fired once and later on only the keypress event. // To emulate the 'right' keydown behavior, the keyCode of the initial ...
conditional_block
event.js
/* ***** BEGIN LICENSE BLOCK ***** * Distributed under the BSD license: * * Copyright (c) 2010, Ajax.org B.V. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of sou...
var pressedKeys = null; var ts = 0; exports.addCommandKeyListener = function(el, callback) { var addListener = exports.addListener; if (useragent.isOldGecko || (useragent.isOpera && !("KeyboardEvent" in window))) { // Old versions of Gecko aka. Firefox < 4.0 didn't repeat the keydown // event ...
{ var hashId = getModifierHash(e); if (!useragent.isMac && pressedKeys) { if (pressedKeys[91] || pressedKeys[92]) hashId |= 8; if (pressedKeys.altGr) { if ((3 & hashId) != 3) pressedKeys.altGr = 0; else return; } ...
identifier_body
borrowck-lend-flow-if.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} } fn main() {}
let _w; if cond() { _w = &v; } else { borrow_mut(v);
random_line_split
borrowck-lend-flow-if.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
borrow_mut(v); //~ ERROR cannot borrow } fn pre_freeze_else() { // In this instance, the freeze and mut borrow are on separate sides // of the if. let mut v = ~3; let _w; if cond() { _w = &v; } else { borrow_mut(v); } } fn main() {}
{ _w = &v; }
conditional_block
borrowck-lend-flow-if.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
fn produce<T>() -> T { fail!(); } fn inc(v: &mut ~int) { *v = ~(**v + 1); } fn pre_freeze_cond() { // In this instance, the freeze is conditional and starts before // the mut borrow. let mut v = ~3; let _w; if cond() { _w = &v; } borrow_mut(v); //~ ERROR cannot borrow } fn p...
{ fail!() }
identifier_body
borrowck-lend-flow-if.rs
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
(_v: &mut int) {} fn cond() -> bool { fail!() } fn for_func(_f: || -> bool) { fail!() } fn produce<T>() -> T { fail!(); } fn inc(v: &mut ~int) { *v = ~(**v + 1); } fn pre_freeze_cond() { // In this instance, the freeze is conditional and starts before // the mut borrow. let mut v = ~3; let _w; ...
borrow_mut
identifier_name
cssClient.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
} return null; } }); } commands.registerCommand('_css.applyCodeAction', applyCodeAction); function applyCodeAction(uri: string, documentVersion: number, edits: TextEdit[]) { let textEditor = window.activeTextEditor; if (textEditor && textEditor.document.uri.toString() === uri) { if (textEditor....
random_line_split
cssClient.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
(item: CompletionItem) { const range = item.range; if (range instanceof Range && range.end.isAfter(position) && range.start.isBeforeOrEqual(position)) { item.range = { inserting: new Range(range.start, position), replacing: range }; } } function updateLabel(item: CompletionItem) { if ...
updateRanges
identifier_name
cssClient.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
} // testing the new completion function updateProposals(r: CompletionItem[] | CompletionList | null | undefined): CompletionItem[] | CompletionList | null | undefined { if (r) { (Array.isArray(r) ? r : r.items).forEach(updateRanges); (Array.isArray(r) ? r : r.items).forEach(updateLabel); ...
{ item.label2 = { name: item.label, type: (item.documentation as string) }; }
conditional_block
cssClient.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
{ const customDataSource = getCustomDataSource(context.subscriptions); let documentSelector = ['css', 'scss', 'less']; // Options to control the language client let clientOptions: LanguageClientOptions = { documentSelector, synchronize: { configurationSection: ['css', 'scss', 'less'] }, initialization...
identifier_body
FilestoreModel.js
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you ...
{ name: 'parentId', type: 'int' }, { name: 'childCount', type: 'int' }, { name: 'created', type: 'int' }, { name: 'canUpdate', type: 'boolean' }, { name: 'canDelete', type: 'boolean' } ] });
{ name: 'serverName', type: 'string' }, { name: 'port', type: 'int', defaultValue: 8080 }, { name: 'urlPath', type: 'string' }, { name: 'status', type: 'string' }, { name: 'serverDirectory', type: 'string' },
random_line_split
pipeline.model.ts
import { AsCodeEvents } from './ascode.model'; import { Parameter } from './parameter.model'; import { Stage } from './stage.model'; import { Usage } from './usage.model'; import { Workflow } from './workflow.model'; export const pipelineNamePattern = new RegExp('^[a-zA-Z0-9._-]+$'); export class PipelineStatus { ...
return PipelineStatus.priority[sum]; } } export class PipelineAudit { id: number; username: string; versionned: Date; pipeline: Pipeline; action: string; } export class PipelineAuditDiff { type: string; before: any; after: any; title: string; } export class Pipeline {...
{ return null; }
conditional_block
pipeline.model.ts
import { AsCodeEvents } from './ascode.model'; import { Parameter } from './parameter.model'; import { Stage } from './stage.model'; import { Usage } from './usage.model'; import { Workflow } from './workflow.model'; export const pipelineNamePattern = new RegExp('^[a-zA-Z0-9._-]+$'); export class PipelineStatus { ...
before: any; after: any; title: string; } export class Pipeline { id: number; name: string; description: string; icon: string; stages: Array<Stage>; parameters: Array<Parameter>; last_modified: number; projectKey: string; usage: Usage; audits: Array<PipelineAudit>; ...
random_line_split
pipeline.model.ts
import { AsCodeEvents } from './ascode.model'; import { Parameter } from './parameter.model'; import { Stage } from './stage.model'; import { Usage } from './usage.model'; import { Workflow } from './workflow.model'; export const pipelineNamePattern = new RegExp('^[a-zA-Z0-9._-]+$'); export class PipelineStatus { ...
() { this.usage = new Usage(); } // Return true if pattern is good public static checkName(name: string): boolean { if (!name) { return false; } return pipelineNamePattern.test(name); } public static hasParameterWithoutValue(pipeline: Pipeline) { ...
constructor
identifier_name
TextAnalyzer.py
import codecs import logging logger = logging.getLogger(__name__) class TextAnalyzer: def __init__(self): logger.debug('-- Initializing TextAnalyzer --') """ Deze functie leest een stopwoorden file (stoplist_tno.tab) in en retourneert deze woorden in een dictionary ""...
""" read stopwords from file as dictionary. """ stopWords = {} try: f = codecs.open(strStopFile,'rU','utf-8') # NB. Use 'U'-mode for UniversalNewline Support for line in f.readlines(): word = line.partition('::')[0].strip()#.decode('utf-8') ...
strStopFile = self._stopWordsFile
conditional_block
TextAnalyzer.py
import codecs import logging logger = logging.getLogger(__name__) class TextAnalyzer: def __init__(self): logger.debug('-- Initializing TextAnalyzer --') """ Deze functie leest een stopwoorden file (stoplist_tno.tab) in en retourneert deze woorden in een dictionary ""...
stopWords[word] = 1 f.close() except IOError, e: msg = 'Can\'t open stopfile %s for reading. %s' % (strStopFile, str(e)) logger.error(msg) return None return stopWords
random_line_split
TextAnalyzer.py
import codecs import logging logger = logging.getLogger(__name__) class
: def __init__(self): logger.debug('-- Initializing TextAnalyzer --') """ Deze functie leest een stopwoorden file (stoplist_tno.tab) in en retourneert deze woorden in een dictionary """ def readStopWordsFile(self, strStopFile): if not strStopFile: ...
TextAnalyzer
identifier_name
TextAnalyzer.py
import codecs import logging logger = logging.getLogger(__name__) class TextAnalyzer: def __init__(self):
""" Deze functie leest een stopwoorden file (stoplist_tno.tab) in en retourneert deze woorden in een dictionary """ def readStopWordsFile(self, strStopFile): if not strStopFile: strStopFile = self._stopWordsFile """ read stopwords from file as dictionary. """ ...
logger.debug('-- Initializing TextAnalyzer --')
identifier_body
mod.rs
mod version; mod init; mod config; mod ignore; mod sweep; mod burn; mod start; mod end; mod destroy; mod patrol; use self::version::Version; use self::init::Init; use self::config::Config; use self::ignore::Ignore; use self::sweep::Sweep; use self::burn::Burn; use self::start::Start; use self::end::End; use self::dest...
(&self) -> bool { true } fn check_settings(&self) -> Result<(), EssentialLack> { if !setting::working_dir_exists() { return Err(EssentialLack::new(EssentialKind::WorkingDir)); } if !setting::Storage::exist() { return Err(EssentialLack::new(EssentialKind::StorageDir));...
allow_to_check_settings
identifier_name
mod.rs
mod version; mod init; mod config; mod ignore; mod sweep; mod burn; mod start; mod end; mod destroy; mod patrol; use self::version::Version; use self::init::Init; use self::config::Config; use self::ignore::Ignore; use self::sweep::Sweep; use self::burn::Burn; use self::start::Start; use self::end::End; use self::dest...
fn allow_to_check_settings(&self) -> bool { true } fn check_settings(&self) -> Result<(), EssentialLack> { if !setting::working_dir_exists() { return Err(EssentialLack::new(EssentialKind::WorkingDir)); } if !setting::Storage::exist() { return Err(EssentialLack::...
{ let current_dir = try!(env::current_dir()); match BANNED_DIRS.iter().find(|d| current_dir.ends_with(d)) { Some(d) => Err(From::from(RunningPlaceError::new(d.to_string()))), None => Ok(()), } }
identifier_body
mod.rs
mod version; mod init; mod config; mod ignore; mod sweep; mod burn; mod start; mod end; mod destroy; mod patrol; use self::version::Version; use self::init::Init; use self::config::Config; use self::ignore::Ignore; use self::sweep::Sweep; use self::burn::Burn; use self::start::Start; use self::end::End; use self::dest...
}; match command.as_ref() { "version" => Version .exec(need_help), "init" => Init .exec(need_help), "config" => Config::new(args.next(), args.next(), args.next()).exec(need_help), "ignore"...
} else { (command, false)
random_line_split
es_backup.py
#!/usr/bin/env python import time, logging, argparse, json, sys from es_manager import ElasticsearchSnapshotManager, get_parser from elasticsearch import exceptions logging.basicConfig(level=logging.INFO) logger = logging.getLogger('elasticsearch') def take_snapshot(options):
if __name__ == '__main__': parser = get_parser("This script will take a snapshot and upload to S3") parser.add_argument("--wait", action="store_true", default=True, help="Wait for the backup to complete") parser.add_argument("--keep", action="store", default=60, help="Number of Elasticsearch snapshots to ...
esm = ElasticsearchSnapshotManager(options) sh = esm.sh snapshot = options.snapshot and options.snapshot or 'all_' + time.strftime('%Y%m%d%H') snapdef = { "include_global_state": True } if options.indices: snapdef['indices'] = ','.join(options.indices) try: sh.create(...
identifier_body
es_backup.py
from elasticsearch import exceptions logging.basicConfig(level=logging.INFO) logger = logging.getLogger('elasticsearch') def take_snapshot(options): esm = ElasticsearchSnapshotManager(options) sh = esm.sh snapshot = options.snapshot and options.snapshot or 'all_' + time.strftime('%Y%m%d%H') snapdef ...
#!/usr/bin/env python import time, logging, argparse, json, sys from es_manager import ElasticsearchSnapshotManager, get_parser
random_line_split
es_backup.py
#!/usr/bin/env python import time, logging, argparse, json, sys from es_manager import ElasticsearchSnapshotManager, get_parser from elasticsearch import exceptions logging.basicConfig(level=logging.INFO) logger = logging.getLogger('elasticsearch') def
(options): esm = ElasticsearchSnapshotManager(options) sh = esm.sh snapshot = options.snapshot and options.snapshot or 'all_' + time.strftime('%Y%m%d%H') snapdef = { "include_global_state": True } if options.indices: snapdef['indices'] = ','.join(options.indices) try: ...
take_snapshot
identifier_name
es_backup.py
#!/usr/bin/env python import time, logging, argparse, json, sys from es_manager import ElasticsearchSnapshotManager, get_parser from elasticsearch import exceptions logging.basicConfig(level=logging.INFO) logger = logging.getLogger('elasticsearch') def take_snapshot(options): esm = ElasticsearchSnapshotManager(o...
except exceptions.TransportError as e: pass if __name__ == '__main__': parser = get_parser("This script will take a snapshot and upload to S3") parser.add_argument("--wait", action="store_true", default=True, help="Wait for the backup to complete") parser.add_argument("--keep", action="store",...
sh.delete(repository=options.repository, snapshot=snap['snapshot'], request_timeout=3600) logger.info('Deleted snapshot %s' % snap['snapshot'])
conditional_block
error.rs
use crate::{constants::MAX_PRECISION_U32, Decimal}; use alloc::string::String; use core::fmt; /// Error type for the library. #[derive(Clone, Debug, PartialEq)] pub enum Error { ErrorString(String), ExceedsMaximumPossibleValue, LessThanMinimumPossibleValue, Underflow, ScaleExceedsMaximumPrecision(u...
(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match *self { Self::ErrorString(ref err) => f.pad(err), Self::ExceedsMaximumPossibleValue => { write!(f, "Number exceeds maximum value that can be represented.") } Self::LessThanMinimumPossibleVa...
fmt
identifier_name
error.rs
use crate::{constants::MAX_PRECISION_U32, Decimal}; use alloc::string::String; use core::fmt; /// Error type for the library. #[derive(Clone, Debug, PartialEq)] pub enum Error { ErrorString(String),
} impl<S> From<S> for Error where S: Into<String>, { #[inline] fn from(from: S) -> Self { Self::ErrorString(from.into()) } } #[cold] pub(crate) fn tail_error(from: &'static str) -> Result<Decimal, Error> { Err(from.into()) } #[cfg(feature = "std")] impl std::error::Error for Error {} imp...
ExceedsMaximumPossibleValue, LessThanMinimumPossibleValue, Underflow, ScaleExceedsMaximumPrecision(u32),
random_line_split
error.rs
use crate::{constants::MAX_PRECISION_U32, Decimal}; use alloc::string::String; use core::fmt; /// Error type for the library. #[derive(Clone, Debug, PartialEq)] pub enum Error { ErrorString(String), ExceedsMaximumPossibleValue, LessThanMinimumPossibleValue, Underflow, ScaleExceedsMaximumPrecision(u...
Self::ScaleExceedsMaximumPrecision(ref scale) => { write!( f, "Scale exceeds the maximum precision allowed: {} > {}", scale, MAX_PRECISION_U32 ) } } } }
{ write!(f, "Number has a high precision that can not be represented.") }
conditional_block
error.rs
use crate::{constants::MAX_PRECISION_U32, Decimal}; use alloc::string::String; use core::fmt; /// Error type for the library. #[derive(Clone, Debug, PartialEq)] pub enum Error { ErrorString(String), ExceedsMaximumPossibleValue, LessThanMinimumPossibleValue, Underflow, ScaleExceedsMaximumPrecision(u...
}
{ match *self { Self::ErrorString(ref err) => f.pad(err), Self::ExceedsMaximumPossibleValue => { write!(f, "Number exceeds maximum value that can be represented.") } Self::LessThanMinimumPossibleValue => { write!(f, "Number less tha...
identifier_body
cli.js
#!/usr/bin/env node // // cli.js // // Copyright (c) 2016-2017 Junpei Kawamoto // // This software is released under the MIT License. // // http://opensource.org/licenses/mit-license.php // const { start, crawl } = require("../lib/crawler"); const argv = require("yargs") .option("lang", { describe...
.argv;
.help("h") .alias("h", "help")
random_line_split
AutoincrementalField.py
# -*- coding: utf-8 -*- """ *************************************************************************** AutoincrementalField.py --------------------- Date : August 2012 Copyright : (C) 2012 by Victor Olaya Email : volayaf at gmail dot com ******************...
(GeoAlgorithm): INPUT = 'INPUT' OUTPUT = 'OUTPUT' def processAlgorithm(self, progress): output = self.getOutputFromName(self.OUTPUT) vlayer = \ dataobjects.getObjectFromUri(self.getParameterValue(self.INPUT)) vprovider = vlayer.dataProvider() fields = vprovider....
AutoincrementalField
identifier_name
AutoincrementalField.py
# -*- coding: utf-8 -*- """ *************************************************************************** AutoincrementalField.py --------------------- Date : August 2012 Copyright : (C) 2012 by Victor Olaya Email : volayaf at gmail dot com ******************...
self.name = 'Add autoincremental field' self.group = 'Vector table tools' self.addParameter(ParameterVector(self.INPUT, self.tr('Input layer'), [ParameterVector.VECTOR_TYPE_ANY])) self.addOutput(OutputVector(self.OUTPUT, self.tr('Incremented')))
identifier_body
AutoincrementalField.py
# -*- coding: utf-8 -*- """ *************************************************************************** AutoincrementalField.py --------------------- Date : August 2012 Copyright : (C) 2012 by Victor Olaya Email : volayaf at gmail dot com ******************...
del writer def defineCharacteristics(self): self.name = 'Add autoincremental field' self.group = 'Vector table tools' self.addParameter(ParameterVector(self.INPUT, self.tr('Input layer'), [ParameterVector.VECTOR_TYPE_ANY])) self.addOutput(OutputVector(self.OUTPU...
progress.setPercentage(int(100 * nElement / nFeat)) nElement += 1 inGeom = inFeat.geometry() outFeat.setGeometry(inGeom) attrs = inFeat.attributes() attrs.append(nElement) outFeat.setAttributes(attrs) writer.addFeature(outFeat)
conditional_block
AutoincrementalField.py
# -*- coding: utf-8 -*- """ *************************************************************************** AutoincrementalField.py --------------------- Date : August 2012 Copyright : (C) 2012 by Victor Olaya Email : volayaf at gmail dot com ******************...
__date__ = 'August 2012' __copyright__ = '(C) 2012, Victor Olaya' # This will get replaced with a git SHA1 when you do a git archive __revision__ = '$Format:%H$' from PyQt4.QtCore import QVariant from qgis.core import QgsField, QgsFeature, QgsGeometry from processing.core.GeoAlgorithm import GeoAlgorithm from proces...
random_line_split
index.d.ts
interface FilepickerStatic { setKey(key: string); /* Pick files From the cloud direct to your site */ pick(options: FilepickerOptions, onSuccess: (result: FilepickerInkBlob) => void, onError?: (fpError: any) => void); /* Pick files From the cloud direct to your site */ pick(onSuccess: (result: File...
} interface FilepickerStoreOptions { /* * Where to store the file. The default is S3. Other options are 'azure', 'dropbox' and 'rackspace'. You must have configured your storage in the developer portal to enable this feature. * * Rackspace, Azure and Dropbox are only available on the Grow and higher...
interface FilepickerMultipleFilePickOptions extends FilepickerOptions { /* Specify the maximum number of files that the user can upload at a time. If the user tries to upload more than this, they will be presented with an error message. By default, there is no cap on the number of files. */ maxFiles?: number; ...
random_line_split
Utils.ts
/** * Copyright (c) Tiny Technologies, Inc. All rights reserved. * Licensed under the LGPL or a commercial license. * For LGPL see License.txt in the project root for license information. * For commercial licenses see https://www.tiny.cloud/ */ import { Unicode } from '@ephox/katamari'; import DomParser from 'tin...
else { content = content.replace(v[0], v[1]); } }); return content; }; /** * Gets the innerText of the specified element. It will handle edge cases * and works better than textContent on Gecko. * * @param {String} html HTML string to get text from. * @return {String} String of text with line feeds...
{ content = content.replace(v, ''); }
conditional_block
Utils.ts
/** * Copyright (c) Tiny Technologies, Inc. All rights reserved. * Licensed under the LGPL or a commercial license. * For LGPL see License.txt in the project root for license information. * For commercial licenses see https://www.tiny.cloud/ */ import { Unicode } from '@ephox/katamari'; import DomParser from 'tin...
if (name === 'br') { text += '\n'; return; } // Ignore wbr, to replicate innerText on Chrome/Firefox if (name === 'wbr') { return; } // img/input/hr but ignore wbr as it's just a potential word break if (shortEndedElements[name]) { text += ' '; } // Ignore...
random_line_split
user-config.ts
import { BuildType, Environment, ModuleType } from '.' /** * Types for config file */ export interface UserConfig { /** javascript environment */ environments: Environment[] /** directory to output to */ outdir: string | null /** Definitions generation type */ buildType?: BuildType /** Mo...
/** Do not generate documentation comments */ noComments: boolean }
random_line_split
compare_crud_spec.ts
/* * Copyright 2019 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agr...
() { return { status: 200, responseHeaders: { "Content-Type": "application/vnd.go.cd.v1+json; charset=utf-8", "ETag": "some-etag" }, responseText: JSON.stringify(ComparisonData.compare()) }; }
comparisonResponse
identifier_name
compare_crud_spec.ts
/* * Copyright 2019 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agr...
const onResponse = jasmine.createSpy().and.callFake((response: ApiResult<any>) => { const responseJSON = response.unwrap() as SuccessResponse<any>; const object = (responseJSON.body as Comparison); expect(object.pipelineName).toEqual("pipeline1"); expect(object.fromCounter).toEqual(1)...
it('should get the difference between the two counters for the given pipeline', (done) => { const apiPath = SparkRoutes.comparePipelines("pipeline1", 1, 3); jasmine.Ajax.stubRequest(apiPath).andReturn(comparisonResponse());
random_line_split
compare_crud_spec.ts
/* * Copyright 2019 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agr...
{ return { status: 200, responseHeaders: { "Content-Type": "application/vnd.go.cd.v1+json; charset=utf-8", "ETag": "some-etag" }, responseText: JSON.stringify(ComparisonData.compare()) }; }
identifier_body
createSampleVideo.py
# -*- coding: utf-8 -*- """ Created on Wed May 18 18:22:12 2016 @author: ajaver """ import os import cv2 import tables import numpy as np from tierpsy.helper.params import read_fps from tierpsy.helper.misc import TimeCounter, print_flush def getSubSampleVidName(masked_image_file): #used by AnalysisPoints.py an...
(masked_image_file, sample_video_name = '', time_factor = 8, size_factor = 5, skip_factor = 2, dflt_fps=30, codec='MPEG', shift_bgnd = False): #skip factor is to reduce th...
createSampleVideo
identifier_name
createSampleVideo.py
# -*- coding: utf-8 -*- """ Created on Wed May 18 18:22:12 2016 @author: ajaver """ import os import cv2 import tables import numpy as np from tierpsy.helper.params import read_fps from tierpsy.helper.misc import TimeCounter, print_flush def getSubSampleVidName(masked_image_file): #used by AnalysisPoints.py an...
if shift_bgnd: #lazy bgnd calculation, just take the last and first frame and get the top 95 pixel value mm = masks[[0,-1], :, :] _bgnd_val = np.percentile(mm[mm!=0], [97.5])[0] for frame_number in range(0, tot_frames, int(time_factor*skip_factor)): cu...
assert vid_writer.isOpened()
random_line_split
createSampleVideo.py
# -*- coding: utf-8 -*- """ Created on Wed May 18 18:22:12 2016 @author: ajaver """ import os import cv2 import tables import numpy as np from tierpsy.helper.params import read_fps from tierpsy.helper.misc import TimeCounter, print_flush def getSubSampleVidName(masked_image_file): #used by AnalysisPoints.py an...
#%% if __name__ == '__main__': #mask_file_name = '/Volumes/behavgenom_archive$/Avelino/Worm_Rig_Tests/Agar_Test/MaskedVideos/Agar_Screening_101116/N2_N10_F1-3_Set1_Pos3_Ch6_12112016_002739.hdf5' #masked_image_file = '/Volumes/behavgenom_archive$/Avelino/Worm_Rig_Tests/Agar_Test/MaskedVideos/Agar_Screenin...
if not sample_video_name: sample_video_name = getSubSampleVidName(masked_image_file) # initialize timers base_name = masked_image_file.rpartition('.')[0].rpartition(os.sep)[-1] progressTime = TimeCounter('{} Generating subsampled video.'.format(base_name)) with tables.File(masked_image...
identifier_body
createSampleVideo.py
# -*- coding: utf-8 -*- """ Created on Wed May 18 18:22:12 2016 @author: ajaver """ import os import cv2 import tables import numpy as np from tierpsy.helper.params import read_fps from tierpsy.helper.misc import TimeCounter, print_flush def getSubSampleVidName(masked_image_file): #used by AnalysisPoints.py an...
vid_writer.release() print_flush(progressTime.get_str(frame_number) + ' DONE.') #%% if __name__ == '__main__': #mask_file_name = '/Volumes/behavgenom_archive$/Avelino/Worm_Rig_Tests/Agar_Test/MaskedVideos/Agar_Screening_101116/N2_N10_F1-3_Set1_Pos3_Ch6_12112016_002739.hdf5' #masked_image...
current_frame = int(tt_vec[frame_number]) img = masks[current_frame] if shift_bgnd: img[img==0] = _bgnd_val im_new = cv2.resize(img, (im_w,im_h)) vid_writer.write(im_new) if frame_number % (500*time_factor) == 0: # calculate ...
conditional_block
app-store.purchase-handler.ts
import {PurchaseHandler} from "./purchase-handler"; import {ProductData, productDataMap} from "./products"; import * as appleReceiptVerify from "node-apple-receipt-verify"; import {APP_STORE_SHARED_SECRET} from "./constants"; import {IapRepository} from "./iap.repository"; import {firestore} from "firebase-admin/lib/fi...
( userId: string, token: string, ): Promise<boolean> { // Validate receipt and fetch the products let products: appleReceiptVerify.PurchasedProducts[]; try { products = await appleReceiptVerify.validate({receipt: token}); } catch (e) { if (e instanceof appleReceiptVerify.EmptyE...
handleValidation
identifier_name