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
views.py
# Copyright 2012 United States Government as represented by the # Administrator of the National Aeronautics and Space Administration. # All Rights Reserved. # # Copyright 2012 Nebula, Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the...
# # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under ...
# http://www.apache.org/licenses/LICENSE-2.0
random_line_split
file_handle_object.py
# ***************************************************************** # Copyright (c) 2013 Massachusetts Institute of Technology # # Developed exclusively at US Government expense under US Air Force contract # FA8721-05-C-002. The rights of the United States Government to use, modify, # reproduce, release, perform, disp...
def get_file_object(self, file_name, command): """returns a file object. command shoule be either 'r' or 'w'.""" # this method exists to aid in unit testing. we do not want to actually # be accessing files during unit tests, so we will use a subclass # of this class wherein this me...
os.makedirs(dir_name)
conditional_block
file_handle_object.py
# ***************************************************************** # Copyright (c) 2013 Massachusetts Institute of Technology # # Developed exclusively at US Government expense under US Air Force contract # FA8721-05-C-002. The rights of the United States Government to use, modify, # reproduce, release, perform, disp...
(object): """A class that handles writing to the file system. We want to separate all file system modification mothods out into a separate class so that we can overwrite them for unit testing. """ def __init__(self): """no initialization necessary.""" pass def create_dir(sel...
file_handle_object
identifier_name
file_handle_object.py
# ***************************************************************** # Copyright (c) 2013 Massachusetts Institute of Technology
# # Developed exclusively at US Government expense under US Air Force contract # FA8721-05-C-002. The rights of the United States Government to use, modify, # reproduce, release, perform, display or disclose this computer software and # computer software documentation in whole or in part, in any manner and for # any pu...
random_line_split
file_handle_object.py
# ***************************************************************** # Copyright (c) 2013 Massachusetts Institute of Technology # # Developed exclusively at US Government expense under US Air Force contract # FA8721-05-C-002. The rights of the United States Government to use, modify, # reproduce, release, perform, disp...
def close_file_object(self, file_object): """closes the file object.""" # this method exists to aid in unit testing. we do not want to # be closing files during unit tests, so we will use a subclass # of this class wherein this method is overwritten. return file_object.clos...
"""returns a file object. command shoule be either 'r' or 'w'.""" # this method exists to aid in unit testing. we do not want to actually # be accessing files during unit tests, so we will use a subclass # of this class wherein this method is overwritten. return open(file_name, command)
identifier_body
__init__.py
import sys import os # import device # import plugin import pkg_resources def version(): return pkg_resources.get_distribution(aux.__package__.title()).version def base_dir(): return os.path.abspath(os.path.dirname(aux.__file__)) def
(): return os.getcwd() import aux from aux.logger import LogController from datetime import datetime import json from aux.internals import plugin_creator_routine from aux.engine import engine_factory logcontroller = None configuration = None systems_pool = [] def run(): from aux.internals.configuration impor...
working_dir
identifier_name
__init__.py
import sys import os # import device # import plugin import pkg_resources def version(): return pkg_resources.get_distribution(aux.__package__.title()).version def base_dir(): return os.path.abspath(os.path.dirname(aux.__file__)) def working_dir(): return os.getcwd() import aux from aux.logger import Lo...
## - read config file try: config.load_default_properties() except Exception, e: print 'Falling back to default settings.' print e.message ## - initiate logger logcontroller = LogController(config) ## - Setup logcontroller.summary['started'] = datetime.now...
plugin_creator_routine(config.options.plugincreator, config.args)
conditional_block
__init__.py
import sys import os # import device # import plugin import pkg_resources def version(): return pkg_resources.get_distribution(aux.__package__.title()).version def base_dir():
def working_dir(): return os.getcwd() import aux from aux.logger import LogController from datetime import datetime import json from aux.internals import plugin_creator_routine from aux.engine import engine_factory logcontroller = None configuration = None systems_pool = [] def run(): from aux.internals.co...
return os.path.abspath(os.path.dirname(aux.__file__))
identifier_body
__init__.py
import sys import os # import device # import plugin import pkg_resources def version(): return pkg_resources.get_distribution(aux.__package__.title()).version def base_dir(): return os.path.abspath(os.path.dirname(aux.__file__)) def working_dir(): return os.getcwd() import aux from aux.logger import Lo...
# __all__ = ['device', # 'plugin', # 'run'] __all__ = ['run'] def exit_hook(): if logcontroller is not None: logcontroller.pprint_summary_on_exit() sys.exitfunc = exit_hook
random_line_split
TotalThroughputVsIterations.py
import CommonConf import CommonViz import re from collections import OrderedDict import numpy as np import random import sys import matplotlib.pyplot as pp import pylab EXPERIMENT_NAME = "TotalThroughputVsIterations" X_LABEL = "TM" Y_LABEL = "Throughput (fraction of total demand)" random.seed() def ...
main("expData/"+sys.argv[1], EXPERIMENT_NAME, set(sys.argv[2:]))
conditional_block
TotalThroughputVsIterations.py
import CommonConf import CommonViz import re from collections import OrderedDict import numpy as np import random import sys import matplotlib.pyplot as pp import pylab EXPERIMENT_NAME = "TotalThroughputVsIterations" X_LABEL = "TM" Y_LABEL = "Throughput (fraction of total demand)" random.seed() def ...
color=colors[solver], label=CommonConf.gen_label(solver), linewidth=linewidth[solver], linestyle=fmts[solver], marker=mrkrs[solver], markersize=mrkrsize[solver]) ax.set_xlabel(X_LABEL); ax.set_ylabel(Y_LABEL); ax.legend(loc=0, borderaxespad=...
(xs, ysPerSolver, ydevsPerSolver) = CommonViz.parseData(dirn, fname, solvers) CommonConf.setupMPPDefaults() colors = CommonConf.getLineColorsDict() fmts = CommonConf.getLineFormatsDict() linewidth = CommonConf.getLineMarkersLWDict() mrkrs = CommonConf.getLineMarkersDict() mrkrsize = CommonConf.getLineMarke...
identifier_body
TotalThroughputVsIterations.py
import CommonConf import CommonViz import re from collections import OrderedDict import numpy as np import random import sys import matplotlib.pyplot as pp import pylab EXPERIMENT_NAME = "TotalThroughputVsIterations" X_LABEL = "TM" Y_LABEL = "Throughput (fraction of total demand)" random.seed() def
(dirn, fname, solvers): (xs, ysPerSolver, ydevsPerSolver) = CommonViz.parseData(dirn, fname, solvers) CommonConf.setupMPPDefaults() colors = CommonConf.getLineColorsDict() fmts = CommonConf.getLineFormatsDict() linewidth = CommonConf.getLineMarkersLWDict() mrkrs = CommonConf.getLineMarkersDict() mrkrsize...
main
identifier_name
TotalThroughputVsIterations.py
import CommonConf import CommonViz
import random import sys import matplotlib.pyplot as pp import pylab EXPERIMENT_NAME = "TotalThroughputVsIterations" X_LABEL = "TM" Y_LABEL = "Throughput (fraction of total demand)" random.seed() def main(dirn, fname, solvers): (xs, ysPerSolver, ydevsPerSolver) = CommonViz.parseData(dirn, fname, so...
import re from collections import OrderedDict import numpy as np
random_line_split
zoho.py
# Copyright (c) 2011-2015 Berkeley Model United Nations. All rights reserved. # Use of this source code is governed by a BSD License (see LICENSE). import json import requests from django.conf import settings def get_contact(school): if not settings.ZOHO_CREDENTIALS:
list_url = 'https://invoice.zoho.com/api/v3/contacts?organization_id=' + settings.ORGANIZATION_ID + '&authtoken=' + settings.AUTHTOKEN contact = { "company_name_contains": school.name } return requests.get(list_url, params=contact).json()["contacts"][0]["contact_id"] def generate_contact_attri...
return
conditional_block
zoho.py
# Copyright (c) 2011-2015 Berkeley Model United Nations. All rights reserved. # Use of this source code is governed by a BSD License (see LICENSE). import json import requests from django.conf import settings def get_contact(school): if not settings.ZOHO_CREDENTIALS:
return requests.get(list_url, params=contact).json()["contacts"][0]["contact_id"] def generate_contact_attributes(school): return { "contact_name": school.primary_name, "company_name": school.name, "payment_terms": "", "payment_terms_label": "Due on Receipt", "currency_i...
return list_url = 'https://invoice.zoho.com/api/v3/contacts?organization_id=' + settings.ORGANIZATION_ID + '&authtoken=' + settings.AUTHTOKEN contact = { "company_name_contains": school.name }
random_line_split
zoho.py
# Copyright (c) 2011-2015 Berkeley Model United Nations. All rights reserved. # Use of this source code is governed by a BSD License (see LICENSE). import json import requests from django.conf import settings def get_contact(school): if not settings.ZOHO_CREDENTIALS: return list_url = 'https://invoic...
(school): return { "contact_name": school.primary_name, "company_name": school.name, "payment_terms": "", "payment_terms_label": "Due on Receipt", "currency_id": "", "website": "", "custom_fields": [ ], "billing_address": { "address": "...
generate_contact_attributes
identifier_name
zoho.py
# Copyright (c) 2011-2015 Berkeley Model United Nations. All rights reserved. # Use of this source code is governed by a BSD License (see LICENSE). import json import requests from django.conf import settings def get_contact(school):
def generate_contact_attributes(school): return { "contact_name": school.primary_name, "company_name": school.name, "payment_terms": "", "payment_terms_label": "Due on Receipt", "currency_id": "", "website": "", "custom_fields": [ ], "billing...
if not settings.ZOHO_CREDENTIALS: return list_url = 'https://invoice.zoho.com/api/v3/contacts?organization_id=' + settings.ORGANIZATION_ID + '&authtoken=' + settings.AUTHTOKEN contact = { "company_name_contains": school.name } return requests.get(list_url, params=contact).json()["contact...
identifier_body
add_vcf_to_project.py
import os from xbrowse_server import xbrowse_controls from django.core.management.base import BaseCommand from xbrowse_server.base.models import Project, Individual, VCFFile from xbrowse_server import sample_management class Command(BaseCommand): def add_arguments(self, parser):
def handle(self, *args, **options): project_id = args[0] project = Project.objects.get(project_id=project_id) vcf_file_path = os.path.abspath(args[1]) vcf_file = VCFFile.objects.get_or_create(file_path=vcf_file_path)[0] if options.get('clear'): for individual...
parser.add_argument('args', nargs='*') parser.add_argument('--indiv-id') parser.add_argument('--cohort-id') parser.add_argument('--clear', action="store_true", help="Whether to clear any previously-added VCF paths before adding this one") parser.add_argument('--load', action="store_true...
identifier_body
add_vcf_to_project.py
import os from xbrowse_server import xbrowse_controls from django.core.management.base import BaseCommand from xbrowse_server.base.models import Project, Individual, VCFFile from xbrowse_server import sample_management class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('ar...
else: sample_management.add_vcf_file_to_project(project, vcf_file) if options.get('load'): print("Loading VCF into project store") xbrowse_controls.load_project(project_id, vcf_files=[vcf_file_path]) print("Loading VCF datastore") xbrowse_cont...
indiv_id=options.get('indiv_id') ) sample_management.add_vcf_file_to_individual(individual, vcf_file)
random_line_split
add_vcf_to_project.py
import os from xbrowse_server import xbrowse_controls from django.core.management.base import BaseCommand from xbrowse_server.base.models import Project, Individual, VCFFile from xbrowse_server import sample_management class
(BaseCommand): def add_arguments(self, parser): parser.add_argument('args', nargs='*') parser.add_argument('--indiv-id') parser.add_argument('--cohort-id') parser.add_argument('--clear', action="store_true", help="Whether to clear any previously-added VCF paths before adding this o...
Command
identifier_name
add_vcf_to_project.py
import os from xbrowse_server import xbrowse_controls from django.core.management.base import BaseCommand from xbrowse_server.base.models import Project, Individual, VCFFile from xbrowse_server import sample_management class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('ar...
else: sample_management.add_vcf_file_to_project(project, vcf_file) if options.get('load'): print("Loading VCF into project store") xbrowse_controls.load_project(project_id, vcf_files=[vcf_file_path]) print("Loading VCF datastore") xbrowse_co...
individual = Individual.objects.get( project=project, indiv_id=options.get('indiv_id') ) sample_management.add_vcf_file_to_individual(individual, vcf_file)
conditional_block
server.rs
use container::{Container, ControlDispatcher}; use config::Config; use lssa::control::Control; use lssa::manager::AppManager; use futures; use futures::Future; use futures::Stream; use futures::Sink; //use futures::{StreamExt, FutureExt}; pub struct Server { container: Container } impl Server { pub fn new(co...
(container: Container) -> futures::sync::mpsc::Sender<Control> { let (tx, rx) = futures::sync::mpsc::channel(4096); ::std::thread::spawn(move || { ::tokio::executor::current_thread::block_on_all( futures::future::ok(()).map(move |_| { let mut manager = App...
launch_manager
identifier_name
server.rs
use container::{Container, ControlDispatcher}; use config::Config; use lssa::control::Control; use lssa::manager::AppManager; use futures; use futures::Future; use futures::Stream; use futures::Sink; //use futures::{StreamExt, FutureExt}; pub struct Server { container: Container } impl Server { pub fn new(co...
tx } pub fn run_apps(&self) -> impl Future<Item = (), Error = ()> { let (tx, rx) = futures::sync::mpsc::channel::<Control>(4096); self.container.set_control_dispatcher(ControlDispatcher::new(tx)); let container = self.container.clone(); let mut control_sender = Self::la...
random_line_split
server.rs
use container::{Container, ControlDispatcher}; use config::Config; use lssa::control::Control; use lssa::manager::AppManager; use futures; use futures::Future; use futures::Stream; use futures::Sink; //use futures::{StreamExt, FutureExt}; pub struct Server { container: Container } impl Server { pub fn new(co...
fn launch_manager(container: Container) -> futures::sync::mpsc::Sender<Control> { let (tx, rx) = futures::sync::mpsc::channel(4096); ::std::thread::spawn(move || { ::tokio::executor::current_thread::block_on_all( futures::future::ok(()).map(move |_| { ...
{ Server { container: Container::new(config) } }
identifier_body
region_GG.py
"""Auto-generated file, do not edit by hand. GG metadata"""
fixed_line=PhoneNumberDesc(national_number_pattern='1481[25-9]\\d{5}', example_number='1481256789', possible_length=(10,), possible_length_local_only=(6,)), mobile=PhoneNumberDesc(national_number_pattern='7(?:781\\d|839\\d|911[17])\\d{5}', example_number='7781123456', possible_length=(10,)), toll_free=Phone...
from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata PHONE_METADATA_GG = PhoneMetadata(id='GG', country_code=44, international_prefix='00', general_desc=PhoneNumberDesc(national_number_pattern='[135789]\\d{6,9}', possible_length=(7, 9, 10), possible_length_local_only=(6,)),
random_line_split
__init__.py
########################################################################## # # Copyright (c) 2013, Image Engine Design Inc. All rights reserved. # Copyright (c) 2013, John Haddon. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that ...
__import__( "GafferScene" ) def __setupEnvironment() : import os def prependToPath( envVar, prefix ) : e = os.environ.get( envVar, "" ) if e : e = ":" + e e = prefix + e os.environ[envVar] = os.path.expandvars( e ) prependToPath( "DL_DISPLAYS_PATH", "$GAFFER_ROOT/renderMan/displayDrivers" ) prepend...
# ##########################################################################
random_line_split
__init__.py
########################################################################## # # Copyright (c) 2013, Image Engine Design Inc. All rights reserved. # Copyright (c) 2013, John Haddon. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that ...
e = prefix + e os.environ[envVar] = os.path.expandvars( e ) prependToPath( "DL_DISPLAYS_PATH", "$GAFFER_ROOT/renderMan/displayDrivers" ) prependToPath( "DL_PROCEDURALS_PATH", "$GAFFER_ROOT/renderMan/procedurals" ) __setupEnvironment() from _GafferRenderMan import * from RenderManRender import RenderManRender...
e = ":" + e
conditional_block
__init__.py
########################################################################## # # Copyright (c) 2013, Image Engine Design Inc. All rights reserved. # Copyright (c) 2013, John Haddon. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that ...
prependToPath( "DL_DISPLAYS_PATH", "$GAFFER_ROOT/renderMan/displayDrivers" ) prependToPath( "DL_PROCEDURALS_PATH", "$GAFFER_ROOT/renderMan/procedurals" ) __setupEnvironment() from _GafferRenderMan import * from RenderManRender import RenderManRender from RenderManShaderBall import RenderManShaderBall __import__...
e = os.environ.get( envVar, "" ) if e : e = ":" + e e = prefix + e os.environ[envVar] = os.path.expandvars( e )
identifier_body
__init__.py
########################################################################## # # Copyright (c) 2013, Image Engine Design Inc. All rights reserved. # Copyright (c) 2013, John Haddon. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that ...
() : import os def prependToPath( envVar, prefix ) : e = os.environ.get( envVar, "" ) if e : e = ":" + e e = prefix + e os.environ[envVar] = os.path.expandvars( e ) prependToPath( "DL_DISPLAYS_PATH", "$GAFFER_ROOT/renderMan/displayDrivers" ) prependToPath( "DL_PROCEDURALS_PATH", "$GAFFER_ROOT/renderM...
__setupEnvironment
identifier_name
bn.ts
Array } from './compat.js'; /** @ignore */ export const isArrowBigNumSymbol = Symbol.for('isArrowBigNum'); /** @ignore */ type BigNumArray = IntArray | UintArray; /** @ignore */ type IntArray = Int8Array | Int16Array | Int32Array; /** @ignore */ type UintArray = Uint8Array | Uint16Array | Uint32Array | Uint8ClampedAr...
/** @nocollapse */ public static signed<T extends IntArray>(num: T): (T & BN<T>) { return new (<any>SignedBigNum)(num) as (T & BN<T>); } /** @nocollapse */ public static unsigned<T extends UintArray>(num: T): (T & BN<T>) { return new (<any>UnsignedBigNum)(num) as (T & BN<T>); } ...
{ switch (isSigned) { case true: return new (<any>SignedBigNum)(num) as (T & BN<T>); case false: return new (<any>UnsignedBigNum)(num) as (T & BN<T>); } switch (num.constructor) { case Int8Array: case Int16Array: case Int32Array: ...
identifier_body
bn.ts
4Array } from './compat.js'; /** @ignore */ export const isArrowBigNumSymbol = Symbol.for('isArrowBigNum'); /** @ignore */ type BigNumArray = IntArray | UintArray; /** @ignore */ type IntArray = Int8Array | Int16Array | Int32Array; /** @ignore */ type UintArray = Uint8Array | Uint16Array | Uint32Array | Uint8ClampedA...
<T extends UintArray>(num: T): (T & BN<T>) { return new (<any>UnsignedBigNum)(num) as (T & BN<T>); } /** @nocollapse */ public static decimal<T extends UintArray>(num: T): (T & BN<T>) { return new (<any>DecimalBigNum)(num) as (T & BN<T>); } constructor(num: T, isSigned?: boolean) { ...
unsigned
identifier_name
bn.ts
switch (hint) { case 'number': return bignumToNumber(this); case 'string': return bignumToString(this); case 'default': return bignumToBigInt(this); } // @ts-ignore return bignumToString(this); }; /** @ignore */ type TypedArrayConstructorArgs = [number | void] | [Iterable<n...
map(callbackfn: (value: number, index: number, array: T) => number, thisArg?: any): T; reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: T) => number): number; reduce(callbackfn: (previousValue: number, currentValue: number, currentIndex: number, array: T) => numb...
random_line_split
EstimationOfPi.py
import random import math def
(error): itt=1000 #itterations previousPI=0 while True: hits=0 # number of hits for i in range(0,itt): x=random.uniform(0,1) y=random.uniform(0,1) z=x*x+y*y #Pythagorean Theorum if math.sqrt(z)<=1: #if point(x,y)lies within the triangle hits=hits+1 currentPI=(hits*4)/itt #print(currentPI) i...
estimatePi
identifier_name
EstimationOfPi.py
import random import math def estimatePi(error): itt=1000 #itterations previousPI=0 while True:
for i in range(0,itt): x=random.uniform(0,1) y=random.uniform(0,1) z=x*x+y*y #Pythagorean Theorum if math.sqrt(z)<=1: #if point(x,y)lies within the triangle hits=hits+1 currentPI=(hits*4)/itt #print(currentPI) if previousPI==0: previousPI=currentPI continue if (math.fabs(previousPI-curre...
hits=0 # number of hits
random_line_split
EstimationOfPi.py
import random import math def estimatePi(error):
error=float(input("Enter the error value :")) pi = estimatePi(error) print("Pi : ",pi)
itt=1000 #itterations previousPI=0 while True: hits=0 # number of hits for i in range(0,itt): x=random.uniform(0,1) y=random.uniform(0,1) z=x*x+y*y #Pythagorean Theorum if math.sqrt(z)<=1: #if point(x,y)lies within the triangle hits=hits+1 currentPI=(hits*4)/itt #print(currentPI) if previous...
identifier_body
EstimationOfPi.py
import random import math def estimatePi(error): itt=1000 #itterations previousPI=0 while True: hits=0 # number of hits for i in range(0,itt): x=random.uniform(0,1) y=random.uniform(0,1) z=x*x+y*y #Pythagorean Theorum if math.sqrt(z)<=1: #if point(x,y)lies within the triangle hits=hits+1 curren...
previousPI=(currentPI+previousPI)/2 #previousPI=currentPI error=float(input("Enter the error value :")) pi = estimatePi(error) print("Pi : ",pi)
return currentPI#return The estimation of pi is 4*hits/shots
conditional_block
surface_state.rs
//! TODO Documentation use std::marker::PhantomData; use crate::libc::c_int; use wlroots_sys::{wl_output_transform, wl_resource, wlr_surface_state}; use crate::{render::PixmanRegion, surface::Surface}; #[derive(Debug)] #[repr(u32)] /// Represents a change in the pending state. /// /// When a particular bit is set, ...
State { state, phantom: PhantomData } } /// Gets the state of the sub surface. /// /// # Panics /// If the invalid state is in an undefined state, this will panic. pub fn committed(&self) -> InvalidState { use self::InvalidState::*; unsafe...
/// # Safety /// Since we rely on the surface providing a valid surface state, /// this function is marked unsafe. pub(crate) unsafe fn new(state: wlr_surface_state) -> State<'surface> {
random_line_split
surface_state.rs
//! TODO Documentation use std::marker::PhantomData; use crate::libc::c_int; use wlroots_sys::{wl_output_transform, wl_resource, wlr_surface_state}; use crate::{render::PixmanRegion, surface::Surface}; #[derive(Debug)] #[repr(u32)] /// Represents a change in the pending state. /// /// When a particular bit is set, ...
} } } /// Get the position of the surface relative to the previous position. /// /// Return value is in (dx, dy) format. pub fn position(&self) -> (i32, i32) { unsafe { (self.state.dx, self.state.dy) } } /// Get the size of the sub surface. /// /// Retu...
{ wlr_log!(WLR_ERROR, "Invalid invalid state {}", invalid); panic!("Invalid invalid state in wlr_surface_state") }
conditional_block
surface_state.rs
//! TODO Documentation use std::marker::PhantomData; use crate::libc::c_int; use wlroots_sys::{wl_output_transform, wl_resource, wlr_surface_state}; use crate::{render::PixmanRegion, surface::Surface}; #[derive(Debug)] #[repr(u32)] /// Represents a change in the pending state. /// /// When a particular bit is set, ...
(&self) -> i32 { unsafe { self.state.scale } } /// Get the output transform applied to the surface. pub fn transform(&self) -> wl_output_transform { unsafe { self.state.transform } } /// Gets the buffer of the surface. pub unsafe fn buffer(&self) -> *mut wl_resource { s...
scale
identifier_name
build.rs
use std::env; use std::process::Command; use std::str::{self, FromStr}; // The rustc-cfg strings below are *not* public API. Please let us know by // opening a GitHub issue if your build environment requires some way to enable // these cfgs other than by executing our build script. fn main() { let minor = match ru...
}; let version = match str::from_utf8(&output.stdout) { Ok(version) => version, Err(_) => return None, }; let mut pieces = version.split('.'); if pieces.next() != Some("rustc 1") { return None; } let next = match pieces.next() { Some(next) => next, ...
random_line_split
build.rs
use std::env; use std::process::Command; use std::str::{self, FromStr}; // The rustc-cfg strings below are *not* public API. Please let us know by // opening a GitHub issue if your build environment requires some way to enable // these cfgs other than by executing our build script. fn
() { let minor = match rustc_minor_version() { Some(minor) => minor, None => return, }; let target = env::var("TARGET").unwrap(); let emscripten = target == "asmjs-unknown-emscripten" || target == "wasm32-unknown-emscripten"; // CString::into_boxed_c_str stabilized in Rust 1.20: ...
main
identifier_name
build.rs
use std::env; use std::process::Command; use std::str::{self, FromStr}; // The rustc-cfg strings below are *not* public API. Please let us know by // opening a GitHub issue if your build environment requires some way to enable // these cfgs other than by executing our build script. fn main()
} // Duration available in core since Rust 1.25: // https://blog.rust-lang.org/2018/03/29/Rust-1.25.html#library-stabilizations if minor >= 25 { println!("cargo:rustc-cfg=core_duration"); } // 128-bit integers stabilized in Rust 1.26: // https://blog.rust-lang.org/2018/05/10/Rust-1...
{ let minor = match rustc_minor_version() { Some(minor) => minor, None => return, }; let target = env::var("TARGET").unwrap(); let emscripten = target == "asmjs-unknown-emscripten" || target == "wasm32-unknown-emscripten"; // CString::into_boxed_c_str stabilized in Rust 1.20: /...
identifier_body
history.py
#!/usr/bin/env python # -- Content-Encoding: UTF-8 -- """ Gathers components according to their history. This algorithm is a test: it can be a memory hog :author: Thomas Calmant :license: Apache Software License 2.0 :version: 3.0.0 .. Copyright 2014 isandlaTech Licensed under the Apache License, Version 2.0...
self._crashes.add(tuple(sorted(components))) _logger.info("%d crash(es) in history:\n%s", len(self._crashes), '\n'.join('- ' + ', '.join(crash) for crash in self._crashes)) def vote(self, candidates, subject, ballot): """ Votes fo...
for old_crash in to_remove: self._crashes.remove(old_crash) # Store the isolate composition at the time of crash
random_line_split
history.py
#!/usr/bin/env python # -- Content-Encoding: UTF-8 -- """ Gathers components according to their history. This algorithm is a test: it can be a memory hog :author: Thomas Calmant :license: Apache Software License 2.0 :version: 3.0.0 .. Copyright 2014 isandlaTech Licensed under the Apache License, Version 2.0...
(self): """ Sets up members """ # A set of tuples: each tuple contains the components which were in an # isolate that crashed self._crashes = set() # Injected self._status = None def __str__(self): """ String representation ""...
__init__
identifier_name
history.py
#!/usr/bin/env python # -- Content-Encoding: UTF-8 -- """ Gathers components according to their history. This algorithm is a test: it can be a memory hog :author: Thomas Calmant :license: Apache Software License 2.0 :version: 3.0.0 .. Copyright 2014 isandlaTech Licensed under the Apache License, Version 2.0...
else: if component_name in components: # Found the isolate where the isolate already is components.remove(component_name) # Store information all_components[candidate] = components # Sort candidates by number ...
neutral_candidate = candidate
conditional_block
history.py
#!/usr/bin/env python # -- Content-Encoding: UTF-8 -- """ Gathers components according to their history. This algorithm is a test: it can be a memory hog :author: Thomas Calmant :license: Apache Software License 2.0 :version: 3.0.0 .. Copyright 2014 isandlaTech Licensed under the Apache License, Version 2.0...
@Validate def validate(self, context): """ Component validated """ # TODO: load previous crashes from a file/db... self._crashes.clear() @Invalidate def invalidate(self, context): """ Component invalidated """ # TODO: store crash...
""" String representation """ return "Components gathering based on history"
identifier_body
msg_pong.rs
use std; use ::serialize::{self, Serializable}; use super::PingMessage; use super::BIP0031_VERSION; #[derive(Debug,Default,Clone)] pub struct PongMessage { pub nonce: u64, } impl PongMessage { pub fn new(ping:&PingMessage) -> PongMessage { PongMessage{ nonce: ping.nonce } } } impl super::Message for Po...
fn deserialize(&mut self, io:&mut std::io::Read, ser:&serialize::SerializeParam) -> serialize::Result { if BIP0031_VERSION < ser.version { self.nonce.deserialize(io, ser) } else { Ok(0usize) } } }
{ if BIP0031_VERSION < ser.version { self.nonce.serialize(io, ser) } else { Ok(0usize) } }
identifier_body
msg_pong.rs
use std; use ::serialize::{self, Serializable}; use super::PingMessage; use super::BIP0031_VERSION; #[derive(Debug,Default,Clone)] pub struct
{ pub nonce: u64, } impl PongMessage { pub fn new(ping:&PingMessage) -> PongMessage { PongMessage{ nonce: ping.nonce } } } impl super::Message for PongMessage { fn get_command(&self) -> [u8; super::message_header::COMMAND_SIZE] { super::message_header::COMMAND_PONG } } impl std::fmt::Displa...
PongMessage
identifier_name
msg_pong.rs
use std; use ::serialize::{self, Serializable}; use super::PingMessage; use super::BIP0031_VERSION; #[derive(Debug,Default,Clone)] pub struct PongMessage { pub nonce: u64, } impl PongMessage { pub fn new(ping:&PingMessage) -> PongMessage { PongMessage{ nonce: ping.nonce } } } impl super::Message for Po...
else { Ok(0usize) } } }
{ self.nonce.deserialize(io, ser) }
conditional_block
msg_pong.rs
use std; use ::serialize::{self, Serializable}; use super::PingMessage; use super::BIP0031_VERSION; #[derive(Debug,Default,Clone)] pub struct PongMessage { pub nonce: u64, } impl PongMessage { pub fn new(ping:&PingMessage) -> PongMessage { PongMessage{ nonce: ping.nonce } } } impl super::Message for Po...
if BIP0031_VERSION < ser.version { self.nonce.get_serialize_size(ser) } else { 0usize } } fn serialize(&self, io:&mut std::io::Write, ser:&serialize::SerializeParam) -> serialize::Result { if BIP0031_VERSION < ser.version { self.nonce.serialize(io, ser) } e...
impl Serializable for PongMessage { fn get_serialize_size(&self, ser:&serialize::SerializeParam) -> usize {
random_line_split
iam_roles.py
from stacker.blueprints.base import Blueprint from troposphere import ( GetAtt, Output, Ref, Sub, iam, ) from awacs.aws import Policy from awacs.helpers.trust import ( get_default_assumerole_policy, get_lambda_assumerole_policy ) class Roles(Blueprint): VARIABLES = { "Ec2Role...
(self, name, assumerole_policy): t = self.template role = t.add_resource( iam.Role( name, AssumeRolePolicyDocument=assumerole_policy, ) ) t.add_output( Output(name + "RoleName", Value=Ref(role)) ) t.add...
create_role
identifier_name
iam_roles.py
from stacker.blueprints.base import Blueprint from troposphere import ( GetAtt, Output, Ref, Sub, iam, ) from awacs.aws import Policy from awacs.helpers.trust import ( get_default_assumerole_policy, get_lambda_assumerole_policy
) class Roles(Blueprint): VARIABLES = { "Ec2Roles": { "type": list, "description": "names of ec2 roles to create", "default": [], }, "LambdaRoles": { "type": list, "description": "names of lambda roles to create", "def...
random_line_split
iam_roles.py
from stacker.blueprints.base import Blueprint from troposphere import ( GetAtt, Output, Ref, Sub, iam, ) from awacs.aws import Policy from awacs.helpers.trust import ( get_default_assumerole_policy, get_lambda_assumerole_policy ) class Roles(Blueprint): VARIABLES = { "Ec2Role...
def create_role(self, name, assumerole_policy): t = self.template role = t.add_resource( iam.Role( name, AssumeRolePolicyDocument=assumerole_policy, ) ) t.add_output( Output(name + "RoleName", Value=Ref(role)) ...
super(Roles, self).__init__(*args, **kwargs) self.roles = [] self.policies = []
identifier_body
iam_roles.py
from stacker.blueprints.base import Blueprint from troposphere import ( GetAtt, Output, Ref, Sub, iam, ) from awacs.aws import Policy from awacs.helpers.trust import ( get_default_assumerole_policy, get_lambda_assumerole_policy ) class Roles(Blueprint): VARIABLES = { "Ec2Role...
for role in variables['LambdaRoles']: self.create_lambda_role(role) self.create_policy()
self.create_ec2_role(role)
conditional_block
benchmarks.rs
extern crate ostrov; extern crate test; use ostrov::runtime::Runtime; use test::Bencher; static NESTED_IFS: &'static str = " (if (if (if (if (if (if (> 1 2 3 4 5 6 7 8 9 10) (= ...
#f ) (= 2 2 2 2 2 2 2 2 2 2) #f ) (= 2 2 2 2 2 2 2 2 2 2) #f ) (= 2 2 2 2 2 2 2 2 2 2) #f ) 2 3 ) "; #[bench] fn nested_eva...
#f ) (= 2 2 2 2 2 2 2 2 2 2)
random_line_split
benchmarks.rs
extern crate ostrov; extern crate test; use ostrov::runtime::Runtime; use test::Bencher; static NESTED_IFS: &'static str = " (if (if (if (if (if (if (> 1 2 3 4 5 6 7 8 9 10) (= ...
(b: &mut Bencher) { let mut runtime = Runtime::new(); b.iter(|| { assert_eq!(runtime.eval_str(NESTED_IFS), runtime.eval_str("3")); }) } #[bench] fn nested_evaluation_bytecode(b: &mut Bencher) { let mut runtime = Runtime::new(); b.iter(|| { assert_eq!(runtime.eval_str(NESTED_IFS), ...
nested_evaluation
identifier_name
benchmarks.rs
extern crate ostrov; extern crate test; use ostrov::runtime::Runtime; use test::Bencher; static NESTED_IFS: &'static str = " (if (if (if (if (if (if (> 1 2 3 4 5 6 7 8 9 10) (= ...
#[bench] fn nested_evaluation_bytecode(b: &mut Bencher) { let mut runtime = Runtime::new(); b.iter(|| { assert_eq!(runtime.eval_str(NESTED_IFS), runtime.eval_str("3")); }) } #[bench] fn procedure_evaluation(b: &mut Bencher) { let input = " (define (fact n) (if (= n 1) ...
{ let mut runtime = Runtime::new(); b.iter(|| { assert_eq!(runtime.eval_str(NESTED_IFS), runtime.eval_str("3")); }) }
identifier_body
recent.js
/** * Created by raj on 19/8/14. */ var fs = require('fs'); var content = fs.read ('animeEpisode.json'); console.log(JSON.stringify(JSON.parse(content)[1][0].title)); videolinks=JSON.parse(content); links=[]; function pages(k)
console.log(data); if (m < links[k].length - 1) { page.close(); console.log('next episoide called'); pages(k, m + 1); } ; if (m == links[k].length -...
{ var page = new WebPage(); page.open('http://www.gogoanime.com/', function (status) { console.log('opened gogoanime :++++ ', status); if (status==fail){ page.close(); pages(k); } if (status == success) { pa...
identifier_body
recent.js
/** * Created by raj on 19/8/14. */ var fs = require('fs'); var content = fs.read ('animeEpisode.json'); console.log(JSON.stringify(JSON.parse(content)[1][0].title)); videolinks=JSON.parse(content); links=[]; function pages(k) { var page = new WebPage(); page.open('http://www.gogoanime.com/', functi...
}); } }); } pages(1,1);
}
random_line_split
recent.js
/** * Created by raj on 19/8/14. */ var fs = require('fs'); var content = fs.read ('animeEpisode.json'); console.log(JSON.stringify(JSON.parse(content)[1][0].title)); videolinks=JSON.parse(content); links=[]; function pages(k) { var page = new WebPage(); page.open('http://www.gogoanime.com/', functi...
if (status == success) { page.includeJs('http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js', function () { console.log('jq included') var data = page.evaluate(function (data) { var tempdata=[]; ...
{ page.close(); pages(k); }
conditional_block
recent.js
/** * Created by raj on 19/8/14. */ var fs = require('fs'); var content = fs.read ('animeEpisode.json'); console.log(JSON.stringify(JSON.parse(content)[1][0].title)); videolinks=JSON.parse(content); links=[]; function
(k) { var page = new WebPage(); page.open('http://www.gogoanime.com/', function (status) { console.log('opened gogoanime :++++ ', status); if (status==fail){ page.close(); pages(k); } if (status == success) { ...
pages
identifier_name
test_course_summaries.py
import ddt from analyticsclient.tests import ( APIListTestCase, APIWithPostableIDsTestCase, ClientTestCase ) @ddt.ddt class CourseSummariesTests(APIListTestCase, APIWithPostableIDsTestCase, ClientTestCase):
_ALL_PARAMS = _LIST_PARAMS | _STRING_PARAMS | _INT_PARAMS other_params = _ALL_PARAMS # Test URL encoding (note: '+' is not handled right by httpretty, but it works in practice) _TEST_STRING = 'Aa1_-:/* ' @ddt.data( (_LIST_PARAMS, ['a', 'b', 'c']), (_LIST_PARAMS, [_TEST_STRING]), ...
endpoint = 'course_summaries' id_field = 'course_ids' _LIST_PARAMS = frozenset([ 'course_ids', 'availability', 'pacing_type', 'program_ids', 'fields', 'exclude', ]) _STRING_PARAMS = frozenset([ 'text_search', 'order_by', 'sort_orde...
identifier_body
test_course_summaries.py
import ddt from analyticsclient.tests import ( APIListTestCase, APIWithPostableIDsTestCase, ClientTestCase ) @ddt.ddt class
(APIListTestCase, APIWithPostableIDsTestCase, ClientTestCase): endpoint = 'course_summaries' id_field = 'course_ids' _LIST_PARAMS = frozenset([ 'course_ids', 'availability', 'pacing_type', 'program_ids', 'fields', 'exclude', ]) _STRING_PARAMS = froze...
CourseSummariesTests
identifier_name
test_course_summaries.py
import ddt from analyticsclient.tests import ( APIListTestCase, APIWithPostableIDsTestCase, ClientTestCase ) @ddt.ddt class CourseSummariesTests(APIListTestCase, APIWithPostableIDsTestCase, ClientTestCase): endpoint = 'course_summaries' id_field = 'course_ids' _LIST_PARAMS = frozenset([ ...
'order_by', 'sort_order', ]) _INT_PARAMS = frozenset([ 'page', 'page_size', ]) _ALL_PARAMS = _LIST_PARAMS | _STRING_PARAMS | _INT_PARAMS other_params = _ALL_PARAMS # Test URL encoding (note: '+' is not handled right by httpretty, but it works in practice) _TE...
'exclude', ]) _STRING_PARAMS = frozenset([ 'text_search',
random_line_split
string_list.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use libc::{c_int}; use std::mem; use string::{cef_string_userfree_utf16_alloc,cef_string_userfree_utf16_free,cef_s...
let v: Box<Vec<*mut cef_string_t>> = mem::transmute(lt); cef_string_list_clear(lt); drop(v); } } #[no_mangle] pub extern "C" fn cef_string_list_copy(lt: *mut cef_string_list_t) -> *mut cef_string_list_t { unsafe { if lt.is_null() { return 0 as *mut cef_string_list_t; } ...
{ return; }
conditional_block
string_list.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use libc::{c_int}; use std::mem; use string::{cef_string_userfree_utf16_alloc,cef_string_userfree_utf16_free,cef_s...
unsafe { if lt.is_null() { return; } let v = string_list_to_vec(lt); if (*v).len() == 0 { return; } let mut cs; while (*v).len() != 0 { cs = (*v).pop(); cef_string_userfree_utf16_free(cs.unwrap()); } } } #[no_mangle] pub extern "C" fn cef_...
random_line_split
string_list.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use libc::{c_int}; use std::mem; use string::{cef_string_userfree_utf16_alloc,cef_string_userfree_utf16_free,cef_s...
(lt: *mut cef_string_list_t, value: *const cef_string_t) { unsafe { if lt.is_null() { return; } let v = string_list_to_vec(lt); let cs = cef_string_userfree_utf16_alloc(); cef_string_utf16_set(mem::transmute((*value).str), (*value).length, cs, 1); (*v).push(cs); } } #[no...
cef_string_list_append
identifier_name
string_list.rs
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ use libc::{c_int}; use std::mem; use string::{cef_string_userfree_utf16_alloc,cef_string_userfree_utf16_free,cef_s...
#[no_mangle] pub extern "C" fn cef_string_list_free(lt: *mut cef_string_list_t) { unsafe { if lt.is_null() { return; } let v: Box<Vec<*mut cef_string_t>> = mem::transmute(lt); cef_string_list_clear(lt); drop(v); } } #[no_mangle] pub extern "C" fn cef_string_list_copy(lt: *mut ...
{ unsafe { if lt.is_null() { return; } let v = string_list_to_vec(lt); if (*v).len() == 0 { return; } let mut cs; while (*v).len() != 0 { cs = (*v).pop(); cef_string_userfree_utf16_free(cs.unwrap()); } } }
identifier_body
test_setup.py
#!/usr/bin/python # -*- coding: utf-8 -*- # system import os import sys dir = os.path.split(os.path.split(os.path.split(os.path.realpath(__file__))[0])[0])[0] sys.path.append(os.path.join(dir, 'scripts')) # testing import mock import unittest from mock import patch # program import setup.load as Config import setup....
class CheckDatabaseCreation(unittest.TestCase): '''Unit tests for the setting up the database.''' ## Structural tests. def test_wrapper_database_function_works(self): assert DB.Main() != False ## Failed config file. def test_database_fail(self): assert DB.CreateTables(config_path=os.path.join(dir...
Config.LoadConfig(os.path.join(dir, 'config', 'dev.json')) assert Config.LoadConfig(os.path.join(dir, 'tests', 'data', 'test_config.json')) == False
identifier_body
test_setup.py
#!/usr/bin/python # -*- coding: utf-8 -*- # system import os import sys dir = os.path.split(os.path.split(os.path.split(os.path.realpath(__file__))[0])[0])[0] sys.path.append(os.path.join(dir, 'scripts')) # testing import mock import unittest from mock import patch # program import setup.load as Config import setup....
def test_config_returns_a_table_list(self): d = Config.LoadConfig(os.path.join(dir, 'config', 'dev.json')) assert type(d['database']) is list def test_config_checks_api_key(self): Config.LoadConfig(os.path.join(dir, 'config', 'dev.json')) assert Config.LoadConfig(os.path.join(dir, 'tests', 'data',...
random_line_split
test_setup.py
#!/usr/bin/python # -*- coding: utf-8 -*- # system import os import sys dir = os.path.split(os.path.split(os.path.split(os.path.realpath(__file__))[0])[0])[0] sys.path.append(os.path.join(dir, 'scripts')) # testing import mock import unittest from mock import patch # program import setup.load as Config import setup....
(self): assert Config.LoadConfig('xxx.json') == False ## Object type tests. def test_config_is_list(self): d = Config.LoadConfig(os.path.join(dir, 'config', 'dev.json')) assert type(d) is dict def test_config_returns_a_table_list(self): d = Config.LoadConfig(os.path.join(dir, 'config', 'dev.json...
test_that_load_config_fails_gracefully
identifier_name
switch.py
"""Support for switches through the SmartThings cloud API.""" from __future__ import annotations from collections.abc import Sequence from pysmartthings import Capability from homeassistant.components.switch import SwitchEntity from . import SmartThingsEntity from .const import DATA_BROKERS, DOMAIN async def asyn...
def get_capabilities(capabilities: Sequence[str]) -> Sequence[str] | None: """Return all capabilities supported if minimum required are present.""" # Must be able to be turned on/off. if Capability.switch in capabilities: return [Capability.switch, Capability.energy_meter, Capability.power_meter]...
"""Add switches for a config entry.""" broker = hass.data[DOMAIN][DATA_BROKERS][config_entry.entry_id] async_add_entities( [ SmartThingsSwitch(device) for device in broker.devices.values() if broker.any_assigned(device.device_id, "switch") ] )
identifier_body
switch.py
"""Support for switches through the SmartThings cloud API.""" from __future__ import annotations from collections.abc import Sequence from pysmartthings import Capability from homeassistant.components.switch import SwitchEntity from . import SmartThingsEntity from .const import DATA_BROKERS, DOMAIN async def asyn...
(self, **kwargs) -> None: """Turn the switch off.""" await self._device.switch_off(set_status=True) # State is set optimistically in the command above, therefore update # the entity state ahead of receiving the confirming push updates self.async_write_ha_state() async def as...
async_turn_off
identifier_name
switch.py
"""Support for switches through the SmartThings cloud API.""" from __future__ import annotations from collections.abc import Sequence from pysmartthings import Capability from homeassistant.components.switch import SwitchEntity from . import SmartThingsEntity from .const import DATA_BROKERS, DOMAIN async def asyn...
return None class SmartThingsSwitch(SmartThingsEntity, SwitchEntity): """Define a SmartThings switch.""" async def async_turn_off(self, **kwargs) -> None: """Turn the switch off.""" await self._device.switch_off(set_status=True) # State is set optimistically in the command above,...
return [Capability.switch, Capability.energy_meter, Capability.power_meter]
conditional_block
switch.py
"""Support for switches through the SmartThings cloud API.""" from __future__ import annotations from collections.abc import Sequence from pysmartthings import Capability from homeassistant.components.switch import SwitchEntity from . import SmartThingsEntity from .const import DATA_BROKERS, DOMAIN async def asyn...
self.async_write_ha_state() @property def is_on(self) -> bool: """Return true if light is on.""" return self._device.status.switch
async def async_turn_on(self, **kwargs) -> None: """Turn the switch on.""" await self._device.switch_on(set_status=True) # State is set optimistically in the command above, therefore update # the entity state ahead of receiving the confirming push updates
random_line_split
amqp_clock.py
#!/usr/bin/env python """ AMQP Clock Fires off simple messages at one-minute intervals to a topic exchange named 'clock', with the topic of the message being the local time as 'year.month.date.dow.hour.minute', for example: '2007.11.26.1.12.33', where the dow (day of week) is 0 for Sunday, 1 for Monday, and so on (sim...
# Make sure our first message is close to the beginning # of a minute now = datetime.now() if now.second > 0: sleep(60 - now.second) while True: now = datetime.now() msg = Message(timestamp=now) msg_topic = now.strftime(TOPIC_PATTERN) ch.basic_publish(msg, E...
parser = OptionParser() parser.add_option('--host', dest='host', help='AMQP server to connect to (default: %default)', default='localhost') parser.add_option('-u', '--userid', dest='userid', help='AMQP userid to authenticate as (default: %d...
identifier_body
amqp_clock.py
#!/usr/bin/env python """ AMQP Clock Fires off simple messages at one-minute intervals to a topic exchange named 'clock', with the topic of the message being the local time as 'year.month.date.dow.hour.minute', for example: '2007.11.26.1.12.33', where the dow (day of week) is 0 for Sunday, 1 for Monday, and so on (sim...
while True: now = datetime.now() msg = Message(timestamp=now) msg_topic = now.strftime(TOPIC_PATTERN) ch.basic_publish(msg, EXCHANGE_NAME, routing_key=msg_topic) # Don't know how long the basic_publish took, so # grab the time again. now = datetime.now() ...
sleep(60 - now.second)
conditional_block
amqp_clock.py
#!/usr/bin/env python """ AMQP Clock Fires off simple messages at one-minute intervals to a topic exchange named 'clock', with the topic of the message being the local time as 'year.month.date.dow.hour.minute', for example: '2007.11.26.1.12.33', where the dow (day of week) is 0 for Sunday, 1 for Monday, and so on (sim...
help='AMQP server to connect to (default: %default)', default='localhost') parser.add_option('-u', '--userid', dest='userid', help='AMQP userid to authenticate as (default: %default)', default='guest') parser.add_opt...
random_line_split
amqp_clock.py
#!/usr/bin/env python """ AMQP Clock Fires off simple messages at one-minute intervals to a topic exchange named 'clock', with the topic of the message being the local time as 'year.month.date.dow.hour.minute', for example: '2007.11.26.1.12.33', where the dow (day of week) is 0 for Sunday, 1 for Monday, and so on (sim...
(): parser = OptionParser() parser.add_option('--host', dest='host', help='AMQP server to connect to (default: %default)', default='localhost') parser.add_option('-u', '--userid', dest='userid', help='AMQP userid to authenticate as (def...
main
identifier_name
SliderUi.ts
import { Arr, Fun, Option } from '@ephox/katamari'; import { PlatformDetection } from '@ephox/sand'; import { Keying } from '../../api/behaviour/Keying'; import { Representing } from '../../api/behaviour/Representing'; import { Receiving } from '../../api/behaviour/Receiving'; import { AlloyComponent } from '../../api...
}) ] : [], [ Representing.config({ store: { mode: 'manual', getValue (_) { return modelDetail.value.get(); } } }), Receiving.config({ channels: { 'mouse.r...
{ return AlloyParts.getPart(slider, detail, 'spectrum').map(Keying.focusIn).map(Fun.constant(true)); }
identifier_body
SliderUi.ts
import { Arr, Fun, Option } from '@ephox/katamari'; import { PlatformDetection } from '@ephox/sand'; import { Keying } from '../../api/behaviour/Keying'; import { Representing } from '../../api/behaviour/Representing'; import { Receiving } from '../../api/behaviour/Receiving'; import { AlloyComponent } from '../../api...
const modelDetail = detail.model; const model = modelDetail.manager; const refresh = (slider: AlloyComponent, thumb: AlloyComponent): void => { model.setPositionFromValue(slider, thumb, detail, { getLeftEdge, getRightEdge, getTopEdge, getBottomEdge, getSpectrum }); }; c...
const getTopEdge = (component: AlloyComponent): Option<AlloyComponent> => AlloyParts.getPart(component, detail, 'top-edge'); const getBottomEdge = (component: AlloyComponent): Option<AlloyComponent> => AlloyParts.getPart(component, detail, 'bottom-edge');
random_line_split
SliderUi.ts
import { Arr, Fun, Option } from '@ephox/katamari'; import { PlatformDetection } from '@ephox/sand'; import { Keying } from '../../api/behaviour/Keying'; import { Representing } from '../../api/behaviour/Representing'; import { Receiving } from '../../api/behaviour/Receiving'; import { AlloyComponent } from '../../api...
(_) { return modelDetail.value.get(); } } }), Receiving.config({ channels: { 'mouse.released': { onReceive: (slider, se) => { const fireOnChoose = () => { AlloyParts.getPart(sl...
getValue
identifier_name
SliderUi.ts
import { Arr, Fun, Option } from '@ephox/katamari'; import { PlatformDetection } from '@ephox/sand'; import { Keying } from '../../api/behaviour/Keying'; import { Representing } from '../../api/behaviour/Representing'; import { Receiving } from '../../api/behaviour/Receiving'; import { AlloyComponent } from '../../api...
} } } } }) ] ]) ), events: AlloyEvents.derive( [ AlloyEvents.run<CustomEvent>(ModelCommon.sliderChangeEvent(), function (slider, simulatedEvent) { changeValue(slider, simulatedEvent.event().value()); ...
{ fireOnChoose(); }
conditional_block
deadlock.rs
// Zeming Lin // For CS4414, probably generates a deadlock. // Inspired by David Evans code from class 13 for CS4414, Fall '13 // This works on an AMD cpu running ubuntu LTS 12.04, // but it fails on an Intel Atom netbook. // Rust tasks also don't like to run concurrently on the same netbook // so it probably isn't ...
else { // Oops, another process grabbed the locks grab_lock(id); } } } fn release_locks() { unsafe { lock1 = None; lock2 = None } } fn update_count(id: uint) { unsafe { grab_lock(id); count += 1; println(fmt!("Count updated by %?: %?", id, count)); release_locks(); } } fn main() { ...
{ lock2 = Some(id); print(fmt!("Process %u grabbed lock2!\n", id)); while (lock1.is_some()) { ; } lock1 = Some(id); print(fmt!("Process %u grabbed lock1!\n", id)); }
conditional_block
deadlock.rs
// but it fails on an Intel Atom netbook. // Rust tasks also don't like to run concurrently on the same netbook // so it probably isn't the code's fault. type Semaphore = Option<uint> ; // either None (available) or owner static mut count: uint = 0; // protected by lock static mut lock1: Semaphore = None; static ...
// Zeming Lin // For CS4414, probably generates a deadlock. // Inspired by David Evans code from class 13 for CS4414, Fall '13 // This works on an AMD cpu running ubuntu LTS 12.04,
random_line_split
deadlock.rs
// Zeming Lin // For CS4414, probably generates a deadlock. // Inspired by David Evans code from class 13 for CS4414, Fall '13 // This works on an AMD cpu running ubuntu LTS 12.04, // but it fails on an Intel Atom netbook. // Rust tasks also don't like to run concurrently on the same netbook // so it probably isn't ...
fn main() { for num in range(0u, 10) { do spawn { for _ in range(0u, 1000) { update_count(num); } } } }
{ unsafe { grab_lock(id); count += 1; println(fmt!("Count updated by %?: %?", id, count)); release_locks(); } }
identifier_body
deadlock.rs
// Zeming Lin // For CS4414, probably generates a deadlock. // Inspired by David Evans code from class 13 for CS4414, Fall '13 // This works on an AMD cpu running ubuntu LTS 12.04, // but it fails on an Intel Atom netbook. // Rust tasks also don't like to run concurrently on the same netbook // so it probably isn't ...
(id: uint) { unsafe { grab_lock(id); count += 1; println(fmt!("Count updated by %?: %?", id, count)); release_locks(); } } fn main() { for num in range(0u, 10) { do spawn { for _ in range(0u, 1000) { update_count(num); } } } }
update_count
identifier_name
env.rs
// except according to those terms. use std::collections::hashmap::HashMap; use expr::{Expr, ExprResult}; use result::SchemerResult; pub type EnvResult = SchemerResult<Env>; pub type EnvSetResult = SchemerResult<()>; #[deriving(Clone)] pub struct Env { entries: HashMap<String, Expr>, outer: Option<Box<Env>> ...
// Copyright 2014 Jeffery Olson // // Licensed under the 3-Clause BSD License, see LICENSE.txt // at the top-level of this repository. // This file may not be copied, modified, or distributed
random_line_split
env.rs
// Copyright 2014 Jeffery Olson // // Licensed under the 3-Clause BSD License, see LICENSE.txt // at the top-level of this repository. // This file may not be copied, modified, or distributed // except according to those terms. use std::collections::hashmap::HashMap; use expr::{Expr, ExprResult}; use result::SchemerRe...
pub fn enclose(&mut self, base: Env) { match self.outer { Some(ref mut outer) => outer.enclose(base), None => self.outer = Some(box base) } } pub fn into_parent(self) -> Option<Env> { self.outer.map(|x| *x) } }
{ match self.entries.find(symbol) { Some(v) => Ok(v.clone()), None => { match &self.outer { &Some(ref outer_env) => outer_env.find(symbol), &None => Err(format!("No variable named {} defined in the environment." ...
identifier_body
env.rs
// Copyright 2014 Jeffery Olson // // Licensed under the 3-Clause BSD License, see LICENSE.txt // at the top-level of this repository. // This file may not be copied, modified, or distributed // except according to those terms. use std::collections::hashmap::HashMap; use expr::{Expr, ExprResult}; use result::SchemerRe...
<'b>(&'b self, symbol: &String) -> ExprResult { match self.entries.find(symbol) { Some(v) => Ok(v.clone()), None => { match &self.outer { &Some(ref outer_env) => outer_env.find(symbol), &None => Err(format!("No variable named {} def...
find
identifier_name
main.rs
extern crate osmpbfreader; extern crate serde; #[macro_use] extern crate serde_derive; #[macro_use(bson, doc)] extern crate bson; extern crate mongodb; use std::collections::HashMap; use std::env::args; use mongodb::coll::options::WriteModel; use mongodb::{Client, ThreadedClient}; use mongodb::db::ThreadedDatabase; us...
osmpbfreader::OsmObj::Way(w) => { let mut path = Vec::new(); for node_id in &w.nodes { match nodes.get(&node_id) { Some(node) => path.push((node.0,node.1)), None => { panic!(); } } ...
{ nodes.insert( n.id, (n.lat(),n.lon()) ); }
conditional_block
main.rs
extern crate osmpbfreader; extern crate serde; #[macro_use] extern crate serde_derive; #[macro_use(bson, doc)] extern crate bson; extern crate mongodb; use std::collections::HashMap; use std::env::args; use mongodb::coll::options::WriteModel; use mongodb::{Client, ThreadedClient}; use mongodb::db::ThreadedDatabase; us...
if exception.message.len()>0 { println!("ERROR(s): {}",exception.message); } } None => () } } } fn main() { // Connect to MongoDB client and select collection let client = Client::connect("localhost", 27017).ok().expect("F...
random_line_split
main.rs
extern crate osmpbfreader; extern crate serde; #[macro_use] extern crate serde_derive; #[macro_use(bson, doc)] extern crate bson; extern crate mongodb; use std::collections::HashMap; use std::env::args; use mongodb::coll::options::WriteModel; use mongodb::{Client, ThreadedClient}; use mongodb::db::ThreadedDatabase; us...
() { // Connect to MongoDB client and select collection let client = Client::connect("localhost", 27017).ok().expect("Failed to initialize client."); let rivers_coll = client.db("wwsupdb").collection("osm"); match rivers_coll.drop() { Ok(_) => println!("Collection droped"), Err(_) => pan...
main
identifier_name
template.py
# Copyright (c) 2010, Florian Ludwig <dino@phidev.org> # see LICENSE """Helpers for code generation based on genshi [0] There are good code generator tools out there like cog [1]. But if you already use genshi in your project this module might help you integrating code generation into your build and deploy process us...
class ShellStyleTemplate(NewTextTemplate): """Template for languages with # commentars""" def __init__(self, *args, **kwargs): kwargs['delims'] = ('#%', '%#', '##*', '*##') NewTextTemplate.__init__(self, *args, **kwargs) def get_template(fpath): """returns template class for given filen...
kwargs['delims'] = ('/*%', '%*/', '/*###', '###*/') NewTextTemplate.__init__(self, *args, **kwargs)
identifier_body
template.py
# Copyright (c) 2010, Florian Ludwig <dino@phidev.org> # see LICENSE """Helpers for code generation based on genshi [0] There are good code generator tools out there like cog [1]. But if you already use genshi in your project this module might help you integrating code generation into your build and deploy process us...
(self, src, dst, local_args={}): print src, '->', tmpl = self.loader.load(src, cls=get_template(src)) args = copy.copy(self.default_args) args.update(local_args) stream = tmpl.generate(**args) print dst data = stream.render() # make sure we only touch file...
gen
identifier_name
template.py
# Copyright (c) 2010, Florian Ludwig <dino@phidev.org> # see LICENSE """Helpers for code generation based on genshi [0] There are good code generator tools out there like cog [1]. But if you already use genshi in your project this module might help you integrating code generation into your build and deploy process us...
def get_template(fpath): """returns template class for given filename""" if fpath.endswith('.css') or fpath.endswith('.as') or fpath.endswith('.js'): return ActionscriptTemplate elif fpath.endswith('.py') or fpath.endswith('.wsgi'): return ShellStyleTemplate elif fpath.endswith('.mxml'...
"""Template for languages with # commentars""" def __init__(self, *args, **kwargs): kwargs['delims'] = ('#%', '%#', '##*', '*##') NewTextTemplate.__init__(self, *args, **kwargs)
random_line_split
template.py
# Copyright (c) 2010, Florian Ludwig <dino@phidev.org> # see LICENSE """Helpers for code generation based on genshi [0] There are good code generator tools out there like cog [1]. But if you already use genshi in your project this module might help you integrating code generation into your build and deploy process us...
def numbered_file(fpath, mode='r'): """Add filenumbers to every line as comment Returns filelike object """ _fileobj = open(fpath, mode) tmpl_cls = get_template(fpath) if tmpl_cls == ActionscriptTemplate: comment_start = '/*' comment_end = '*/' last_symbole = ';...
logging.warn('WARNING: don\'t know the file type of "%s"' % fpath) return NewTextTemplate
conditional_block
views.py
# Copyright 2012 Twitter # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, softw...
from django.db import connection def execute(sql): cursor = connection.cursor() cursor.execute(sql) return cursor.fetchall() users = convert(execute(TMPL % { 'table': 'auth_user', 'date': 'date_joined', })) apps = convert(execute(TMPL % { 'table': ...
return [(calendar.timegm(i[0].timetuple()), i[1]) for i in lst]
identifier_body
views.py
# Copyright 2012 Twitter # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, softw...
context = { 'title': 'Metrics', 'users': users, 'apps': apps, 'top_apps': top_apps, 'ab_signups': ab_signups, } return render_to_response('admin/metrics.html', context, context_instance=RequestContext(request)) @staff_member_required def admin_login(request...
'date': 'date_created', })) top_apps = get_top_recent_apps()
random_line_split
views.py
# Copyright 2012 Twitter # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, softw...
(request): TMPL = """ SELECT date_trunc('day', %(date)s), COUNT(1) FROM %(table)s GROUP BY date_trunc('day', %(date)s) ORDER BY date_trunc('day', %(date)s) ASC """ def convert(lst): return [(calendar.timegm(i[0].timetuple()), i[1]) for i in lst] from django.db i...
metrics
identifier_name