signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def get_by_id ( cls , record_id , execute = True ) : """Return a single instance of the model queried by ID . Args : record _ id ( int ) : Integer representation of the ID to query on . Keyword Args : execute ( bool , optional ) : Should this method execute the query or return a query object for further...
query = cls . base_query ( ) . where ( cls . id == record_id ) if execute : return query . get ( ) return query
def sample_ogrid ( self , ogrid : np . array ) -> np . array : """Sample an open mesh - grid array and return the result . Args ogrid ( Sequence [ Sequence [ float ] ] ) : An open mesh - grid . Returns : numpy . ndarray : An array of sampled points . The ` ` shape ` ` is based on the lengths of the open m...
if len ( ogrid ) != self . dimensions : raise ValueError ( "len(ogrid) must equal self.dimensions, " "%r != %r" % ( len ( ogrid ) , self . dimensions ) ) ogrids = [ np . ascontiguousarray ( array , np . float32 ) for array in ogrid ] out = np . ndarray ( [ array . size for array in ogrids ] , np . float32 ) lib . N...
def deep_update ( source , overrides ) : """Update a nested dictionary or similar mapping . Modify ` ` source ` ` in place . : type source : collections . Mapping : type overrides : collections . Mapping : rtype : collections . Mapping"""
for key , value in overrides . items ( ) : if isinstance ( value , collections . Mapping ) and value : returned = deep_update ( source . get ( key , { } ) , value ) source [ key ] = returned else : source [ key ] = overrides [ key ] return source
def get ( self , request , bot_id , id , format = None ) : """Get MessengerBot by id serializer : MessengerBotSerializer responseMessages : - code : 401 message : Not authenticated"""
return super ( MessengerBotDetail , self ) . get ( request , bot_id , id , format )
def add_package ( self , pkg_name , recurse = True , include_bases = True , parent_pkg = None ) : """Add all classes to the backup in the specified package ( including all modules and all sub - packages ) for which is _ backup _ class returns True . Note that self . add _ class is used , so base classes will ad...
if parent_pkg : pkg = import_module ( '.' + pkg_name , parent_pkg ) else : pkg = import_module ( pkg_name ) for module_loader , name , ispkg in pkgutil . walk_packages ( pkg . __path__ ) : if not ispkg : # Module mod = import_module ( '.' + name , pkg_name ) for name , member in getmembers (...
def update_timer ( self , timer , action , usecs ) : """Called by libcouchbase to add / remove timers"""
if action == PYCBC_EVACTION_WATCH : timer . schedule ( usecs , self . reactor ) elif action == PYCBC_EVACTION_UNWATCH : timer . cancel ( ) elif action == PYCBC_EVACTION_CLEANUP : timer . cleanup ( )
def RunDecompiler ( d , dx , decompiler_name ) : """Run the decompiler on a specific analysis : param d : the DalvikVMFormat object : type d : : class : ` DalvikVMFormat ` object : param dx : the analysis of the format : type dx : : class : ` VMAnalysis ` object : param decompiler : the type of decompiler...
if decompiler_name is not None : log . debug ( "Decompiler ..." ) decompiler_name = decompiler_name . lower ( ) # TODO put this into the configuration object and make it more dynamic # e . g . detect new decompilers and so on . . . if decompiler_name == "dex2jad" : d . set_decompiler ( decom...
def list_types_poi ( self , ** kwargs ) : """Obtain a list of families , types and categories of POI . Args : lang ( str ) : Language code ( * es * or * en * ) . Returns : Status boolean and parsed response ( list [ ParkingPoiType ] ) , or message string in case of error ."""
# Endpoint parameters url_args = { 'language' : util . language_code ( kwargs . get ( 'lang' ) ) } # Request result = self . make_request ( 'list_poi_types' , url_args ) if not util . check_result ( result ) : return False , result . get ( 'message' , 'UNKNOWN ERROR' ) # Parse values = util . response_list ( result...
def _format_postconditions ( postconditions : List [ icontract . _Contract ] , prefix : Optional [ str ] = None ) -> List [ str ] : """Format postconditions as reST . : param postconditions : postconditions of a function : param prefix : prefix to be prepended to ` ` : ensures : ` ` directive : return : list ...
if not postconditions : return [ ] result = [ ] # type : List [ str ] if prefix is not None : result . append ( ":{} ensures:" . format ( prefix ) ) else : result . append ( ":ensures:" ) for postcondition in postconditions : result . append ( " * {}" . format ( _format_contract ( contract = postcond...
def is_full_overlap ( self1 ) : """true if they are a full overlap : return : is full overlap : rtype : bool"""
if len ( self1 . overs ) == 0 : return False if len ( self1 . dif1 ) > 0 : if max ( self1 . dif1 ) != 1 or max ( self1 . dif2 ) != 1 : return False if self1 . start1 and self1 . end1 and self1 . start2 and self1 . end2 : return True return False
def get_items ( self , sequence_id , gt = None , gte = None , lt = None , lte = None , limit = None , query_ascending = True , results_ascending = True ) : """Returns sequenced item generator ."""
records = self . get_records ( sequence_id = sequence_id , gt = gt , gte = gte , lt = lt , lte = lte , limit = limit , query_ascending = query_ascending , results_ascending = results_ascending , ) for item in map ( self . from_record , records ) : yield item
def bifurcated_extend ( self , corpus , max_size ) : """Replaces the results with those n - grams that contain any of the original n - grams , and that represent points at which an n - gram is a constituent of multiple larger n - grams with a lower label count . : param corpus : corpus of works to which res...
temp_fd , temp_path = tempfile . mkstemp ( text = True ) try : self . _prepare_bifurcated_extend_data ( corpus , max_size , temp_path , temp_fd ) finally : try : os . remove ( temp_path ) except OSError as e : msg = ( 'Failed to remove temporary file containing unreduced ' 'results: {}' ) ...
def _TerminateFlow ( rdf_flow , reason = None , flow_state = rdf_flow_objects . Flow . FlowState . ERROR ) : """Does the actual termination ."""
flow_cls = registry . FlowRegistry . FlowClassByName ( rdf_flow . flow_class_name ) flow_obj = flow_cls ( rdf_flow ) if not flow_obj . IsRunning ( ) : # Nothing to do . return logging . info ( "Terminating flow %s on %s, reason: %s" , rdf_flow . flow_id , rdf_flow . client_id , reason ) rdf_flow . flow_state = flow...
def setup_config ( command , filename , section , vars ) : """Place any commands to setup chatapp here"""
confuri = "config:" + filename if ":" in section : confuri += "#" + section . rsplit ( ":" , 1 ) [ - 1 ] conf = appconfig ( confuri ) load_environment ( conf . global_conf , conf . local_conf )
def GetUserDetails ( user , alias = None ) : """Gets the details of a specific user associated with a given account . https : / / t3n . zendesk . com / entries / 22427672 - GetUserDetails : param alias : short code for a particular account . If none will use account ' s default alias : param user : user name ...
if alias is None : alias = clc . v1 . Account . GetAlias ( ) r = clc . v1 . API . Call ( 'post' , 'User/GetUserDetails' , { 'AccountAlias' : alias , 'UserName' : user } ) if int ( r [ 'StatusCode' ] ) == 0 : r [ 'UserDetails' ] [ 'Roles' ] = User . _UserRoleList_itos ( r [ 'UserDetails' ] [ 'Roles' ] ) retu...
def _poll_upload ( self , upload_key , action ) : """Poll upload until quickkey is found upload _ key - - upload _ key returned by upload / * functions"""
if len ( upload_key ) != UPLOAD_KEY_LENGTH : # not a regular 11 - char - long upload key # There is no API to poll filedrop uploads return UploadResult ( action = action , quickkey = None , hash_ = None , filename = None , size = None , created = None , revision = None ) quick_key = None while quick_key is None : ...
def _from_rest_on_create ( model , props ) : """Assign the default values when creating a model This is done on fields with ` on _ create = < value > ` ."""
fields = model . get_fields_with_prop ( 'on_create' ) for field in fields : props [ field [ 0 ] ] = field [ 1 ]
def generate_ical_file ( generator ) : """Generate an iCalendar file"""
global events ics_fname = generator . settings [ 'PLUGIN_EVENTS' ] [ 'ics_fname' ] if not ics_fname : return ics_fname = os . path . join ( generator . settings [ 'OUTPUT_PATH' ] , ics_fname ) log . debug ( "Generating calendar at %s with %d events" % ( ics_fname , len ( events ) ) ) tz = generator . settings . get...
def finish_and_die ( self ) : """If there is a request pending , let it finish and be handled , then disconnect and die . If not , cancel any pending queue requests and just die ."""
self . logstate ( 'finish_and_die' ) self . stop_working_on_queue ( ) if self . jobphase != 'pending_request' : self . stopFactory ( )
def interpolate_xarray ( xpoints , ypoints , values , shape , kind = 'cubic' , blocksize = CHUNK_SIZE ) : """Interpolate , generating a dask array ."""
vchunks = range ( 0 , shape [ 0 ] , blocksize ) hchunks = range ( 0 , shape [ 1 ] , blocksize ) token = tokenize ( blocksize , xpoints , ypoints , values , kind , shape ) name = 'interpolate-' + token from scipy . interpolate import interp2d interpolator = interp2d ( xpoints , ypoints , values , kind = kind ) dskx = { ...
def cli ( env , snapshot_id ) : """Deletes a snapshot on a given volume"""
file_storage_manager = SoftLayer . FileStorageManager ( env . client ) deleted = file_storage_manager . delete_snapshot ( snapshot_id ) if deleted : click . echo ( 'Snapshot %s deleted' % snapshot_id )
def to_url ( self ) : """Serialize as a URL for a GET request ."""
base_url = urlparse ( self . url ) if PY3 : query = parse_qs ( base_url . query ) for k , v in self . items ( ) : query . setdefault ( k , [ ] ) . append ( to_utf8_optional_iterator ( v ) ) scheme = base_url . scheme netloc = base_url . netloc path = base_url . path params = base_url . p...
def run_model ( self , op_list , num_steps , feed_vars = ( ) , feed_data = None , print_every = 100 , allow_initialize = True ) : """Runs ` op _ list ` for ` num _ steps ` . Args : op _ list : A list of ops to run . num _ steps : Number of steps to run this for . If feeds are used , this is a maximum . ` No...
feed_data = feed_data or itertools . repeat ( ( ) ) ops = [ bookkeeper . global_step ( ) ] ops . extend ( op_list ) sess = tf . get_default_session ( ) self . prepare_model ( sess , allow_initialize = allow_initialize ) results = [ ] try : if num_steps is None : counter = itertools . count ( 0 ) elif nu...
def _colorize ( token , # type : str weight , # type : float weight_range , # type : float ) : # type : ( . . . ) - > str """Return token wrapped in a span with some styles ( calculated from weight and weight _ range ) applied ."""
token = html_escape ( token ) if np . isclose ( weight , 0. ) : return ( '<span ' 'style="opacity: {opacity}"' '>{token}</span>' . format ( opacity = _weight_opacity ( weight , weight_range ) , token = token ) ) else : return ( '<span ' 'style="background-color: {color}; opacity: {opacity}" ' 'title="{weight:.3...
def from_path ( cls , path , suffix = "" ) : """Convenient constructor that takes in the path name of VASP run to perform Bader analysis . Args : path ( str ) : Name of directory where VASP output files are stored . suffix ( str ) : specific suffix to look for ( e . g . ' . relax1' for ' CHGCAR . relax1...
def _get_filepath ( filename ) : name_pattern = filename + suffix + '*' if filename != 'POTCAR' else filename + '*' paths = glob . glob ( os . path . join ( path , name_pattern ) ) fpath = None if len ( paths ) >= 1 : # using reverse = True because , if multiple files are present , # they likely hav...
def mach60 ( msg ) : """Aircraft MACH number Args : msg ( String ) : 28 bytes hexadecimal message ( BDS60 ) string Returns : float : MACH number"""
d = hex2bin ( data ( msg ) ) if d [ 23 ] == '0' : return None mach = bin2int ( d [ 24 : 34 ] ) * 2.048 / 512.0 return round ( mach , 3 )
def unravel ( txt , binding , msgtype = "response" ) : """Will unpack the received text . Depending on the context the original response may have been transformed before transmission . : param txt : : param binding : : param msgtype : : return :"""
# logger . debug ( " unravel ' % s ' " , txt ) if binding not in [ BINDING_HTTP_REDIRECT , BINDING_HTTP_POST , BINDING_SOAP , BINDING_URI , BINDING_HTTP_ARTIFACT , None ] : raise UnknownBinding ( "Don't know how to handle '%s'" % binding ) else : try : if binding == BINDING_HTTP_REDIRECT : x...
def convert_command_output ( * command ) : """Command line interface for ` ` coloredlogs - - to - html ` ` . Takes a command ( and its arguments ) and runs the program under ` ` script ` ` ( emulating an interactive terminal ) , intercepts the output of the command and converts ANSI escape sequences in the ou...
captured_output = capture ( command ) converted_output = convert ( captured_output ) if connected_to_terminal ( ) : fd , temporary_file = tempfile . mkstemp ( suffix = '.html' ) with open ( temporary_file , 'w' ) as handle : handle . write ( converted_output ) webbrowser . open ( temporary_file ) el...
def serialize_to_normalized_compact_json ( py_obj ) : """Serialize a native object to normalized , compact JSON . The JSON string is normalized by sorting any dictionary keys . It will be on a single line without whitespace between elements . Args : py _ obj : object Any object that can be represented in ...
return json . dumps ( py_obj , sort_keys = True , separators = ( ',' , ':' ) , cls = ToJsonCompatibleTypes )
def _check_stop_conditions ( self , sensor_graph ) : """Check if any of our stop conditions are met . Args : sensor _ graph ( SensorGraph ) : The sensor graph we are currently simulating Returns : bool : True if we should stop the simulation"""
for stop in self . stop_conditions : if stop . should_stop ( self . tick_count , self . tick_count - self . _start_tick , sensor_graph ) : return True return False
def filename_sanitized ( self , extension , default_filename = 'file' ) : """Returns a filename that is safer to use on the filesystem . The filename will not contain a slash ( nor the path separator for the current platform , if different ) , it will not start with a dot , and it will have the expected exten...
assert extension assert extension [ 0 ] != '.' assert default_filename assert '.' not in default_filename extension = '.' + extension fname = self . filename_unsafe if fname is None : fname = default_filename fname = posixpath . basename ( fname ) fname = os . path . basename ( fname ) fname = fname . lstrip ( '.' ...
def normal ( self , t , i ) : """Handle normal chars ."""
current = [ ] if t == "\\" : try : t = next ( i ) current . extend ( self . reference ( t , i ) ) except StopIteration : current . append ( t ) elif t == "(" : current . extend ( self . subgroup ( t , i ) ) elif self . verbose and t == "#" : current . extend ( self . verbose_comm...
def parse_list_buckets ( data ) : """Parser for list buckets response . : param data : Response data for list buckets . : return : List of : class : ` Bucket < Bucket > ` ."""
root = S3Element . fromstring ( 'ListBucketsResult' , data ) return [ Bucket ( bucket . get_child_text ( 'Name' ) , bucket . get_localized_time_elem ( 'CreationDate' ) ) for buckets in root . findall ( 'Buckets' ) for bucket in buckets . findall ( 'Bucket' ) ]
def _validate_name ( name ) : """Pre - flight ` ` Bucket ` ` name validation . : type name : str or : data : ` NoneType ` : param name : Proposed bucket name . : rtype : str or : data : ` NoneType ` : returns : ` ` name ` ` if valid ."""
if name is None : return # The first and las characters must be alphanumeric . if not all ( [ name [ 0 ] . isalnum ( ) , name [ - 1 ] . isalnum ( ) ] ) : raise ValueError ( "Bucket names must start and end with a number or letter." ) return name
def domain_list ( gandi ) : """List domains manageable by REST API ."""
domains = gandi . dns . list ( ) for domain in domains : gandi . echo ( domain [ 'fqdn' ] ) return domains
def ising_to_qubo ( h , J , offset = 0.0 ) : """Convert an Ising problem to a QUBO problem . Map an Ising model defined on spins ( variables with { - 1 , + 1 } values ) to quadratic unconstrained binary optimization ( QUBO ) formulation : math : ` x ' Q x ` defined over binary variables ( 0 or 1 values ) , wh...
# the linear biases are the easiest q = { ( v , v ) : 2. * bias for v , bias in iteritems ( h ) } # next the quadratic biases for ( u , v ) , bias in iteritems ( J ) : if bias == 0.0 : continue q [ ( u , v ) ] = 4. * bias q [ ( u , u ) ] -= 2. * bias q [ ( v , v ) ] -= 2. * bias # finally calcul...
def query_quality ( self ) : """Overrides align . . warning : : this returns the full query quality , not just the aligned portion"""
if not self . entries . qual : return None if self . entries . qual == '*' : return None if self . check_flag ( 0x10 ) : return self . entries . qual [ : : - 1 ] return self . entries . qual
def predict ( self , v = None , X = None ) : """In classification this returns the classes , in regression it is equivalent to the decision function"""
if X is None : X = v v = None m = self . model ( v = v ) return m . predict ( X )
def create_host ( url = "local://local:6666/host" ) : '''This is the main function to create a new Host to which you can spawn actors . It will be set by default at local address if no parameter * url * is given , which would result in remote incomunication between hosts . This function shuould be called once...
if url in util . hosts . keys ( ) : raise HostError ( 'Host already created. Only one host can' + ' be ran with the same url.' ) else : if not util . hosts : util . main_host = Host ( url ) util . hosts [ url ] = util . main_host else : util . hosts [ url ] = Host ( url ) return ...
def get_bytes ( self ) : """client _ DH _ inner _ data # 6643b654 nonce : int128 server _ nonce : int128 retry _ id : long g _ b : string = Client _ DH _ Inner _ Data"""
ret = struct . pack ( "<I16s16sQ" , client_DH_inner_data . constructor , self . nonce , self . server_nonce , self . retry_id ) bytes_io = BytesIO ( ) bytes_io . write ( ret ) serialize_string ( bytes_io , self . g_b ) return bytes_io . getvalue ( )
def process_account ( self , message ) : """This is used for processing of account Updates . It will return instances of : class : bitshares . account . AccountUpdate `"""
self . on_account ( AccountUpdate ( message , blockchain_instance = self . blockchain ) )
def register ( coordinator ) : """Registers this module as a worker with the given coordinator ."""
timer_queue = Queue . Queue ( ) coordinator . register ( TimerItem , timer_queue ) coordinator . worker_threads . append ( TimerThread ( timer_queue , coordinator . input_queue ) )
def server_pxe ( ) : '''Configure server to PXE perform a one off PXE boot CLI Example : . . code - block : : bash salt dell drac . server _ pxe'''
if __execute_cmd ( 'config -g cfgServerInfo -o \ cfgServerFirstBootDevice PXE' ) : if __execute_cmd ( 'config -g cfgServerInfo -o cfgServerBootOnce 1' ) : return server_reboot else : log . warning ( 'failed to set boot order' ) return False log . warning ( 'failed to configur...
def to_dict ( self , fields = None ) : """Convert context to dict containing only builtin types . Args : fields ( list of str ) : If present , only write these fields into the dict . This can be used to avoid constructing expensive fields ( such as ' graph ' ) for some cases . Returns : dict : Dictified...
data = { } def _add ( field ) : return ( fields is None or field in fields ) if _add ( "resolved_packages" ) : resolved_packages = [ ] for pkg in ( self . _resolved_packages or [ ] ) : resolved_packages . append ( pkg . handle . to_dict ( ) ) data [ "resolved_packages" ] = resolved_packages if _...
def read_msgpack ( path_or_buf , encoding = 'utf-8' , iterator = False , ** kwargs ) : """Load msgpack pandas object from the specified file path THIS IS AN EXPERIMENTAL LIBRARY and the storage format may not be stable until a future release . Parameters path _ or _ buf : string File path , BytesIO like o...
path_or_buf , _ , _ , should_close = get_filepath_or_buffer ( path_or_buf ) if iterator : return Iterator ( path_or_buf ) def read ( fh ) : unpacked_obj = list ( unpack ( fh , encoding = encoding , ** kwargs ) ) if len ( unpacked_obj ) == 1 : return unpacked_obj [ 0 ] if should_close : t...
def user_password_requirements ( self , user_id , ** kwargs ) : "https : / / developer . zendesk . com / rest _ api / docs / core / users # get - a - list - of - password - requirements"
api_path = "/api/v2/users/{user_id}/password/requirements.json" api_path = api_path . format ( user_id = user_id ) return self . call ( api_path , ** kwargs )
def nestedPath ( path , depth , length ) : '''returns a nested version of ` basename ` , using the starting characters . For example : > > > NestedPathDatastore . nested _ path ( ' abcdefghijk ' , 3 , 2) ' ab / cd / ef ' > > > NestedPathDatastore . nested _ path ( ' abcdefghijk ' , 4 , 2) ' ab / cd / ef /...
components = [ path [ n : n + length ] for n in xrange ( 0 , len ( path ) , length ) ] components = components [ : depth ] return '/' . join ( components )
async def update_template_context ( self , context : dict ) -> None : """Update the provided template context . This adds additional context from the various template context processors . Arguments : context : The context to update ( mutate ) ."""
processors = self . template_context_processors [ None ] if has_request_context ( ) : blueprint = _request_ctx_stack . top . request . blueprint if blueprint is not None and blueprint in self . template_context_processors : processors = chain ( processors , self . template_context_processors [ blueprint...
def read_members ( self , container_id , query_membership = None ) : """ReadMembers . [ Preview API ] : param str container _ id : : param str query _ membership : : rtype : [ str ]"""
route_values = { } if container_id is not None : route_values [ 'containerId' ] = self . _serialize . url ( 'container_id' , container_id , 'str' ) query_parameters = { } if query_membership is not None : query_parameters [ 'queryMembership' ] = self . _serialize . query ( 'query_membership' , query_membership ...
def get_result ( self , decorated_function , * args , ** kwargs ) : """: meth : ` WCacheStorage . get _ result ` method implementation"""
try : return self . _storage [ decorated_function ] except KeyError as e : raise WCacheStorage . CacheMissedException ( 'No cache record found' ) from e
def _parse_varnishstat ( self , output , varnishstat_format , tags = None ) : """The text option ( - 1 ) is not reliable enough when counters get large . VBE . media _ video _ prd _ services _ 01(10.93.67.16 , , 8080 ) . happy18446744073709551615 2 types of data , " a " for counter ( " c " in newer versions of ...
tags = tags or [ ] # FIXME : this check is processing an unbounded amount of data # we should explicitly list the metrics we want to get from the check if varnishstat_format == "xml" : p = xml . parsers . expat . ParserCreate ( ) p . StartElementHandler = self . _start_element p . EndElementHandler = lambda...
def generate_samples ( self ) : """Generate training samples ( network inputs and outputs )"""
filenames = glob_all ( self . args . random_data_folder , '*.wav' ) shuffle ( filenames ) while True : for fn in filenames : for x , y in self . vectors_from_fn ( fn ) : yield x , y
def list_rbac_policies ( self , retrieve_all = True , ** _params ) : """Fetch a list of all RBAC policies for a project ."""
return self . list ( 'rbac_policies' , self . rbac_policies_path , retrieve_all , ** _params )
def join_sources ( source_module : DeploymentModule , contract_name : str ) : """Use join - contracts . py to concatenate all imported Solidity files . Args : source _ module : a module name to look up contracts _ source _ path ( ) contract _ name : ' TokenNetworkRegistry ' , ' SecretRegistry ' etc ."""
joined_file = Path ( __file__ ) . parent . joinpath ( 'joined.sol' ) remapping = { module : str ( path ) for module , path in contracts_source_path ( ) . items ( ) } command = [ './utils/join-contracts.py' , '--import-map' , json . dumps ( remapping ) , str ( contracts_source_path_of_deployment_module ( source_module ,...
def cmap_powerlaw_adjust ( cmap , a ) : """Returns a new colormap based on the one given but adjusted via power - law , ` newcmap = oldcmap * * a ` . : param cmap : colormap instance ( e . g . , cm . jet ) : param a : power"""
if a < 0. : return cmap cdict = copy . copy ( cmap . _segmentdata ) fn = lambda x : ( x [ 0 ] ** a , x [ 1 ] , x [ 2 ] ) for key in ( 'red' , 'green' , 'blue' ) : cdict [ key ] = map ( fn , cdict [ key ] ) cdict [ key ] . sort ( ) assert ( cdict [ key ] [ 0 ] < 0 or cdict [ key ] [ - 1 ] > 1 ) , "Result...
def taylor ( f , n = 2 , ** kwargs ) : """Taylor / Mclaurin polynomial aproximation for the given function . The ` ` n ` ` ( default 2 ) is the amount of aproximation terms for ` ` f ` ` . Other arguments are keyword - only and will be passed to the ` ` f . series ` ` method ."""
return sum ( Stream ( f . series ( n = None , ** kwargs ) ) . limit ( n ) )
def PopupError ( * args , button_color = DEFAULT_ERROR_BUTTON_COLOR , background_color = None , text_color = None , auto_close = False , auto_close_duration = None , non_blocking = False , icon = DEFAULT_WINDOW_ICON , line_width = None , font = None , no_titlebar = False , grab_anywhere = False , keep_on_top = False , ...
Popup ( * args , button_type = POPUP_BUTTONS_ERROR , background_color = background_color , text_color = text_color , non_blocking = non_blocking , icon = icon , line_width = line_width , button_color = button_color , auto_close = auto_close , auto_close_duration = auto_close_duration , font = font , no_titlebar = no_ti...
def find ( self , name ) : """Returns the extension pack with the specified name if found . in name of type str The name of the extension pack to locate . return return _ data of type : class : ` IExtPack ` The extension pack if found . raises : class : ` VBoxErrorObjectNotFound ` No extension pack matc...
if not isinstance ( name , basestring ) : raise TypeError ( "name can only be an instance of type basestring" ) return_data = self . _call ( "find" , in_p = [ name ] ) return_data = IExtPack ( return_data ) return return_data
def iget_batches ( task_ids , batch_size = 10 ) : """Yield out a map of the keys and futures in batches of the batch size passed in ."""
make_key = lambda _id : ndb . Key ( FuriousAsyncMarker , _id ) for keys in i_batch ( imap ( make_key , task_ids ) , batch_size ) : yield izip ( keys , ndb . get_multi_async ( keys ) )
def callback ( val , schema , name = None ) : # pylint : disable - msg = W0613 """! ~ ~ callback ( function )"""
if name is None : name = schema if not _callbacks . has_key ( name ) : return False return _callbacks [ name ] ( val )
def entry_breadcrumbs ( entry ) : """Breadcrumbs for an Entry ."""
date = entry . publication_date if is_aware ( date ) : date = localtime ( date ) return [ year_crumb ( date ) , month_crumb ( date ) , day_crumb ( date ) , Crumb ( entry . title ) ]
def _verify_part_size ( self ) : """Verifies that the part size is smaller then the maximum part size which is 5GB ."""
if self . _part_size > PartSize . MAXIMUM_UPLOAD_SIZE : self . _status = TransferState . FAILED raise SbgError ( 'Part size = {}b. Maximum part size is {}b' . format ( self . _part_size , PartSize . MAXIMUM_UPLOAD_SIZE ) )
def U ( Document , __raw__ = None , ** update ) : """Generate a MongoDB update document through paramater interpolation . Arguments passed by name have their name interpreted as an optional operation prefix ( defaulting to ` set ` , e . g . ` push ` ) , a double - underscore separated field reference ( e . g . ...
ops = Update ( __raw__ ) args = _process_arguments ( Document , UPDATE_ALIASES , { } , update , UPDATE_PASSTHROUGH ) for operation , _ , field , value in args : if not operation : operation = DEFAULT_UPDATE if isinstance ( operation , tuple ) : operation , cast = ( '$' + operation [ 0 ] ) , oper...
def identical_blocks ( self ) : """: return A list of all block matches that appear to be identical"""
identical_blocks = [ ] for ( func_a , func_b ) in self . function_matches : identical_blocks . extend ( self . get_function_diff ( func_a , func_b ) . identical_blocks ) return identical_blocks
def _get_struct_fillstyle ( self , shape_number ) : """Get the values for the FILLSTYLE record ."""
obj = _make_object ( "FillStyle" ) obj . FillStyleType = style_type = unpack_ui8 ( self . _src ) if style_type == 0x00 : if shape_number <= 2 : obj . Color = self . _get_struct_rgb ( ) else : obj . Color = self . _get_struct_rgba ( ) if style_type in ( 0x10 , 0x12 , 0x13 ) : obj . GradientMa...
def update_weights ( self , x , y ) : """Weight updates as described in the Földiák ' s paper ."""
m = self . _inputSize n = self . _outputSize W = self . _W Q = self . _Q t = self . _t alpha = self . _alpha beta = self . _beta gamma = self . _gamma p = self . _p for i in range ( n ) : for j in range ( n ) : Delta_W = - alpha * ( y [ i ] * y [ j ] - p * p ) W [ i , j ] += Delta_W if i == ...
def call ( self , uri , * args , ** kwargs ) : """Sends a RPC request to the WAMP server"""
if self . _state == STATE_DISCONNECTED : raise Exception ( "WAMP is currently disconnected!" ) options = { 'disclose_me' : True } uri = self . get_full_uri ( uri ) message = self . send_and_await_response ( CALL ( options = options , procedure = uri , args = args , kwargs = kwargs ) ) if message == WAMP_RESULT : ...
def finalize_structure ( self ) : """Any functions needed to cleanup the structure ."""
self . group_list . append ( self . current_group ) group_set = get_unique_groups ( self . group_list ) for item in self . group_list : self . group_type_list . append ( group_set . index ( item ) ) self . group_list = [ x . convert_to_dict ( ) for x in group_set ]
def tickets_update_many ( self , data , ids = None , ** kwargs ) : "https : / / developer . zendesk . com / rest _ api / docs / core / tickets # update - many - tickets"
api_path = "/api/v2/tickets/update_many.json" api_query = { } if "query" in kwargs . keys ( ) : api_query . update ( kwargs [ "query" ] ) del kwargs [ "query" ] if ids : api_query . update ( { "ids" : ids , } ) return self . call ( api_path , query = api_query , method = "PUT" , data = data , ** kwargs )
def format_date ( self , date : Union [ int , float , datetime . datetime ] , gmt_offset : int = 0 , relative : bool = True , shorter : bool = False , full_format : bool = False , ) -> str : """Formats the given date ( which should be GMT ) . By default , we return a relative time ( e . g . , " 2 minutes ago " ) ...
if isinstance ( date , ( int , float ) ) : date = datetime . datetime . utcfromtimestamp ( date ) now = datetime . datetime . utcnow ( ) if date > now : if relative and ( date - now ) . seconds < 60 : # Due to click skew , things are some things slightly # in the future . Round timestamps in the immediate ...
def mount ( self ) : """Mounts the sftp system if it ' s not already mounted ."""
if self . mounted : return self . _mount_point_local_create ( ) if len ( self . system . mount_opts ) == 0 : sshfs_opts = "" else : sshfs_opts = " -o %s" % " -o " . join ( self . system . mount_opts ) if self . system . auth_method == self . system . AUTH_METHOD_PUBLIC_KEY : ssh_opts = '-o PreferredAuth...
def _add_new_state ( self , * event , ** kwargs ) : """Triggered when shortcut keys for adding a new state are pressed , or Menu Bar " Edit , Add State " is clicked . Adds a new state only if the the state machine tree is in focus ."""
if react_to_event ( self . view , self . view [ 'state_machine_tree_view' ] , event ) : state_type = StateType . EXECUTION if 'state_type' not in kwargs else kwargs [ 'state_type' ] gui_helper_state_machine . add_new_state ( self . _selected_sm_model , state_type ) return True
def plot_pipeline ( self , pipeline , * args , ** kwargs ) : '''Plots the light curve for the target de - trended with a given pipeline . : param str pipeline : The name of the pipeline ( lowercase ) . Options are ' everest2 ' , ' everest1 ' , and other mission - specific pipelines . For ` K2 ` , the available pi...
if pipeline != 'everest2' : return getattr ( missions , self . mission ) . pipelines . plot ( self . ID , pipeline , * args , ** kwargs ) else : # We ' re going to plot the everest 2 light curve like we plot # the other pipelines for easy comparison plot_raw = kwargs . get ( 'plot_raw' , False ) plot_cbv = ...
def split ( txt , seps ) : """Splits a text in a meaningful list of words based on a list of word separators ( define in pyqode . core . settings ) : param txt : Text to split : param seps : List of words separators : return : A * * set * * of words found in the document ( excluding punctuations , numbers...
# replace all possible separators with a default sep default_sep = seps [ 0 ] for sep in seps [ 1 : ] : if sep : txt = txt . replace ( sep , default_sep ) # now we can split using the default _ sep raw_words = txt . split ( default_sep ) words = set ( ) for word in raw_words : # w = w . strip ( ) if wor...
def execute_java_for_coverage ( self , targets , * args , ** kwargs ) : """Execute java for targets directly and don ' t use the test mixin . This execution won ' t be wrapped with timeouts and other test mixin code common across test targets . Used for coverage instrumentation ."""
distribution = self . preferred_jvm_distribution_for_targets ( targets ) actual_executor = SubprocessExecutor ( distribution ) return distribution . execute_java ( * args , executor = actual_executor , ** kwargs )
def reset_to_flows ( self , force = False , _meta = None ) : """Keeps only the absolute values . This removes all attributes which can not be aggregated and must be recalculated after the aggregation . Parameters force : boolean , optional If True , reset to flows although the system can not be recalcul...
# Development note : The attributes which should be removed are # defined in self . _ _ non _ agg _ attributes _ _ strwarn = None for df in self . __basic__ : if ( getattr ( self , df ) ) is None : if force : strwarn = ( "Reset system warning - Recalculation after " "reset not possible " "becaus...
def findObjects ( pixels , values , nside , zvalues , rev , good ) : """Characterize labelled candidates in a multi - dimensional HEALPix map . Parameters : values : ( Sparse ) HEALPix array of data values nside : HEALPix dimensionality pixels : Pixel values associated to ( sparse ) HEALPix array zvalues ...
ngood = len ( good ) objs = numpy . recarray ( ( ngood , ) , dtype = [ ( 'LABEL' , 'i4' ) , ( 'NPIX' , 'i4' ) , ( 'VAL_MAX' , 'f4' ) , ( 'IDX_MAX' , 'i4' ) , ( 'ZIDX_MAX' , 'i4' ) , ( 'PIX_MAX' , 'i4' ) , ( 'X_MAX' , 'f4' ) , ( 'Y_MAX' , 'f4' ) , ( 'Z_MAX' , 'f4' ) , ( 'X_CENT' , 'f4' ) , ( 'Y_CENT' , 'f4' ) , ( 'Z_CEN...
def add_node ( self , node ) : """Add given node to the hypergraph . @ attention : While nodes can be of any type , it ' s strongly recommended to use only numbers and single - line strings as node identifiers if you intend to use write ( ) . @ type node : node @ param node : Node identifier ."""
if ( not node in self . node_links ) : self . node_links [ node ] = [ ] self . node_attr [ node ] = [ ] self . graph . add_node ( ( node , 'n' ) ) else : raise AdditionError ( "Node %s already in graph" % node )
def _to_array ( value ) : """As a convenience , turn Python lists and tuples into NumPy arrays ."""
if isinstance ( value , ( tuple , list ) ) : return array ( value ) elif isinstance ( value , ( float , int ) ) : return np . float64 ( value ) else : return value
def _len_lcs ( x , y ) : """Returns the length of the Longest Common Subsequence between two seqs . Source : http : / / www . algorithmist . com / index . php / Longest _ Common _ Subsequence Args : x : sequence of words y : sequence of words Returns integer : Length of LCS between x and y"""
table = _lcs ( x , y ) n , m = len ( x ) , len ( y ) return table [ n , m ]
def export_domain ( self , domain ) : """Provides the BIND ( Berkeley Internet Name Domain ) 9 formatted contents of the requested domain . This call is for a single domain only , and as such , does not provide subdomain information . Sample export : { u ' accountId ' : 00000, u ' contentType ' : u ' BIND...
uri = "/domains/%s/export" % utils . get_id ( domain ) resp , resp_body = self . _async_call ( uri , method = "GET" , error_class = exc . NotFound ) return resp_body . get ( "contents" , "" )
def compress ( obj ) : """Outputs json without whitespace ."""
return json . dumps ( obj , sort_keys = True , separators = ( ',' , ':' ) , cls = CustomEncoder )
def crop ( self , minimum_address , maximum_address ) : """Keep given range and discard the rest . ` minimum _ address ` is the first word address to keep ( including ) . ` maximum _ address ` is the last word address to keep ( excluding ) ."""
minimum_address *= self . word_size_bytes maximum_address *= self . word_size_bytes maximum_address_address = self . _segments . maximum_address self . _segments . remove ( 0 , minimum_address ) self . _segments . remove ( maximum_address , maximum_address_address )
def session_exists ( self , username ) : """: param username : : type username : str : return : : rtype :"""
logger . debug ( "session_exists(%s)?" % username ) return self . _store . containsSession ( username , 1 )
def ref_argument ( bound_args , address ) : """Taking a bound _ args object , and an ArgumentAddress , retrieves the data currently stored in bound _ args for this particular address ."""
if address . kind == ArgumentKind . regular : return bound_args . arguments [ address . name ] return bound_args . arguments [ address . name ] [ address . key ]
def unregister_listener ( self , listener ) : """Remove a listener callback added with register _ listener ( ) . Parameters listener : function Reference to the callback function that should be removed"""
listener_id = hashable_identity ( listener ) self . _listeners . pop ( listener_id , None )
def check_required_fields ( method , uri , body , field_names ) : """Check required fields in the request body . Raises : BadRequestError with reason 3 : Missing request body BadRequestError with reason 5 : Missing required field in request body"""
# Check presence of request body if body is None : raise BadRequestError ( method , uri , reason = 3 , message = "Missing request body" ) # Check required input fields for field_name in field_names : if field_name not in body : raise BadRequestError ( method , uri , reason = 5 , message = "Missing requi...
def params_as_tensors_for ( * objs , convert = True ) : """Context manager which changes the representation of parameters and data holders for the specific parameterized object ( s ) . This can also be used to turn off tensor conversion functions wrapped with ` params _ as _ tensors ` : @ gpflow . params _ ...
objs = set ( objs ) # remove duplicate objects so the tensor mode won ' t be changed before saving prev_values = [ _params_as_tensors_enter ( o , convert ) for o in objs ] try : yield finally : for o , pv in reversed ( list ( zip ( objs , prev_values ) ) ) : _params_as_tensors_exit ( o , pv )
def scrubID ( ID ) : """: param ID : An ID that can be of various types , this is very kludgy : returns : An integer ID"""
try : if type ( ID ) == list : return int ( ID [ 0 ] ) elif type ( ID ) == str : return int ( ID ) elif type ( ID ) == int : return ID elif type ( ID ) == unicode : return int ( ID ) except ValueError : return None
def filename ( self ) : """Returns the provided data as a file location ."""
if self . _filename : return self . _filename else : with tempfile . NamedTemporaryFile ( delete = False ) as f : f . write ( self . _bytes ) return f . name
def obj_tpr ( result , reference , connectivity = 1 ) : """The true positive rate of distinct binary object detection . The true positive rates gives a percentage measure of how many distinct binary objects in the first array also exists in the second array . A partial overlap ( of minimum one voxel ) is here...
_ , _ , n_obj_result , _ , mapping = __distinct_binary_object_correspondences ( reference , result , connectivity ) return len ( mapping ) / float ( n_obj_result )
def __load ( fh , mode = MODE_AUTO ) : """Load Mesh from STL file : param FileIO fh : The file handle to open : param int mode : The mode to open , default is : py : data : ` AUTOMATIC ` . : return :"""
header = fh . read ( Stl . HEADER_SIZE ) . lower ( ) name = "" data = None if not header . strip ( ) : return if mode in ( Stl . MODE_AUTO , Stl . MODE_ASCII ) and header . startswith ( 'solid' ) : try : name = header . split ( '\n' , 1 ) [ 0 ] [ : 5 ] . strip ( ) data = Stl . __load_ascii ( fh ...
def save ( self , force_insert = False ) : """Save the model and any related many - to - many fields . : param force _ insert : Should the save force an insert ? : return : Number of rows impacted , or False ."""
delayed = { } for field , value in self . data . items ( ) : model_field = getattr ( type ( self . instance ) , field , None ) # If this is a many - to - many field , we cannot save it to the instance until the instance # is saved to the database . Collect these fields and delay the setting until after ...
def swipe ( self , x1 , y1 , x2 , y2 , duration = 0 ) : """Args : duration ( float ) : start coordinate press duration ( seconds ) [ [ FBRoute POST : @ " / wda / dragfromtoforduration " ] respondWithTarget : self action : @ selector ( handleDragCoordinate : ) ] ,"""
data = dict ( fromX = x1 , fromY = y1 , toX = x2 , toY = y2 , duration = duration ) return self . http . post ( '/wda/dragfromtoforduration' , data = data )
def fit_autocorrelation ( autocorrelation , time , GammaGuess , TrapFreqGuess = None , method = 'energy' , MakeFig = True , show_fig = True ) : """Fits exponential relaxation theory to data . Parameters autocorrelation : array array containing autocorrelation to be fitted time : array array containing the...
datax = time datay = autocorrelation method = method . lower ( ) if method == 'energy' : p0 = _np . array ( [ GammaGuess ] ) Params_Fit , Params_Fit_Err = fit_curvefit ( p0 , datax , datay , _energy_autocorrelation_fitting_eqn ) autocorrelation_fit = _energy_autocorrelation_fitting_eqn ( _np . arange ( 0 , ...
def get_or_create ( self , ** kwargs ) : """Looks up an object with the given kwargs , creating one if necessary . Returns a tuple of ( object , created ) , where created is a boolean specifying whether an object was created ."""
model = self . get ( ** kwargs ) is_created = False if model is None : is_created = True model = self . _model_class ( ) for key , value in list ( kwargs . items ( ) ) : setattr ( model , key , value ) return model , is_created
def create ( self , name , ** kwargs ) : '''Create a dataset , including the field types . Optionally , specify args such as : description : description of the dataset columns : list of columns ( see docs / tests for list structure ) category : must exist in / admin / metadata tags : list of tag strings r...
new_backend = kwargs . pop ( "new_backend" , False ) resource = _format_old_api_request ( content_type = "json" ) if new_backend : resource += "?nbe=true" payload = { "name" : name } if "row_identifier" in kwargs : payload [ "metadata" ] = { "rowIdentifier" : kwargs . pop ( "row_identifier" , None ) } payload ....
def Magic ( self ) : # self . view . setFixedSize ( self . width ( ) , self . width ( ) ) self . WholeData = [ ] self . x_scale = self . width_plot / self . width_load self . y_scale = self . height_plot / self . height_load self . z_scale = self . depth_plot / self . depth_load # print ( self . x _...
# xgrid . setTransform ( xmean , ymean , zmean ) self . view . addItem ( xgrid ) self . view . addItem ( ygrid ) self . view . addItem ( zgrid ) self . view . addItem ( ThreeDimView )
def first ( self ) : """First chunk"""
return self . values [ tuple ( zeros ( len ( self . values . shape ) ) ) ]
def call ( conn = None , call = None , kwargs = None ) : '''Call function from shade . func function to call from shade . openstackcloud library CLI Example . . code - block : : bash salt - cloud - f call myopenstack func = list _ images t sujksalt - cloud - f call myopenstack func = create _ network na...
if call == 'action' : raise SaltCloudSystemExit ( 'The call function must be called with ' '-f or --function.' ) if 'func' not in kwargs : raise SaltCloudSystemExit ( 'No `func` argument passed' ) if conn is None : conn = get_conn ( ) func = kwargs . pop ( 'func' ) for key , value in kwargs . items ( ) : ...