signature
stringlengths
29
44.1k
implementation
stringlengths
0
85.2k
def merge ( self , merge_area , tab ) : """Merges top left cell with all cells until bottom _ right"""
top , left , bottom , right = merge_area cursor = self . grid . actions . cursor top_left_code = self . code_array ( ( top , left , cursor [ 2 ] ) ) selection = Selection ( [ ( top , left ) ] , [ ( bottom , right ) ] , [ ] , [ ] , [ ] ) # Check if the merge area overlaps another merge area error_msg = _ ( "Overlapping ...
def _get_input_data ( self , var , start_date , end_date ) : """Get the data for a single variable over the desired date range ."""
logging . info ( self . _print_verbose ( "Getting input data:" , var ) ) if isinstance ( var , ( float , int ) ) : return var else : cond_pfull = ( ( not hasattr ( self , internal_names . PFULL_STR ) ) and var . def_vert and self . dtype_in_vert == internal_names . ETA_STR ) data = self . data_loader . recu...
def orthonormal_initializer ( output_size , input_size , debug = False ) : """adopted from Timothy Dozat https : / / github . com / tdozat / Parser / blob / master / lib / linalg . py Parameters output _ size : int input _ size : int debug : bool Whether to skip this initializer Returns Q : np . ndarr...
print ( ( output_size , input_size ) ) if debug : Q = np . random . randn ( input_size , output_size ) / np . sqrt ( output_size ) return np . transpose ( Q . astype ( np . float32 ) ) I = np . eye ( output_size ) lr = .1 eps = .05 / ( output_size + input_size ) success = False tries = 0 while not success and t...
def push_intent ( self , intent ) : """Registers or updates an intent and returns the intent _ json with an ID"""
if intent . id : print ( 'Updating {} intent' . format ( intent . name ) ) self . update ( intent ) else : print ( 'Registering {} intent' . format ( intent . name ) ) intent = self . register ( intent ) return intent
def parse_extension_item ( header : str , pos : int , header_name : str ) -> Tuple [ ExtensionHeader , int ] : """Parse an extension definition from ` ` header ` ` at the given position . Return an ` ` ( extension name , parameters ) ` ` pair , where ` ` parameters ` ` is a list of ` ` ( name , value ) ` ` pair...
# Extract extension name . name , pos = parse_token ( header , pos , header_name ) pos = parse_OWS ( header , pos ) # Extract all parameters . parameters = [ ] while peek_ahead ( header , pos ) == ";" : pos = parse_OWS ( header , pos + 1 ) parameter , pos = parse_extension_item_param ( header , pos , header_nam...
def setTimeout ( self , time ) : """Set global timeout value , in seconds , for all DDE calls"""
self . conversation . SetDDETimeout ( round ( time ) ) return self . conversation . GetDDETimeout ( )
def get_decoder_component ( name , input_layer , encoded_layer , head_num , hidden_dim , attention_activation = None , feed_forward_activation = 'relu' , dropout_rate = 0.0 , trainable = True ) : """Multi - head self - attention , multi - head query attention and feed - forward layer . : param name : Prefix of na...
self_attention_name = '%s-MultiHeadSelfAttention' % name query_attention_name = '%s-MultiHeadQueryAttention' % name feed_forward_name = '%s-FeedForward' % name self_attention_layer = _wrap_layer ( name = self_attention_name , input_layer = input_layer , build_func = attention_builder ( name = self_attention_name , head...
def attach ( cls , tuning_job_name , sagemaker_session = None , job_details = None , estimator_cls = None ) : """Attach to an existing hyperparameter tuning job . Create a HyperparameterTuner bound to an existing hyperparameter tuning job . After attaching , if there exists a best training job ( or any other co...
sagemaker_session = sagemaker_session or Session ( ) if job_details is None : job_details = sagemaker_session . sagemaker_client . describe_hyper_parameter_tuning_job ( HyperParameterTuningJobName = tuning_job_name ) estimator_cls = cls . _prepare_estimator_cls ( estimator_cls , job_details [ 'TrainingJobDefinition...
def license_fallback ( vendor_dir , sdist_name ) : """Hardcoded license URLs . Check when updating if those are still needed"""
libname = libname_from_dir ( sdist_name ) if libname not in HARDCODED_LICENSE_URLS : raise ValueError ( 'No hardcoded URL for {} license' . format ( libname ) ) url = HARDCODED_LICENSE_URLS [ libname ] _ , _ , name = url . rpartition ( '/' ) dest = license_destination ( vendor_dir , libname , name ) r = requests . ...
def help_center_article_subscription_show ( self , article_id , id , locale = None , ** kwargs ) : "https : / / developer . zendesk . com / rest _ api / docs / help _ center / subscriptions # show - article - subscription"
api_path = "/api/v2/help_center/articles/{article_id}/subscriptions/{id}.json" api_path = api_path . format ( article_id = article_id , id = id ) if locale : api_opt_path = "/api/v2/help_center/{locale}/articles/{article_id}/subscriptions/{id}.json" api_path = api_opt_path . format ( article_id = article_id , i...
def decorate ( self , pos , widget , is_first = True ) : """builds a list element for given position in the tree . It consists of the original widget taken from the Tree and some decoration columns depending on the existence of parent and sibling positions . The result is a urwid . Columns widget ."""
line = None if pos is not None : original_widget = widget cols = self . _construct_spacer ( pos , [ ] ) # Construct arrow leading from parent here , # if we have a parent and indentation is turned on if self . _indent > 0 : if is_first : indent = self . _construct_first_indent ( ...
def shape_based_slice_insertation ( sl1 , sl2 , dim , nslices , order = 3 ) : """Insert ` nslices ` new slices between ` sl1 ` and ` sl2 ` along dimension ` dim ` using shape based binary interpolation . Extrapolation is handled adding ` nslices ` / 2 step - wise eroded copies of the last slice in each direct...
sl1 = sl1 . astype ( numpy . bool ) sl2 = sl2 . astype ( numpy . bool ) # extrapolation through erosion if 0 == numpy . count_nonzero ( sl1 ) : slices = [ sl1 ] for _ in range ( nslices / 2 ) : slices . append ( numpy . zeros_like ( sl1 ) ) for i in range ( 1 , nslices / 2 + nslices % 2 + 1 ) [ : : ...
def gep ( self , i ) : """Resolve the type of the i - th element ( for getelementptr lookups ) ."""
if not isinstance ( i . type , IntType ) : raise TypeError ( i . type ) return self . pointee
def _proxy ( self ) : """Generate an instance context for the instance , the context is capable of performing various actions . All instance actions are proxied to the context : returns : TaskQueueContext for this TaskQueueInstance : rtype : twilio . rest . taskrouter . v1 . workspace . task _ queue . TaskQue...
if self . _context is None : self . _context = TaskQueueContext ( self . _version , workspace_sid = self . _solution [ 'workspace_sid' ] , sid = self . _solution [ 'sid' ] , ) return self . _context
def _check_min_max_indices ( self , min_index = None , max_index = None ) : """Ensure the given start / end fragment indices make sense : if one of them is ` ` None ` ` ( i . e . , not specified ) , then set it to ` ` 0 ` ` or ` ` len ( self ) ` ` ."""
min_index = min_index or 0 max_index = max_index or len ( self ) if min_index < 0 : self . log_exc ( u"min_index is negative" , None , True , ValueError ) if max_index > len ( self ) : self . log_exc ( u"max_index is bigger than the number of intervals in the list" , None , True , ValueError ) return min_index ...
def point ( self , t ) : """returns the coordinates of the Bezier curve evaluated at t ."""
distance = self . end - self . start return self . start + distance * t
def supply_and_demand ( lcm , choosers , alternatives , alt_segmenter , price_col , base_multiplier = None , clip_change_low = 0.75 , clip_change_high = 1.25 , iterations = 5 , multiplier_func = None ) : """Adjust real estate prices to compensate for supply and demand effects . Parameters lcm : LocationChoiceMo...
logger . debug ( 'start: calculating supply and demand price adjustment' ) # copy alternatives so we don ' t modify the user ' s original alternatives = alternatives . copy ( ) # if alt _ segmenter is a string , get the actual column for segmenting demand if isinstance ( alt_segmenter , str ) : alt_segmenter = alte...
def emit ( self , span_datas ) : """: type span _ datas : list of : class : ` ~ opencensus . trace . span _ data . SpanData ` : param list of opencensus . trace . span _ data . SpanData span _ datas : SpanData tuples to emit"""
try : # TODO : keep the stream alive . # The stream is terminated after iteration completes . # To keep it alive , we can enqueue proto spans here # and asyncronously read them and send to the agent . responses = self . client . Export ( self . generate_span_requests ( span_datas ) ) # read response for _ i...
def _get_dataruns ( self ) : '''Returns a list of dataruns , in order .'''
if self . _data_runs is None : raise DataStreamError ( "Resident datastream don't have dataruns" ) if not self . _data_runs_sorted : self . _data_runs . sort ( key = _itemgetter ( 0 ) ) self . _data_runs_sorted = True return [ data [ 1 ] for data in self . _data_runs ]
def updateidf ( idf , dct ) : """update idf using dct"""
for key in list ( dct . keys ( ) ) : if key . startswith ( 'idf.' ) : idftag , objkey , objname , field = key2elements ( key ) if objname == '' : try : idfobj = idf . idfobjects [ objkey . upper ( ) ] [ 0 ] except IndexError as e : idfobj = idf...
def _freecpu ( conn ) : '''Internal variant of freecpu taking a libvirt connection as parameter'''
cpus = conn . getInfo ( ) [ 2 ] for dom in _get_domain ( conn , iterable = True ) : if dom . ID ( ) > 0 : cpus -= dom . info ( ) [ 3 ] return cpus
def value_for_keypath ( obj , path ) : """Get value from walking key path with start object obj ."""
val = obj for part in path . split ( '.' ) : match = re . match ( list_index_re , part ) if match is not None : val = _extract ( val , match . group ( 1 ) ) if not isinstance ( val , list ) and not isinstance ( val , tuple ) : raise TypeError ( 'expected list/tuple' ) index =...
def add_to ( self , parent , additions ) : "Modify parent to include all elements in additions"
for x in additions : if x not in parent : parent . append ( x ) self . changed ( )
def set_ylim ( self , xlims , dx , xscale , reverse = False ) : """Set y limits for plot . This will set the limits for the y axis for the specific plot . Args : ylims ( len - 2 list of floats ) : The limits for the axis . dy ( float ) : Amount to increment by between the limits . yscale ( str ) : Scale...
self . _set_axis_limits ( 'y' , xlims , dx , xscale , reverse ) return
def _read_modeling_results ( self , directory , silent = False ) : """Read modeling results from a given mod / directory . Possible values to read in are : * voltages * potentials * sensitivities"""
voltage_file = directory + os . sep + 'volt.dat' if os . path . isfile ( voltage_file ) : if not silent : print ( 'reading voltages' ) self . read_voltages ( voltage_file ) sens_files = sorted ( glob ( directory + os . sep + 'sens' + os . sep + 'sens*.dat' ) ) # check if there are sensitivity files , an...
def extract_source_geom ( dstore , srcidxs ) : """Extract the geometry of a given sources Example : http : / / 127.0.0.1:8800 / v1 / calc / 30 / extract / source _ geom / 1,2,3"""
for i in srcidxs . split ( ',' ) : rec = dstore [ 'source_info' ] [ int ( i ) ] geom = dstore [ 'source_geom' ] [ rec [ 'gidx1' ] : rec [ 'gidx2' ] ] yield rec [ 'source_id' ] , geom
def tg90p ( tas , t90 , freq = 'YS' ) : r"""Number of days with daily mean temperature over the 90th percentile . Number of days with daily mean temperature over the 90th percentile . Parameters tas : xarray . DataArray Mean daily temperature [ ° C ] or [ K ] t90 : xarray . DataArray 90th percentile of ...
if 'dayofyear' not in t90 . coords . keys ( ) : raise AttributeError ( "t10 should have dayofyear coordinates." ) t90 = utils . convert_units_to ( t90 , tas ) # adjustment of t90 to tas doy range t90 = utils . adjust_doy_calendar ( t90 , tas ) # create array of percentile with tas shape and coords thresh = xr . ful...
def do_preprocess ( defn ) : """Run a string through the C preprocessor that ships with pycparser but is weirdly inaccessible ?"""
from pycparser . ply import lex , cpp lexer = lex . lex ( cpp ) p = cpp . Preprocessor ( lexer ) # p . add _ path ( dir ) will add dir to the include search path p . parse ( defn ) return '' . join ( tok . value for tok in p . parser if tok . type not in p . ignore )
def _goto ( self , pose , duration , wait , accurate ) : """Goes to a given cartesian pose . : param matrix pose : homogeneous matrix representing the target position : param float duration : move duration : param bool wait : whether to wait for the end of the move : param bool accurate : trade - off betwee...
kwargs = { } if not accurate : kwargs [ 'max_iter' ] = 3 q0 = self . convert_to_ik_angles ( self . joints_position ) q = self . inverse_kinematics ( pose , initial_position = q0 , ** kwargs ) joints = self . convert_from_ik_angles ( q ) last = self . motors [ - 1 ] for m , pos in list ( zip ( self . motors , joints...
def set_cookie ( cookies , key , value = '' , max_age = None , expires = None , path = '/' , domain = None , secure = False , httponly = False ) : '''Set a cookie key into the cookies dictionary * cookies * .'''
cookies [ key ] = value if expires is not None : if isinstance ( expires , datetime ) : now = ( expires . now ( expires . tzinfo ) if expires . tzinfo else expires . utcnow ( ) ) delta = expires - now # Add one second so the date matches exactly ( a fraction of # time gets lost betwe...
def get_type_data ( name ) : """Return dictionary representation of type . Can be used to initialize primordium . type . primitives . Type"""
name = name . upper ( ) try : return { 'authority' : 'birdland.mit.edu' , 'namespace' : 'unit system' , 'identifier' : name , 'domain' : 'Unit System Types' , 'display_name' : JEFFS_UNIT_SYSTEM_TYPES [ name ] + ' Unit System Type' , 'display_label' : JEFFS_UNIT_SYSTEM_TYPES [ name ] , 'description' : ( 'The unit sy...
def has_unclosed_brackets ( text ) : """Starting at the end of the string . If we find an opening bracket for which we didn ' t had a closing one yet , return True ."""
stack = [ ] # Ignore braces inside strings text = re . sub ( r'''('[^']*'|"[^"]*")''' , '' , text ) # XXX : handle escaped quotes . ! for c in reversed ( text ) : if c in '])}' : stack . append ( c ) elif c in '[({' : if stack : if ( ( c == '[' and stack [ - 1 ] == ']' ) or ( c == '{...
def filter ( self , s , method = 'chebyshev' , order = 30 ) : r"""Filter signals ( analysis or synthesis ) . A signal is defined as a rank - 3 tensor of shape ` ` ( N _ NODES , N _ SIGNALS , N _ FEATURES ) ` ` , where ` ` N _ NODES ` ` is the number of nodes in the graph , ` ` N _ SIGNALS ` ` is the number of...
s = self . G . _check_signal ( s ) # TODO : not in self . Nin ( Nf = Nin x Nout ) . if s . ndim == 1 or s . shape [ - 1 ] not in [ 1 , self . Nf ] : if s . ndim == 3 : raise ValueError ( 'Third dimension (#features) should be ' 'either 1 or the number of filters Nf = {}, ' 'got {}.' . format ( self . Nf , s...
def from_pure ( cls , z ) : """Creates a pure composition . Args : z ( int ) : atomic number"""
return cls ( cls . _key , { z : 1.0 } , { z : 1.0 } , pyxray . element_symbol ( z ) )
def open ( self ) : """Open the connection with the device ."""
try : self . device . open ( ) except ConnectTimeoutError as cte : raise ConnectionException ( cte . msg ) self . device . timeout = self . timeout self . device . _conn . _session . transport . set_keepalive ( self . keepalive ) if hasattr ( self . device , "cu" ) : # make sure to remove the cu attr from previ...
def apply_obfuscation ( source ) : """Returns ' source ' all obfuscated ."""
global keyword_args global imported_modules tokens = token_utils . listified_tokenizer ( source ) keyword_args = analyze . enumerate_keyword_args ( tokens ) imported_modules = analyze . enumerate_imports ( tokens ) variables = find_obfuscatables ( tokens , obfuscatable_variable ) classes = find_obfuscatables ( tokens ,...
def main ( ) : """This is an example of project documentation using AIKIF It documents the project itself , including requirements , design , test , goals ,"""
print ( 'Initialising AIKIF Project...' ) name = 'AIKIF' type = 'Software' desc = """ Artificial Intelligence Knowledge Information Framework - Project Overview This document was autogenerated via aikif/examples/AIKIF_project.py """ desc += '\n Last updated ' + mod_dt . TodayAsString ( ) fldr = ...
def titletable ( html_doc , tofloat = True ) : """return a list of [ ( title , table ) , . . . . . ] title = previous item with a < b > tag table = rows - > [ [ cell1 , cell2 , . . ] , [ cell1 , cell2 , . . ] , . . ]"""
soup = BeautifulSoup ( html_doc , "html.parser" ) btables = soup . find_all ( [ 'b' , 'table' ] ) # find all the < b > and < table > titletables = [ ] for i , item in enumerate ( btables ) : if item . name == 'table' : for j in range ( i + 1 ) : if btables [ i - j ] . name == 'b' : # step back t...
def parse_free_space_response ( content , hostname ) : """Parses of response content XML from WebDAV server and extract an amount of free space . : param content : the XML content of HTTP response from WebDAV server for getting free space . : param hostname : the server hostname . : return : an amount of free...
try : tree = etree . fromstring ( content ) node = tree . find ( './/{DAV:}quota-available-bytes' ) if node is not None : return int ( node . text ) else : raise MethodNotSupported ( name = 'free' , server = hostname ) except TypeError : raise MethodNotSupported ( name = 'free' , ser...
def add_commit ( self , commit ) : """Adds the commit to the commits array if it doesn ' t already exist , and returns the commit ' s index in the array ."""
sha1 = commit . hex if sha1 in self . _commits : return self . _commits [ sha1 ] title , separator , body = commit . message . partition ( "\n" ) commit = { 'explored' : False , 'sha1' : sha1 , 'name' : GitUtils . abbreviate_sha1 ( sha1 ) , 'describe' : GitUtils . describe ( sha1 ) , 'refs' : GitUtils . refs_to ( s...
def retrieve_remote_content ( id : str , guid : str = None , handle : str = None , entity_type : str = None , sender_key_fetcher : Callable [ [ str ] , str ] = None , ) : """Retrieve remote content and return an Entity object . Currently , due to no other protocols supported , always use the Diaspora protocol . ...
# TODO add support for AP protocol_name = "diaspora" if not guid : guid = id utils = importlib . import_module ( "federation.utils.%s" % protocol_name ) return utils . retrieve_and_parse_content ( guid = guid , handle = handle , entity_type = entity_type , sender_key_fetcher = sender_key_fetcher , )
def water_self_diffusion_coefficient ( T = None , units = None , warn = True , err_mult = None ) : """Temperature - dependent self - diffusion coefficient of water . Parameters T : float Temperature ( default : in Kelvin ) units : object ( optional ) object with attributes : Kelvin , meter , kilogram wa...
if units is None : K = 1 m = 1 s = 1 else : K = units . Kelvin m = units . meter s = units . second if T is None : T = 298.15 * K _D0 = D0 * m ** 2 * s ** - 1 _TS = TS * K if err_mult is not None : _dD0 = dD0 * m ** 2 * s ** - 1 _dTS = dTS * K _D0 += err_mult [ 0 ] * _dD0 _TS...
def handle ( self , * args , ** options ) : """Generates image thumbnails NOTE : To keep memory consumption stable avoid iteration over the Image queryset"""
pks = Image . objects . all ( ) . values_list ( 'id' , flat = True ) total = len ( pks ) for idx , pk in enumerate ( pks ) : image = None try : image = Image . objects . get ( pk = pk ) self . stdout . write ( u'Processing image {0} / {1} {2}' . format ( idx + 1 , total , image ) ) self ...
def download_ftp_url ( source_url , target_uri , buffer_size = 8192 ) : """Uses urllib . thread safe ?"""
ensure_file_directory ( target_uri ) with urllib . request . urlopen ( source_url ) as source_file : with open ( target_uri , 'wb' ) as target_file : shutil . copyfileobj ( source_file , target_file , buffer_size )
def is_assignment_allowed ( self ) : """Check if analyst assignment is allowed"""
if not self . is_manage_allowed ( ) : return False review_state = api . get_workflow_status_of ( self . context ) edit_states = [ "open" , "attachment_due" , "to_be_verified" ] return review_state in edit_states
def get_source_pars ( src ) : """Extract the parameters associated with a pyLikelihood Source object ."""
fnmap = src . getSrcFuncs ( ) keys = fnmap . keys ( ) if 'Position' in keys : ppars = get_function_pars ( src . getSrcFuncs ( ) [ str ( 'Position' ) ] ) elif 'SpatialDist' in keys : ppars = get_function_pars ( src . getSrcFuncs ( ) [ str ( 'SpatialDist' ) ] ) else : raise Exception ( 'Failed to extract spat...
def delete_collection_namespaced_lease ( self , namespace , ** kwargs ) : """delete collection of Lease This method makes a synchronous HTTP request by default . To make an asynchronous HTTP request , please pass async _ req = True > > > thread = api . delete _ collection _ namespaced _ lease ( namespace , as...
kwargs [ '_return_http_data_only' ] = True if kwargs . get ( 'async_req' ) : return self . delete_collection_namespaced_lease_with_http_info ( namespace , ** kwargs ) else : ( data ) = self . delete_collection_namespaced_lease_with_http_info ( namespace , ** kwargs ) return data
def close ( self ) : """Closes this : class : ` ` PCapStream ` ` by closing the underlying Python stream ."""
if self . _stream : values = ( self . _total . nbytes , self . _total . npackets , int ( math . ceil ( self . _total . nseconds ) ) , self . _filename ) if self . _dryrun : msg = 'Would write %d bytes, %d packets, %d seconds to %s.' else : msg = 'Wrote %d bytes, %d packets, %d seconds to %s....
def _remove_network ( network ) : '''Remove network , including all connected containers'''
ret = { 'name' : network [ 'Name' ] , 'changes' : { } , 'result' : False , 'comment' : '' } errors = [ ] for cid in network [ 'Containers' ] : try : cinfo = __salt__ [ 'docker.inspect_container' ] ( cid ) except CommandExecutionError : # Fall back to container ID cname = cid else : c...
def detect_suicidal_func ( func ) : """Detect if the function is suicidal Detect the public functions calling suicide / selfdestruct without protection Returns : ( bool ) : True if the function is suicidal"""
if func . is_constructor : return False if func . visibility != 'public' : return False calls = [ c . name for c in func . internal_calls ] if not ( 'suicide(address)' in calls or 'selfdestruct(address)' in calls ) : return False if func . is_protected ( ) : return False return True
def Nu_horizontal_cylinder ( Pr , Gr , Method = None , AvailableMethods = False ) : r'''This function handles choosing which horizontal cylinder free convection correlation is used . Generally this is used by a helper class , but can be used directly . Will automatically select the correlation to use if none is...
def list_methods ( ) : methods = [ ] for key , values in horizontal_cylinder_correlations . items ( ) : methods . append ( key ) if 'Morgan' in methods : methods . remove ( 'Morgan' ) methods . insert ( 0 , 'Morgan' ) return methods if AvailableMethods : return list_methods (...
def _gen_exclusion_paths ( ) : """Generate file paths to be excluded for namespace packages ( bytecode cache files ) ."""
# always exclude the package module itself yield '__init__.py' yield '__init__.pyc' yield '__init__.pyo' if not hasattr ( imp , 'get_tag' ) : return base = os . path . join ( '__pycache__' , '__init__.' + imp . get_tag ( ) ) yield base + '.pyc' yield base + '.pyo' yield base + '.opt-1.pyc' yield base + '.opt-2.pyc'
def generate_alchemy_graph ( alchemy_uri , prefixes = None , identifier = "NautilusSparql" ) : """Generate a graph and change the global graph to this one : param alchemy _ uri : A Uri for the graph : param prefixes : A dictionary of prefixes and namespaces to bind to the graph : param identifier : An identif...
registerplugins ( ) ident = URIRef ( identifier ) uri = Literal ( alchemy_uri ) store = plugin . get ( "SQLAlchemy" , Store ) ( identifier = ident ) graph = Graph ( store , identifier = ident ) graph . open ( uri , create = True ) for prefix , ns in ( prefixes or GRAPH_BINDINGS ) . items ( ) : if prefix == "" : ...
def GetArtifactPathDependencies ( rdf_artifact ) : """Return a set of knowledgebase path dependencies . Args : rdf _ artifact : RDF artifact object . Returns : A set of strings for the required kb objects e . g . [ " users . appdata " , " systemroot " ]"""
deps = set ( ) for source in rdf_artifact . sources : for arg , value in iteritems ( source . attributes ) : paths = [ ] if arg in [ "path" , "query" ] : paths . append ( value ) if arg == "key_value_pairs" : # This is a REGISTRY _ VALUE { key : blah , value : blah } dict . ...
def find_changed ( ) : """Find changes since the revision it is currently holding"""
session_token = request . headers [ 'session_token' ] repository = request . headers [ 'repository' ] current_user = have_authenticated_user ( request . environ [ 'REMOTE_ADDR' ] , repository , session_token ) if current_user is False : return fail ( user_auth_fail_msg ) repository_path = config [ 'repositories' ] ...
def intersect ( self , x1 , x2 = None ) : """Returns a list of all segments intersected by [ x1 , x2]"""
def condition ( x1 , x2 , tree ) : # print self . id , tree . x1 , tree . x2 , x1 , x2 if ( tree . x1 != None and tree . x2 != None ) and ( tree . x1 <= x1 and x1 < tree . x2 or tree . x1 <= x2 and x2 < tree . x2 ) : return True return False if x2 == None : xx1 , xx2 = x1 , x1 elif x1 > x2 : xx1...
def ends_with_path_separator ( self , file_path ) : """Return True if ` ` file _ path ` ` ends with a valid path separator ."""
if is_int_type ( file_path ) : return False file_path = make_string_path ( file_path ) return ( file_path and file_path not in ( self . path_separator , self . alternative_path_separator ) and ( file_path . endswith ( self . _path_separator ( file_path ) ) or self . alternative_path_separator is not None and file_p...
def round_to_multiple ( number , multiple ) : '''Rounding up to the nearest multiple of any positive integer Parameters number : int , float Input number . multiple : int Round up to multiple of multiple . Will be converted to int . Must not be equal zero . Returns ceil _ mod _ number : int Rounded ...
multiple = int ( multiple ) if multiple == 0 : multiple = 1 ceil_mod_number = number - number % ( - multiple ) return int ( ceil_mod_number )
def __reply ( self , reply , args , kwargs ) : """simulate the reply"""
binding = self . method . binding . input msg = binding . get_message ( self . method , args , kwargs ) log . debug ( 'inject (simulated) send message:\n%s' , msg ) binding = self . method . binding . output return self . succeeded ( binding , reply )
def box ( n_traces = 5 , n = 100 , mode = None ) : """Returns a DataFrame with the required format for a box plot Parameters : n _ traces : int Number of traces n : int Number of points for each trace mode : string Format for each item ' abc ' for alphabet columns ' stocks ' for random stock nam...
df = pd . DataFrame ( [ np . random . chisquare ( np . random . randint ( 2 , 10 ) , n_traces ) for _ in range ( n ) ] , columns = getName ( n_traces , mode = mode ) ) return df
def update_0100 ( self ) : """CC bits " HNZVC " : - 0100"""
self . N = 0 self . Z = 1 self . V = 0 self . C = 0
def can_vote_in_poll ( self , poll , user ) : """Given a poll , checks whether the user can answer to it ."""
# First we have to check if the poll is curently open if poll . duration : poll_dtend = poll . created + dt . timedelta ( days = poll . duration ) if poll_dtend < now ( ) : return False # Is this user allowed to vote in polls in the current forum ? can_vote = ( self . _perform_basic_permission_check ( p...
def to_JSON ( self ) : """Dumps object fields into a JSON formatted string : returns : the JSON string"""
return json . dumps ( { "reception_time" : self . _reception_time , "Location" : json . loads ( self . _location . to_JSON ( ) ) , "Weather" : json . loads ( self . _weather . to_JSON ( ) ) } )
def set_value ( self , value ) : """Sets the user value ( mode ) of the choice . Like for Symbol . set _ value ( ) , the visibility might truncate the value . Choices without the ' optional ' attribute ( is _ optional ) can never be in n mode , but 0 / " n " is still accepted since it ' s not a malformed valu...
if value == self . user_value : # We know the value must be valid if it was successfully set # previously self . _was_set = True return True if not ( ( self . orig_type is BOOL and value in ( 2 , 0 , "y" , "n" ) ) or ( self . orig_type is TRISTATE and value in ( 2 , 1 , 0 , "y" , "m" , "n" ) ) ) : # Display tri...
def wallet_contains ( self , wallet , account ) : """Check whether * * wallet * * contains * * account * * : param wallet : Wallet to check contains * * account * * : type wallet : str : param account : Account to check exists in * * wallet * * : type account : str : raises : : py : exc : ` nano . rpc . R...
wallet = self . _process_value ( wallet , 'wallet' ) account = self . _process_value ( account , 'account' ) payload = { "wallet" : wallet , "account" : account } resp = self . call ( 'wallet_contains' , payload ) return resp [ 'exists' ] == '1'
def add_initial ( initial_input ) : """Constructs a stateful object for handling vensim ' s ' Initial ' functionality Parameters initial _ input : basestring The expression which will be evaluated , and the first value of which returned Returns reference : basestring reference to the Initial object ` _ ...
stateful = { 'py_name' : utils . make_python_identifier ( '_initial_%s' % initial_input ) [ 0 ] , 'real_name' : 'Smooth of %s' % initial_input , 'doc' : 'Returns the value taken on during the initialization phase' , 'py_expr' : 'functions.Initial(lambda: %s)' % ( initial_input ) , 'unit' : 'None' , 'lims' : 'None' , 'e...
def is_local ( self ) : """Whether this is a local variable . In general , a variable is * local * if its containing scope is a statement ( e . g . a block ) , or a function , given that the variable is not one of the function ' s parameters ."""
return ( isinstance ( self . scope , CodeStatement ) or ( isinstance ( self . scope , CodeFunction ) and self not in self . scope . parameters ) )
def select_one_user ( users ) : """Display the users returned by search api . : params users : API [ ' result ' ] [ ' userprofiles ' ] : return : a User object ."""
if len ( users ) == 1 : select_i = 0 else : table = PrettyTable ( [ 'Sequence' , 'Name' ] ) for i , user in enumerate ( users , 1 ) : table . add_row ( [ i , user [ 'nickname' ] ] ) click . echo ( table ) select_i = click . prompt ( 'Select one user' , type = int , default = 1 ) while se...
def read_response ( self ) : """Read the response from a previously sent command"""
try : response = self . _parser . read_response ( ) except : self . disconnect ( ) raise if isinstance ( response , ResponseError ) : raise response # print ( response ) return response
def search_unique_identities ( db , term , source = None ) : """Look for unique identities . This function returns those unique identities which match with the given ' term ' . The term will be compated with name , email , username and source values of each identity . When ` source ` is given , this search ...
uidentities = [ ] pattern = '%' + term + '%' if term else None with db . connect ( ) as session : query = session . query ( UniqueIdentity ) . join ( Identity ) . filter ( UniqueIdentity . uuid == Identity . uuid ) if source : query = query . filter ( Identity . source == source ) if pattern : ...
def new_post ( GITDIRECTORY = CONFIG [ 'output_to' ] , kind = KINDS [ 'writing' ] ) : # pragma : no coverage # noqa """This function should create a template for a new post with a title read from the user input . Most other fields should be defaults . TODO : update this function"""
title = input ( "Give the title of the post: " ) while ':' in title : title = input ( "Give the title of the post (':' not allowed): " ) author = CONFIG [ 'author' ] date = datetime . datetime . strftime ( datetime . datetime . now ( ) , '%Y-%m-%d' ) tags = input ( "Give the tags, separated by ', ':" ) published = ...
def fileopenbox ( msg = None , title = None , default = "*" , filetypes = None ) : """A dialog to get a file name . About the " default " argument The " default " argument specifies a filepath that ( normally ) contains one or more wildcards . fileopenbox will display only files that match the default filep...
if sys . platform == 'darwin' : _bring_to_front ( ) localRoot = Tk ( ) localRoot . withdraw ( ) initialbase , initialfile , initialdir , filetypes = fileboxSetup ( default , filetypes ) # if initialfile contains no wildcards ; we don ' t want an # initial file . It won ' t be used anyway . # Also : if initialbase i...
def _create_record ( self , rtype , name , content ) : """Create record . If it already exists , do nothing ."""
if not self . _list_records ( rtype , name , content ) : self . _update_records ( [ { } ] , { 'type' : rtype , 'hostname' : self . _relative_name ( name ) , 'destination' : content , 'priority' : self . _get_lexicon_option ( 'priority' ) , } ) LOGGER . debug ( 'create_record: %s' , True ) return True
def setHTML_from_file ( self , filename , args ) : """Définition d ' un texte pour le cord du message"""
# vérification d ' usage if not os . path . isfile ( filename ) : return False with open ( filename ) as fp : # Create a text / plain message self . mail_html = fp . read ( ) . format ( ** args ) # retour ok return True
def returnFees ( self ) : """Returns a dictionary of all fees that apply through the network Example output : . . code - block : : js { ' proposal _ create ' : { ' fee ' : 400000.0 } , ' asset _ publish _ feed ' : { ' fee ' : 1000.0 } , ' account _ create ' : { ' basic _ fee ' : 950000.0 , ' price _ per...
from bitsharesbase . operations import operations r = { } obj , base = self . blockchain . rpc . get_objects ( [ "2.0.0" , "1.3.0" ] ) fees = obj [ "parameters" ] [ "current_fees" ] [ "parameters" ] scale = float ( obj [ "parameters" ] [ "current_fees" ] [ "scale" ] ) for f in fees : op_name = "unknown %d" % f [ 0 ...
def listdir ( self ) : """HACK around not having a beaver _ config stanza TODO : Convert this to a glob"""
ls = os . listdir ( self . _folder ) return [ x for x in ls if os . path . splitext ( x ) [ 1 ] [ 1 : ] == "log" ]
def _post ( self , xml_query ) : '''POST the request .'''
req = urllib2 . Request ( url = 'http://www.rcsb.org/pdb/rest/search' , data = xml_query ) f = urllib2 . urlopen ( req ) return f . read ( ) . strip ( )
def show_delvol_on_destroy ( name , kwargs = None , call = None ) : '''Do not delete all / specified EBS volumes upon instance termination CLI Example : . . code - block : : bash salt - cloud - a show _ delvol _ on _ destroy mymachine'''
if call != 'action' : raise SaltCloudSystemExit ( 'The show_delvol_on_destroy action must be called ' 'with -a or --action.' ) if not kwargs : kwargs = { } instance_id = kwargs . get ( 'instance_id' , None ) device = kwargs . get ( 'device' , None ) volume_id = kwargs . get ( 'volume_id' , None ) if instance_id...
def slug ( self ) : """Generate a short ( 7 - character ) cuid as a bytestring . While this is a convenient shorthand , this is much less likely to be unique and should not be relied on . Prefer full - size cuids where possible ."""
identifier = "" # use a truncated timestamp millis = int ( time . time ( ) * 1000 ) millis_string = _to_base36 ( millis ) identifier += millis_string [ - 2 : ] # use a truncated counter count = _pad ( _to_base36 ( self . counter ) , 1 ) identifier += count # use a truncated fingerprint identifier += self . fingerprint ...
def compile ( self , source , options = { } ) : """Compile stylus into css source : A string containing the stylus code options : A dictionary of arguments to pass to the compiler Returns a string of css resulting from the compilation"""
options = dict ( options ) if "paths" in options : options [ "paths" ] += self . paths else : options [ "paths" ] = self . paths if "compress" not in options : options [ "compress" ] = self . compress return self . context . call ( "compiler" , source , options , self . plugins , self . imports )
def _on_song_changed ( self , song ) : """播放列表 current _ song 发生变化后的回调 判断变化后的歌曲是否有效的 , 有效则播放 , 否则将它标记为无效歌曲 。 如果变化后的歌曲是 None , 则停止播放 。"""
logger . debug ( 'Player received song changed signal' ) if song is not None : logger . info ( 'Try to play song: %s' % song ) if song . url : self . play ( song . url ) else : self . _playlist . mark_as_bad ( song ) self . play_next ( ) else : self . stop ( ) logger . info (...
def hoverLeaveEvent ( self , event ) : """Processes the hovering information for this node . : param event | < QHoverEvent >"""
if self . _hoverSpot : if self . _hoverSpot . hoverLeaveEvent ( event ) : self . update ( ) self . _hoverSpot = None self . _hovered = False super ( XNode , self ) . setToolTip ( self . _toolTip ) super ( XNode , self ) . hoverLeaveEvent ( event )
def plot_scatter_matrix ( self , freq = None , title = None , figsize = ( 10 , 10 ) , ** kwargs ) : """Wrapper around pandas ' scatter _ matrix . Args : * freq ( str ) : Data frequency used for display purposes . Refer to pandas docs for valid freq strings . * figsize ( ( x , y ) ) : figure size * title (...
if title is None : title = self . _get_default_plot_title ( freq , 'Return Scatter Matrix' ) plt . figure ( ) ser = self . _get_series ( freq ) . to_returns ( ) . dropna ( ) pd . scatter_matrix ( ser , figsize = figsize , ** kwargs ) return plt . suptitle ( title )
def post ( self , bucket = None , key = None , uploads = missing , upload_id = None ) : """Upload a new object or start / complete a multipart upload . : param bucket : The bucket ( instance or id ) to get the object from . ( Default : ` ` None ` ` ) : param key : The file key . ( Default : ` ` None ` ` ) :...
if uploads is not missing : return self . multipart_init ( bucket , key ) elif upload_id is not None : return self . multipart_complete ( bucket , key , upload_id ) abort ( 403 )
def get_resource_bin_session ( self , proxy ) : """Gets the session for retrieving resource to bin mappings . arg : proxy ( osid . proxy . Proxy ) : a proxy return : ( osid . resource . ResourceBinSession ) - a ` ` ResourceBinSession ` ` raise : NullArgument - ` ` proxy ` ` is ` ` null ` ` raise : Operati...
if not self . supports_resource_bin ( ) : raise errors . Unimplemented ( ) # pylint : disable = no - member return sessions . ResourceBinSession ( proxy = proxy , runtime = self . _runtime )
def set_default_interface ( etree ) : """Sets the default interface that PyAMF will use to deal with XML entities ( both objects and blobs ) ."""
global types , ET , modules t = _get_etree_type ( etree ) _types = set ( types or [ ] ) _types . update ( [ t ] ) types = tuple ( _types ) modules [ t ] = etree old , ET = ET , etree return old
def remove ( release ) : '''Remove a specific version of the kernel . release The release number of an installed kernel . This must be the entire release number as returned by : py : func : ` ~ salt . modules . kernelpkg _ linux _ yum . list _ installed ` , not the package name . CLI Example : . . code ...
if release not in list_installed ( ) : raise CommandExecutionError ( 'Kernel release \'{0}\' is not installed' . format ( release ) ) if release == active ( ) : raise CommandExecutionError ( 'Active kernel cannot be removed' ) target = '{0}-{1}' . format ( _package_name ( ) , release ) log . info ( 'Removing ke...
def tdecode ( pkt , * args ) : """Run tshark to decode and display the packet . If no args defined uses - V"""
if not args : args = [ "-V" ] fname = get_temp_file ( ) wrpcap ( fname , [ pkt ] ) subprocess . call ( [ "tshark" , "-r" , fname ] + list ( args ) )
def findBracketBackward ( self , block , column , bracket ) : """Search for a needle and return ( block , column ) Raise ValueError , if not found NOTE this method ignores comments"""
if bracket in ( '(' , ')' ) : opening = '(' closing = ')' elif bracket in ( '[' , ']' ) : opening = '[' closing = ']' elif bracket in ( '{' , '}' ) : opening = '{' closing = '}' else : raise AssertionError ( 'Invalid bracket "%s"' % bracket ) depth = 1 for foundBlock , foundColumn , char in ...
def _show_corners ( self , image , corners ) : """Show chessboard corners found in image ."""
temp = image cv2 . drawChessboardCorners ( temp , ( self . rows , self . columns ) , corners , True ) window_name = "Chessboard" cv2 . imshow ( window_name , temp ) if cv2 . waitKey ( 0 ) : cv2 . destroyWindow ( window_name )
def take ( self , indexer , axis = 1 , verify = True , convert = True ) : """Take items along any axis ."""
self . _consolidate_inplace ( ) indexer = ( np . arange ( indexer . start , indexer . stop , indexer . step , dtype = 'int64' ) if isinstance ( indexer , slice ) else np . asanyarray ( indexer , dtype = 'int64' ) ) n = self . shape [ axis ] if convert : indexer = maybe_convert_indices ( indexer , n ) if verify : ...
def back_slash_to_front_converter ( string ) : """Replacing all \ in the str to / : param string : single string to modify : type string : str"""
try : if not string or not isinstance ( string , str ) : return string return string . replace ( '\\' , '/' ) except Exception : return string
def read ( self , name , pwd = None ) : """Return file bytes ( as a string ) for name ."""
with self . open ( name , "r" , pwd ) as fp : return fp . read ( )
def _decode_sense_packet ( self , version , packet ) : """Decode a sense packet into the list of sensors ."""
data = self . _sense_packet_to_data ( packet ) offset = 4 i = 0 datalen = len ( data ) - offset - 6 temp_count = int ( datalen / 2 ) temp = [ ] for i in range ( temp_count ) : temp_index = i * 2 + offset temp . append ( self . _decode_temp ( data [ temp_index ] , data [ temp_index + 1 ] ) ) self . _debug ( PROP...
def parsetime ( s ) : """Internal function to parse the time parses time in HH : MM : SS . mmm format . Returns : a four - tuple ` ` ( hours , minutes , seconds , milliseconds ) ` `"""
try : fields = s . split ( '.' ) subfields = fields [ 0 ] . split ( ':' ) H = int ( subfields [ 0 ] ) M = int ( subfields [ 1 ] ) S = int ( subfields [ 2 ] ) if len ( subfields ) > 3 : m = int ( subfields [ 3 ] ) else : m = 0 if len ( fields ) > 1 : m = int ( fiel...
def _notify ( self , func , * args , ** kw ) : """Internal helper . Calls the IStreamListener function ' func ' with the given args , guarding around errors ."""
for x in self . listeners : try : getattr ( x , func ) ( * args , ** kw ) except Exception : log . err ( )
def version_variants ( version ) : """Given an igraph version number , returns a list of possible version number variants to try when looking for a suitable nightly build of the C core to download from igraph . org ."""
result = [ version ] # Add trailing " . 0 " as needed to ensure that we have at least # major . minor . patch parts = version . split ( "." ) while len ( parts ) < 3 : parts . append ( "0" ) result . append ( "." . join ( parts ) ) return result
def retry_erroneous ( self , name , properties_update = None ) : # type : ( str , dict ) - > int """Removes the ERRONEOUS state of the given component , and retries a validation : param name : Name of the component to retry : param properties _ update : A dictionary to update the initial properties of the c...
with self . __instances_lock : try : stored_instance = self . __instances [ name ] except KeyError : raise ValueError ( "Unknown component instance '{0}'" . format ( name ) ) else : return stored_instance . retry_erroneous ( properties_update )
def super_lm_base ( ) : """Set of hyperparameters ."""
hparams = common_hparams . basic_params1 ( ) hparams . hidden_size = 512 hparams . moe_hidden_sizes = "512" hparams . batch_size = 16384 hparams . max_length = 0 # All hyperparameters ending in " dropout " are automatically set to 0.0 # when not in training mode . hparams . layer_prepostprocess_dropout = 0.0 hparams . ...
def fetch_objects ( self , oids ) : '''This methods is used to fetch models from a list of identifiers . Default implementation performs a bulk query on identifiers . Override this method to customize the objects retrieval .'''
objects = self . model . objects . in_bulk ( oids ) if len ( objects . keys ( ) ) != len ( oids ) : non_existants = set ( oids ) - set ( objects . keys ( ) ) msg = _ ( 'Unknown identifiers: {identifiers}' ) . format ( identifiers = ', ' . join ( str ( ne ) for ne in non_existants ) ) raise validators . Vali...