signature stringlengths 29 44.1k | implementation stringlengths 0 85.2k |
|---|---|
def buy_limit_order ( self , amount , price , base = "btc" , quote = "usd" , limit_price = None ) :
"""Order to buy amount of bitcoins for specified price .""" | data = { 'amount' : amount , 'price' : price }
if limit_price is not None :
data [ 'limit_price' ] = limit_price
url = self . _construct_url ( "buy/" , base , quote )
return self . _post ( url , data = data , return_json = True , version = 2 ) |
def _as_parameter_ ( self ) :
"""Compatibility with ctypes .
Allows passing transparently a Point object to an API call .""" | return RECT ( self . left , self . top , self . right , self . bottom ) |
def on_failure ( self , exc , task_id , args , kwargs , einfo ) :
"""Update query status and send email notification to a user""" | super ( ) . on_failure ( exc , task_id , args , kwargs , einfo )
if isinstance ( exc , OperationRunDoesNotExist ) :
return
self . _operation_run . on_failure ( ) |
def add_or_update ( user_id , app_id , value ) :
'''Editing evaluation .''' | rec = MEvaluation . get_by_signature ( user_id , app_id )
if rec :
entry = TabEvaluation . update ( value = value , ) . where ( TabEvaluation . uid == rec . uid )
entry . execute ( )
else :
TabEvaluation . create ( uid = tools . get_uuid ( ) , user_id = user_id , post_id = app_id , value = value , ) |
def link ( self , x , y , w , h , link ) :
"Put a link on the page" | if not self . page in self . page_links :
self . page_links [ self . page ] = [ ]
self . page_links [ self . page ] += [ ( x * self . k , self . h_pt - y * self . k , w * self . k , h * self . k , link ) , ] |
def get_bottleneck_path ( image_lists , label_name , index , bottleneck_dir , category , module_name ) :
"""Returns a path to a bottleneck file for a label at the given index .
Args :
image _ lists : OrderedDict of training images for each label .
label _ name : Label string we want to get an image for .
in... | module_name = ( module_name . replace ( '://' , '~' ) # URL scheme .
. replace ( '/' , '~' ) # URL and Unix paths .
. replace ( ':' , '~' ) . replace ( '\\' , '~' ) )
# Windows paths .
return get_image_path ( image_lists , label_name , index , bottleneck_dir , category ) + '_' + module_name + '.txt' |
def get_urls ( self , cache = True ) :
"""Get the urls for an artist
Args :
Kwargs :
cache ( bool ) : A boolean indicating whether or not the cached value should be used ( if available ) . Defaults to True .
Results :
A url document dict
Example :
> > > a = artist . Artist ( ' the unicorns ' )
> > >... | if not ( cache and ( 'urls' in self . cache ) ) :
response = self . get_attribute ( 'urls' )
self . cache [ 'urls' ] = response [ 'urls' ]
return self . cache [ 'urls' ] |
def get_key_columns ( self , cursor , table_name ) :
"""Backends can override this to return a list of ( column _ name , referenced _ table _ name ,
referenced _ column _ name ) for all key columns in given table .""" | source_field_dict = self . _name_to_index ( cursor , table_name )
sql = """
select
COLUMN_NAME = fk_cols.COLUMN_NAME,
REFERENCED_TABLE_NAME = pk.TABLE_NAME,
REFERENCED_COLUMN_NAME = pk_cols.COLUMN_NAME
from INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS ref_const
join INFORMATION_SCHEMA.TABLE_CONSTRAINTS fk
... |
def theme_get ( ) :
"""Return the default theme
The default theme is the one set ( using : func : ` theme _ set ` ) by
the user . If none has been set , then : class : ` theme _ gray ` is
the default .""" | from . theme_gray import theme_gray
_theme = get_option ( 'current_theme' )
if isinstance ( _theme , type ) :
_theme = _theme ( )
return _theme or theme_gray ( ) |
def put_file ( up_token , key , file_path , params = None , mime_type = 'application/octet-stream' , check_crc = False , progress_handler = None , upload_progress_recorder = None , keep_last_modified = False ) :
"""上传文件到七牛
Args :
up _ token : 上传凭证
key : 上传文件名
file _ path : 上传文件的路径
params : 自定义变量 , 规格参考 ht... | ret = { }
size = os . stat ( file_path ) . st_size
# fname = os . path . basename ( file _ path )
with open ( file_path , 'rb' ) as input_stream :
file_name = os . path . basename ( file_path )
modify_time = int ( os . path . getmtime ( file_path ) )
if size > config . _BLOCK_SIZE * 2 :
ret , info =... |
def check_loop ( self , service ) :
"""While the reporter is not shutting down and the service being checked
is present in the reporter ' s configuration , this method will launch a
job to run all of the service ' s checks and then pause for the
configured interval .""" | logger . info ( "Starting check loop for service '%s'" , service . name )
def handle_checks_result ( f ) :
try :
came_up , went_down = f . result ( )
except Exception :
logger . exception ( "Error checking service '%s'" , service . name )
return
if not came_up and not went_down :
... |
def snapshot_pop ( self ) :
'''This command is the inverse of vagrant snapshot push : it will restore the pushed state .''' | NO_SNAPSHOTS_PUSHED = 'No pushed snapshot found!'
output = self . _run_vagrant_command ( [ 'snapshot' , 'pop' ] )
if NO_SNAPSHOTS_PUSHED in output :
raise RuntimeError ( NO_SNAPSHOTS_PUSHED ) |
def merge_with ( self , other ) :
"""Returns a ` TensorShape ` combining the information in ` self ` and ` other ` .
The dimensions in ` self ` and ` other ` are merged elementwise ,
according to the rules defined for ` Dimension . merge _ with ( ) ` .
Args :
other : Another ` TensorShape ` .
Returns :
... | other = as_shape ( other )
if self . _dims is None :
return other
else :
try :
self . assert_same_rank ( other )
new_dims = [ ]
for i , dim in enumerate ( self . _dims ) :
new_dims . append ( dim . merge_with ( other [ i ] ) )
return TensorShape ( new_dims )
excep... |
def _get_ll_pointer_type ( self , target_data , context = None ) :
"""Convert this type object to an LLVM type .""" | from . import Module , GlobalVariable
from . . binding import parse_assembly
if context is None :
m = Module ( )
else :
m = Module ( context = context )
foo = GlobalVariable ( m , self , name = "foo" )
with parse_assembly ( str ( m ) ) as llmod :
return llmod . get_global_variable ( foo . name ) . type |
def field_from_json ( self , key_and_type , json_value ) :
"""Convert a JSON - serializable representation back to a field .""" | assert ':' in key_and_type
key , type_code = key_and_type . split ( ':' , 1 )
from_json = self . field_function ( type_code , 'from_json' )
value = from_json ( json_value )
return key , value |
def get_field_keys ( self , pattern = None ) :
"""Builds a set of all field keys used in the pattern including nested fields .
: param pattern : The kmatch pattern to get field keys from or None to use self . pattern
: type pattern : list or None
: returns : A set object of all field keys used in the pattern ... | # Use own pattern or passed in argument for recursion
pattern = pattern or self . pattern
# Validate the pattern so we can make assumptions about the data
self . _validate ( pattern )
keys = set ( )
# Valid pattern length can only be 2 or 3
# With key filters , field key is second item just like 3 item patterns
if len ... |
def _check_remote_command ( self , destination , timeout_ms , success_msgs = None ) :
"""Open a stream to destination , check for remote errors .
Used for reboot , remount , and root services . If this method returns , the
command was successful , otherwise an appropriate error will have been
raised .
Args ... | timeout = timeouts . PolledTimeout . from_millis ( timeout_ms )
stream = self . _adb_connection . open_stream ( destination , timeout )
if not stream :
raise usb_exceptions . AdbStreamUnavailableError ( 'Service %s not supported' , destination )
try :
message = stream . read ( timeout_ms = timeout )
# Some ... |
def add_params_to_qs ( query , params ) :
"""Extend a query with a list of two - tuples .""" | if isinstance ( params , dict ) :
params = params . items ( )
queryparams = urlparse . parse_qsl ( query , keep_blank_values = True )
queryparams . extend ( params )
return urlencode ( queryparams ) |
def get_config_dir ( ) :
"""Return tmuxp configuration directory .
` ` TMUXP _ CONFIGDIR ` ` environmental variable has precedence if set . We also
evaluate XDG default directory from XDG _ CONFIG _ HOME environmental variable
if set or its default . Then the old default ~ / . tmuxp is returned for
compatib... | paths = [ ]
if 'TMUXP_CONFIGDIR' in os . environ :
paths . append ( os . environ [ 'TMUXP_CONFIGDIR' ] )
if 'XDG_CONFIG_HOME' in os . environ :
paths . append ( os . environ [ 'XDG_CONFIG_HOME' ] )
else :
paths . append ( '~/.config/tmuxp/' )
paths . append ( '~/.tmuxp' )
for path in paths :
path = os .... |
def copy_action_callback ( self , * event ) :
"""Callback method for copy action""" | if react_to_event ( self . view , self . tree_view , event ) and self . active_entry_widget is None :
sm_selection , sm_selected_model_list = self . get_state_machine_selection ( )
# only list specific elements are copied by widget
if sm_selection is not None :
sm_selection . set ( sm_selected_model... |
def send ( self , fail_silently = False ) :
"""Sends the sms message""" | if not self . to : # Don ' t bother creating the connection if there ' s nobody to send to
return 0
res = self . get_connection ( fail_silently ) . send_messages ( [ self ] )
sms_post_send . send ( sender = self , to = self . to , from_phone = self . from_phone , body = self . body )
return res |
def _find_local_signals ( cls , signals , namespace ) :
"""Add name info to every " local " ( present in the body of this class )
signal and add it to the mapping . Also complete signal
initialization as member of the class by injecting its name .""" | from . import Signal
signaller = cls . _external_signaller_and_handler
for aname , avalue in namespace . items ( ) :
if isinstance ( avalue , Signal ) :
if avalue . name :
aname = avalue . name
else :
avalue . name = aname
assert ( ( aname not in signals ) or ( aname ... |
def receive_request ( self , transaction ) :
"""Handles the Blocks option in a incoming request .
: type transaction : Transaction
: param transaction : the transaction that owns the request
: rtype : Transaction
: return : the edited transaction""" | if transaction . request . block2 is not None :
host , port = transaction . request . source
key_token = hash ( str ( host ) + str ( port ) + str ( transaction . request . token ) )
num , m , size = transaction . request . block2
if key_token in self . _block2_receive :
self . _block2_receive [ ... |
def auto_stratify ( scores , ** kwargs ) :
"""Generate Strata instance automatically
Parameters
scores : array - like , shape = ( n _ items , )
ordered array of scores which quantify the classifier confidence for
the items in the pool . High scores indicate a high confidence that
the true label is a " 1 "... | if 'stratification_method' in kwargs :
method = kwargs [ 'stratification_method' ]
else :
method = 'cum_sqrt_F'
if 'stratification_n_strata' in kwargs :
n_strata = kwargs [ 'stratification_n_strata' ]
else :
n_strata = 'auto'
if 'stratification_n_bins' in kwargs :
n_bins = kwargs [ 'stratification_n... |
def random_codebuch ( path ) :
"""Generate a month - long codebuch and save it to a file .""" | lines = [ ]
for i in range ( 31 ) :
line = str ( i + 1 ) + " "
# Pick rotors
all_rotors = [ 'I' , 'II' , 'III' , 'IV' , 'V' ]
rotors = [ random . choice ( all_rotors ) ]
while len ( rotors ) < 3 :
r = random . choice ( all_rotors )
if not r in rotors :
rotors . append ( r... |
def netflowv9_defragment ( plist , verb = 1 ) :
"""Process all NetflowV9/10 Packets to match IDs of the DataFlowsets
with the Headers
params :
- plist : the list of mixed NetflowV9/10 packets .
- verb : verbose print ( 0/1)""" | if not isinstance ( plist , ( PacketList , list ) ) :
plist = [ plist ]
# We need the whole packet to be dissected to access field def in
# NetflowFlowsetV9 or NetflowOptionsFlowsetV9/10
definitions = { }
definitions_opts = { }
ignored = set ( )
# Iterate through initial list
for pkt in plist :
_netflowv9_defra... |
async def _init_writer ( self ) :
"""Open the current base file with the ( original ) mode and encoding .
Return the resulting stream .""" | async with self . _initialization_lock :
if not self . initialized :
self . stream = await aiofiles . open ( file = self . absolute_file_path , mode = self . mode , encoding = self . encoding , loop = self . loop , ) |
def update_from_obj ( self , obj , copy = False ) :
"""Updates this configuration object from another .
See : meth : ` ConfigurationObject . update ` for details .
: param obj : Values to update the ConfigurationObject with .
: type obj : ConfigurationObject
: param copy : Copies lists and dictionaries .
... | obj . clean ( )
obj_config = obj . _config
all_props = self . __class__ . CONFIG_PROPERTIES
if copy :
for key , value in six . iteritems ( obj_config ) :
attr_config = all_props . get ( key )
if attr_config :
attr_type = attr_config . attr_type
if attr_type :
... |
def process_docopts ( test = None ) : # type : ( Optional [ Dict [ str , Any ] ] ) - > None
"""Just process the command line options and commands
: return :""" | if test :
arguments = test
else :
arguments = docopt ( __doc__ , version = "Jiggle Version {0}" . format ( __version__ ) )
logger . debug ( arguments )
file_opener = FileOpener ( )
central_module_finder = CentralModuleFinder ( file_opener )
if arguments [ "--module" ] :
central_module = arguments [ "--modul... |
def has_plugin_conf ( self , phase , name ) :
"""Check whether a plugin is configured .""" | try :
self . get_plugin_conf ( phase , name )
return True
except ( KeyError , IndexError ) :
return False |
def bin_hash160 ( s , hex_format = False ) :
"""s is in hex or binary format""" | if hex_format and is_hex ( s ) :
s = unhexlify ( s )
return hashlib . new ( 'ripemd160' , bin_sha256 ( s ) ) . digest ( ) |
def generate_code ( max_length , max_nest , ops ) :
"""Generates code samples .
Args :
max _ length : int . max literal length .
max _ nest : int . max nesting level .
ops : CodeOp . set of allowable operations .
Returns :
1 . ( str ) output value .
2 . ( str ) Code operation .""" | stack = [ ]
def fetch_one ( ) : # Always use an existing nested value for one of the operands .
if stack :
return stack . pop ( )
else : # Produce a numeral of max _ length - digits .
value = random . randint ( 10 ** ( max_length - 1 ) , 10 ** max_length - 1 )
code = str ( value )
... |
def not_explicitly_defined ( table , name , is_bytes = False ) :
"""Compose a table with the specified entry name of values not explicitly defined .""" | all_chars = ALL_ASCII if is_bytes else ALL_CHARS
s = set ( )
for k , v in table . items ( ) :
s . update ( v )
if name in table :
table [ name ] = list ( set ( table [ name ] ) | ( all_chars - s ) )
else :
table [ name ] = list ( all_chars - s ) |
def public ( self , * args , ** kwargs ) :
"""Only return public actions""" | kwargs [ 'public' ] = True
return self . filter ( * args , ** kwargs ) |
def _ensure_exists ( wrapped ) :
'''Decorator to ensure that the named container exists .''' | @ functools . wraps ( wrapped )
def check_exists ( name , * args , ** kwargs ) :
if not exists ( name ) :
raise CommandExecutionError ( 'Container \'{0}\' does not exist' . format ( name ) )
return wrapped ( name , * args , ** salt . utils . args . clean_kwargs ( ** kwargs ) )
return check_exists |
def make_key ( self , * parts ) :
"""Generate a namespaced key for the given path .""" | separator = getattr ( self . model_class , 'index_separator' , '.' )
parts = map ( decode , parts )
return '%s%s' % ( self . _base_key , separator . join ( map ( str , parts ) ) ) |
def extract_files ( self , resource ) :
""": param resource str | iterable files , a file or a directory
@ return : iterable""" | if hasattr ( resource , "__iter__" ) :
files = [ file for file in resource if self . can_be_extracted ( file ) ]
elif os . path . isfile ( resource ) :
files = [ resource ] if self . can_be_extracted ( resource ) else [ ]
else :
files = self . _extract_from_directory ( resource )
return files |
def fit ( self , X , y , model_filename = None ) :
"""Fit FastText according to X , y
Parameters :
X : list of text
each item is a text
y : list
each item is either a label ( in multi class problem ) or list of
labels ( in multi label problem )""" | train_file = "temp.train"
X = [ x . replace ( "\n" , " " ) for x in X ]
y = [ item [ 0 ] for item in y ]
y = [ _ . replace ( " " , "-" ) for _ in y ]
lines = [ "__label__{} , {}" . format ( j , i ) for i , j in zip ( X , y ) ]
content = "\n" . join ( lines )
write ( train_file , content )
if model_filename :
self .... |
async def send_job_result ( self , job_id : BackendJobId , result : str , text : str = "" , grade : float = None , problems : Dict [ str , SPResult ] = None , tests : Dict [ str , Any ] = None , custom : Dict [ str , Any ] = None , state : str = "" , archive : Optional [ bytes ] = None , stdout : Optional [ str ] = Non... | if job_id not in self . __running_job :
raise JobNotRunningException ( )
del self . __running_job [ job_id ]
if grade is None :
if result == "success" :
grade = 100.0
else :
grade = 0.0
if problems is None :
problems = { }
if custom is None :
custom = { }
if tests is None :
tests... |
def upload_file ( self , container , src_file_path , dst_name = None , put = True , content_type = None ) :
"""Upload a single file .""" | if not os . path . exists ( src_file_path ) :
raise RuntimeError ( 'file not found: ' + src_file_path )
if not dst_name :
dst_name = os . path . basename ( src_file_path )
if not content_type :
content_type = "application/octet.stream"
headers = dict ( self . _base_headers )
if content_type :
headers [ ... |
def min_freq ( self ) :
"""Returns the point where the minimum frequency is reached and its value""" | i = np . unravel_index ( np . argmin ( self . bands ) , self . bands . shape )
return self . qpoints [ i [ 1 ] ] , self . bands [ i ] |
def all_sample_keys ( self ) -> List [ str ] :
"""Return the unique keys of all samples in this : class : ` SampleSheet ` .
The keys are discovered first by the order of samples and second by
the order of keys upon those samples .""" | all_keys : List [ str ] = [ ]
for key in chain . from_iterable ( [ sample . keys ( ) for sample in self ] ) :
if key not in all_keys :
all_keys . append ( key )
return all_keys |
def Canonicalize ( node , output = None , ** kw ) :
'''Canonicalize ( node , output = None , * * kw ) - > UTF - 8
Canonicalize a DOM document / element node and all descendents .
Return the text ; if output is specified then output . write will
be called to output the text and None will be returned
Keyword ... | if output :
apply ( _implementation , ( node , output . write ) , kw )
else :
s = StringIO . StringIO ( )
apply ( _implementation , ( node , s . write ) , kw )
return s . getvalue ( ) |
def get_launch_config ( self , scaling_group ) :
"""Returns the launch configuration for the specified scaling group .""" | key_map = { "OS-DCF:diskConfig" : "disk_config" , "flavorRef" : "flavor" , "imageRef" : "image" , }
uri = "/%s/%s/launch" % ( self . uri_base , utils . get_id ( scaling_group ) )
resp , resp_body = self . api . method_get ( uri )
ret = { }
data = resp_body . get ( "launchConfiguration" )
ret [ "type" ] = data . get ( "... |
def inflate_plugin_dict ( plugin_dict , inflate_plugin ) :
"""Inflate a list of strings / dictionaries to a list of plugin instances .
Args :
plugin _ dict ( dict ) : a dict of dict .
inflate _ plugin ( method ) : the method to inflate the plugin .
Returns :
list : a plugin instances list .""" | plugins = [ ]
for identifier , definition in plugin_dict . items ( ) :
try :
plugins . append ( inflate_plugin ( identifier , definition ) )
except PluginNotFoundError as e :
logger . error ( 'Could not import plugin identified by %s. ' 'Exception: %s.' , identifier , e )
return plugins |
def main ( args = None ) :
"""Create a private key and a certificate and write them to a file .""" | if args is None :
args = sys . argv [ 1 : ]
o = Options ( )
try :
o . parseOptions ( args )
except usage . UsageError , e :
raise SystemExit ( str ( e ) )
else :
return createSSLCertificate ( o ) |
def getChild ( self , name , ns = None , default = None ) :
"""Get a child by ( optional ) name and / or ( optional ) namespace .
@ param name : The name of a child element ( may contain prefix ) .
@ type name : basestring
@ param ns : An optional namespace used to match the child .
@ type ns : ( I { prefix... | if self . __root is None :
return default
if ns is None :
prefix , name = splitPrefix ( name )
if prefix is None :
ns = None
else :
ns = self . __root . resolvePrefix ( prefix )
if self . __root . match ( name , ns ) :
return self . __root
else :
return default |
def textgetter ( path : str , * , default : T = NO_DEFAULT , strip : bool = False ) -> t . Callable [ [ Element ] , t . Union [ str , T ] ] :
"""shortcut for making an XML element text getter""" | find = compose ( str . strip if strip else identity , partial ( _raise_if_none , exc = LookupError ( path ) ) , methodcaller ( 'findtext' , path ) )
return ( find if default is NO_DEFAULT else lookup_defaults ( find , default ) ) |
def check_path ( file_path ) :
'''Checks if the directories for this path exist , and creates them in case .''' | directory = os . path . dirname ( file_path )
if directory != '' :
if not os . path . exists ( directory ) :
os . makedirs ( directory , 0o775 ) |
def _get_type ( self , obj ) :
"""Return the type of an object .""" | typever = obj [ 'Type' ]
typesplit = typever . split ( '.' )
return typesplit [ 0 ] + '.' + typesplit [ 1 ] |
def _load_from_configs ( self , filename ) :
"""Return content of file which located in configuration directory""" | config_filename = os . path . join ( self . _config_path , filename )
if os . path . exists ( config_filename ) :
try :
f = open ( config_filename , 'r' )
content = '' . join ( f . readlines ( ) )
f . close ( )
return content
except Exception as err :
raise err
else :
... |
def xgroup_create ( self , name , groupname , id = '$' , mkstream = False ) :
"""Create a new consumer group associated with a stream .
name : name of the stream .
groupname : name of the consumer group .
id : ID of the last item in the stream to consider already delivered .""" | pieces = [ 'XGROUP CREATE' , name , groupname , id ]
if mkstream :
pieces . append ( Token . get_token ( 'MKSTREAM' ) )
return self . execute_command ( * pieces ) |
def _isValidQuery ( self , query , mode = "phonefy" ) :
"""Method to verify if a given query is processable by the platform .
The system looks for the forbidden characters in self . Forbidden list .
Args :
query : The query to be launched .
mode : To be chosen amongst mailfy , phonefy , usufy , searchfy .
... | try : # Suport for version 2 of wrappers
validator = self . modes [ mode ] . get ( "query_validator" )
if validator :
try :
compiledRegexp = re . compile ( "^{expr}$" . format ( expr = validator ) )
return compiledRegexp . match ( query )
except AttributeError as e :
... |
def context ( src ) :
"""Used to add the source _ id to the error message . To be used as
with context ( src ) :
operation _ with ( src )
Typically the operation is filtering a source , that can fail for
tricky geometries .""" | try :
yield
except Exception :
etype , err , tb = sys . exc_info ( )
msg = 'An error occurred with source id=%s. Error: %s'
msg %= ( src . source_id , err )
raise_ ( etype , msg , tb ) |
def get_process ( self , dwProcessId ) :
"""@ type dwProcessId : int
@ param dwProcessId : Global ID of the process to look for .
@ rtype : L { Process }
@ return : Process object with the given global ID .""" | self . __initialize_snapshot ( )
if dwProcessId not in self . __processDict :
msg = "Unknown process ID %d" % dwProcessId
raise KeyError ( msg )
return self . __processDict [ dwProcessId ] |
def copy ( self ) :
"""Returns a copy of the dynamic bayesian network .
Returns
DynamicBayesianNetwork : copy of the dynamic bayesian network
Examples
> > > from pgmpy . models import DynamicBayesianNetwork as DBN
> > > from pgmpy . factors . discrete import TabularCPD
> > > dbn = DBN ( )
> > > dbn . ... | dbn = DynamicBayesianNetwork ( )
dbn . add_nodes_from ( self . _nodes ( ) )
dbn . add_edges_from ( self . edges ( ) )
cpd_copy = [ cpd . copy ( ) for cpd in self . get_cpds ( ) ]
dbn . add_cpds ( * cpd_copy )
return dbn |
def detectEquilibration ( A_t , fast = True , nskip = 1 ) :
"""Automatically detect equilibrated region of a dataset using a heuristic that maximizes number of effectively uncorrelated samples .
Parameters
A _ t : np . ndarray
timeseries
nskip : int , optional , default = 1
number of samples to sparsify d... | T = A_t . size
# Special case if timeseries is constant .
if A_t . std ( ) == 0.0 :
return ( 0 , 1 , 1 )
# Changed from Neff = N to Neff = 1 after issue # 122
g_t = np . ones ( [ T - 1 ] , np . float32 )
Neff_t = np . ones ( [ T - 1 ] , np . float32 )
for t in range ( 0 , T - 1 , nskip ) :
try :
g_t [ t... |
def do_membership ( args ) :
"""Write the membership output file""" | config , name , label , coord = args
filenames = make_filenames ( config , label )
srcfile = filenames [ 'srcfile' ]
memfile = filenames [ 'memfile' ]
logger . info ( "Writing %s..." % memfile )
from ugali . analysis . loglike import write_membership
write_membership ( memfile , config , srcfile , section = 'source' ) |
def expand_tweet_urls ( tweet ) :
"""Replace shortened URLs with long URLs in the twitter status , and add the " RT " flag .
Should be used before urlize _ tweet""" | if 'retweeted_status' in tweet :
text = 'RT @{user}: {text}' . format ( user = tweet [ 'retweeted_status' ] [ 'user' ] [ 'screen_name' ] , text = tweet [ 'retweeted_status' ] [ 'text' ] )
urls = tweet [ 'retweeted_status' ] [ 'entities' ] [ 'urls' ]
else :
text = tweet [ 'text' ]
urls = tweet [ 'entitie... |
def kdeplot ( df , projection = None , extent = None , figsize = ( 8 , 6 ) , ax = None , clip = None , ** kwargs ) :
"""Spatial kernel density estimate plot .
Parameters
df : GeoDataFrame
The data being plotted .
projection : geoplot . crs object instance , optional
A geographic projection . For more info... | import seaborn as sns
# Immediately fail if no seaborn .
# Initialize the figure .
fig = _init_figure ( ax , figsize )
# Necessary prior .
xs = np . array ( [ p . x for p in df . geometry ] )
ys = np . array ( [ p . y for p in df . geometry ] )
# Load the projection .
if projection :
projection = projection . load ... |
def movingSum ( requestContext , seriesList , windowSize ) :
"""Graphs the moving sum of a metric ( or metrics ) over a fixed number of
past points , or a time interval .
Takes one metric or a wildcard seriesList followed by a number N of
datapoints or a quoted string with a length of time like ' 1hour ' or '... | if not seriesList :
return [ ]
windowInterval = None
if isinstance ( windowSize , six . string_types ) :
delta = parseTimeOffset ( windowSize )
windowInterval = abs ( delta . seconds + ( delta . days * 86400 ) )
if windowInterval :
previewSeconds = windowInterval
else :
previewSeconds = max ( [ s . ... |
def verify_sig ( signed_request , secret , issuer = None , algorithms = None , expected_aud = None ) :
"""Verify the JWT signature .
Given a raw JWT , this verifies it was signed with
* secret * , decodes it , and returns the JSON dict .""" | if not issuer :
issuer = _get_issuer ( signed_request = signed_request )
signed_request = _to_bytes ( signed_request )
app_req = _get_json ( signed_request )
# Check signature .
try :
jwt . decode ( signed_request , secret , verify = True , algorithms = algorithms , audience = expected_aud )
except jwt . Expire... |
def create_cbz ( directory ) :
"""Creates or updates a CBZ from files in the given comic directory .""" | if not os . path . isdir ( directory ) :
print ( "ERROR: Directory" , directory , "not found." )
return
base = os . path . basename ( directory . rstrip ( os . path . sep ) )
zipname = '%s.cbz' % base
zipname = os . path . join ( directory , zipname )
d = os . path . join ( directory , 'inorder' )
if os . path ... |
def build_swagger_12_api_declaration ( resource_name , api_declaration ) :
""": param resource _ name : The ` path ` parameter from the resource listing for
this resource .
: type resource _ name : string
: param api _ declaration : JSON representing a Swagger 1.2 api declaration
: type api _ declaration : ... | # NOTE : This means our resource paths are currently constrained to be valid
# pyramid routes ! ( minus the leading / )
route_name = 'pyramid_swagger.swagger12.apidocs-{0}' . format ( resource_name )
return PyramidEndpoint ( path = '/{0}' . format ( resource_name ) , route_name = route_name , view = build_swagger_12_ap... |
def _format_params ( self , type_ , params ) :
"""Reformat some of the parameters for sapi .""" | if 'initial_state' in params : # NB : at this moment the error raised when initial _ state does not match lin / quad ( in
# active qubits ) is not very informative , but there is also no clean way to check here
# that they match because lin can be either a list or a dict . In the future it would be
# good to check .
... |
def one_item ( self , item , detach : bool = False , denorm : bool = False , cpu : bool = False ) :
"Get ` item ` into a batch . Optionally ` detach ` and ` denorm ` ." | ds = self . single_ds
with ds . set_item ( item ) :
return self . one_batch ( ds_type = DatasetType . Single , detach = detach , denorm = denorm , cpu = cpu ) |
def getOverlayKey ( self , ulOverlayHandle , pchValue , unBufferSize ) :
"""Fills the provided buffer with the string key of the overlay . Returns the size of buffer required to store the key , including
the terminating null character . k _ unVROverlayMaxKeyLength will be enough bytes to fit the string .""" | fn = self . function_table . getOverlayKey
pError = EVROverlayError ( )
result = fn ( ulOverlayHandle , pchValue , unBufferSize , byref ( pError ) )
return result , pError |
def insertUserStore ( siteStore , userStorePath ) :
"""Move the SubStore at the indicated location into the given site store ' s
directory and then hook it up to the site store ' s authentication database .
@ type siteStore : C { Store }
@ type userStorePath : C { FilePath }""" | # The following may , but does not need to be in a transaction , because it
# is merely an attempt to guess a reasonable filesystem name to use for
# this avatar . The user store being operated on is expected to be used
# exclusively by this process .
ls = siteStore . findUnique ( LoginSystem )
unattachedSubStore = Sto... |
def segmentlist_range ( start , stop , period ) :
"""Analogous to Python ' s range ( ) builtin , this generator yields a
sequence of continuous adjacent segments each of length " period "
with the first starting at " start " and the last ending not after
" stop " . Note that the segments generated do not form... | n = 1
b = start
while True :
a , b = b , start + n * period
if b > stop :
break
yield segments . segment ( a , b )
n += 1 |
def initialize_symmetric ( cls , noise_protocol : 'NoiseProtocol' ) -> 'SymmetricState' :
"""Instead of taking protocol _ name as an argument , we take full NoiseProtocol object , that way we have access to
protocol name and crypto functions
Comments below are mostly copied from specification .
: param noise ... | # Create SymmetricState
instance = cls ( )
instance . noise_protocol = noise_protocol
# If protocol _ name is less than or equal to HASHLEN bytes in length , sets h equal to protocol _ name with zero
# bytes appended to make HASHLEN bytes . Otherwise sets h = HASH ( protocol _ name ) .
if len ( noise_protocol . name ) ... |
def handle_startendtag ( self , tag , attrs ) :
"""Normalize the tag with trailing ' / ' character ( such as ` < img . . . / > ` ) .
The trailing ' / ' character has no effect on void elements , but on
foreign elements it marks the start tag as self - closing .
. . seealso : :
` HTML5 - Start tags
< http ... | is_foreign = tag not in _VOID_ELEMENTS
self . _append_tag ( tag , attrs , closing = is_foreign )
if tag in _BLOCK_ELEMENTS :
self . _enter_newline ( )
elif tag not in _HIDDEN_ELEMENTS :
self . _reset_newline_status ( ) |
def status ( ctx , opts , owner_repo_package ) :
"""Get the synchronisation status for a package .
- OWNER / REPO / PACKAGE : Specify the OWNER namespace ( i . e . user or org ) , the
REPO name where the package is stored , and the PACKAGE name ( slug ) of the
package itself . All separated by a slash .
Exa... | owner , repo , slug = owner_repo_package
click . echo ( "Getting status of %(package)s in %(owner)s/%(repo)s ... " % { "owner" : click . style ( owner , bold = True ) , "repo" : click . style ( repo , bold = True ) , "package" : click . style ( slug , bold = True ) , } , nl = False , )
context_msg = "Failed to get stat... |
def readBUTTONCONDACTIONSs ( self ) :
"""Read zero or more button - condition actions""" | out = [ ]
while 1 :
action = self . readBUTTONCONDACTION ( )
if action :
out . append ( action )
else :
break
return out |
def add_plugins ( self , page , placeholder ) :
"""Add a " TextPlugin " in all languages .""" | for language_code , lang_name in iter_languages ( self . languages ) :
for no in range ( 1 , self . dummy_text_count + 1 ) :
add_plugin_kwargs = self . get_add_plugin_kwargs ( page , no , placeholder , language_code , lang_name )
log . info ( 'add plugin to placeholder "%s" (pk:%i) in: %s - no: %i' ... |
def cli ( env , account_id ) :
"""Detail a CDN Account .""" | manager = SoftLayer . CDNManager ( env . client )
account = manager . get_account ( account_id )
table = formatting . KeyValueTable ( [ 'name' , 'value' ] )
table . align [ 'name' ] = 'r'
table . align [ 'value' ] = 'l'
table . add_row ( [ 'id' , account [ 'id' ] ] )
table . add_row ( [ 'account_name' , account [ 'cdnA... |
def write_image ( r , filename ) :
"""将流式数据存储在文件中
: param r : 响应
: param filename : 文件名
: return :""" | with open ( filename , 'wb' ) as fd :
for chunk in r . iter_content ( 1024 ) :
fd . write ( chunk ) |
def average ( self , axis ) :
"""Returns d - 1 dimensional histogram of ( estimated ) mean value of axis
NB this is very different from averaging over the axis ! ! !""" | axis = self . get_axis_number ( axis )
avg_hist = np . ma . average ( self . all_axis_bin_centers ( axis ) , weights = self . histogram , axis = axis )
if self . dimensions == 2 :
new_hist = Hist1d
else :
new_hist = Histdd
return new_hist . from_histogram ( histogram = avg_hist , bin_edges = itemgetter ( * self... |
def _url_to_epub ( self ) :
"""* generate the epub book from a URL *""" | self . log . debug ( 'starting the ``_url_to_epub`` method' )
from polyglot import htmlCleaner
cleaner = htmlCleaner ( log = self . log , settings = self . settings , url = self . urlOrPath , outputDirectory = self . outputDirectory , title = self . title , # SET TO FALSE TO USE WEBPAGE TITLE ,
style = False , # add si... |
def SetParserProp ( self , prop , value ) :
"""Change the parser processing behaviour by changing some of
its internal properties . Note that some properties can only
be changed before any read has been done .""" | ret = libxml2mod . xmlTextReaderSetParserProp ( self . _o , prop , value )
return ret |
def command_msg ( housecode , command ) :
"""Create an X10 message to send the house code and a command code .""" | house_byte = 0
if isinstance ( housecode , str ) :
house_byte = insteonplm . utils . housecode_to_byte ( housecode ) << 4
elif isinstance ( housecode , int ) and housecode < 16 :
house_byte = housecode << 4
else :
house_byte = housecode
return X10Received ( house_byte + command , 0x80 ) |
def CV ( self , days = 45 ) :
"""Coefficient of Variation .
計算 days 日內之變異數 , 預設 45 日""" | if len ( self . raw_data ) >= days :
data_avg = sum ( self . raw_data [ - days : ] ) / days
return self . SD / data_avg
else :
return 0 |
def to_CAG ( self ) :
"""Export to a Causal Analysis Graph ( CAG ) PyGraphviz AGraph object .
The CAG shows the influence relationships between the variables and
elides the function nodes .""" | G = nx . DiGraph ( )
for ( name , attrs ) in self . nodes ( data = True ) :
if attrs [ "type" ] == "variable" :
for pred_fn in self . predecessors ( name ) :
if not any ( fn_type in pred_fn for fn_type in ( "condition" , "decision" ) ) :
for pred_var in self . predecessors ( pred... |
def url_quote_part ( s , safechars = '/' , encoding = None ) :
"""Wrap urllib . quote ( ) to support unicode strings . A unicode string
is first converted to UTF - 8 . After that urllib . quote ( ) is called .""" | if isinstance ( s , unicode ) :
if encoding is None :
encoding = url_encoding
s = s . encode ( encoding , 'ignore' )
return urllib . quote ( s , safechars ) |
def cluster_application_attempts ( self , application_id ) :
"""With the application attempts API , you can obtain a collection of
resources that represent an application attempt .
: param str application _ id : The application id
: returns : API response object with JSON data
: rtype : : py : class : ` yar... | path = '/ws/v1/cluster/apps/{appid}/appattempts' . format ( appid = application_id )
return self . request ( path ) |
def fetch_all_mood_stations ( self , terr = KKBOXTerritory . TAIWAN ) :
'''Fetches all mood stations .
: param terr : the current territory .
: return : API response .
: rtype : dict
See ` https : / / docs - en . kkbox . codes / v1.1 / reference # moodstations ` .''' | url = 'https://api.kkbox.com/v1.1/mood-stations'
url += '?' + url_parse . urlencode ( { 'territory' : terr } )
return self . http . _post_data ( url , None , self . http . _headers_with_access_token ( ) ) |
def _edge_mapping ( G ) :
"""Assigns a variable for each edge in G .
( u , v ) and ( v , u ) map to the same variable .""" | edge_mapping = { edge : idx for idx , edge in enumerate ( G . edges ) }
edge_mapping . update ( { ( e1 , e0 ) : idx for ( e0 , e1 ) , idx in edge_mapping . items ( ) } )
return edge_mapping |
def sort ( in_file , out_file ) :
"""Sorts the given file .""" | filehandle = open ( in_file , 'r' )
lines = filehandle . readlines ( )
filehandle . close ( )
lines . sort ( )
filehandle = open ( out_file , 'w' )
for line in lines :
filehandle . write ( line )
filehandle . close ( ) |
def path_new_using_function ( w : int , h : int , func : Callable [ [ int , int , int , int , Any ] , float ] , userData : Any = 0 , dcost : float = 1.41 , ) -> tcod . path . AStar :
"""Return a new AStar using the given callable function .
Args :
w ( int ) : Clipping width .
h ( int ) : Clipping height .
f... | return tcod . path . AStar ( tcod . path . _EdgeCostFunc ( ( func , userData ) , ( w , h ) ) , dcost ) |
def avail_locations ( conn = None , call = None ) :
'''Return a dict of all available VM locations on the cloud provider with
relevant data''' | if call == 'action' :
raise SaltCloudSystemExit ( 'The avail_locations function must be called with ' '-f or --function, or with the --list-locations option' )
if not conn :
conn = get_conn ( )
# pylint : disable = E0602
locations = conn . list_locations ( )
ret = { }
for img in locations :
if isinstance ( ... |
def sse ( self , request ) :
"""SSE .""" | response = Response ( status = 200 )
response . content_type = 'text/event-stream'
response . text = ''
active_request_id = request . GET . get ( 'request_id' )
client_last_request_id = str ( request . headers . get ( 'Last-Event-Id' , 0 ) )
if self . history :
last_request_id = next ( reversed ( self . history ) )... |
def lookup_comments ( self , reverse = False ) :
"Implement as required by parent to lookup comments in file system ." | comments = [ ]
if self . thread_id is None :
self . thread_id = self . lookup_thread_id ( )
path = self . thread_id
with open ( self . thread_id , 'r' , newline = '' ) as fdesc :
reader = csv . reader ( fdesc )
header = reader . __next__ ( )
assert header == self . header
for num , line in enumerate... |
def vert_tab_pos ( self , positions ) :
'''Sets tab positions , up to a maximum of 32 positions . Also can clear tab positions .
Args :
positions - - Either a list of tab positions ( between 1 and 255 ) , or ' clear ' .
Returns :
None
Raises :
RuntimeError : Invalid position parameter .
RuntimeError :... | if positions == 'clear' :
self . send ( chr ( 27 ) + 'B' + chr ( 0 ) )
return
if positions . min < 1 or positions . max > 255 :
raise RuntimeError ( 'Invalid position parameter in function horzTabPos' )
sendstr = chr ( 27 ) + 'D'
if len ( positions ) <= 16 :
for position in positions :
sendstr +... |
def _update_state_from_response ( self , response_json ) :
""": param response _ json : the json obj returned from query
: return :""" | if response_json . get ( 'data' ) is not None :
cloud_clock = response_json . get ( 'data' )
else :
cloud_clock = response_json
self . parent . json_state = cloud_clock
cloud_clock_last_reading = cloud_clock . get ( 'last_reading' )
dials = cloud_clock . get ( 'dials' )
for dial in dials :
if dial . get ( '... |
def hash ( * cols ) :
"""Calculates the hash code of given columns , and returns the result as an int column .
> > > spark . createDataFrame ( [ ( ' ABC ' , ) ] , [ ' a ' ] ) . select ( hash ( ' a ' ) . alias ( ' hash ' ) ) . collect ( )
[ Row ( hash = - 757602832 ) ]""" | sc = SparkContext . _active_spark_context
jc = sc . _jvm . functions . hash ( _to_seq ( sc , cols , _to_java_column ) )
return Column ( jc ) |
def execute ( self , app_path , app_args , version , ** kwargs ) :
"""The execute functon of the hook will be called to start the required application
: param app _ path : ( str ) The path of the application executable
: param app _ args : ( str ) Any arguments the application may require
: param version : ( ... | multi_launchapp = self . parent
extra = multi_launchapp . get_setting ( "extra" )
use_rez = False
if self . check_rez ( ) :
from rez . resolved_context import ResolvedContext
from rez . config import config
# Define variables used to bootstrap tank from overwrite on first reference
# PYTHONPATH is used ... |
def get_filename ( self , t ) :
"""Return the appropriate filename for the given time
based on the defined period .""" | root , ext = os . path . splitext ( self . base_filename )
# remove seconds not significant to the period
if self . _period_seconds :
t -= t % self . _period_seconds
# convert it to a datetime object for formatting
dt = datetime . datetime . utcfromtimestamp ( t )
# append the datestring to the filename
# workaroun... |
def compile_query ( query : dict ) -> PyQuery :
"""Compiles a query
Syntax :
TBA""" | def _pair_to_dict ( pair ) :
if isinstance ( pair , dict ) :
return pair
return { pair [ 0 ] : pair [ 1 ] }
def _reduce ( pair ) :
try :
return { 'and' : ( _pair_to_dict ( pair [ 0 ] ) , _pair_to_dict ( pair [ 1 ] ) ) }
except ( KeyError , IndexError ) :
return _pair_to_dict ( pa... |
def initialize_object ( B , res , row ) :
"""Do a shallow initialization of an object
Arguments :
- row < dict > : dict of data like depth = 1 , i . e . many _ refs are only ids""" | B = get_backend ( )
field_groups = FieldGroups ( B . get_concrete ( res ) )
try :
obj = B . get_object ( B . get_concrete ( res ) , row [ 'id' ] )
except B . object_missing_error ( B . get_concrete ( res ) ) :
tbl = B . get_concrete ( res )
obj = tbl ( )
# Set attributes , refs
for fname , field in field_gr... |
def has_length ( value , minimum = None , maximum = None , ** kwargs ) :
"""Indicate whether ` ` value ` ` has a length greater than or equal to a
supplied ` ` minimum ` ` and / or less than or equal to ` ` maximum ` ` .
. . note : :
This function works on any ` ` value ` ` that supports the
: func : ` len ... | if minimum is None and maximum is None :
raise ValueError ( 'minimum and maximum cannot both be None' )
length = len ( value )
minimum = validators . numeric ( minimum , allow_empty = True )
maximum = validators . numeric ( maximum , allow_empty = True )
return is_between ( length , minimum = minimum , maximum = ma... |
def set_bandwidth ( self , bandwidth ) :
"""Sets bandwidth constraint .
: param bandwidth : bandwidth integer value ( in Kb / s )""" | yield from self . _hypervisor . send ( "nio set_bandwidth {name} {bandwidth}" . format ( name = self . _name , bandwidth = bandwidth ) )
self . _bandwidth = bandwidth |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.