file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
12.1k
suffix
large_stringlengths
0
12k
middle
large_stringlengths
0
7.51k
fim_type
large_stringclasses
4 values
f0f1d6ProgressViewIOS.android.js
'use strict'; var React = require('React'); var StyleSheet = require('StyleSheet'); var Text = require('Text'); var View = require('View'); var DummyProgressViewIOS = function (_React$Component) { babelHelpers.inherits(DummyProgressViewIOS, _React$Component); function DummyProgressViewIOS()
babelHelpers.createClass(DummyProgressViewIOS, [{ key: 'render', value: function render() { return React.createElement( View, { style: [styles.dummy, this.props.style] }, React.createElement( Text, { style: styles.text }, 'ProgressViewIOS is not su...
{ babelHelpers.classCallCheck(this, DummyProgressViewIOS); return babelHelpers.possibleConstructorReturn(this, (DummyProgressViewIOS.__proto__ || Object.getPrototypeOf(DummyProgressViewIOS)).apply(this, arguments)); }
identifier_body
f0f1d6ProgressViewIOS.android.js
'use strict'; var React = require('React'); var StyleSheet = require('StyleSheet'); var Text = require('Text'); var View = require('View'); var DummyProgressViewIOS = function (_React$Component) { babelHelpers.inherits(DummyProgressViewIOS, _React$Component); function
() { babelHelpers.classCallCheck(this, DummyProgressViewIOS); return babelHelpers.possibleConstructorReturn(this, (DummyProgressViewIOS.__proto__ || Object.getPrototypeOf(DummyProgressViewIOS)).apply(this, arguments)); } babelHelpers.createClass(DummyProgressViewIOS, [{ key: 'render', value: functi...
DummyProgressViewIOS
identifier_name
f0f1d6ProgressViewIOS.android.js
'use strict'; var React = require('React'); var StyleSheet = require('StyleSheet'); var Text = require('Text');
babelHelpers.inherits(DummyProgressViewIOS, _React$Component); function DummyProgressViewIOS() { babelHelpers.classCallCheck(this, DummyProgressViewIOS); return babelHelpers.possibleConstructorReturn(this, (DummyProgressViewIOS.__proto__ || Object.getPrototypeOf(DummyProgressViewIOS)).apply(this, arguments...
var View = require('View'); var DummyProgressViewIOS = function (_React$Component) {
random_line_split
channel_1000_uvplot.py
import os import matplotlib.pyplot as plt import numpy as np from plotting_styles import onecolumn_figure, default_figure from paths import paper1_figures_path ''' Make a UV plot of the 1000th HI channel. ''' uvw = np.load("/mnt/MyRAID/M33/VLA/14B-088/HI/" "14B-088_HI_LSRK.ms.contsub_channel_1000.uvw.n...
plt.savefig(paper1_figures_path("m33_hi_uv_plane_chan1000.pdf")) plt.savefig(paper1_figures_path("m33_hi_uv_plane_chan1000.png")) plt.close() default_figure()
plt.grid() plt.tight_layout()
random_line_split
main_test.ts
/// <reference path='../../typings/mocha/mocha.d.ts'/> /// <reference path='../../typings/chai/chai.d.ts'/> /// <reference path='../../typings/node/node.d.ts'/> import * as assert from 'assert'; import * as ts from 'typescript'; import * as chai from 'chai'; import * as fs from 'fs'; import {Minifier, options} from '....
var defaultLibName = ts.getDefaultLibFilePath(options); var libSource = fs.readFileSync(ts.getDefaultLibFilePath(options), 'utf-8'); var libSourceFile: ts.SourceFile; function parseFile(fileName: string, fileContent: string): ts.Program { var compilerHost: ts.CompilerHost = { getSourceFile: function(sourceNam...
{ var result = translateSource(code); return chai.expect(result); }
identifier_body
main_test.ts
/// <reference path='../../typings/mocha/mocha.d.ts'/> /// <reference path='../../typings/chai/chai.d.ts'/> /// <reference path='../../typings/node/node.d.ts'/> import * as assert from 'assert'; import * as ts from 'typescript'; import * as chai from 'chai'; import * as fs from 'fs'; import {Minifier, options} from '....
} }); return namesToContents['test.ts']; } describe('Equality statement', () => {it('shows that 1 equals 1', () => { assert.equal(1, 1); })}); describe('Recognizes invalid TypeScript inputs', () => { it('expects a "Malformed TypeScript" error when fed invalid TypeScript', () => { var minifier = new Mini...
// if (not a .d.ts file) and (is a .js or .ts file) if (!sf.fileName.match(/\.d\.ts$/) && !!sf.fileName.match(/\.[jt]s$/)) { namesToContents[sf.fileName] = minifier.visit(sf);
random_line_split
main_test.ts
/// <reference path='../../typings/mocha/mocha.d.ts'/> /// <reference path='../../typings/chai/chai.d.ts'/> /// <reference path='../../typings/node/node.d.ts'/> import * as assert from 'assert'; import * as ts from 'typescript'; import * as chai from 'chai'; import * as fs from 'fs'; import {Minifier, options} from '....
}); return namesToContents['test.ts']; } describe('Equality statement', () => {it('shows that 1 equals 1', () => { assert.equal(1, 1); })}); describe('Recognizes invalid TypeScript inputs', () => { it('expects a "Malformed TypeScript" error when fed invalid TypeScript', () => { var minifier = new Minifier(...
{ namesToContents[sf.fileName] = minifier.visit(sf); }
conditional_block
main_test.ts
/// <reference path='../../typings/mocha/mocha.d.ts'/> /// <reference path='../../typings/chai/chai.d.ts'/> /// <reference path='../../typings/node/node.d.ts'/> import * as assert from 'assert'; import * as ts from 'typescript'; import * as chai from 'chai'; import * as fs from 'fs'; import {Minifier, options} from '....
(code: string) { var result = translateSource(code); return chai.expect(result); } var defaultLibName = ts.getDefaultLibFilePath(options); var libSource = fs.readFileSync(ts.getDefaultLibFilePath(options), 'utf-8'); var libSourceFile: ts.SourceFile; function parseFile(fileName: string, fileContent: string): ts.Pr...
expectTranslate
identifier_name
lastilePro.py
# # lastilePro.py # # (c) 2013, martin isenburg - http://rapidlasso.com # rapidlasso GmbH - fast tools to catch reality # # uses lastile.exe to compute a tiling for a folder # worth of LiDAR files with a user-specified tile # size (and an optional buffer) # # LiDAR input: LAS/LAZ/BIN/TXT/SHP/BIL/ASC/DTM...
c = c + 1 ### maybe an output format was selected if sys.argv[c] != "#": if sys.argv[c] == "las": command.append("-olas") elif sys.argv[c] == "laz": command.append("-olaz") elif sys.argv[c] == "bin": command.append("-obin") elif sys.argv[c] == "txt": ...
command.append("-extra_pass")
conditional_block
lastilePro.py
# # lastilePro.py # # (c) 2013, martin isenburg - http://rapidlasso.com # rapidlasso GmbH - fast tools to catch reality # # uses lastile.exe to compute a tiling for a folder # worth of LiDAR files with a user-specified tile # size (and an optional buffer) # # LiDAR input: LAS/LAZ/BIN/TXT/SHP/BIL/ASC/DTM...
### create the geoprocessor object gp = arcgisscripting.create(9.3) ### report that something is happening gp.AddMessage("Starting lastile production ...") ### get number of arguments argc = len(sys.argv) ### report arguments (for debug) #gp.AddMessage("Arguments:") #for i in range(0, argc): # gp...
if console == True: process = subprocess.Popen(command) else: process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True) output,error = process.communicate() returncode = process.poll() return returncode,output
identifier_body
lastilePro.py
# # lastilePro.py # # (c) 2013, martin isenburg - http://rapidlasso.com # rapidlasso GmbH - fast tools to catch reality # # uses lastile.exe to compute a tiling for a folder # worth of LiDAR files with a user-specified tile # size (and an optional buffer) # # LiDAR input: LAS/LAZ/BIN/TXT/SHP/BIL/ASC/DTM...
(command,console): if console == True: process = subprocess.Popen(command) else: process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True) output,error = process.communicate() returncode = process.poll() return r...
check_output
identifier_name
lastilePro.py
# # lastilePro.py # # (c) 2013, martin isenburg - http://rapidlasso.com # rapidlasso GmbH - fast tools to catch reality # # uses lastile.exe to compute a tiling for a folder # worth of LiDAR files with a user-specified tile # size (and an optional buffer) # # LiDAR input: LAS/LAZ/BIN/TXT/SHP/BIL/ASC/DTM...
### maybe create a buffer around the tiles if sys.argv[c] != "0": command.append("-buffer") command.append(sys.argv[c].replace(",",".")) c = c + 1 ### maybe the output will be over 2000 tiles if sys.argv[c] == "true": command.append("-extra_pass") c = c + 1 ### maybe an output format wa...
command.append("-tile_size") command.append(sys.argv[c].replace(",",".")) c = c + 1
random_line_split
get_test.py
import os import requests import json import pandas as pd import numpy as np import time from datetime import datetime TMDB_KEY = "60027f35df522f00e57a79b9d3568423" """ def get_tmdb_id_list(): #function to get all Tmdb_id between 06-16 import requests import json # from year 1996-2016 year = ran...
+ "&include_adult=false&include_video=false" \ + "&page=%d" \ + "&primary_release_year=%d" for n in page_num: for yr in year: rq = requests.get(tmdb_id_query % (TMDB_KEY,n,yr)).json() for item in rq['results']: ...
+ "api_key=%s" \ + "&language=en-US&sort_by=release_date.asc" \
random_line_split
Knob.js
CanvasFocus = this.handleCanvasFocus.bind(this); this.handleCanvasBlur = this.handleCanvasBlur.bind(this); this.handleCanvasKeyDown = this.handleCanvasKeyDown.bind(this); this.captureMouse = this.captureMouse.bind(this); this.releaseMouse = this.releaseMouse.bind(this); } // Utility method that can...
adjustValueByPixels(deltaPixels) { const deltaNormalizedValue = deltaPixels*DRAG_PIXELS_TO_NORMALIZED_VALUE; let newValue = this.normalizedValueToInternal(clampUnit(this.internalValueToNormalized(this.props.value + this.accumulatedValue) + deltaNormalizedValue)); if (this.props.integral) { const ...
{ this.captureMouse(); this.lastMousePosition = {x: e.nativeEvent.pageX, y: e.nativeEvent.pageY}; this.canvasElem.focus(); // Since we preventDefault, need to do this manually e.preventDefault(); }
identifier_body
Knob.js
(nv); } parseToInternalValue(s) { return this.props.integral ? parseInt(s) : parseFloat(s); } componentDidMount() { this.updateCanvas(); } componentDidUpdate() { this.updateCanvas(); } componentWillUnmount() { if (this.mouseCaptured) { this.releaseMouse(); } } handleIn...
<div style={{position: 'relative'}}> <label style={{display: 'block', position: 'absolute', top: -(0.5*canvasHeight + 15), width: WIDE_WIDTH, left: -0.5*WIDE_WIDTH, textAlign: 'center', whiteSpace: 'nowrap'}}>{label}</label>
random_line_split
Knob.js
CanvasFocus = this.handleCanvasFocus.bind(this); this.handleCanvasBlur = this.handleCanvasBlur.bind(this); this.handleCanvasKeyDown = this.handleCanvasKeyDown.bind(this); this.captureMouse = this.captureMouse.bind(this); this.releaseMouse = this.releaseMouse.bind(this); } // Utility method that can...
() { this.commitEditText(); this.setState({ inputFocused: false, editingText: null, }); } handleInputChange(e) { if (this.state.inputFocused) { this.setState({ editingText: e.target.value, }); } else { // NOTE: I'm not sure if this code can be reached, but ...
handleInputBlur
identifier_name
Knob.js
curve = this.props.curve; const min = this.props.min; const max = this.props.max; let v; if (curve === 'linear') { v = min + nv*(max - min); } else if (curve === 'log') { v = min * Math.exp(nv * Math.log(max/min)); } else { throw new Error('Unrecognized value for curve', cur...
{ const FOCUS_CIRCLE_RADIUS = 2; ctx.lineWidth = 1; ctx.strokeStyle = inactiveArcStyle; ctx.beginPath(); ctx.arc(knobCenterX, knobCenterY, 0.65*canvasWidth, 0, 2*Math.PI); ctx.stroke(); }
conditional_block
kindck-inherited-copy-bound.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 ...
(&self) {} } impl<T:Copy> Foo for T { } fn take_param<T:Foo>(foo: &T) { } fn a() { let x = box 3; take_param(&x); //~ ERROR `core::marker::Copy` is not implemented } fn b() { let x = box 3; let y = &x; let z = &x as &Foo; //~ ERROR `core::marker::Copy` is not implemented } fn main() { }
foo
identifier_name
kindck-inherited-copy-bound.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 ...
} impl<T:Copy> Foo for T { } fn take_param<T:Foo>(foo: &T) { } fn a() { let x = box 3; take_param(&x); //~ ERROR `core::marker::Copy` is not implemented } fn b() { let x = box 3; let y = &x; let z = &x as &Foo; //~ ERROR `core::marker::Copy` is not implemented } fn main() { }
{}
identifier_body
kindck-inherited-copy-bound.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 ...
fn main() { }
random_line_split
angular-local-storage-tests.ts
interface TestScope extends ng.IScope { submit: (key: string, value: string) => boolean; getItem: (key: string) => string; removeItem: (key: string) => boolean; clearNumbers: () => boolean; clearAll: () => boolean; unbind: Function; update: (val: string) => void; property: string; } class TestControlle...
// getStorageType var storageType: string = localStorageService.getStorageType(); // set $scope.submit = (key, value) => { return localStorageService.set(key, value); }; // get $scope.getItem = (key) => { return localStorageService.get<string>(key); }; // remove $s...
}
random_line_split
angular-local-storage-tests.ts
interface TestScope extends ng.IScope { submit: (key: string, value: string) => boolean; getItem: (key: string) => string; removeItem: (key: string) => boolean; clearNumbers: () => boolean; clearAll: () => boolean; unbind: Function; update: (val: string) => void; property: string; } class TestControlle...
// getStorageType var storageType: string = localStorageService.getStorageType(); // set $scope.submit = (key, value) => { return localStorageService.set(key, value); }; // get $scope.getItem = (key) => { return localStorageService.get<string>(key); }; // remove ...
{ // do something }
conditional_block
angular-local-storage-tests.ts
interface TestScope extends ng.IScope { submit: (key: string, value: string) => boolean; getItem: (key: string) => string; removeItem: (key: string) => boolean; clearNumbers: () => boolean; clearAll: () => boolean; unbind: Function; update: (val: string) => void; property: string; } class TestControlle...
$scope.removeItem = (key) => { return localStorageService.remove(key); }; // clearAll(regexp) $scope.clearNumbers = () => { return localStorageService.clearAll(/^\d+$/); }; // clearAll $scope.clearAll = () => { return localStorageService.clearAll(); }; // keys ...
{ // isSupported if (localStorageService.isSupported) { // do something } // getStorageType var storageType: string = localStorageService.getStorageType(); // set $scope.submit = (key, value) => { return localStorageService.set(key, value); }; // get $scope.getItem...
identifier_body
angular-local-storage-tests.ts
interface TestScope extends ng.IScope { submit: (key: string, value: string) => boolean; getItem: (key: string) => string; removeItem: (key: string) => boolean; clearNumbers: () => boolean; clearAll: () => boolean; unbind: Function; update: (val: string) => void; property: string; } class
{ constructor($scope: TestScope, localStorageService: ng.local.storage.ILocalStorageService) { // isSupported if (localStorageService.isSupported) { // do something } // getStorageType var storageType: string = localStorageService.getStorageType(); // set $scope.submit = (key, val...
TestController
identifier_name
config.rs
_write: Vec<Rule>, } /// Whether or not a matching [Rule] should Allow or Deny access #[derive(Clone, Deserialize, Debug, PartialEq, Serialize, JsonSchema)] pub enum Action { /// Matching rules will allow packets through. #[serde(rename = "ALLOW")] Allow, /// Matching rules will block packets. #[se...
} impl<'de> Deserialize<'de> for PortRange { /// Port ranges can be specified in yaml as either "10" as as single value /// or as "10-20" as a range, between a minimum and a maximum. /// This deserializes either format into a [PortRange]. fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> ...
{ if self.0.start == (self.0.end - 1) { return serializer.serialize_str(self.0.start.to_string().as_str()); } let range = format!("{}-{}", self.0.start, self.0.end); serializer.serialize_str(range.as_str()) }
identifier_body
config.rs
_write: Vec<Rule>, } /// Whether or not a matching [Rule] should Allow or Deny access #[derive(Clone, Deserialize, Debug, PartialEq, Serialize, JsonSchema)] pub enum Action { /// Matching rules will allow packets through. #[serde(rename = "ALLOW")] Allow, /// Matching rules will block packets. #[se...
self.ports .iter() .any(|range| range.contains(&address.port())) } } /// Invalid min and max values for a [PortRange]. #[derive(Debug, thiserror::Error)] pub enum PortRangeError { #[error("invalid port range: min {min:?} is greater than or equal to max {max:?}")] InvalidRa...
{ return false; }
conditional_block
config.rs
use schemars::JsonSchema; use serde::de::{self, Visitor}; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use crate::{filters::ConvertProtoConfigError, map_proto_enum}; use super::quilkin::filters::firewall::v1alpha1::{ firewall::{Action as ProtoAction, PortRange as ProtoPortRange, Rule as ProtoRul...
random_line_split
config.rs
_write: Vec<Rule>, } /// Whether or not a matching [Rule] should Allow or Deny access #[derive(Clone, Deserialize, Debug, PartialEq, Serialize, JsonSchema)] pub enum Action { /// Matching rules will allow packets through. #[serde(rename = "ALLOW")] Allow, /// Matching rules will block packets. #[se...
{ pub action: Action, /// ipv4 or ipv6 CIDR address. #[schemars(with = "String")] pub source: IpNetwork, pub ports: Vec<PortRange>, } impl Rule { /// Returns `true` if `address` matches the provided CIDR address as well /// as at least one of the port ranges in the [Rule]. /// /// ...
Rule
identifier_name
lib.rs
<T> once we're done using it pub fn shareable(self) -> Arc<T> { self.0 } } impl<T> Deref for UniqueArc<T> { type Target = T; fn deref(&self) -> &T { &*self.0 } } impl<T> DerefMut for UniqueArc<T> { fn deref_mut(&mut self) -> &mut T { // We know this to be uniquely owned...
else { None } } #[inline] fn is_unique(&self) -> bool { // We can use Relaxed here, but the justification is a bit subtle. // // The reason to use Acquire would be to synchronize with other threads // that are modifying the refcount with Release, i.e. to...
{ unsafe { // See make_mut() for documentation of the threadsafety here. Some(&mut (*this.ptr()).data) } }
conditional_block
lib.rs
ne(&self, other: &Arc<T>) -> bool { *(*self) != *(*other) } } impl<T: ?Sized + PartialOrd> PartialOrd for Arc<T> { fn partial_cmp(&self, other: &Arc<T>) -> Option<Ordering> { (**self).partial_cmp(&**other) } fn lt(&self, other: &Arc<T>) -> bool { *(*self) < *(*other) } ...
/// The slice length. length: usize, }
random_line_split
lib.rs
(&self, f: &mut fmt::Formatter) -> fmt::Result { fmt::Pointer::fmt(&self.ptr(), f) } } impl<T: ?Sized + 'static> fmt::Debug for NonZeroPtrMut<T> { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { <Self as fmt::Pointer>::fmt(self, f) } } impl<T: ?Sized + 'static> PartialEq for NonZero...
fmt
identifier_name
lib.rs
} impl<T: ?Sized + 'static> Eq for NonZeroPtrMut<T> {} pub struct Arc<T: ?Sized + 'static> { p: NonZeroPtrMut<ArcInner<T>>, } /// An Arc that is known to be uniquely owned /// /// This lets us build arcs that we can mutate before /// freezing, without needing to change the allocation pub struct UniqueArc<T: ?Si...
{ self.ptr() == other.ptr() }
identifier_body
conf.py
created by # sphinx-quickstart on Tue Jul 9 22:26:36 2013. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # ser...
(cls, name): return MagicMock() MOCK_MODULES = ['face_recognition_models', 'Click', 'dlib', 'numpy', 'PIL'] sys.modules.update((mod_name, Mock()) for mod_name in MOCK_MODULES) # If extensions (or modules to document with autodoc) are in another # directory, add these directories to sys.path here. If the d...
__getattr__
identifier_name
conf.py
created by # sphinx-quickstart on Tue Jul 9 22:26:36 2013. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # ser...
# Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'face_recognition', u'Face Recognition Documentation', u'Adam Geitgey', 'face_recognition', 'One line descri...
# -- Options for Texinfo output ----------------------------------------
random_line_split
conf.py
created by # sphinx-quickstart on Tue Jul 9 22:26:36 2013. # # This file is execfile()d with the current directory set to its # containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # ser...
MOCK_MODULES = ['face_recognition_models', 'Click', 'dlib', 'numpy', 'PIL'] sys.modules.update((mod_name, Mock()) for mod_name in MOCK_MODULES) # If extensions (or modules to document with autodoc) are in another # directory, add these directories to sys.path here. If the directory is # relative to the documentation...
@classmethod def __getattr__(cls, name): return MagicMock()
identifier_body
manual_migration.rs
// Copyright 2020 The Exonum Team // // 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 i...
(db: Arc<dyn Database>) { // Create fork to apply changes to it. let fork = db.fork(); { let new_data = Migration::new("test", &fork); let mut new_schema = v2::Schema::new(new_data.clone()); let old_data = Prefixed::new("test", fork.readonly()); let old_schema = v1::Schema::...
manual_migration
identifier_name
manual_migration.rs
// Copyright 2020 The Exonum Team // // 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 i...
new_schema.wallets.put(&public_key, new_wallet); } if i % 1_000 == 999 { println!("Processed {} wallets", i + 1); } } } fn manual_migration(db: Arc<dyn Database>) { // Create fork to apply changes to it. let fork = db.fork(); { let new_data = M...
{ let old_schema = v1::Schema::new(old_data); let mut new_schema = v2::Schema::new(new_data.clone()); // Migrate wallets. for (i, (public_key, wallet)) in old_schema.wallets.iter().enumerate() { if wallet.username == "Eve" { // We don't like Eves 'round these parts. Remove her trans...
identifier_body
manual_migration.rs
// Copyright 2020 The Exonum Team // // 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 i...
// Migrate wallets. for (i, (public_key, wallet)) in old_schema.wallets.iter().enumerate() { if wallet.username == "Eve" { // We don't like Eves 'round these parts. Remove her transaction history // and don't migrate the wallet. new_data.create_tombstone(("histories"...
/// - Wallets and wallet history belonging to the users named "Eve' are dropped. fn migrate_wallets(new_data: Migration<&Fork>, old_data: Prefixed<ReadonlyFork<'_>>) { let old_schema = v1::Schema::new(old_data); let mut new_schema = v2::Schema::new(new_data.clone());
random_line_split
manual_migration.rs
// Copyright 2020 The Exonum Team // // 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 i...
if i % 1_000 == 999 { println!("Processed {} wallets", i + 1); } } } fn manual_migration(db: Arc<dyn Database>) { // Create fork to apply changes to it. let fork = db.fork(); { let new_data = Migration::new("test", &fork); let mut new_schema = v2::Schema::...
{ // Merkelize the wallet history. let mut history = new_schema.histories.get(&public_key); history.extend(&old_schema.histories.get(&public_key)); let new_wallet = v2::Wallet { username: wallet.username, balance: wallet.balance, ...
conditional_block
mod.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use common::SourceLocationKey; use fixture_tests::Fixture; use graphql_ir::{build, Program}; use graphql_syntax::parse_executable; ...
}
{ panic!("Expected exactly one %extensions% section marker.") }
conditional_block
mod.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */
use graphql_syntax::parse_executable; use graphql_test_helpers::diagnostics_to_sorted_string; use relay_test_schema::get_test_schema_with_extensions; use relay_transforms::validate_server_only_directives; use std::sync::Arc; pub fn transform_fixture(fixture: &Fixture<'_>) -> Result<String, String> { let parts: Vec...
use common::SourceLocationKey; use fixture_tests::Fixture; use graphql_ir::{build, Program};
random_line_split
mod.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use common::SourceLocationKey; use fixture_tests::Fixture; use graphql_ir::{build, Program}; use graphql_syntax::parse_executable; ...
{ let parts: Vec<_> = fixture.content.split("%extensions%").collect(); if let [base, extensions] = parts.as_slice() { let source_location = SourceLocationKey::standalone(fixture.file_name); let ast = parse_executable(base, source_location).unwrap(); let schema = get_test_schema_with_ext...
identifier_body
mod.rs
/* * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ use common::SourceLocationKey; use fixture_tests::Fixture; use graphql_ir::{build, Program}; use graphql_syntax::parse_executable; ...
(fixture: &Fixture<'_>) -> Result<String, String> { let parts: Vec<_> = fixture.content.split("%extensions%").collect(); if let [base, extensions] = parts.as_slice() { let source_location = SourceLocationKey::standalone(fixture.file_name); let ast = parse_executable(base, source_location).unwra...
transform_fixture
identifier_name
lib.rs
#![feature(test)] extern crate time; extern crate test; #[test]
// pretty print pub fn pretty_print(e : &str) { let t = time::now(); let s = time::strftime("%Y-%m-%d %H:%M:%S", &t); if s.is_ok() { println!("{0}\t{1}", s.unwrap(), e); } else { println!("####-##-## ##:##:##\t{}", e); } } // mean of array pub fn mean(a : &[f32]) -> f32 { let m...
fn it_works() { }
random_line_split
lib.rs
#![feature(test)] extern crate time; extern crate test; #[test] fn it_works() { } // pretty print pub fn pretty_print(e : &str)
// mean of array pub fn mean(a : &[f32]) -> f32 { let mut sum = 0.0; let mut n = 0.0; for p in a.iter() { sum = sum + *p; // need to (*) dereference pointers n = n + 1.0; } let f = sum / n; return f; } // median of array pub fn median(a : &[f32]) -> f32 { let l = a.len(); ...
{ let t = time::now(); let s = time::strftime("%Y-%m-%d %H:%M:%S", &t); if s.is_ok() { println!("{0}\t{1}", s.unwrap(), e); } else { println!("####-##-## ##:##:##\t{}", e); } }
identifier_body
lib.rs
#![feature(test)] extern crate time; extern crate test; #[test] fn
() { } // pretty print pub fn pretty_print(e : &str) { let t = time::now(); let s = time::strftime("%Y-%m-%d %H:%M:%S", &t); if s.is_ok() { println!("{0}\t{1}", s.unwrap(), e); } else { println!("####-##-## ##:##:##\t{}", e); } } // mean of array pub fn mean(a : &[f32]) -> f32 { ...
it_works
identifier_name
lib.rs
#![feature(test)] extern crate time; extern crate test; #[test] fn it_works() { } // pretty print pub fn pretty_print(e : &str) { let t = time::now(); let s = time::strftime("%Y-%m-%d %H:%M:%S", &t); if s.is_ok()
else { println!("####-##-## ##:##:##\t{}", e); } } // mean of array pub fn mean(a : &[f32]) -> f32 { let mut sum = 0.0; let mut n = 0.0; for p in a.iter() { sum = sum + *p; // need to (*) dereference pointers n = n + 1.0; } let f = sum / n; return f; } // media...
{ println!("{0}\t{1}", s.unwrap(), e); }
conditional_block
event-kit.d.ts
// Type definitions for event-kit (v1.1.0) // Project: https://github.com/atom/event-kit // Definitions by: david-driscoll <https://github.com/david-driscoll/> // Definitions: https://github.com/borisyankov/DefinitelyTyped // Generated by: https://github.com/david-driscoll/atom-typescript-generator // Generation tool ...
{ /** * Construct an instance, optionally with one or more disposables */ constructor(); /** * Dispose all disposables added to this composite disposable. * * If this object has already been disposed, this method has no effect. */ ...
CompositeDisposable
identifier_name
event-kit.d.ts
// Type definitions for event-kit (v1.1.0) // Project: https://github.com/atom/event-kit // Definitions by: david-driscoll <https://github.com/david-driscoll/> // Definitions: https://github.com/borisyankov/DefinitelyTyped // Generated by: https://github.com/david-driscoll/atom-typescript-generator // Generation tool ...
/** * Invoke handlers registered via {::on} for the given event name. * @param eventName - The name of the event to emit. Handlers registered with {::on} for the same name will be invoked. * @param ...value - Callbacks will be invoked with this value as an argument. */ ...
random_line_split
RelayModernEnvironmentExecuteSubscriptionWithMatchTestPlainUserNameRenderer_name$normalization.graphql.js
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @generated SignedSource<<e8b636a26472c96224e2eadc9f2d6038>> * @flow * @lightSyntaxTransform * @nogrep */ /* eslint-disabl...
module.exports = node;
{ (node/*: any*/).hash = "66782037b8711299a7b744a9ff2840c5"; }
conditional_block
RelayModernEnvironmentExecuteSubscriptionWithMatchTestPlainUserNameRenderer_name$normalization.graphql.js
/** * Copyright (c) Meta Platforms, Inc. and affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @generated SignedSource<<e8b636a26472c96224e2eadc9f2d6038>>
*/ /* eslint-disable */ 'use strict'; /*:: import type { NormalizationSplitOperation } from 'relay-runtime'; */ var node/*: NormalizationSplitOperation*/ = { "kind": "SplitOperation", "metadata": {}, "name": "RelayModernEnvironmentExecuteSubscriptionWithMatchTestPlainUserNameRenderer_name$normalization", ...
* @flow * @lightSyntaxTransform * @nogrep
random_line_split
SecureDict.py
def interactiveConsole(a,b=None): ''' Useful function for debugging Placing interactiveConsole(locals(),globals()) into code will drop into an interactive console when run ''' import code d = {} if b:
d.update(a) c=code.InteractiveConsole(locals=d) c.interact() class SecureDict(object): __slots__ = ('__items__',) def __init__(self, *a, **kw): self.__items__ = dict(*a, **kw) def getItem(self, item, default = None): if default!=None: return self.__items__.get(i...
d.update(b)
conditional_block
SecureDict.py
def interactiveConsole(a,b=None): ''' Useful function for debugging Placing interactiveConsole(locals(),globals()) into code will drop into an interactive console when run ''' import code d = {} if b: d.update(b) d.update(a) c=code.InteractiveConsole(locals=d)...
def setItem(self, item, value): self.__items__[item] = value def __len__(self): return len(self.__items__) def __repr__(self): return 'SecureDict(%r)' % self.__items__ __str__ = __repr__ def keys(self): return self.__items__.keys() def values(self): ...
if default!=None: return self.__items__.get(item,default) try: return self.__items__[item] except KeyError: raise KeyError('Key Error: %s'%item)
identifier_body
SecureDict.py
def interactiveConsole(a,b=None): ''' Useful function for debugging Placing interactiveConsole(locals(),globals()) into code will drop into an interactive console when run ''' import code d = {} if b: d.update(b) d.update(a) c=code.InteractiveConsole(locals=d)...
(self): return self.__items__.keys() def values(self): return self.__items__.values() def pop(self,key): return self.__items__.pop(key)
keys
identifier_name
SecureDict.py
def interactiveConsole(a,b=None): ''' Useful function for debugging Placing interactiveConsole(locals(),globals()) into code will drop into an interactive console when run ''' import code d = {} if b: d.update(b) d.update(a) c=code.InteractiveConsole(locals=d)...
def pop(self,key): return self.__items__.pop(key)
return self.__items__.keys() def values(self): return self.__items__.values()
random_line_split
[id].ts
import fs from "fs"; import path from "path"; import * as showdown from "showdown"; import { POSTS_DIR, getPosts } from "."; const converter: showdown.Converter = new showdown.Converter(); export const getFullPost = async (posts: any[], slug: string): Promise<any> => { const postData = posts.find((post) => post.slug...
} }; export default async (req, res) => { const posts = await getPosts(); const post = await getFullPost(posts, req.url.split("/").pop()); return res.status(200).json(post); };
{ return { redirect: postData.url, }; }
conditional_block
[id].ts
import fs from "fs"; import path from "path"; import * as showdown from "showdown"; import { POSTS_DIR, getPosts } from ".";
if (!postData) { return { error: true, }; } if (postData.url) { return { error: true, }; } try { const articlePath: string = path.resolve( POSTS_DIR, postData.path, "article.md" ); const entry: string = await fs.promises.readFile(articlePath, "utf-8...
const converter: showdown.Converter = new showdown.Converter(); export const getFullPost = async (posts: any[], slug: string): Promise<any> => { const postData = posts.find((post) => post.slug === slug);
random_line_split
lev.js
0); //start physics game.physics.startSystem(Phaser.Physics.ARCADE); //add background game.add.sprite(0, 0, 'sky'); //releaseLedge(); //add music deadSound = game.add.audio('deadS'); coinMusic = game.add.audio('coinS'); //game music music = game.add.audio('gamemusic',1,true); music.play('',0,1,true)...
(){ var ledge2 = platforms.getFirstDead(); //var ledge2 = platforms.getFirstExists(false); ledge2.reset(600,game.world.height - 200); //ledge2.reset(600,game.world.height - 200); //200 //add velocity to the ledge ledge2.body.velocity.x = -200; ledge2.body.immovable = true; //kill the ledge when i...
addSecondLedge
identifier_name
lev.js
.audio('coinS'); //game music music = game.add.audio('gamemusic',1,true); music.play('',0,1,true); //create a group platforms = game.add.group(); platforms.enableBody = true; //platforms.physicsBodyType = Phaser.Physics.ARCADE; platforms.createMultiple(8,'ground'); //////// //platforms.setAll('body.velo...
{ //move to the right player.body.velocity.x = 200; player.animations.play('right'); }
conditional_block
lev.js
0); //start physics game.physics.startSystem(Phaser.Physics.ARCADE); //add background game.add.sprite(0, 0, 'sky'); //releaseLedge(); //add music deadSound = game.add.audio('deadS'); coinMusic = game.add.audio('coinS'); //game music music = game.add.audio('gamemusic',1,true); music.play('',0,1,true)...
//***********need to change here so the ledge can appear in different time this.timer = this.game.time.events.loop(1600,addLS,this); //this.Startimer = this.game.time.events.loop(randNumber(),addstar,this); //this.Startimer.start(); //add the first ledge function addfirstledge(){ var ledge1 = platforms.getFirs...
{ i = Math.floor((Math.random() * (1+3000-1999)) + 1999); return i; }
identifier_body
lev.js
0); //start physics game.physics.startSystem(Phaser.Physics.ARCADE); //add background game.add.sprite(0, 0, 'sky'); //releaseLedge(); //add music deadSound = game.add.audio('deadS'); coinMusic = game.add.audio('coinS'); //game music music = game.add.audio('gamemusic',1,true); music.play('',0,1,true)...
this.timer = this.game.time.events.loop(1600,addLS,this); //this.Startimer = this.game.time.events.loop(randNumber(),addstar,this); //this.Startimer.start(); //add the first ledge function addfirstledge(){ var ledge1 = platforms.getFirstDead(); //var ledge2 = platforms.getFirstExists(false); ledge1.reset(200...
random_line_split
sph_echo_test.rs
extern crate sphlib; extern crate libc; use sphlib::{sph_echo, utils}; #[test] fn will_be_224_hash()
#[test] fn will_be_256_hash() { let dest = sph_echo::echo256_init_load_close(""); let actual = utils::to_hex_hash(&dest); assert_eq!("4496cd09d425999aefa75189ee7fd3c97362aa9e4ca898328002d20a4b519788", actual.to_string()); } #[test] fn will_be_384_hash() { let dest = sph_echo::echo384_init_load_cl...
{ let dest = sph_echo::echo224_init_load_close(""); let actual = utils::to_hex_hash(&dest); assert_eq!("17da087595166f733fff7cdb0bca6438f303d0e00c48b5e7a3075905", actual.to_string()); }
identifier_body
sph_echo_test.rs
extern crate sphlib; extern crate libc; use sphlib::{sph_echo, utils}; #[test] fn will_be_224_hash() { let dest = sph_echo::echo224_init_load_close(""); let actual = utils::to_hex_hash(&dest); assert_eq!("17da087595166f733fff7cdb0bca6438f303d0e00c48b5e7a3075905", actual.to_string()); }
assert_eq!("4496cd09d425999aefa75189ee7fd3c97362aa9e4ca898328002d20a4b519788", actual.to_string()); } #[test] fn will_be_384_hash() { let dest = sph_echo::echo384_init_load_close(""); let actual = utils::to_hex_hash(&dest); assert_eq!("134040763f840559b84b7a1ae5d6d64fc3659821a789cc64a7f1444c09ee7f81a...
#[test] fn will_be_256_hash() { let dest = sph_echo::echo256_init_load_close(""); let actual = utils::to_hex_hash(&dest);
random_line_split
sph_echo_test.rs
extern crate sphlib; extern crate libc; use sphlib::{sph_echo, utils}; #[test] fn will_be_224_hash() { let dest = sph_echo::echo224_init_load_close(""); let actual = utils::to_hex_hash(&dest); assert_eq!("17da087595166f733fff7cdb0bca6438f303d0e00c48b5e7a3075905", actual.to_string()); } #[test] fn
() { let dest = sph_echo::echo256_init_load_close(""); let actual = utils::to_hex_hash(&dest); assert_eq!("4496cd09d425999aefa75189ee7fd3c97362aa9e4ca898328002d20a4b519788", actual.to_string()); } #[test] fn will_be_384_hash() { let dest = sph_echo::echo384_init_load_close(""); let actual = uti...
will_be_256_hash
identifier_name
read.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use crate::repo::AdminRepo; use anyhow::{Error, Result}; use blobstore::Blobstore; use context::CoreContext; use skiplist::{deserialize_ski...
let maybebytes = repo.repo_blobstore.get(ctx, &blobstore_key).await?; match maybebytes { Some(bytes) => { debug!( logger, "received {} bytes from blobstore", bytes.as_bytes().len() ); let bytes = bytes.into_raw_bytes(); ...
ctx: &CoreContext, repo: &AdminRepo, logger: &Logger, blobstore_key: String, ) -> Result<Option<SkiplistIndex>, Error> {
random_line_split
read.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use crate::repo::AdminRepo; use anyhow::{Error, Result}; use blobstore::Blobstore; use context::CoreContext; use skiplist::{deserialize_ski...
{ let maybebytes = repo.repo_blobstore.get(ctx, &blobstore_key).await?; match maybebytes { Some(bytes) => { debug!( logger, "received {} bytes from blobstore", bytes.as_bytes().len() ); let bytes = bytes.into_raw_bytes()...
identifier_body
read.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use crate::repo::AdminRepo; use anyhow::{Error, Result}; use blobstore::Blobstore; use context::CoreContext; use skiplist::{deserialize_ski...
( ctx: &CoreContext, repo: &AdminRepo, logger: &Logger, blobstore_key: String, ) -> Result<Option<SkiplistIndex>, Error> { let maybebytes = repo.repo_blobstore.get(ctx, &blobstore_key).await?; match maybebytes { Some(bytes) => { debug!( logger, ...
get_skiplist_index
identifier_name
read.rs
/* * Copyright (c) Meta Platforms, Inc. and affiliates. * * This software may be used and distributed according to the terms of the * GNU General Public License version 2. */ use crate::repo::AdminRepo; use anyhow::{Error, Result}; use blobstore::Blobstore; use context::CoreContext; use skiplist::{deserialize_ski...
}; Ok(()) } pub async fn get_skiplist_index( ctx: &CoreContext, repo: &AdminRepo, logger: &Logger, blobstore_key: String, ) -> Result<Option<SkiplistIndex>, Error> { let maybebytes = repo.repo_blobstore.get(ctx, &blobstore_key).await?; match maybebytes { Some(bytes) => { ...
{ info!(logger, "skiplist not found"); }
conditional_block
test_ramda_v0.27.x_misc.js
/* @flow */ /*eslint-disable no-undef, no-unused-vars, no-console*/ import _, { compose, pipe, curry, filter, find, isNil, repeat, replace, zipWith } from "ramda"; import { describe, it } from 'flow-typed-test'; const ns: Array<number> = [1, 2, 3, 4, 5]; const ss: Array<string> = ["one", "two", "thre...
const r4: string = replace(/[,]/, "|")("b,d,d"); }); it('should supports replace by RegExp with replacement fn', () => { const fn = (match: string, g1: string): string => g1; const r1: string = replace(/([,])d/, fn, "b,d,d"); const r2: string = replace(/([,])d/)(fn, "b,d,d"); const...
const r1: string = replace(/[,]/, "|", "b,d,d"); const r2: string = replace(/[,]/)("|", "b,d,d"); const r3: string = replace(/[,]/)("|")("b,d,d");
random_line_split
frame.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/. */ use msg::constellation_msg::{FrameId, PipelineId}; use pipeline::Pipeline; use script_traits::LoadData; use std::c...
}; let frame = match self.frames.get(&frame_id) { Some(frame) => frame, None => { warn!("Frame {:?} iterated after closure.", frame_id); continue; }, }; let child_frame_ids = frame.pre...
let pipelines = self.pipelines; loop { let frame_id = match self.stack.pop() { Some(frame_id) => frame_id, None => return None,
random_line_split
frame.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/. */ use msg::constellation_msg::{FrameId, PipelineId}; use pipeline::Pipeline; use script_traits::LoadData; use std::c...
(&mut self) -> Vec<FrameState> { replace(&mut self.next, vec!()) } /// Update the current entry of the Frame from an entry that has been traversed to. pub fn update_current(&mut self, pipeline_id: PipelineId, entry: FrameState) { self.pipeline_id = pipeline_id; self.instant = entry....
remove_forward_entries
identifier_name
mutex.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 (tx, rx) = channel(); for _ in range(0, K) { let tx2 = tx.clone(); spawn(proc() { inc(); tx2.send(()); }); let tx2 = tx.clone(); spawn(proc() { inc(); tx2.send(()); }); } drop(tx); for _ in range(0, 2 * K) { rx.rec...
} }
random_line_split
mutex.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 ...
(guard: mutex::LockGuard) -> Guard { Guard { guard: guard } } /// Static initialization of a mutex. This constant can be used to initialize /// other mutex constants. pub const MUTEX_INIT: StaticMutex = StaticMutex { lock: mutex::NATIVE_MUTEX_INIT }; impl StaticMutex { /// Attempts to grab this lock, see ...
lift_guard
identifier_name
xsupport.py
"""Assorted commands. """ import os import threading import sublime import sublime_plugin from Vintageous.state import _init_vintageous from Vintageous.state import State from Vintageous.vi import settings from Vintageous.vi import cmd_defs from Vintageous.vi.dot_file import DotFile from Vintageous.vi.utils import m...
(self, view): settings.destroy(view) class ViMouseTracker(sublime_plugin.EventListener): def on_text_command(self, view, command, args): if command == 'drag_select': state = State(view) if state.mode in (modes.VISUAL, modes.VISUAL_LINE, modes...
on_close
identifier_name
xsupport.py
"""Assorted commands. """ import os import threading import sublime import sublime_plugin from Vintageous.state import _init_vintageous from Vintageous.state import State from Vintageous.vi import settings from Vintageous.vi import cmd_defs from Vintageous.vi.dot_file import DotFile from Vintageous.vi.utils import m...
else: with open(path, 'w'): pass self.window.open_file(path)
self.window.open_file(path)
conditional_block
xsupport.py
"""Assorted commands. """ import os import threading import sublime import sublime_plugin from Vintageous.state import _init_vintageous from Vintageous.state import State from Vintageous.vi import settings from Vintageous.vi import cmd_defs from Vintageous.vi.dot_file import DotFile from Vintageous.vi.utils import m...
if state.mode in (modes.VISUAL, modes.VISUAL_LINE, modes.VISUAL_BLOCK): if (args.get('extend') or (args.get('by') == 'words') or args.get('additive')): return elif not args.get('extend'): ...
random_line_split
xsupport.py
"""Assorted commands. """ import os import threading import sublime import sublime_plugin from Vintageous.state import _init_vintageous from Vintageous.state import State from Vintageous.vi import settings from Vintageous.vi import cmd_defs from Vintageous.vi.dot_file import DotFile from Vintageous.vi.utils import m...
class ReloadVintageousSettings(sublime_plugin.TextCommand): def run(self, edit): DotFile.from_user().run() class VintageousOpenConfigFile(sublime_plugin.WindowCommand): """Opens or creates $packages/User/.vintageousrc. """ def run(self): path = os.path.realpath(os.path.join(sublim...
prefs = sublime.load_settings('Preferences.sublime-settings') value = prefs.get('vintageous_use_ctrl_keys', False) prefs.set('vintageous_use_ctrl_keys', (not value)) sublime.save_settings('Preferences.sublime-settings') status = 'enabled' if (not value) else 'disabled' print("Pac...
identifier_body
fitsinfo.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ ``fitsinfo`` is a command-line script based on astropy.io.fits for printing a summary of the HDUs in one or more FITS files(s) to the standard output. Example usage of ``fitsinfo``: 1. Print a summary of the HDUs in a FITS file:: $ fitsinfo file...
fitsinfo(filename)
print()
conditional_block
fitsinfo.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ ``fitsinfo`` is a command-line script based on astropy.io.fits for printing a summary of the HDUs in one or more FITS files(s) to the standard output. Example usage of ``fitsinfo``: 1. Print a summary of the HDUs in a FITS file:: $ fitsinfo file...
"""The main function called by the `fitsinfo` script.""" parser = argparse.ArgumentParser( description=('Print a summary of the HDUs in a FITS file(s).')) parser.add_argument('filename', nargs='+', help='Path to one or more FITS files. ' 'Wildcards ar...
identifier_body
fitsinfo.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ ``fitsinfo`` is a command-line script based on astropy.io.fits for printing a summary of the HDUs in one or more FITS files(s) to the standard output. Example usage of ``fitsinfo``: 1. Print a summary of the HDUs in a FITS file:: $ fitsinfo file...
(args=None): """The main function called by the `fitsinfo` script.""" parser = argparse.ArgumentParser( description=('Print a summary of the HDUs in a FITS file(s).')) parser.add_argument('filename', nargs='+', help='Path to one or more FITS files. ' ...
main
identifier_name
fitsinfo.py
# Licensed under a 3-clause BSD style license - see LICENSE.rst """ ``fitsinfo`` is a command-line script based on astropy.io.fits for printing a summary of the HDUs in one or more FITS files(s) to the standard output. Example usage of ``fitsinfo``: 1. Print a summary of the HDUs in a FITS file:: $ fitsinfo file...
def main(args=None): """The main function called by the `fitsinfo` script.""" parser = argparse.ArgumentParser( description=('Print a summary of the HDUs in a FITS file(s).')) parser.add_argument('filename', nargs='+', help='Path to one or more FITS files. ' ...
except IOError as e: log.error(str(e)) return
random_line_split
xSlider.js
/* * @fileOverview xSlider * @version 1.5.1 * @date 2016-2-25 * @author Xinbo Shang * */ "use strict"; (function(factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as anonymous module. define(['jquery'], factory); } else if (typeof exports === 'object...
var _this = this; this.TIMER = setInterval(function() { if (_this.OPTIONS.direction == 'rtl') { _this.toPrev(); } else { _this.toNext(); } }, _this.OPTIONS.interval...
} }, autoPlay: function() { if (this.OPTIONS.autoPlay) {
random_line_split
xSlider.js
/* * @fileOverview xSlider * @version 1.5.1 * @date 2016-2-25 * @author Xinbo Shang * */ "use strict"; (function(factory) { if (typeof define === 'function' && define.amd) { // AMD. Register as anonymous module. define(['jquery'], factory); } else if (typeof exports === 'object...
}, // when autoplay and the options.direction is rtl, switch to the prev toPrev: function() { if (!this.IS_WORKING) { var next = this.CURRENT_DISPLAY - 1; this.animate(next); } }, animate: function(num) { var _t...
{ var next = this.CURRENT_DISPLAY + 1; this.animate(next); }
conditional_block
keypair.unit.js
'use strict'; var expect = require('chai').expect; var bitcore = require('bitcore-lib'); var Message = require('bitcore-message'); var secp256k1 = require('secp256k1'); var KeyPair = require('../../lib/crypto-tools/keypair'); var prvk = '4d548b387bed22aff9ca560416d7b13ecbad16f28bc41ef5acaff3019bfa5134'; var prvk2 = '0...
describe('@constructor', function() { it('should work without the new keyword', function() { expect(KeyPair()).to.be.instanceOf(KeyPair); }); }); describe('#getPrivateKey', function() { it('should use the private key supplied if provided', function() { var kp = KeyPair(prvk); exp...
describe('KeyPair', function() {
random_line_split
index.js
var express = require('express'); var app = module.exports = express(); var api = require('lib/db-api'); var config = require('lib/config'); var path = require('path'); var url = require('url'); var resolve = path.resolve; var strip = require('strip');
app.get('/topic/:id', function(req, res, next){ log('Facebook Request /topic/%s', req.params.id); api.topic.get(req.params.id, function (err, topicDoc) { if (err) return _handleError(err, req, res); log('Serving Facebook topic %s', topicDoc.id); var baseUrl = url.format({ protocol: config.proto...
var log = require('debug')('democracyos:facebook-card');
random_line_split
dom.rs
::opts; pub use style_traits::UnsafeNode; /// An opaque handle to a node, which, unlike UnsafeNode, cannot be transformed /// back into a non-opaque representation. The only safe operation that can be /// performed on this node is to compare it to another opaque handle or to another /// OpaqueNode. /// /// Layout and...
note_restyle_hint
identifier_name
dom.rs
_SELF, RestyleHint}; use selector_parser::{ElementExt, PseudoElement, RestyleDamage}; use sink::Push; use std::fmt::Debug; use std::ops::BitOr; use std::sync::Arc; use stylist::ApplicableDeclarationBlock; use traversal::DomTraversalContext; use util::opts; pub use style_traits::UnsafeNode; /// An opaque handle to a n...
.get_box().clone_display() == display::T::none } /// Returns true if this node has a styled layout frame that owns the style. fn frame_has_style(&self) -> bool { false } /// Returns the styles from the layout frame that owns them, if any. /// /// FIXME(bholley): Once we start dropp...
/// Returns true if this element's current style is display:none. Only valid /// to call after styling. fn is_display_none(&self) -> bool { self.borrow_data().unwrap() .current_styles().primary
random_line_split
dom.rs
, RestyleHint}; use selector_parser::{ElementExt, PseudoElement, RestyleDamage}; use sink::Push; use std::fmt::Debug; use std::ops::BitOr; use std::sync::Arc; use stylist::ApplicableDeclarationBlock; use traversal::DomTraversalContext; use util::opts; pub use style_traits::UnsafeNode; /// An opaque handle to a node, ...
} pub struct LayoutIterator<T>(pub T); impl<T, I> Iterator for LayoutIterator<T> where T: Iterator<Item=I>, I: NodeInfo { type Item = I; fn next(&mut self) -> Option<I> { loop { // Filter out nodes that layout should ignore. let n = self.0.next(); if n.is_none() || ...
{ self.is_element() || self.is_text_node() }
identifier_body
gulpfile.js
var path = require('path'); var gulp = require('gulp'); var eslint = require('gulp-eslint'); var excludeGitignore = require('gulp-exclude-gitignore'); var mocha = require('gulp-mocha'); var istanbul = require('gulp-istanbul'); var nsp = require('gulp-nsp'); var plumber = require('gulp-plumber'); var coveralls = require...
return gulp.src(path.join(__dirname, 'coverage/lcov.info')) .pipe(coveralls()); }); gulp.task('babel', function () { return gulp.src('lib/**/*.js') .pipe(babel()) .pipe(gulp.dest('dist')); }); gulp.task('clean', function () { return del('dist'); }); gulp.task('prepublish', ['nsp', 'babel']); gulp...
{ return; }
conditional_block
gulpfile.js
var path = require('path'); var gulp = require('gulp'); var eslint = require('gulp-eslint'); var excludeGitignore = require('gulp-exclude-gitignore'); var mocha = require('gulp-mocha'); var istanbul = require('gulp-istanbul'); var nsp = require('gulp-nsp'); var plumber = require('gulp-plumber'); var coveralls = require...
gulp.task('babel', function () { return gulp.src('lib/**/*.js') .pipe(babel()) .pipe(gulp.dest('dist')); }); gulp.task('clean', function () { return del('dist'); }); gulp.task('prepublish', ['nsp', 'babel']); gulp.task('default', ['test', 'static']);
return gulp.src(path.join(__dirname, 'coverage/lcov.info')) .pipe(coveralls()); });
random_line_split
__init__.py
""" calabar.tunnels This module encapsulates various tunnel processes and their management. """ import signal import os import sys import psi.process TUN_TYPE_STR = 'tunnel_type' # Configuration/dictionary key for the type of tunnel # Should match the tunnel_type argument to Tunnel __init__ methods PROC_NOT_RUNNING...
{ 'tunnel_type': 'ssh', 'from': 'root@10.10.251.2:386', 'to': '127.0.0.1:387 } } """ tun_confs_d = {} for section in config.sections(): if section.startswith(TUNNEL_PREFIX): tun_conf_d = ...
}, 'bar':
random_line_split
__init__.py
""" calabar.tunnels This module encapsulates various tunnel processes and their management. """ import signal import os import sys import psi.process TUN_TYPE_STR = 'tunnel_type' # Configuration/dictionary key for the type of tunnel # Should match the tunnel_type argument to Tunnel __init__ methods PROC_NOT_RUNNING...
return False class TunnelsAlreadyLoadedException(Exception): """Once tunnels are loaded the first time, other methods must be used to update them""" pass class ExecutableNotFound(Exception): """ The given tunnel executable wasn't found or isn't executable. """ pass class TunnelTypeD...
status = proc.status if not status in PROC_NOT_RUNNING: return True
conditional_block
__init__.py
""" calabar.tunnels This module encapsulates various tunnel processes and their management. """ import signal import os import sys import psi.process TUN_TYPE_STR = 'tunnel_type' # Configuration/dictionary key for the type of tunnel # Should match the tunnel_type argument to Tunnel __init__ methods PROC_NOT_RUNNING...
(self): """ Start all of the configured tunnels and register to keep them running. """ for t in self.tunnels: try: t.open() except ExecutableNotFound, e: print >> sys.stderr, e def continue_tunnels(self): """ En...
start_tunnels
identifier_name
__init__.py
""" calabar.tunnels This module encapsulates various tunnel processes and their management. """ import signal import os import sys import psi.process TUN_TYPE_STR = 'tunnel_type' # Configuration/dictionary key for the type of tunnel # Should match the tunnel_type argument to Tunnel __init__ methods PROC_NOT_RUNNING...
""" tun_confs_d = {} for section in config.sections(): if section.startswith(TUNNEL_PREFIX): tun_conf_d = parse_tunnel(config, section) tun_name = section[len(TUNNEL_PREFIX):] tun_confs_d[tun_name] = tun_conf_d return tun_confs_d def parse_tunnel(config, ...
""" Return a dictionary of dictionaries containg tunnel configurations based on the given SafeConfigParser instance. An example return value might be:: { 'foo': { 'tunnel_type': 'vpnc', 'conf_file': '/etc/calabar/foo.conf', ...
identifier_body
deprecate.d.ts
// TODO: This file should be removed once https://github.com/emberjs/ember.js/issues/17185 close // tslint:disable-next-line:strict-export-declare-modifiers interface DeprecationOptions { id: string; until: string; url?: string; } /** * Display a deprecation warning with the provided message and a stack trace ...
/** * Display a warning with the provided message. */ export function warn(message: string, test: boolean, options: { id: string }): void; export function warn(message: string, options: { id: string }): void; /** * @deprecated Missing deprecation options: https://emberjs.com/deprecations/v2.x/#toc_ember-debug-functi...
*/ export function runInDebug(func: () => any): void;
random_line_split
setup.py
from setuptools import setup, Extension import numpy as np import platform version = '0.1.3' ext_modules = []
setup (name = 'droneapi', zip_safe=True, version = version, description = 'Python language bindings for the DroneApi', long_description = '''Python language bindings for the DroneApi (includes the droneapi MAVProxy module)''', url = 'https://github.com/diydrones/droneapi-python', ...
random_line_split
brightness_filter.class.js
(function(global) { 'use strict'; var fabric = global.fabric || (global.fabric = { }), extend = fabric.util.object.extend; /** * Brightness filter class * @class fabric.Image.filters.Brightness * @memberOf fabric.Image.filters * @extends fabric.Image.filters.BaseFilter * @see {@link fabri...
context.putImageData(imageData, 0, 0); }, /** * Returns object representation of an instance * @return {Object} Object representation of an instance */ toObject: function() { return extend(this.callSuper('toObject'), { brightness: this.brightness }); } }); ...
{ data[i] += brightness; data[i + 1] += brightness; data[i + 2] += brightness; }
conditional_block
brightness_filter.class.js
(function(global) { 'use strict'; var fabric = global.fabric || (global.fabric = { }), extend = fabric.util.object.extend; /** * Brightness filter class * @class fabric.Image.filters.Brightness * @memberOf fabric.Image.filters * @extends fabric.Image.filters.BaseFilter * @see {@link fabri...
* object.applyFilters(canvas.renderAll.bind(canvas)); */ fabric.Image.filters.Brightness = fabric.util.createClass(fabric.Image.filters.BaseFilter, /** @lends fabric.Image.filters.Brightness.prototype */ { /** * Filter type * @param {String} type * @default */ type: 'Brightness', ...
* }); * object.filters.push(filter);
random_line_split
eda.py
(TfidfVectorizer, self).build_analyzer() return lambda doc: english_stemmer.stemWords(analyzer(doc)) def text_to_wordlist( review, remove_stopwords=False ): # Function to convert a document to a sequence of words, # optionally removing stop words. Returns a list of words. # # 1. Remove HTML ...
(ngram=3,stem=False,max_features=2000,min_df=2,remove_stopwords=True,holdout_perc=0.25,seed=123,debug=True): train_data = pd.read_csv('data/train.csv') if debug: df = train_data.loc[:5000] else: print(">>> loading test set ...") test = pd.read_csv('data/test.csv') test.fillna...
build_data_set
identifier_name
eda.py
", text) text = re.sub(r"\'ve", " have ", text) text = re.sub(r"can't", "cannot ", text) text = re.sub(r"n't", " not ", text) text = re.sub(r"i'm", "i am ", text) text = re.sub(r"\'re", " are ", text) text = re.sub(r"\'d", " would ", text) text = re.sub(r"\'ll", " will ", text) text = r...
columns=columns))
random_line_split