signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def configure ( self , conf = None , targets = None , logger = None , callconf = False , keepstate = None , modules = None ) : """Apply input conf on targets objects . Specialization of this method is done in the _ configure method . : param conf : configuration model to configure . Default is this conf . : t...
result = [ ] self . loadmodules ( modules = modules ) modules = [ ] conf = self . _toconf ( conf ) if conf is None : conf = self . conf if targets is None : targets = self . targets if logger is None : logger = self . logger if keepstate is None : keepstate = self . keepstate for target in targets : ...
def sequence_edit_distance ( predictions , labels , weights_fn = common_layers . weights_nonzero ) : """Average edit distance , ignoring padding 0s . The score returned is the edit distance divided by the total length of reference truth and the weight returned is the total length of the truth . Args : predi...
if weights_fn is not common_layers . weights_nonzero : raise ValueError ( "Only weights_nonzero can be used for this metric." ) with tf . variable_scope ( "edit_distance" , values = [ predictions , labels ] ) : # Transform logits into sequence classes by taking max at every step . predictions = tf . to_int32 ( ...
def spi_configure ( self , polarity , phase , bitorder ) : """Configure the SPI interface ."""
ret = api . py_aa_spi_configure ( self . handle , polarity , phase , bitorder ) _raise_error_if_negative ( ret )
def _addDataFile ( self , filename ) : """Given a filename , add it to the graph"""
if filename . endswith ( '.ttl' ) : self . _rdfGraph . parse ( filename , format = 'n3' ) else : self . _rdfGraph . parse ( filename , format = 'xml' )
def visitObjectDef ( self , ctx : jsgParser . ObjectDefContext ) : """objectDef : ID objectExpr"""
name = as_token ( ctx ) self . _context . grammarelts [ name ] = JSGObjectExpr ( self . _context , ctx . objectExpr ( ) , name )
def build_k5_graph ( ) : """Makes a new K5 graph . Ref : http : / / mathworld . wolfram . com / Pentatope . html"""
graph = UndirectedGraph ( ) # K5 has 5 nodes for _ in range ( 5 ) : graph . new_node ( ) # K5 has 10 edges # - - Edge : a graph . new_edge ( 1 , 2 ) # - - Edge : b graph . new_edge ( 2 , 3 ) # - - Edge : c graph . new_edge ( 3 , 4 ) # - - Edge : d graph . new_edge ( 4 , 5 ) # - - Edge : e graph . new_edge ( 5 , 1 )...
async def delete_tree ( self , prefix , * , separator = None ) : """Deletes all keys with a prefix of Key . Parameters : key ( str ) : Key to delete separator ( str ) : Delete only up to a given separator Response : bool : ` ` True ` ` on success"""
response = await self . _discard ( prefix , recurse = True , separator = separator ) return response . body is True
def pause ( profile_process = 'worker' ) : """Pause profiling . Parameters profile _ process : string whether to profile kvstore ` server ` or ` worker ` . server can only be profiled when kvstore is of type dist . if this is not passed , defaults to ` worker `"""
profile_process2int = { 'worker' : 0 , 'server' : 1 } check_call ( _LIB . MXProcessProfilePause ( int ( 1 ) , profile_process2int [ profile_process ] , profiler_kvstore_handle ) )
def main ( ) : '''Run the server .'''
try : ip = sys . argv [ 1 ] port = int ( sys . argv [ 2 ] ) except ( IndexError , ValueError ) : print ( 'Usage: {} <BIND_IP> <PORT>' . format ( sys . argv [ 0 ] ) ) sys . exit ( 1 ) server = socket . socket ( socket . AF_INET , socket . SOCK_STREAM ) server . setsockopt ( socket . SOL_SOCKET , socket ....
def write_output ( self ) : """Write all stored output data to storage ."""
for data in self . output_data . values ( ) : self . create_output ( data . get ( 'key' ) , data . get ( 'value' ) , data . get ( 'type' ) )
def load_data_subject_areas ( subject_file ) : """reads the subject file to a list , to confirm config is setup"""
lst = [ ] if os . path . exists ( subject_file ) : with open ( subject_file , 'r' ) as f : for line in f : lst . append ( line . strip ( ) ) else : print ( 'MISSING DATA FILE (subject_file) ' , subject_file ) print ( 'update your config.py or config.txt' ) return lst
def divmod_neg ( a , b ) : """Return divmod with closest result to zero"""
q , r = divmod ( a , b ) # make sure r is close to zero sr = np . sign ( r ) if np . abs ( r ) > b / 2 : q += sr r -= b * sr return q , r
def POST_AUTH ( self , courseid ) : # pylint : disable = arguments - differ """POST request"""
course , __ = self . get_course_and_check_rights ( courseid , allow_all_staff = False ) errors = [ ] course_content = { } try : data = web . input ( ) course_content = self . course_factory . get_course_descriptor_content ( courseid ) course_content [ 'name' ] = data [ 'name' ] if course_content [ 'name...
def residuals_plot ( model , X , y , ax = None , hist = True , test_size = 0.25 , train_color = 'b' , test_color = 'g' , line_color = LINE_COLOR , random_state = None , train_alpha = 0.75 , test_alpha = 0.75 , ** kwargs ) : """Quick method : Divides the dataset X , y into a train and test split ( the size of the ...
# Instantiate the visualizer visualizer = ResidualsPlot ( model = model , ax = ax , hist = hist , train_color = train_color , test_color = test_color , line_color = line_color , train_alpha = train_alpha , test_alpha = test_alpha , ** kwargs ) # Create the train and test splits X_train , X_test , y_train , y_test = tra...
def disable ( cls ) : """Restore sys . stderr and sys . stdout to their original objects . Resets colors to their original values . : return : If streams restored successfully . : rtype : bool"""
# Skip if not on Windows . if not IS_WINDOWS : return False # Restore default colors . if hasattr ( sys . stderr , '_original_stream' ) : getattr ( sys , 'stderr' ) . color = None if hasattr ( sys . stdout , '_original_stream' ) : getattr ( sys , 'stdout' ) . color = None # Restore original streams . change...
def is_node_ready ( node ) : """Returns True if none of the argument holders contain any ` Empty ` object ."""
return all ( ref_argument ( node . bound_args , a ) is not Empty for a in serialize_arguments ( node . bound_args ) )
def calculate_sector_area ( radius , angle ) : """A function to compute the area of a sector of a circle . Args : radius : Radius of the circle ( float ) angle : Angle by which sector is formed ( float ) . Should be less than 360. Returns : Area of sector . Returns None if angle is 360 or greater . Exam...
pi = 22 / 7 if angle >= 360 : return None sector_area = ( pi * radius ** 2 ) * ( angle / 360 ) return sector_area
def btc_is_p2sh_script ( script_hex ) : """Is the given scriptpubkey a p2sh script ?"""
if script_hex . startswith ( "a914" ) and script_hex . endswith ( "87" ) and len ( script_hex ) == 46 : return True else : return False
async def connect ( self , conn_id , connection_string ) : """Connect to a device . See : meth : ` AbstractDeviceAdapter . connect ` ."""
self . _logger . info ( "Inside connect, conn_id=%d, conn_string=%s" , conn_id , connection_string ) try : self . _setup_connection ( conn_id , connection_string ) resp = await self . _execute ( self . _adapter . connect_sync , conn_id , connection_string ) _raise_error ( conn_id , 'connect' , resp ) except...
def set_many ( self , data , expiry = DEFAULT_EXPIRY ) : """Set a bunch of values in the cache at once from a dict of key / value pairs . For certain backends ( memcached ) , this is much more efficient than calling set ( ) multiple times . If timeout is given , use that timeout for the key ; otherwise use th...
for key , value in data . items ( ) : self . set ( key , value , expiry = expiry ) return [ ]
def clear ( self ) : """Cleans up the manager . The manager can ' t be used after this method has been called"""
self . _lock = None self . _ipopo_instance = None self . _context = None self . requirement = None self . _value = None self . _field = None
def gatk_rnaseq_calling ( data ) : """Use GATK to perform gVCF variant calling on RNA - seq data"""
from bcbio . bam import callable data = utils . deepish_copy ( data ) tools_on = dd . get_tools_on ( data ) if not tools_on : tools_on = [ ] tools_on . append ( "gvcf" ) data = dd . set_tools_on ( data , tools_on ) data = dd . set_jointcaller ( data , [ "%s-joint" % v for v in dd . get_variantcaller ( data ) ] ) ou...
def create_style ( self , title = None , defaults = None , mappings = None , verbose = VERBOSE ) : """Creates a new visual style : param title : title of the visual style : param defaults : a list of dictionaries for each visualProperty : param mappings : a list of dictionaries for each visualProperty : par...
u = self . __url host = u . split ( "//" ) [ 1 ] . split ( ":" ) [ 0 ] port = u . split ( ":" ) [ 2 ] . split ( "/" ) [ 0 ] version = u . split ( ":" ) [ 2 ] . split ( "/" ) [ 1 ] if defaults : defaults_ = [ ] for d in defaults : if d : defaults_ . append ( d ) defaults = defaults_ if ma...
def set_title ( self , title ) : """Set terminal title ."""
assert isinstance ( title , six . text_type ) self . _winapi ( windll . kernel32 . SetConsoleTitleW , title )
def recursively_preempt_states ( self ) : """Preempt the state and all of it child states ."""
super ( ContainerState , self ) . recursively_preempt_states ( ) # notify the transition condition variable to let the state instantaneously stop self . _transitions_cv . acquire ( ) self . _transitions_cv . notify_all ( ) self . _transitions_cv . release ( ) for state in self . states . values ( ) : state . recurs...
def get_activating_subs ( self ) : """Extract INDRA ActiveForm Statements based on a mutation from BEL . The SPARQL pattern used to extract ActiveForms due to mutations look for a ProteinAbundance as a subject which has a child encoding the amino acid substitution . The object of the statement is an Activit...
q_mods = prefixes + """ SELECT ?enzyme_name ?sub_label ?act_type ?rel ?stmt ?subject WHERE { ?stmt a belvoc:Statement . ?stmt belvoc:hasRelationship ?rel . ?stmt belvoc:hasSubject ?subject . ?stmt belvoc:hasObject ?object . ...
def for_method ( cls , server , namespace , classname , methodname ) : # pylint : disable = line - too - long """Factory method that returns a new : class : ` ~ pywbem . ValueMapping ` instance that maps CIM method return values to the ` Values ` qualifier of that method . If a ` Values ` qualifier is defined...
# noqa : E501 conn = server try : get_class = conn . GetClass except AttributeError : conn = server . conn get_class = conn . GetClass class_obj = get_class ( ClassName = classname , namespace = namespace , LocalOnly = False , IncludeQualifiers = True ) try : method_obj = class_obj . methods [ methodnam...
def is_installable_file ( path ) : """Determine if a path can potentially be installed"""
from . vendor . pip_shims . shims import is_installable_dir , is_archive_file from . patched . notpip . _internal . utils . packaging import specifiers from . _compat import Path if hasattr ( path , "keys" ) and any ( key for key in path . keys ( ) if key in [ "file" , "path" ] ) : path = urlparse ( path [ "file" ]...
def switch ( poi ) : """Zaps into a specific product specified by switch context to the product of interest ( poi ) A poi is : sdox : dev - for product " dev " located in container " sdox " If poi does not contain a " : " it is interpreted as product name implying that a product within this container is alr...
parts = poi . split ( ':' ) if len ( parts ) == 2 : container_name , product_name = parts elif len ( parts ) == 1 and os . environ . get ( 'CONTAINER_NAME' ) : # interpret poi as product name if already zapped into a product in order # to enable simply switching products by doing ape zap prod . container_name =...
def get_id2upper ( objs ) : """Get all parent item IDs for each item in dict keys ."""
id2upper = { } for obj in objs : _get_id2upper ( id2upper , obj . item_id , obj ) return id2upper
def exclude_refs ( self , * objs ) : '''Exclude any references to the specified objects from sizing . While any references to the given objects are excluded , the objects will be sized if specified as positional arguments in subsequent calls to methods * * asizeof * * and * * asizesof * * .'''
for o in objs : self . _seen . setdefault ( id ( o ) , 0 )
def calc_one_vert_inverse ( one_vert , xyz = None , exponent = None ) : """Calculate how many electrodes influence one vertex , using the inverse function . Parameters one _ vert : ndarray vector of xyz position of a vertex xyz : ndarray nChan X 3 with the position of all the channels exponent : int ...
trans = empty ( xyz . shape [ 0 ] ) for i , one_xyz in enumerate ( xyz ) : trans [ i ] = 1 / ( norm ( one_vert - one_xyz ) ** exponent ) return trans
def messageReceived ( self , message ) : """Called on incoming message from ZeroMQ . : param message : message data"""
i = message . index ( b'' ) assert i > 0 ( routingInfo , msgId , payload ) = ( message [ : i - 1 ] , message [ i - 1 ] , message [ i + 1 : ] ) msgParts = payload [ 0 : ] self . _routingInfo [ msgId ] = routingInfo self . gotMessage ( msgId , * msgParts )
def arrayify ( self ) : """Returns an array of node bias values and connection weights for use in a GA ."""
gene = [ ] for layer in self . layers : if layer . type != 'Input' : for i in range ( layer . size ) : gene . append ( layer . weight [ i ] ) for connection in self . connections : for i in range ( connection . fromLayer . size ) : for j in range ( connection . toLayer . size ) : ...
def forward ( ctx , x , dutyCycles , k , boostStrength ) : """Use the boost strength to compute a boost factor for each unit represented in x . These factors are used to increase the impact of each unit to improve their chances of being chosen . This encourages participation of more columns in the learning pr...
batchSize = x . shape [ 0 ] if boostStrength > 0.0 : targetDensity = float ( k ) / ( x . shape [ 1 ] * x . shape [ 2 ] * x . shape [ 3 ] ) boostFactors = torch . exp ( ( targetDensity - dutyCycles ) * boostStrength ) boosted = x . detach ( ) * boostFactors else : boosted = x . detach ( ) # Take the boos...
def _get_ipaddress ( node ) : """Adds the ipaddress attribute to the given node object if not already present and it is correctly given by ohai Returns True if ipaddress is added , False otherwise"""
if "ipaddress" not in node : with settings ( hide ( 'stdout' ) , warn_only = True ) : output = sudo ( 'ohai -l warn ipaddress' ) if output . succeeded : try : node [ 'ipaddress' ] = json . loads ( output ) [ 0 ] except ValueError : abort ( "Could not parse ohai's ...
def append ( self , key , item ) : """Append item to the list at key . Creates the list at key if it doesn ' t exist ."""
with self . _lock : if key in self . _dict : self . _dict [ key ] . append ( item ) else : self . _dict [ key ] = [ item ]
def commit ( jaide , commands , check , sync , comment , confirm , at_time , blank ) : """Execute a commit against the device . Purpose : This function will send set commands to a device , and commit | the changes . Options exist for confirming , comments , | synchronizing , checking , blank commits , or dela...
# set the commands to do nothing if the user wants a blank commit . if blank : commands = 'annotate system ""' output = "" # add show | compare output if commands != "" : output += color ( "show | compare:\n" , 'yel' ) try : output += color_diffs ( jaide . compare_config ( commands ) ) + '\n' ex...
def ValidateDate ( date , column_name = None , problems = None ) : """Validates a non - required date string value using IsValidDate ( ) : - if invalid adds InvalidValue error ( if problems accumulator is provided ) - an empty date string is regarded as valid ! Otherwise we might end up with many duplicate er...
if IsEmpty ( date ) or IsValidDate ( date ) : return True else : if problems : problems . InvalidValue ( column_name , date ) return False
def convert_filename ( txtfilename , outdir = '.' ) : """Convert a . TXT filename to a Therion . TH filename"""
return os . path . join ( outdir , os . path . basename ( txtfilename ) ) . rsplit ( '.' , 1 ) [ 0 ] + '.th'
def update_db ( self , new_values ) : """Update database values and application configuration . The provided keys must be defined in the ` ` WAFFLE _ CONFS ` ` setting . Arguments : new _ values ( dict ) : dict of configuration variables and their values The dict has the following structure : ' MY _ CONFI...
confs = self . app . config . get ( 'WAFFLE_CONFS' , { } ) to_update = { } for key in new_values . keys ( ) : # Some things cannot be changed . . . if key . startswith ( 'WAFFLE_' ) : continue # No arbitrary keys if key not in confs . keys ( ) : continue value = new_values [ key ] se...
def insertItem ( self , index , item ) : """Inserts parameter * item * at index"""
row = index . row ( ) self . beginInsertRows ( QtCore . QModelIndex ( ) , row , row ) self . model . insertRow ( row ) self . endInsertRows ( ) self . model . overwriteParam ( index . row ( ) , item )
def Fill ( self , P = [ ( 100 , 0 ) , ( 85 , 15 ) , ( 0 , 3 ) ] , Color = 'blue' , Alpha = 0.3 ) : '''Fill a region in planimetric rectangular coord . : param P : the peak points of the region in planimetric rectangular coord : type P : a list consist of at least three tuples , which are the points in planimetr...
a = [ ] b = [ ] for i in P : a . append ( i [ 0 ] ) b . append ( i [ 1 ] ) return ( a , b )
def hybrid_coroutine_worker ( selector , workers ) : """Runs a set of workers , all of them in the main thread . This runner is here for testing purposes . : param selector : A function returning a worker key , given a job . : type selector : function : param workers : A dict of workers . : type worke...
jobs = Queue ( ) worker_source = { } worker_sink = { } for k , w in workers . items ( ) : worker_source [ k ] , worker_sink [ k ] = w . setup ( ) def get_result ( ) : source = jobs . source ( ) for msg in source : key , job = msg worker = selector ( job ) if worker is None : ...
def get_section_metrics ( cls ) : """Get the mapping between metrics and sections in Manuscripts report : return : a dict with the mapping between metrics and sections in Manuscripts report"""
return { "overview" : { "activity_metrics" : [ Closed , Opened ] , "author_metrics" : [ ] , "bmi_metrics" : [ BMI ] , "time_to_close_metrics" : [ DaysToCloseMedian ] , "projects_metrics" : [ Projects ] } , "com_channels" : { "activity_metrics" : [ ] , "author_metrics" : [ ] } , "project_activity" : { "metrics" : [ Open...
def date_to_datetime ( d ) : """> > > date _ to _ datetime ( date ( 2000 , 1 , 2 ) ) datetime . datetime ( 2000 , 1 , 2 , 0 , 0) > > > date _ to _ datetime ( datetime ( 2000 , 1 , 2 , 3 , 4 , 5 ) ) datetime . datetime ( 2000 , 1 , 2 , 3 , 4 , 5)"""
if not isinstance ( d , datetime ) : d = datetime . combine ( d , datetime . min . time ( ) ) return d
def setup_axes ( ax = None , panels = 'blue' , colorbars = [ False ] , right_margin = None , left_margin = None , projection = '2d' , show_ticks = False ) : """Grid of axes for plotting , legends and colorbars ."""
if '3d' in projection : from mpl_toolkits . mplot3d import Axes3D avail_projections = { '2d' , '3d' } if projection not in avail_projections : raise ValueError ( 'choose projection from' , avail_projections ) if left_margin is not None : raise ValueError ( 'Currently not supporting to pass `left_margin`.' )...
def auto_code_to_openid ( self , auth_code ) : """授权码查询 openid 接口 : param auth _ code : 扫码支付授权码 , 设备读取用户微信中的条码或者二维码信息 : return : 返回的结果数据"""
data = { 'appid' : self . appid , 'auth_code' : auth_code , } return self . _post ( 'tools/authcodetoopenid' , data = data )
def resolve_parameters ( self , func , extra_env = None ) : """Resolve parameter dictionary for the supplied function"""
parameter_list = [ ( k , v . default == inspect . Parameter . empty ) for k , v in inspect . signature ( func ) . parameters . items ( ) ] extra_env = extra_env if extra_env is not None else { } kwargs = { } for parameter_name , is_required in parameter_list : # extra _ env is a ' local ' object data defined in - place...
def get_buckets ( min_length , max_length , bucket_count ) : '''Get bucket by length .'''
if bucket_count <= 0 : return [ max_length ] unit_length = int ( ( max_length - min_length ) // ( bucket_count ) ) buckets = [ min_length + unit_length * ( i + 1 ) for i in range ( 0 , bucket_count ) ] buckets [ - 1 ] = max_length return buckets
def draw_capitan_stroke_images ( self , symbols : List [ CapitanSymbol ] , destination_directory : str , stroke_thicknesses : List [ int ] ) -> None : """Creates a visual representation of the Capitan strokes by drawing lines that connect the points from each stroke of each symbol . : param symbols : The list o...
total_number_of_symbols = len ( symbols ) * len ( stroke_thicknesses ) output = "Generating {0} images with {1} symbols in {2} different stroke thicknesses ({3})" . format ( total_number_of_symbols , len ( symbols ) , len ( stroke_thicknesses ) , stroke_thicknesses ) print ( output ) print ( "In directory {0}" . format...
def get_ontology ( self , id = None , uri = None , match = None ) : """get the saved - ontology with given ID or via other methods . . ."""
if not id and not uri and not match : return None if type ( id ) == type ( "string" ) : uri = id id = None if not is_http ( uri ) : match = uri uri = None if match : if type ( match ) != type ( "string" ) : return [ ] res = [ ] for x in self . all_ontologies : ...
def add_authenticated_read ( self ) : """Add ` ` read ` ` perm for all authenticated subj . Public ` ` read ` ` is removed if present ."""
self . remove_perm ( d1_common . const . SUBJECT_PUBLIC , 'read' ) self . add_perm ( d1_common . const . SUBJECT_AUTHENTICATED , 'read' )
def pois_from_point ( point , distance = None , amenities = None ) : """Get point of interests ( POIs ) within some distance north , south , east , and west of a lat - long point . Parameters point : tuple a lat - long point distance : numeric distance in meters amenities : list List of amenities th...
bbox = bbox_from_point ( point = point , distance = distance ) north , south , east , west = bbox return create_poi_gdf ( amenities = amenities , north = north , south = south , east = east , west = west )
def p_typename ( self , t ) : "typename : NAME \n | NAME ' ( ' INTLIT ' ) '"
t [ 0 ] = TypeX ( t [ 1 ] , None ) if len ( t ) == 2 else TypeX ( t [ 1 ] , int ( t [ 3 ] ) )
def backup ( app ) : """Dump the database ."""
dump_path = dump_database ( app ) config = PsiturkConfig ( ) config . load_config ( ) conn = boto . connect_s3 ( config . get ( 'AWS Access' , 'aws_access_key_id' ) , config . get ( 'AWS Access' , 'aws_secret_access_key' ) , ) bucket = conn . create_bucket ( app , location = boto . s3 . connection . Location . DEFAULT ...
def _axes ( self ) : """Set the _ force _ vertical flag when rendering axes"""
self . view . _force_vertical = True super ( HorizontalGraph , self ) . _axes ( ) self . view . _force_vertical = False
def apply ( self , value , input_ranges , backend = None ) : """Apply the compositor on the input with the given input ranges ."""
from . overlay import CompositeOverlay if backend is None : backend = Store . current_backend kwargs = { k : v for k , v in self . kwargs . items ( ) if k != 'output_type' } if isinstance ( value , CompositeOverlay ) and len ( value ) == 1 : value = value . values ( ) [ 0 ] if self . transfer_parameters : ...
def get ( path , profile = None , hosts = None , scheme = None , username = None , password = None , default_acl = None ) : '''Get value saved in znode path path to check profile Configured Zookeeper profile to authenticate with ( Default : None ) hosts Lists of Zookeeper Hosts ( Default : ' 127.0.0.1:2...
conn = _get_zk_conn ( profile = profile , hosts = hosts , scheme = scheme , username = username , password = password , default_acl = default_acl ) ret , _ = conn . get ( path ) return salt . utils . stringutils . to_str ( ret )
def is_verified ( self ) : """Retrieves the verification status of the incident / incidents from the output response Returns : verified ( namedtuple ) : List of named tuples of verification status of the incident / incidents"""
resource_list = self . traffic_incident ( ) verified = namedtuple ( 'verified' , 'verified' ) if len ( resource_list ) == 1 and resource_list [ 0 ] is None : return None else : try : return [ verified ( resource [ 'verified' ] ) for resource in resource_list ] except ( KeyError , TypeError ) : ...
def _build_filter_part ( self , cls , filters , order_by = None , select = None ) : """Build the filter part"""
import types query_parts = [ ] order_by_filtered = False if order_by : if order_by [ 0 ] == "-" : order_by_method = "DESC" ; order_by = order_by [ 1 : ] else : order_by_method = "ASC" ; if select : if order_by and order_by in select : order_by_filtered = True query_parts ...
def to_choices_dict ( choices ) : """Convert choices into key / value dicts . pairwise _ choices ( [ 1 ] ) - > { 1 : 1} pairwise _ choices ( [ ( 1 , ' 1st ' ) , ( 2 , ' 2nd ' ) ] ) - > { 1 : ' 1st ' , 2 : ' 2nd ' } pairwise _ choices ( [ ( ' Group ' , ( ( 1 , ' 1st ' ) , 2 ) ) ] ) - > { ' Group ' : { 1 : ' 1s...
# Allow single , paired or grouped choices style : # choices = [ 1 , 2 , 3] # choices = [ ( 1 , ' First ' ) , ( 2 , ' Second ' ) , ( 3 , ' Third ' ) ] # choices = [ ( ' Category ' , ( ( 1 , ' First ' ) , ( 2 , ' Second ' ) ) ) , ( 3 , ' Third ' ) ] ret = OrderedDict ( ) for choice in choices : if ( not isinstance (...
def _departure ( self ) -> datetime : """Extract departure time ."""
departure_time = datetime . strptime ( self . journey . MainStop . BasicStop . Dep . Time . text , "%H:%M" ) . time ( ) if departure_time > ( self . now - timedelta ( hours = 1 ) ) . time ( ) : return datetime . combine ( self . now . date ( ) , departure_time ) return datetime . combine ( self . now . date ( ) + t...
def recognise_model ( feature_filename , symbollist_filename , model_directory , recognition_filename , pronunciation_dictionary_filename , list_words_filename = '' , cmllr_directory = None , tokens_count = None , hypotheses_count = 1 , htk_trace = 0 ) : """Perform recognition using a model and assuming a single wo...
# Normalize UTF - 8 to avoid Mac problems temp_dictionary_filename = utf8_normalize ( pronunciation_dictionary_filename ) # Create language word list if list_words_filename : list_words = parse_wordlist ( list_words_filename ) else : list_words = sorted ( parse_dictionary ( temp_dictionary_filename ) . keys ( )...
def _verify_python3_env ( ) : """Ensures that the environment is good for unicode on Python 3."""
if PY2 : return try : import locale fs_enc = codecs . lookup ( locale . getpreferredencoding ( ) ) . name except Exception : fs_enc = 'ascii' if fs_enc != 'ascii' : return extra = '' if os . name == 'posix' : import subprocess try : rv = subprocess . Popen ( [ 'locale' , '-a' ] , std...
def affine ( data , mat = np . identity ( 4 ) , mode = "constant" , interpolation = "linear" ) : """affine transform data with matrix mat , which is the inverse coordinate transform matrix ( similar to ndimage . affine _ transform ) Parameters data , ndarray 3d array to be transformed mat , ndarray 3x3 ...
warnings . warn ( "gputools.transform.affine: API change as of gputools>= 0.2.8: the inverse of the matrix is now used as in scipy.ndimage.affine_transform" ) if not ( isinstance ( data , np . ndarray ) and data . ndim == 3 ) : raise ValueError ( "input data has to be a 3d array!" ) interpolation_defines = { "linea...
def column ( self ) : """Get the column object : param DeclarativeMeta model : the model : param str field : the field : return InstrumentedAttribute : the column to filter on"""
field = self . name model_field = get_model_field ( self . schema , field ) try : return getattr ( self . model , model_field ) except AttributeError : raise InvalidFilters ( "{} has no attribute {}" . format ( self . model . __name__ , model_field ) )
def incr ( self , stat , count = 1 , rate = 1 ) : """Increment a stat by ` count ` ."""
return self . send ( stat , "%s|c" % count , rate )
def report_stderr ( host , stderr ) : """Take a stderr and print it ' s lines to output if lines are present . : param host : the host where the process is running : type host : str : param stderr : the std error of that process : type stderr : paramiko . channel . Channel"""
lines = stderr . readlines ( ) if lines : print ( "STDERR from {host}:" . format ( host = host ) ) for line in lines : print ( line . rstrip ( ) , file = sys . stderr )
def _clean_up_key ( self , key ) : """Returns the key string with no naughty characters ."""
for n in self . naughty : key = key . replace ( n , '_' ) return key
def print_line ( s , bold = False , underline = False , blinking = False , color = None , bgcolor = None , end = '\n' ) : """Prints a string with the given formatting ."""
s = get_line ( s , bold = bold , underline = underline , blinking = blinking , color = color , bgcolor = bgcolor ) print ( s , end = end )
def safe_remove_file ( filename , app ) : """Removes a given resource file from builder resources . Needed mostly during test , if multiple sphinx - build are started . During these tests js / cass - files are not cleaned , so a css _ file from run A is still registered in run B . : param filename : filename ...
data_file = filename static_data_file = os . path . join ( "_static" , data_file ) if data_file . split ( "." ) [ - 1 ] == "js" : if hasattr ( app . builder , "script_files" ) and static_data_file in app . builder . script_files : app . builder . script_files . remove ( static_data_file ) elif data_file . s...
def apwp ( data , print_results = False ) : """calculates expected pole positions and directions for given plate , location and age Parameters _ _ _ _ _ data : [ plate , lat , lon , age ] plate : [ NA , SA , AF , IN , EU , AU , ANT , GL ] NA : North America SA : South America AF : Africa IN : India ...
pole_lat , pole_lon = bc02 ( data ) # get the pole for these parameters # get the declination and inclination for that pole ExpDec , ExpInc = vgp_di ( pole_lat , pole_lon , data [ 1 ] , data [ 2 ] ) # convert the inclination to paleo latitude paleo_lat = magnetic_lat ( ExpInc ) if print_results : # print everything out...
def init ( ) : """Initialization , all begin from here"""
su ( ) args = sys . argv args . pop ( 0 ) cmd = "{0}sun_daemon" . format ( bin_path ) if len ( args ) == 1 : if args [ 0 ] == "start" : print ( "Starting SUN daemon: {0} &" . format ( cmd ) ) subprocess . call ( "{0} &" . format ( cmd ) , shell = True ) elif args [ 0 ] == "stop" : print...
def calc_et0_wet0_v1 ( self ) : """Correct the given reference evapotranspiration and update the corresponding log sequence . Required control parameters : | NHRU | | KE | | WfET0 | Required input sequence : | PET | Calculated flux sequence : | ET0 | Updated log sequence : | WET0 | Basic equ...
con = self . parameters . control . fastaccess inp = self . sequences . inputs . fastaccess flu = self . sequences . fluxes . fastaccess log = self . sequences . logs . fastaccess for k in range ( con . nhru ) : flu . et0 [ k ] = ( con . wfet0 [ k ] * con . ke [ k ] * inp . pet + ( 1. - con . wfet0 [ k ] ) * log . ...
def main ( argv ) : """This is a test and will assemble the file in argv [ 0]"""
init ( ) if OPTIONS . StdErrFileName . value : OPTIONS . stderr . value = open ( 'wt' , OPTIONS . StdErrFileName . value ) asmlex . FILENAME = OPTIONS . inputFileName . value = argv [ 0 ] input_ = open ( OPTIONS . inputFileName . value , 'rt' ) . read ( ) assemble ( input_ ) generate_binary ( OPTIONS . outputFileNa...
def cloud_config ( path = None , env_var = 'SALT_CLOUD_CONFIG' , defaults = None , master_config_path = None , master_config = None , providers_config_path = None , providers_config = None , profiles_config_path = None , profiles_config = None ) : '''Read in the Salt Cloud config and return the dict'''
if path : config_dir = os . path . dirname ( path ) else : config_dir = salt . syspaths . CONFIG_DIR # Load the cloud configuration overrides = load_config ( path , env_var , os . path . join ( config_dir , 'cloud' ) ) if defaults is None : defaults = DEFAULT_CLOUD_OPTS . copy ( ) # Set defaults early to ov...
def shadowUpdate ( self , srcJSONPayload , srcCallback , srcTimeout ) : """* * Description * * Update the device shadow JSON document string from AWS IoT by publishing the provided JSON document to the corresponding shadow topics . Shadow response topics will be subscribed to receive responses from AWS IoT re...
# Validate JSON self . _basicJSONParserHandler . setString ( srcJSONPayload ) if self . _basicJSONParserHandler . validateJSON ( ) : with self . _dataStructureLock : # clientToken currentToken = self . _tokenHandler . getNextToken ( ) self . _tokenPool [ currentToken ] = Timer ( srcTimeout , self . ...
def parse ( self ) : """Retreive and parse Play by Play data for the given nhlscrapi . GameKey : returns : ` ` self ` ` on success , ` ` None ` ` otherwise"""
try : return ( super ( FaceOffRep , self ) . parse ( ) and self . parse_home_face_offs ( ) and self . parse_away_face_offs ( ) ) except : return None
def backoff_delays ( start , stop , factor = 2.0 , jitter = False ) : """Geometric backoff sequence w / jitter"""
cur = start while cur <= stop : if jitter : yield cur - ( cur * random . random ( ) ) else : yield cur cur = cur * factor
def temp_land ( self , pcps , water ) : """Derive high / low percentiles of land temperature Equations 12 an 13 ( Zhu and Woodcock , 2012) Parameters pcps : ndarray potential cloud pixels , boolean water : ndarray water mask , boolean tirs1 : ndarray Output tuple : 17.5 and 82.5 percentile tempe...
# eq 12 clearsky_land = ~ ( pcps | water ) # use clearsky _ land to mask tirs1 clear_land_temp = self . tirs1 . copy ( ) clear_land_temp [ ~ clearsky_land ] = np . nan clear_land_temp [ ~ self . mask ] = np . nan # take 17.5 and 82.5 percentile , eq 13 low , high = np . nanpercentile ( clear_land_temp , ( 17.5 , 82.5 )...
def fundm ( self ) : """以字典形式返回分级母基数据"""
# 添加当前的ctime self . __fundm_url = self . __fundm_url . format ( ctime = int ( time . time ( ) ) ) # 请求数据 rep = requests . get ( self . __fundm_url ) # 获取返回的json字符串 fundmjson = json . loads ( rep . text ) # 格式化返回的json字符串 data = self . formatfundajson ( fundmjson ) self . __fundm = data return self . __fundm
def add_or_update ( uid , post_data ) : '''Add or update the data by the given ID of post .'''
catinfo = MCategory . get_by_uid ( uid ) if catinfo : MCategory . update ( uid , post_data ) else : TabTag . create ( uid = uid , name = post_data [ 'name' ] , slug = post_data [ 'slug' ] , order = post_data [ 'order' ] , kind = post_data [ 'kind' ] if 'kind' in post_data else '1' , pid = post_data [ 'pid' ] , ...
def extend_supplement_links ( destination , source ) : """Extends ( merges ) destination dictionary with supplement _ links from source dictionary . Values are expected to be lists , or any data structure that has ` extend ` method . @ param destination : Destination dictionary that will be extended . @ typ...
for key , value in iteritems ( source ) : if key not in destination : destination [ key ] = value else : destination [ key ] . extend ( value )
def cli_main ( ) : # pragma : no cover """Main function when running from CLI ."""
if '--debug' in sys . argv : LOG . setLevel ( logging . DEBUG ) elif '--verbose' in sys . argv : LOG . setLevel ( logging . INFO ) args = _get_arguments ( ) try : plugin , folder = get_plugin_and_folder ( inputzip = args . inputzip , inputdir = args . inputdir , inputfile = args . inputfile ) LOG . debu...
def compiled_update_func ( self ) : """Returns compiled update function"""
def get_not_none_col_assignment ( column_name ) : return ALCHEMY_TEMPLATES . not_none_col_assignment . safe_substitute ( col_name = column_name ) def get_compiled_args ( arg_name ) : return ALCHEMY_TEMPLATES . func_arg . safe_substitute ( arg_name = arg_name ) join_string = "\n" + self . tab + self . tab column...
def push ( self ) : """Push the changes back to the remote ( s ) after fetching"""
print ( 'pushing...' ) push_kwargs = { } push_args = [ ] if self . settings [ 'push.tags' ] : push_kwargs [ 'push' ] = True if self . settings [ 'push.all' ] : push_kwargs [ 'all' ] = True else : if '.' in self . remotes : self . remotes . remove ( '.' ) if not self . remotes : # Only local ...
def _delete_security_groups ( self ) : """Delete the security groups for each role in the cluster , and the group for the cluster ."""
group_names = self . _get_all_group_names_for_cluster ( ) for group in group_names : self . ec2 . delete_security_group ( group )
def get_localized_docstring ( obj , domain ) : """Get a cleaned - up , localized copy of docstring of this class ."""
if obj . __class__ . __doc__ is not None : return inspect . cleandoc ( gettext . dgettext ( domain , obj . __class__ . __doc__ ) )
def protocols ( ) : """Return a list of values from the IANA Service Name and Transport Protocol Port Number Registry , or an empty list if the IANA website is unreachable . Store it as a function attribute so that we only build the list once ."""
if not hasattr ( protocols , 'protlist' ) : plist = [ ] try : data = requests . get ( 'http://www.iana.org/assignments/service-names' '-port-numbers/service-names-port-numbers.csv' ) except requests . exceptions . RequestException : return [ ] for line in data . iter_lines ( ) : ...
def load_lines ( filename ) : """Load a text file as an array of lines . Args : filename : Path to the input file . Returns : An array of strings , each representing an individual line ."""
with open ( filename , 'r' , encoding = 'utf-8' ) as f : return [ line . rstrip ( '\n' ) for line in f . readlines ( ) ]
def cross_validate ( self , ax , info = '' ) : '''Cross - validate to find the optimal value of : py : obj : ` lambda ` . : param ax : The current : py : obj : ` matplotlib . pyplot ` axis instance to plot the cross - validation results . : param str info : The label to show in the bottom right - hand corner of...
# Loop over all chunks ax = np . atleast_1d ( ax ) for b , brkpt in enumerate ( self . breakpoints ) : log . info ( "Cross-validating chunk %d/%d..." % ( b + 1 , len ( self . breakpoints ) ) ) med_training = np . zeros_like ( self . lambda_arr ) med_validation = np . zeros_like ( self . lambda_arr ) # M...
def get_file_link ( self , file_key ) : '''Gets link to file Args : file _ keykey for the file return ( status code , ? )'''
# does not work self . _raise_unimplemented_error ( ) uri = '/' . join ( [ self . api_uri , self . files_suffix , file_key , self . file_link_suffix , ] ) return self . _req ( 'get' , uri )
def fit_transform ( self , data ) : """Fits and transforms the SFrame ` data ` using a fitted model . Parameters data : SFrame The data to be transformed . Returns A transformed SFrame . Returns out : SFrame A transformed SFrame . See Also fit , transform"""
self . _setup_from_data ( data ) ret = self . transform_chain . fit_transform ( data ) self . __proxy__ . update ( { "fitted" : True } ) return ret
def open ( self ) : """Opens the connection ."""
self . _id = str ( uuid . uuid4 ( ) ) self . _client . open_connection ( self . _id , info = self . _connection_args )
def should_add_ServerHello ( self ) : """Selecting a cipher suite should be no trouble as we already caught the None case previously . Also , we do not manage extensions at all ."""
if isinstance ( self . mykey , PrivKeyRSA ) : kx = "RSA" elif isinstance ( self . mykey , PrivKeyECDSA ) : kx = "ECDSA" usable_suites = get_usable_ciphersuites ( self . cur_pkt . ciphers , kx ) c = usable_suites [ 0 ] if self . preferred_ciphersuite in usable_suites : c = self . preferred_ciphersuite self ....
def _organize_qc_files ( program , qc_dir ) : """Organize outputs from quality control runs into a base file and secondary outputs . Provides compatibility with CWL output . Returns None if no files created during processing ."""
base_files = { "fastqc" : "fastqc_report.html" , "qualimap_rnaseq" : "qualimapReport.html" , "qualimap" : "qualimapReport.html" } if os . path . exists ( qc_dir ) : out_files = [ ] for fname in [ os . path . join ( qc_dir , x ) for x in os . listdir ( qc_dir ) ] : if os . path . isfile ( fname ) and not...
def lmfit_parameter_values ( self , params ) : """` params ` is a [ ` lmfit . Parameters ` ] [ 1 ] object . Returns a tuple containing the values of the parameters in ` params ` . The order is determined by sorting the parameter keys alphabetically . [1 ] : http : / / lmfit . github . io / lmfit - py / parame...
return tuple ( params [ key ] . value for key in sorted ( params ) )
def update ( self , body ) : """Update the MessageInstance : param unicode body : The text of the message you want to send : returns : Updated MessageInstance : rtype : twilio . rest . api . v2010 . account . message . MessageInstance"""
data = values . of ( { 'Body' : body , } ) payload = self . _version . update ( 'POST' , self . _uri , data = data , ) return MessageInstance ( self . _version , payload , account_sid = self . _solution [ 'account_sid' ] , sid = self . _solution [ 'sid' ] , )
def get_intern_pattern ( self , url = None ) : """Get pattern for intern URL matching . @ return non - empty regex pattern or None @ rtype String or None"""
if url is None : url = self . url if not url : return None if url . startswith ( 'file://' ) : i = url . rindex ( '/' ) if i > 6 : # remove last filename to make directory internal url = url [ : i + 1 ] return re . escape ( url )