idx int64 0 63k | question stringlengths 53 5.28k | target stringlengths 5 805 |
|---|---|---|
34,400 | def mode_readable ( self ) : ret = "" mode = self . _raw_mode if mode . MANUAL : ret = "manual" if self . target_temperature < self . min_temp : ret += " off" elif self . target_temperature >= self . max_temp : ret += " on" else : ret += " (%sC)" % self . target_temperature else : ret = "auto" if mode . AWAY : ret += "... | Return a readable representation of the mode .. |
34,401 | def boost ( self , boost ) : _LOGGER . debug ( "Setting boost mode: %s" , boost ) value = struct . pack ( 'BB' , PROP_BOOST , bool ( boost ) ) self . _conn . make_request ( PROP_WRITE_HANDLE , value ) | Sets boost mode . |
34,402 | def window_open_config ( self , temperature , duration ) : _LOGGER . debug ( "Window open config, temperature: %s duration: %s" , temperature , duration ) self . _verify_temperature ( temperature ) if duration . seconds < 0 and duration . seconds > 3600 : raise ValueError value = struct . pack ( 'BBB' , PROP_WINDOW_OPE... | Configures the window open behavior . The duration is specified in 5 minute increments . |
34,403 | def locked ( self , lock ) : _LOGGER . debug ( "Setting the lock: %s" , lock ) value = struct . pack ( 'BB' , PROP_LOCK , bool ( lock ) ) self . _conn . make_request ( PROP_WRITE_HANDLE , value ) | Locks or unlocks the thermostat . |
34,404 | def temperature_offset ( self , offset ) : _LOGGER . debug ( "Setting offset: %s" , offset ) if offset < - 3.5 or offset > 3.5 : raise TemperatureException ( "Invalid value: %s" % offset ) current = - 3.5 values = { } for i in range ( 15 ) : values [ current ] = i current += 0.5 value = struct . pack ( 'BB' , PROP_OFFS... | Sets the thermostat s temperature offset . |
34,405 | def _init_socket ( self ) : try : self . _connection = socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) self . _connection . connect ( ( self . host , self . port ) ) self . _connection . settimeout ( self . timeout ) self . _connection_file = self . _connection . makefile ( 'b' ) except : self . _connection... | Initialises the socket used for communicating with a q service |
34,406 | def close ( self ) : if self . _connection : self . _connection_file . close ( ) self . _connection_file = None self . _connection . close ( ) self . _connection = None | Closes connection with the q service . |
34,407 | def _initialize ( self ) : credentials = ( self . username if self . username else '' ) + ':' + ( self . password if self . password else '' ) credentials = credentials . encode ( self . _encoding ) self . _connection . send ( credentials + b'\3\0' ) response = self . _connection . recv ( 1 ) if len ( response ) != 1 :... | Performs a IPC protocol handshake . |
34,408 | def qlist ( array , adjust_dtype = True , ** meta ) : if type ( array ) in ( list , tuple ) : if meta and 'qtype' in meta and meta [ 'qtype' ] == QGENERAL_LIST : tarray = numpy . ndarray ( shape = len ( array ) , dtype = numpy . dtype ( 'O' ) ) for i in range ( len ( array ) ) : tarray [ i ] = array [ i ] array = tarra... | Converts an input array to q vector and enriches object instance with meta data . |
34,409 | def parse_url ( url , warning = True ) : parsed = urllib_parse . urlparse ( url ) query = urllib_parse . parse_qs ( parsed . query ) is_gdrive = parsed . hostname == 'drive.google.com' is_download_link = parsed . path . endswith ( '/uc' ) file_id = None if is_gdrive and 'id' in query : file_ids = query [ 'id' ] if len ... | Parse URLs especially for Google Drive links . |
34,410 | def extractall ( path , to = None ) : if to is None : to = osp . dirname ( path ) if path . endswith ( '.zip' ) : opener , mode = zipfile . ZipFile , 'r' elif path . endswith ( '.tar' ) : opener , mode = tarfile . open , 'r' elif path . endswith ( '.tar.gz' ) or path . endswith ( '.tgz' ) : opener , mode = tarfile . op... | Extract archive file . |
34,411 | def _add_word ( completer ) : def inner ( word : str ) : completer . words . add ( word ) return inner | Used to add words to the completors |
34,412 | def _remove_word ( completer ) : def inner ( word : str ) : try : completer . words . remove ( word ) except Exception : pass return inner | Used to remove words from the completors |
34,413 | def set_info ( self , * args , ** kwargs ) -> None : self . root_logger . setLevel ( logging . INFO ) try : self . messaging . pub_handler . setLevel ( logging . INFO ) except Exception : pass | Sets the log level to INFO |
34,414 | def do_REMOTE ( self , target : str , remote_command : str , source : list , * args , ** kwargs ) -> None : if target == self . messaging . _service_name : info = 'target for remote command is the bot itself! Returning the function' self . logger . info ( info ) return self . _handle_command ( remote_command , source ,... | Send a remote command to a service . Used |
34,415 | def do_IDENT ( self , service_name : str , source : list , * args , ** kwargs ) -> None : self . logger . info ( ' IDENT %s as %s' , service_name , source ) self . messaging . _address_map [ service_name ] = source | Perform identification of a service to a binary representation . |
34,416 | def _name_helper ( name : str ) : name = name . rstrip ( ) if name . endswith ( ( '.service' , '.socket' , '.target' ) ) : return name return name + '.service' | default to returning a name with . service |
34,417 | def get_vexbot_certificate_filepath ( ) -> ( str , bool ) : public_filepath , secret_filepath = _certificate_helper ( 'vexbot.key' , 'vexbot.key_secret' ) if path . isfile ( secret_filepath ) : return secret_filepath , True if not path . isfile ( public_filepath ) : err = ( 'certificates not found. Generate certificate... | Returns the vexbot certificate filepath and the whether it is the private filepath or not |
34,418 | def get_code ( self , * args , ** kwargs ) : callback = self . _commands [ args [ 0 ] ] source = _inspect . getsourcelines ( callback ) [ 0 ] return "\n" + "" . join ( source ) | get the python source code from callback |
34,419 | def _get_state ( self ) -> None : if self . last_message is None : return uuid = self . last_message . uuid if uuid != self . _last_bot_uuid : self . logger . info ( ' UUID message mismatch' ) self . logger . debug ( ' Old UUID: %s | New UUID: %s' , self . _last_bot_uuid , uuid ) self . send_identity ( ) self . _last_b... | Internal method that accomplishes checking to make sure that the UUID has not changed |
34,420 | def send_identity ( self ) : service_name = { 'service_name' : self . messaging . _service_name } service_name = _json . dumps ( service_name ) . encode ( 'utf8' ) identify_frame = ( b'' , b'IDENT' , _json . dumps ( [ ] ) . encode ( 'utf8' ) , service_name ) if self . messaging . _run_control_loop : send = self . messa... | Send the identity of the service . |
34,421 | def _config_convert_to_address_helper ( self ) -> None : to_address = self . _socket_factory . to_address for k , v in self . config . items ( ) : if k == 'chatter_subscription_port' : continue if k . endswith ( 'port' ) : self . config [ k ] = to_address ( v ) | converts the config from ports to zmq ip addresses Operates on self . config using self . _socket_factory . to_address |
34,422 | def add_callback ( self , callback : _Callable , * args , ** kwargs ) -> None : self . loop . add_callback ( callback , * args , ** kwargs ) | Add a callback to the event loop |
34,423 | def start ( self ) -> None : self . _setup ( ) if self . _run_control_loop : asyncio . set_event_loop ( asyncio . new_event_loop ( ) ) self . _heartbeat_reciever . start ( ) self . _logger . info ( ' Start Loop' ) return self . loop . start ( ) else : self . _logger . debug ( ' run_control_loop == False' ) | Start the internal control loop . Potentially blocking depending on the value of _run_control_loop set by the initializer . |
34,424 | def send_command ( self , command : str , * args , ** kwargs ) : info = 'send command `%s` to bot. Args: %s | Kwargs: %s' self . _messaging_logger . command . info ( info , command , args , kwargs ) command = command . encode ( 'utf8' ) args = _json . dumps ( args ) . encode ( 'utf8' ) kwargs = _json . dumps ( kwargs )... | For request bot to perform some action |
34,425 | def to_address ( self , port : str ) : if isinstance ( port , str ) and len ( port ) > 6 : return port zmq_address = '{}://{}:{}' return zmq_address . format ( self . protocol , self . address , port ) | transforms the ports into addresses . Will fall through if the port looks like an address |
34,426 | def iterate_multiple_addresses ( self , ports : ( str , list , tuple ) ) : if isinstance ( ports , ( str , int ) ) : ports = tuple ( ports , ) result = [ ] for port in ports : result . append ( self . to_address ( port ) ) return result | transforms an iterable or the expectation of an iterable into zmq addresses |
34,427 | def is_command ( self , text : str ) -> bool : if text [ 0 ] in self . shebangs : return True return False | checks for presence of shebang in the first character of the text |
34,428 | def _handle_text ( self , text : str ) : if self . is_command ( text ) : self . _logger . debug ( ' first word is a command' ) command , args , kwargs = _get_cmd_args_kwargs ( text ) self . _logger . info ( ' command: %s, %s %s' , command , args , kwargs ) result = self . _handle_command ( command , args , kwargs ) if ... | Check to see if text is a command . Otherwise check to see if the second word is a command . |
34,429 | def _first_word_not_cmd ( self , first_word : str , command : str , args : tuple , kwargs : dict ) -> None : if self . service_interface . is_service ( first_word ) : self . _logger . debug ( ' first word is a service' ) kwargs = self . service_interface . get_metadata ( first_word , kwargs ) self . _logger . debug ( '... | check to see if this is an author or service . This method does high level control handling |
34,430 | def _sentence_to_features ( self , sentence : list ) : sentence_features = [ ] prefixes = ( '-1' , '0' , '+1' ) for word_idx in range ( len ( sentence ) ) : word_features = { } for i in range ( 3 ) : if word_idx == len ( sentence ) - 1 and i == 2 : word_features [ 'EOS' ] = True elif word_idx == 0 and i == 0 : word_fea... | Convert a word into discrete features in self . crf_features including word before and word after . |
34,431 | def find_template_companion ( template , extension = '' , check = True ) : if check and not os . path . isfile ( template ) : yield '' return template = os . path . abspath ( template ) template_dirname = os . path . dirname ( template ) template_basename = os . path . basename ( template ) . split ( '.' ) current_path... | Returns the first found template companion file |
34,432 | def from_element ( self , element , defaults = { } ) : if isinstance ( defaults , SvdElement ) : defaults = vars ( defaults ) for key in self . props : try : value = element . find ( key ) . text except AttributeError : default = defaults [ key ] if key in defaults else None value = element . get ( key , default ) if v... | Populate object variables from SVD element |
34,433 | def fold ( self ) : if self . dim is None : return [ self ] if self . name . endswith ( "[%s]" ) : self . name = self . name . replace ( "%s" , str ( self . dim ) ) return [ self ] registers = [ ] for offset , index in enumerate ( self . dimIndex ) : reg = self . copy ( ) reg . name = self . name . replace ( "%s" , str... | Folds the Register in accordance with it s dimensions . |
34,434 | def get_tc_device ( self ) : if self . direction == TrafficDirection . OUTGOING : return self . device if self . direction == TrafficDirection . INCOMING : return self . ifb_device raise ParameterError ( "unknown direction" , expected = TrafficDirection . LIST , value = self . direction ) | Return a device name that associated network communication direction . |
34,435 | def delete_tc ( self ) : rule_finder = TcShapingRuleFinder ( logger = logger , tc = self ) filter_param = rule_finder . find_filter_param ( ) if not filter_param : message = "shaping rule not found ({})." . format ( rule_finder . get_filter_string ( ) ) if rule_finder . is_empty_filter_condition ( ) : message += " you ... | Delete a specific shaping rule . |
34,436 | def request ( identifier , namespace = 'cid' , domain = 'compound' , operation = None , output = 'JSON' , searchtype = None , ** kwargs ) : if not identifier : raise ValueError ( 'identifier/cid cannot be None' ) if isinstance ( identifier , int ) : identifier = str ( identifier ) if not isinstance ( identifier , text_... | Construct API request from parameters and return the response . |
34,437 | def get ( identifier , namespace = 'cid' , domain = 'compound' , operation = None , output = 'JSON' , searchtype = None , ** kwargs ) : if ( searchtype and searchtype != 'xref' ) or namespace in [ 'formula' ] : response = request ( identifier , namespace , domain , None , 'JSON' , searchtype , ** kwargs ) . read ( ) st... | Request wrapper that automatically handles async requests . |
34,438 | def get_json ( identifier , namespace = 'cid' , domain = 'compound' , operation = None , searchtype = None , ** kwargs ) : try : return json . loads ( get ( identifier , namespace , domain , operation , 'JSON' , searchtype , ** kwargs ) . decode ( ) ) except NotFoundError as e : log . info ( e ) return None | Request wrapper that automatically parses JSON response and supresses NotFoundError . |
34,439 | def get_sdf ( identifier , namespace = 'cid' , domain = 'compound' , operation = None , searchtype = None , ** kwargs ) : try : return get ( identifier , namespace , domain , operation , 'SDF' , searchtype , ** kwargs ) . decode ( ) except NotFoundError as e : log . info ( e ) return None | Request wrapper that automatically parses SDF response and supresses NotFoundError . |
34,440 | def get_compounds ( identifier , namespace = 'cid' , searchtype = None , as_dataframe = False , ** kwargs ) : results = get_json ( identifier , namespace , searchtype = searchtype , ** kwargs ) compounds = [ Compound ( r ) for r in results [ 'PC_Compounds' ] ] if results else [ ] if as_dataframe : return compounds_to_f... | Retrieve the specified compound records from PubChem . |
34,441 | def get_substances ( identifier , namespace = 'sid' , as_dataframe = False , ** kwargs ) : results = get_json ( identifier , namespace , 'substance' , ** kwargs ) substances = [ Substance ( r ) for r in results [ 'PC_Substances' ] ] if results else [ ] if as_dataframe : return substances_to_frame ( substances ) return ... | Retrieve the specified substance records from PubChem . |
34,442 | def get_assays ( identifier , namespace = 'aid' , ** kwargs ) : results = get_json ( identifier , namespace , 'assay' , 'description' , ** kwargs ) return [ Assay ( r ) for r in results [ 'PC_AssayContainer' ] ] if results else [ ] | Retrieve the specified assay records from PubChem . |
34,443 | def get_properties ( properties , identifier , namespace = 'cid' , searchtype = None , as_dataframe = False , ** kwargs ) : if isinstance ( properties , text_types ) : properties = properties . split ( ',' ) properties = ',' . join ( [ PROPERTY_MAP . get ( p , p ) for p in properties ] ) properties = 'property/%s' % pr... | Retrieve the specified properties from PubChem . |
34,444 | def deprecated ( message = None ) : def deco ( func ) : @ functools . wraps ( func ) def wrapped ( * args , ** kwargs ) : warnings . warn ( message or 'Call to deprecated function {}' . format ( func . __name__ ) , category = PubChemPyDeprecationWarning , stacklevel = 2 ) return func ( * args , ** kwargs ) return wrapp... | Decorator to mark functions as deprecated . A warning will be emitted when the function is used . |
34,445 | def _parse_prop ( search , proplist ) : props = [ i for i in proplist if all ( item in i [ 'urn' ] . items ( ) for item in search . items ( ) ) ] if len ( props ) > 0 : return props [ 0 ] [ 'value' ] [ list ( props [ 0 ] [ 'value' ] . keys ( ) ) [ 0 ] ] | Extract property value from record using the given urn search filter . |
34,446 | def to_dict ( self ) : data = { 'aid' : self . aid , 'number' : self . number , 'element' : self . element } for coord in { 'x' , 'y' , 'z' } : if getattr ( self , coord ) is not None : data [ coord ] = getattr ( self , coord ) if self . charge is not 0 : data [ 'charge' ] = self . charge return data | Return a dictionary containing Atom data . |
34,447 | def set_coordinates ( self , x , y , z = None ) : self . x = x self . y = y self . z = z | Set all coordinate dimensions at once . |
34,448 | def to_dict ( self ) : data = { 'aid1' : self . aid1 , 'aid2' : self . aid2 , 'order' : self . order } if self . style is not None : data [ 'style' ] = self . style return data | Return a dictionary containing Bond data . |
34,449 | def _setup_atoms ( self ) : self . _atoms = { } aids = self . record [ 'atoms' ] [ 'aid' ] elements = self . record [ 'atoms' ] [ 'element' ] if not len ( aids ) == len ( elements ) : raise ResponseParseError ( 'Error parsing atom elements' ) for aid , element in zip ( aids , elements ) : self . _atoms [ aid ] = Atom (... | Derive Atom objects from the record . |
34,450 | def _setup_bonds ( self ) : self . _bonds = { } if 'bonds' not in self . record : return aid1s = self . record [ 'bonds' ] [ 'aid1' ] aid2s = self . record [ 'bonds' ] [ 'aid2' ] orders = self . record [ 'bonds' ] [ 'order' ] if not len ( aid1s ) == len ( aid2s ) == len ( orders ) : raise ResponseParseError ( 'Error pa... | Derive Bond objects from the record . |
34,451 | def from_cid ( cls , cid , ** kwargs ) : record = json . loads ( request ( cid , ** kwargs ) . read ( ) . decode ( ) ) [ 'PC_Compounds' ] [ 0 ] return cls ( record ) | Retrieve the Compound record for the specified CID . |
34,452 | def to_dict ( self , properties = None ) : if not properties : skip = { 'aids' , 'sids' , 'synonyms' } properties = [ p for p in dir ( Compound ) if isinstance ( getattr ( Compound , p ) , property ) and p not in skip ] return { p : [ i . to_dict ( ) for i in getattr ( self , p ) ] if p in { 'atoms' , 'bonds' } else ge... | Return a dictionary containing Compound data . Optionally specify a list of the desired properties . |
34,453 | def synonyms ( self ) : if self . cid : results = get_json ( self . cid , operation = 'synonyms' ) return results [ 'InformationList' ] [ 'Information' ] [ 0 ] [ 'Synonym' ] if results else [ ] | A ranked list of all the names associated with this Compound . |
34,454 | def from_sid ( cls , sid ) : record = json . loads ( request ( sid , 'sid' , 'substance' ) . read ( ) . decode ( ) ) [ 'PC_Substances' ] [ 0 ] return cls ( record ) | Retrieve the Substance record for the specified SID . |
34,455 | def to_dict ( self , properties = None ) : if not properties : skip = { 'deposited_compound' , 'standardized_compound' , 'cids' , 'aids' } properties = [ p for p in dir ( Substance ) if isinstance ( getattr ( Substance , p ) , property ) and p not in skip ] return { p : getattr ( self , p ) for p in properties } | Return a dictionary containing Substance data . |
34,456 | def from_aid ( cls , aid ) : record = json . loads ( request ( aid , 'aid' , 'assay' , 'description' ) . read ( ) . decode ( ) ) [ 'PC_AssayContainer' ] [ 0 ] return cls ( record ) | Retrieve the Assay record for the specified AID . |
34,457 | def to_dict ( self , properties = None ) : if not properties : properties = [ p for p in dir ( Assay ) if isinstance ( getattr ( Assay , p ) , property ) ] return { p : getattr ( self , p ) for p in properties } | Return a dictionary containing Assay data . |
34,458 | def _is_possible_token ( token , token_length = 6 ) : if not isinstance ( token , bytes ) : token = six . b ( str ( token ) ) return token . isdigit ( ) and len ( token ) <= token_length | Determines if given value is acceptable as a token . Used when validating tokens . |
34,459 | def get_hotp ( secret , intervals_no , as_string = False , casefold = True , digest_method = hashlib . sha1 , token_length = 6 , ) : if isinstance ( secret , six . string_types ) : secret = secret . encode ( 'utf-8' ) secret = secret . replace ( b' ' , b'' ) try : key = base64 . b32decode ( secret , casefold = casefold... | Get HMAC - based one - time password on the basis of given secret and interval number . |
34,460 | def get_totp ( secret , as_string = False , digest_method = hashlib . sha1 , token_length = 6 , interval_length = 30 , clock = None , ) : if clock is None : clock = time . time ( ) interv_no = int ( clock ) // interval_length return get_hotp ( secret , intervals_no = interv_no , as_string = as_string , digest_method = ... | Get time - based one - time password on the basis of given secret and time . |
34,461 | def valid_hotp ( token , secret , last = 1 , trials = 1000 , digest_method = hashlib . sha1 , token_length = 6 , ) : if not _is_possible_token ( token , token_length = token_length ) : return False for i in six . moves . xrange ( last + 1 , last + trials + 1 ) : token_candidate = get_hotp ( secret = secret , intervals_... | Check if given token is valid for given secret . Return interval number that was successful or False if not found . |
34,462 | def valid_totp ( token , secret , digest_method = hashlib . sha1 , token_length = 6 , interval_length = 30 , clock = None , window = 0 , ) : if _is_possible_token ( token , token_length = token_length ) : if clock is None : clock = time . time ( ) for w in range ( - window , window + 1 ) : if int ( token ) == get_totp ... | Check if given token is valid time - based one - time password for given secret . |
34,463 | def parametrize ( params ) : returned = str ( params [ 0 ] ) returned += "" . join ( "[" + str ( p ) + "]" for p in params [ 1 : ] ) return returned | Return list of params as params . |
34,464 | def urlencode ( params ) : if not isinstance ( params , dict ) : raise TypeError ( "Only dicts are supported." ) params = flatten ( params ) url_params = OrderedDict ( ) for param in params : value = param . pop ( ) name = parametrize ( param ) if isinstance ( value , ( list , tuple ) ) : name += "[]" url_params [ name... | Urlencode a multidimensional dict . |
34,465 | def find_matlab_root ( ) : matlab_root = None path_dirs = os . environ . get ( "PATH" ) . split ( os . pathsep ) for path_dir in path_dirs : candidate = realpath ( join ( path_dir , 'matlab' ) ) if isfile ( candidate ) or isfile ( candidate + '.exe' ) : matlab_root = dirname ( dirname ( candidate ) ) break return matla... | Look for matlab binary and return root directory of MATLAB installation . |
34,466 | def load_engine_and_libs ( matlab_root , options ) : if sys . maxsize > 2 ** 32 : bits = '64bit' else : bits = '32bit' system = platform . system ( ) if system == 'Linux' : if bits == '64bit' : lib_dir = join ( matlab_root , "bin" , "glnxa64" ) else : lib_dir = join ( matlab_root , "bin" , "glnx86" ) check_python_matla... | Load and return libeng and libmx . Start and return MATLAB engine . |
34,467 | def check_python_matlab_architecture ( bits , lib_dir ) : if not os . path . isdir ( lib_dir ) : raise RuntimeError ( "It seem that you are using {bits} version of Python, but there's no matching MATLAB installation in {lib_dir}." . format ( bits = bits , lib_dir = lib_dir ) ) | Make sure we can find corresponding installation of Python and MATLAB . |
34,468 | def eval ( self , expression ) : expression_wrapped = wrap_script . format ( expression ) self . _libeng . engEvalString ( self . _ep , expression_wrapped ) mxresult = self . _libeng . engGetVariable ( self . _ep , 'ERRSTR__' ) error_string = self . _libmx . mxArrayToString ( mxresult ) self . _libmx . mxDestroyArray (... | Evaluate expression in MATLAB engine . |
34,469 | def get ( self , name ) : pm = self . _libeng . engGetVariable ( self . _ep , name ) out = mxarray_to_ndarray ( self . _libmx , pm ) self . _libmx . mxDestroyArray ( pm ) return out | Get variable name from MATLAB workspace . |
34,470 | def put ( self , name , value ) : pm = ndarray_to_mxarray ( self . _libmx , value ) self . _libeng . engPutVariable ( self . _ep , name , pm ) self . _libmx . mxDestroyArray ( pm ) | Put a variable to MATLAB workspace . |
34,471 | def dirs ( self , before = time . time ( ) , exited = True ) : timestamp = iso ( before ) root = os . path . join ( self . root , "start-time" ) os . chdir ( root ) by_t = ( d for d in glob . iglob ( "????-??-??T*.*Z" ) if d < timestamp ) if exited is None : def predicate ( directory ) : return True else : def predicat... | Provider a generator of container state directories . |
34,472 | def methods ( ) : "Names of operations provided by containerizers, as a set." pairs = inspect . getmembers ( Containerizer , predicate = inspect . ismethod ) return set ( k for k , _ in pairs if k [ 0 : 1 ] != "_" ) | Names of operations provided by containerizers as a set . |
34,473 | def stdio ( containerizer , * args ) : try : name = args [ 0 ] method , proto = { "launch" : ( containerizer . launch , Launch ) , "update" : ( containerizer . update , Update ) , "usage" : ( containerizer . usage , Usage ) , "wait" : ( containerizer . wait , Wait ) , "destroy" : ( containerizer . destroy , Destroy ) ,... | Connect containerizer class to command line args and STDIN |
34,474 | def construct ( path , name = None ) : "Selects an appropriate CGroup subclass for the given CGroup path." name = name if name else path . split ( "/" ) [ 4 ] classes = { "memory" : Memory , "cpu" : CPU , "cpuacct" : CPUAcct } constructor = classes . get ( name , CGroup ) log . debug ( "Chose %s for: %s" , constructor ... | Selects an appropriate CGroup subclass for the given CGroup path . |
34,475 | def serialize ( cls , ** properties ) : obj = cls ( ) for k , v in properties . iteritems ( ) : log . debug ( "%s.%s = %r" , cls . __name__ , k , v ) setattr ( obj , k , v ) return obj . SerializeToString ( ) | With a Protobuf class and properties as keyword arguments sets all the properties on a new instance of the class and serializes the resulting value . |
34,476 | def logger ( height = 1 ) : caller = inspect . stack ( ) [ height ] scope = caller [ 0 ] . f_globals function = caller [ 3 ] path = scope [ "__name__" ] if path == "__main__" and scope [ "__package__" ] : path = scope [ "__package__" ] return logging . getLogger ( path + "." + function + "()" ) | Obtain a function logger for the calling function . Uses the inspect module to find the name of the calling function and its position in the module hierarchy . With the optional height argument logs for caller s caller and so forth . |
34,477 | def load_jupyter_server_extension ( nb_server_app ) : app = nb_server_app . web_app host_pattern = '.*$' app . add_handlers ( host_pattern , [ ( utils . url_path_join ( app . settings [ 'base_url' ] , '/http_over_websocket' ) , handlers . HttpOverWebSocketHandler ) , ( utils . url_path_join ( app . settings [ 'base_url... | Called by Jupyter when this module is loaded as a server extension . |
34,478 | def _validate_min_version ( min_version ) : if min_version is not None : try : parsed_min_version = version . StrictVersion ( min_version ) except ValueError : return ExtensionVersionResult ( error_reason = ExtensionValidationError . UNPARSEABLE_REQUESTED_VERSION , requested_extension_version = min_version ) if parsed_... | Validates the extension version matches the requested version . |
34,479 | def streaming_callback ( self , body_part ) : b64_body_string = base64 . b64encode ( body_part ) . decode ( 'utf-8' ) response = { 'message_id' : self . _message_id , 'data' : b64_body_string , } if self . _last_response is None : response . update ( self . _generate_metadata_body ( ) ) else : self . _last_response [ '... | Handles a streaming chunk of the response . |
34,480 | def lower_dict ( d ) : _d = { } for k , v in d . items ( ) : try : _d [ k . lower ( ) ] = v except AttributeError : _d [ k ] = v return _d | Lower cases string keys in given dict . |
34,481 | def urlparse ( d , keys = None ) : d = d . copy ( ) if keys is None : keys = d . keys ( ) for key in keys : d [ key ] = _urlparse ( d [ key ] ) return d | Returns a copy of the given dictionary with url values parsed . |
34,482 | def prefix ( prefix ) : d = { } e = lower_dict ( environ . copy ( ) ) prefix = prefix . lower ( ) for k , v in e . items ( ) : try : if k . startswith ( prefix ) : k = k [ len ( prefix ) : ] d [ k ] = v except AttributeError : pass return d | Returns a dictionary of all environment variables starting with the given prefix lower cased and stripped . |
34,483 | def map ( ** kwargs ) : d = { } e = lower_dict ( environ . copy ( ) ) for k , v in kwargs . items ( ) : d [ k ] = e . get ( v . lower ( ) ) return d | Returns a dictionary of the given keyword arguments mapped to their values from the environment with input keys lower cased . |
34,484 | def Load ( file ) : with open ( file , 'rb' ) as file : model = dill . load ( file ) return model | Loads a model from specified file |
34,485 | def _AddInput ( self , variable ) : if isinstance ( variable , Variable ) : self . inputs . append ( variable ) else : print ( 'Error: ' , variable . name , variable , ' given is not a variable' ) raise TypeError | Add one more variable as an input of the block |
34,486 | def _AddOutput ( self , variable ) : if isinstance ( variable , Variable ) : self . outputs . append ( variable ) else : print ( variable ) raise TypeError | Add one more variable as an output of the block |
34,487 | def InputValues ( self , it , nsteps = None ) : if nsteps == None : nsteps = self . max_input_order I = np . zeros ( ( self . n_inputs , nsteps ) ) for iv , variable in enumerate ( self . inputs ) : I [ iv , : ] = variable . _values [ it - nsteps + 1 : it + 1 ] return I | Returns the input values at a given iteration for solving the block outputs |
34,488 | def _AddVariable ( self , variable ) : if isinstance ( variable , Signal ) : if not variable in self . signals : self . signals . append ( variable ) elif isinstance ( variable , Variable ) : if not variable in self . variables : self . variables . append ( variable ) else : raise TypeError self . _utd_graph = False | Add a variable to the model . Should not be used by end - user |
34,489 | def VariablesValues ( self , variables , t ) : if ( t < self . te ) | ( t > 0 ) : i = t // self . ts ti = self . ts * i if type ( variables ) == list : values = [ ] for variable in variables : values . append ( variables . values [ i ] * ( ( ti - t ) / self . ts + 1 ) + variables . values [ i + 1 ] * ( t - ti ) / self ... | Returns the value of given variables at time t . Linear interpolation is performed between two time steps . |
34,490 | def to_python ( self , value ) : if value == "" : return None try : if isinstance ( value , six . string_types ) : return self . deserializer ( value ) elif isinstance ( value , bytes ) : return self . deserializer ( value . decode ( 'utf8' ) ) except ValueError : pass return value | Convert a string from the database to a Python value . |
34,491 | def get_prep_value ( self , value ) : if value == "" : return None if isinstance ( value , ( dict , list ) ) : return self . serializer ( value ) return super ( JSONField , self ) . get_prep_value ( value ) | Convert the value to a string so it can be stored in the database . |
34,492 | def render_to ( template = None , content_type = None ) : def renderer ( function ) : @ wraps ( function ) def wrapper ( request , * args , ** kwargs ) : output = function ( request , * args , ** kwargs ) if not isinstance ( output , dict ) : return output tmpl = output . pop ( 'TEMPLATE' , template ) if tmpl is None :... | Decorator for Django views that sends returned dict to render_to_response function . |
34,493 | def ajax_request ( func ) : @ wraps ( func ) def wrapper ( request , * args , ** kwargs ) : for accepted_type in request . META . get ( 'HTTP_ACCEPT' , '' ) . split ( ',' ) : if accepted_type in FORMAT_TYPES . keys ( ) : format_type = accepted_type break else : format_type = 'application/json' response = func ( request... | If view returned serializable dict returns response in a format requested by HTTP_ACCEPT header . Defaults to JSON if none requested or match . |
34,494 | def autostrip ( cls ) : warnings . warn ( "django-annoying autostrip is deprecated and will be removed in a " "future version. Django now has native support for stripping form " "fields. " "https://docs.djangoproject.com/en/stable/ref/forms/fields/#django.forms.CharField.strip" , DeprecationWarning , stacklevel = 2 , )... | strip text fields before validation |
34,495 | def _patch_file ( path , content ) : f = open ( path ) existing_content = f . read ( ) f . close ( ) if existing_content == content : log . warn ( 'Already patched.' ) return False log . warn ( 'Patching...' ) _rename_path ( path ) f = open ( path , 'w' ) try : f . write ( content ) finally : f . close ( ) return True | Will backup the file then patch it |
34,496 | def _set_overlay_verify ( name , overlay_path , config_path ) : global DEBUG if os . path . exists ( config_path ) : print ( "Config path already exists! Not moving forward" ) print ( "config_path: {0}" . format ( config_path ) ) return - 1 os . makedirs ( config_path ) with open ( config_path + "/dtbo" , 'wb' ) as out... | _set_overlay_verify - Function to load the overlay and verify it was setup properly |
34,497 | def load ( overlay , path = "" ) : global DEBUG global _LOADED if DEBUG : print ( "LOAD OVERLAY: {0} @ {1}" . format ( overlay , path ) ) if overlay . upper ( ) in _OVERLAYS . keys ( ) : cpath = OVERLAYCONFIGPATH + "/" + _FOLDERS [ overlay . upper ( ) ] if DEBUG : print ( "VALID OVERLAY" ) print ( "CONFIG PATH: {0}" .... | load - Load a DTB Overlay |
34,498 | def run ( self ) : while not self . stopped : now = datetime . utcnow ( ) for job in self . parent . jobs : if not job . next_run : continue if job . next_run >= self . last_check and job . next_run <= now : if job . state . allow_start : job . start ( ) else : job . next_run = job . cron_iter . get_next ( datetime ) s... | Continually monitors Jobs of the parent Dagobah . |
34,499 | def set_backend ( self , backend ) : self . backend = backend self . dagobah_id = self . backend . get_new_dagobah_id ( ) for job in self . jobs : job . backend = backend for task in job . tasks . values ( ) : task . backend = backend self . commit ( cascade = True ) | Manually set backend after construction . |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.