signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def parse_localnamespacepath ( parser , event , node ) : # pylint : disable = unused - argument """Parse LOCALNAMESPACEPATH for Namespace . Return assembled namespace < ! ELEMENT LOCALNAMESPACEPATH ( NAMESPACE + ) >"""
( next_event , next_node ) = six . next ( parser ) namespaces = [ ] if not _is_start ( next_event , next_node , 'NAMESPACE' ) : print ( next_event , next_node ) raise ParseError ( 'Expecting NAMESPACE' ) namespaces . append ( parse_namespace ( parser , next_event , next_node ) ) while 1 : ( next_event , nex...
def _update_pop ( self , pop_size ) : """Assigns fitnesses to particles that are within bounds ."""
valid_particles = [ ] invalid_particles = [ ] for part in self . population : if any ( x > 1 or x < - 1 for x in part ) : invalid_particles . append ( part ) else : valid_particles . append ( part ) self . _model_count += len ( valid_particles ) for part in valid_particles : self . update_pa...
def engage ( proto = 'udp' ) : '''Fire thrusters .'''
from ironman . server import ServerFactory from twisted . internet import reactor from twisted . internet . defer import Deferred getattr ( reactor , 'listen{0:s}' . format ( proto . upper ( ) ) ) ( 8888 , ServerFactory ( proto , Deferred ) ) reactor . run ( )
def get_station_temperature_datetime ( self , station_id ) : """Return temperature measurement datetime for a given station"""
request = requests . get ( "{}/station/{}/parameters/temperature/datetime" . format ( self . base_url , station_id ) ) if request . status_code != 200 : return None return datetime . strptime ( request . json ( ) , "%Y-%m-%dT%H:%M:%S" )
def duration ( self ) : """Calculates the breeding cage ' s duration . This is relative to the current date ( if alive ) or the date of inactivation ( if not ) . The duration is formatted in days ."""
if self . End : age = self . End - self . Start else : age = datetime . date . today ( ) - self . Start return age . days
def _overapprox ( self ) : """The method extracts a model corresponding to an over - approximation of an MCS , i . e . it is the model of the hard part of the formula ( the corresponding oracle call is made in : func : ` compute ` ) . Here , the set of selectors is divided into two parts : ` ` self . ss _ a...
model = self . oracle . get_model ( ) for sel in self . sels : if len ( model ) < sel or model [ sel - 1 ] > 0 : # soft clauses contain positive literals # so if var is true then the clause is satisfied self . ss_assumps . append ( sel ) else : self . setd . append ( sel )
def connect ( sock , addr ) : """Connect to some addr ."""
try : sock . connect ( addr ) except ssl . SSLError as e : return ( ssl . SSLError , e . strerror if e . strerror else e . message ) except socket . herror as ( _ , msg ) : return ( socket . herror , msg ) except socket . gaierror as ( _ , msg ) : return ( socket . gaierror , msg ) except socket . timeo...
def checkpat ( self , pattern ) : """check for errors in a regex pattern"""
if pattern is None : return try : re . match ( pattern , "" ) except re . error : print3 ( "\nBad user-defined singular pattern:\n\t%s\n" % pattern ) raise BadUserDefinedPatternError
def _pre_action ( self , action ) : """Overrides the superclass method to actuate the robot with the passed joint velocities and gripper control . Args : action ( numpy array ) : The control to apply to the robot . The first @ self . mujoco _ robot . dof dimensions should be the desired normalized joint v...
# clip actions into valid range assert len ( action ) == self . dof , "environment got invalid action dimension" low , high = self . action_spec action = np . clip ( action , low , high ) if self . has_gripper : arm_action = action [ : self . mujoco_robot . dof ] gripper_action_in = action [ self . mujoco_robot...
def mostly ( fn ) : """95 % chance of happening"""
def wrapped ( * args , ** kwargs ) : if in_percentage ( 95 ) : fn ( * args , ** kwargs ) return wrapped
def _validate_value ( self , value , field_spec , path , errors ) : """Validates that the given field value is valid given the associated field spec and path . Any validation failures are added to the given errors collection ."""
# Check if the value is None and add an error if the field is not nullable . # Note that for backward compatibility reasons , the default value of ' nullable ' # is the inverse of ' required ' ( which use to mean both that the key be present # and not set to None ) . if value is None : if not field_spec . get ( 'nu...
def _connectionEstablished ( self , transport ) : '''Store a reference to our transport and write an open frame .'''
self . transport = transport self . transport . writeOpen ( ) self . heartbeater . schedule ( )
def bitrate ( self ) : """The number of bits per seconds used in the audio coding ( an int ) . If this is provided explicitly by the compressed file format , this is a precise reflection of the encoding . Otherwise , it is estimated from the on - disk file size . In this case , some imprecision is possible ...
if hasattr ( self . mgfile . info , 'bitrate' ) and self . mgfile . info . bitrate : # Many formats provide it explicitly . return self . mgfile . info . bitrate else : # Otherwise , we calculate bitrate from the file size . ( This # is the case for all of the lossless formats . ) if not self . length : # Avoid...
def genms ( self , scans = [ ] ) : """Generate an MS that contains all calibrator scans with 1 s integration time ."""
if len ( scans ) : scanstr = string . join ( [ str ( ss ) for ss in sorted ( scans ) ] , ',' ) else : scanstr = self . allstr print 'Splitting out all cal scans (%s) with 1s int time' % scanstr newname = ps . sdm2ms ( self . sdmfile , self . sdmfile . rstrip ( '/' ) + '.ms' , scanstr , inttime = '1' ) # integra...
def intersectionlist_to_matrix ( ilist , xterms , yterms ) : """WILL BE DEPRECATED Replace with method to return pandas dataframe"""
z = [ [ 0 ] * len ( xterms ) for i1 in range ( len ( yterms ) ) ] xmap = { } xi = 0 for x in xterms : xmap [ x ] = xi xi = xi + 1 ymap = { } yi = 0 for y in yterms : ymap [ y ] = yi yi = yi + 1 for i in ilist : z [ ymap [ i [ 'y' ] ] ] [ xmap [ i [ 'x' ] ] ] = i [ 'j' ] logging . debug ( "Z={}" . fo...
def create_user_task ( sender = None , body = None , ** kwargs ) : # pylint : disable = unused - argument """Create a : py : class : ` UserTaskStatus ` record for each : py : class : ` UserTaskMixin ` . Also creates a : py : class : ` UserTaskStatus ` for each chain , chord , or group containing the new : py : ...
try : task_class = import_string ( sender ) except ImportError : return if issubclass ( task_class . __class__ , UserTaskMixin ) : arguments_dict = task_class . arguments_as_dict ( * body [ 'args' ] , ** body [ 'kwargs' ] ) user_id = _get_user_id ( arguments_dict ) task_id = body [ 'id' ] if bod...
def _get_msiexec ( use_msiexec ) : '''Return if msiexec . exe will be used and the command to invoke it .'''
if use_msiexec is False : return False , '' if isinstance ( use_msiexec , six . string_types ) : if os . path . isfile ( use_msiexec ) : return True , use_msiexec else : log . warning ( "msiexec path '%s' not found. Using system registered " "msiexec instead" , use_msiexec ) use_msie...
def url_join ( base , url , allow_fragments = True ) : """Join a base URL and a possibly relative URL to form an absolute interpretation of the latter . : param base : the base URL for the join operation . : param url : the URL to join . : param allow _ fragments : indicates whether fragments should be allo...
if isinstance ( base , tuple ) : base = url_unparse ( base ) if isinstance ( url , tuple ) : url = url_unparse ( url ) base , url = normalize_string_tuple ( ( base , url ) ) s = make_literal_wrapper ( base ) if not base : return url if not url : return base bscheme , bnetloc , bpath , bquery , bfragment...
def findRequirements ( ) : """Read the requirements . txt file and parse into requirements for setup ' s install _ requirements option ."""
requirementsPath = os . path . join ( REPO_DIR , "requirements.txt" ) requirements = parse_file ( requirementsPath ) # User has a pre - release version of numenta packages installed , which is only # possible if the user installed and built the packages from source and # it is up to the user to decide when to update th...
async def emit ( self , event , data = None , namespace = None , callback = None ) : """Emit a custom event to the server . The only difference with the : func : ` socketio . Client . emit ` method is that when the ` ` namespace ` ` argument is not given the namespace associated with the class is used . Not...
return await self . client . emit ( event , data = data , namespace = namespace or self . namespace , callback = callback )
def is_valid_hendecasyllables ( self , scanned_line : str ) -> bool : """Determine if a scansion pattern is one of the valid Hendecasyllables metrical patterns : param scanned _ line : a line containing a sequence of stressed and unstressed syllables : return bool > > > print ( MetricalValidator ( ) . is _ va...
line = scanned_line . replace ( self . constants . FOOT_SEPARATOR , "" ) line = line . replace ( " " , "" ) if len ( line ) < 11 : return False line = line [ : - 1 ] + self . constants . OPTIONAL_ENDING return self . VALID_HENDECASYLLABLES . __contains__ ( line )
def _compute_term_3 ( self , C , rrup , mag ) : """This computes the third term in equation 2 , page 2."""
return ( C [ 'a3' ] * np . log10 ( rrup + C [ 'a4' ] * np . power ( 10 , C [ 'a5' ] * mag ) ) )
def ProcessMessage ( self , message ) : """Begins an enrollment flow for this client . Args : message : The Certificate sent by the client . Note that this message is not authenticated ."""
cert = rdf_crypto . Certificate ( message . payload ) queue = self . well_known_session_id . Queue ( ) client_id = message . source # It makes no sense to enrol the same client multiple times , so we # eliminate duplicates . Note , that we can still enroll clients multiple # times due to cache expiration . try : en...
def build_duration ( self ) : """Return the difference between build and build _ done states"""
return int ( self . state . build_done ) - int ( self . state . build )
def bed12 ( self , score = "0" , rgb = "." ) : """return a bed12 ( http : / / genome . ucsc . edu / FAQ / FAQformat . html # format1) representation of this interval"""
if not self . is_gene_pred : raise CruzException ( "can't create bed12 from non genepred feature" ) exons = list ( self . exons ) # go from global start , stop , to relative start , length . . . sizes = "," . join ( [ str ( e [ 1 ] - e [ 0 ] ) for e in exons ] ) + "," starts = "," . join ( [ str ( e [ 0 ] - self . ...
def make_serializable ( json ) : """This function ensures that the dictionary is JSON serializable . If not , keys with non - serializable values are removed from the return value . Args : json ( dict ) : Dictionary to convert to serializable Returns : new _ dict ( dict ) : New dictionary with non JSON se...
new_dict = dict ( ) for key , value in iteritems ( json ) : if is_valid_json ( value ) : new_dict [ key ] = value return new_dict
def set_CCLE_context ( self , cell_types ) : """Set context of all nodes and node members from CCLE ."""
self . get_gene_names ( ) # Get expression and mutations from context client exp_values = context_client . get_protein_expression ( self . _gene_names , cell_types ) mut_values = context_client . get_mutations ( self . _gene_names , cell_types ) # Make a dict of presence / absence of mutations muts = { cell_line : { } ...
def page ( self , course , username ) : """Get all data and display the page"""
data = list ( self . database . user_tasks . find ( { "username" : username , "courseid" : course . get_id ( ) } ) ) tasks = course . get_tasks ( ) result = dict ( [ ( taskid , { "taskid" : taskid , "name" : tasks [ taskid ] . get_name ( self . user_manager . session_language ( ) ) , "tried" : 0 , "status" : "notviewed...
def cache_penalty_model ( penalty_model , database = None ) : """Caching function for penaltymodel _ cache . Args : penalty _ model ( : class : ` penaltymodel . PenaltyModel ` ) : Penalty model to be cached . database ( str , optional ) : The path to the desired sqlite database file . If None , will use t...
# only handles index - labelled nodes if not _is_index_labelled ( penalty_model . graph ) : mapping , __ = _graph_canonicalization ( penalty_model . graph ) penalty_model = penalty_model . relabel_variables ( mapping , inplace = False ) # connect to the database . Note that once the connection is made it cannot...
def helical_geometry ( space , src_radius , det_radius , num_turns , n_pi = 1 , num_angles = None , det_shape = None ) : """Create a default helical geometry from ` ` space ` ` . This function is intended for simple test cases where users do not need the full flexibility of the geometries , but simply wants a ...
# Find maximum distance from rotation axis corners = space . domain . corners ( ) [ : , : 2 ] rho = np . max ( np . linalg . norm ( corners , axis = 1 ) ) offset_along_axis = space . partition . min_pt [ 2 ] pitch = space . partition . extent [ 2 ] / num_turns # Find default values according to Nyquist criterion . # We...
def search ( self , title = None , sort = None , maxresults = 999999 , libtype = None , ** kwargs ) : """Search the library . If there are many results , they will be fetched from the server in batches of X _ PLEX _ CONTAINER _ SIZE amounts . If you ' re only looking for the first < num > results , it would be ...
# cleanup the core arguments args = { } for category , value in kwargs . items ( ) : args [ category ] = self . _cleanSearchFilter ( category , value , libtype ) if title is not None : args [ 'title' ] = title if sort is not None : args [ 'sort' ] = self . _cleanSearchSort ( sort ) if libtype is not None : ...
def gen_df_save ( df_grid_group : pd . DataFrame ) -> pd . DataFrame : '''generate a dataframe for saving Parameters df _ output _ grid _ group : pd . DataFrame an output dataframe of a single group and grid Returns pd . DataFrame a dataframe with date time info prepended for saving'''
# generate df _ datetime for prepending idx_dt = df_grid_group . index ser_year = pd . Series ( idx_dt . year , index = idx_dt , name = 'Year' ) ser_DOY = pd . Series ( idx_dt . dayofyear , index = idx_dt , name = 'DOY' ) ser_hour = pd . Series ( idx_dt . hour , index = idx_dt , name = 'Hour' ) ser_min = pd . Series ( ...
def _iter_service_names ( ) : '''Detect all of the service names available to upstart via init configuration files and via classic sysv init scripts'''
found = set ( ) for line in glob . glob ( '/etc/init.d/*' ) : name = os . path . basename ( line ) found . add ( name ) yield name # This walk method supports nested services as per the init man page # definition ' For example a configuration file / etc / init / rc - sysinit . conf # is named rc - sysinit ,...
def summarise_events ( self ) : """takes the logfiles and produces an event summary matrix date command result process source 20140421 9 40 178 9 20140423 0 0 6 0 20140424 19 1 47 19 20140425 24 0 117 24 20140426 16 0 83 16 20140427 1 0 6 1 20140429 0 0 0 4"""
all_dates = [ ] d_command = self . _count_by_date ( self . command_file , all_dates ) d_result = self . _count_by_date ( self . result_file , all_dates ) d_process = self . _count_by_date ( self . process_file , all_dates ) d_source = self . _count_by_date ( self . source_file , all_dates ) with open ( self . log_sum ,...
def setup ( self , url , stream = True , post = False , parameters = None , timeout = None ) : # type : ( str , bool , bool , Optional [ Dict ] , Optional [ float ] ) - > requests . Response """Setup download from provided url returning the response Args : url ( str ) : URL to download stream ( bool ) : Wheth...
self . close_response ( ) self . response = None try : if post : full_url , parameters = self . get_url_params_for_post ( url , parameters ) self . response = self . session . post ( full_url , data = parameters , stream = stream , timeout = timeout ) else : self . response = self . sess...
def generate_pos_tagger ( check_accuracy = False ) : """Accuracy is about 0.94 with 90 % training data ."""
global tagger logging . debug ( "Reading TIGER corpus" ) corp = nltk . corpus . ConllCorpusReader ( DIR_PATH , TIGER_FILE_NAME , [ 'ignore' , 'words' , 'ignore' , 'ignore' , 'pos' ] , encoding = 'utf-8' ) tagged_sents = list ( corp . tagged_sents ( ) ) logging . debug ( "Shuffling sentences" ) random . shuffle ( tagged...
def update ( self , status , source = None , params = { } ) : "Update your status . Returns the ID of the new post ."
params = params . copy ( ) params [ 'status' ] = status if source : params [ 'source' ] = source return self . __parsed_post ( self . __post ( '/statuses/update.xml' , params ) , txml . parseUpdateResponse )
def subtract_imagenet_mean_preprocess_batch ( batch ) : """Subtract ImageNet mean pixel - wise from a BGR image ."""
batch = F . swapaxes ( batch , 0 , 1 ) ( r , g , b ) = F . split ( batch , num_outputs = 3 , axis = 0 ) r = r - 123.680 g = g - 116.779 b = b - 103.939 batch = F . concat ( b , g , r , dim = 0 ) batch = F . swapaxes ( batch , 0 , 1 ) return batch
def cmp ( self , other_service ) : """Compare with an instance of this object . Returns None if the object is not comparable , False is relevant attributes don ' t match and True if they do ."""
if not isinstance ( other_service , HttpService ) : return None for att in dir ( self ) : if att == 'cmp' or att . startswith ( '_' ) : continue if not hasattr ( other_service , att ) : return None if getattr ( self , att ) != getattr ( other_service , att ) : return False return...
def embed_snippet ( views , drop_defaults = True , state = None , indent = 2 , embed_url = None , requirejs = True , cors = True ) : """Return a snippet that can be embedded in an HTML file . Parameters { views _ attribute } { embed _ kwargs } Returns A unicode string with an HTML snippet containing sever...
data = embed_data ( views , drop_defaults = drop_defaults , state = state ) widget_views = u'\n' . join ( widget_view_template . format ( view_spec = escape_script ( json . dumps ( view_spec ) ) ) for view_spec in data [ 'view_specs' ] ) if embed_url is None : embed_url = DEFAULT_EMBED_REQUIREJS_URL if requirejs el...
def update_video ( self ) : """Read list of files , convert to video time , and add video to queue ."""
window_start = self . parent . value ( 'window_start' ) window_length = self . parent . value ( 'window_length' ) d = self . parent . info . dataset videos , begsec , endsec = d . read_videos ( window_start , window_start + window_length ) lg . debug ( f'Video: {begsec} - {endsec}' ) self . endsec = endsec videos = [ s...
def _read_http_data ( self , size , kind , flag ) : """Read HTTP / 2 DATA frames . Structure of HTTP / 2 DATA frame [ RFC 7540 ] : | Length ( 24 ) | | Type ( 8 ) | Flags ( 8 ) | | R | Stream Identifier ( 31 ) | | Pad Length ? ( 8 ) | | Data ( * ) . . . | Padding ( * ) . . . Octets Bits Name Descript...
_plen = 0 _flag = dict ( END_STREAM = False , # bit 0 PADDED = False , # bit 3 ) for index , bit in enumerate ( flag ) : if index == 0 and bit : _flag [ 'END_STREAM' ] = True elif index == 3 and bit : _flag [ 'PADDED' ] = True _plen = self . _read_unpack ( 1 ) elif bit : rais...
def patch_qs ( url : Text , data : Dict [ Text , Text ] ) -> Text : """Given an URL , change the query string to include the values specified in the dictionary . If the keys of the dictionary can be found in the query string of the URL , then they will be removed . It is guaranteed that all other values of ...
qs_id = 4 p = list ( urlparse ( url ) ) qs = parse_qsl ( p [ qs_id ] ) # type : List [ Tuple [ Text , Text ] ] patched_qs = list ( chain ( filter ( lambda x : x [ 0 ] not in data , qs ) , data . items ( ) , ) ) p [ qs_id ] = urlencode ( patched_qs ) return urlunparse ( p )
def destroy_window ( window ) : '''Destroys the specified window and its context . Wrapper for : void glfwDestroyWindow ( GLFWwindow * window ) ;'''
_glfw . glfwDestroyWindow ( window ) window_addr = ctypes . cast ( ctypes . pointer ( window ) , ctypes . POINTER ( ctypes . c_ulong ) ) . contents . value for callback_repository in _callback_repositories : if window_addr in callback_repository : del callback_repository [ window_addr ]
def _make_sparse_blocks_with_virtual ( self , variable , records , data ) : '''Handles the data for the variable with sparse records . Organizes the physical record numbers into blocks in a list : [ [ start _ rec1 , end _ rec1 , data _ 1 ] , [ start _ rec2 , enc _ rec2 , data _ 2 ] , . . . ] Place consecutive...
# Gather the ranges for which we have physical data sparse_blocks = CDF . _make_blocks ( records ) sparse_data = [ ] if ( isinstance ( data , np . ndarray ) ) : for sblock in sparse_blocks : # each block in this list : [ starting _ rec # , ending _ rec # , data ] asparse = [ ] asparse . append ( sbl...
def receive ( ) : """Receive a command from Training Service . Returns a tuple of command ( CommandType ) and payload ( str )"""
header = _in_file . read ( 8 ) logging . getLogger ( __name__ ) . debug ( 'Received command, header: [%s]' % header ) if header is None or len ( header ) < 8 : # Pipe EOF encountered logging . getLogger ( __name__ ) . debug ( 'Pipe EOF encountered' ) return None , None length = int ( header [ 2 : ] ) data = _in...
def deploy ( environment , zappa_settings ) : """Package , create and deploy to Lambda ."""
print ( ( "Deploying " + environment ) ) zappa , settings , lambda_name , zip_path = _package ( environment , zappa_settings ) s3_bucket_name = settings [ 's3_bucket' ] try : # Load your AWS credentials from ~ / . aws / credentials zappa . load_credentials ( ) # Make sure the necessary IAM execution roles are a...
def app_uninstall ( self , package_name , keep_data = False ) : """Uninstall package Args : - package _ name ( string ) : package name ex : com . example . demo - keep _ data ( bool ) : keep the data and cache directories"""
if keep_data : return self . run_cmd ( 'uninstall' , '-k' , package_name ) else : return self . run_cmd ( 'uninstall' , package_name )
def __parse ( value ) : """Parse the string date . Supports the subset of ISO8601 used by xsd : time , but is lenient with what is accepted , handling most reasonable syntax . Subsecond information is rounded to microseconds due to a restriction in the python datetime . time implementation . @ param value...
match_result = _RE_TIME . match ( value ) if match_result is None : raise ValueError ( "date data has invalid format '%s'" % ( value , ) ) time , round_up = _time_from_match ( match_result ) tzinfo = _tzinfo_from_match ( match_result ) if round_up : time = _bump_up_time_by_microsecond ( time ) return time . rep...
def pretrain ( texts_loc , vectors_model , output_dir , width = 96 , depth = 4 , embed_rows = 2000 , loss_func = "cosine" , use_vectors = False , dropout = 0.2 , n_iter = 1000 , batch_size = 3000 , max_length = 500 , min_length = 5 , seed = 0 , n_save_every = None , ) : """Pre - train the ' token - to - vector ' ( ...
config = dict ( locals ( ) ) msg = Printer ( ) util . fix_random_seed ( seed ) has_gpu = prefer_gpu ( ) msg . info ( "Using GPU" if has_gpu else "Not using GPU" ) output_dir = Path ( output_dir ) if not output_dir . exists ( ) : output_dir . mkdir ( ) msg . good ( "Created output directory" ) srsly . write_json...
def _ensure_append ( self , new_items , append_to , index = 0 ) : """Ensure an item is appended to a list or create a new empty list : param new _ items : the item ( s ) to append : type new _ items : list ( obj ) : param append _ to : the list on which to append the items : type append _ to : list ( ) : ...
append_to = append_to or [ ] append_to . insert ( index , new_items ) return append_to
def handle_erroneous_response ( self , response : requests . Response ) -> NoReturn : """Attempts to decode an erroneous response into an exception , and to subsequently throw that exception . Raises : BugZooException : the exception described by the error response . UnexpectedResponse : if the response can...
logger . debug ( "handling erroneous response: %s" , response ) try : err = BugZooException . from_dict ( response . json ( ) ) except Exception : err = UnexpectedResponse ( response ) raise err
async def filter_new_posts ( self , source_id , post_ids ) : """Filters ist of post _ id for new ones . : param source _ id : id of the source : type string : : param post _ ids : list of post ids : type list : : returns : list of unknown post ids ."""
new_ids = [ ] try : db_client = self . _db posts_in_db = await db_client . get_known_posts ( source_id , post_ids ) new_ids = [ p for p in post_ids if p not in posts_in_db ] except Exception as exc : logger . error ( "Error when filtering for new posts {} {}" . format ( source_id , post_ids ) ) logg...
def min_feedback_arc_set ( edges , remove = False , maxcycles = 20000 ) : """A directed graph may contain directed cycles , when such cycles are undesirable , we wish to eliminate them and obtain a directed acyclic graph ( DAG ) . A feedback arc set has the property that it has at least one edge of every cycl...
G = nx . DiGraph ( ) edge_to_index = { } for i , ( a , b , w ) in enumerate ( edges ) : G . add_edge ( a , b ) edge_to_index [ a , b ] = i nedges = len ( edges ) L = LPInstance ( ) L . add_objective ( edges , objective = MINIMIZE ) constraints = [ ] ncycles = 0 for c in nx . simple_cycles ( G ) : cycle_edge...
def mass_3d ( self , R , Rs , rho0 ) : """mass enclosed a 3d sphere or radius r : param r : : param Ra : : param Rs : : return :"""
Rs = float ( Rs ) m_3d = 4. * np . pi * rho0 * Rs ** 3 * ( np . log ( ( Rs + R ) / Rs ) - R / ( Rs + R ) ) return m_3d
def _get_clearinghouse_vessel_handle ( vesselhandle ) : """< Purpose > Acquires the unique vessel identifier for a given vesselhandle . < Arguments > vesselhandle : A vessel handle expressed in the form node _ ip : node _ port : vesselname . < Side Effects > Opens a connection to the vessel to retrieve ...
host , portstring , vesselname = vesselhandle . split ( ':' ) port = int ( portstring ) # get information about the node ' s vessels try : nodehandle = nmclient . nmclient_createhandle ( host , port , timeout = seash_global_variables . globalseashtimeout ) except NMClientException , e : return ( False , str ( e...
def read_excitation_energies ( self ) : """Read a excitation energies after a TD - DFT calculation . Returns : A list : A list of tuple for each transition such as [ ( energie ( eV ) , lambda ( nm ) , oscillatory strength ) , . . . ]"""
transitions = list ( ) # read in file with zopen ( self . filename , "r" ) as f : line = f . readline ( ) td = False while line != "" : if re . search ( r"^\sExcitation energies and oscillator strengths:" , line ) : td = True if td : if re . search ( r"^\sExcited Stat...
def update ( self , request , * args , ** kwargs ) : """Update a resource ."""
# NOTE : Use the original method instead when support for locking is added : # https : / / github . com / encode / django - rest - framework / issues / 4675 # return super ( ) . update ( request , * args , * * kwargs ) with transaction . atomic ( ) : return self . _update ( request , * args , ** kwargs )
def _set_default_action ( self , v , load = False ) : """Setter method for default _ action , mapped from YANG variable / openflow _ state / detail / default _ action ( default - packet - action ) If this variable is read - only ( config : false ) in the source YANG file , then _ set _ default _ action is consi...
if hasattr ( v , "_utype" ) : v = v . _utype ( v ) try : t = YANGDynClass ( v , base = RestrictedClassType ( base_type = unicode , restriction_type = "dict_key" , restriction_arg = { u'dcm-action-drop' : { 'value' : 1 } , u'dcm-action-invalid' : { 'value' : 0 } , u'dcm-action-send-to-controller' : { 'value' : 2...
def update_instance ( self ) : """Save bound form data into the XmlObject model instance and return the updated instance ."""
# NOTE : django model form has a save method - not applicable here , # since an XmlObject by itself is not expected to have a save method # ( only likely to be saved in context of a fedora or exist object ) if hasattr ( self , 'cleaned_data' ) : # possible to have an empty object / no data opts = self . _meta #...
def get_primary_group ( obj_name , obj_type = 'file' ) : r'''Gets the primary group of the passed object Args : obj _ name ( str ) : The path for which to obtain primary group information obj _ type ( str ) : The type of object to query . This value changes the format of the ` ` obj _ name ` ` parameter...
# Not all filesystems mountable within windows have SecurityDescriptors . # For instance , some mounted SAMBA shares , or VirtualBox shared folders . If # we can ' t load a file descriptor for the file , we default to " Everyone " # http : / / support . microsoft . com / kb / 243330 # Validate obj _ type try : obj_...
def normalize ( self , text , normalizations = None ) : """Normalize a given text applying all normalizations . Normalizations to apply can be specified through a list of parameters and will be executed in that order . Args : text : The text to be processed . normalizations : List of normalizations to app...
for normalization , kwargs in self . _parse_normalizations ( normalizations or self . _config . normalizations ) : try : text = getattr ( self , normalization ) ( text , ** kwargs ) except AttributeError as e : self . _logger . debug ( 'Invalid normalization: %s' , e ) return text
def to_polygon ( self ) : """Return a 4 - cornered polygon equivalent to this rectangle"""
x , y = self . corners . T vertices = PixCoord ( x = x , y = y ) return PolygonPixelRegion ( vertices = vertices , meta = self . meta , visual = self . visual )
def readQuotes ( self , start , end ) : '''read quotes from Yahoo Financial'''
if self . symbol is None : LOG . debug ( 'Symbol is None' ) return [ ] return self . __yf . getQuotes ( self . symbol , start , end )
def draw_header ( canvas ) : """Draws the invoice header"""
canvas . setStrokeColorRGB ( 0.9 , 0.5 , 0.2 ) canvas . setFillColorRGB ( 0.2 , 0.2 , 0.2 ) canvas . setFont ( 'Helvetica' , 16 ) canvas . drawString ( 18 * cm , - 1 * cm , 'Invoice' ) canvas . drawInlineImage ( settings . INV_LOGO , 1 * cm , - 1 * cm , 250 , 16 ) canvas . setLineWidth ( 4 ) canvas . line ( 0 , - 1.25 ...
def run_apidoc ( _ ) : """Generage API documentation"""
import better_apidoc better_apidoc . main ( [ 'better-apidoc' , '-t' , os . path . join ( '.' , '_templates' ) , '--force' , '--no-toc' , '--separate' , '-o' , os . path . join ( '.' , 'API' ) , os . path . join ( '..' , 'src' , 'qnet' ) , ] )
def _do_generate ( self , source_list , hang_type , crashed_thread , delimiter = ' | ' ) : """each element of signatureList names a frame in the crash stack ; and is : - a prefix of a relevant frame : Append this element to the signature - a relevant frame : Append this element and stop looking - irrelevant :...
notes = [ ] debug_notes = [ ] # shorten source _ list to the first signatureSentinel sentinel_locations = [ ] for a_sentinel in self . signature_sentinels : if type ( a_sentinel ) == tuple : a_sentinel , condition_fn = a_sentinel if not condition_fn ( source_list ) : continue try : ...
def get_compatible_generator_action ( self , filename ) : """Return the * * first * * compatible : class : ` GeneratorAction ` for a given filename or ` ` None ` ` if none is found . Args : filename ( str ) : The filename of the template to process ."""
# find first compatible generator action for action in self . __generator_actions : if action . act_on_file ( filename ) : return action return None
def get_hg_revision ( repopath ) : """Return Mercurial revision for the repository located at repopath Result is a tuple ( global , local , branch ) , with None values on error For example : > > > get _ hg _ revision ( " . " ) ( ' eba7273c69df + ' , ' 2015 + ' , ' default ' )"""
try : assert osp . isdir ( osp . join ( repopath , '.hg' ) ) proc = programs . run_program ( 'hg' , [ 'id' , '-nib' , repopath ] ) output , _err = proc . communicate ( ) # output is now : ( ' eba7273c69df + 2015 + default \ n ' , None ) # Split 2 times max to allow spaces in branch names . retur...
def replyToComment ( self , repo_user , repo_name , pull_number , body , in_reply_to ) : """POST / repos / : owner / : repo / pulls / : number / comments Like create , but reply to an existing comment . : param body : The text of the comment . : param in _ reply _ to : The comment ID to reply to ."""
return self . api . makeRequest ( [ "repos" , repo_user , repo_name , "pulls" , str ( pull_number ) , "comments" ] , method = "POST" , data = dict ( body = body , in_reply_to = in_reply_to ) )
def validate ( tmpl , path ) : """Validate a path against the path template . . . code - block : : python > > > validate ( ' users / * / messages / * ' , ' users / me / messages / 123 ' ) True > > > validate ( ' users / * / messages / * ' , ' users / me / drafts / 123 ' ) False > > > validate ( ' / v1 /...
pattern = _generate_pattern_for_template ( tmpl ) + "$" return True if re . match ( pattern , path ) is not None else False
def get_from ( self , x , y ) : """Get the character at the specified location . : param x : The column ( x coord ) of the character . : param y : The row ( y coord ) of the character . : return : A 4 - tuple of ( ascii code , foreground , attributes , background ) for the character at the location ."""
# Convert to buffer coordinates y -= self . _start_line if y < 0 or y >= self . _buffer_height or x < 0 or x >= self . width : return None cell = self . _buffer . get ( x , y ) return cell [ 0 ] , cell [ 1 ] , cell [ 2 ] , cell [ 3 ]
def weld_str_lower ( array ) : """Convert values to lowercase . Parameters array : numpy . ndarray or WeldObject Input data . Returns WeldObject Representation of this computation ."""
obj_id , weld_obj = create_weld_object ( array ) weld_template = """map( {array}, |e: vec[i8]| result( for(e, appender[i8], |c: appender[i8], j: i64, f: i8| if(f > 64c && f < 91c, merge(c, f + 32c), ...
def parse ( self , record , is_first_dir_record_of_root , bytes_to_skip , continuation ) : # type : ( bytes , bool , int , bool ) - > None '''Method to parse a rock ridge record . Parameters : record - The record to parse . is _ first _ dir _ record _ of _ root - Whether this is the first directory record o...
# Note that we very explicitly do not check if self . _ initialized is True # here ; this can be called multiple times in the case where there is # a continuation entry . if continuation : entry_list = self . ce_entries else : entry_list = self . dr_entries self . bytes_to_skip = bytes_to_skip offset = bytes_to...
def update_product_version ( id , ** kwargs ) : """Update the ProductVersion with ID id with new values ."""
content = update_product_version_raw ( id , ** kwargs ) if content : return utils . format_json ( content )
def transform ( self , X , lenscale = None ) : r"""Apply the sigmoid basis function to X . Parameters X : ndarray ( N , d ) array of observations where N is the number of samples , and d is the dimensionality of X . lenscale : float the length scale ( scalar ) of the RBFs to apply to X . If not input , ...
N , d = X . shape lenscale = self . _check_dim ( d , lenscale ) return expit ( cdist ( X / lenscale , self . C / lenscale , 'euclidean' ) )
def from_dict ( cls , d , identifier_str = None ) : """Load a ` ResolvedContext ` from a dict . Args : d ( dict ) : Dict containing context data . identifier _ str ( str ) : String identifying the context , this is only used to display in an error string if a serialization version mismatch is detected . ...
# check serialization version def _print_version ( value ) : return '.' . join ( str ( x ) for x in value ) toks = str ( d [ "serialize_version" ] ) . split ( '.' ) load_ver = tuple ( int ( x ) for x in toks ) curr_ver = ResolvedContext . serialize_version if load_ver [ 0 ] > curr_ver [ 0 ] : msg = [ "The conte...
def default_strlen ( strlen = None ) : """Sets the default string length for lstring and ilwd : char , if they are treated as strings . Default is 50."""
if strlen is not None : _default_types_status [ 'default_strlen' ] = strlen # update the typeDicts as needed lstring_as_obj ( _default_types_status [ 'lstring_as_obj' ] ) ilwd_as_int ( _default_types_status [ 'ilwd_as_int' ] ) return _default_types_status [ 'default_strlen' ]
def thermal_conductivity ( self , temperature , volume ) : """Eq ( 17 ) in 10.1103 / PhysRevB . 90.174107 Args : temperature ( float ) : temperature in K volume ( float ) : in Ang ^ 3 Returns : float : thermal conductivity in W / K / m"""
gamma = self . gruneisen_parameter ( temperature , volume ) theta_d = self . debye_temperature ( volume ) theta_a = theta_d * self . natoms ** ( - 1. / 3. ) prefactor = ( 0.849 * 3 * 4 ** ( 1. / 3. ) ) / ( 20. * np . pi ** 3 ) # kg / K ^ 3 / s ^ 3 prefactor = prefactor * ( self . kb / self . hbar ) ** 3 * self . avg_ma...
def serialize ( self , attr , obj , accessor = None , ** kwargs ) : """Pulls the value for the given key from the object , applies the field ' s formatting and returns the result . : param str attr : The attribute or key to get from the object . : param str obj : The object to pull the key from . : param ca...
if self . _CHECK_ATTRIBUTE : value = self . get_value ( obj , attr , accessor = accessor ) if value is missing_ and hasattr ( self , 'default' ) : default = self . default value = default ( ) if callable ( default ) else default if value is missing_ : return value else : value = ...
def add_new_enriched_bins_matrixes ( region_files , dfs , bin_size ) : """Add enriched bins based on bed files . There is no way to find the correspondence between region file and matrix file , but it does not matter ."""
dfs = _remove_epic_enriched ( dfs ) names = [ "Enriched_" + os . path . basename ( r ) for r in region_files ] regions = region_files_to_bins ( region_files , names , bin_size ) new_dfs = OrderedDict ( ) assert len ( regions . columns ) == len ( dfs ) for region , ( n , df ) in zip ( regions , dfs . items ( ) ) : r...
def mkdir ( path , mode = 0o755 , delete = False ) : """Make a directory . Create a leaf directory and all intermediate ones . Works like ` ` mkdir ` ` , except that any intermediate path segment ( not just the rightmost ) will be created if it does not exist . This is recursive . Args : path ( str ) : Di...
logger . info ( "mkdir: %s" % path ) if os . path . isdir ( path ) : if not delete : return True if not remove ( path ) : return False try : os . makedirs ( path , mode ) return True except Exception : logger . exception ( "Failed to mkdir: %s" % path ) return False
def _read_mode_route ( self , size , kind ) : """Read options with route data . Positional arguments : * size - int , length of option * kind - int , 7/131/137 ( RR / LSR / SSR ) Returns : * dict - - extracted option with route data Structure of these options : * [ RFC 791 ] Loose Source Route | 100...
if size < 3 or ( size - 3 ) % 4 != 0 : raise ProtocolError ( f'{self.alias}: [Optno {kind}] invalid format' ) _rptr = self . _read_unpack ( 1 ) if _rptr < 4 : raise ProtocolError ( f'{self.alias}: [Optno {kind}] invalid format' ) data = dict ( kind = kind , type = self . _read_opt_type ( kind ) , length = size ...
def _from_dict ( cls , _dict ) : """Initialize a Workspace object from a json dictionary ."""
args = { } if 'name' in _dict : args [ 'name' ] = _dict . get ( 'name' ) else : raise ValueError ( 'Required property \'name\' not present in Workspace JSON' ) if 'description' in _dict : args [ 'description' ] = _dict . get ( 'description' ) if 'language' in _dict : args [ 'language' ] = _dict . get ( ...
def apply_connectivity_changes ( self , request ) : """Handle apply connectivity changes request json , trigger add or remove vlan methods , get responce from them and create json response : param request : json with all required action to configure or remove vlans from certain port : return Serialized Driver...
if request is None or request == "" : raise Exception ( self . __class__ . __name__ , "request is None or empty" ) holder = JsonRequestDeserializer ( jsonpickle . decode ( request ) ) if not holder or not hasattr ( holder , "driverRequest" ) : raise Exception ( self . __class__ . __name__ , "Deserialized reques...
def check_unique_attr ( self , attrs , user = None , form = None , flash_msg = None ) : """Checks that an attribute of the current user is unique amongst all users . If no value is provided , the current form will be used ."""
user = user or self . current ucol = self . options [ "username_column" ] email = self . options [ "email_column" ] if not isinstance ( attrs , ( list , tuple , dict ) ) : attrs = [ attrs ] for name in attrs : if isinstance ( attrs , dict ) : value = attrs [ name ] else : form = form or curr...
def get_precinctsreporting ( self , obj ) : """Precincts reporting if vote is top level result else ` ` None ` ` ."""
if obj . division . level == obj . candidate_election . election . division . level : return obj . candidate_election . election . meta . precincts_reporting return None
def tail_threshold ( vals , N = 1000 ) : """Determine a threshold above which there are N louder values"""
vals = numpy . array ( vals ) if len ( vals ) < N : raise RuntimeError ( 'Not enough input values to determine threshold' ) vals . sort ( ) return min ( vals [ - N : ] )
def increment ( self , subname = None , delta = 1 ) : '''Increment the gauge with ` delta ` : keyword subname : The subname to report the data to ( appended to the client name ) : type subname : str : keyword delta : The delta to add to the gauge : type delta : int > > > gauge = Gauge ( ' application _ ...
delta = int ( delta ) sign = "+" if delta >= 0 else "" return self . _send ( subname , "%s%d" % ( sign , delta ) )
def scan_file ( self , this_file , this_filename ) : """Submit a file to be scanned by Malwares : param this _ file : File to be scanned ( 200MB file size limit ) : param this _ filename : Filename for scanned file : return : JSON response that contains scan _ id and permalink ."""
params = { 'api_key' : self . api_key , 'filename' : this_filename } try : files = { 'file' : ( this_file . name , open ( this_file . name , 'rb' ) , 'application/octet-stream' ) } except TypeError as e : return dict ( error = e . message ) try : response = requests . post ( self . base + 'file/upload' , fi...
def tuple_division ( tup1 , tup2 ) : """Function to divide corresponding elements in two given tuples . > > > tuple _ division ( ( 10 , 4 , 6 , 9 ) , ( 5 , 2 , 3 , 3 ) ) (2 , 2 , 2 , 3) > > > tuple _ division ( ( 12 , 6 , 8 , 16 ) , ( 6 , 3 , 4 , 4 ) ) (2 , 2 , 2 , 4) > > > tuple _ division ( ( 20 , 14 , ...
return tuple ( ele1 // ele2 for ele1 , ele2 in zip ( tup1 , tup2 ) )
def playbook_treeview ( playbook ) : """Creates a fake filesystem with playbook files and uses generate _ tree ( ) to recurse and return a JSON structure suitable for bootstrap - treeview ."""
fs = fake_filesystem . FakeFilesystem ( ) mock_os = fake_filesystem . FakeOsModule ( fs ) files = models . File . query . filter ( models . File . playbook_id . in_ ( [ playbook ] ) ) paths = { } for file in files : fs . create_file ( file . path ) paths [ file . path ] = file . id return jsonutils . dumps ( ge...
def embed_data_in_blockchain ( data , private_key , blockchain_client = BlockchainInfoClient ( ) , fee = OP_RETURN_FEE , change_address = None , format = 'bin' ) : """Builds , signs , and dispatches an OP _ RETURN transaction ."""
# build and sign the tx signed_tx = make_op_return_tx ( data , private_key , blockchain_client , fee = fee , change_address = change_address , format = format ) # dispatch the signed transction to the network response = broadcast_transaction ( signed_tx , blockchain_client ) # return the response return response
def most_frequent_item ( lst ) : """This function determines the element with the highest frequency in a given list . Examples : most _ frequent _ item ( [ 1 , 2 , 3 , 1 , 2 , 3 , 12 , 4 , 2 ] ) - > 2 most _ frequent _ item ( [ 1 , 2 , 6 , 7 , 0 , 1 , 0 , 1 , 0 ] ) - > 1 most _ frequent _ item ( [ 1 , 2 , 3...
max_count = 0 frequent_item = lst [ 0 ] for item in lst : item_count = lst . count ( item ) if ( item_count > max_count ) : max_count = item_count frequent_item = item return frequent_item
def readDataAsync ( self , fileName , callback ) : """Interprets the specified data file asynchronously . When interpreting is over , the specified callback is called . The file is interpreted as data . As a side effect , it invalidates all entities ( as the passed file can contain any arbitrary command ) ; t...
def async_call ( ) : self . _lock . acquire ( ) try : self . _impl . readData ( fileName ) self . _errorhandler_wrapper . check ( ) except Exception : self . _lock . release ( ) raise else : self . _lock . release ( ) callback . run ( ) Thread ( target = a...
def impute_dataframe_zero ( df_impute ) : """Replaces all ` ` NaNs ` ` , ` ` - infs ` ` and ` ` + infs ` ` from the DataFrame ` df _ impute ` with 0s . The ` df _ impute ` will be modified in place . All its columns will be into converted into dtype ` ` np . float64 ` ` . : param df _ impute : DataFrame to impu...
df_impute . replace ( [ np . PINF , np . NINF ] , 0 , inplace = True ) df_impute . fillna ( 0 , inplace = True ) # Ensure a type of " np . float64" df_impute . astype ( np . float64 , copy = False ) return df_impute
def get_uri ( source ) : """Check a media source as a valid file or uri and return the proper uri"""
import gst src_info = source_info ( source ) if src_info [ 'is_file' ] : # Is this a file ? return get_uri ( src_info [ 'uri' ] ) elif gst . uri_is_valid ( source ) : # Is this a valid URI source for Gstreamer uri_protocol = gst . uri_get_protocol ( source ) if gst . uri_protocol_is_supported ( gst . URI_SR...
def rebase_array ( d , recursive = False ) : """Transform an indexed dictionary ( such as those returned by the dzn2dict function when parsing arrays ) into an multi - dimensional list . Parameters d : dict The indexed dictionary to convert . bool : recursive Whether to rebase the array recursively . ...
arr = [ ] min_val , max_val = _extremes ( d . keys ( ) ) for idx in range ( min_val , max_val + 1 ) : v = d [ idx ] if recursive and _is_dict ( v ) : v = rebase_array ( v ) arr . append ( v ) return arr
def flush ( self ) : """Write all data from buffer to socket and reset write buffer ."""
if self . _wbuf : buffer = '' . join ( self . _wbuf ) self . _wbuf = [ ] self . write ( buffer )
def POST ( self , ** kwargs ) : '''Start an execution command and immediately return the job id . . http : post : : / minions : reqheader X - Auth - Token : | req _ token | : reqheader Accept : | req _ accept | : reqheader Content - Type : | req _ ct | : resheader Content - Type : | res _ ct | : status ...
job_data = list ( self . exec_lowstate ( client = 'local_async' , token = cherrypy . session . get ( 'token' ) ) ) cherrypy . response . status = 202 return { 'return' : job_data , '_links' : { 'jobs' : [ { 'href' : '/jobs/{0}' . format ( i [ 'jid' ] ) } for i in job_data if i ] , } , }