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
leap.js
/** * Copyright (c) 2013, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * https://raw.github.com/facebook/regenerator/master/LICENSE file. An * additional grant of patent rights can be found in the PATENTS file in * the same directory. */ var as...
return loc; }; function getLeapLocation(entry, property, label) { var loc = entry[property]; if (loc) { if (label) { if (entry.label && entry.label.name === label.name) { return loc; } } else { return loc; } } return null; } LMp.emitBreak = function(label) {...
{ this.emitter.emitAssign(finallyEntry.nextLocTempVar, loc); loc = finallyEntry.firstLoc; }
conditional_block
leap.js
/** * Copyright (c) 2013, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * https://raw.github.com/facebook/regenerator/master/LICENSE file. An * additional grant of patent rights can be found in the PATENTS file in * the same directory. */ var as...
(breakLoc, continueLoc, label) { Entry.call(this); n.Literal.assert(breakLoc); n.Literal.assert(continueLoc); if (label) { n.Identifier.assert(label); } else { label = null; } Object.defineProperties(this, { breakLoc: { value: breakLoc }, continueLoc: { value: continueLoc }, label: ...
LoopEntry
identifier_name
leap.js
/** * Copyright (c) 2013, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * https://raw.github.com/facebook/regenerator/master/LICENSE file. An * additional grant of patent rights can be found in the PATENTS file in * the same directory. */ var as...
inherits(TryEntry, Entry); exports.TryEntry = TryEntry; function CatchEntry(firstLoc, paramId) { Entry.call(this); n.Literal.assert(firstLoc); n.Identifier.assert(paramId); Object.defineProperties(this, { firstLoc: { value: firstLoc }, paramId: { value: paramId } }); } inherits(CatchEntry, Entry...
{ Entry.call(this); if (catchEntry) { assert.ok(catchEntry instanceof CatchEntry); } else { catchEntry = null; } if (finallyEntry) { assert.ok(finallyEntry instanceof FinallyEntry); } else { finallyEntry = null; } Object.defineProperties(this, { catchEntry: { value: catchEntry }, ...
identifier_body
test_users.py
# Copyright 2010 OpenStack 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 b...
class UsersTest(test.TestCase): def setUp(self): super(UsersTest, self).setUp() self.flags(verbose=True) self.stubs.Set(users.Controller, '__init__', fake_init) fakes.FakeAuthManager.clear_fakes() fakes.FakeAuthManager.projects = dict(testacct=Projec...
self.manager = fakes.FakeAuthManager()
identifier_body
test_users.py
# Copyright 2010 OpenStack 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 b...
(self): serializer = users.UsersTemplate() fixture = {'users': [{'id': 'id1', 'name': 'guy1', 'secret': 'secret1', 'admin': False}, {'id': 'id2', 'name': '...
test_index
identifier_name
test_users.py
# Copyright 2010 OpenStack 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 b...
def test_user_create(self): secret = utils.generate_password() body = dict(user=dict(name='test_guy', access='acc3', secret=secret, admin=True)) req = fakes.HTTPRequest.blank('/v2/fake/users') r...
self.assertTrue('id1' not in [u.id for u in fakes.FakeAuthManager.auth_data])
random_line_split
electronTypes.ts
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *---------------------------------------------------------------...
export interface OpenDevToolsOptions { /** * Opens the devtools with specified dock state, can be `right`, `bottom`, * `undocked`, `detach`. Defaults to last used dock state. In `undocked` mode it's * possible to dock back. In `detach` mode it's not. */ mode: ('right' | 'bottom' | 'undocked' | 'detach'); /*...
/** * The checked state of the checkbox if `checkboxLabel` was set. Otherwise `false`. */ checkboxChecked: boolean; }
random_line_split
lib.rs
//! Implementation of Rust panics via process aborts //! //! When compared to the implementation via unwinding, this crate is *much* //! simpler! That being said, it's not quite as versatile, but here goes! #![no_std] #![unstable(feature = "panic_abort", issue = "32837")] #![doc(issue_tracker_base_url = "https://githu...
} else if #[cfg(any(target_os = "hermit", all(target_vendor = "fortanix", target_env = "sgx") ))] { unsafe fn abort() -> ! { // call std::sys::abort_internal extern "C" { pub fn __rust_abort() -> !; ...
cfg_if::cfg_if! { if #[cfg(unix)] { unsafe fn abort() -> ! { libc::abort(); }
random_line_split
lib.rs
//! Implementation of Rust panics via process aborts //! //! When compared to the implementation via unwinding, this crate is *much* //! simpler! That being said, it's not quite as versatile, but here goes! #![no_std] #![unstable(feature = "panic_abort", issue = "32837")] #![doc(issue_tracker_base_url = "https://githu...
// "Leak" the payload and shim to the relevant abort on the platform in question. #[rustc_std_internal_symbol] pub unsafe extern "C-unwind" fn __rust_start_panic(_payload: *mut &mut dyn BoxMeUp) -> u32 { // Android has the ability to attach a message as part of the abort. #[cfg(target_os = "android")] and...
{ unreachable!() }
identifier_body
lib.rs
//! Implementation of Rust panics via process aborts //! //! When compared to the implementation via unwinding, this crate is *much* //! simpler! That being said, it's not quite as versatile, but here goes! #![no_std] #![unstable(feature = "panic_abort", issue = "32837")] #![doc(issue_tracker_base_url = "https://githu...
() {} #[rustc_std_internal_symbol] #[cfg(all(target_os = "windows", target_env = "gnu", target_arch = "x86"))] pub extern "C" fn rust_eh_unregister_frames() {} }
rust_eh_register_frames
identifier_name
order_by_step.js
/** * @license * Copyright 2015 The Lovefield Project 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 ...
goog.provide('lf.proc.OrderByStep'); goog.require('lf.Order'); goog.require('lf.fn'); goog.require('lf.fn.AggregatedColumn'); goog.require('lf.proc.PhysicalQueryPlanNode'); goog.require('lf.query.SelectContext'); /** * @constructor @struct * @extends {lf.proc.PhysicalQueryPlanNode} * * @param {!Array<!lf.query....
*/
random_line_split
order_by_step.js
/** * @license * Copyright 2015 The Lovefield Project 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 ...
else { // if (relations.length > 1) { relations.sort(this.relationComparatorFn_.bind(this)); } return relations; }; /** * Determines whether sorting is requested on a column that has been aggregated * with lf.fn.distinct (if any). * @param {!lf.proc.Relation} relation The input relation. * @return {?lf.s...
{ var distinctColumn = this.findDistinctColumn_(relations[0]); // If such a column exists, sort the results of the lf.fn.distinct // aggregator instead, since this is what will be used in the returned // result. var relationToSort = goog.isNull(distinctColumn) ? relations[0] : relat...
conditional_block
transformers.js
var _ = require('lodash'), fs = require('fs'), path = require('path'), through = require('through'), filesize = require('file-size'); function browserify(file, options) { var source = []; function write(data) { source.push(data); }; function
(file, options) { var renderTemplate = function(options, stats) { var si = options.size.representation === 'si', computedSize = filesize(stats.size, { fixed: options.size.decimals, spacer: options.size.spacer }), jsonOptions = JSON.stringify(options), ...
end
identifier_name
transformers.js
var _ = require('lodash'), fs = require('fs'), path = require('path'), through = require('through'), filesize = require('file-size'); function browserify(file, options) { var source = []; function write(data)
; function end(file, options) { var renderTemplate = function(options, stats) { var si = options.size.representation === 'si', computedSize = filesize(stats.size, { fixed: options.size.decimals, spacer: options.size.spacer }), jsonOptions = JSON.stringi...
{ source.push(data); }
identifier_body
transformers.js
var _ = require('lodash'), fs = require('fs'), path = require('path'), through = require('through'), filesize = require('file-size'); function browserify(file, options) { var source = []; function write(data) { source.push(data); }; function end(file, options) { var renderTemplate = f...
}.bind(this); fs.stat(file, fileStat); } return (function transform(file, options) { var options = _.extend({ size: { unit: 'human', decimals: '2', spacer: ' ', representation: 'si' }, output: { file: { ...
{ var result = '', prependHeader = renderTemplate(options, stats); try { result = [prependHeader, source.join('')].join(''); } catch (error) { error.message += ' in "' + file + '"'; this.emit('error', error); } this.queue(result); ...
conditional_block
transformers.js
var _ = require('lodash'), fs = require('fs'), path = require('path'), through = require('through'), filesize = require('file-size'); function browserify(file, options) { var source = []; function write(data) { source.push(data); }; function end(file, options) { var renderTemplate = f...
prependHeader = renderTemplate(options, stats); try { result = [prependHeader, source.join('')].join(''); } catch (error) { error.message += ' in "' + file + '"'; this.emit('error', error); } this.queue(result); this.queue(null); }...
if (options.output.file) { var result = '',
random_line_split
main.rs
/* * 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 ...
* KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ use std::{ fs::{self, File}, io::{BufRead, BufReader}, path::Path, }; use ::ndarray::{Array, ArrayD, Axis}; use image::{FilterType, GenericImageView}; use anyh...
random_line_split
main.rs
/* * 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 ...
() -> anyhow::Result<()> { let ctx = Context::cpu(0); println!("{}", concat!(env!("CARGO_MANIFEST_DIR"), "/cat.png")); let img = image::open(concat!(env!("CARGO_MANIFEST_DIR"), "/cat.png")) .context("Failed to open cat.png")?; println!("original image dimensions: {:?}", img.dimensions()); ...
main
identifier_name
main.rs
/* * 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 ...
{ let ctx = Context::cpu(0); println!("{}", concat!(env!("CARGO_MANIFEST_DIR"), "/cat.png")); let img = image::open(concat!(env!("CARGO_MANIFEST_DIR"), "/cat.png")) .context("Failed to open cat.png")?; println!("original image dimensions: {:?}", img.dimensions()); // for bigger size images...
identifier_body
main.rs
#![deny( missing_debug_implementations, missing_copy_implementations, trivial_casts, trivial_numeric_casts, unused_import_braces, unused_qualifications, unsafe_code, dead_code, unused_results, )] extern crate clap; extern crate rand; extern crate time; extern crate ctrlc; extern cra...
() { let opts = Options::parse(); let cont = Arc::new(RwLock::new(true)); { let host = opts.host.clone(); let port = opts.port; let cont = cont.clone(); ctrlc::set_handler(move || { println!("Ctrl+C received, terminating..."); *cont.write().unwrap() ...
main
identifier_name
main.rs
#![deny( missing_debug_implementations, missing_copy_implementations, trivial_casts, trivial_numeric_casts, unused_import_braces, unused_qualifications, unsafe_code, dead_code, unused_results, )] extern crate clap; extern crate rand; extern crate time; extern crate ctrlc; extern cra...
}
{ println!("Game loop thread failed: {:?}", error); }
conditional_block
main.rs
#![deny( missing_debug_implementations,
unused_import_braces, unused_qualifications, unsafe_code, dead_code, unused_results, )] extern crate clap; extern crate rand; extern crate time; extern crate ctrlc; extern crate serde; extern crate serde_json; extern crate websocket; mod options; pub mod math; pub mod message; pub mod server; use...
missing_copy_implementations, trivial_casts, trivial_numeric_casts,
random_line_split
main.rs
#![deny( missing_debug_implementations, missing_copy_implementations, trivial_casts, trivial_numeric_casts, unused_import_braces, unused_qualifications, unsafe_code, dead_code, unused_results, )] extern crate clap; extern crate rand; extern crate time; extern crate ctrlc; extern cra...
{ let opts = Options::parse(); let cont = Arc::new(RwLock::new(true)); { let host = opts.host.clone(); let port = opts.port; let cont = cont.clone(); ctrlc::set_handler(move || { println!("Ctrl+C received, terminating..."); *cont.write().unwrap() = f...
identifier_body
collisionDetector.js
/* The MIT License Copyright (c) 2012 Olaf Horstmann, indiegamr.com 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...
module.Collisions.checkPixelCollision = checkPixelCollision; var _collisionDistancePrecheck = function(bitmap1,bitmap2) { var ir1,ir2,b1,b2; b1 = bitmap1.localToGlobal(0,0); b2 = bitmap2.localToGlobal(0,0); ir1 = bitmap1 instanceof createjs.Bitmap ? {width:bitmap1.image.width, height:bit...
return pixelIntersection; }
random_line_split
index.ts
/* * Copyright (c) 2016-2017 Red Hat, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Red H...
@Parameter({names: ["--logger-debug"], description: "Enable the logger in debug mode"}) debugLogger : boolean; @Parameter({names: ["--logger-prefix-off"], description: "Disable prefix mode in logging"}) prefixOffLogger : boolean; constructor() { this.args = ArgumentProcessor.inject(this, ...
@Argument({description: "Name of the command to execute from this entry point."}) commandName : string;
random_line_split
index.ts
/* * Copyright (c) 2016-2017 Red Hat, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Red H...
} // call run method new EntryPoint().run();
{ // turn into debugging mode if (this.debugLogger) { Log.enableDebug(); } if (this.prefixOffLogger) { Log.disablePrefix(); } try { var promise : Promise<any>; switch(this.commandName) { case 'che-test': ...
identifier_body
index.ts
/* * Copyright (c) 2016-2017 Red Hat, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Red H...
else { Log.getLogger().error(error.toString()); } } catch (e) { Log.getLogger().error(error.toString()); if (error instanceof TypeError || error instanceof SyntaxError) { console.log(error.stack)...
{ Log.getLogger().error(errorMessage.message); }
conditional_block
index.ts
/* * Copyright (c) 2016-2017 Red Hat, Inc. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html * * Contributors: * Red H...
() : void { // turn into debugging mode if (this.debugLogger) { Log.enableDebug(); } if (this.prefixOffLogger) { Log.disablePrefix(); } try { var promise : Promise<any>; switch(this.commandName) { case 'ch...
run
identifier_name
sourcemap-locator.js
var ajax = require('ajax') var Future = require("async-future") var decodeDataUrl = require("./decodeDataUrl") exports.fromUrl = function(sourceUrl, toSource) { return ajax(sourceUrl, true).then(function(response) { return fromSourceOrHeaders(response.headers, response.text, toSource) }) } exports.fro...
exports.cacheGet = ajax.cacheGet exports.cacheSet = ajax.cacheSet var URL_PATTERN = '(((?:http|https|file)://)?[^\\s)]+|javascript:.*)' var SOURCE_MAP_PATTERN_PART = " sourceMappingURL=("+URL_PATTERN+")" var SOURCE_MAP_PATTERN1 = "\/\/#"+SOURCE_MAP_PATTERN_PART var SOURCE_MAP_PATTERN2 = "\/\/@"+SOURCE_MAP_PATTERN_P...
}
random_line_split
sourcemap-locator.js
var ajax = require('ajax') var Future = require("async-future") var decodeDataUrl = require("./decodeDataUrl") exports.fromUrl = function(sourceUrl, toSource) { return ajax(sourceUrl, true).then(function(response) { return fromSourceOrHeaders(response.headers, response.text, toSource) }) } exports.fro...
exports.cacheGet = ajax.cacheGet exports.cacheSet = ajax.cacheSet var URL_PATTERN = '(((?:http|https|file)://)?[^\\s)]+|javascript:.*)' var SOURCE_MAP_PATTERN_PART = " sourceMappingURL=("+URL_PATTERN+")" var SOURCE_MAP_PATTERN1 = "\/\/#"+SOURCE_MAP_PATTERN_PART var SOURCE_MAP_PATTERN2 = "\/\/@"+SOURCE_MAP_PATTERN_...
{ if(toSource === undefined) toSource = false var sourcemapUrl = getSourceMapUrl(headers, sourceText) if(sourcemapUrl === undefined) { return Future(undefined) } else if(toSource) { if(sourcemapUrl.indexOf('data:') === 0) { return Future(decodeDataUrl(sourcemapUrl)) ...
identifier_body
sourcemap-locator.js
var ajax = require('ajax') var Future = require("async-future") var decodeDataUrl = require("./decodeDataUrl") exports.fromUrl = function(sourceUrl, toSource) { return ajax(sourceUrl, true).then(function(response) { return fromSourceOrHeaders(response.headers, response.text, toSource) }) } exports.fro...
(headers, sourceText, toSource) { if(toSource === undefined) toSource = false var sourcemapUrl = getSourceMapUrl(headers, sourceText) if(sourcemapUrl === undefined) { return Future(undefined) } else if(toSource) { if(sourcemapUrl.indexOf('data:') === 0) { return Future(decod...
fromSourceOrHeaders
identifier_name
exceptions.py
from datetime import datetime class PanoplyException(Exception): def __init__(self, args=None, retryable=True): super(PanoplyException, self).__init__(args) self.retryable = retryable class IncorrectParamError(Exception): def __init__(self, msg: str = "Incorrect input parametr"): sup...
(Exception): def __init__(self, message, code, exception_cls, phase, source_type, source_id, database_id): super().__init__(message) self.message = message self.code = code self.phase = phase self.source_type = source_type self.source_id = source_id ...
DataSourceException
identifier_name
exceptions.py
from datetime import datetime class PanoplyException(Exception):
class IncorrectParamError(Exception): def __init__(self, msg: str = "Incorrect input parametr"): super().__init__(msg) class DataSourceException(Exception): def __init__(self, message, code, exception_cls, phase, source_type, source_id, database_id): super().__init__(messag...
def __init__(self, args=None, retryable=True): super(PanoplyException, self).__init__(args) self.retryable = retryable
identifier_body
exceptions.py
from datetime import datetime class PanoplyException(Exception): def __init__(self, args=None, retryable=True): super(PanoplyException, self).__init__(args) self.retryable = retryable
class IncorrectParamError(Exception): def __init__(self, msg: str = "Incorrect input parametr"): super().__init__(msg) class DataSourceException(Exception): def __init__(self, message, code, exception_cls, phase, source_type, source_id, database_id): super().__init__(message) ...
random_line_split
decode.rs
//! Utilities for decoding a C4FM signal into symbols. use bits; use consts; /// Decodes symbol from sample at each symbol instant. #[derive(Copy, Clone)] pub struct Decoder { /// Sample index into current symbol period. pos: usize, /// Decider used for decoding symbol at each symbol instant. decider:...
mthresh: f32, /// Lower threshold. nthresh: f32, } impl Decider { /// Create a new Decider with the given positive threshold, mid threshold, and /// negative threshold. pub fn new(pthresh: f32, mthresh: f32, nthresh: f32) -> Decider { Decider { pthresh: pthresh, ...
/// Upper threshold. pthresh: f32, /// Middle threshold.
random_line_split
decode.rs
//! Utilities for decoding a C4FM signal into symbols. use bits; use consts; /// Decodes symbol from sample at each symbol instant. #[derive(Copy, Clone)] pub struct Decoder { /// Sample index into current symbol period. pos: usize, /// Decider used for decoding symbol at each symbol instant. decider:...
else { bits::Dibit::new(0b11) } } } #[cfg(test)] mod test { use super::*; #[test] fn test_decider() { let d = Decider::new(-0.004, -0.1, -0.196); assert_eq!(d.decide(0.044).bits(), 0b01); assert_eq!(d.decide(-0.052).bits(), 0b00); assert_eq!(d.deci...
{ bits::Dibit::new(0b10) }
conditional_block
decode.rs
//! Utilities for decoding a C4FM signal into symbols. use bits; use consts; /// Decodes symbol from sample at each symbol instant. #[derive(Copy, Clone)] pub struct Decoder { /// Sample index into current symbol period. pos: usize, /// Decider used for decoding symbol at each symbol instant. decider:...
} #[cfg(test)] mod test { use super::*; #[test] fn test_decider() { let d = Decider::new(-0.004, -0.1, -0.196); assert_eq!(d.decide(0.044).bits(), 0b01); assert_eq!(d.decide(-0.052).bits(), 0b00); assert_eq!(d.decide(-0.148).bits(), 0b10); assert_eq!(d.decide(-0.2...
{ if sample > self.pthresh { bits::Dibit::new(0b01) } else if sample > self.mthresh && sample <= self.pthresh { bits::Dibit::new(0b00) } else if sample <= self.mthresh && sample > self.nthresh { bits::Dibit::new(0b10) } else { bits::Dibit::...
identifier_body
decode.rs
//! Utilities for decoding a C4FM signal into symbols. use bits; use consts; /// Decodes symbol from sample at each symbol instant. #[derive(Copy, Clone)] pub struct Decoder { /// Sample index into current symbol period. pos: usize, /// Decider used for decoding symbol at each symbol instant. decider:...
() { let mut d = Decoder::new(Decider::new(0.0, 0.0, 0.0)); assert!(d.feed(0.2099609375000000).is_none()); assert!(d.feed(0.2165222167968750).is_none()); assert!(d.feed(0.2179870605468750).is_none()); assert!(d.feed(0.2152709960937500).is_none()); assert!(d.feed(0.209472...
test_decoder
identifier_name
screen.py
import time from pygame.locals import * import gui MOUSE_LEFT_BUTTON = 1 MOUSE_MIDDLE_BUTTON = 2 MOUSE_RIGHT_BUTTON = 3 MOUSE_WHEELUP = 4 MOUSE_WHEELDOWN = 5 class Screen(object): """Base gui screen class every game screen class should inherit from this one """ __triggers = [] ...
elif event.button == MOUSE_RIGHT_BUTTON: return {'action': "help", 'help': trigger['action']} def on_keydown(self, event): """Default implementation of a keyboard event handling. If keypress is detected by a GUI engine it calls this me...
trigger['mouse_pos'] = event.pos return trigger
conditional_block
screen.py
import time from pygame.locals import * import gui MOUSE_LEFT_BUTTON = 1 MOUSE_MIDDLE_BUTTON = 2 MOUSE_RIGHT_BUTTON = 3 MOUSE_WHEELUP = 4 MOUSE_WHEELDOWN = 5 class Screen(object): """Base gui screen class every game screen class should inherit from this one """ __triggers = [] ...
pass def leave_cancel(self): """ Called by GUI engine when ESCAPE trigger is activated This is the right place to implement things like getting the screen to state before any changes were made """ pass
"""
random_line_split
screen.py
import time from pygame.locals import * import gui MOUSE_LEFT_BUTTON = 1 MOUSE_MIDDLE_BUTTON = 2 MOUSE_RIGHT_BUTTON = 3 MOUSE_WHEELUP = 4 MOUSE_WHEELDOWN = 5 class Screen(object): """Base gui screen class every game screen class should inherit from this one """ __triggers = [] ...
(self): """ Called by GUI engine right before gui_client::run_screen() is invoked Suitable for saving initial state that can be reveresed by the screen's cancel() method """ pass def leave_confirm(self): """ Called by GUI engine when CONFIRM trigger is activated Eve...
enter
identifier_name
screen.py
import time from pygame.locals import * import gui MOUSE_LEFT_BUTTON = 1 MOUSE_MIDDLE_BUTTON = 2 MOUSE_RIGHT_BUTTON = 3 MOUSE_WHEELUP = 4 MOUSE_WHEELDOWN = 5 class Screen(object): """Base gui screen class every game screen class should inherit from this one """ __triggers = [] ...
def get_image(self, img_key, subkey1 = None, subkey2 = None, subkey3 = None): """Returns an image object from GUI engine, identified by its key(s)""" return gui.GUI.get_image(img_key, subkey1, subkey2, subkey3) def redraw_flip(self): """Redraws the screen, takes care about mouse cur...
"""Returns an actual timestamp""" return int(time.time() * zoom)
identifier_body
native.rs
use std::fs::File; use std::io; use std::os::unix::fs::MetadataExt; use std::os::unix::io::AsRawFd; use nix::errno::Errno; use crate::util::io::io_err; mod sys { use nix::libc::c_int; #[link(name = "fallocate")] extern "C" { pub fn native_fallocate(fd: c_int, len: u64) -> c_int; } } pub fn ...
Errno::EINTR => { continue; } e => { return io_err(e.desc()); } }, _ => unreachable!(), } } }
return Ok(false); } Errno::ENOSPC => { return io_err("Out of disk space!"); }
random_line_split
native.rs
use std::fs::File; use std::io; use std::os::unix::fs::MetadataExt; use std::os::unix::io::AsRawFd; use nix::errno::Errno; use crate::util::io::io_err; mod sys { use nix::libc::c_int; #[link(name = "fallocate")] extern "C" { pub fn native_fallocate(fd: c_int, len: u64) -> c_int; } } pub fn ...
pub fn fallocate(f: &File, len: u64) -> io::Result<bool> { // We ignore the len here, if you actually have a u64 max, then you're kinda fucked either way. loop { match unsafe { sys::native_fallocate(f.as_raw_fd(), len) } { 0 => return Ok(true), -1 => match Errno::last() { ...
{ let stat = f.metadata()?; Ok(stat.blocks() * stat.blksize() < stat.size()) }
identifier_body
native.rs
use std::fs::File; use std::io; use std::os::unix::fs::MetadataExt; use std::os::unix::io::AsRawFd; use nix::errno::Errno; use crate::util::io::io_err; mod sys { use nix::libc::c_int; #[link(name = "fallocate")] extern "C" { pub fn native_fallocate(fd: c_int, len: u64) -> c_int; } } pub fn ...
(f: &File, len: u64) -> io::Result<bool> { // We ignore the len here, if you actually have a u64 max, then you're kinda fucked either way. loop { match unsafe { sys::native_fallocate(f.as_raw_fd(), len) } { 0 => return Ok(true), -1 => match Errno::last() { Errno::...
fallocate
identifier_name
native.rs
use std::fs::File; use std::io; use std::os::unix::fs::MetadataExt; use std::os::unix::io::AsRawFd; use nix::errno::Errno; use crate::util::io::io_err; mod sys { use nix::libc::c_int; #[link(name = "fallocate")] extern "C" { pub fn native_fallocate(fd: c_int, len: u64) -> c_int; } } pub fn ...
e => { return io_err(e.desc()); } }, _ => unreachable!(), } } }
{ continue; }
conditional_block
config.rs
use std::io::Read; use std::fs::File; use std::path::PathBuf; use std::env::home_dir; use serde_json; #[derive(Debug, Serialize, Deserialize)] pub struct XyPair { pub x: u32, pub y: u32 } impl XyPair { #[allow(dead_code)] pub fn new (x: u32, y: u32) -> Self { XyPair { x, y } } } #[derive...
serde_json::from_str(&body).expect("Failed to parse config.") }
random_line_split
config.rs
use std::io::Read; use std::fs::File; use std::path::PathBuf; use std::env::home_dir; use serde_json; #[derive(Debug, Serialize, Deserialize)] pub struct XyPair { pub x: u32, pub y: u32 } impl XyPair { #[allow(dead_code)] pub fn new (x: u32, y: u32) -> Self { XyPair { x, y } } } #[derive...
} fn config_path() -> PathBuf { home_dir() .expect("Failed to locate home directory.") .join(".config") .join("scrotrim") .join("config.json") } pub fn read_config() -> Config { let path = config_path(); let mut body = String::new(); let mut file = File::open(&path).ex...
{ Config { resolution: XyPair::new(x, y), screens } }
identifier_body
config.rs
use std::io::Read; use std::fs::File; use std::path::PathBuf; use std::env::home_dir; use serde_json; #[derive(Debug, Serialize, Deserialize)] pub struct XyPair { pub x: u32, pub y: u32 } impl XyPair { #[allow(dead_code)] pub fn new (x: u32, y: u32) -> Self { XyPair { x, y } } } #[derive...
() -> PathBuf { home_dir() .expect("Failed to locate home directory.") .join(".config") .join("scrotrim") .join("config.json") } pub fn read_config() -> Config { let path = config_path(); let mut body = String::new(); let mut file = File::open(&path).expect("Failed to op...
config_path
identifier_name
mod.rs
use rustc_serialize::json; use std::fmt; use std::rc; use std::collections; use std::any; use super::schema; use super::validators; pub type KeywordResult = Result<Option<validators::BoxedValidator>, schema::SchemaError>; pub type KeywordPair = (Vec<&'static str>, Box<Keyword + 'static>); pub type KeywordPairs = Vec<...
{ let (keys, keyword) = keyword_pair; let consumer = rc::Rc::new(KeywordConsumer { keys: keys.clone(), keyword: keyword }); for key in keys.iter() { map.insert(key, consumer.clone()); } }
identifier_body
mod.rs
use rustc_serialize::json; use std::fmt; use std::rc; use std::collections; use std::any; use super::schema; use super::validators; pub type KeywordResult = Result<Option<validators::BoxedValidator>, schema::SchemaError>; pub type KeywordPair = (Vec<&'static str>, Box<Keyword + 'static>); pub type KeywordPairs = Vec<...
(&self, set: &mut collections::HashSet<&str>) { for key in self.keys.iter() { if set.contains(key) { set.remove(key); } } } } pub fn decouple_keyword(keyword_pair: KeywordPair, map: &mut KeywordMap) { let (keys, keyword) = keyword_...
consume
identifier_name
mod.rs
use rustc_serialize::json; use std::fmt; use std::rc; use std::collections; use std::any; use super::schema; use super::validators; pub type KeywordResult = Result<Option<validators::BoxedValidator>, schema::SchemaError>; pub type KeywordPair = (Vec<&'static str>, Box<Keyword + 'static>); pub type KeywordPairs = Vec<...
} } } pub fn decouple_keyword(keyword_pair: KeywordPair, map: &mut KeywordMap) { let (keys, keyword) = keyword_pair; let consumer = rc::Rc::new(KeywordConsumer { keys: keys.clone(), keyword: keyword }); for key in keys.iter() { map.insert(key, consumer.clone());...
{ set.remove(key); }
conditional_block
mod.rs
use rustc_serialize::json; use std::fmt; use std::rc; use std::collections; use std::any; use super::schema; use super::validators; pub type KeywordResult = Result<Option<validators::BoxedValidator>, schema::SchemaError>; pub type KeywordPair = (Vec<&'static str>, Box<Keyword + 'static>); pub type KeywordPairs = Vec<...
} } } } pub fn decouple_keyword(keyword_pair: KeywordPair, map: &mut KeywordMap) { let (keys, keyword) = keyword_pair; let consumer = rc::Rc::new(KeywordConsumer { keys: keys.clone(), keyword: keyword }); for key in keys.iter() { map.insert(key, consu...
impl KeywordConsumer { pub fn consume(&self, set: &mut collections::HashSet<&str>) { for key in self.keys.iter() { if set.contains(key) { set.remove(key);
random_line_split
index-tests.tsx
import { Theme } from "@artsy/palette" import { mount } from "enzyme" import React from "react" import { FairEventSection } from "../index" const data = [ { name: "TEFAF New York Fall 2019", id: "RmFpcjp0ZWZhZi1uZXcteW9yay1mYWxsLTIwMTk=", gravityID: "tefaf-new-york-fall-2019", image: { aspect_r...
})
</Theme> ) expect(comp.text()).toContain("TEFAF New York Fall 2019") })
random_line_split
ReportRaidBuffList.tsx
import React from 'react'; import SPECS from 'game/SPECS'; import SPELLS from 'common/SPELLS'; import { Class, CombatantInfoEvent } from 'parser/core/Events'; import './ReportRaidBuffList.scss'; import ReportRaidBuffListItem from './ReportRaidBuffListItem'; const AVAILABLE_RAID_BUFFS = new Map<number, Array<Class |...
}); return map; }, results); }; interface Props { combatants: CombatantInfoEvent[]; } const ReportRaidBuffList = ({ combatants }: Props) => { const buffs = getCompositionBreakdown(combatants); return ( <div className="raidbuffs"> <h1>Raid Buffs</h1> {Array.from(buffs, ([spellId, coun...
{ map.set(spellId, map.get(spellId)! + 1); }
conditional_block
ReportRaidBuffList.tsx
import React from 'react'; import SPECS from 'game/SPECS'; import SPELLS from 'common/SPELLS'; import { Class, CombatantInfoEvent } from 'parser/core/Events'; import './ReportRaidBuffList.scss'; import ReportRaidBuffListItem from './ReportRaidBuffListItem'; const AVAILABLE_RAID_BUFFS = new Map<number, Array<Class |...
}); return combatants.reduce((map, combatant) => { const spec = SPECS[combatant.specID]; if (!spec) { return map; } const className = spec.className; AVAILABLE_RAID_BUFFS.forEach((providedBy, spellId) => { if (providedBy.includes(className) || providedBy.includes(spec)) { m...
const getCompositionBreakdown = (combatants: CombatantInfoEvent[]) => { const results = new Map<number, number>(); AVAILABLE_RAID_BUFFS.forEach((providedBy, spellId) => { results.set(spellId, 0);
random_line_split
a02762.js
var a02762 = [ [ "AmbigSpec", "a02762.html#aaa3a04113f5db03951771afa6423e7f4", null ], [ "~AmbigSpec", "a02762.html#a5283933a9e7267b3505f5f18cf289f3e", null ], [ "correct_fragments", "a02762.html#ad3a4b121b26cf829422700494aed91e4", null ],
[ "wrong_ngram_size", "a02762.html#a4cfb10d18b7c636f3afa5f223afa445e", null ] ];
[ "correct_ngram_id", "a02762.html#a879c6167dbfc54980bfeb5a15b32bf73", null ], [ "type", "a02762.html#ae29644f82c6feac4df14b22368fa0873", null ], [ "wrong_ngram", "a02762.html#a9d7f07e5b038c6d61acc9bb75ba7ef1b", null ],
random_line_split
__init__.py
# Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the...
# Copyright (c) 2014 Rackspace, Inc. #
random_line_split
clean_raxml_parsimony_tree.py
#!/usr/bin/env python # File created on 10 Nov 2011 from __future__ import division __author__ = "Jesse Stombaugh" __copyright__ = "Copyright 2011, The QIIME project" __credits__ = ["Jesse Stombaugh"] __license__ = "GPL" __version__ = "1.9.1-dev" __maintainer__ = "Jesse Stombaugh" __email__ = "jesse.stombaugh@colorado...
# get the nodes for the inserted sequences nodes_dict = get_insert_dict(tree2, set(tips_to_keep)) # remove nodes accordingly final_tree = drop_duplicate_nodes(tree2, nodes_dict) # final_tree.nameUnnamedNodes() # write out the resulting tree open_outpath = open(opts.output_fp, 'w') o...
tree2 = decorate_numtips(tree)
conditional_block
clean_raxml_parsimony_tree.py
#!/usr/bin/env python # File created on 10 Nov 2011 from __future__ import division __author__ = "Jesse Stombaugh" __copyright__ = "Copyright 2011, The QIIME project" __credits__ = ["Jesse Stombaugh"] __license__ = "GPL" __version__ = "1.9.1-dev" __maintainer__ = "Jesse Stombaugh" __email__ = "jesse.stombaugh@colorado...
script_info['script_usage'] = [] script_info['script_usage'].append( ("Example (depth):", "For this case the user can pass in input Raxml tree, duplicate tips, and define an output filepath. When using the depth option, only the deepest replicate is kept. ", " %prog -i raxml_v730_final_placement.tre -t 6 ...
script_info[ 'script_description'] = "This script allows the user to remove specific duplicate tips from a Raxml tree."
random_line_split
clean_raxml_parsimony_tree.py
#!/usr/bin/env python # File created on 10 Nov 2011 from __future__ import division __author__ = "Jesse Stombaugh" __copyright__ = "Copyright 2011, The QIIME project" __credits__ = ["Jesse Stombaugh"] __license__ = "GPL" __version__ = "1.9.1-dev" __maintainer__ = "Jesse Stombaugh" __email__ = "jesse.stombaugh@colorado...
if __name__ == "__main__": main()
option_parser, opts, args =\ parse_command_line_parameters(**script_info) # get options tree_fp = opts.input_tree tips_to_keep = opts.tips_to_keep.split(',') scoring_method = opts.scoring_method # load tree tree = DndParser(open(tree_fp, 'U'), constructor=PhyloNode) # decorate mea...
identifier_body
clean_raxml_parsimony_tree.py
#!/usr/bin/env python # File created on 10 Nov 2011 from __future__ import division __author__ = "Jesse Stombaugh" __copyright__ = "Copyright 2011, The QIIME project" __credits__ = ["Jesse Stombaugh"] __license__ = "GPL" __version__ = "1.9.1-dev" __maintainer__ = "Jesse Stombaugh" __email__ = "jesse.stombaugh@colorado...
(): option_parser, opts, args =\ parse_command_line_parameters(**script_info) # get options tree_fp = opts.input_tree tips_to_keep = opts.tips_to_keep.split(',') scoring_method = opts.scoring_method # load tree tree = DndParser(open(tree_fp, 'U'), constructor=PhyloNode) # deco...
main
identifier_name
Ping.py
''' @author: lockrecv@gmail.com A pure python ping implementation using raw socket. Note that ICMP messages can only be sent from processes running as root. Inspired by Matthew Dixon Cowles <http://www.visi.com/~mdc/>. ''' import os import select import socket import struct import time class Ping: ''' Power On...
my_socket.close() return delay def verbose_ping(self, dest_addr, timeout = 2, count = 4, psize = 64): ''' Send 'count' ping with 'psize' size to 'dest_addr' with the given 'timeout' and display the result ''' for i in xrange(count): p...
self.send_one_ping(my_socket, dest_addr, my_id, psize) delay = self.receive_one_ping(my_socket, my_id, timeout)
random_line_split
Ping.py
''' @author: lockrecv@gmail.com A pure python ping implementation using raw socket. Note that ICMP messages can only be sent from processes running as root. Inspired by Matthew Dixon Cowles <http://www.visi.com/~mdc/>. ''' import os import select import socket import struct import time class Ping: ''' Power On...
def send_one_ping(self, my_socket, dest_addr, idd, psize): '''Send one ping to the given address''' dest_addr = socket.gethostbyname(dest_addr) # Remove header size from packet size psize = psize - 8 # Header is type (8), code (8), checksum (16), i...
'''Receive the ping from the socket''' time_left = timeout while True: started_select = time.time() what_ready = select.select([my_socket], [], [], time_left) how_long_in_select = (time.time() - started_select) if what_ready[0] == []: # Timeout ...
identifier_body
Ping.py
''' @author: lockrecv@gmail.com A pure python ping implementation using raw socket. Note that ICMP messages can only be sent from processes running as root. Inspired by Matthew Dixon Cowles <http://www.visi.com/~mdc/>. ''' import os import select import socket import struct import time class Ping: ''' Power On...
(self, dest_addr, timeout = 2, count = 4, psize = 64): ''' Send 'count' ping with 'psize' size to 'dest_addr' with the given 'timeout' and display the result ''' for i in xrange(count): print 'ping %s with ...' % dest_addr try: delay = self...
verbose_ping
identifier_name
Ping.py
''' @author: lockrecv@gmail.com A pure python ping implementation using raw socket. Note that ICMP messages can only be sent from processes running as root. Inspired by Matthew Dixon Cowles <http://www.visi.com/~mdc/>. ''' import os import select import socket import struct import time class Ping: ''' Power On...
summ = (summ >> 16) + (summ & 0xffff) summ = summ + (summ >> 16) answer = ~summ answer = answer & 0xffff # Swap bytes answer = answer >> 8 | (answer << 8 & 0xff00) return answer def receive_one_ping(self, my_socket, idd, timeout): ...
summ = summ + ord(source_string[len(source_string)-1]) summ = summ & 0xffffffff
conditional_block
World.ts
import {RNG} from "./RNG"; import {GameObject} from './GameObject'; import {Components} from './Component'; import {EventDispatcher} from './EventDispatcher'; // ### // 管理所有的 GameObject // 提供公共方法 // ### export class World { eventDispatcher: EventDispatcher; root: GameObject; rng: RNG; constructor(seed...
urn this.rng.nextRange(0, length); } nextRange(start: number, end: number) { return this.rng.nextRange(start, end); } choice(array) { return this.rng.choice(array); } on(event: string, target, handler?) { this.eventDispatcher.on(event, target, handler); } off(...
ret
identifier_name
World.ts
import {RNG} from "./RNG"; import {GameObject} from './GameObject'; import {Components} from './Component'; import {EventDispatcher} from './EventDispatcher'; // ### // 管理所有的 GameObject // 提供公共方法 // ### export class World { eventDispatcher: EventDispatcher; root: GameObject; rng: RNG; constructor(seed...
} /* * 这个方法可以快速注册多个事件处理函数 * 一般用在单元测试用例里面 */ onEventMap(eventMap) { for (let event in eventMap) { this.on(event, eventMap); } } }
random_line_split
World.ts
import {RNG} from "./RNG"; import {GameObject} from './GameObject'; import {Components} from './Component'; import {EventDispatcher} from './EventDispatcher'; // ### // 管理所有的 GameObject // 提供公共方法 // ### export class World { eventDispatcher: EventDispatcher; root: GameObject; rng: RNG; constructor(seed...
this.root.update(dt); } nextInt() { return this.rng.nextInt(); } nextIndex(length) { return this.rng.nextRange(0, length); } nextRange(start: number, end: number) { return this.rng.nextRange(start, end); } choice(array) { return this.rng.choic...
root.createChild(name); } update(dt = 0) {
identifier_body
object.rs
use libc::c_void; use ffi::object::{self, LLVMObjectFileRef, LLVMSymbolIteratorRef}; use cbox::CBox; use std::fmt; use std::iter::Iterator; use std::marker::PhantomData; use std::mem; use buffer::MemoryBuffer; use util; /// An external object file that has been parsed by LLVLM pub struct ObjectFile { obj: LLVMObj...
} pub struct Symbol<'a> { pub name: &'a str, pub address: *const c_void, pub size: usize } impl<'a> Copy for Symbol<'a> {} impl<'a> Clone for Symbol<'a> { fn clone(&self) -> Symbol<'a> { *self } } impl<'a> fmt::Debug for Symbol<'a> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Resul...
{ unsafe { object::LLVMDisposeSymbolIterator(self.iter) } }
identifier_body
object.rs
use libc::c_void; use ffi::object::{self, LLVMObjectFileRef, LLVMSymbolIteratorRef}; use cbox::CBox; use std::fmt; use std::iter::Iterator; use std::marker::PhantomData; use std::mem; use buffer::MemoryBuffer; use util; /// An external object file that has been parsed by LLVLM pub struct ObjectFile { obj: LLVMObj...
(&mut self) -> Option<Symbol<'a>> { unsafe { let name = util::to_str(object::LLVMGetSymbolName(self.iter) as *mut i8); let size = object::LLVMGetSymbolSize(self.iter) as usize; let address = object::LLVMGetSymbolAddress(self.iter) as usize; Some(Symbol { ...
next
identifier_name
object.rs
use libc::c_void; use ffi::object::{self, LLVMObjectFileRef, LLVMSymbolIteratorRef}; use cbox::CBox; use std::fmt; use std::iter::Iterator; use std::marker::PhantomData; use std::mem; use buffer::MemoryBuffer; use util; /// An external object file that has been parsed by LLVLM pub struct ObjectFile { obj: LLVMObj...
pub struct Symbol<'a> { pub name: &'a str, pub address: *const c_void, pub size: usize } impl<'a> Copy for Symbol<'a> {} impl<'a> Clone for Symbol<'a> { fn clone(&self) -> Symbol<'a> { *self } } impl<'a> fmt::Debug for Symbol<'a> { fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {...
unsafe { object::LLVMDisposeSymbolIterator(self.iter) } } }
random_line_split
object.rs
use libc::c_void; use ffi::object::{self, LLVMObjectFileRef, LLVMSymbolIteratorRef}; use cbox::CBox; use std::fmt; use std::iter::Iterator; use std::marker::PhantomData; use std::mem; use buffer::MemoryBuffer; use util; /// An external object file that has been parsed by LLVLM pub struct ObjectFile { obj: LLVMObj...
else { Ok(ptr.into()) } } } /// Iterate through the symbols in this object fil pub fn symbols(&self) -> Symbols { Symbols { iter: unsafe { object::LLVMGetSymbols(self.obj) }, marker: PhantomData } } } pub struct Symbols<'a> { ...
{ Err(CBox::from("unknown error")) }
conditional_block
gcloud_iam_sa.py
# pylint: skip-file # vim: expandtab:tabstop=4:shiftwidth=4 #pylint: disable=too-many-branches def main(): ''' ansible module for gcloud iam servicetaccount''' module = AnsibleModule( argument_spec=dict( # credentials state=dict(default='present', type='str', ...
module.exit_json(changed=False, results=api_rval, state="present") module.exit_json(failed=True, changed=False, results='Unknown state passed. %s' % state, state="unknown") # pylint: disable=redefined-builtin, unused-wildcard-import, wildcard...
module.exit_json(changed=True, results=api_rval, state="present|update")
random_line_split
gcloud_iam_sa.py
# pylint: skip-file # vim: expandtab:tabstop=4:shiftwidth=4 #pylint: disable=too-many-branches def
(): ''' ansible module for gcloud iam servicetaccount''' module = AnsibleModule( argument_spec=dict( # credentials state=dict(default='present', type='str', choices=['present', 'absent', 'list']), name=dict(default=None, type='str'), ...
main
identifier_name
gcloud_iam_sa.py
# pylint: skip-file # vim: expandtab:tabstop=4:shiftwidth=4 #pylint: disable=too-many-branches def main():
# pylint: disable=redefined-builtin, unused-wildcard-import, wildcard-import, locally-disabled # import module snippets. This are required from ansible.module_utils.basic import * main()
''' ansible module for gcloud iam servicetaccount''' module = AnsibleModule( argument_spec=dict( # credentials state=dict(default='present', type='str', choices=['present', 'absent', 'list']), name=dict(default=None, type='str'), display...
identifier_body
gcloud_iam_sa.py
# pylint: skip-file # vim: expandtab:tabstop=4:shiftwidth=4 #pylint: disable=too-many-branches def main(): ''' ansible module for gcloud iam servicetaccount''' module = AnsibleModule( argument_spec=dict( # credentials state=dict(default='present', type='str', ...
module.exit_json(changed=False, results=api_rval['results'], state="list") ######## # Delete ######## if state == 'absent': if gcloud.exists(): if module.check_mode: module.exit_json(changed=False, msg='Would have performed a delete.') api_rva...
module.fail_json(msg=api_rval, state="list")
conditional_block
pyunit_benign_glrm.py
import sys sys.path.insert(1,"../../../") import h2o from tests import pyunit_utils from h2o.estimators.glrm import H2OGeneralizedLowRankEstimator def glrm_benign(): print "Importing benign.csv data..." benignH2O = h2o.upload_file(pyunit_utils.locate("smalldata/logreg/benign.csv")) benignH2O.describe() for i...
else: glrm_benign()
pyunit_utils.standalone_test(glrm_benign)
conditional_block
pyunit_benign_glrm.py
import sys sys.path.insert(1,"../../../") import h2o from tests import pyunit_utils from h2o.estimators.glrm import H2OGeneralizedLowRankEstimator def glrm_benign():
if __name__ == "__main__": pyunit_utils.standalone_test(glrm_benign) else: glrm_benign()
print "Importing benign.csv data..." benignH2O = h2o.upload_file(pyunit_utils.locate("smalldata/logreg/benign.csv")) benignH2O.describe() for i in range(8,16,2): print "H2O GLRM with rank " + str(i) + " decomposition:\n" glrm_h2o = H2OGeneralizedLowRankEstimator(k=i, init="SVD", recover_svd=True) glr...
identifier_body
pyunit_benign_glrm.py
import sys sys.path.insert(1,"../../../") import h2o from tests import pyunit_utils from h2o.estimators.glrm import H2OGeneralizedLowRankEstimator def glrm_benign(): print "Importing benign.csv data..." benignH2O = h2o.upload_file(pyunit_utils.locate("smalldata/logreg/benign.csv")) benignH2O.describe() for i...
if __name__ == "__main__": pyunit_utils.standalone_test(glrm_benign) else: glrm_benign()
glrm_h2o = H2OGeneralizedLowRankEstimator(k=i, init="SVD", recover_svd=True) glrm_h2o.train(x=benignH2O.names, training_frame=benignH2O) glrm_h2o.show()
random_line_split
pyunit_benign_glrm.py
import sys sys.path.insert(1,"../../../") import h2o from tests import pyunit_utils from h2o.estimators.glrm import H2OGeneralizedLowRankEstimator def
(): print "Importing benign.csv data..." benignH2O = h2o.upload_file(pyunit_utils.locate("smalldata/logreg/benign.csv")) benignH2O.describe() for i in range(8,16,2): print "H2O GLRM with rank " + str(i) + " decomposition:\n" glrm_h2o = H2OGeneralizedLowRankEstimator(k=i, init="SVD", recover_svd=True) ...
glrm_benign
identifier_name
tree.ts
import { Injectable, Optional } from '@ts-stack/di'; import { Fn, TreeConfig, RouteType, RouteParam } from './types'; @Injectable() export class Tree { type: RouteType; children: this[]; protected path: string; protected wildChild: boolean; protected handle: Fn | null; protected indices: string...
(tree: this, fullPath: string, path: string, numParams: number, handle: Fn) { // Find the longest common prefix // This also implies that the common prefix contains no ':' or '*' // since the existing key can't contain those chars. let i = 0; const min = Math.min(path.length, tree.path.length);...
mergeTree
identifier_name
tree.ts
import { Injectable, Optional } from '@ts-stack/di'; import { Fn, TreeConfig, RouteType, RouteParam } from './types'; @Injectable() export class Tree { type: RouteType; children: this[]; protected path: string; protected wildChild: boolean; protected handle: Fn | null; protected indices: string...
return { handle, params }; } } protected newTree(treeConfig?: TreeConfig) { return new (this.constructor as typeof Tree)(treeConfig) as this; } protected countParams(path: string) { let n = 0; for (const char of path) { if (char != ':' && char != '*') { cont...
{ handle = tree.handle; }
conditional_block
tree.ts
import { Injectable, Optional } from '@ts-stack/di'; import { Fn, TreeConfig, RouteType, RouteParam } from './types'; @Injectable() export class Tree { type: RouteType; children: this[]; protected path: string; protected wildChild: boolean; protected handle: Fn | null; protected indices: string...
const child = tree.children[0]; child.priority++; this.mergeTree(child, fullPath, newPath, numParams, handle); return; } // Check if a child with the next path char exists for (let j = 0; j < tree.indices.length; j++) { if (firstChar == tree.indices[j])...
if (tree.type == RouteType.param && firstChar == '/' && tree.children.length == 1) {
random_line_split
trait-cast-generic.rs
// Copyright 2014 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 ...
<T> { x: T, } impl<T> Foo for Bar<T> { } pub fn main() { let a = Bar { x: 1u }; let b = &a as &Foo; }
Bar
identifier_name
trait-cast-generic.rs
// Copyright 2014 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 ...
let b = &a as &Foo; }
random_line_split
reduce.rs
/* * 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 ...
{ pub base: BaseAttrsNode, pub axis: Array<IndexExpr>, pub keepdims: bool, pub exclude: bool, pub unbiased: bool, }
VarianceAttrsNode
identifier_name
reduce.rs
/* * 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 ...
*/ use crate::ir::attrs::BaseAttrsNode; use crate::ir::PrimExpr; use crate::runtime::array::Array; use tvm_macros::Object; type IndexExpr = PrimExpr; #[repr(C)] #[derive(Object, Debug)] #[ref_name = "ReduceAttrs"] #[type_key = "relay.attrs.ReduceAttrs"] pub struct ReduceAttrsNode { pub base: BaseAttrsNode, ...
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License.
random_line_split
net_error_list.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 https://mozilla.org/MPL/2.0/. */ // see https://github.com/adobe/chromium/blob/master/net/base/net_error_list.h #[allow(dead_code, non_camel_case_...
{ IO_PENDING = 1, FAILED = 2, ABORTED = 3, INVALID_ARGUMENT = 4, INVALID_HANDLE = 5, FILE_NOT_FOUND = 6, TIMED_OUT = 7, FILE_TOO_BIG = 8, UNEXPECTED = 9, ACCESS_DENIED = 10, NOT_IMPLEMENTED = 11, INSUFFICIENT_RESOURCES = 12, OUT_OF_MEMORY = 13, UPLOAD_FILE_CHANGE...
NetError
identifier_name
net_error_list.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 https://mozilla.org/MPL/2.0/. */ // see https://github.com/adobe/chromium/blob/master/net/base/net_error_list.h #[allow(dead_code, non_camel_case_...
SSL_UNSAFE_NEGOTIATION = 128, SSL_WEAK_SERVER_EPHEMERAL_DH_KEY = 129, PROXY_CONNECTION_FAILED = 130, MANDATORY_PROXY_CONFIGURATION_FAILED = 131, PRECONNECT_MAX_SOCKET_LIMIT = 133, SSL_CLIENT_AUTH_PRIVATE_KEY_ACCESS_DENIED = 134, SSL_CLIENT_AUTH_CERT_NO_PRIVATE_KEY = 135, PROXY_CERTIFICAT...
SSL_BAD_RECORD_MAC_ALERT = 126, PROXY_AUTH_REQUESTED = 127,
random_line_split
helpers.ts
// TODO: should be move to Jmx namespace Core { export function scopeStoreJolokiaHandle($scope, jolokia, jolokiaHandle) { // TODO do we even need to store the jolokiaHandle in the scope? if (jolokiaHandle) { $scope.$on('$destroy', function () { closeHandle($scope, jolokia) }); $scop...
(jolokia, $scope, arguments, callback: (response: any) => void, options?: any): () => void { let decorated = { responseJson: '', success: (response) => { let json = angular.toJson(response.value); if (decorated.responseJson !== json) { decorated.responseJson = json; c...
registerForChanges
identifier_name
helpers.ts
// TODO: should be move to Jmx namespace Core { export function scopeStoreJolokiaHandle($scope, jolokia, jolokiaHandle) { // TODO do we even need to store the jolokiaHandle in the scope? if (jolokiaHandle) { $scope.$on('$destroy', function () { closeHandle($scope, jolokia) }); $scop...
/** * Escapes the mbean as a path for Jolokia POST "list" requests. * See: https://jolokia.org/reference/html/protocol.html#list * * @param {string} mbean the mbean * @returns {string} */ export function escapeMBeanPath(mbean: string): string { return applyJolokiaEscapeRules(mbean).replace('...
{ return encodeURI(applyJolokiaEscapeRules(mbean)); }
identifier_body
helpers.ts
// TODO: should be move to Jmx namespace Core { export function scopeStoreJolokiaHandle($scope, jolokia, jolokiaHandle) { // TODO do we even need to store the jolokiaHandle in the scope? if (jolokiaHandle) { $scope.$on('$destroy', function () { closeHandle($scope, jolokia) }); $scop...
* * @param jolokia * @param scope * @param arguments * @param callback * @param options * @returns Object */ export function registerForChanges(jolokia, $scope, arguments, callback: (response: any) => void, options?: any): () => void { let decorated = { responseJson: '', succes...
* calls back when a change occurs
random_line_split
helpers.ts
// TODO: should be move to Jmx namespace Core { export function scopeStoreJolokiaHandle($scope, jolokia, jolokiaHandle) { // TODO do we even need to store the jolokiaHandle in the scope? if (jolokiaHandle) { $scope.$on('$destroy', function () { closeHandle($scope, jolokia) }); $scop...
else { answer = keyForArgument(arguments); } return answer; } export function getResponseHistory(): any { if (responseHistory === null) { //responseHistory = getOrInitObjectFromLocalStorage('responseHistory'); responseHistory = {}; log.debug("Created response history", response...
{ answer = arguments.map((arg) => { return keyForArgument(arg); }).join(':'); }
conditional_block
font_image_data_generator.js
/** * Created by gooma on 4/16/2016. * * Generate font of same style, with different scale **/ Dr.Declare('Graphic.FontImageDataGenerator', 'class'); Dr.Require('Graphic.FontImageDataGenerator', 'Graphic.ImageDataExt'); Dr.Require('Graphic.FontImageDataGenerator', 'Graphic.ImageOperation'); Dr.Implement('Graphic.Fo...
var context = generated_image_data_ext.data.getContext('2d'); context.font = font_config.attribute; context.textAlign = "start"; context.textBaseline = "middle"; // better than 'top' context.fillStyle = font_config.fill_style; context.fillText(symbol, 0, font_config.line_height * 0.5); this.symbol...
ImageDataExt.type.CANVAS_ELEMENT, metrics_width, font_config.line_height);
random_line_split
font_image_data_generator.js
/** * Created by gooma on 4/16/2016. * * Generate font of same style, with different scale **/ Dr.Declare('Graphic.FontImageDataGenerator', 'class'); Dr.Require('Graphic.FontImageDataGenerator', 'Graphic.ImageDataExt'); Dr.Require('Graphic.FontImageDataGenerator', 'Graphic.ImageOperation'); Dr.Implement('Graphic.Fo...
}, getScaledSymbolImageData: function (symbol, scale_ratio, font_config) { font_config = font_config || this._default_font_config; var cache_key = symbol + '|' + scale_ratio + ':' + font_config.cache_tag; var scaled_image_data = this.scaled_symbol_image_data_map[cache_key]; if (!scaled_image_data) { ...
{ return this.generateSymbolImageData(symbol, font_config, this.getSymbolMetricsWidth(symbol, font_config)); }
conditional_block
mod.rs
// Copyright 2012-2014 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...
.as_slice(), [Number(color as int)], &mut Variables::new()); if s.is_ok() { try!(self.out.write(s.unwrap().as_slice())); return Ok(true) } } Ok(false) } fn attr(&mut self, attr: att...
.strings .find_equiv(&("setab")) .unwrap()
random_line_split
mod.rs
// Copyright 2012-2014 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...
(&mut self, attr: attr::Attr) -> IoResult<bool> { match attr { attr::ForegroundColor(c) => self.fg(c), attr::BackgroundColor(c) => self.bg(c), _ => { let cap = cap_for_attr(attr); let parm = self.ti.strings.find_equiv(&cap); if ...
attr
identifier_name
service.py
# Licensed to the Software Freedom Conservancy (SFC) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The SFC licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
self.env = env def start(self): """ Starts the ChromeDriver Service. :Exceptions: - WebDriverException : Raised either when it cannot find the executable, when it does not have permissions for the executable, or when it cannot connect to the service. ...
if self.port == 0: self.port = utils.free_port()
random_line_split
service.py
# Licensed to the Software Freedom Conservancy (SFC) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The SFC licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not...
if self.port == 0: self.port = utils.free_port() self.env = env def start(self): """ Starts the ChromeDriver Service. :Exceptions: - WebDriverException : Raised either when it cannot find the executable, when it does not have permissions for...
self.service_args.append('--log-path=%s' % log_path)
conditional_block