file_name
large_stringlengths
4
140
prefix
large_stringlengths
0
39k
suffix
large_stringlengths
0
36.1k
middle
large_stringlengths
0
29.4k
fim_type
large_stringclasses
4 values
import_.py
from __future__ import absolute_import class DummyException(Exception): pass def
( name, modules=None, exceptions=DummyException, locals_=None, globals_=None, level=-1): '''Import the requested items into the global scope WARNING! this method _will_ overwrite your global scope If you have a variable named "path" and you call import_global('sys') it will be overwritt...
import_global
identifier_name
import_.py
from __future__ import absolute_import class DummyException(Exception): pass def import_global( name, modules=None, exceptions=DummyException, locals_=None, globals_=None, level=-1): '''Import the requested items into the global scope WARNING! this method _will_ overwrite your global sc...
if k and k[0] != '_': globals_[k] = getattr(module, k) except exceptions as e: return e finally: # Clean up, just to be sure del name, modules, exceptions, locals_, globals_, frame
modules = set(modules).intersection(dir(module)) # Add all items in modules to the global scope for k in set(dir(module)).intersection(modules):
random_line_split
import_.py
from __future__ import absolute_import class DummyException(Exception): pass def import_global( name, modules=None, exceptions=DummyException, locals_=None, globals_=None, level=-1):
'''Import the requested items into the global scope WARNING! this method _will_ overwrite your global scope If you have a variable named "path" and you call import_global('sys') it will be overwritten with sys.path Args: name (str): the name of the module to import, e.g. sys modules (s...
identifier_body
import_.py
from __future__ import absolute_import class DummyException(Exception): pass def import_global( name, modules=None, exceptions=DummyException, locals_=None, globals_=None, level=-1): '''Import the requested items into the global scope WARNING! this method _will_ overwrite your global s...
try: name = name.split('.') # Relative imports are supported (from .spam import eggs) if not name[0]: name = name[1:] level = 1 # raise IOError((name, level)) module = __import__( name=name[0] or '.',...
globals_ = frame.f_globals
conditional_block
HINFO.py
# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license # Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and ...
cpu = parser.get_counted_bytes() os = parser.get_counted_bytes() return cls(rdclass, rdtype, cpu, os)
identifier_body
HINFO.py
# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license # Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and ...
def __init__(self, rdclass, rdtype, cpu, os): super().__init__(rdclass, rdtype) self.cpu = self._as_bytes(cpu, True, 255) self.os = self._as_bytes(os, True, 255) def to_text(self, origin=None, relativize=True, **kw): return '"{}" "{}"'.format(dns.rdata._escapify(self.cpu), ...
__slots__ = ['cpu', 'os']
random_line_split
HINFO.py
# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license # Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. # # Permission to use, copy, modify, and distribute this software and its # documentation for any purpose with or without fee is hereby granted, # provided that the above copyright notice and ...
(self, origin=None, relativize=True, **kw): return '"{}" "{}"'.format(dns.rdata._escapify(self.cpu), dns.rdata._escapify(self.os)) @classmethod def from_text(cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None): cpu = t...
to_text
identifier_name
Sequence.js
/* * Sequence is used internally to provide further methods to iterables * that are also genuine flat sequences, i.e all iterables but maps. * * None of the Sequence methods mutates the collection. * * Sequence can also act as a temporary Array wrapper so that an Array instance * can beneficiate from all Sequence metho...
/* * Returns the index of the first occurence of item * in this sequence or -1 if none exists. */ Sequence.prototype.indexOf = function(item, startingIndex) { startingIndex = startingIndex || 0; for (var i = startingIndex, length = this.items.length; i < length; i++) { if (this.items[i] === item) return i...
return this._createNew(result); };
random_line_split
hsibackend.py
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*- # # Copyright 2002 Ben Escoto <ben@emerose.org> # Copyright 2007 Kenneth Loafman <kenneth@loafman.com> # # This file is part of duplicity. # # Duplicity is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License...
else: self.remote_prefix = "" def _put(self, source_path, remote_filename): commandline = '%s "put %s : %s%s"' % (hsi_command, source_path.name, self.remote_prefix, remote_filename) self.subprocess_popen(commandline) def _get(self, remote_filename, local_path): com...
self.remote_prefix = self.remote_dir + "/"
conditional_block
hsibackend.py
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*- # # Copyright 2002 Ben Escoto <ben@emerose.org> # Copyright 2007 Kenneth Loafman <kenneth@loafman.com> # # This file is part of duplicity. # # Duplicity is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License...
(duplicity.backend.Backend): def __init__(self, parsed_url): duplicity.backend.Backend.__init__(self, parsed_url) self.host_string = parsed_url.hostname self.remote_dir = parsed_url.path if self.remote_dir: self.remote_prefix = self.remote_dir + "/" else: ...
HSIBackend
identifier_name
hsibackend.py
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*- # # Copyright 2002 Ben Escoto <ben@emerose.org> # Copyright 2007 Kenneth Loafman <kenneth@loafman.com> # # This file is part of duplicity. # # Duplicity is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License...
duplicity.backend.register_backend("hsi", HSIBackend) duplicity.backend.uses_netloc.extend(['hsi'])
commandline = '%s "rm %s%s"' % (hsi_command, self.remote_prefix, filename) self.subprocess_popen(commandline)
identifier_body
hsibackend.py
# -*- Mode:Python; indent-tabs-mode:nil; tab-width:4 -*- # # Copyright 2002 Ben Escoto <ben@emerose.org> # Copyright 2007 Kenneth Loafman <kenneth@loafman.com> # # This file is part of duplicity. # # Duplicity is free software; you can redistribute it and/or modify it # under the terms of the GNU General Public License...
def _get(self, remote_filename, local_path): commandline = '%s "get %s : %s%s"' % (hsi_command, local_path.name, self.remote_prefix, remote_filename) self.subprocess_popen(commandline) def _list(self): import sys commandline = '%s "ls -l %s"' % (hsi_command, self.remote_dir) ...
commandline = '%s "put %s : %s%s"' % (hsi_command, source_path.name, self.remote_prefix, remote_filename) self.subprocess_popen(commandline)
random_line_split
casper.py
#!/usr/bin/env python """casper.py Utility class for getting and presenting information from casper.jxml. The results from casper.jxml are undocumented and thus quite likely to be removed. Do not rely on its continued existence! Copyright (C) 2014 Shea G Craig <shea.craig@da.org> This program is free software: you ...
(self): """Make our data human readable.""" # deepcopy so we don't mess with the valid XML. pretty_data = copy.deepcopy(self) self._indent(pretty_data) elementstring = ElementTree.tostring(pretty_data) return elementstring.encode('utf-8') def makeelement(self, tag, a...
__repr__
identifier_name
casper.py
#!/usr/bin/env python """casper.py Utility class for getting and presenting information from casper.jxml. The results from casper.jxml are undocumented and thus quite likely to be removed. Do not rely on its continued existence! Copyright (C) 2014 Shea G Craig <shea.craig@da.org> This program is free software: you ...
def __repr__(self): """Make our data human readable.""" # deepcopy so we don't mess with the valid XML. pretty_data = copy.deepcopy(self) self._indent(pretty_data) elementstring = ElementTree.tostring(pretty_data) return elementstring.encode('utf-8') def makeel...
elem.tail += pad
conditional_block
casper.py
#!/usr/bin/env python """casper.py Utility class for getting and presenting information from casper.jxml. The results from casper.jxml are undocumented and thus quite likely to be removed. Do not rely on its continued existence! Copyright (C) 2014 Shea G Craig <shea.craig@da.org> This program is free software: you ...
# This handles that issue. return ElementTree.Element(tag, attrib) def update(self): """Request an updated set of data from casper.jxml.""" response = requests.post(self.url, data=self.auth) response_xml = ElementTree.fromstring(response.text) # Remove previous data...
def makeelement(self, tag, attrib): """Return an Element.""" # We use ElementTree.SubElement() a lot. Unfortunately, it relies on a # super() call to its __class__.makeelement(), which will fail due to # the class NOT being Element.
random_line_split
casper.py
#!/usr/bin/env python """casper.py Utility class for getting and presenting information from casper.jxml. The results from casper.jxml are undocumented and thus quite likely to be removed. Do not rely on its continued existence! Copyright (C) 2014 Shea G Craig <shea.craig@da.org> This program is free software: you ...
def _indent(self, elem, level=0, more_sibs=False): """Indent an xml element object to prepare for pretty printing. Method is internal to discourage indenting the self._root Element, thus potentially corrupting it. """ i = "\n" pad = ' ' if level: ...
"""Initialize a Casper object. jss: JSS object. """ self.jss = jss self.url = "%s%s" % (self.jss.base_url, '/casper.jxml') self.auth = urllib.urlencode({'username': self.jss.user, 'password': self.jss.password}) super(Casper, sel...
identifier_body
index.d.ts
// Type definitions for bootstrap-datepicker // Project: https://github.com/eternicode/bootstrap-datepicker // Definitions by: Boris Yankov <https://github.com/borisyankov/> // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped // TypeScript Version: 2.3 /// <reference types="jquery"/> /** * All options...
datesDisabled?:string|string[]; daysOfWeekHighlighted?:string|number[]; defaultViewDate?:Date|string|DatepickerViewDate; updateViewDate?:boolean; } interface DatepickerViewDate { year:number; /** Month starting with 0 */ month:number; /** Day of the month starting with 1 */ day:numb...
zIndexOffset?: number; showOnFocus?: boolean; immediateUpdates?: boolean; title?: string; container?: string;
random_line_split
locked_env_var.rs
//! Unit test helpers for dealing with environment variables. //! //! A lot of our functionality can change depending on how certain //! environment variables are set. This complicates unit testing, //! because Rust runs test cases in parallel on separate threads, but //! environment variables are shared across threads...
} impl Drop for LockedEnvVar { fn drop(&mut self) { match self.original_value { Some(ref val) => { env::set_var(&*self.lock, val); } None => { env::remove_var(&*self.lock); } } } } /// Create a static thread-safe ...
{ env::remove_var(&*self.lock); }
identifier_body
locked_env_var.rs
//! Unit test helpers for dealing with environment variables. //! //! A lot of our functionality can change depending on how certain //! environment variables are set. This complicates unit testing, //! because Rust runs test cases in parallel on separate threads, but //! environment variables are shared across threads...
assert_eq!(env::var("HAB_TESTING_LOCKED_ENV_VAR"), Ok(String::from("foo"))); lock.set("bar"); assert_eq!(env::var("HAB_TESTING_LOCKED_ENV_VAR"), Ok(String::from("bar"))); lock.set("foobar"); assert_eq!(env::var("HA...
{ let lock = lock_var(); lock.set("foo");
random_line_split
locked_env_var.rs
//! Unit test helpers for dealing with environment variables. //! //! A lot of our functionality can change depending on how certain //! environment variables are set. This complicates unit testing, //! because Rust runs test cases in parallel on separate threads, but //! environment variables are shared across threads...
<V>(&self, value: V) where V: AsRef<OsStr> { env::set_var(&*self.lock, value.as_ref()); } /// Unsets an environment variable. pub fn unset(&self) { env::remove_var(&*self.lock); } } impl Drop for LockedEnvVar { fn drop(&mut self) { match self.original_value { So...
set
identifier_name
fig4.py
#### # Figure 4 # needs: # - data/*.npz produced by run.py #### import glob import sys sys.path.append('..') from lib.mppaper import * import lib.mpsetup as mpsetup import lib.immune as immune files = sorted((immune.parse_value(f, 'epsilon'), f) for f in glob.glob("data/*.npz")) import run sigma = run.sigma #### le...
axP.locator_params(axis='x', nbins=5, tight=True) axP.set_xlim(0, 20) axP.set_ylabel(r'$P_r^\star$') axP.legend(ncol=2, handletextpad=0.1, loc='upper right', bbox_to_anchor=(1.05, 1.20)) for a in [axQ, axP]: a.set_ylim(ymin=0.0) mpsetup.despine(a) a.set_yticks([]) a.xaxis.labelpa...
axP.plot(x/sigma, p, label='ind. %g' % (i+1), **linedotstyle)
conditional_block
fig4.py
#### # Figure 4 # needs: # - data/*.npz produced by run.py #### import glob import sys sys.path.append('..') from lib.mppaper import * import lib.mpsetup as mpsetup import lib.immune as immune
import run sigma = run.sigma #### left figure #### epsilons = [] similarities = [] similaritiesQ = [] similaritiesPtilde = [] for epsilon, f in files: npz = np.load(f) P1 = npz['P1'] P2 = npz['P2'] Ptilde1 = npz['Ptilde1'] Ptilde2 = npz['Ptilde2'] Q1 = npz['Q1'] Q2 = npz['Q2'] epsilons....
files = sorted((immune.parse_value(f, 'epsilon'), f) for f in glob.glob("data/*.npz"))
random_line_split
IOErrorEvent.ts
////////////////////////////////////////////////////////////////////////////////////// // // The MIT License (MIT) // // Copyright (c) 2017-present, cyder.org // All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation ...
class IOErrorEvent extends Event { /** * Emitted when an error causes input or output operations to fail. */ public static readonly IO_ERROR:string = "ioError"; /** * Creates an Event object that contains specific information about ioError events. Event objects are passed as * paramete...
random_line_split
IOErrorEvent.ts
////////////////////////////////////////////////////////////////////////////////////// // // The MIT License (MIT) // // Copyright (c) 2017-present, cyder.org // All rights reserved. // // Permission is hereby granted, free of charge, to any person obtaining a copy of // this software and associated documentation ...
extends Event { /** * Emitted when an error causes input or output operations to fail. */ public static readonly IO_ERROR:string = "ioError"; /** * Creates an Event object that contains specific information about ioError events. Event objects are passed as * parameters to Event listen...
IOErrorEvent
identifier_name
pandoc_fignos.py
#! /usr/bin/env python """pandoc-fignos: a pandoc filter that inserts figure nos. and refs.""" # Copyright 2015, 2016 Thomas J. Duck. # All rights reserved. # # 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 Softwa...
if s.startswith('{') and s.endswith('}'): return True else: return False # New pandoc >= 1.16 else: assert len(value[0]['c']) == 3 return True # Pandoc >= 1.16 has image attributes by defaul...
# Old pandoc < 1.16 if len(value[0]['c']) == 2: s = stringify(value[1:]).strip()
random_line_split
pandoc_fignos.py
#! /usr/bin/env python """pandoc-fignos: a pandoc filter that inserts figure nos. and refs.""" # Copyright 2015, 2016 Thomas J. Duck. # All rights reserved. # # 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 Softwa...
def ast(string): """Returns an AST representation of the string.""" toks = [Str(tok) for tok in string.split()] spaces = [Space()]*len(toks) ret = list(itertools.chain(*zip(toks, spaces))) if string[0] == ' ': ret = [Space()] + ret return ret if string[-1] == ' ' else ret[:-1] def is_...
"""Parses a figure reference.""" prefix = value[0][0]['citationPrefix'] label = REF_PATTERN.match(value[1][0]['c']).groups()[0] suffix = value[0][0]['citationSuffix'] return prefix, label, suffix
identifier_body
pandoc_fignos.py
#! /usr/bin/env python """pandoc-fignos: a pandoc filter that inserts figure nos. and refs.""" # Copyright 2015, 2016 Thomas J. Duck. # All rights reserved. # # 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 Softwa...
if key == 'Para': return Para(value) else: return Plain(value) # pylint: disable=unused-argument def replace_attrimages(key, value, fmt, meta): """Replaces attributed images while storing reference labels.""" if is_attrimage(key, value): # Parse the image ...
newvalue = repair_broken_refs(value) if newvalue: value = newvalue else: break
conditional_block
pandoc_fignos.py
#! /usr/bin/env python """pandoc-fignos: a pandoc filter that inserts figure nos. and refs.""" # Copyright 2015, 2016 Thomas J. Duck. # All rights reserved. # # 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 Softwa...
(key, value, fmt, meta): """Preprocesses to correct for problems.""" if key in ('Para', 'Plain'): while True: newvalue = repair_broken_refs(value) if newvalue: value = newvalue else: break if key == 'Para': return Pa...
preprocess
identifier_name
legendre.rs
//compute Jacobi symbol of a number use super::Mod; use std::collections::HashSet; #[derive(Debug, Clone, PartialEq, Eq, Hash)] enum Jacobi { Value(i8), // -1, 0, 1 Frac{pos: bool, numer: u64, denom: u64}, } impl Jacobi { fn from_val(a: i8) -> Jacobi { Jacobi::Value(a) } fn from_frac(s: ...
} } fn two_numer(&self) -> Option<Jacobi> { // J((ab)/n) = J(a/n)*J(b/n) // J(2/n) = { 1 iff n≡±1(mod 8), -1 iff n≡ٍ±3(mod 8) } if let &Jacobi::Frac{pos: p, numer: n, denom: d} = self { let z = n.trailing_zeros(); let n_ = n / 2u64.pow(z); let ...
} else { None
random_line_split
legendre.rs
//compute Jacobi symbol of a number use super::Mod; use std::collections::HashSet; #[derive(Debug, Clone, PartialEq, Eq, Hash)] enum Jacobi { Value(i8), // -1, 0, 1 Frac{pos: bool, numer: u64, denom: u64}, } impl Jacobi { fn from_val(a: i8) -> Jacobi { Jacobi::Value(a) } fn
(s: bool, a: u64, b: u64) -> Jacobi { Jacobi::Frac{pos: s, numer: a, denom: b} } fn print(&self) { if let &Jacobi::Frac{pos: p, numer: n, denom: d} = self { println!(" {} J( {} / {} )", if p { '+' } else { '-' }, n, d); } else if let &Jacobi::Value(v) = ...
from_frac
identifier_name
legendre.rs
//compute Jacobi symbol of a number use super::Mod; use std::collections::HashSet; #[derive(Debug, Clone, PartialEq, Eq, Hash)] enum Jacobi { Value(i8), // -1, 0, 1 Frac{pos: bool, numer: u64, denom: u64}, } impl Jacobi { fn from_val(a: i8) -> Jacobi { Jacobi::Value(a) } fn from_frac(s: ...
None } } }
if n.modulo(4) == 3 && d.modulo(4) == 3 { Some(Jacobi::from_frac(!p, d, n)) } else { None } } else {
conditional_block
issue-13698.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
// except according to those terms. // aux-build:issue-13698.rs // ignore-cross-compile extern crate issue_13698; pub struct Foo; // @!has issue_13698/struct.Foo.html '//*[@id="method.foo"]' 'fn foo' impl issue_13698::Foo for Foo {} pub trait Bar { #[doc(hidden)] fn bar(&self) {} } // @!has issue_13698/str...
// option. This file may not be copied, modified, or distributed
random_line_split
issue-13698.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
} // @!has issue_13698/struct.Foo.html '//*[@id="method.foo"]' 'fn bar' impl Bar for Foo {}
{}
identifier_body
issue-13698.rs
// Copyright 2015 The Rust Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution and at // http://rust-lang.org/COPYRIGHT. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or ...
; // @!has issue_13698/struct.Foo.html '//*[@id="method.foo"]' 'fn foo' impl issue_13698::Foo for Foo {} pub trait Bar { #[doc(hidden)] fn bar(&self) {} } // @!has issue_13698/struct.Foo.html '//*[@id="method.foo"]' 'fn bar' impl Bar for Foo {}
Foo
identifier_name
primitives_OBSERVED.py
from astrodata.ReductionObjects import PrimitiveSet class OBSERVEDPrimitives(PrimitiveSet): astrotype = "OBSERVED" def init(self, rc): print "OBSERVEDPrimitives.init(rc)" return def typeSpecificPrimitive(self, rc): print "OBSERVEDPrimitives::typeSpecificPrimitive()" ...
def unmark(self, rc): for ad in rc.get_inputs_as_astrodata(): if ad.is_type("UNMARKED"): print "OBSERVEDPrimitives::unmark(%s) not marked" % ad.filename else: ad.phu_set_key_value("S_MARKED", None) rc.report_output(ad) ...
for ad in rc.get_inputs_as_astrodata(): if ad.is_type("MARKED"): print "OBSERVEDPrimitives::mark(%s) already marked" % ad.filename else: ad.phu_set_key_value("S_MARKED", "TRUE") rc.report_output(ad) yield rc
identifier_body
primitives_OBSERVED.py
from astrodata.ReductionObjects import PrimitiveSet class OBSERVEDPrimitives(PrimitiveSet): astrotype = "OBSERVED" def init(self, rc): print "OBSERVEDPrimitives.init(rc)" return def typeSpecificPrimitive(self, rc): print "OBSERVEDPrimitives::typeSpecificPrimitive()" ...
else: ad.phu_set_key_value("S_MARKED", None) rc.report_output(ad) yield rc
print "OBSERVEDPrimitives::unmark(%s) not marked" % ad.filename
conditional_block
primitives_OBSERVED.py
from astrodata.ReductionObjects import PrimitiveSet class
(PrimitiveSet): astrotype = "OBSERVED" def init(self, rc): print "OBSERVEDPrimitives.init(rc)" return def typeSpecificPrimitive(self, rc): print "OBSERVEDPrimitives::typeSpecificPrimitive()" def mark(self, rc): for ad in rc.get_inputs_as_astrodata(): ...
OBSERVEDPrimitives
identifier_name
primitives_OBSERVED.py
from astrodata.ReductionObjects import PrimitiveSet class OBSERVEDPrimitives(PrimitiveSet): astrotype = "OBSERVED" def init(self, rc):
def mark(self, rc): for ad in rc.get_inputs_as_astrodata(): if ad.is_type("MARKED"): print "OBSERVEDPrimitives::mark(%s) already marked" % ad.filename else: ad.phu_set_key_value("S_MARKED", "TRUE") rc.report_output(ad) yield rc ...
print "OBSERVEDPrimitives.init(rc)" return def typeSpecificPrimitive(self, rc): print "OBSERVEDPrimitives::typeSpecificPrimitive()"
random_line_split
index.js
//inicializamos eventos y procesos desde el DOM $(document).ready(function(){ IniciarEventos();} ); function IniciarEventos(){ $('#datetimepicker1').datetimepicker({locale:'es',format: "DD/MM/YYYY"}); $('#datetimepicker2').datetimepicker({locale:'es',format: "DD/MM/YYYY"}); fechaactual('fecdesde') fechaactual('f...
function getubication(lat,lng){ $('#modalview').modal({ show: true, remote: '/faultcars/getubicationmaps/'+lat+'/'+lng }); return false }
{ if(typeof(id) != 'undefined'){ $.ajax({url:'/faultcars/faultcarschangedstatenj.json', type:'post', dataType:'json', headers: { 'Security-Access-PublicToken':'A33esaSP9skSjasdSfFSssEwS2IksSZxPlA4asSJ4GEW4S' }, data:{id:id,state:1}, success: function(data){ $.each( data,...
identifier_body
index.js
//inicializamos eventos y procesos desde el DOM $(document).ready(function(){ IniciarEventos();} ); function IniciarEventos(){ $('#datetimepicker1').datetimepicker({locale:'es',format: "DD/MM/YYYY"}); $('#datetimepicker2').datetimepicker({locale:'es',format: "DD/MM/YYYY"}); fechaactual('fecdesde') fechaactual('f...
(lat,lng){ $('#modalview').modal({ show: true, remote: '/faultcars/getubicationmaps/'+lat+'/'+lng }); return false }
getubication
identifier_name
index.js
//inicializamos eventos y procesos desde el DOM $(document).ready(function(){ IniciarEventos();} ); function IniciarEventos(){ $('#datetimepicker1').datetimepicker({locale:'es',format: "DD/MM/YYYY"}); $('#datetimepicker2').datetimepicker({locale:'es',format: "DD/MM/YYYY"}); fechaactual('fecdesde') fechaactual('f...
if(val.error != ''){ alert('Error: '+val.error) }else{ $('#faultend'+id).hide(1) } }); } }) } } function getubication(lat,lng){ $('#modalview').modal({ show: true, remote: '/faultcars/getubicationmaps/'+lat+'/'+lng }); return false...
success: function(data){ $.each( data, function( key, val ) {
random_line_split
index.js
//inicializamos eventos y procesos desde el DOM $(document).ready(function(){ IniciarEventos();} ); function IniciarEventos(){ $('#datetimepicker1').datetimepicker({locale:'es',format: "DD/MM/YYYY"}); $('#datetimepicker2').datetimepicker({locale:'es',format: "DD/MM/YYYY"}); fechaactual('fecdesde') fechaactual('f...
} function getubication(lat,lng){ $('#modalview').modal({ show: true, remote: '/faultcars/getubicationmaps/'+lat+'/'+lng }); return false }
{ $.ajax({url:'/faultcars/faultcarschangedstatenj.json', type:'post', dataType:'json', headers: { 'Security-Access-PublicToken':'A33esaSP9skSjasdSfFSssEwS2IksSZxPlA4asSJ4GEW4S' }, data:{id:id,state:1}, success: function(data){ $.each( data, function( key, val ) { ...
conditional_block
tests.py
"""Unittests that do not require the server to be running an common tests of responses. The TestCase here just calls the functions that provide the logic to the ws views with DummyRequest objects to mock a real request. The functions starting with `check_...` are called with UnitTest.TestCase instance as the first ar...
def check_render_markdown_response(test_case, response): """Check of `response` to a `render_markdown` call.""" expected = '<p>hi from <a href="http://phylo.bio.ku.edu" target="_blank">' \ 'http://phylo.bio.ku.edu</a> and ' \ '<a href="https://github.com/orgs/OpenTreeOfLife/das...
test_case.assertIn(k, response)
conditional_block
tests.py
"""Unittests that do not require the server to be running an common tests of responses. The TestCase here just calls the functions that provide the logic to the ws views with DummyRequest objects to mock a real request. The functions starting with `check_...` are called with UnitTest.TestCase instance as the first ar...
def check_index_response(test_case, response): """Verifies the existene of expected keys in the response to an index call. 'documentation_url', 'description', and 'source_url' keys must be in the response. """ for k in ['documentation_url', 'description', 'source_url']: test_case.assertIn(k,...
"""Adds a version number (3) to the request to mimic the matching based on URL in the real app. """ req = testing.DummyRequest() get_app_settings_for_testing(req.registry.settings) req.matchdict['api_version'] = 'v3' return req
identifier_body
tests.py
"""Unittests that do not require the server to be running an common tests of responses. The TestCase here just calls the functions that provide the logic to the ws views with DummyRequest objects to mock a real request. The functions starting with `check_...` are called with UnitTest.TestCase instance as the first ar...
req = testing.DummyRequest() get_app_settings_for_testing(req.registry.settings) req.matchdict['api_version'] = 'v3' return req def check_index_response(test_case, response): """Verifies the existene of expected keys in the response to an index call. 'documentation_url', 'description', and 's...
def gen_versioned_dummy_request(): """Adds a version number (3) to the request to mimic the matching based on URL in the real app. """
random_line_split
tests.py
"""Unittests that do not require the server to be running an common tests of responses. The TestCase here just calls the functions that provide the logic to the ws views with DummyRequest objects to mock a real request. The functions starting with `check_...` are called with UnitTest.TestCase instance as the first ar...
(test_case, doc_id, resp): """Simple check of an `external_url` `resp` response for `doc_id`. `doc_id` and `url` fields of the response are checked.""" test_case.assertEquals(resp.get('doc_id'), doc_id) test_case.assertTrue(resp.get('url', '').endswith('{}.json'.format(doc_id))) def check_push_failur...
check_external_url_response
identifier_name
auction_demo_tests.py
from itertools import product from demos.auction_model import demo def test02(): sellers = [4] buyers = [100] results = demo(sellers, buyers, time_limit=False) expected_results = {100: 4, 4: 100} for k, v in results.items(): assert expected_results[k] == v, "Hmmm... That's not right {}={}...
errors = [] for k, v in results.items(): if not expected_results[k] == v: # , "Hmmm... That's not right {}={}".format(k, v) errors.append((k, v)) if errors: error_sets.append(errors) if error_sets: print("-" * 80) for i in error_sets: ...
random_line_split
auction_demo_tests.py
from itertools import product from demos.auction_model import demo def test02():
def test03(): expected_results = {101: 5, 5: 101, 6: None, 7: None} sellers = [k for k in expected_results if k < 100] buyers = [k for k in expected_results if k >= 100] results = demo(sellers, buyers) for k, v in results.items(): assert expected_results[k] == v, "Hmmm... That's not right...
sellers = [4] buyers = [100] results = demo(sellers, buyers, time_limit=False) expected_results = {100: 4, 4: 100} for k, v in results.items(): assert expected_results[k] == v, "Hmmm... That's not right {}={}".format(k, v)
identifier_body
auction_demo_tests.py
from itertools import product from demos.auction_model import demo def test02(): sellers = [4] buyers = [100] results = demo(sellers, buyers, time_limit=False) expected_results = {100: 4, 4: 100} for k, v in results.items(): assert expected_results[k] == v, "Hmmm... That's not right {}={}...
def test06(): expected_results = {0: 102, 1: 108, 2: 105, 3: 107, 4: 100, 5: 106, 6: 112, 7: 111, 8: 103, 9: 109, 10: 104, 100: 4, 101: None, 102: 0, 103: 8, 104: 10, 105: 2, 106: 5, 107: 3, 108: 1, 109: 9, 110: None, 111: 7, 112: 6} sellers = [k for k in expected_results if k < 100] buyers = [k for k in...
assert expected_results[k] == v, "Hmmm... That's not right {}={}".format(k, v)
conditional_block
auction_demo_tests.py
from itertools import product from demos.auction_model import demo def test02(): sellers = [4] buyers = [100] results = demo(sellers, buyers, time_limit=False) expected_results = {100: 4, 4: 100} for k, v in results.items(): assert expected_results[k] == v, "Hmmm... That's not right {}={}...
(): expected_results = {0: 101, 101: 0, 102: None, 103: None} # result: 0 enters contract with price 334.97 (the highest price) sellers = [k for k in expected_results if k < 100] buyers = [k for k in expected_results if k >= 100] results = demo(sellers, buyers) for k, v in r...
test04
identifier_name
hoit.rs
pub extern fn run(instance: lv2::Lv2handle, n_samples: u32) { unsafe{ let synth = instance as *mut Lv2SynthPlugin; let uris = &mut (*synth).uris; let seq = (*synth).in_port; let output = (*synth).output; // pointer to 1st event body let mut ev: *const lv2::Lv2AtomEven...
(instance: lv2::Lv2handle, n_samples: u32) { unsafe{ let synth = instance as *mut Synth; // frameindex of eventstart. In jalv this is relative to currently processed buffer chunk of length n_samples let istart = (*ev).time_in_frames as u32; match lv2::lv2_mi...
run
identifier_name
hoit.rs
pub extern fn run(instance: lv2::Lv2handle, n_samples: u32) { unsafe{ let synth = instance as *mut Lv2SynthPlugin; let uris = &mut (*synth).uris; let seq = (*synth).in_port; let output = (*synth).output; // pointer to 1st event body let mut ev: *const lv2::Lv2AtomEven...
if (*synth).noteison { let coef = 1.0 as f32; let f0 = (*synth).f0; for i in 0..n_samples { // let amp = (*synth).osc.get(); let amp = (*synth).OscBLIT.get(); *output.offset(i as isize) = (amp as f32) * coef; } ...
{ unsafe{ let synth = instance as *mut Synth; // frameindex of eventstart. In jalv this is relative to currently processed buffer chunk of length n_samples let istart = (*ev).time_in_frames as u32; match lv2::lv2_midi_message_type(msg) { ...
identifier_body
hoit.rs
pub extern fn run(instance: lv2::Lv2handle, n_samples: u32) { unsafe{ let synth = instance as *mut Lv2SynthPlugin; let uris = &mut (*synth).uris; let seq = (*synth).in_port; let output = (*synth).output; // pointer to 1st event body let mut ev: *const lv2::Lv2AtomEven...
(*synth).osc.set_dphase(f0,(*synth).fs); // TODO don't set fs here (*synth).OscBLIT.reset((*synth).fs); (*synth).OscBLIT.set_f0fn(f0); for i in istart-1..n_samples { // l...
(*synth).f0 = f0; (*synth).currentmidivel = *msg.offset(2); let coef = 1.0 as f32; (*synth).osc.reset();
random_line_split
TicketGrid.js
/** * @class NetProfile.tickets.controller.TicketGrid * @extends Ext.app.Controller */ Ext.define('NetProfile.tickets.controller.TicketGrid', { extend: 'Ext.app.Controller', requires: [ 'Ext.menu.Menu' ], fromTemplateText: 'From Template', fromTemplateTipText: 'Add ticket from template', scheduleText: 'Sche...
});
}); }
random_line_split
app-state.ts
import { observable, computed, action } from 'mobx'; import { remote as electron } from 'electron'; class AppState { @observable isFocused = false; @observable isIdle = false; @observable devModeEnabled = false; // network status as reported by chromium @observable isOnline = navigator.onLine; ...
} export default new AppState();
{ const win = electron.getCurrentWindow(); win.on('focus', () => { this.isFocused = true; console.log('App got focus'); }); win.on('blur', () => { this.isFocused = false; console.log('App lost focus'); }); this.isFocused = w...
identifier_body
app-state.ts
import { observable, computed, action } from 'mobx'; import { remote as electron } from 'electron'; class AppState { @observable isFocused = false; @observable isIdle = false; @observable devModeEnabled = false; // network status as reported by chromium @observable isOnline = navigator.onLine; ...
export default new AppState();
random_line_split
app-state.ts
import { observable, computed, action } from 'mobx'; import { remote as electron } from 'electron'; class AppState { @observable isFocused = false; @observable isIdle = false; @observable devModeEnabled = false; // network status as reported by chromium @observable isOnline = navigator.onLine; ...
() { console.log(`Chromium reports state change to: ${navigator.onLine ? 'ONLINE' : 'OFFLINE'}`); this.isOnline = navigator.onLine; } constructor() { const win = electron.getCurrentWindow(); win.on('focus', () => { this.isFocused = true; console.log('App ...
changeOnlineStatus
identifier_name
lib.rs
extern crate rusty_c_sys; use rusty_c_sys as ffi; trait Pika2 { fn next_pika2(&mut self) -> i32; } impl Pika2 for i32 { fn next_pika2(&mut self) -> i32 { let raw = self as *mut i32; unsafe { ffi::next_pika2(raw) } } } #[cfg(test)] mod tests { use super::*; ...
() { let mut x = ffi::defend; let p = x.next_pika2(); assert_eq!(x, ffi::attack); assert_eq!(p, ffi::attack); } }
from_defend
identifier_name
lib.rs
extern crate rusty_c_sys; use rusty_c_sys as ffi; trait Pika2 { fn next_pika2(&mut self) -> i32; } impl Pika2 for i32 { fn next_pika2(&mut self) -> i32 { let raw = self as *mut i32; unsafe { ffi::next_pika2(raw) } } } #[cfg(test)] mod tests { use super::*; ...
let mut x = ffi::defend; let p = x.next_pika2(); assert_eq!(x, ffi::attack); assert_eq!(p, ffi::attack); } }
random_line_split
lib.rs
extern crate rusty_c_sys; use rusty_c_sys as ffi; trait Pika2 { fn next_pika2(&mut self) -> i32; } impl Pika2 for i32 { fn next_pika2(&mut self) -> i32 { let raw = self as *mut i32; unsafe { ffi::next_pika2(raw) } } } #[cfg(test)] mod tests { use super::*; ...
#[test] fn from_defend() { let mut x = ffi::defend; let p = x.next_pika2(); assert_eq!(x, ffi::attack); assert_eq!(p, ffi::attack); } }
{ let mut x = ffi::attack; let p = x.next_pika2(); assert_eq!(x, ffi::defend); assert_eq!(p, ffi::defend); }
identifier_body
app.module.ts
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { HttpClientModule } from '@angular/common/http'; import { FormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; import { AppRoutingModule } from './app-routing.module'; import { M...
FormsModule, AppRoutingModule ], providers: [ MyFriendsService, WebsocketService ], bootstrap: [AppComponent] }) export class AppModule { }
random_line_split
app.module.ts
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { HttpClientModule } from '@angular/common/http'; import { FormsModule } from '@angular/forms'; import { AppComponent } from './app.component'; import { AppRoutingModule } from './app-routing.module'; import { M...
{ }
AppModule
identifier_name
wrapping_sub_mul.rs
use num::arithmetic::traits::{ WrappingMul, WrappingSub, WrappingSubAssign, WrappingSubMul, WrappingSubMulAssign, }; fn
<T: WrappingMul<T, Output = T> + WrappingSub<T, Output = T>>( x: T, y: T, z: T, ) -> T { x.wrapping_sub(y.wrapping_mul(z)) } fn wrapping_sub_mul_assign<T: WrappingMul<T, Output = T> + WrappingSubAssign<T>>( x: &mut T, y: T, z: T, ) { x.wrapping_sub_assign(y.wrapping_mul(z)); } macro_ru...
wrapping_sub_mul
identifier_name
wrapping_sub_mul.rs
use num::arithmetic::traits::{ WrappingMul, WrappingSub, WrappingSubAssign, WrappingSubMul, WrappingSubMulAssign, };
) -> T { x.wrapping_sub(y.wrapping_mul(z)) } fn wrapping_sub_mul_assign<T: WrappingMul<T, Output = T> + WrappingSubAssign<T>>( x: &mut T, y: T, z: T, ) { x.wrapping_sub_assign(y.wrapping_mul(z)); } macro_rules! impl_wrapping_sub_mul { ($t:ident) => { impl WrappingSubMul<$t> for $t { ...
fn wrapping_sub_mul<T: WrappingMul<T, Output = T> + WrappingSub<T, Output = T>>( x: T, y: T, z: T,
random_line_split
wrapping_sub_mul.rs
use num::arithmetic::traits::{ WrappingMul, WrappingSub, WrappingSubAssign, WrappingSubMul, WrappingSubMulAssign, }; fn wrapping_sub_mul<T: WrappingMul<T, Output = T> + WrappingSub<T, Output = T>>( x: T, y: T, z: T, ) -> T
fn wrapping_sub_mul_assign<T: WrappingMul<T, Output = T> + WrappingSubAssign<T>>( x: &mut T, y: T, z: T, ) { x.wrapping_sub_assign(y.wrapping_mul(z)); } macro_rules! impl_wrapping_sub_mul { ($t:ident) => { impl WrappingSubMul<$t> for $t { type Output = $t; /// Com...
{ x.wrapping_sub(y.wrapping_mul(z)) }
identifier_body
dwr_db_I_gid_0.js
// This file is generated I_gid_0 = [ "I2111", "I2106", "I2113", "I2115", "I2105", "I2114", "I2110", "I1004", "I0554", "I0701", "I0553", "I0559", "I1408", "I0551", "I0702", "I0953", "I0693", "I2002", "I2011", "I1996", "I2017", "I0678", "I2007", "I1999", "I2016", "I2005", "I2013", "I2010", "I1995", "I2008", "I1997", "I...
"I1022", "I1018", "I1016", "I1145", "I1147", "I1036", "I0583", "I0585", "I0587", "I0580", "I0586", "I0582", "I0050", "I0250", "I0256", "I0253", "I0249", "I0792", "I1174", "I0987", "I1193", "I1192", "I1519", "I1549", "I1886", "I0533", "I0536", "I0532", "I0686", "I1676", "I1738", "I0887", "I0035", "I1339", "I0040", "I042...
"I1020",
random_line_split
helpDisplay.py
# -*- coding: utf-8 -*- ## ## ## This file is part of Indico. ## Copyright (C) 2002 - 2014 European Organization for Nuclear Research (CERN). ## ## Indico 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; eith...
p = help.WPHelp(self) return p.display()
identifier_body
helpDisplay.py
# -*- coding: utf-8 -*- ## ## ## This file is part of Indico. ## Copyright (C) 2002 - 2014 European Organization for Nuclear Research (CERN). ## ## Indico 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; eith...
## You should have received a copy of the GNU General Public License ## along with Indico;if not, see <http://www.gnu.org/licenses/>. import MaKaC.webinterface.rh.base as base import MaKaC.webinterface.pages.help as help class RHHelp( base.RH ): def _process( self ): p = help.WPHelp(self) return ...
##
random_line_split
helpDisplay.py
# -*- coding: utf-8 -*- ## ## ## This file is part of Indico. ## Copyright (C) 2002 - 2014 European Organization for Nuclear Research (CERN). ## ## Indico 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; eith...
( self ): p = help.WPHelp(self) return p.display()
_process
identifier_name
DownloadingButton.tsx
/* * 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/. * */ import * as React from 'react'; import * as events from '@csegames/camelot-unchained/lib/events'; import s...
extends React.Component<DownloadingButtonProps> { public render() { return ( <DownloadingButtonView onClick={this.props.onClick} onMouseOver={this.playSound}> <ButtonText>{this.props.text}</ButtonText> <Shine /> </DownloadingButtonView> ); } private playSound = () => { ev...
DownloadingButton
identifier_name
DownloadingButton.tsx
/* * 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/. * */ import * as React from 'react'; import * as events from '@csegames/camelot-unchained/lib/events'; import s...
position: absolute; height: 90%; width: 70%; border-left-radius: 50%; background: linear-gradient(to right, transparent, ${goldenColor}, transparent); bottom: 5px; left: 15px; opacity: 0; -webkit-animation: ${shineAnim} 1.3s ease infinite; animation: ${shineAnim} 1.3s ease infinite; -webkit-clip-p...
const Shine = styled('div')`
random_line_split
DownloadingButton.tsx
/* * 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/. * */ import * as React from 'react'; import * as events from '@csegames/camelot-unchained/lib/events'; import s...
private playSound = () => { events.fire('play-sound', 'select-change'); } } export default DownloadingButton;
{ return ( <DownloadingButtonView onClick={this.props.onClick} onMouseOver={this.playSound}> <ButtonText>{this.props.text}</ButtonText> <Shine /> </DownloadingButtonView> ); }
identifier_body
sintez.js
$(document).ready(function(){ $("#dropdownleft").hover( function() { $('.dropdown-menu', this).stop( true, true ).slideDown("fast"); $(this).toggleClass('open'); }, function() { $('.dropdown-menu', this).stop( true, true ).slideUp("fas...
/* sintez.js */
random_line_split
three_dim_stats.py
""" 30 Oct 2013 """ from pytadbit.eqv_rms_drms import rmsdRMSD_wrapper from pytadbit.consistency import consistency_wrapper from itertools import combinations import numpy as np from math import pi, sqrt, cos, sin, acos def generate_sphere_points(n=100): """ Returns list of 3d coordinates of points on a sp...
c/ | / | / | B )g |b \ | \ | a\ | \h| \| C is given by the theorem of Al-Kash...
random_line_split
three_dim_stats.py
""" 30 Oct 2013 """ from pytadbit.eqv_rms_drms import rmsdRMSD_wrapper from pytadbit.consistency import consistency_wrapper from itertools import combinations import numpy as np from math import pi, sqrt, cos, sin, acos def generate_sphere_points(n=100): """ Returns list of 3d coordinates of points on a sp...
""" Main function for the calculation of the accessibility of a model. """ superradius = superradius or 1 # number of dots in a circle is dependent the ones in a sphere numc = sqrt(nump) * sqrt(pi) right_angle = pi / 2 - pi / numc # keeps the remaining of integer conversion, to correct r...
identifier_body
three_dim_stats.py
""" 30 Oct 2013 """ from pytadbit.eqv_rms_drms import rmsdRMSD_wrapper from pytadbit.consistency import consistency_wrapper from itertools import combinations import numpy as np from math import pi, sqrt, cos, sin, acos def generate_sphere_points(n=100): """ Returns list of 3d coordinates of points on a sp...
(part1, part2): """ Calculates the distance between two particles. :param part1: coordinate in list format (x, y, z) :param part2: coordinate in list format (x, y, z) :returns: distance between two points in space """ return sqrt((part1[0] - part2[0])**2 + (part1[1] - part2...
distance
identifier_name
three_dim_stats.py
""" 30 Oct 2013 """ from pytadbit.eqv_rms_drms import rmsdRMSD_wrapper from pytadbit.consistency import consistency_wrapper from itertools import combinations import numpy as np from math import pi, sqrt, cos, sin, acos def generate_sphere_points(n=100): """ Returns list of 3d coordinates of points on a sp...
subsize += 1 xm += x[i] ym += y[i] zm += z[i] xm /= subsize ym /= subsize zm /= subsize return xm, ym, zm def mass_center(x, y, z, zeros): """ Transforms coordinates according to the center of mass :param x: list of x coordinates :param y: list of y co...
continue
conditional_block
task_basic_info.rs
// Copyright 2014 The Servo Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at ...
let mut resident_size: size_t = 0; let rv = unsafe { TaskBasicInfoResidentSize(&mut resident_size) }; if rv == 0 { Some(resident_size as usize) } else { None } } extern { fn TaskBasicInfoVirtualSize(virtual_size: *mut size_t) -> c_int; fn TaskBasicInfoResidentSize(resident_size: *mut si...
/// Obtains task_basic_info::resident_size. pub fn resident_size() -> Option<usize> {
random_line_split
task_basic_info.rs
// Copyright 2014 The Servo Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at ...
extern { fn TaskBasicInfoVirtualSize(virtual_size: *mut size_t) -> c_int; fn TaskBasicInfoResidentSize(resident_size: *mut size_t) -> c_int; } #[cfg(test)] mod test { use super::*; #[test] fn test_stuff() { // In theory these can fail to return a value, but in practice they // do...
{ let mut resident_size: size_t = 0; let rv = unsafe { TaskBasicInfoResidentSize(&mut resident_size) }; if rv == 0 { Some(resident_size as usize) } else { None } }
identifier_body
task_basic_info.rs
// Copyright 2014 The Servo Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at ...
else { None } } /// Obtains task_basic_info::resident_size. pub fn resident_size() -> Option<usize> { let mut resident_size: size_t = 0; let rv = unsafe { TaskBasicInfoResidentSize(&mut resident_size) }; if rv == 0 { Some(resident_size as usize) } else { None } } extern { fn TaskBasicInfo...
{ Some(virtual_size as usize) }
conditional_block
task_basic_info.rs
// Copyright 2014 The Servo Project Developers. See the COPYRIGHT // file at the top-level directory of this distribution. // // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at ...
() { // In theory these can fail to return a value, but in practice they // don't unless something really bizarre has happened with the OS. So // assume they succeed. The returned values are non-deterministic, but // check they're non-zero as a basic sanity test. assert!(virtual_...
test_stuff
identifier_name
config.py
""" Configurations -------------- Various setups for different app instances """ class Config: """Default config""" DEBUG = False TESTING = False SESSION_STORE = 'session' MONGODB_DB = 'default' SECRET_KEY = 'flask+braiiin=<3' LIVE = ['v1'] STATIC_PATH = 'static' HASHING_ROUNDS...
class TestConfig(Config): """For automated testing""" TESTING = True MONGODB_DB = 'test'
"""For local runs""" DEBUG = True MONGODB_DB = 'dev'
identifier_body
config.py
""" Configurations -------------- Various setups for different app instances """ class Config: """Default config""" DEBUG = False TESTING = False SESSION_STORE = 'session' MONGODB_DB = 'default' SECRET_KEY = 'flask+braiiin=<3' LIVE = ['v1'] STATIC_PATH = 'static' HASHING_ROUNDS...
(Config): """Production vars""" INIT = { 'port': 80, 'host': '127.0.0.1', } class DevelopmentConfig(Config): """For local runs""" DEBUG = True MONGODB_DB = 'dev' class TestConfig(Config): """For automated testing""" TESTING = True MONGODB_DB = 'test'
ProductionConfig
identifier_name
config.py
""" Configurations -------------- Various setups for different app instances """ class Config: """Default config""" DEBUG = False TESTING = False SESSION_STORE = 'session' MONGODB_DB = 'default' SECRET_KEY = 'flask+braiiin=<3' LIVE = ['v1'] STATIC_PATH = 'static' HASHING_ROUNDS...
class DevelopmentConfig(Config): """For local runs""" DEBUG = True MONGODB_DB = 'dev' class TestConfig(Config): """For automated testing""" TESTING = True MONGODB_DB = 'test'
random_line_split
StopPropagation.tsx
/* * Copyright (C) 2020 Graylog, Inc.
* * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * Server Side Public License for more details. * * You should have received a copy of the Server Side Public License ...
* * This program is free software: you can redistribute it and/or modify * it under the terms of the Server Side Public License, version 1, * as published by MongoDB, Inc.
random_line_split
test_link_aggregator.py
import unittest import logging from domaincrawl.link_aggregator import LinkAggregator from domaincrawl.link_filters import DomainFilter, is_acceptable_url_scheme from domaincrawl.site_graph import SiteGraph from domaincrawl.util import URLNormalizer, extract_domain_port class LinkAggregatorTest(unittest.Tes...
site_graph = SiteGraph(logger) link_aggregator = LinkAggregator(logger, site_graph, link_mappers=[url_norm.normalize_with_domain], link_filters=[domain_filter.passes, is_acceptable_url_scheme]) valid_links = ["/a/b","/a/b/./","http://acme.com:8002/a","https://acme.com:8002/b?q=asd#frag"] ...
logger.debug("Constructed normalized base url : %s"%normalized_url) domain_filter = DomainFilter(base_domain, logger)
random_line_split
test_link_aggregator.py
import unittest import logging from domaincrawl.link_aggregator import LinkAggregator from domaincrawl.link_filters import DomainFilter, is_acceptable_url_scheme from domaincrawl.site_graph import SiteGraph from domaincrawl.util import URLNormalizer, extract_domain_port class LinkAggregatorTest(unittest.Tes...
self.assertEqual(len(expected_links), site_graph.num_edges()) for link in expected_links: self.assertTrue(site_graph.has_edge(normalized_url, link))
self.assertTrue(site_graph.has_vertex(link))
conditional_block
test_link_aggregator.py
import unittest import logging from domaincrawl.link_aggregator import LinkAggregator from domaincrawl.link_filters import DomainFilter, is_acceptable_url_scheme from domaincrawl.site_graph import SiteGraph from domaincrawl.util import URLNormalizer, extract_domain_port class
(unittest.TestCase): logging.basicConfig(format='%(asctime)s %(levelname)s:%(message)s', level=logging.DEBUG, datefmt='%m/%d/%Y %I:%M:%S %p') def test_link_dedup(self): base_url = "acme.com:8999" base_domain, port = extract_domain_port(base_url) logger = logging.getLogger() ...
LinkAggregatorTest
identifier_name
test_link_aggregator.py
import unittest import logging from domaincrawl.link_aggregator import LinkAggregator from domaincrawl.link_filters import DomainFilter, is_acceptable_url_scheme from domaincrawl.site_graph import SiteGraph from domaincrawl.util import URLNormalizer, extract_domain_port class LinkAggregatorTest(unittest.Tes...
logging.basicConfig(format='%(asctime)s %(levelname)s:%(message)s', level=logging.DEBUG, datefmt='%m/%d/%Y %I:%M:%S %p') def test_link_dedup(self): base_url = "acme.com:8999" base_domain, port = extract_domain_port(base_url) logger = logging.getLogger() url_norm = URLNormalize...
identifier_body
index.js
var through = require('through2'), falafel = require('falafel'),
function lintroller(_checks) { var count = 0, files = [], stream = through(add_files, noop), checks = _checks || [] checks.forEach(resolve_check) checks = checks.filter(Boolean) return stream function add_files(chunk, enc, next) { files.push(chunk.toString()) if (!count) { ...
fs = require('fs') module.exports = lintroller
random_line_split
index.js
var through = require('through2'), falafel = require('falafel'), fs = require('fs') module.exports = lintroller function lintroller(_checks) { var count = 0, files = [], stream = through(add_files, noop), checks = _checks || [] checks.forEach(resolve_check) checks = checks.filter(Bool...
} function noop() {}
{ if (!rule.name || !rule.test || typeof rule.test !== 'function') { rule = false return } rule.description = rule.description || rule.name rule.count = rule.count || 0 }
identifier_body
index.js
var through = require('through2'), falafel = require('falafel'), fs = require('fs') module.exports = lintroller function lintroller(_checks) { var count = 0, files = [], stream = through(add_files, noop), checks = _checks || [] checks.forEach(resolve_check) checks = checks.filter(Bool...
(chunk, enc, next) { files.push(chunk.toString()) if (!count) { count++ read_file(files.shift()) } next() } function read_file(filename) { fs.readFile(filename, 'utf8', process_file) function process_file(err, data) { if (err) process.stdout.write('whoopsie goldberg') &...
add_files
identifier_name
index.js
var through = require('through2'), falafel = require('falafel'), fs = require('fs') module.exports = lintroller function lintroller(_checks) { var count = 0, files = [], stream = through(add_files, noop), checks = _checks || [] checks.forEach(resolve_check) checks = checks.filter(Bool...
next() } function read_file(filename) { fs.readFile(filename, 'utf8', process_file) function process_file(err, data) { if (err) process.stdout.write('whoopsie goldberg') && process.exit(1) falafel('' + data, check_node) if (!files.length) return finish() count++ read_fi...
{ count++ read_file(files.shift()) }
conditional_block
NodeGraphContainer.tsx
import React from 'react'; import { useToggle } from 'react-use'; import { Badge, Collapse, useStyles2, useTheme2 } from '@grafana/ui'; import { applyFieldOverrides, DataFrame, GrafanaTheme2 } from '@grafana/data'; import { css } from '@emotion/css'; import { ExploreId, StoreState } from '../../types'; import { splitOp...
exploreId: ExploreId; // When showing the node graph together with trace view we do some changes so it works better. withTraceView?: boolean; } type Props = OwnProps & ConnectedProps<typeof connector>; export function UnconnectedNodeGraphContainer(props: Props) { const { dataFrames, range, splitOpen, withTrac...
interface OwnProps { // Edges and Nodes are separate frames dataFrames: DataFrame[];
random_line_split
NodeGraphContainer.tsx
import React from 'react'; import { useToggle } from 'react-use'; import { Badge, Collapse, useStyles2, useTheme2 } from '@grafana/ui'; import { applyFieldOverrides, DataFrame, GrafanaTheme2 } from '@grafana/data'; import { css } from '@emotion/css'; import { ExploreId, StoreState } from '../../types'; import { splitOp...
{ splitOpen, }; const connector = connect(mapStateToProps, mapDispatchToProps); export const NodeGraphContainer = connector(UnconnectedNodeGraphContainer);
identifier_body
NodeGraphContainer.tsx
import React from 'react'; import { useToggle } from 'react-use'; import { Badge, Collapse, useStyles2, useTheme2 } from '@grafana/ui'; import { applyFieldOverrides, DataFrame, GrafanaTheme2 } from '@grafana/data'; import { css } from '@emotion/css'; import { ExploreId, StoreState } from '../../types'; import { splitOp...
? () => toggleOpen() : undefined} > <div style={{ height: withTraceView ? 500 : 600 }}> <NodeGraph dataFrames={frames} getLinks={getLinks} /> </div> </Collapse> ); } function mapStateToProps(state: StoreState, { exploreId }: OwnProps) { return { range: state.explore[exploreId]!.ran...
withTraceView
identifier_name
util.py
# coding: utf-8 """ General utilities. """ from __future__ import division, print_function __author__ = "adrn <adrn@astro.columbia.edu>" # Standard library import collections import sys import logging import multiprocessing # Third-party import numpy as np __all__ = ['get_pool'] # Create logger logger = logging....
(self, backend): import matplotlib.pyplot as plt from IPython.core.interactiveshell import InteractiveShell from IPython.core.pylabtools import backend2gui self.shell = InteractiveShell.instance() self.old_backend = backend2gui[str(plt.get_backend())] self.new_backend = ...
__init__
identifier_name
util.py
# coding: utf-8 """ General utilities. """ from __future__ import division, print_function __author__ = "adrn <adrn@astro.columbia.edu>" # Standard library import collections import sys import logging import multiprocessing # Third-party import numpy as np __all__ = ['get_pool'] # Create logger logger = logging....
class ImmutableDict(collections.Mapping): def __init__(self, somedict): self._dict = dict(somedict) # make a copy self._hash = None def __getitem__(self, key): return self._dict[key] def __len__(self): return len(self._dict) def __iter__(self): return iter(...
for name, func in vars(cls).items(): if not func.__doc__: for parent in cls.__bases__: try: parfunc = getattr(parent, name) except AttributeError: # parent doesn't have function break if parfunc and getattr(parfu...
identifier_body
util.py
# coding: utf-8 """ General utilities. """ from __future__ import division, print_function __author__ = "adrn <adrn@astro.columbia.edu>" # Standard library import collections import sys import logging import multiprocessing # Third-party import numpy as np __all__ = ['get_pool'] # Create logger logger = logging....
else: logger.debug("Running serial...") pool = SerialPool() return pool def gram_schmidt(y): """ Modified Gram-Schmidt orthonormalization of the matrix y(n,n) """ n = y.shape[0] if y.shape[1] != n: raise ValueError("Invalid shape: {}".format(y.shape)) mo = np.zeros(n...
logger.debug("Running with multiprocessing on {} cores..." .format(threads)) pool = multiprocessing.Pool(threads)
conditional_block
util.py
# coding: utf-8 """ General utilities. """ from __future__ import division, print_function __author__ = "adrn <adrn@astro.columbia.edu>" # Standard library import collections import sys import logging import multiprocessing # Third-party import numpy as np __all__ = ['get_pool'] # Create logger logger = logging....
if mpi: from emcee.utils import MPIPool # Initialize the MPI pool pool = MPIPool() # Make sure the thread we're running on is the master if not pool.is_master(): pool.wait() sys.exit(0) logger.debug("Running with MPI...") elif threads >...
threads : int (optional) If mpi is False and threads is specified, use a Python multiprocessing pool with the specified number of threads. """
random_line_split