signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def CreateGRRTempFile ( filename = None , lifetime = 0 , mode = "w+b" , suffix = "" ) : """Open file with GRR prefix in directory to allow easy deletion . Missing parent dirs will be created . If an existing directory is specified its permissions won ' t be modified to avoid breaking system functionality . Pe...
directory = GetDefaultGRRTempDirectory ( ) EnsureTempDirIsSane ( directory ) prefix = config . CONFIG . Get ( "Client.tempfile_prefix" ) if filename is None : outfile = tempfile . NamedTemporaryFile ( prefix = prefix , suffix = suffix , dir = directory , delete = False ) else : if filename . startswith ( "/" ) ...
def mount_points ( self ) : """Iterator of partition ' s mount points obtained by reading / proc / mounts . Returns empty list if / proc / mounts is not readable or if there are no mount points ."""
aliases = self . aliases try : return [ e . mdir for e in mounts ( ) if e . dev in aliases ] except ( OSError , IOError ) : return [ ]
def cli_guilds ( world , tibiadata , json ) : """Displays the list of guilds for a specific world"""
world = " " . join ( world ) guilds = _fetch_and_parse ( ListedGuild . get_world_list_url , ListedGuild . list_from_content , ListedGuild . get_world_list_url_tibiadata , ListedGuild . list_from_tibiadata , tibiadata , world ) if json and guilds : import json as _json print ( _json . dumps ( guilds , default = ...
def _get_subparser ( self , path , group_table = None ) : """For each part of the path , walk down the tree of subparsers , creating new ones if one doesn ' t already exist ."""
group_table = group_table or { } for length in range ( 0 , len ( path ) ) : parent_path = path [ : length ] parent_subparser = self . subparsers . get ( tuple ( parent_path ) , None ) if not parent_subparser : # No subparser exists for the given subpath - create and register # a new subparser . # Si...
def register ( self , kind , handler ) : """Register a handler for a given type , class , interface , or abstract base class . View registration should happen within the ` start ` callback of an extension . For example , to register the previous ` json ` view example : class JSONExtension : def start ( self...
if __debug__ : # In production this logging is completely skipped , regardless of logging level . if py3 and not pypy : # Where possible , we shorten things to just the cannonical name . log . debug ( "Registering view handler." , extra = dict ( type = name ( kind ) , handler = name ( handler ) ) ) else...
def copy ( self ) : """This method can be used for creating a copy of a WCNF object . It creates another object of the : class : ` WCNF ` class and makes use of the * deepcopy * functionality to copy both hard and soft clauses . : return : an object of class : class : ` WCNF ` . Example : . . code - block...
wcnf = WCNF ( ) wcnf . nv = self . nv wcnf . topw = self . topw wcnf . hard = copy . deepcopy ( self . hard ) wcnf . soft = copy . deepcopy ( self . soft ) wcnf . wght = copy . deepcopy ( self . wght ) wcnf . comments = copy . deepcopy ( self . comments ) return wcnf
def pause_multiple ( self , infohash_list ) : """Pause multiple torrents . : param infohash _ list : Single or list ( ) of infohashes ."""
data = self . _process_infohash_list ( infohash_list ) return self . _post ( 'command/pauseAll' , data = data )
def on_connect_button__clicked ( self , event ) : '''Connect to Zero MQ plugin hub ( ` zmq _ plugin . hub . Hub ` ) using the settings from the text entry fields ( e . g . , hub URI , plugin name ) . Emit ` plugin - connected ` signal with the new plugin instance after hub connection has been established .'''
hub_uri = self . plugin_uri . get_text ( ) ui_plugin_name = self . ui_plugin_name . get_text ( ) plugin = self . create_plugin ( ui_plugin_name , hub_uri ) self . init_plugin ( plugin ) self . connect_button . set_sensitive ( False ) self . emit ( 'plugin-connected' , plugin )
def kmeans ( phate_op , k = 8 , random_state = None ) : """KMeans on the PHATE potential Clustering on the PHATE operator as introduced in Moon et al . This is similar to spectral clustering . Parameters phate _ op : phate . PHATE Fitted PHATE operator k : int , optional ( default : 8) Number of clust...
if phate_op . graph is not None : diff_potential = phate_op . calculate_potential ( ) if isinstance ( phate_op . graph , graphtools . graphs . LandmarkGraph ) : diff_potential = phate_op . graph . interpolate ( diff_potential ) return cluster . KMeans ( k , random_state = random_state ) . fit_predic...
def ToInternal ( self ) : """Convert wavelengths to the internal representation of angstroms . For internal use only ."""
self . validate_units ( ) savewunits = self . waveunits angwave = self . waveunits . Convert ( self . _wavetable , 'angstrom' ) self . _wavetable = angwave . copy ( ) self . waveunits = savewunits
def iter_node ( node , name = '' , unknown = None , # Runtime optimization list = list , getattr = getattr , isinstance = isinstance , enumerate = enumerate , missing = NonExistent ) : """Iterates over an object : - If the object has a _ fields attribute , it gets attributes in the order of this and returns n...
fields = getattr ( node , '_fields' , None ) if fields is not None : for name in fields : value = getattr ( node , name , missing ) if value is not missing : yield value , name if unknown is not None : unknown . update ( set ( vars ( node ) ) - set ( fields ) ) elif isinstanc...
def get_template ( template_file = '' , ** kwargs ) : """Get the Jinja2 template and renders with dict _ kwargs _ . Args : template _ file ( str ) : name of the template file kwargs : Keywords to use for rendering the Jinja2 template . Returns : String of rendered JSON template ."""
template = get_template_object ( template_file ) LOG . info ( 'Rendering template %s' , template . filename ) for key , value in kwargs . items ( ) : LOG . debug ( '%s => %s' , key , value ) rendered_json = template . render ( ** kwargs ) LOG . debug ( 'Rendered JSON:\n%s' , rendered_json ) return rendered_json
def get_tier_from_participants ( participantsIdentities , minimum_tier = Tier . bronze , queue = Queue . RANKED_SOLO_5x5 ) : """Returns the tier of the lowest tier and the participantsIDs divided by tier player in the match : param participantsIdentities : the match participants : param minimum _ tier : the m...
leagues = leagues_by_summoner_ids ( [ p . player . summonerId for p in participantsIdentities ] , queue ) match_tier = max ( leagues . keys ( ) , key = operator . attrgetter ( 'value' ) ) return match_tier , { league : ids for league , ids in leagues . items ( ) if league . is_better_or_equal ( minimum_tier ) }
def render_tag_from_config ( self ) : """Configure tag _ from _ config plugin"""
phase = 'postbuild_plugins' plugin = 'tag_from_config' if not self . has_tag_suffixes_placeholder ( ) : return unique_tag = self . user_params . image_tag . value . split ( ':' ) [ - 1 ] tag_suffixes = { 'unique' : [ unique_tag ] , 'primary' : [ ] } if self . user_params . build_type . value == BUILD_TYPE_ORCHESTRA...
def __MaxSizeToInt ( self , max_size ) : """Convert max _ size to an int ."""
size_groups = re . match ( r'(?P<size>\d+)(?P<unit>.B)?$' , max_size ) if size_groups is None : raise ValueError ( 'Could not parse maxSize' ) size , unit = size_groups . group ( 'size' , 'unit' ) shift = 0 if unit is not None : unit_dict = { 'KB' : 10 , 'MB' : 20 , 'GB' : 30 , 'TB' : 40 } shift = unit_dict...
def close_milestone ( self , id , ** kwargs ) : """Close / Release a Product Milestone This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please define a ` callback ` function to be invoked when receiving the response . > > > def callback _ function ( response )...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'callback' ) : return self . close_milestone_with_http_info ( id , ** kwargs ) else : ( data ) = self . close_milestone_with_http_info ( id , ** kwargs ) return data
def schemes ( self ) : """Return supported schemes ."""
if not self . _schemes : _schemes = [ ] if self . types . keys ( ) & _HTTP_PROTOS : _schemes . append ( 'HTTP' ) if self . types . keys ( ) & _HTTPS_PROTOS : _schemes . append ( 'HTTPS' ) self . _schemes = tuple ( _schemes ) return self . _schemes
async def Set ( self , annotations ) : '''annotations : typing . Sequence [ ~ EntityAnnotations ] Returns - > typing . Sequence [ ~ ErrorResult ]'''
# map input types to rpc msg _params = dict ( ) msg = dict ( type = 'Annotations' , request = 'Set' , version = 2 , params = _params ) _params [ 'annotations' ] = annotations reply = await self . rpc ( msg ) return reply
def substitute ( sequence , offset , ref , alt ) : """Mutate a sequence by substituting given ` alt ` at instead of ` ref ` at the given ` position ` . Parameters sequence : sequence String of amino acids or DNA bases offset : int Base 0 offset from start of ` sequence ` ref : sequence or str What d...
n_ref = len ( ref ) sequence_ref = sequence [ offset : offset + n_ref ] assert str ( sequence_ref ) == str ( ref ) , "Reference %s at offset %d != expected reference %s" % ( sequence_ref , offset , ref ) prefix = sequence [ : offset ] suffix = sequence [ offset + n_ref : ] return prefix + alt + suffix
def get_settings ( self ) : """Returns current settings . Only accessible if authenticated as the user ."""
url = self . _imgur . _base_url + "/3/account/{0}/settings" . format ( self . name ) return self . _imgur . _send_request ( url )
def variables ( self ) : '''return a list of available variables'''
return sorted ( list ( self . mapping . vars . keys ( ) ) , key = lambda v : self . mapping . vars [ v ] . index )
def stop ( self , group_mask = ALL_GROUPS ) : """stops the current trajectory ( turns off the motors ) : param group _ mask : mask for which CFs this should apply to : return :"""
self . _send_packet ( struct . pack ( '<BB' , self . COMMAND_STOP , group_mask ) )
def load_menus ( c ) : """load _ menus loops through INSTALLED _ APPS and loads the menu . py files from them ."""
# we don ' t need to do this more than once if c . loaded : return # Fetch all installed app names app_names = settings . INSTALLED_APPS if apps : app_names = [ app_config . name for app_config in apps . get_app_configs ( ) ] # loop through our INSTALLED _ APPS for app in app_names : # skip any django apps ...
def is_ready ( self ) : """Is thread & ioloop ready . : returns bool :"""
if not self . _thread : return False if not self . _ready . is_set ( ) : return False return True
def cache ( self , con ) : """Put a dedicated connection back into the idle cache ."""
self . _lock . acquire ( ) try : if not self . _maxcached or len ( self . _idle_cache ) < self . _maxcached : con . _reset ( force = self . _reset ) # rollback possible transaction # the idle cache is not full , so put it there self . _idle_cache . append ( con ) # append it ...
def check_output ( self , ** kwargs ) : """Runs this command returning its captured stdout . : param kwargs : Any extra keyword arguments to pass along to ` subprocess . Popen ` . : returns : The captured standard output stream of the command . : rtype : string : raises : : class : ` subprocess . CalledProc...
env , kwargs = self . _prepare_env ( kwargs ) return subprocess . check_output ( self . cmd , env = env , ** kwargs ) . decode ( 'utf-8' )
def update_object_with_data ( content , record ) : """Update the content with the record data : param content : A single folderish catalog brain or content object : type content : ATContentType / DexterityContentType / CatalogBrain : param record : The data to update : type record : dict : returns : The u...
# ensure we have a full content object content = get_object ( content ) # get the proper data manager dm = IDataManager ( content ) if dm is None : fail ( 400 , "Update for this object is not allowed" ) # Iterate through record items for k , v in record . items ( ) : try : success = dm . set ( k , v , *...
def check_all ( self ) -> Generator [ AAAError , None , None ] : """Run everything required for checking this function . Returns : A generator of errors . Raises : ValidationError : A non - recoverable linting error is found ."""
# Function def if function_is_noop ( self . node ) : return self . mark_bl ( ) self . mark_def ( ) # ACT # Load act block and kick out when none is found self . act_node = self . load_act_node ( ) self . act_block = Block . build_act ( self . act_node . node , self . node ) act_block_first_line_no , act_block_last_...
def transmit ( self , what = None , to_whom = None ) : """Transmit one or more infos from one node to another . " what " dictates which infos are sent , it can be : (1 ) None ( in which case the node ' s _ what method is called ) . (2 ) an Info ( in which case the node transmits the info ) (3 ) a subclass o...
# make the list of what what = self . flatten ( [ what ] ) for i in range ( len ( what ) ) : if what [ i ] is None : what [ i ] = self . _what ( ) elif inspect . isclass ( what [ i ] ) and issubclass ( what [ i ] , Info ) : what [ i ] = self . infos ( type = what [ i ] ) what = self . flatten ( ...
def _GetResources ( hsrc , types = None , names = None , languages = None ) : """Get resources from hsrc . types = a list of resource types to search for ( None = all ) names = a list of resource names to search for ( None = all ) languages = a list of resource languages to search for ( None = all ) Return ...
if types : types = set ( types ) if names : names = set ( names ) if languages : languages = set ( languages ) res = { } try : # logger . debug ( " Enumerating resource types " ) enum_types = win32api . EnumResourceTypes ( hsrc ) if types and not "*" in types : enum_types = filter ( lambda t...
def cardinal ( self , to ) : """Return the number of dependencies of this package to the given node . Args : to ( Package / Module ) : target node . Returns : int : number of dependencies ."""
return sum ( m . cardinal ( to ) for m in self . submodules )
def _is_bst ( root , min_value = float ( '-inf' ) , max_value = float ( 'inf' ) ) : """Check if the binary tree is a BST ( binary search tree ) . : param root : Root node of the binary tree . : type root : binarytree . Node | None : param min _ value : Minimum node value seen . : type min _ value : int | fl...
if root is None : return True return ( min_value < root . value < max_value and _is_bst ( root . left , min_value , root . value ) and _is_bst ( root . right , root . value , max_value ) )
def raw_input_replacement ( self , prompt = '' ) : """For raw _ input builtin function emulation"""
self . widget_proxy . wait_input ( prompt ) self . input_condition . acquire ( ) while not self . widget_proxy . data_available ( ) : self . input_condition . wait ( ) inp = self . widget_proxy . input_data self . input_condition . release ( ) return inp
def claim_exp ( self , data ) : """Required expiration time ."""
expiration = getattr ( settings , 'OAUTH_ID_TOKEN_EXPIRATION' , 30 ) expires = self . now + timedelta ( seconds = expiration ) return timegm ( expires . utctimetuple ( ) )
def left ( self ) : """Entry is left sibling of current directory entry"""
return self . source . directory [ self . left_sibling_id ] if self . left_sibling_id != NOSTREAM else None
def set_style ( key ) : """Select a style by name , e . g . set _ style ( ' default ' ) . To revert to the previous style use the key ' unset ' or False ."""
if key is None : return elif not key or key in [ 'unset' , 'backup' ] : if 'backup' in styles : plt . rcParams . update ( styles [ 'backup' ] ) else : raise Exception ( 'No style backed up to restore' ) elif key not in styles : raise KeyError ( '%r not in available styles.' ) else : ...
def plot ( shape_records , facecolor = 'w' , edgecolor = 'k' , linewidths = .5 , ax = None , xlims = None , ylims = None ) : """Plot the geometry of a shapefile : param shape _ records : geometry and attributes list : type shape _ records : ShapeRecord object ( output of a shapeRecords ( ) method ) : param fa...
# Axes handle if ax is None : fig = pb . figure ( ) ax = fig . add_subplot ( 111 ) # Iterate over shape _ records for srec in shape_records : points = np . vstack ( srec . shape . points ) sparts = srec . shape . parts par = list ( sparts ) + [ points . shape [ 0 ] ] polygs = [ ] for pj in r...
def describe_connection ( self ) : """Return string representation of the device , including the connection state"""
if self . device == None : return "%s [disconnected]" % ( self . name ) else : return "%s connected to %s %s version: %s [serial: %s]" % ( self . name , self . vendor_name , self . product_name , self . version_number , self . serial_number )
def pairwise_distances ( x , y = None , ** kwargs ) : r"""pairwise _ distances ( x , y = None , * , exponent = 1) Pairwise distance between points . Return the pairwise distance between points in two sets , or in the same set if only one set is passed . Parameters x : array _ like An : math : ` n \ time...
x = _transform_to_2d ( x ) if y is None or y is x : return _pdist ( x , ** kwargs ) else : y = _transform_to_2d ( y ) return _cdist ( x , y , ** kwargs )
def undo ( ui , repo , clname , ** opts ) : """undo the effect of a CL Creates a new CL that undoes an earlier CL . After creating the CL , opens the CL text for editing so that you can add the reason for the undo to the description ."""
if repo [ None ] . branch ( ) != "default" : raise hg_util . Abort ( "cannot run hg undo outside default branch" ) err = clpatch_or_undo ( ui , repo , clname , opts , mode = "undo" ) if err : raise hg_util . Abort ( err )
async def cleanup ( self , ctx , search : int = 100 ) : """Cleans up the bot ' s messages from the channel . If a search number is specified , it searches that many messages to delete . If the bot has Manage Messages permissions , then it will try to delete messages that look like they invoked the bot as well...
spammers = Counter ( ) channel = ctx . message . channel prefixes = self . bot . command_prefix if callable ( prefixes ) : prefixes = prefixes ( self . bot , ctx . message ) def is_possible_command_invoke ( entry ) : valid_call = any ( entry . content . startswith ( prefix ) for prefix in prefixes ) return ...
def _calculateParameters ( self , fout ) : q_d_f = 0 '''fout = fref * ( p _ total / q _ total ) * ( 1 / div ) p _ total = 2 * ( ( p _ counter + 4 ) + p _ 0 ) [ 16 . . 1023] q _ total = q _ counter + 2 [ 2 . . 129] div = [ 2 , ( 3 ) , 4 . . 127] constraints : f _ ref * p _ total / q _ total = [ 100 . ....
for self . q_counter in range ( 128 ) : self . q_total = self . q_counter + 2 if ( self . fref / self . q_total ) < 0.25 : # PLL constraint break for self . div in range ( 2 , 128 ) : q_d_f = self . q_total * self . div * fout if isinstance ( q_d_f , six . integer_types ) and q_d_f >...
def process_import_request ( username , path , timestamp , logger_handler ) : """React to import request . Look into user ' s directory and react to files user uploaded there . Behavior of this function can be set by setting variables in : mod : ` ftp . settings ` . Args : username ( str ) : Name of the u...
items = [ ] error_protocol = [ ] # import logger into local namespace global logger logger = logger_handler # read user configuration user_conf = passwd_reader . read_user_config ( username ) # lock directory to prevent user to write during processing of the batch logger . info ( "Locking user´s directory." ) recursive...
def get_team_players ( self , team ) : """Queries the API and fetches the players for a particular team"""
team_id = self . team_names . get ( team , None ) try : req = self . _get ( 'teams/{}/' . format ( team_id ) ) team_players = req . json ( ) [ 'squad' ] if not team_players : click . secho ( "No players found for this team" , fg = "red" , bold = True ) else : self . writer . team_players...
def elcm_session_delete ( irmc_info , session_id , terminate = False ) : """send an eLCM request to remove a session from the session list : param irmc _ info : node info : param session _ id : session id : param terminate : a running session must be terminated before removing : raises : ELCMSessionNotFound...
# Terminate the session first if needs to if terminate : # Get session status to check session = elcm_session_get_status ( irmc_info , session_id ) status = session [ 'Session' ] [ 'Status' ] # Terminate session if it is activated or running if status == 'running' or status == 'activated' : elcm...
def add_current_text_if_valid ( self ) : """Add current text to combo box history if valid"""
valid = self . is_valid ( self . currentText ( ) ) if valid or valid is None : self . add_current_text ( ) return True else : self . set_current_text ( self . selected_text )
def show ( ) : """Show image summary information"""
ecode = 0 try : o = collections . OrderedDict ( ) inimage = imagelist [ 0 ] anchoreDB = contexts [ 'anchore_db' ] image = anchoreDB . load_image ( inimage ) if image : mymeta = image [ 'meta' ] alltags_current = image [ 'anchore_current_tags' ] distrodict = anchore_utils . ge...
def _GSE2_PAZ_read ( gsefile ) : """Read the instrument response information from a GSE Poles and Zeros file . Formatted for files generated by the SEISAN program RESP . Format must be CAL2 , not coded for any other format at the moment , contact the authors to add others in . : type gsefile : string : pa...
with open ( gsefile , 'r' ) as f : # First line should start with CAL2 header = f . readline ( ) if not header [ 0 : 4 ] == 'CAL2' : raise IOError ( 'Unknown format for GSE file, only coded for CAL2' ) station = header . split ( ) [ 1 ] channel = header . split ( ) [ 2 ] sensor = header . sp...
def EnumerateAllConfigs ( self , stats , file_objects ) : """Generate RDFs for the fully expanded configs . Args : stats : A list of RDF StatEntries corresponding to the file _ objects . file _ objects : A list of file handles . Returns : A tuple of a list of RDFValue PamConfigEntries found & a list of st...
# Convert the stats & file _ objects into a cache of a # simple path keyed dict of file contents . cache = { } for stat_obj , file_obj in zip ( stats , file_objects ) : cache [ stat_obj . pathspec . path ] = utils . ReadFileBytesAsUnicode ( file_obj ) result = [ ] external = [ ] # Check to see if we have the old pa...
def refresh ( self ) : """Re - traces modules modified since the time they were traced ."""
self . trace ( list ( self . _fnames . keys ( ) ) , _refresh = True )
def epilogue ( app_name ) : """Return the epilogue for the help command ."""
app_name = clr . stringc ( app_name , "bright blue" ) command = clr . stringc ( "command" , "cyan" ) help = clr . stringc ( "--help" , "green" ) return "\n%s %s %s for more info on a command\n" % ( app_name , command , help )
def delete_file ( f ) : """Delete the given file : param f : the file to delete : type f : : class : ` JB _ File ` : returns : None : rtype : None : raises : : class : ` OSError `"""
fp = f . get_fullpath ( ) log . info ( "Deleting file %s" , fp ) os . remove ( fp )
def parse_elem ( element ) : """Parse a OSM node XML element . Args : element ( etree . Element ) : XML Element to parse Returns : Node : Object representing parsed element"""
ident = int ( element . get ( 'id' ) ) latitude = element . get ( 'lat' ) longitude = element . get ( 'lon' ) flags = _parse_flags ( element ) return Node ( ident , latitude , longitude , * flags )
def handle_exception ( self , exc_info = None , rendered = False , source_hint = None ) : """Exception handling helper . This is used internally to either raise rewritten exceptions or return a rendered traceback for the template ."""
global _make_traceback if exc_info is None : exc_info = sys . exc_info ( ) # the debugging module is imported when it ' s used for the first time . # we ' re doing a lot of stuff there and for applications that do not # get any exceptions in template rendering there is no need to load # all of that . if _make_trace...
def update_menu ( self ) : """Update context menu"""
self . menu . clear ( ) add_actions ( self . menu , self . create_context_menu_actions ( ) )
def fold ( self , elems ) : """Perform constant folding . If the result of applying the operator to the elements would be a fixed constant value , returns the result of applying the operator to the operands . Otherwise , returns an instance of ` ` Instructions ` ` containing the instructions necessary to ap...
# Are the elements constants ? if all ( isinstance ( e , Constant ) for e in elems ) : return [ Constant ( self . op ( * [ e . value for e in elems ] ) ) ] return [ Instructions ( elems [ : ] + [ self ] ) ]
def get_invoices ( self , limit = 50 , closed = False , get_all = False ) : """Gets an accounts invoices . : param int limit : Number of invoices to get back in a single call . : param bool closed : If True , will also get CLOSED invoices : param bool get _ all : If True , will paginate through invoices until...
mask = "mask[invoiceTotalAmount, itemCount]" _filter = { 'invoices' : { 'createDate' : { 'operation' : 'orderBy' , 'options' : [ { 'name' : 'sort' , 'value' : [ 'DESC' ] } ] } , 'statusCode' : { 'operation' : 'OPEN' } , } } if closed : del _filter [ 'invoices' ] [ 'statusCode' ] return self . client . call ( 'Accou...
def validate ( cnpj_number ) : """This function validates a CNPJ number . This function uses calculation package to calculate both digits and then validates the number . : param cnpj _ number : a CNPJ number to be validated . Only numbers . : type cnpj _ number : string : return : Bool - - True for a vali...
_cnpj = compat . clear_punctuation ( cnpj_number ) if ( len ( _cnpj ) != 14 or len ( set ( _cnpj ) ) == 1 ) : return False first_part = _cnpj [ : 12 ] second_part = _cnpj [ : 13 ] first_digit = _cnpj [ 12 ] second_digit = _cnpj [ 13 ] if ( first_digit == calc . calculate_first_digit ( first_part ) and second_digit ...
def get_orgas ( self ) : """Return the list of pk for all orgas"""
r = self . _request ( 'orgas/' ) if not r : return None retour = [ ] for data in r . json ( ) [ 'data' ] : o = Orga ( ) o . __dict__ . update ( data ) o . pk = o . id retour . append ( o ) return retour
def execute ( self , conn , block_name = "" , transaction = False ) : """block : / a / b / c # d"""
if not conn : dbsExceptionHandler ( "dbsException-failed-connect2host" , "Oracle/BlockParent/List. Expects db connection from upper layer." , self . logger . exception ) sql = self . sql if isinstance ( block_name , basestring ) : binds = { 'block_name' : block_name } elif type ( block_name ) is list : bind...
def create_fake_copies ( files , destination ) : """Create copies of the given list of files in the destination given . Creates copies of the actual files to be committed using git show : < filename > Return a list of destination files ."""
dest_files = [ ] for filename in files : leaf_dest_folder = os . path . join ( destination , os . path . dirname ( filename ) ) if not os . path . exists ( leaf_dest_folder ) : os . makedirs ( leaf_dest_folder ) dest_file = os . path . join ( destination , filename ) bash ( "git show :{filename}...
def qs_from_dict ( qsdict , prefix = "" ) : '''Same as dict _ from _ qs , but in reverse i . e . { " period " : { " di " : { } , " fhr " : { } } } = > " period . di , period . fhr "'''
prefix = prefix + '.' if prefix else "" def descend ( qsd ) : for key , val in sorted ( qsd . items ( ) ) : if val : yield qs_from_dict ( val , prefix + key ) else : yield prefix + key return "," . join ( descend ( qsdict ) )
def interfaces_info ( ) : """Returns interfaces data ."""
def replace ( value ) : if value == netifaces . AF_LINK : return 'link' if value == netifaces . AF_INET : return 'ipv4' if value == netifaces . AF_INET6 : return 'ipv6' return value results = { } for iface in netifaces . interfaces ( ) : addrs = netifaces . ifaddresses ( ifac...
def _select_property ( self , line ) : """try to match a property and load it"""
g = self . current [ 'graph' ] if not line : out = g . all_properties using_pattern = False else : using_pattern = True if line . isdigit ( ) : line = int ( line ) out = g . get_property ( line ) if out : if type ( out ) == type ( [ ] ) : choice = self . _selectFromList ( out , u...
def sort_dicoms ( dicoms ) : """Sort the dicoms based om the image possition patient : param dicoms : list of dicoms"""
# find most significant axis to use during sorting # the original way of sorting ( first x than y than z ) does not work in certain border situations # where for exampe the X will only slightly change causing the values to remain equal on multiple slices # messing up the sorting completely ) dicom_input_sorted_x = sort...
def field_dict ( self , model ) : """Helper function that returns a dictionary of all fields in the given model . If self . field _ filter is set , it only includes the fields that match the filter ."""
if self . field_filter : return dict ( [ ( f . name , f ) for f in model . _meta . fields if self . field_filter ( f ) ] ) else : return dict ( [ ( f . name , f ) for f in model . _meta . fields if not f . rel and not f . primary_key and not f . unique and not isinstance ( f , ( models . AutoField , models . Te...
def apply_taper ( delta_t , taper , f_0 , tau , amp , phi , l , m , inclination ) : """Return tapering window ."""
# Times of tapering do not include t = 0 taper_times = - numpy . arange ( 1 , int ( taper * tau / delta_t ) ) [ : : - 1 ] * delta_t Y_plus , Y_cross = spher_harms ( l , m , inclination ) taper_hp = amp * Y_plus * numpy . exp ( 10 * taper_times / tau ) * numpy . cos ( two_pi * f_0 * taper_times + phi ) taper_hc = amp * ...
def get_comments_for_commentor_on_date ( self , resource_id , from_ , to ) : """Gets a list of all comments corresponding to a resource ` ` Id ` ` and effective during the entire given date range inclusive but not confined to the date range . arg : resource _ id ( osid . id . Id ) : the ` ` Id ` ` of the resource...
# Implemented from template for # osid . relationship . RelationshipLookupSession . get _ relationships _ for _ destination _ on _ date comment_list = [ ] for comment in self . get_comments_for_commentor ( ) : if overlap ( from_ , to , comment . start_date , comment . end_date ) : comment_list . append ( co...
def get_helper ( name = None , quiet = True , ** kwargs ) : '''get the correct helper depending on the environment variable HELPME _ CLIENT quiet : if True , suppress most output about the client ( e . g . speak )'''
# Second priority , from environment from helpme . defaults import HELPME_CLIENT # First priority , from command line if name is not None : HELPME_CLIENT = name # If no obvious credential provided , we can use HELPME _ CLIENT if HELPME_CLIENT == 'github' : from . github import Helper ; elif HELPME_CLIENT == 'us...
def fix ( self , value = None ) : """Fix all instances of this variable to a value if provided or to their current value otherwise . Args : value : value to be set ."""
if value is None : self . _impl . fix ( ) else : self . _impl . fix ( value )
def get_entries ( self , criteria , inc_structure = False , optional_data = None ) : """Get ComputedEntries satisfying a particular criteria . . . note : : The get _ entries _ in _ system and get _ entries methods should be used with care . In essence , all entries , GGA , GGA + U or otherwise , are returne...
all_entries = list ( ) optional_data = [ ] if not optional_data else list ( optional_data ) optional_data . append ( "oxide_type" ) fields = [ k for k in optional_data ] fields . extend ( [ "task_id" , "unit_cell_formula" , "energy" , "is_hubbard" , "hubbards" , "pseudo_potential.labels" , "pseudo_potential.functional"...
def linkcode_resolve ( domain , info ) : # NOQA : C901 """Determine the URL corresponding to Python object Notes From https : / / github . com / numpy / numpy / blob / v1.15.1 / doc / source / conf . py , 7c49cfa on Jul 31 . License BSD - 3 . https : / / github . com / numpy / numpy / blob / v1.15.1 / LICENSE...
if domain != 'py' : return None modname = info [ 'module' ] fullname = info [ 'fullname' ] submod = sys . modules . get ( modname ) if submod is None : return None obj = submod for part in fullname . split ( '.' ) : try : obj = getattr ( obj , part ) except Exception : return None # stri...
def call_jira_rest ( self , url , user , password , method = "GET" , data = None ) : """Make JIRA REST call : param data : data for rest call : param method : type of call : GET or POST for now : param url : url to call : param user : user for authentication : param password : password for authentication ...
headers = { 'content-type' : 'application/json' } self . _logger . debug ( 'Connecting to Jira to call the following REST method {0}' . format ( url ) ) if method == "GET" : response = requests . get ( self . base_url + url , auth = requests . auth . HTTPBasicAuth ( user , password ) ) elif method == "POST" : r...
def stop ( self ) : """Stop the timer ."""
if self . _t0 is None : raise RuntimeError ( 'Timer not started.' ) self . _time += self . _get_time ( ) self . _t0 = None
def setdim ( P , dim = None ) : """Adjust the dimensions of a polynomial . Output the results into Poly object Args : P ( Poly ) : Input polynomial dim ( int ) : The dimensions of the output polynomial . If omitted , increase polynomial with one dimension . If the new dim is smaller then P ' s dimension...
P = P . copy ( ) ldim = P . dim if not dim : dim = ldim + 1 if dim == ldim : return P P . dim = dim if dim > ldim : key = numpy . zeros ( dim , dtype = int ) for lkey in P . keys : key [ : ldim ] = lkey P . A [ tuple ( key ) ] = P . A . pop ( lkey ) else : key = numpy . zeros ( dim ,...
def scroll ( self , start_locator , end_locator ) : """Scrolls from one element to another Key attributes for arbitrary elements are ` id ` and ` name ` . See ` introduction ` for details about locating elements ."""
el1 = self . _element_find ( start_locator , True , True ) el2 = self . _element_find ( end_locator , True , True ) driver = self . _current_application ( ) driver . scroll ( el1 , el2 )
def mean_loss_ratios_with_steps ( self , steps ) : """Split the mean loss ratios , producing a new set of loss ratios . The new set of loss ratios always includes 0.0 and 1.0 : param int steps : the number of steps we make to go from one loss ratio to the next . For example , if we have [ 0.5 , 0.7 ] : : ...
loss_ratios = self . mean_loss_ratios if min ( loss_ratios ) > 0.0 : # prepend with a zero loss_ratios = numpy . concatenate ( [ [ 0.0 ] , loss_ratios ] ) if max ( loss_ratios ) < 1.0 : # append a 1.0 loss_ratios = numpy . concatenate ( [ loss_ratios , [ 1.0 ] ] ) return fine_graining ( loss_ratios , steps )
def account_setup ( remote , token , resp ) : """Perform additional setup after user have been logged in ."""
resource = get_resource ( remote ) with db . session . begin_nested ( ) : person_id = resource . get ( 'PersonID' , [ None ] ) external_id = resource . get ( 'uidNumber' , person_id ) [ 0 ] # Set CERN person ID in extra _ data . token . remote_account . extra_data = { 'external_id' : external_id , } ...
def _get_requested_databases ( self ) : """Returns a list of databases requested , not including ignored dbs"""
requested_databases = [ ] if ( ( self . _requested_namespaces is not None ) and ( self . _requested_namespaces != [ ] ) ) : for requested_namespace in self . _requested_namespaces : if requested_namespace [ 0 ] is '*' : return [ ] elif requested_namespace [ 0 ] not in IGNORE_DBS : ...
def readWord ( self ) : """Reads a word value from the L { ReadData } stream object . @ rtype : int @ return : The word value read from the L { ReadData } stream ."""
word = unpack ( self . endianness + ( 'H' if not self . signed else 'h' ) , self . readAt ( self . offset , 2 ) ) [ 0 ] self . offset += 2 return word
def source_loader ( self , source_paths , create_missing_tables = True ) : """Load source from 3 csv files . First file should contain global settings : * ` ` native _ lagnauge , languages ` ` header on first row * appropriate values on following rows Example : : native _ lagnauge , languages ru , ru ...
if not isinstance ( source_paths , Iterable ) or len ( source_paths ) < 3 : raise TypeError ( 'FromCSVTablesGenerator.source_loader accepts list of 3 paths as argument. Got `%s` instead' % source_paths ) self . native_language = '' self . languages = [ ] self . templates = [ ] self . tables = { } self . load_settin...
def align ( args ) : """% prog align clustfile Align clustfile to clustSfile . Useful for benchmarking aligners ."""
p = OptionParser ( align . __doc__ ) p . set_cpus ( ) opts , args = p . parse_args ( args ) if len ( args ) != 1 : sys . exit ( not p . print_help ( ) ) clustfile , = args parallel_musclewrap ( clustfile , opts . cpus )
def set_defaults ( self ) : """Add each model entry with it ' s default"""
for key , value in self . spec . items ( ) : setattr ( self , key . upper ( ) , value . get ( "default" , None ) )
def error_creator5 ( ) : """Raise a safe style error and append a full message ."""
try : error_creator4 ( ) except SafeError as e4 : message = ErrorMessage ( 'Creator 5 problem' , detail = Message ( Paragraph ( 'Could not' , ImportantText ( 'call' ) , 'function.' ) , Paragraph ( 'Try reinstalling your computer with windows.' ) ) , suggestion = Message ( ImportantText ( 'Important note' ) ) ) ...
def script ( klass , args , interval ) : """Run the script * args * every * interval * ( e . g . " 10s " ) to peform health check"""
if isinstance ( args , six . string_types ) or isinstance ( args , six . binary_type ) : warnings . warn ( "Check.script should take a list of args" , DeprecationWarning ) args = [ "sh" , "-c" , args ] return { 'args' : args , 'interval' : interval }
def run_file ( name , database , query_file = None , output = None , grain = None , key = None , overwrite = True , saltenv = None , check_db_exists = True , ** connection_args ) : '''Execute an arbitrary query on the specified database . . versionadded : : 2017.7.0 name Used only as an ID database The na...
ret = { 'name' : name , 'changes' : { } , 'result' : True , 'comment' : 'Database {0} is already present' . format ( database ) } if any ( [ query_file . startswith ( proto ) for proto in [ 'http://' , 'https://' , 'salt://' , 's3://' , 'swift://' ] ] ) : query_file = __salt__ [ 'cp.cache_file' ] ( query_file , sal...
def vector_dot ( vector1 , vector2 ) : """Computes the dot - product of the input vectors . : param vector1 : input vector 1 : type vector1 : list , tuple : param vector2 : input vector 2 : type vector2 : list , tuple : return : result of the dot product : rtype : float"""
try : if vector1 is None or len ( vector1 ) == 0 or vector2 is None or len ( vector2 ) == 0 : raise ValueError ( "Input vectors cannot be empty" ) except TypeError as e : print ( "An error occurred: {}" . format ( e . args [ - 1 ] ) ) raise TypeError ( "Input must be a list or tuple" ) except Except...
def weld_groupby_aggregate ( grouped_df , weld_types , by_indices , aggregation , result_type = None ) : """Perform aggregation on grouped data . Parameters grouped _ df : WeldObject DataFrame which has been grouped through weld _ groupby . weld _ types : list of WeldType Corresponding to data . by _ in...
obj_id , weld_obj = create_weld_object ( grouped_df ) all_indices = list ( range ( len ( weld_types ) ) ) column_indices = list ( filter ( lambda x : x not in by_indices , all_indices ) ) by_weld_types = [ weld_types [ i ] for i in by_indices ] column_weld_types = [ weld_types [ i ] for i in column_indices ] new_column...
def _restoreItemFromArchive ( self ) : """Callback for item menu ."""
if self . _current_item is None : return dp = getattr ( self . _current_item , '_dp' , None ) if dp and dp . archived : dp . restore_from_archive ( parent = self )
def forward_local ( self , local_port , remote_port = None , remote_host = "localhost" , local_host = "localhost" , ) : """Open a tunnel connecting ` ` local _ port ` ` to the server ' s environment . For example , say you want to connect to a remote PostgreSQL database which is locked down and only accessible ...
if not remote_port : remote_port = local_port # TunnelManager does all of the work , sitting in the background ( so we # can yield ) and spawning threads every time somebody connects to our # local port . finished = Event ( ) manager = TunnelManager ( local_port = local_port , local_host = local_host , remote_port ...
def _add_vxr_levels_r ( self , f , vxrhead , numVXRs ) : '''Build a new level of VXRs . . . make VXRs more tree - like From : VXR1 - > VXR2 - > VXR3 - > VXR4 - > . . . - > VXRn To : new VXR1 / | VXR2 VXR3 VXR4 VXR5 . . . . . VXRn Parameters : f : file The open CDF file vxrhead : int The byte l...
newNumVXRs = int ( numVXRs / CDF . NUM_VXRlvl_ENTRIES ) remaining = int ( numVXRs % CDF . NUM_VXRlvl_ENTRIES ) vxroff = vxrhead prevxroff = - 1 if ( remaining != 0 ) : newNumVXRs += 1 CDF . level += 1 for x in range ( 0 , newNumVXRs ) : newvxroff = self . _write_vxr ( f , numEntries = CDF . NUM_VXRlvl_ENTRIES )...
def send_file ( self , recipient_id , file_path , notification_type = NotificationType . regular ) : """Send file to the specified recipient . https : / / developers . facebook . com / docs / messenger - platform / send - api - reference / file - attachment Input : recipient _ id : recipient id to send to f...
return self . send_attachment ( recipient_id , "file" , file_path , notification_type )
def derivable ( self ) : """Whether the spec ( only valid for derived specs ) can be derived given the inputs and switches provided to the study"""
try : # Just need to iterate all study inputs and catch relevant # exceptions list ( self . pipeline . study_inputs ) except ( ArcanaOutputNotProducedException , ArcanaMissingDataException ) : return False return True
def getInstalledThemes ( self , store ) : """Collect themes from all offerings installed on this store , or ( if called multiple times ) return the previously collected list ."""
if not store in self . _getInstalledThemesCache : self . _getInstalledThemesCache [ store ] = ( self . _realGetInstalledThemes ( store ) ) return self . _getInstalledThemesCache [ store ]
def _get_manifest_data ( self ) : """Return the list of items in the manifest : return : list"""
with tempfile . NamedTemporaryFile ( delete = True ) as tmp : try : self . s3 . download_fileobj ( self . sitename , self . manifest_file , tmp ) tmp . seek ( 0 ) data = tmp . read ( ) if data is not None : return data . split ( "," ) except Exception as ex : ...
def is_symbol ( string ) : """Return true if the string is a mathematical symbol ."""
return ( is_int ( string ) or is_float ( string ) or is_constant ( string ) or is_unary ( string ) or is_binary ( string ) or ( string == '(' ) or ( string == ')' ) )
def getNumDownloads ( self , fileInfo ) : """Function to get the number of times a file has been downloaded"""
downloads = fileInfo [ fileInfo . find ( "FILE INFORMATION" ) : ] if - 1 != fileInfo . find ( "not included in ranking" ) : return "0" downloads = downloads [ : downloads . find ( ".<BR>" ) ] downloads = downloads [ downloads . find ( "</A> with " ) + len ( "</A> with " ) : ] return downloads
def domain ( self ) : """Return domain from the url"""
remove_pac = self . cleanup . replace ( "https://" , "" ) . replace ( "http://" , "" ) . replace ( "www." , "" ) try : return remove_pac . split ( '/' ) [ 0 ] except : return None
def get_dataset ( self , name , multi_instance = 0 ) : """get a specific dataset . example : try : gyro _ data = ulog . get _ dataset ( ' sensor _ gyro ' ) except ( KeyError , IndexError , ValueError ) as error : print ( type ( error ) , " ( sensor _ gyro ) : " , error ) : param name : name of the datas...
return [ elem for elem in self . _data_list if elem . name == name and elem . multi_id == multi_instance ] [ 0 ]
def parse_simple_args ( self , term ) : """parse the shortcut forms , return True / False"""
match = SHORTCUT . match ( term ) if not match : return False _ , start , end , _ , stride , _ , format = match . groups ( ) if start is not None : try : start = int ( start , 0 ) except ValueError : raise AnsibleError ( "can't parse start=%s as integer" % start ) if end is not None : tr...