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
editorsObserver.ts
{ return this.editorsPerResourceCounter.has(resource); } constructor( @IEditorGroupsService private editorGroupsService: IEditorGroupsService, @IStorageService private readonly storageService: IStorageService ) { super(); this.registerListeners(); } private registerListeners(): void { this._registe...
{ await this.doEnsureOpenedEditorsLimit(limit, [...this.mostRecentEditorsMap.values()], exclude); }
conditional_block
editorsObserver.ts
= this.editorsPerResourceCounter.get(editor.resource); return editors?.has(editor.typeId) ?? false; } hasEditors(resource: URI): boolean { return this.editorsPerResourceCounter.has(resource); } constructor( @IEditorGroupsService private editorGroupsService: IEditorGroupsService, @IStorageService private...
(group: IEditorGroup, editor: IEditorInput): IEditorIdentifier | undefined { const groupMap = this.keyMap.get(group.id); if (!groupMap) { return undefined; } return groupMap.get(editor); } private ensureKey(group: IEditorGroup, editor: IEditorInput): IEditorIdentifier { let groupMap = this.keyMap.get(g...
findKey
identifier_name
issue-15896.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...
{ enum R { REB(()) } struct Tau { t: uint } enum E { B(R, Tau) } let e = B(REB(()), Tau { t: 3 }); let u = match e { B( Tau{t: x}, //~^ ERROR mismatched types: expected `main::R`, found `main::Tau` // (expected enum main::R, found struct main::Tau) ...
identifier_body
issue-15896.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...
{ t: uint } enum E { B(R, Tau) } let e = B(REB(()), Tau { t: 3 }); let u = match e { B( Tau{t: x}, //~^ ERROR mismatched types: expected `main::R`, found `main::Tau` // (expected enum main::R, found struct main::Tau) _) => x, }; }
Tau
identifier_name
issue-15896.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...
}
random_line_split
GameObject.ts
/// <reference path="Transform3D.ts" /> namespace zen { export class GameObject extends Transform3D { public name:string = "GameObject"; public tag:string = ""; public layer:string = ""; private _guid:string = zen.guid.create(); public get guid() { return t...
} else { console.error("System: " + component.type + " doesn't exist"); } } public getComponent<T extends Component>(type:ComponentType | number):T { return <T>this._components[type]; } public removeComponent(component:Component):voi...
{ console.error("Game Object already has " + component.type + " Component"); }
conditional_block
GameObject.ts
/// <reference path="Transform3D.ts" /> namespace zen { export class GameObject extends Transform3D { public name:string = "GameObject"; public tag:string = ""; public layer:string = ""; private _guid:string = zen.guid.create(); public get guid() { return t...
public getComponent<T extends Component>(type:ComponentType | number):T { return <T>this._components[type]; } public removeComponent(component:Component):void { let system:System = this._app.systemManager.getSystem(component.type); if(system) { ...
{ let system:System = this._app.systemManager.getSystem(component.type); if(system) { if(!this._components[component.type]) { component.gameObject = this; system.addComponent(this, component); this._components[component....
identifier_body
GameObject.ts
/// <reference path="Transform3D.ts" /> namespace zen { export class GameObject extends Transform3D { public name:string = "GameObject"; public tag:string = ""; public layer:string = ""; private _guid:string = zen.guid.create(); public get guid() { return t...
<T extends Component>(type:ComponentType | number):T { return <T>this._components[type]; } public removeComponent(component:Component):void { let system:System = this._app.systemManager.getSystem(component.type); if(system) { if(this._components[compo...
getComponent
identifier_name
GameObject.ts
/// <reference path="Transform3D.ts" /> namespace zen { export class GameObject extends Transform3D { public name:string = "GameObject"; public tag:string = "";
public layer:string = ""; private _guid:string = zen.guid.create(); public get guid() { return this._guid; } private _app:Application; constructor(app:Application) { super(); this._app = app; } private _components:{...
random_line_split
units.rs
use std::ops::Add; use std::marker::PhantomData; /// Create void enumerations to define unit types. #[derive(Debug, Clone, Copy)] enum Inch {} #[derive(Debug, Clone, Copy)] enum Mm {} /// `Length` is a type with phantom type parameter `Unit`, /// and is not generic over the length type (that is `f64`). /// /// `f64` ...
impl<Unit> Add for Length<Unit> { type Output = Length<Unit>; // add() returns a new `Length` struct containing the sum. fn add(self, rhs: Length<Unit>) -> Length<Unit> { // `+` calls the `Add` implementation for `f64`. Length(self.0 + rhs.0, PhantomData) } } fn main() { // Specif...
/// The `Add` trait defines the behavior of the `+` operator.
random_line_split
units.rs
use std::ops::Add; use std::marker::PhantomData; /// Create void enumerations to define unit types. #[derive(Debug, Clone, Copy)] enum Inch {} #[derive(Debug, Clone, Copy)] enum Mm {} /// `Length` is a type with phantom type parameter `Unit`, /// and is not generic over the length type (that is `f64`). /// /// `f64` ...
() { // Specifies `one_foot` to have phantom type parameter `Inch`. let one_foot: Length<Inch> = Length(12.0, PhantomData); // `one_meter` has phantom type parameter `Mm`. let one_meter: Length<Mm> = Length(1000.0, PhantomData); // `+` calls the `add()` method we implemented for `Length<Unit>`. ...
main
identifier_name
units.rs
use std::ops::Add; use std::marker::PhantomData; /// Create void enumerations to define unit types. #[derive(Debug, Clone, Copy)] enum Inch {} #[derive(Debug, Clone, Copy)] enum Mm {} /// `Length` is a type with phantom type parameter `Unit`, /// and is not generic over the length type (that is `f64`). /// /// `f64` ...
} fn main() { // Specifies `one_foot` to have phantom type parameter `Inch`. let one_foot: Length<Inch> = Length(12.0, PhantomData); // `one_meter` has phantom type parameter `Mm`. let one_meter: Length<Mm> = Length(1000.0, PhantomData); // `+` calls the `add()` method we implemented for `Leng...
{ // `+` calls the `Add` implementation for `f64`. Length(self.0 + rhs.0, PhantomData) }
identifier_body
formatter.ts
last = acc[acc.length - 1] if (last && last.math === c.math) { last.text += c.text } else {
return acc }, []) .map(c => c.math ? `$${c.text}$` : c.text) .join('') } function shortLabel(label, options) { if (typeof options[label] === 'string') return options[label] return { article: 'art.', chapter: 'ch.', subchapter: 'subch.', column: 'col.', figure: 'fig.', lin...
acc.push(c) }
random_line_split
formatter.ts
function shortLabel(label, options) { if (typeof options[label] === 'string') return options[label] return { article: 'art.', chapter: 'ch.', subchapter: 'subch.', column: 'col.', figure: 'fig.', line: 'l.', note: 'n.', issue: 'no.', opus: 'op.', page: 'p.', paragraph: '...
ormatted-citation'(c
identifier_name
formatter.ts
= acc[acc.length - 1] if (last && last.math === c.math) { last.text += c.text } else { acc.push(c) } return acc }, []) .map(c => c.math ? `$${c.text}$` : c.text) .join('') } function shortLabel(label, options) { if (typeof options[label] === 'string') return optio...
let formatted = '' for (const citation of citations) { formatted += `\\${citation.suppressAuthor ? 'citeyear' : options.command}${citation2latex(citation, options)}` } return formatted } public async biblatex(citations, options) { if (citations.length === 0) return '' let command ...
{ const state = citations.reduce((acc, cit) => { for (const field of ['prefix', 'suffix', 'suppressAuthor', 'locator', 'label']) { acc[field] = (acc[field] || 0) + (cit[field] ? 1 : 0) } return acc }, {}) if (state.suffix === 0 && state.prefix === 0 && state.locator ...
conditional_block
formatter.ts
= acc[acc.length - 1] if (last && last.math === c.math) { last.text += c.text } else { acc.push(c) } return acc }, []) .map(c => c.math ? `$${c.text}$` : c.text) .join('') } function shortLabel(label, options) { if (typeof options[label] === 'string') return optio...
public async citationLinks(citations, options) { return citations.map(citation => `cites: ${citation.citekey}`).join('\n') } public async cite(citations, options) { return this.natbib(citations, options) } public async citet(citations, options) { return this.natbib(citations, { command: 'citet', ...optio...
{ const formatted = citations.map(cit => `${options.keyprefix || ''}${cit.citekey}${options.keypostfix || ''}`) return formatted.length ? `${options.citeprefix || ''}${formatted.join(options.separator || ',')}${options.citekeypostfix || ''}` : '' }
identifier_body
ds.rs
use crate::error::*; use crate::rr::dnssec::{Algorithm, DigestType}; use crate::serialize::binary::*; use crate::rr::dnssec::rdata::DNSKEY; use crate::rr::Name; /// [RFC 4034, DNSSEC Resource Records, March 2005](https://tools.ietf.org/html/rfc4034#section-5) /// /// ```text /// 5.1. DS RDATA Wire Format /// /// ...
} /// Read the RData from the given Decoder pub fn read(decoder: &mut BinDecoder, rdata_length: Restrict<u16>) -> ProtoResult<DS> { let start_idx = decoder.index(); let key_tag: u16 = decoder.read_u16()?.unverified(/*key_tag is valid as any u16*/); let algorithm: Algorithm = Algorithm::read(decoder)?; ...
{ Err("Ring or OpenSSL must be enabled for this feature".into()) }
identifier_body
ds.rs
use crate::error::*; use crate::rr::dnssec::{Algorithm, DigestType}; use crate::serialize::binary::*; use crate::rr::dnssec::rdata::DNSKEY; use crate::rr::Name; /// [RFC 4034, DNSSEC Resource Records, March 2005](https://tools.ietf.org/html/rfc4034#section-5) /// /// ```text /// 5.1. DS RDATA Wire Format /// /// ...
pub fn covers(&self, name: &Name, key: &DNSKEY) -> ProtoResult<bool> { key.to_digest(name, self.digest_type()) .map(|hash| hash.as_ref() == self.digest()) } /// This will always return an error unless the Ring or OpenSSL features are enabled #[cfg(not(any(feature = "openssl", featur...
random_line_split
ds.rs
use crate::error::*; use crate::rr::dnssec::{Algorithm, DigestType}; use crate::serialize::binary::*; use crate::rr::dnssec::rdata::DNSKEY; use crate::rr::Name; /// [RFC 4034, DNSSEC Resource Records, March 2005](https://tools.ietf.org/html/rfc4034#section-5) /// /// ```text /// 5.1. DS RDATA Wire Format /// /// ...
(encoder: &mut BinEncoder, rdata: &DS) -> ProtoResult<()> { encoder.emit_u16(rdata.key_tag())?; rdata.algorithm().emit(encoder)?; // always 3 for now encoder.emit(rdata.digest_type().into())?; encoder.emit_vec(rdata.digest())?; Ok(()) } #[cfg(test)] mod tests { #![allow(clippy::dbg_macro, clip...
emit
identifier_name
emailExtract.py
# This program extracts UF email addresses from a CSV file and prints them organized by class sections. import os import re COURSE_NAME = "EEE3308C" def extractEmailAddress(list): for item in list: if "@ufl.edu" in item: return item raise RuntimeError def extractCVSInfo(namePattern): ...
print(COURSE_NAME + " Student Email Summary:",end="\n\n") print("All Emails", end=" ") print("(%d students)" % sum([len(value) for value in dict.values()])) for emails in dict.values(): for email in emails: print(email,end="; ") print("\n\n") for section,emails in dict.items(): print("Section %s (%d st...
dict[entry].append(email)
conditional_block
emailExtract.py
# This program extracts UF email addresses from a CSV file and prints them organized by class sections. import os import re COURSE_NAME = "EEE3308C" def
(list): for item in list: if "@ufl.edu" in item: return item raise RuntimeError def extractCVSInfo(namePattern): csvFiles = [file for file in os.listdir('.') if re.match(namePattern,file)] if len(csvFiles) > 1: print("Multiple " + COURSE_NAME + " CSV files in the current di...
extractEmailAddress
identifier_name
emailExtract.py
# This program extracts UF email addresses from a CSV file and prints them organized by class sections. import os import re COURSE_NAME = "EEE3308C" def extractEmailAddress(list): for item in list: if "@ufl.edu" in item: return item raise RuntimeError def extractCVSInfo(namePattern): ...
else: dict[entry].append(email) print(COURSE_NAME + " Student Email Summary:",end="\n\n") print("All Emails", end=" ") print("(%d students)" % sum([len(value) for value in dict.values()])) for emails in dict.values(): for email in emails: print(email,end="; ") print("\n\n") for s...
random_line_split
emailExtract.py
# This program extracts UF email addresses from a CSV file and prints them organized by class sections. import os import re COURSE_NAME = "EEE3308C" def extractEmailAddress(list):
def extractCVSInfo(namePattern): csvFiles = [file for file in os.listdir('.') if re.match(namePattern,file)] if len(csvFiles) > 1: print("Multiple " + COURSE_NAME + " CSV files in the current directory: ", csvFiles) print("Please make sure there is only one " + COURSE_NAME + " CSV file and tr...
for item in list: if "@ufl.edu" in item: return item raise RuntimeError
identifier_body
index.d.ts
// Type definitions for Web Audio API // Project: http://www.w3.org/TR/webaudio/ // Definitions by: Baruch Berger <https://github.com/bbss>, Kon <http://phyzkit.net/>, kubosho <https://github.com/kubosho> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // // This file refers to the latest published w...
bandpass, /** * The lowshelf filter allows all frequencies through, but adds a boost (or attenuation) to the lower frequencies. It implements a second-order lowshelf filter. * * ## frequency * The upper limit of the frequences where the boost (or attenuation) is applied. * ## Q * ...
* Controls the width of the band. The width becomes narrower as the Q value increases. * ## gain * Not used in this filter type */
random_line_split
segment.rs
use backend::obj; use backend::obj::*; use backend::world::agent; use core::clock::Seconds; use core::geometry::Transform; use core::geometry::*; use core::math; use core::math::ExponentialFilter; use num::Zero; #[derive(Clone)] pub enum PilotRotation { None, Orientation(Position), LookAt(Position), Turn(Angle), ...
#[derive(Clone)] pub struct State { age_seconds: Seconds, age_frames: usize, maturity: f32, charge: ExponentialFilter<f32>, pub intent: Intent, pub last_touched: Option<agent::Key>, } impl Default for State { fn default() -> Self { State { age_seconds: Seconds::zero(), age_frames: 0, maturity: 1.0, ...
}
random_line_split
segment.rs
use backend::obj; use backend::obj::*; use backend::world::agent; use core::clock::Seconds; use core::geometry::Transform; use core::geometry::*; use core::math; use core::math::ExponentialFilter; use num::Zero; #[derive(Clone)] pub enum PilotRotation { None, Orientation(Position), LookAt(Position), Turn(Angle), ...
pub fn restore(&mut self, current_charge: f32, target_charge: f32) { self.charge.reset_to(target_charge, current_charge); } pub fn update(&mut self, dt: Seconds) { self.age_seconds += dt; self.age_frames += 1; self.charge.update(dt.into()); } pub fn with_charge(current_charge: f32, target_charge: f32, ...
{ self.maturity = maturity }
identifier_body
segment.rs
use backend::obj; use backend::obj::*; use backend::world::agent; use core::clock::Seconds; use core::geometry::Transform; use core::geometry::*; use core::math; use core::math::ExponentialFilter; use num::Zero; #[derive(Clone)] pub enum PilotRotation { None, Orientation(Position), LookAt(Position), Turn(Angle), ...
, }) } pub fn growing_radius(&self) -> f32 { self.state.maturity * self.mesh.shape.radius() } pub fn growing_scaled_vertex(&self, index: usize) -> Position { self.state.maturity * self.mesh.scaled_vertex(index) } } impl obj::Drawable for Segment { fn color(&self) -> Rgba { let rgba = self.livery.albedo; ...
{ max - 1 }
conditional_block
segment.rs
use backend::obj; use backend::obj::*; use backend::world::agent; use core::clock::Seconds; use core::geometry::Transform; use core::geometry::*; use core::math; use core::math::ExponentialFilter; use num::Zero; #[derive(Clone)] pub enum PilotRotation { None, Orientation(Position), LookAt(Position), Turn(Angle), ...
{ Idle, Move(Position), Brake(Position), RunAway(Position), PilotTo(Option<Position>, PilotRotation), } #[derive(Clone)] pub struct State { age_seconds: Seconds, age_frames: usize, maturity: f32, charge: ExponentialFilter<f32>, pub intent: Intent, pub last_touched: Option<agent::Key>, } impl Default for S...
Intent
identifier_name
jquery.prettyphoto.js
// If at the beginning, hide the previous link if(set_position == 0) { $pp_pic_holder .find('a.pp_previous') .css('visibility','hidden') .addClass('disabled') .unbind('click'); }else{ $pp_pic_holder.find('a.pp_previous.disabled') .css('visibility','visible') .remove...
random_line_split
jquery.prettyphoto.js
* Closes prettyPhoto. */ $.prettyPhoto.close = function(){ clearInterval(pp_slideshow); $pp_pic_holder.stop().find('object,embed').css('visibility','hidden'); $('div.pp_pic_holder,div.ppt,.pp_fade').fadeOut(settings.animation_speed,function(){ $(this).remove(); }); $pp_overlay.fa...
{ if(doresize && typeof $pp_pic_holder != 'undefined') { scroll_pos = _get_scroll(); titleHeight = $ppt.height(), contentHeight = $pp_pic_holder.height(), contentwidth = $pp_pic_holder.width(); projectedTop = (windowHeight/2) + scroll_pos['scrollTop'] - (contentHeight/2); proje...
identifier_body
jquery.prettyphoto.js
pp_images[set_position]).replace(/{autoplay}/g,settings.autoplay); break; case 'flash': correctSizes = _fitToViewport(movie_width,movie_height); // Fit item to viewport flash_vars = pp_images[set_position]; flash_vars = flash_vars.substring(pp_images[set_position].indexOf('...
_fitToViewport
identifier_name
Config.ts
/** * Loads values from VS Code config. It is currently only read at extension launch, * but config change watchers can be added here if needed. */ import * as vscode from "vscode"; const hackConfig = vscode.workspace.getConfiguration("hack"); // tslint:disable-next-line:no-non-null-assertion export const localWo...
( newWorkspace: string, trust: "trusted" | "untrusted" ) { const remembered = hhastRememberedWorkspaces; remembered[newWorkspace] = trust; await hackConfig.update( "rememberedWorkspaces", remembered, vscode.ConfigurationTarget.Global ); } export const remoteEnabled = hackConfig.get<boolean>("re...
rememberHhastWorkspace
identifier_name
Config.ts
/** * Loads values from VS Code config. It is currently only read at extension launch,
*/ import * as vscode from "vscode"; const hackConfig = vscode.workspace.getConfiguration("hack"); // tslint:disable-next-line:no-non-null-assertion export const localWorkspacePath = vscode.workspace.workspaceFolders![0].uri .fsPath; export let clientPath = hackConfig.get<string>("clientPath") || "hh_client"; cl...
* but config change watchers can be added here if needed.
random_line_split
Config.ts
/** * Loads values from VS Code config. It is currently only read at extension launch, * but config change watchers can be added here if needed. */ import * as vscode from "vscode"; const hackConfig = vscode.workspace.getConfiguration("hack"); // tslint:disable-next-line:no-non-null-assertion export const localWo...
} });
{ vscode.commands.executeCommand("workbench.action.reloadWindow"); }
conditional_block
Config.ts
/** * Loads values from VS Code config. It is currently only read at extension launch, * but config change watchers can be added here if needed. */ import * as vscode from "vscode"; const hackConfig = vscode.workspace.getConfiguration("hack"); // tslint:disable-next-line:no-non-null-assertion export const localWo...
export const remoteEnabled = hackConfig.get<boolean>("remote.enabled", false); export const remoteType: "ssh" | "docker" | undefined = hackConfig.get( "remote.type", undefined ); export const remoteWorkspacePath = hackConfig.get<string>( "remote.workspacePath" ); export const sshHost = hackConfig.get<string>("r...
{ const remembered = hhastRememberedWorkspaces; remembered[newWorkspace] = trust; await hackConfig.update( "rememberedWorkspaces", remembered, vscode.ConfigurationTarget.Global ); }
identifier_body
python.py
klein = raw_input() gross = raw_input() zahl = [] if gross[0] == '0': zahl.append((1,0)) else: zahl.append((0,1)) for i in range(1,len(gross)): if gross[i] == '0': zahl.append((zahl[i - 1][0] + 1, zahl[i - 1][1])) else: zahl.append((zahl[i - 1][0], zahl[i - 1][1] + 1)) plus = 0 for i in range(len(klein)):...
else: plus += zahl[len(gross) - len(klein) + i][0] if i > 0: plus -= zahl[i - 1][0] print plus
plus += zahl[len(gross) - len(klein) + i][1] if i > 0: plus -= zahl[i - 1][1]
conditional_block
python.py
klein = raw_input() gross = raw_input() zahl = [] if gross[0] == '0': zahl.append((1,0)) else: zahl.append((0,1)) for i in range(1,len(gross)): if gross[i] == '0': zahl.append((zahl[i - 1][0] + 1, zahl[i - 1][1])) else: zahl.append((zahl[i - 1][0], zahl[i - 1][1] + 1)) plus = 0 for i in range(len(klein)):...
print plus
random_line_split
snapping.js
function snap( point, e )
} } // elements for ( var i = 0; i < points.length; i++ ) { // points if ( axisOn ) { if ( Math.abs( pos.x - points[i].x ) < 5) { point.x = points[i].x; } if ( Math.abs( pos.y - points[i].y ) < 5) { point.y = points[i].y; } } else { ...
{ // grid var pos = getMousePos(canvas, e); if (objects[0].density != -1) { for ( var i = 0; i < objects[0].xes.length; i++ ) { if ( Math.abs( pos.x - objects[0].xes[i] ) < 5) { point.x = objects[0].xes[i]; } } for ( var i = 0; i < objects[0].yes.length; i++ ) { ...
identifier_body
snapping.js
function snap( point, e ) { // grid var pos = getMousePos(canvas, e); if (objects[0].density != -1) { for ( var i = 0; i < objects[0].xes.length; i++ ) { if ( Math.abs( pos.x - objects[0].xes[i] ) < 5) { point.x = objects[0].xes[i]; } } for ( var i = 0; i < objects[0]...
} return point; } function snaPoint( e ) { var point = new Point(); var pos = getMousePos(canvas, e); point.x = pos.x; point.y = pos.y; point = snap( point, e); canvasRedraw( point ); axis( e ); }
{ if ( Math.abs( pos.x - points[i].x ) < 5 && Math.abs( pos.y - points[i].y ) < 5) { point.x = points[i].x; point.y = points[i].y; } }
conditional_block
snapping.js
function snap( point, e ) { // grid var pos = getMousePos(canvas, e); if (objects[0].density != -1) {
if ( Math.abs( pos.x - objects[0].xes[i] ) < 5) { point.x = objects[0].xes[i]; } } for ( var i = 0; i < objects[0].yes.length; i++ ) { if ( Math.abs( pos.y - objects[0].yes[i] ) < 5) { point.y = objects[0].yes[i]; } } } // elements for ( var i ...
for ( var i = 0; i < objects[0].xes.length; i++ ) {
random_line_split
snapping.js
function
( point, e ) { // grid var pos = getMousePos(canvas, e); if (objects[0].density != -1) { for ( var i = 0; i < objects[0].xes.length; i++ ) { if ( Math.abs( pos.x - objects[0].xes[i] ) < 5) { point.x = objects[0].xes[i]; } } for ( var i = 0; i < objects[0].yes.length; ...
snap
identifier_name
kv62pmf.py
""" A tool for converting kv6 models into pmf. GreaseMonkey, 2013 - Public Domain WARNING: I haven't checked to ensure that X,Y are around the right way. If you find your models have been flipped inadvertently, let me know! --GM """ from __future__ import print_function import sys, struct # Backwards compatibilit...
(s): return struct.unpack("<BBBBHBB",s) blkdata = [parseblk(infp.read(8)) for i in range(blklen)] xoffset = [struct.unpack("<I", infp.read(4))[0] for i in range(xsiz)] xyoffset = [struct.unpack("<H", infp.read(2))[0] for i in range(xsiz*ysiz)] assert blklen == sum(xoffset) assert blklen == sum(xyoffset) # Corollary...
parseblk
identifier_name
kv62pmf.py
""" A tool for converting kv6 models into pmf. GreaseMonkey, 2013 - Public Domain WARNING: I haven't checked to ensure that X,Y are around the right way. If you find your models have been flipped inadvertently, let me know! --GM """ from __future__ import print_function import sys, struct # Backwards compatibilit...
infp = open(sys.argv[1],"rb") if infp.read(4) != b"Kvxl": raise Exception("not a KV6 file") xsiz, ysiz, zsiz, xpivot, ypivot, zpivot, blklen = struct.unpack("<IIIfffI", infp.read(28)) print(xsiz, ysiz, zsiz, xpivot, ypivot, zpivot) xpivot = int(xpivot*ptspacing+0.5) ypivot = int(ypivot*ptspacing+0.5) zpivot = int...
raise Exception("bone name too large")
conditional_block
kv62pmf.py
""" A tool for converting kv6 models into pmf. GreaseMonkey, 2013 - Public Domain WARNING: I haven't checked to ensure that X,Y are around the right way. If you find your models have been flipped inadvertently, let me know! --GM """
import sys, struct # Backwards compatibility - make new code work on old version, not vice-versa PY2 = sys.version_info[0] == 2 PY3 = sys.version_info[0] == 3 if PY2: # This script didn't use range() anyway, so no problem overwriting it in Py2 import __builtin__ range = getattr(__builtin__, "xrange") _ord = ord el...
from __future__ import print_function
random_line_split
kv62pmf.py
""" A tool for converting kv6 models into pmf. GreaseMonkey, 2013 - Public Domain WARNING: I haven't checked to ensure that X,Y are around the right way. If you find your models have been flipped inadvertently, let me know! --GM """ from __future__ import print_function import sys, struct # Backwards compatibilit...
blkdata = [parseblk(infp.read(8)) for i in range(blklen)] xoffset = [struct.unpack("<I", infp.read(4))[0] for i in range(xsiz)] xyoffset = [struct.unpack("<H", infp.read(2))[0] for i in range(xsiz*ysiz)] assert blklen == sum(xoffset) assert blklen == sum(xyoffset) # Corollary: sum(xoffset) == sum(xyoffset) # Proof:...
return struct.unpack("<BBBBHBB",s)
identifier_body
propane.py
#!/usr/bin/env python import sys import optparse import socket import random class bcolors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' if sys.platform == 'win32': HEADER...
if options.chosenmode == "2": resultpath = options.webdir + ''.join(random.choice('0123456789ABCDEF') for i in range(16)) s.send("site cpfr %s" % options.file) if "350" in s.recv(1024): good("File exists! Copying now") else: error("File cannot be found or accessed") s.send("site cpto %s" % resultpath) ...
parser = optparse.OptionParser(banner(), version="%prog") parser.add_option("-t", "--target", dest="target", default="localhost", type="string", help="Target IP") parser.add_option("-p", "--port", dest="port", default=21, type="int", help="Target Port") parser.add_option("-f", "--file", dest="file", default="/etc/p...
identifier_body
propane.py
#!/usr/bin/env python import sys import optparse import socket import random class bcolors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' if sys.platform == 'win32': HEADER...
def main(): parser = optparse.OptionParser(banner(), version="%prog") parser.add_option("-t", "--target", dest="target", default="localhost", type="string", help="Target IP") parser.add_option("-p", "--port", dest="port", default=21, type="int", help="Target Port") parser.add_option("-f", "--file", dest="file", ...
os.system('clear')
conditional_block
propane.py
#!/usr/bin/env python
import optparse import socket import random class bcolors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' if sys.platform == 'win32': HEADER = '' OKBLUE = '' OKGREEN...
import sys
random_line_split
propane.py
#!/usr/bin/env python import sys import optparse import socket import random class bcolors: HEADER = '\033[95m' OKBLUE = '\033[94m' OKGREEN = '\033[92m' WARNING = '\033[93m' FAIL = '\033[91m' ENDC = '\033[0m' BOLD = '\033[1m' UNDERLINE = '\033[4m' if sys.platform == 'win32': HEADER...
( msg ): print bcolors.BOLD + bcolors.OKBLUE + "[" + bcolors.ENDC + "*" + bcolors.OKBLUE + "] " + bcolors.ENDC + str( msg ) + bcolors.ENDC def error( msg ): print bcolors.BOLD + bcolors.FAIL + "[" + bcolors.ENDC + "-" + bcolors.FAIL + "] " + bcolors.ENDC + str( msg ) + bcolors.ENDC def banner(): title = "proFTPd Arb...
status
identifier_name
test_iosxe.py
""" Tests are performed against csr1000v-universalk9.03.15.00.S.155-2.S-std. """ import unittest from iosxe.iosxe import IOSXE from iosxe.exceptions import AuthError node = '172.16.92.134' username = 'cisco' password = 'cisco' port = 55443 class TestIOSXE(unittest.TestCase):
def setUp(self): self.xe = IOSXE(node=node, username=username, password=password, disable_warnings=True) def test_iosxe_is_a_IOSXE(self): self.assertIsInstance(self.xe, IOSXE) def test_invalid_user_pass_returns_auth_error(self): self.assertRaises(AuthError, IOSXE, node=node, username=...
identifier_body
test_iosxe.py
Tests are performed against csr1000v-universalk9.03.15.00.S.155-2.S-std. """ import unittest from iosxe.iosxe import IOSXE from iosxe.exceptions import AuthError node = '172.16.92.134' username = 'cisco' password = 'cisco' port = 55443 class TestIOSXE(unittest.TestCase): def setUp(self): self.xe = IOSX...
"""
random_line_split
test_iosxe.py
""" Tests are performed against csr1000v-universalk9.03.15.00.S.155-2.S-std. """ import unittest from iosxe.iosxe import IOSXE from iosxe.exceptions import AuthError node = '172.16.92.134' username = 'cisco' password = 'cisco' port = 55443 class TestIOSXE(unittest.TestCase): def setUp(self): self.xe = ...
(self): self.assertEqual(self.xe.url_base, 'https://{0}:{1}/api/v1'.format(node, port)) def test_token_uri(self): self.assertEqual(self.xe.token_uri, '/auth/token-services') def test_save_config_success(self): resp = self.xe.save_config() self.assertEqual(204, resp.status_code)...
test_url_base
identifier_name
lib.rs
// Copyright 2014 The Gfx-rs Developers. // // 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 ag...
pub use draw_state::{DrawState, BlendPreset}; pub use draw_state::state; pub use draw_state::target::*; // public re-exports pub use device::{Device, SubmitInfo, Factory, Resources}; pub use device::{attrib, tex, handle}; pub use device::as_byte_slice; pub use device::{BufferRole, BufferInfo, BufferUsage}; pub use dev...
} // draw state re-exports
random_line_split
heroes.component.ts
import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { Hero } from './hero'; import { HeroService } from './hero.service'; //import { AppRoutingModule } from './app-routing.module'; @Component({ moduleId: module.id, selector: 'my-heroes', templateUrl: 'heroes.comp...
onSelect(hero: Hero): void { this.selectedHero = hero; } getHeroes(): void { this.heroService.getHeroes().then(heroes => this.heroes = heroes); } add(name: string): void { name = name.trim(); if (!name) { return; } this.heroService.create(name) .then(hero => { this.heroe...
{}
identifier_body
heroes.component.ts
import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { Hero } from './hero'; import { HeroService } from './hero.service'; //import { AppRoutingModule } from './app-routing.module'; @Component({ moduleId: module.id, selector: 'my-heroes', templateUrl: 'heroes.comp...
}); } ngOnInit(): void { this.getHeroes(); } gotoDetail(): void { this.router.navigate(['/detail', this.selectedHero.id]); } }
{ this.selectedHero = null; }
conditional_block
heroes.component.ts
import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { Hero } from './hero'; import { HeroService } from './hero.service'; //import { AppRoutingModule } from './app-routing.module'; @Component({ moduleId: module.id, selector: 'my-heroes', templateUrl: 'heroes.comp...
gotoDetail(): void { this.router.navigate(['/detail', this.selectedHero.id]); } }
ngOnInit(): void { this.getHeroes(); }
random_line_split
heroes.component.ts
import { Component, OnInit } from '@angular/core'; import { Router } from '@angular/router'; import { Hero } from './hero'; import { HeroService } from './hero.service'; //import { AppRoutingModule } from './app-routing.module'; @Component({ moduleId: module.id, selector: 'my-heroes', templateUrl: 'heroes.comp...
(name: string): void { name = name.trim(); if (!name) { return; } this.heroService.create(name) .then(hero => { this.heroes.push(hero); this.selectedHero = null; }); } delete(hero: Hero): void { this.heroService .delete(hero.id) .then(() => { this.h...
add
identifier_name
b64.rs
#[repr(C)] #[cfg_attr(feature = "extra_traits", derive(Debug, Eq, Hash, PartialEq))] pub struct stat { pub st_dev: ::dev_t, pub st_ino: ::ino_t, pub st_nlink: ::nlink_t, pub st_mode: ::mode_t, st_padding0: i16, pub st_uid: ::uid_t, pub st_gid: ::gid_t, st_padding1: i32, pub st_rdev: ...
(&self) -> ::stat { *self } }
clone
identifier_name
b64.rs
#[repr(C)] #[cfg_attr(feature = "extra_traits", derive(Debug, Eq, Hash, PartialEq))] pub struct stat { pub st_dev: ::dev_t, pub st_ino: ::ino_t, pub st_nlink: ::nlink_t, pub st_mode: ::mode_t, st_padding0: i16, pub st_uid: ::uid_t, pub st_gid: ::gid_t, st_padding1: i32, pub st_rdev: ...
}
random_line_split
vgg.py
# Copyright (c) 2015-2016 Anish Athalye. Released under GPLv3. import tensorflow as tf import numpy as np import scipy.io import pdb MEAN_PIXEL = np.array([ 123.68 , 116.779, 103.939]) def net(data_path, input_image): layers = ( 'conv1_1', 'relu1_1', 'conv1_2', 'relu1_2', 'pool1', 'conv2_1', '...
def unprocess(image): return image + MEAN_PIXEL
return image - MEAN_PIXEL
identifier_body
vgg.py
# Copyright (c) 2015-2016 Anish Athalye. Released under GPLv3. import tensorflow as tf import numpy as np import scipy.io import pdb MEAN_PIXEL = np.array([ 123.68 , 116.779, 103.939]) def net(data_path, input_image): layers = ( 'conv1_1', 'relu1_1', 'conv1_2', 'relu1_2', 'pool1', 'conv2_1', '...
'conv5_1', 'relu5_1', 'conv5_2', 'relu5_2', 'conv5_3', 'relu5_3', 'conv5_4', 'relu5_4' ) data = scipy.io.loadmat(data_path) mean = data['normalization'][0][0][0] mean_pixel = np.mean(mean, axis=(0, 1)) weights = data['layers'][0] net = {} current = input_image for i, n...
'conv4_1', 'relu4_1', 'conv4_2', 'relu4_2', 'conv4_3', 'relu4_3', 'conv4_4', 'relu4_4', 'pool4',
random_line_split
vgg.py
# Copyright (c) 2015-2016 Anish Athalye. Released under GPLv3. import tensorflow as tf import numpy as np import scipy.io import pdb MEAN_PIXEL = np.array([ 123.68 , 116.779, 103.939]) def net(data_path, input_image): layers = ( 'conv1_1', 'relu1_1', 'conv1_2', 'relu1_2', 'pool1', 'conv2_1', '...
assert len(net) == len(layers) return net def _conv_layer(input, weights, bias): conv = tf.nn.conv2d(input, tf.constant(weights), strides=(1, 1, 1, 1), padding='SAME') return tf.nn.bias_add(conv, bias) def _pool_layer(input): return tf.nn.max_pool(input, ksize=(1, 2, 2, 1), strides...
kind = name[:4] if kind == 'conv': kernels, bias = weights[i][0][0][0][0] # matconvnet: weights are [width, height, in_channels, out_channels] # tensorflow: weights are [height, width, in_channels, out_channels] kernels = np.transpose(kernels, (1, 0, 2, 3)) ...
conditional_block
vgg.py
# Copyright (c) 2015-2016 Anish Athalye. Released under GPLv3. import tensorflow as tf import numpy as np import scipy.io import pdb MEAN_PIXEL = np.array([ 123.68 , 116.779, 103.939]) def net(data_path, input_image): layers = ( 'conv1_1', 'relu1_1', 'conv1_2', 'relu1_2', 'pool1', 'conv2_1', '...
(image): return image - MEAN_PIXEL def unprocess(image): return image + MEAN_PIXEL
preprocess
identifier_name
react-loader.d.ts
// Type definitions for react-loader 2.4
// Project: https://github.com/quickleft/react-loader // Definitions by: Sudarsan Balaji <https://github.com/artfuldev> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 import { Component } from 'react'; interface LoaderOptions { lines?: number; length?: number; widt...
random_line_split
react-loader.d.ts
// Type definitions for react-loader 2.4 // Project: https://github.com/quickleft/react-loader // Definitions by: Sudarsan Balaji <https://github.com/artfuldev> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.8 import { Component } from 'react'; interface LoaderOptions { ...
extends Component<LoaderProps> { } declare namespace ReactLoader { } export = ReactLoader;
ReactLoader
identifier_name
unitdata.py
# -*- coding: utf-8 -*- # # Copyright © 2012 - 2014 Michal Čihař <michal@cihar.com> # # This file is part of Weblate <http://weblate.org/> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, eithe...
lf): ''' Returns queryset with related units. ''' related_units = Unit.objects.filter( contentsum=self.contentsum, translation__subproject__project=self.project, ) if self.language is not None: related_units = related_units.filter( ...
_related_units(se
identifier_name
unitdata.py
# -*- coding: utf-8 -*- # # Copyright © 2012 - 2014 Michal Čihař <michal@cihar.com> # # This file is part of Weblate <http://weblate.org/> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, eithe...
positive = models.BooleanField(default=True) class Meta(object): unique_together = ('suggestion', 'user') app_label = 'trans' def __unicode__(self): if self.positive: vote = '+1' else: vote = '-1' return u'{0} for {1} by {2}'.format( ...
''' suggestion = models.ForeignKey(Suggestion) user = models.ForeignKey(User)
random_line_split
unitdata.py
# -*- coding: utf-8 -*- # # Copyright © 2012 - 2014 Michal Čihař <michal@cihar.com> # # This file is part of Weblate <http://weblate.org/> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, eithe...
app_label = 'trans' def __unicode__(self): return u'suggestion for {0} by {1}'.format( self.contentsum, self.user.username if self.user else 'unknown', ) def accept(self, translation, request): allunits = translation.unit_set.filter( contents...
tentsum = models.CharField(max_length=40, db_index=True) target = models.TextField() user = models.ForeignKey(User, null=True, blank=True) project = models.ForeignKey(Project) language = models.ForeignKey(Language) votes = models.ManyToManyField( User, through='Vote', relate...
identifier_body
unitdata.py
# -*- coding: utf-8 -*- # # Copyright © 2012 - 2014 Michal Čihař <michal@cihar.com> # # This file is part of Weblate <http://weblate.org/> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, eithe...
# Update unit flags for relunit in suggestion.get_related_units(): relunit.update_has_suggestion() class Suggestion(models.Model, RelatedUnitMixin): contentsum = models.CharField(max_length=40, db_index=True) target = models.TextField() user = models.ForeignKey(User, null=True, ...
r.profile.suggested += 1 user.profile.save()
conditional_block
FFlistGlyphinfo.py
#!/usr/bin/env python 'FontForge: List all the data in a glyph object in key, value pairs' __url__ = 'http://github.com/silnrsi/pysilfont' __copyright__ = 'Copyright (c) 2015, SIL International (http://www.sil.org)' __license__ = 'Released under the MIT License (http://opensource.org/licenses/MIT)' __author__ = 'David...
outf.write("%s,%s\n" % (k,attrk)) else: print "Invalid glyph" glyphn = raw_input("Glyph name or number: ") print "done" outf.close execute("FF",doit, argspec)
for k in dir(g): attrk=getattr(g,k) if attrk is None:
random_line_split
FFlistGlyphinfo.py
#!/usr/bin/env python 'FontForge: List all the data in a glyph object in key, value pairs' __url__ = 'http://github.com/silnrsi/pysilfont' __copyright__ = 'Copyright (c) 2015, SIL International (http://www.sil.org)' __license__ = 'Released under the MIT License (http://opensource.org/licenses/MIT)' __author__ = 'David...
if k == "ttinstrs": # ttinstr values are not printable characters outf.write("%s,%s\n" % (k,"<has values>")) else: outf.write("%s,%s\n" % (k,attrk)) # Write out all normal keys where value is none for k in dir(g): ...
isglyph=True if not(glyphn in font): try: glyphn=int(glyphn) except ValueError: isglyph=False else: if not(glyphn in font): isglyph=False if isglyph: g=font[glyphn] outf.write...
conditional_block
FFlistGlyphinfo.py
#!/usr/bin/env python 'FontForge: List all the data in a glyph object in key, value pairs' __url__ = 'http://github.com/silnrsi/pysilfont' __copyright__ = 'Copyright (c) 2015, SIL International (http://www.sil.org)' __license__ = 'Released under the MIT License (http://opensource.org/licenses/MIT)' __author__ = 'David...
(args) : font=args.font outf = args.output glyphn = raw_input("Glyph name or number: ") while glyphn: isglyph=True if not(glyphn in font): try: glyphn=int(glyphn) except ValueError: isglyph=False else: ...
doit
identifier_name
FFlistGlyphinfo.py
#!/usr/bin/env python 'FontForge: List all the data in a glyph object in key, value pairs' __url__ = 'http://github.com/silnrsi/pysilfont' __copyright__ = 'Copyright (c) 2015, SIL International (http://www.sil.org)' __license__ = 'Released under the MIT License (http://opensource.org/licenses/MIT)' __author__ = 'David...
# Write to file all normal key,value pairs - exclude __ and built in functions for k in dir(g): if k[0:2] == "__": continue attrk=getattr(g,k) if attrk is None: continue tk=type(attrk) if tk == types.BuiltinFunctionT...
font=args.font outf = args.output glyphn = raw_input("Glyph name or number: ") while glyphn: isglyph=True if not(glyphn in font): try: glyphn=int(glyphn) except ValueError: isglyph=False else: if not(glyph...
identifier_body
Level3State.js
define(['../../game', 'collectableItem', 'states/levels/LevelState'], function (game, CollectableItem, Parent) { var map, levelThreeFirstLayerBackground, levelThreeSecondLayerPlatforms, shampoosGroup, shampoosCoordinates; function Level3State() { }; Level3State.prototyp...
}; Level3State.prototype.createMap = function () { // Load level one map map = game.add.tilemap('LevelThreeMap'); map.addTilesetImage('background', 'background'); map.addTilesetImage('platforms', 'platforms'); levelThreeFirstLayerBackground = map.createLayer('LevelThre...
{ this.player.level = 4; game.state.start('level4', true, false, this.player, this.engine); }
conditional_block
Level3State.js
define(['../../game', 'collectableItem', 'states/levels/LevelState'], function (game, CollectableItem, Parent) { var map, levelThreeFirstLayerBackground, levelThreeSecondLayerPlatforms, shampoosGroup, shampoosCoordinates; function Level3State()
; Level3State.prototype = new Parent(); Level3State.prototype.constructor = Level3State; Level3State.prototype.preload = function () { this.load.tilemap('LevelThreeMap', 'levels/LevelThreeMap.json', null, Phaser.Tilemap.TILED_JSON); this.load.image('background', 'images/L3-CosmeticShop/wal...
{ }
identifier_body
Level3State.js
define(['../../game', 'collectableItem', 'states/levels/LevelState'], function (game, CollectableItem, Parent) { var map, levelThreeFirstLayerBackground, levelThreeSecondLayerPlatforms, shampoosGroup, shampoosCoordinates; function Level3State() { }; Level3State.prototyp...
() { var body = document.getElementsByTagName('body')[0], div = document.createElement('div'), span, spanText, divPrehistory, spanInDivPrehistory, spanInDivPrehistoryText, continueGameButton, continueGameButtonText, ...
showLevelPrehistory
identifier_name
Level3State.js
define(['../../game', 'collectableItem', 'states/levels/LevelState'], function (game, CollectableItem, Parent) { var map, levelThreeFirstLayerBackground, levelThreeSecondLayerPlatforms, shampoosGroup, shampoosCoordinates; function Level3State() { }; Level3State.prototyp...
this.player.placeAtMap(50, 120); Parent.prototype.initializePlayer.call(this); }; Level3State.prototype.initializeCollectableItems = function () { //Create shampoos shampoosGroup = this.add.group(); shampoosGroup.enableBody = true; shampoosCoordinates = [ ...
random_line_split
sparseMatrixPrepare.py
3 clause import numpy as np import pandas as pd import sparseAP_cy # cython for calculation ############################################################################################ # def copySym(rowBased_row_array,rowBased_col_array,rowBased_data_array,singleRowInds): """ For single col items or single...
(rowBased_row_array,rowBased_col_array,S_rowBased_data_array): """ format affinity/similarity matrix """ # Get parameters data_len=len(S_rowBased_data_array) row_indptr=sparseAP_cy.getIndptr(rowBased_row_array) if row_indptr[-1]!=data_len: row_indptr=np.concatenate((row_indptr,np.array(...
preCompute
identifier_name
sparseMatrixPrepare.py
3 clause import numpy as np import pandas as pd import sparseAP_cy # cython for calculation ############################################################################################ # def copySym(rowBased_row_array,rowBased_col_array,rowBased_data_array,singleRowInds): """ For single col items or single...
# change row, col index if there is any sample removed if len(singleSampleInds)>0: changeIndV=np.vectorize(lambda x:rowOriLeftDict[x]) rowBased_row_array=changeIndV(rowBased_row_array) rowBased_col_array=changeIndV(rowBased_col_array) #rearrange based on new row index and...
rowBased_col_array,rowBased_row_array,rowBased_data_array=copySym(rowBased_col_array.astype(np.int),rowBased_row_array.astype(np.int),rowBased_data_array,singleColInds)
conditional_block
sparseMatrixPrepare.py
3 clause import numpy as np import pandas as pd import sparseAP_cy # cython for calculation ############################################################################################ # def copySym(rowBased_row_array,rowBased_col_array,rowBased_data_array,singleRowInds): """ For single col items or single...
#Add random samll value to remove degeneracies random_state=np.random.RandomState(0) S_rowBased_data_array+=1e-12*random_state.randn(data_len)*(np.amax(S_rowBased_data_array)-np.amin(S_rowBased_data_array)) #Convert row_to_col_ind_arr/col_to
""" format affinity/similarity matrix """ # Get parameters data_len=len(S_rowBased_data_array) row_indptr=sparseAP_cy.getIndptr(rowBased_row_array) if row_indptr[-1]!=data_len: row_indptr=np.concatenate((row_indptr,np.array([data_len]))) row_to_col_ind_arr=np.lexsort((rowBased_row_array...
identifier_body
sparseMatrixPrepare.py
3 clause import numpy as np import pandas as pd import sparseAP_cy # cython for calculation ############################################################################################ # def copySym(rowBased_row_array,rowBased_col_array,rowBased_data_array,singleRowInds): """ For single col items or single...
rowBased_col_array=changeIndV(rowBased_col_array) #rearrange based on new row index and new col index, print ('{0}, sort by row,col'.format(datetime.now())) sortedLeftOriInd = np.lexsort((rowBased_col_array,rowBased_row_array)).astype(np.int) rowBased_row_array=sparseAP_cy.npArrRearrange_int_p...
random_line_split
conf.py
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # # RawSpeed documentation build configuration file, created by # sphinx-quickstart on Mon Aug 14 18:30:09 2017. # # 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 # a...
exclude_patterns = [] # The name of the Pygments (syntax highlighting) style to use. pygments_style = 'sphinx' # If true, `todo` and `todoList` produce output, else they produce nothing. todo_include_todos = False # -- Options for HTML output ---------------------------------------------- # The theme to use for HT...
random_line_split
main.rs
#[macro_use] extern crate serde_derive; extern crate serde; extern crate serde_json; use std::collections::BTreeMap as Map; #[derive(Serialize)] struct Resource { // Always serialized. name: String, // Never serialized. #[serde(skip_serializing)] hash: String, // Use a method to decide whet...
// Prints: // // [ // { // "name": "Stack Overflow" // }, // { // "name": "GitHub", // "metadata": { // "headquarters": "San Francisco" // } // } // ] println!("{}", json); }
{ let resources = vec![ Resource { name: "Stack Overflow".to_string(), hash: "b6469c3f31653d281bbbfa6f94d60fea130abe38".to_string(), metadata: Map::new(), }, Resource { name: "GitHub".to_string(), hash: "5cb7a0c47e53854cd00e1a968de5...
identifier_body
main.rs
#[macro_use] extern crate serde_derive; extern crate serde; extern crate serde_json; use std::collections::BTreeMap as Map; #[derive(Serialize)] struct Resource { // Always serialized. name: String, // Never serialized. #[serde(skip_serializing)] hash: String, // Use a method to decide whet...
}, Resource { name: "GitHub".to_string(), hash: "5cb7a0c47e53854cd00e1a968de5abce1c124601".to_string(), metadata: { let mut metadata = Map::new(); metadata.insert("headquarters".to_string(), "San Francisc...
metadata: Map::new(),
random_line_split
main.rs
#[macro_use] extern crate serde_derive; extern crate serde; extern crate serde_json; use std::collections::BTreeMap as Map; #[derive(Serialize)] struct Resource { // Always serialized. name: String, // Never serialized. #[serde(skip_serializing)] hash: String, // Use a method to decide whet...
() { let resources = vec![ Resource { name: "Stack Overflow".to_string(), hash: "b6469c3f31653d281bbbfa6f94d60fea130abe38".to_string(), metadata: Map::new(), }, Resource { name: "GitHub".to_string(), hash: "5cb7a0c47e53854cd00e1a968...
main
identifier_name
main_faketestclients.py
import yaml import time import random import threading import subprocess from rackattack.physical import pikapatch from rackattack import clientfactory from rackattack.physical import config from rackattack.api import Requirement, AllocationInfo from rackattack.physical.tests.integration.main import useFakeGeneralConfi...
def _generateAllocationInfo(self): allocationInfo = AllocationInfo(user="johabab", purpose="loadTests") return allocationInfo def allocate(self, nrHosts, pool="default"): self._updateNrAllocatedHosts() self._allocate(nrHosts, pool) def _allocateForBackground(self): ...
return requirements
random_line_split
main_faketestclients.py
import yaml import time import random import threading import subprocess from rackattack.physical import pikapatch from rackattack import clientfactory from rackattack.physical import config from rackattack.api import Requirement, AllocationInfo from rackattack.physical.tests.integration.main import useFakeGeneralConfi...
def _performRandomLoadAction(self): wantedAllocationRatio = 0.65 allocationRatio = self._nrAllocatedHosts / float(self._nrHosts) print "allocationRatio: {}, nrAllocated: {}, nrHosts: {}".format(allocationRatio, self._...
cmd = "osmosis listlabels --objectStores=%(osmosisServerIP)s:1010 star | head -n 1" % \ dict(osmosisServerIP=self._osmosisServerIP) print "Running %(cmd)s" % dict(cmd=cmd) labelName = subprocess.check_output(cmd, shell=True) labelName = labelName.strip() return labelName
identifier_body
main_faketestclients.py
import yaml import time import random import threading import subprocess from rackattack.physical import pikapatch from rackattack import clientfactory from rackattack.physical import config from rackattack.api import Requirement, AllocationInfo from rackattack.physical.tests.integration.main import useFakeGeneralConfi...
(): print """Available commands: bgstress on/off \tRuns allocations (and frees them) in the background. allocate nrHosts [pool=default] \tAllocates the given number of hosts from the given pool. free \tFrees the current allocation (which was created with the 'allocate...
main
identifier_name
main_faketestclients.py
import yaml import time import random import threading import subprocess from rackattack.physical import pikapatch from rackattack import clientfactory from rackattack.physical import config from rackattack.api import Requirement, AllocationInfo from rackattack.physical.tests.integration.main import useFakeGeneralConfi...
cmdline = cmdline.split(" ") cmdline = [item.strip() for item in cmdline] commandName = cmdline[0] args = cmdline[1:] if commandName not in commands: print "Invalid command: %(commandName)s" % dict(commandName=commandName) continue command = comma...
continue
conditional_block
mod.rs
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any lat...
mod bloom; mod bloom_group; mod group_position; pub use self::bloom::Bloom; pub use self::bloom_group::BloomGroup; pub use self::group_position::GroupPosition;
random_line_split
sendCommand.js
var receiveData = require('./receiveData'); var PROMPTREGEX = require('../lib/statics').PROMPT; var SPLITREGEX = require('../lib/statics').SPLIT; module.exports = function (stream, opt, callback) { var args = Array.prototype.slice.call(arguments); callback = args.pop(); if (typeof(callback) !== 'function') { ...
options = (typeof opt !== 'function') && opt || {}; var timeout = options.timeout || 60000; var promptRegex = options.promptRegex || PROMPTREGEX; var splitRegex = options.splitRegex || SPLITREGEX; var cmd = options.cmd || ''; var echo = options.echo || false; var error; stream.write(new Buffer(cmd + '...
random_line_split
sendCommand.js
var receiveData = require('./receiveData'); var PROMPTREGEX = require('../lib/statics').PROMPT; var SPLITREGEX = require('../lib/statics').SPLIT; module.exports = function (stream, opt, callback) { var args = Array.prototype.slice.call(arguments); callback = args.pop(); if (typeof(callback) !== 'function') { ...
//TODO convert to type? callback(null, data); }); }); };
{ data.shift(); }
conditional_block
test.js
var test = require('tape') var classes = require('./') test('css selector classes', function(t) { t.plan(9)
var c c = classes('.wat > .yo') t.notEqual(c.indexOf('wat'), -1, 'should return correct classes') t.notEqual(c.indexOf('yo'), -1, 'should return correct classes') c = classes('div > .yo body[hacks=true] .lol div, span:hover .phat') t.notEqual(c.indexOf('phat'), -1, 'should return correct classes...
t.deepEquals(classes('.wat'), ['wat'])
random_line_split
optionresolver.py
import optparse, yaml, json class OptionResolver(object): """Resolve user input options""" def __init__(self): self.parser = optparse.OptionParser()
def set_options(self): """Use optparser to manage options""" self.parser.add_option( "--manifest", "-m", help = "The location of the manifest file.", default = "./manifest.yml") self.parser.add_option( "--destina...
self.set_options()
random_line_split
optionresolver.py
import optparse, yaml, json class OptionResolver(object): """Resolve user input options""" def __init__(self): self.parser = optparse.OptionParser() self.set_options() def set_options(self): """Use optparser to manage options""" self.parser.add_option(...
(self): """Get extra parameters :rtype: dict[str, str] """ params_string = self.parse().extra_parameters if params_string: return json.loads(self.parse().extra_parameters)
extra_parameters
identifier_name
optionresolver.py
import optparse, yaml, json class OptionResolver(object): """Resolve user input options""" def __init__(self): self.parser = optparse.OptionParser() self.set_options() def set_options(self): """Use optparser to manage options""" self.parser.add_option(...
return yaml.load(yamlstring) def destination(self): """Get the assembly location :rtype: str """ return self.parse().destination def extra_parameters(self): """Get extra parameters :rtype: dict[str, str] """ ...
yamlstring = yamlstring.format(**params)
conditional_block
optionresolver.py
import optparse, yaml, json class OptionResolver(object): """Resolve user input options""" def __init__(self): self.parser = optparse.OptionParser() self.set_options() def set_options(self): """Use optparser to manage options""" self.parser.add_option(...
def destination(self): """Get the assembly location :rtype: str """ return self.parse().destination def extra_parameters(self): """Get extra parameters :rtype: dict[str, str] """ params_string = self.parse().extra_parameters ...
"""Get the parsed values from the manifest :rtype: dict[str, mixed] """ with open(self.manifest_location(), "r") as stream: yamlstring = stream.read() # Allow token replacements params = self.extra_parameters() if params: ...
identifier_body
models.py
from django.conf import settings as dj_settings from django.db import models, transaction from django.core.signals import got_request_exception from django.http import Http404 from django.utils.encoding import smart_unicode from django.utils.translation import ugettext_lazy as _ from djangodblog import settings from d...
(sender, request=None, **kwargs): try: exc_type, exc_value, traceback = sys.exc_info() if not settings.CATCH_404_ERRORS \ and issubclass(exc_type, Http404): return if dj_settings.DEBUG or getattr(exc_type, 'skip_dblog', False): ...
handle_exception
identifier_name
models.py
from django.conf import settings as dj_settings from django.db import models, transaction from django.core.signals import got_request_exception from django.http import Http404 from django.utils.encoding import smart_unicode from django.utils.translation import ugettext_lazy as _ from djangodblog import settings from d...
def save(self, *args, **kwargs): if not self.checksum: self.checksum = construct_checksum(self) super(Error, self).save(*args, **kwargs) got_request_exception.connect(ErrorBatch.handle_exception)
return "%s: %s" % (self.class_name, smart_unicode(self.message))
identifier_body
models.py
from django.conf import settings as dj_settings from django.db import models, transaction from django.core.signals import got_request_exception from django.http import Http404 from django.utils.encoding import smart_unicode from django.utils.translation import ugettext_lazy as _ from djangodblog import settings from d...
objects = ErrorBatchManager() class Meta: unique_together = (('logger', 'server_name', 'checksum'),) verbose_name_plural = _('summaries') verbose_name = _('summary') def __unicode__(self): return "(%s) %s: %s" % (self.times_seen, self.class_name, self.error()) ...
status = models.PositiveIntegerField(default=0, db_column="is_resolved", choices=STATUS_LEVELS) times_seen = models.PositiveIntegerField(default=1) last_seen = models.DateTimeField(default=datetime.datetime.now, db_index=True) first_seen = models.DateTimeField(default=datetime.d...
random_line_split