signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def connectExec ( connection , protocol , commandLine ) : """Connect a Protocol to a ssh exec session"""
deferred = connectSession ( connection , protocol ) @ deferred . addCallback def requestSubsystem ( session ) : return session . requestExec ( commandLine ) return deferred
def orient ( mag_azimuth , field_dip , or_con ) : """uses specified orientation convention to convert user supplied orientations to laboratory azimuth and plunge"""
or_con = str ( or_con ) if mag_azimuth == - 999 : return "" , "" if or_con == "1" : # lab _ mag _ az = mag _ az ; sample _ dip = - dip return mag_azimuth , - field_dip if or_con == "2" : return mag_azimuth - 90. , - field_dip if or_con == "3" : # lab _ mag _ az = mag _ az ; sample _ dip = 90 . - dip ret...
def _Viscosity ( rho , T , fase = None , drho = None ) : """Equation for the Viscosity Parameters rho : float Density , [ kg / m3] T : float Temperature , [ K ] fase : dict , optional for calculate critical enhancement phase properties drho : float , optional for calculate critical enhancement [ ∂...
Tr = T / Tc Dr = rho / rhoc # Eq 11 H = [ 1.67752 , 2.20462 , 0.6366564 , - 0.241605 ] mu0 = 100 * Tr ** 0.5 / sum ( [ Hi / Tr ** i for i , Hi in enumerate ( H ) ] ) # Eq 12 I = [ 0 , 1 , 2 , 3 , 0 , 1 , 2 , 3 , 5 , 0 , 1 , 2 , 3 , 4 , 0 , 1 , 0 , 3 , 4 , 3 , 5 ] J = [ 0 , 0 , 0 , 0 , 1 , 1 , 1 , 1 , 1 , 2 , 2 , 2 , 2 ...
def _build_http ( http = None ) : """Construct an http client suitable for googleapiclient usage w / user agent ."""
if not http : http = httplib2 . Http ( timeout = HTTP_REQUEST_TIMEOUT , ca_certs = HTTPLIB_CA_BUNDLE ) user_agent = 'Python-httplib2/{} (gzip), {}/{}' . format ( httplib2 . __version__ , 'custodian-gcp' , '0.1' ) return set_user_agent ( http , user_agent )
def get_stoplist ( language ) : """Returns an built - in stop - list for the language as a set of words ."""
file_path = os . path . join ( "stoplists" , "%s.txt" % language ) try : stopwords = pkgutil . get_data ( "justext" , file_path ) except IOError : raise ValueError ( "Stoplist for language '%s' is missing. " "Please use function 'get_stoplists' for complete list of stoplists " "and feel free to contribute by yo...
def to_unicode ( data , encoding = 'UTF-8' ) : """Convert a number of different types of objects to unicode ."""
if isinstance ( data , unicode_type ) : return data if isinstance ( data , bytes ) : return unicode_type ( data , encoding = encoding ) if hasattr ( data , '__iter__' ) : try : dict ( data ) except TypeError : pass except ValueError : # Assume it ' s a one dimensional data structure ...
def setxy ( self ) : """computes all vertex coordinates ( x , y ) using an algorithm by Brandes & Kopf ."""
self . _edge_inverter ( ) self . _detect_alignment_conflicts ( ) inf = float ( 'infinity' ) # initialize vertex coordinates attributes : for l in self . layers : for v in l : self . grx [ v ] . root = v self . grx [ v ] . align = v self . grx [ v ] . sink = v self . grx [ v ] . shift...
def _prepare_forms ( self ) : """private function to prepare content for paramType = form"""
content_type = 'application/x-www-form-urlencoded' if self . __op . consumes and content_type not in self . __op . consumes : raise errs . SchemaError ( 'content type {0} does not present in {1}' . format ( content_type , self . __op . consumes ) ) return content_type , six . moves . urllib . parse . urlencode ( se...
def generate ( env ) : """Add default tools ."""
for t in SCons . Tool . tool_list ( env [ 'PLATFORM' ] , env ) : SCons . Tool . Tool ( t ) ( env )
def set_syslog_config ( host , username , password , syslog_config , config_value , protocol = None , port = None , firewall = True , reset_service = True , esxi_hosts = None , credstore = None ) : '''Set the specified syslog configuration parameter . By default , this function will reset the syslog service after...
ret = { } # First , enable the syslog firewall ruleset , for each host , if needed . if firewall and syslog_config == 'loghost' : if esxi_hosts : if not isinstance ( esxi_hosts , list ) : raise CommandExecutionError ( '\'esxi_hosts\' must be a list.' ) for esxi_host in esxi_hosts : ...
def grab_focus ( self ) : """grab window ' s focus . Keyboard and scroll events will be forwarded to the sprite who has the focus . Check the ' focused ' property of sprite in the on - render event to decide how to render it ( say , add an outline when focused = true )"""
scene = self . get_scene ( ) if scene and scene . _focus_sprite != self : scene . _focus_sprite = self
def _update_partition_dci_id ( self , tenant_name , dci_id , vrf_prof = None , part_name = None ) : """Function to update DCI ID of partition ."""
self . dcnm_obj . update_project ( tenant_name , part_name , dci_id = dci_id , vrf_prof = vrf_prof )
def _get_model_cost ( self , formula , model ) : """Given a WCNF formula and a model , the method computes the MaxSAT cost of the model , i . e . the sum of weights of soft clauses that are unsatisfied by the model . : param formula : an input MaxSAT formula : param model : a satisfying assignment : type ...
model_set = set ( model ) cost = 0 for i , cl in enumerate ( formula . soft ) : cost += formula . wght [ i ] if all ( l not in model_set for l in filter ( lambda l : abs ( l ) <= self . formula . nv , cl ) ) else 0 return cost
def fetch_json_by_name ( name ) : """Fetch json based on the element name First gets the href based on a search by name , then makes a second query to obtain the element json : method : GET : param str name : element name : return : : py : class : ` smc . api . web . SMCResult `"""
result = fetch_meta_by_name ( name ) if result . href : result = fetch_json_by_href ( result . href ) return result
def draw ( self ) : """Renders the class balance chart on the specified axes from support ."""
# Number of colors is either number of classes or 2 colors = resolve_colors ( len ( self . support_ ) ) if self . _mode == BALANCE : self . ax . bar ( np . arange ( len ( self . support_ ) ) , self . support_ , color = colors , align = 'center' , width = 0.5 ) # Compare mode else : bar_width = 0.35 labels =...
def concat ( self , * args , ** kwargs ) : """: type args : FormattedText : type kwargs : FormattedText"""
for arg in args : assert self . formatted_text . _is_compatible ( arg ) , "Cannot concat text with different modes" self . format_args . append ( arg . text ) for kwarg in kwargs : value = kwargs [ kwarg ] assert self . formatted_text . _is_compatible ( value ) , "Cannot concat text with different modes...
def copy_clip_rectangle_list ( self ) : """Return the current clip region as a list of rectangles in user coordinates . : return : A list of rectangles , as ` ` ( x , y , width , height ) ` ` tuples of floats . : raises : : exc : ` CairoError ` if the clip region cannot be represented as a list of u...
rectangle_list = cairo . cairo_copy_clip_rectangle_list ( self . _pointer ) _check_status ( rectangle_list . status ) rectangles = rectangle_list . rectangles result = [ ] for i in range ( rectangle_list . num_rectangles ) : rect = rectangles [ i ] result . append ( ( rect . x , rect . y , rect . width , rect ....
def point_probability ( self , threshold ) : """Determine the probability of exceeding a threshold at a grid point based on the ensemble forecasts at that point . Args : threshold : If > = threshold assigns a 1 to member , otherwise 0. Returns : EnsembleConsensus"""
point_prob = np . zeros ( self . data . shape [ 1 : ] ) for t in range ( self . data . shape [ 1 ] ) : point_prob [ t ] = np . where ( self . data [ : , t ] >= threshold , 1.0 , 0.0 ) . mean ( axis = 0 ) return EnsembleConsensus ( point_prob , "point_probability" , self . ensemble_name , self . run_date , self . va...
def _xray_register_type_fix ( wrapped , instance , args , kwargs ) : """Send the actual connection or curser to register type ."""
our_args = list ( copy . copy ( args ) ) if len ( our_args ) == 2 and isinstance ( our_args [ 1 ] , ( XRayTracedConn , XRayTracedCursor ) ) : our_args [ 1 ] = our_args [ 1 ] . __wrapped__ return wrapped ( * our_args , ** kwargs )
def create_estimator ( model_name , hparams , run_config , schedule = "train_and_evaluate" , decode_hparams = None , use_tpu = False , use_tpu_estimator = False , use_xla = False ) : """Create a T2T Estimator ."""
model_fn = t2t_model . T2TModel . make_estimator_model_fn ( model_name , hparams , decode_hparams = decode_hparams , use_tpu = use_tpu ) del use_xla if use_tpu or use_tpu_estimator : problem = hparams . problem batch_size = ( problem . tpu_batch_size_per_shard ( hparams ) * run_config . tpu_config . num_shards ...
def word_freq ( word : str , domain : str = "all" ) -> int : """* * Not officially supported . * * Get word frequency of a word by domain . This function will make a query to the server of Thai National Corpus . Internet connection is required . * * IMPORTANT : * * Currently ( as of 29 April 2019 ) always r...
listdomain = { "all" : "" , "imaginative" : "1" , "natural-pure-science" : "2" , "applied-science" : "3" , "social-science" : "4" , "world-affairs-history" : "5" , "commerce-finance" : "6" , "arts" : "7" , "belief-thought" : "8" , "leisure" : "9" , "others" : "0" , } url = "http://www.arts.chula.ac.th/~ling/TNCII/corp....
def _new_page ( self ) : """Helper function to start a new page . Not intended for external use ."""
self . _current_page = Drawing ( * self . _pagesize ) if self . _bgimage : self . _current_page . add ( self . _bgimage ) self . _pages . append ( self . _current_page ) self . page_count += 1 self . _position = [ 1 , 0 ]
def _auth ( self , load ) : '''Authenticate the client , use the sent public key to encrypt the AES key which was generated at start up . This method fires an event over the master event manager . The event is tagged " auth " and returns a dict with information about the auth event # Verify that the key w...
if not salt . utils . verify . valid_id ( self . opts , load [ 'id' ] ) : log . info ( 'Authentication request from invalid id %s' , load [ 'id' ] ) return { 'enc' : 'clear' , 'load' : { 'ret' : False } } log . info ( 'Authentication request from %s' , load [ 'id' ] ) # 0 is default which should be ' unlimited ...
def _to_dsn ( hosts ) : """Convert a host URI into a dsn for aiopg . > > > _ to _ dsn ( ' aiopg : / / myhostname : 4242 / mydb ' ) ' postgres : / / crate @ myhostname : 4242 / mydb ' > > > _ to _ dsn ( ' aiopg : / / myhostname : 4242 ' ) ' postgres : / / crate @ myhostname : 4242 / doc ' > > > _ to _ dsn ...
p = urlparse ( hosts ) try : user_and_pw , netloc = p . netloc . split ( '@' , maxsplit = 1 ) except ValueError : netloc = p . netloc user_and_pw = 'crate' try : host , port = netloc . split ( ':' , maxsplit = 1 ) except ValueError : host = netloc port = 5432 dbname = p . path [ 1 : ] if p . pat...
def remove_get_department_uids ( portal ) : """Removes getDepartmentUIDs indexes and metadata"""
logger . info ( "Removing filtering by department ..." ) del_index ( portal , "bika_catalog" , "getDepartmentUIDs" ) del_index ( portal , "bika_setup_catalog" , "getDepartmentUID" ) del_index ( portal , CATALOG_ANALYSIS_REQUEST_LISTING , "getDepartmentUIDs" ) del_index ( portal , CATALOG_WORKSHEET_LISTING , "getDepartm...
def Create ( event_type ) : """Factory method creates objects derived from : py : class ` . Event ` with class name matching the : py : class ` . EventType ` . : param event _ type : number for type of event : returns : constructed event corresponding to ` ` event _ type ` ` : rtype : : py : class : ` . Event...
if event_type in EventType . Name : # unknown event type gets base class if EventType . Name [ event_type ] == Event . __name__ : return Event ( ) else : # instantiate Event subclass with same name as EventType name return [ t for t in EventFactory . event_list if t . __name__ == EventType . Nam...
def argmin ( self , rows : List [ Row ] , column : ComparableColumn ) -> List [ Row ] : """Takes a list of rows and a column and returns a list containing a single row ( dict from columns to cells ) that has the minimum numerical value in the given column . We return a list instead of a single dict to be consis...
if not rows : return [ ] value_row_pairs = [ ( row . values [ column . name ] , row ) for row in rows ] if not value_row_pairs : return [ ] # Returns a list containing the row with the max cell value . return [ sorted ( value_row_pairs , key = lambda x : x [ 0 ] ) [ 0 ] [ 1 ] ]
def read_and_redirect ( request , notification_id ) : """Marks the supplied notification as read and then redirects to the supplied URL from the ` ` next ` ` URL parameter . * * IMPORTANT * * : This is CSRF - unsafe method . Only use it if its okay for you to mark notifications as read without a robust check ...
notification_page = reverse ( 'notifications:all' ) next_page = request . GET . get ( 'next' , notification_page ) if is_safe_url ( next_page ) : target = next_page else : target = notification_page try : user_nf = request . user . notifications . get ( pk = notification_id ) if not user_nf . read : ...
def dump_hex ( ofd , start , len_ , prefix = 0 ) : """Convert ` start ` to hex and logs it , 16 bytes per log statement . https : / / github . com / thom311 / libnl / blob / libnl3_2_25 / lib / msg . c # L760 Positional arguments : ofd - - function to call with arguments similar to ` logging . debug ` . sta...
prefix_whitespaces = ' ' * prefix limit = 16 - ( prefix * 2 ) start_ = start [ : len_ ] for line in ( start_ [ i : i + limit ] for i in range ( 0 , len ( start_ ) , limit ) ) : # stackoverflow . com / a / 9475354/1198943 hex_lines , ascii_lines = list ( ) , list ( ) for c in line : hex_lines . append (...
def mfpt_sensitivity ( T , target , i ) : r"""Sensitivity matrix of the mean first - passage time from specified state . Parameters T : ( M , M ) ndarray Transition matrix target : int or list Target state or set for mfpt computation i : int Compute the sensitivity for state ` i ` Returns S : ( M ...
# check input T = _types . ensure_ndarray_or_sparse ( T , ndim = 2 , uniform = True , kind = 'numeric' ) target = _types . ensure_int_vector ( target ) # go if _issparse ( T ) : _showSparseConversionWarning ( ) mfpt_sensitivity ( T . todense ( ) , target , i ) else : return dense . sensitivity . mfpt_sensit...
def setup_continuous_delivery ( self , swap_with_slot , app_type_details , cd_project_url , create_account , vsts_app_auth_token , test , webapp_list ) : """Use this method to setup Continuous Delivery of an Azure web site from a source control repository . : param swap _ with _ slot : the slot to use for deploym...
branch = self . _repo_info . branch or 'refs/heads/master' self . _validate_cd_project_url ( cd_project_url ) vsts_account_name = self . _get_vsts_account_name ( cd_project_url ) # Verify inputs before we start generating tokens source_repository , account_name , team_project_name = self . _get_source_repository ( self...
def selected ( self ) : """Check whether all the matched elements are selected . Returns : bool"""
query_results = self . map ( lambda el : el . is_selected ( ) , 'selected' ) . results if query_results : return all ( query_results ) return False
def normalize ( location_name , preserve_commas = False ) : """Normalize * location _ name * by stripping punctuation and collapsing runs of whitespace , and return the normalized name ."""
def replace ( match ) : if preserve_commas and ',' in match . group ( 0 ) : return ',' return ' ' return NORMALIZATION_RE . sub ( replace , location_name ) . strip ( ) . lower ( )
def compete ( source_x , source_o , timeout = None , memlimit = None , cgroup = 'tictactoe' , cgroup_path = '/sys/fs/cgroup' ) : """Fights two source files . Returns either : * ( ' ok ' , ' x ' | ' draw ' | ' o ' , GAMEPLAY ) * ( ' error ' , GUILTY , REASON , GAMEPLAY ) REASON : = utf8 - encoded error strin...
gameplay = [ ] for xo , moveresult , log in run_interactive ( source_x , source_o , timeout , memlimit , cgroup , cgroup_path ) : if moveresult [ 0 ] == 'error' : return 'error' , xo , moveresult [ 1 ] , gameplay + [ 0 ] elif moveresult [ 0 ] == 'state_coords' : gameplay . append ( coords_to_num...
def cli ( env , ack_all ) : """Summary and acknowledgement of upcoming and ongoing maintenance events"""
manager = AccountManager ( env . client ) events = manager . get_upcoming_events ( ) if ack_all : for event in events : result = manager . ack_event ( event [ 'id' ] ) event [ 'acknowledgedFlag' ] = result env . fout ( event_table ( events ) )
def set_key ( self , section , key , value ) : """Stores given key in settings file . : param section : Current section to save the key into . : type section : unicode : param key : Current key to save . : type key : unicode : param value : Current key value to save . : type value : object"""
LOGGER . debug ( "> Saving '{0}' in '{1}' section with value: '{2}' in settings file." . format ( key , section , foundations . strings . to_string ( value ) ) ) self . __settings . beginGroup ( section ) self . __settings . setValue ( key , QVariant ( value ) ) self . __settings . endGroup ( )
def parse_args ( args , kwargs ) : """Returns a kwargs dictionary by turning args into kwargs"""
if 'style' in kwargs : args += ( kwargs [ 'style' ] , ) del kwargs [ 'style' ] for arg in args : if not isinstance ( arg , ( bytes , unicode ) ) : raise ValueError ( "args must be strings:" + repr ( args ) ) if arg . lower ( ) in FG_COLORS : if 'fg' in kwargs : raise ValueErr...
def get_monitor ( self , topics ) : """Attempts to find a Monitor in device cloud that matches the provided topics : param topics : a string list of topics ( e . g . ` ` [ ' DeviceCore [ U ] ' , ' FileDataCore ' ] ) ` ` ) Returns a : class : ` DeviceCloudMonitor ` if found , otherwise None ."""
for monitor in self . get_monitors ( MON_TOPIC_ATTR == "," . join ( topics ) ) : return monitor # return the first one , even if there are multiple return None
def beta ( self , val : float ) -> None : "Set beta ( or alpha as makes sense for given optimizer ) ."
if val is None : return if 'betas' in self . opt_keys : self . set_val ( 'betas' , ( self . _mom , listify ( val , self . _beta ) ) ) elif 'alpha' in self . opt_keys : self . set_val ( 'alpha' , listify ( val , self . _beta ) ) self . _beta = listify ( val , self . _beta )
def set_domain_id ( self , value = None , default = False , disable = False ) : """Configures the mlag domain - id value Args : value ( str ) : The value to configure the domain - id default ( bool ) : Configures the domain - id using the default keyword disable ( bool ) : Negates the domain - id using the ...
return self . _configure_mlag ( 'domain-id' , value , default , disable )
def msgHasAcceptableInstId ( self , msg , frm ) -> bool : """Return true if the instance id of message corresponds to a correct replica . : param msg : the node message to validate : return :"""
# TODO : refactor this ! this should not do anything except checking ! instId = getattr ( msg , f . INST_ID . nm , None ) if not ( isinstance ( instId , int ) and instId >= 0 ) : return False if instId >= self . requiredNumberOfInstances : if instId not in self . msgsForFutureReplicas : self . msgsForFu...
def angle ( self ) : """Angle value ."""
if self . use_global_light : return self . _image_resources . get_data ( 'global_angle' , 30.0 ) return self . value . get ( Key . LocalLightingAngle ) . value
def _prepare_output ( partitions , verbose ) : """Returns dict with ' raw ' and ' message ' keys filled ."""
out = { } partitions_count = len ( partitions ) out [ 'raw' ] = { 'offline_count' : partitions_count , } if partitions_count == 0 : out [ 'message' ] = 'No offline partitions.' else : out [ 'message' ] = "{count} offline partitions." . format ( count = partitions_count ) if verbose : lines = ( '{}:{...
def setShowGridRows ( self , state ) : """Sets whether or not the grid rows should be rendered when drawing the \ grid . : param state | < bool >"""
delegate = self . itemDelegate ( ) if ( isinstance ( delegate , XTreeWidgetDelegate ) ) : delegate . setShowGridRows ( state )
def _calc_T_var ( self , X ) -> int : """Calculate the number of samples , T , from the shape of X"""
shape = X . shape tensor_rank : int = len ( shape ) if tensor_rank == 0 : return 1 if tensor_rank == 1 : return shape [ 0 ] if tensor_rank == 2 : if shape [ 1 ] > 1 : raise ValueError ( 'Initial value of a variable must have dimension T*1.' ) return shape [ 0 ]
def _inline ( ins ) : """Inline code"""
tmp = [ x . strip ( ' \t\r\n' ) for x in ins . quad [ 1 ] . split ( '\n' ) ] # Split lines i = 0 while i < len ( tmp ) : if not tmp [ i ] or tmp [ i ] [ 0 ] == ';' : # a comment or empty string ? tmp . pop ( i ) continue if tmp [ i ] [ 0 ] == '#' : # A preprocessor directive i += 1 ...
def safe_url ( self , url , errors = 'strict' ) : """URL encode value for safe HTTP request . Args : url ( string ) : The string to URL Encode . Returns : ( string ) : The urlencoded string ."""
if url is not None : url = quote ( self . s ( url , errors = errors ) , safe = '~' ) return url
def get_bandstructure_by_material_id ( self , material_id , line_mode = True ) : """Get a BandStructure corresponding to a material _ id . REST Endpoint : https : / / www . materialsproject . org / rest / v2 / materials / < mp - id > / vasp / bandstructure or https : / / www . materialsproject . org / rest / v2...
prop = "bandstructure" if line_mode else "bandstructure_uniform" data = self . get_data ( material_id , prop = prop ) return data [ 0 ] [ prop ]
def get_gam_splines ( start = 0 , end = 100 , n_bases = 10 , spline_order = 3 , add_intercept = True ) : """Main function required by ( TF ) Concise class"""
# make sure n _ bases is an int assert type ( n_bases ) == int x = np . arange ( start , end + 1 ) knots = get_knots ( start , end , n_bases , spline_order ) X_splines = get_X_spline ( x , knots , n_bases , spline_order , add_intercept ) S = get_S ( n_bases , spline_order , add_intercept ) # Get the same knot positions...
def my_init ( self ) : """Method automatically called from base class constructor ."""
self . _start_time = time . time ( ) self . _stats = { } self . _stats_lock = threading . Lock ( )
def reverse_complement ( self ) : '''str : Returns the reverse complement of ` ` Sequence . sequence ` ` .'''
if self . _reverse_complement is None : self . _reverse_complement = self . _get_reverse_complement ( ) return self . _reverse_complement
def get_tensor_info ( self ) : """See base class for details ."""
return { feature_key : feature . get_tensor_info ( ) for feature_key , feature in self . _feature_dict . items ( ) }
def _SanitizeField ( self , field ) : """Sanitizes a field for output . This method replaces any field delimiters with a space . Args : field ( str ) : name of the field to sanitize . Returns : str : value of the field ."""
if self . _field_delimiter and isinstance ( field , py2to3 . STRING_TYPES ) : return field . replace ( self . _field_delimiter , ' ' ) return field
def run_parallel ( pipeline , input_gen , options = { } , ncpu = 4 , chunksize = 200 ) : """Run a pipeline in parallel over a input generator cutting it into small chunks . > > > # if we have a simple component > > > from reliure . pipeline import Composable > > > # that we want to run over a given input : ...
t0 = time ( ) # FIXME : there is a know issue when pipeline results are " big " object , the merge is bloking . . . to be investigate # TODO : add get _ pipeline args to prodvide a fct to build the pipeline ( in each worker ) logger = logging . getLogger ( "reliure.run_parallel" ) jobs = [ ] results = [ ] Qdata = mp . ...
def cancel ( self , mark_completed_as_cancelled = False ) : """Cancel the future . If the future has not been started yet , it will never start running . If the future is already running , it will run until the worker function exists . The worker function can check if the future has been cancelled using the :...
with self . _lock : if not self . _completed or mark_completed_as_cancelled : self . _cancelled = True callbacks = self . _prepare_done_callbacks ( ) callbacks ( )
def has_mixed_eol_chars ( text ) : """Detect if text has mixed EOL characters"""
eol_chars = get_eol_chars ( text ) if eol_chars is None : return False correct_text = eol_chars . join ( ( text + eol_chars ) . splitlines ( ) ) return repr ( correct_text ) != repr ( text )
def conv_from_name ( name ) : """Understand simulink syntax for fixed types and returns the proper conversion structure . @ param name : the type name as in simulin ( i . e . UFix _ 8_7 . . . ) @ raise ConversionError : When cannot decode the string"""
_match = re . match ( r"^(?P<signed>u?fix)_(?P<bits>\d+)_(?P<binary>\d+)" , name , flags = re . I ) if not _match : raise ConversionError ( "Cannot interpret name: " + name ) params = _match . groupdict ( ) if params [ 'signed' ] == 'fix' : signed = True else : signed = False bits = int ( params [ 'bits' ] ...
def _check_status ( self ) : """Check repo status and except if dirty ."""
logger . info ( 'Checking repo status' ) status = self . log_call ( [ 'git' , 'status' , '--porcelain' ] , callwith = subprocess . check_output , cwd = self . cwd , ) if status : raise DirtyException ( status )
def bilinear_interp ( data , x , y ) : """Interpolate input ` ` data ` ` at " pixel " coordinates ` ` x ` ` and ` ` y ` ` ."""
x = np . asarray ( x ) y = np . asarray ( y ) if x . shape != y . shape : raise ValueError ( "X- and Y-coordinates must have identical shapes." ) out_shape = x . shape out_size = x . size x = x . ravel ( ) y = y . ravel ( ) x0 = np . empty ( out_size , dtype = np . int ) y0 = np . empty ( out_size , dtype = np . in...
def changelist_view ( self , request , extra_context = None ) : """Get object currently tracked and add a button to get back to it"""
extra_context = extra_context or { } if 'object' in request . GET . keys ( ) : value = request . GET [ 'object' ] . split ( ':' ) content_type = get_object_or_404 ( ContentType , id = value [ 0 ] , ) tracked_object = get_object_or_404 ( content_type . model_class ( ) , id = value [ 1 ] , ) extra_context...
def show ( self , ticket ) : """通过ticket换取二维码 详情请参考 https : / / mp . weixin . qq . com / wiki ? t = resource / res _ main & id = mp1443433542 : param ticket : 二维码 ticket 。 可以通过 : func : ` create ` 获取到 : return : 返回的 Request 对象 使用示例 : : from wechatpy import WeChatClient client = WeChatClient ( ' appid ...
if isinstance ( ticket , dict ) : ticket = ticket [ 'ticket' ] return requests . get ( url = 'https://mp.weixin.qq.com/cgi-bin/showqrcode' , params = { 'ticket' : ticket } )
def resolve_url ( self , resource_name ) : """Return a URL to a local copy of a resource , suitable for get _ generator ( )"""
if self . target_format == 'csv' and self . target_file != DEFAULT_METATAB_FILE : # For CSV packages , need to get the package and open it to get the resoruce URL , becuase # they are always absolute web URLs and may not be related to the location of the metadata . s = self . get_resource ( ) rs = s . doc . res...
def normalize_reference_name ( name ) : """Search the dictionary of species - specific references to find a reference name that matches aside from capitalization . If no matching reference is found , raise an exception ."""
lower_name = name . strip ( ) . lower ( ) for reference in Species . _reference_names_to_species . keys ( ) : if reference . lower ( ) == lower_name : return reference raise ValueError ( "Reference genome '%s' not found" % name )
def main ( ) : """Main entry point for iotile - sgcompile ."""
arg_parser = build_args ( ) args = arg_parser . parse_args ( ) model = DeviceModel ( ) parser = SensorGraphFileParser ( ) parser . parse_file ( args . sensor_graph ) if args . format == u'ast' : write_output ( parser . dump_tree ( ) , True , args . output ) sys . exit ( 0 ) parser . compile ( model ) if not arg...
def create_pipeline ( self , name , description , ** kwargs ) : '''Creates a pipeline with the provided attributes . Args : namerequired name string kwargs { name , description , orgWide , aclEntries } user specifiable ones only return ( status code , pipeline _ dict ) ( as created )'''
# req sanity check if not ( name and description ) : return requests . codes . bad_request , None kwargs . update ( { 'name' : name , 'description' : description } ) new_pl = StreakPipeline ( ** kwargs ) uri = '/' . join ( [ self . api_uri , self . pipelines_suffix ] ) code , r_data = self . _req ( 'put' , uri , ne...
def inject_experiment ( ) : """Inject experiment and enviroment variables into the template context ."""
exp = Experiment ( session ) return dict ( experiment = exp , env = os . environ )
def session_rollback ( self , session ) : """Send session _ rollback signal in sqlalchemy ` ` after _ rollback ` ` . This marks the failure of session so the session may enter commit phase ."""
# this may happen when there ' s nothing to rollback if not hasattr ( session , 'meepo_unique_id' ) : self . logger . debug ( "skipped - session_rollback" ) return # del session meepo id after rollback self . logger . debug ( "%s - after_rollback" % session . meepo_unique_id ) signal ( "session_rollback" ) . se...
def geostrophic_wind ( heights , f , dx , dy ) : r"""Calculate the geostrophic wind given from the heights or geopotential . Parameters heights : ( M , N ) ndarray The height field , with either leading dimensions of ( x , y ) or trailing dimensions of ( y , x ) , depending on the value of ` ` dim _ order `...
if heights . dimensionality [ '[length]' ] == 2.0 : norm_factor = 1. / f else : norm_factor = mpconsts . g / f dhdy = first_derivative ( heights , delta = dy , axis = - 2 ) dhdx = first_derivative ( heights , delta = dx , axis = - 1 ) return - norm_factor * dhdy , norm_factor * dhdx
def _interpolate ( im , x , y , name ) : """Perform bilinear sampling on im given x , y coordiantes . Implements the differentiable sampling mechanism with bilinear kerenl in https : / / arxiv . org / abs / 1506.02025. Modified from https : / / github . com / tensorflow / models / tree / master / transformer ...
with tf . variable_scope ( name ) : x = tf . reshape ( x , [ - 1 ] ) y = tf . reshape ( y , [ - 1 ] ) # constants num_batch = tf . shape ( im ) [ 0 ] _ , height , width , channels = im . get_shape ( ) . as_list ( ) x = tf . to_float ( x ) y = tf . to_float ( y ) height_f = tf . cast ( he...
def build_tree ( X , y , criterion , max_depth , current_depth = 1 ) : """Builds the decision tree ."""
# check for max _ depth accomplished if max_depth >= 0 and current_depth >= max_depth : return Leaf ( y ) # check for 0 gain gain , question = find_best_question ( X , y , criterion ) if gain == 0 : return Leaf ( y ) # split true_X , false_X , true_y , false_y = split ( X , y , question ) # Build the ` true ` b...
def print ( root ) : # type : ( Union [ Nonterminal , Terminal , Rule ] ) - > str """Transform the parsed tree to the string . Expects tree like structure . You can see example output below . ( R ) SplitRules26 | - - ( N ) Iterate | ` - - ( R ) SplitRules30 | ` - - ( N ) Symb | ` - - ( R ) SplitRules4 ...
# print the part before the element def print_before ( previous = 0 , defined = None , is_last = False ) : defined = defined or { } ret = '' if previous != 0 : for i in range ( previous - 1 ) : # if the column is still active write | if i in defined : ret += '| ' ...
def _add_inline_definition ( item , statement ) : '''Adds an inline definition to statement .'''
global _current_statement backup = _current_statement type_ , options = _expand_one_key_dictionary ( item ) _current_statement = UnnamedStatement ( type = type_ ) _parse_statement ( options ) statement . add_child ( _current_statement ) _current_statement = backup
def center_cell_text ( cell ) : """Horizontally center the text within a cell ' s grid Like this : : | foo | - - > | foo | Parameters cell : dashtable . data2rst . Cell Returns cell : dashtable . data2rst . Cell"""
lines = cell . text . split ( '\n' ) cell_width = len ( lines [ 0 ] ) - 2 truncated_lines = [ '' ] for i in range ( 1 , len ( lines ) - 1 ) : truncated = lines [ i ] [ 2 : len ( lines [ i ] ) - 2 ] . rstrip ( ) truncated_lines . append ( truncated ) truncated_lines . append ( '' ) max_line_length = get_longest_...
def output ( data , ** kwargs ) : # pylint : disable = unused - argument '''Print out via pretty print'''
if isinstance ( data , Exception ) : data = six . text_type ( data ) if 'output_indent' in __opts__ and __opts__ [ 'output_indent' ] >= 0 : return pprint . pformat ( data , indent = __opts__ [ 'output_indent' ] ) return pprint . pformat ( data )
def count_de_novos_per_transcript ( ensembl , gene_id , de_novos = [ ] ) : """count de novos in transcripts for a gene . Args : ensembl : EnsemblRequest object to request data from ensembl gene _ id : HGNC symbol for gene de _ novos : list of de novo positions , so we can check they all fit in the gene tr...
transcripts = get_transcript_ids ( ensembl , gene_id ) # TODO : allow for genes without any coding sequence . if len ( transcripts ) == 0 : raise IndexError ( "{0} lacks coding transcripts" . format ( gene_id ) ) # count the de novos observed in all transcripts counts = { } for key in transcripts : try : ...
def get_account ( self , account , use_sis_id = False , ** kwargs ) : """Retrieve information on an individual account . : calls : ` GET / api / v1 / accounts / : id < https : / / canvas . instructure . com / doc / api / accounts . html # method . accounts . show > ` _ : param account : The object or ID of the ...
if use_sis_id : account_id = account uri_str = 'accounts/sis_account_id:{}' else : account_id = obj_or_id ( account , "account" , ( Account , ) ) uri_str = 'accounts/{}' response = self . __requester . request ( 'GET' , uri_str . format ( account_id ) , _kwargs = combine_kwargs ( ** kwargs ) ) return Ac...
def _get_leftMargin ( self ) : """This must return an int or float . If the glyph has no outlines , this must return ` None ` . Subclasses may override this method ."""
bounds = self . bounds if bounds is None : return None xMin , yMin , xMax , yMax = bounds return xMin
def parse_comparison_operation ( operation : str ) -> Tuple [ Optional [ str ] , str ] : """Parse the comparision operator in an operation ."""
_operation = operation . strip ( ) if not _operation : raise QueryParserException ( 'Operation is not valid: {}' . format ( operation ) ) # Check inclusion comparison if _operation [ : 2 ] in ( '<=' , '=<' ) : return '<=' , _operation [ 2 : ] . strip ( ) if _operation [ : 2 ] in ( '>=' , '=>' ) : return '>=...
def _ordered_categories ( df , categories ) : """Make the columns in df categorical Parameters : categories : dict Of the form { str : list } , where the key the column name and the value is the ordered category list"""
for col , cats in categories . items ( ) : df [ col ] = df [ col ] . astype ( CategoricalDtype ( cats , ordered = True ) ) return df
def _filter_parameters ( parameters ) : """Filters the ignored parameters out ."""
if not parameters : return None return OrderedDict ( ( param , value ) for param , value in six . iteritems ( parameters ) if param not in IGNORED_PARAMS )
def is_en_passant ( self , move : Move ) -> bool : """Checks if the given pseudo - legal move is an en passant capture ."""
return ( self . ep_square == move . to_square and bool ( self . pawns & BB_SQUARES [ move . from_square ] ) and abs ( move . to_square - move . from_square ) in [ 7 , 9 ] and not self . occupied & BB_SQUARES [ move . to_square ] )
def ref ( self ) : """Get the reference number of the dataset . Args : : no argument Returns : : dataset reference number C library equivalent : SDidtoref"""
sds_ref = _C . SDidtoref ( self . _id ) _checkErr ( 'idtoref' , sds_ref , 'illegal SDS identifier' ) return sds_ref
def calculateProbableRootOfGeneTree ( speciesTree , geneTree , processID = lambda x : x ) : """Goes through each root possible branch making it the root . Returns tree that requires the minimum number of duplications ."""
# get all rooted trees # run dup calc on each tree # return tree with fewest number of dups if geneTree . traversalID . midEnd <= 3 : return ( 0 , 0 , geneTree ) checkGeneTreeMatchesSpeciesTree ( speciesTree , geneTree , processID ) l = [ ] def fn ( tree ) : if tree . traversalID . mid != geneTree . left . trav...
def tune ( runner , kernel_options , device_options , tuning_options ) : """Find the best performing kernel configuration in the parameter space : params runner : A runner from kernel _ tuner . runners : type runner : kernel _ tuner . runner : param kernel _ options : A dictionary with all options for the ker...
results = [ ] cache = { } # scale variables in x because PSO works with velocities to visit different configurations tuning_options [ "scaling" ] = True # using this instead of get _ bounds because scaling is used bounds , _ , _ = get_bounds_x0_eps ( tuning_options ) args = ( kernel_options , tuning_options , runner , ...
def LearnToExecute ( # pylint : disable = invalid - name batch_size , max_length = 1 , max_nesting = 1 , token_by_char = True , mode = Mode . TRAIN_COMBINE , loss_threshold = 0.1 , min_tries = DEFAULT_MIN_CURRICULUM_EVAL_TRIES , task_type = TaskType . ALG_CTRL ) : """Factory method for LearnToExecute Dataset module...
# defaults mode to " train - combine " if mode == Mode . TRAIN_COMBINE : curriculum = CombineCurriculum ( max_length , max_nesting , loss_threshold , min_tries = min_tries ) elif mode == Mode . TRAIN_MIX : curriculum = MixCurriculum ( max_length , max_nesting , loss_threshold , min_tries = min_tries ) elif mode...
def apparent_temp ( temp , rh , wind ) : """Compute apparent temperature ( real feel ) , using formula from http : / / www . bom . gov . au / info / thermal _ stress /"""
if temp is None or rh is None or wind is None : return None vap_press = ( float ( rh ) / 100.0 ) * 6.105 * math . exp ( 17.27 * temp / ( 237.7 + temp ) ) return temp + ( 0.33 * vap_press ) - ( 0.70 * wind ) - 4.00
def find_srv_by_name_and_hostname ( self , host_name , sdescr ) : """Get a specific service based on a host _ name and service _ description : param host _ name : host name linked to needed service : type host _ name : str : param sdescr : service name we need : type sdescr : str : return : the service fo...
key = ( host_name , sdescr ) return self . name_to_item . get ( key , None )
def _update_status ( self , sub_job_num = None ) : """Gets the job status . Return : str : The current status of the job"""
job_id = '%s.%s' % ( self . cluster_id , sub_job_num ) if sub_job_num else str ( self . cluster_id ) format = [ '-format' , '"%d"' , 'JobStatus' ] cmd = 'condor_q {0} {1} && condor_history {0} {1}' . format ( job_id , ' ' . join ( format ) ) args = [ cmd ] out , err = self . _execute ( args , shell = True , run_in_job_...
def config_string ( self ) : """See the class documentation ."""
# Note : _ write _ to _ conf is determined when the value is calculated . This # is a hidden function call due to property magic . val = self . str_value if not self . _write_to_conf : return "" if self . orig_type in _BOOL_TRISTATE : return "{}{}={}\n" . format ( self . kconfig . config_prefix , self . name , ...
def create_hook ( self , name , config , events = github . GithubObject . NotSet , active = github . GithubObject . NotSet ) : """: calls : ` POST / orgs / : owner / hooks < http : / / developer . github . com / v3 / orgs / hooks > ` _ : param name : string : param config : dict : param events : list of strin...
assert isinstance ( name , ( str , unicode ) ) , name assert isinstance ( config , dict ) , config assert events is github . GithubObject . NotSet or all ( isinstance ( element , ( str , unicode ) ) for element in events ) , events assert active is github . GithubObject . NotSet or isinstance ( active , bool ) , active...
def getVariantAnnotations ( self , referenceName , startPosition , endPosition ) : """Generator for iterating through variant annotations in this variant annotation set . : param referenceName : : param startPosition : : param endPosition : : return : generator of protocol . VariantAnnotation"""
variantIter = self . _variantSet . getPysamVariants ( referenceName , startPosition , endPosition ) for record in variantIter : yield self . convertVariantAnnotation ( record )
def _get_usage ( self , account_number , number ) : """Get Fido usage . Get the following data - talk - text - data Roaming data is not supported yet"""
# Prepare data data = { "ctn" : number , "language" : "en-US" , "accountNumber" : account_number } # Http request try : raw_res = yield from self . _session . post ( USAGE_URL , data = data , headers = self . _headers , timeout = self . _timeout ) except OSError : raise PyFidoError ( "Can not get usage" ) # Loa...
def sort_timeseries ( self , ascending = True ) : """Sorts the data points within the TimeSeries according to their occurrence inline . : param boolean ascending : Determines if the TimeSeries will be ordered ascending or descending . If this is set to descending once , the ordered parameter defined in : py :...
# the time series is sorted by default if ascending and self . _sorted : return sortorder = 1 if not ascending : sortorder = - 1 self . _predefinedSorted = False self . _timeseriesData . sort ( key = lambda i : sortorder * i [ 0 ] ) self . _sorted = ascending return self
def params ( self ) : """Returns a list where each element is a nicely formatted parameter of this function . This includes argument lists , keyword arguments and default values ."""
def fmt_param ( el ) : if isinstance ( el , str ) or isinstance ( el , unicode ) : return el else : return '(%s)' % ( ', ' . join ( map ( fmt_param , el ) ) ) try : getspec = getattr ( inspect , 'getfullargspec' , inspect . getargspec ) s = getspec ( self . func ) except TypeError : # I ...
def generate_PVdelV_nt_pos_vecs ( self , generative_model , genomic_data ) : """Process P ( delV | V ) into Pi arrays . Set the attributes PVdelV _ nt _ pos _ vec and PVdelV _ 2nd _ nt _ pos _ per _ aa _ vec . Parameters generative _ model : GenerativeModelVJ VJ generative model class containing the model p...
cutV_genomic_CDR3_segs = genomic_data . cutV_genomic_CDR3_segs nt2num = { 'A' : 0 , 'C' : 1 , 'G' : 2 , 'T' : 3 } num_del_pos = generative_model . PdelV_given_V . shape [ 0 ] num_V_genes = generative_model . PdelV_given_V . shape [ 1 ] PVdelV_nt_pos_vec = [ [ ] ] * num_V_genes PVdelV_2nd_nt_pos_per_aa_vec = [ [ ] ] * n...
def add_material ( self , material ) : """Add a material to the mesh , IF it ' s not already present ."""
if self . has_material ( material ) : return self . materials . append ( material )
def acquaint_insides ( swap_gate : ops . Gate , acquaintance_gate : ops . Operation , qubits : Sequence [ ops . Qid ] , before : bool , layers : Layers , mapping : Dict [ ops . Qid , int ] ) -> None : """Acquaints each of the qubits with another set specified by an acquaintance gate . Args : qubits : The list...
max_reach = _get_max_reach ( len ( qubits ) , round_up = before ) reaches = itertools . chain ( range ( 1 , max_reach + 1 ) , range ( max_reach , - 1 , - 1 ) ) offsets = ( 0 , 1 ) * max_reach swap_gate = SwapPermutationGate ( swap_gate ) ops = [ ] for offset , reach in zip ( offsets , reaches ) : if offset == befor...
def get_att_mats ( translate_model ) : """Get ' s the tensors representing the attentions from a build model . The attentions are stored in a dict on the Transformer object while building the graph . Args : translate _ model : Transformer object to fetch the attention weights from . Returns : Tuple of a...
enc_atts = [ ] dec_atts = [ ] encdec_atts = [ ] prefix = "transformer/body/" postfix_self_attention = "/multihead_attention/dot_product_attention" if translate_model . hparams . self_attention_type == "dot_product_relative" : postfix_self_attention = ( "/multihead_attention/" "dot_product_attention_relative" ) post...
def setConf ( self , conf , type = 'simu' ) : """set information for different type dict , : param conf : configuration information , str or dict : param type : simu , ctrl , misc"""
if conf is None : return else : if isinstance ( conf , str ) : conf = MagBlock . str2dict ( conf ) self . setConfDict [ type ] ( conf )
def updateQueue ( destinationRoot , queueDict , debug = False ) : """With a dictionary that represents a queue entry , update the queue entry with the values"""
attrDict = bagatom . AttrDict ( queueDict ) url = urlparse . urljoin ( destinationRoot , "APP/queue/" + attrDict . ark + "/" ) queueXML = bagatom . queueEntryToXML ( attrDict ) urlID = os . path . join ( destinationRoot , attrDict . ark ) uploadXML = bagatom . wrapAtom ( queueXML , id = urlID , title = attrDict . ark )...