query
stringlengths
5
1.23k
positive
stringlengths
53
15.2k
id_
int64
0
252k
task_name
stringlengths
87
242
negative
listlengths
20
553
Make a path more readable
def make_readable_path ( path ) : home = os . path . expanduser ( "~" ) if path . startswith ( home ) : path = "~" + path [ len ( home ) : ] return path
3,800
https://github.com/pylp/pylp/blob/7ebaa55fbaf61cb8175f211dd41ef2928c22d4d4/pylp/utils/paths.py#L13-L19
[ "def", "run", "(", "self", ")", ":", "logger", ".", "info", "(", "\"Initializing...\"", ")", "javabridge", ".", "call", "(", "self", ".", "jobject", ",", "\"initialize\"", ",", "\"()V\"", ")", "logger", ".", "info", "(", "\"Running...\"", ")", "javabridge", ".", "call", "(", "self", ".", "jobject", ",", "\"runExperiment\"", ",", "\"()V\"", ")", "logger", ".", "info", "(", "\"Finished...\"", ")", "javabridge", ".", "call", "(", "self", ".", "jobject", ",", "\"postProcess\"", ",", "\"()V\"", ")" ]
Yield all unions of start with other in shortlex order .
def shortlex ( start , other , excludestart = False ) : if not excludestart : yield start queue = collections . deque ( [ ( start , other ) ] ) while queue : current , other = queue . popleft ( ) while other : first , other = other [ 0 ] , other [ 1 : ] result = current | first yield result if other : queue . append ( ( result , other ) )
3,801
https://github.com/xflr6/bitsets/blob/ddcfe17e7c7a11f71f1c6764b2cecf7db05d9cdf/bitsets/combos.py#L10-L38
[ "def", "from_file", "(", "campaign_file", ",", "*", "*", "kwargs", ")", ":", "realpath", "=", "osp", ".", "realpath", "(", "campaign_file", ")", "if", "osp", ".", "isdir", "(", "realpath", ")", ":", "campaign_file", "=", "osp", ".", "join", "(", "campaign_file", ",", "YAML_CAMPAIGN_FILE", ")", "campaign", "=", "Configuration", ".", "from_file", "(", "campaign_file", ")", "return", "default_campaign", "(", "campaign", ",", "*", "*", "kwargs", ")" ]
Yield all intersections of end with other in reverse shortlex order .
def reverse_shortlex ( end , other , excludeend = False ) : if not excludeend : yield end queue = collections . deque ( [ ( end , other ) ] ) while queue : current , other = queue . popleft ( ) while other : first , other = other [ 0 ] , other [ 1 : ] result = current & first yield result if other : queue . append ( ( result , other ) )
3,802
https://github.com/xflr6/bitsets/blob/ddcfe17e7c7a11f71f1c6764b2cecf7db05d9cdf/bitsets/combos.py#L41-L70
[ "def", "_maximization", "(", "self", ",", "X", ")", ":", "# Iterate through clusters and recalculate mean and covariance", "for", "i", "in", "range", "(", "self", ".", "k", ")", ":", "resp", "=", "np", ".", "expand_dims", "(", "self", ".", "responsibility", "[", ":", ",", "i", "]", ",", "axis", "=", "1", ")", "mean", "=", "(", "resp", "*", "X", ")", ".", "sum", "(", "axis", "=", "0", ")", "/", "resp", ".", "sum", "(", ")", "covariance", "=", "(", "X", "-", "mean", ")", ".", "T", ".", "dot", "(", "(", "X", "-", "mean", ")", "*", "resp", ")", "/", "resp", ".", "sum", "(", ")", "self", ".", "parameters", "[", "i", "]", "[", "\"mean\"", "]", ",", "self", ".", "parameters", "[", "i", "]", "[", "\"cov\"", "]", "=", "mean", ",", "covariance", "# Update weights", "n_samples", "=", "np", ".", "shape", "(", "X", ")", "[", "0", "]", "self", ".", "priors", "=", "self", ".", "responsibility", ".", "sum", "(", "axis", "=", "0", ")", "/", "n_samples" ]
removes UTF chars from filename
def generate_filename ( self , instance , filename ) : from unidecode import unidecode return super ( ) . generate_filename ( instance , unidecode ( force_text ( filename ) ) )
3,803
https://github.com/druids/django-chamber/blob/eef4169923557e96877a664fa254e8c0814f3f23/chamber/models/fields.py#L69-L75
[ "def", "shapes_match", "(", "a", ",", "b", ")", ":", "if", "isinstance", "(", "a", ",", "(", "tuple", ",", "list", ")", ")", "and", "isinstance", "(", "b", ",", "(", "tuple", ",", "list", ")", ")", ":", "if", "len", "(", "a", ")", "!=", "len", "(", "b", ")", ":", "return", "False", "return", "all", "(", "[", "shapes_match", "(", "ia", ",", "ib", ")", "for", "ia", ",", "ib", "in", "zip", "(", "a", ",", "b", ")", "]", ")", "elif", "isinstance", "(", "a", ",", "dict", ")", "and", "isinstance", "(", "b", ",", "dict", ")", ":", "if", "len", "(", "a", ")", "!=", "len", "(", "b", ")", ":", "return", "False", "match", "=", "True", "for", "(", "ak", ",", "av", ")", ",", "(", "bk", ",", "bv", ")", "in", "zip", "(", "a", ".", "items", "(", ")", ",", "b", ".", "items", "(", ")", ")", ":", "match", "=", "match", "and", "all", "(", "[", "ak", "==", "bk", "and", "shapes_match", "(", "av", ",", "bv", ")", "]", ")", "return", "match", "else", ":", "shape_checker", "=", "shape_checkers", "[", "(", "type", "(", "a", ")", ",", "type", "(", "b", ")", ")", "]", "return", "shape_checker", "(", "a", ",", "b", ")" ]
Retrieve the next item in the queue .
def next ( self ) : if self . blocking >= 0 : # returns queue name and item, we just need item res = self . redis . blpop ( [ self . name ] , timeout = self . blocking ) if res : res = res [ 1 ] else : res = self . redis . lpop ( self . name ) value = self . deserialize ( res ) logger . debug ( 'Popped from "%s": %s' , self . name , repr ( value ) ) return value
3,804
https://github.com/PaulMcMillan/tasa/blob/fd548d97fd08e61c0e71296b08ffedb7d949e06a/tasa/store.py#L58-L73
[ "def", "native_libraries_verify", "(", ")", ":", "with", "open", "(", "BINARY_EXT_TEMPLATE", ",", "\"r\"", ")", "as", "file_obj", ":", "template", "=", "file_obj", ".", "read", "(", ")", "expected", "=", "template", ".", "format", "(", "revision", "=", "REVISION", ")", "with", "open", "(", "BINARY_EXT_FILE", ",", "\"r\"", ")", "as", "file_obj", ":", "contents", "=", "file_obj", ".", "read", "(", ")", "if", "contents", "!=", "expected", ":", "err_msg", "=", "\"\\n\"", "+", "get_diff", "(", "contents", ",", "expected", ",", "\"docs/python/binary-extension.rst.actual\"", ",", "\"docs/python/binary-extension.rst.expected\"", ",", ")", "raise", "ValueError", "(", "err_msg", ")", "else", ":", "print", "(", "\"docs/python/binary-extension.rst contents are as expected.\"", ")" ]
Send a value to this LIFO Queue .
def send ( self , * args ) : # this and the serializer could use some streamlining if None in args : raise TypeError ( 'None is not a valid queue item.' ) serialized_values = [ self . serialize ( value ) for value in args ] logger . debug ( 'Sending to "%s": %s' , self . name , serialized_values ) return self . redis . rpush ( self . name , * serialized_values )
3,805
https://github.com/PaulMcMillan/tasa/blob/fd548d97fd08e61c0e71296b08ffedb7d949e06a/tasa/store.py#L75-L85
[ "def", "_get_corenlp_version", "(", ")", ":", "corenlp_home", "=", "os", ".", "environ", ".", "get", "(", "\"CORENLP_HOME\"", ")", "if", "corenlp_home", ":", "for", "fn", "in", "os", ".", "listdir", "(", "corenlp_home", ")", ":", "m", "=", "re", ".", "match", "(", "\"stanford-corenlp-([\\d.]+)-models.jar\"", ",", "fn", ")", "if", "m", ":", "return", "m", ".", "group", "(", "1", ")" ]
Clear any existing values from this queue .
def clear ( self ) : logger . debug ( 'Clearing queue: "%s"' , self . name ) return self . redis . delete ( self . name )
3,806
https://github.com/PaulMcMillan/tasa/blob/fd548d97fd08e61c0e71296b08ffedb7d949e06a/tasa/store.py#L99-L102
[ "def", "find_signature", "(", "self", ",", "data_stream", ",", "msg_signature", ")", ":", "signature_match_index", "=", "None", "# The message that will be returned if it matches the signature", "msg_signature", "=", "msg_signature", ".", "split", "(", ")", "# Split into list", "# convert to bytearray in order to be able to compare with the messages list which contains bytearrays", "msg_signature", "=", "bytearray", "(", "int", "(", "x", ",", "16", ")", "for", "x", "in", "msg_signature", ")", "# loop through each message returned from Russound", "index_of_last_f7", "=", "None", "for", "i", "in", "range", "(", "len", "(", "data_stream", ")", ")", ":", "if", "data_stream", "[", "i", "]", "==", "247", ":", "index_of_last_f7", "=", "i", "# the below line checks for the matching signature, ensuring ALL bytes of the response have been received", "if", "(", "data_stream", "[", "i", ":", "i", "+", "len", "(", "msg_signature", ")", "]", "==", "msg_signature", ")", "and", "(", "len", "(", "data_stream", ")", "-", "i", ">=", "24", ")", ":", "signature_match_index", "=", "i", "break", "if", "signature_match_index", "is", "None", ":", "# Scrap bytes up to end of msg (to avoid searching these again)", "data_stream", "=", "data_stream", "[", "index_of_last_f7", ":", "len", "(", "data_stream", ")", "]", "matching_message", "=", "None", "else", ":", "matching_message", "=", "data_stream", "[", "signature_match_index", ":", "len", "(", "data_stream", ")", "]", "_LOGGER", ".", "debug", "(", "\"Message signature found at location: %s\"", ",", "signature_match_index", ")", "return", "matching_message", ",", "data_stream" ]
Converts a 32 bit unsigned number to signed .
def u2i ( uint32 ) : mask = ( 2 ** 32 ) - 1 if uint32 & ( 1 << 31 ) : v = uint32 | ~ mask else : v = uint32 & mask return v
3,807
https://github.com/PierreRust/apigpio/blob/2b969f40e06219b43a43498d8baf87f5935ceab2/apigpio/apigpio.py#L301-L319
[ "def", "_remove_player", "(", "self", ",", "player_id", ")", ":", "player", "=", "self", ".", "_mpris_players", ".", "get", "(", "player_id", ")", "if", "player", ":", "if", "player", ".", "get", "(", "\"subscription\"", ")", ":", "player", "[", "\"subscription\"", "]", ".", "disconnect", "(", ")", "del", "self", ".", "_mpris_players", "[", "player_id", "]" ]
Converts a 32 bit unsigned number to signed . If the number is negative it indicates an error . On error a pigpio exception will be raised if exceptions is True .
def _u2i ( uint32 ) : v = u2i ( uint32 ) if v < 0 : if exceptions : raise ApigpioError ( error_text ( v ) ) return v
3,808
https://github.com/PierreRust/apigpio/blob/2b969f40e06219b43a43498d8baf87f5935ceab2/apigpio/apigpio.py#L322-L332
[ "def", "keyspace", "(", "self", ",", "keyspace", ")", ":", "if", "FORMAT_SPEC", ".", "search", "(", "keyspace", ")", ":", "return", "KeyspacedProxy", "(", "self", ",", "keyspace", ")", "else", ":", "return", "KeyspacedProxy", "(", "self", ",", "self", ".", "_keyspaces", "[", "keyspace", "]", ")" ]
Adds a callback .
def append ( self , cb ) : self . callbacks . append ( cb . callb ) self . monitor = self . monitor | cb . callb . bit yield from self . pi . _pigpio_aio_command ( _PI_CMD_NB , self . handle , self . monitor )
3,809
https://github.com/PierreRust/apigpio/blob/2b969f40e06219b43a43498d8baf87f5935ceab2/apigpio/apigpio.py#L450-L456
[ "def", "save", "(", "self", ",", "create_multiple_renditions", "=", "True", ",", "preserve_source_rendition", "=", "True", ",", "encode_to", "=", "enums", ".", "EncodeToEnum", ".", "FLV", ")", ":", "if", "is_ftp_connection", "(", "self", ".", "connection", ")", "and", "len", "(", "self", ".", "assets", ")", ">", "0", ":", "self", ".", "connection", ".", "post", "(", "xml", "=", "self", ".", "to_xml", "(", ")", ",", "assets", "=", "self", ".", "assets", ")", "elif", "not", "self", ".", "id", "and", "self", ".", "_filename", ":", "self", ".", "id", "=", "self", ".", "connection", ".", "post", "(", "'create_video'", ",", "self", ".", "_filename", ",", "create_multiple_renditions", "=", "create_multiple_renditions", ",", "preserve_source_rendition", "=", "preserve_source_rendition", ",", "encode_to", "=", "encode_to", ",", "video", "=", "self", ".", "_to_dict", "(", ")", ")", "elif", "not", "self", ".", "id", "and", "len", "(", "self", ".", "renditions", ")", ">", "0", ":", "self", ".", "id", "=", "self", ".", "connection", ".", "post", "(", "'create_video'", ",", "video", "=", "self", ".", "_to_dict", "(", ")", ")", "elif", "self", ".", "id", ":", "data", "=", "self", ".", "connection", ".", "post", "(", "'update_video'", ",", "video", "=", "self", ".", "_to_dict", "(", ")", ")", "if", "data", ":", "self", ".", "_load", "(", "data", ")" ]
Removes a callback .
def remove ( self , cb ) : if cb in self . callbacks : self . callbacks . remove ( cb ) new_monitor = 0 for c in self . callbacks : new_monitor |= c . bit if new_monitor != self . monitor : self . monitor = new_monitor yield from self . pi . _pigpio_aio_command ( _PI_CMD_NB , self . handle , self . monitor )
3,810
https://github.com/PierreRust/apigpio/blob/2b969f40e06219b43a43498d8baf87f5935ceab2/apigpio/apigpio.py#L459-L469
[ "def", "save", "(", "self", ",", "create_multiple_renditions", "=", "True", ",", "preserve_source_rendition", "=", "True", ",", "encode_to", "=", "enums", ".", "EncodeToEnum", ".", "FLV", ")", ":", "if", "is_ftp_connection", "(", "self", ".", "connection", ")", "and", "len", "(", "self", ".", "assets", ")", ">", "0", ":", "self", ".", "connection", ".", "post", "(", "xml", "=", "self", ".", "to_xml", "(", ")", ",", "assets", "=", "self", ".", "assets", ")", "elif", "not", "self", ".", "id", "and", "self", ".", "_filename", ":", "self", ".", "id", "=", "self", ".", "connection", ".", "post", "(", "'create_video'", ",", "self", ".", "_filename", ",", "create_multiple_renditions", "=", "create_multiple_renditions", ",", "preserve_source_rendition", "=", "preserve_source_rendition", ",", "encode_to", "=", "encode_to", ",", "video", "=", "self", ".", "_to_dict", "(", ")", ")", "elif", "not", "self", ".", "id", "and", "len", "(", "self", ".", "renditions", ")", ">", "0", ":", "self", ".", "id", "=", "self", ".", "connection", ".", "post", "(", "'create_video'", ",", "video", "=", "self", ".", "_to_dict", "(", ")", ")", "elif", "self", ".", "id", ":", "data", "=", "self", ".", "connection", ".", "post", "(", "'update_video'", ",", "video", "=", "self", ".", "_to_dict", "(", ")", ")", "if", "data", ":", "self", ".", "_load", "(", "data", ")" ]
Runs a pigpio socket command .
def _pigpio_aio_command ( self , cmd , p1 , p2 , ) : with ( yield from self . _lock ) : data = struct . pack ( 'IIII' , cmd , p1 , p2 , 0 ) self . _loop . sock_sendall ( self . s , data ) response = yield from self . _loop . sock_recv ( self . s , 16 ) _ , res = struct . unpack ( '12sI' , response ) return res
3,811
https://github.com/PierreRust/apigpio/blob/2b969f40e06219b43a43498d8baf87f5935ceab2/apigpio/apigpio.py#L518-L532
[ "def", "reset", "(", "self", ",", "force", ")", ":", "client", "=", "self", ".", "create_client", "(", ")", "bucket", "=", "client", ".", "lookup_bucket", "(", "self", ".", "bucket_name", ")", "if", "bucket", "is", "not", "None", ":", "if", "not", "force", ":", "self", ".", "_log", ".", "error", "(", "\"Bucket already exists, aborting.\"", ")", "raise", "ExistingBackendError", "self", ".", "_log", ".", "info", "(", "\"Bucket already exists, deleting all content.\"", ")", "for", "blob", "in", "bucket", ".", "list_blobs", "(", ")", ":", "self", ".", "_log", ".", "info", "(", "\"Deleting %s ...\"", "%", "blob", ".", "name", ")", "bucket", ".", "delete_blob", "(", "blob", ".", "name", ")", "else", ":", "client", ".", "create_bucket", "(", "self", ".", "bucket_name", ")" ]
Runs an extended pigpio socket command .
def _pigpio_aio_command_ext ( self , cmd , p1 , p2 , p3 , extents , rl = True ) : with ( yield from self . _lock ) : ext = bytearray ( struct . pack ( 'IIII' , cmd , p1 , p2 , p3 ) ) for x in extents : if isinstance ( x , str ) : ext . extend ( _b ( x ) ) else : ext . extend ( x ) self . _loop . sock_sendall ( self . s , ext ) response = yield from self . _loop . sock_recv ( self . s , 16 ) _ , res = struct . unpack ( '12sI' , response ) return res
3,812
https://github.com/PierreRust/apigpio/blob/2b969f40e06219b43a43498d8baf87f5935ceab2/apigpio/apigpio.py#L535-L556
[ "def", "reset", "(", "self", ",", "force", ")", ":", "client", "=", "self", ".", "create_client", "(", ")", "bucket", "=", "client", ".", "lookup_bucket", "(", "self", ".", "bucket_name", ")", "if", "bucket", "is", "not", "None", ":", "if", "not", "force", ":", "self", ".", "_log", ".", "error", "(", "\"Bucket already exists, aborting.\"", ")", "raise", "ExistingBackendError", "self", ".", "_log", ".", "info", "(", "\"Bucket already exists, deleting all content.\"", ")", "for", "blob", "in", "bucket", ".", "list_blobs", "(", ")", ":", "self", ".", "_log", ".", "info", "(", "\"Deleting %s ...\"", "%", "blob", ".", "name", ")", "bucket", ".", "delete_blob", "(", "blob", ".", "name", ")", "else", ":", "client", ".", "create_bucket", "(", "self", ".", "bucket_name", ")" ]
Store a script for later execution .
def store_script ( self , script ) : if len ( script ) : res = yield from self . _pigpio_aio_command_ext ( _PI_CMD_PROC , 0 , 0 , len ( script ) , [ script ] ) return _u2i ( res ) else : return 0
3,813
https://github.com/PierreRust/apigpio/blob/2b969f40e06219b43a43498d8baf87f5935ceab2/apigpio/apigpio.py#L603-L622
[ "def", "render_category_averages", "(", "obj", ",", "normalize_to", "=", "100", ")", ":", "context", "=", "{", "'reviewed_item'", ":", "obj", "}", "ctype", "=", "ContentType", ".", "objects", ".", "get_for_model", "(", "obj", ")", "reviews", "=", "models", ".", "Review", ".", "objects", ".", "filter", "(", "content_type", "=", "ctype", ",", "object_id", "=", "obj", ".", "id", ")", "category_averages", "=", "{", "}", "for", "review", "in", "reviews", ":", "review_category_averages", "=", "review", ".", "get_category_averages", "(", "normalize_to", ")", "if", "review_category_averages", ":", "for", "category", ",", "average", "in", "review_category_averages", ".", "items", "(", ")", ":", "if", "category", "not", "in", "category_averages", ":", "category_averages", "[", "category", "]", "=", "review_category_averages", "[", "category", "]", "else", ":", "category_averages", "[", "category", "]", "+=", "review_category_averages", "[", "category", "]", "if", "reviews", "and", "category_averages", ":", "for", "category", ",", "average", "in", "category_averages", ".", "items", "(", ")", ":", "category_averages", "[", "category", "]", "=", "category_averages", "[", "category", "]", "/", "models", ".", "Rating", ".", "objects", ".", "filter", "(", "category", "=", "category", ",", "value__isnull", "=", "False", ",", "review__content_type", "=", "ctype", ",", "review__object_id", "=", "obj", ".", "id", ")", ".", "exclude", "(", "value", "=", "''", ")", ".", "count", "(", ")", "else", ":", "category_averages", "=", "{", "}", "for", "category", "in", "models", ".", "RatingCategory", ".", "objects", ".", "filter", "(", "counts_for_average", "=", "True", ")", ":", "category_averages", "[", "category", "]", "=", "0.0", "context", ".", "update", "(", "{", "'category_averages'", ":", "category_averages", "}", ")", "return", "context" ]
Runs a stored script .
def run_script ( self , script_id , params = None ) : # I p1 script id # I p2 0 # I p3 params * 4 (0-10 params) # (optional) extension # I[] params if params is not None : ext = bytearray ( ) for p in params : ext . extend ( struct . pack ( "I" , p ) ) nump = len ( params ) extents = [ ext ] else : nump = 0 extents = [ ] res = yield from self . _pigpio_aio_command_ext ( _PI_CMD_PROCR , script_id , 0 , nump * 4 , extents ) return _u2i ( res )
3,814
https://github.com/PierreRust/apigpio/blob/2b969f40e06219b43a43498d8baf87f5935ceab2/apigpio/apigpio.py#L625-L656
[ "def", "union", "(", "self", ",", "*", "dstreams", ")", ":", "if", "not", "dstreams", ":", "raise", "ValueError", "(", "\"should have at least one DStream to union\"", ")", "if", "len", "(", "dstreams", ")", "==", "1", ":", "return", "dstreams", "[", "0", "]", "if", "len", "(", "set", "(", "s", ".", "_jrdd_deserializer", "for", "s", "in", "dstreams", ")", ")", ">", "1", ":", "raise", "ValueError", "(", "\"All DStreams should have same serializer\"", ")", "if", "len", "(", "set", "(", "s", ".", "_slideDuration", "for", "s", "in", "dstreams", ")", ")", ">", "1", ":", "raise", "ValueError", "(", "\"All DStreams should have same slide duration\"", ")", "cls", "=", "SparkContext", ".", "_jvm", ".", "org", ".", "apache", ".", "spark", ".", "streaming", ".", "api", ".", "java", ".", "JavaDStream", "jdstreams", "=", "SparkContext", ".", "_gateway", ".", "new_array", "(", "cls", ",", "len", "(", "dstreams", ")", ")", "for", "i", "in", "range", "(", "0", ",", "len", "(", "dstreams", ")", ")", ":", "jdstreams", "[", "i", "]", "=", "dstreams", "[", "i", "]", ".", "_jdstream", "return", "DStream", "(", "self", ".", "_jssc", ".", "union", "(", "jdstreams", ")", ",", "self", ",", "dstreams", "[", "0", "]", ".", "_jrdd_deserializer", ")" ]
Returns the run status of a stored script as well as the current values of parameters 0 to 9 .
def script_status ( self , script_id ) : res = yield from self . _pigpio_aio_command ( _PI_CMD_PROCP , script_id , 0 ) bytes = u2i ( res ) if bytes > 0 : # Fixme : this sould be the same a _rxbuf # data = self._rxbuf(bytes) data = yield from self . _loop . sock_recv ( self . s , bytes ) while len ( data ) < bytes : b = yield from self . _loop . sock_recv ( self . s , bytes - len ( data ) ) data . extend ( b ) pars = struct . unpack ( '11i' , _str ( data ) ) status = pars [ 0 ] params = pars [ 1 : ] else : status = bytes params = ( ) return status , params
3,815
https://github.com/PierreRust/apigpio/blob/2b969f40e06219b43a43498d8baf87f5935ceab2/apigpio/apigpio.py#L659-L702
[ "def", "edge_to_bel", "(", "u", ":", "BaseEntity", ",", "v", ":", "BaseEntity", ",", "edge_data", ":", "EdgeData", ",", "sep", ":", "Optional", "[", "str", "]", "=", "None", ")", "->", "str", ":", "return", "edge_to_bel", "(", "u", ",", "v", ",", "data", "=", "edge_data", ",", "sep", "=", "sep", ")" ]
Stops a running script .
def stop_script ( self , script_id ) : res = yield from self . _pigpio_aio_command ( _PI_CMD_PROCS , script_id , 0 ) return _u2i ( res )
3,816
https://github.com/PierreRust/apigpio/blob/2b969f40e06219b43a43498d8baf87f5935ceab2/apigpio/apigpio.py#L705-L716
[ "def", "_merge_data", "(", "dat1", ",", "dat2", ")", ":", "cnt", "=", "0", "for", "key", "in", "dat1", ":", "flg1", "=", "len", "(", "dat1", "[", "key", "]", ")", ">", "0", "flg2", "=", "len", "(", "dat2", "[", "key", "]", ")", ">", "0", "if", "flg1", "!=", "flg2", ":", "cnt", "+=", "1", "if", "cnt", ":", "raise", "Warning", "(", "'Cannot merge catalogues with different'", "+", "' attributes'", ")", "return", "None", "else", ":", "for", "key", "in", "dat1", ":", "if", "isinstance", "(", "dat1", "[", "key", "]", ",", "np", ".", "ndarray", ")", ":", "dat1", "[", "key", "]", "=", "np", ".", "concatenate", "(", "(", "dat1", "[", "key", "]", ",", "dat2", "[", "key", "]", ")", ",", "axis", "=", "0", ")", "elif", "isinstance", "(", "dat1", "[", "key", "]", ",", "list", ")", ":", "dat1", "[", "key", "]", "+=", "dat2", "[", "key", "]", "else", ":", "raise", "ValueError", "(", "'Unknown type'", ")", "return", "dat1" ]
Deletes a stored script .
def delete_script ( self , script_id ) : res = yield from self . _pigpio_aio_command ( _PI_CMD_PROCD , script_id , 0 ) return _u2i ( res )
3,817
https://github.com/PierreRust/apigpio/blob/2b969f40e06219b43a43498d8baf87f5935ceab2/apigpio/apigpio.py#L719-L730
[ "def", "union", "(", "self", ",", "*", "dstreams", ")", ":", "if", "not", "dstreams", ":", "raise", "ValueError", "(", "\"should have at least one DStream to union\"", ")", "if", "len", "(", "dstreams", ")", "==", "1", ":", "return", "dstreams", "[", "0", "]", "if", "len", "(", "set", "(", "s", ".", "_jrdd_deserializer", "for", "s", "in", "dstreams", ")", ")", ">", "1", ":", "raise", "ValueError", "(", "\"All DStreams should have same serializer\"", ")", "if", "len", "(", "set", "(", "s", ".", "_slideDuration", "for", "s", "in", "dstreams", ")", ")", ">", "1", ":", "raise", "ValueError", "(", "\"All DStreams should have same slide duration\"", ")", "cls", "=", "SparkContext", ".", "_jvm", ".", "org", ".", "apache", ".", "spark", ".", "streaming", ".", "api", ".", "java", ".", "JavaDStream", "jdstreams", "=", "SparkContext", ".", "_gateway", ".", "new_array", "(", "cls", ",", "len", "(", "dstreams", ")", ")", "for", "i", "in", "range", "(", "0", ",", "len", "(", "dstreams", ")", ")", ":", "jdstreams", "[", "i", "]", "=", "dstreams", "[", "i", "]", ".", "_jdstream", "return", "DStream", "(", "self", ".", "_jssc", ".", "union", "(", "jdstreams", ")", ",", "self", ",", "dstreams", "[", "0", "]", ".", "_jrdd_deserializer", ")" ]
Clears gpios 0 - 31 if the corresponding bit in bits is set .
def clear_bank_1 ( self , bits ) : res = yield from self . _pigpio_aio_command ( _PI_CMD_BC1 , bits , 0 ) return _u2i ( res )
3,818
https://github.com/PierreRust/apigpio/blob/2b969f40e06219b43a43498d8baf87f5935ceab2/apigpio/apigpio.py#L749-L764
[ "def", "list_configs", "(", ")", ":", "try", ":", "configs", "=", "snapper", ".", "ListConfigs", "(", ")", "return", "dict", "(", "(", "config", "[", "0", "]", ",", "config", "[", "2", "]", ")", "for", "config", "in", "configs", ")", "except", "dbus", ".", "DBusException", "as", "exc", ":", "raise", "CommandExecutionError", "(", "'Error encountered while listing configurations: {0}'", ".", "format", "(", "_dbus_exception_to_reason", "(", "exc", ",", "locals", "(", ")", ")", ")", ")" ]
Sets gpios 0 - 31 if the corresponding bit in bits is set .
def set_bank_1 ( self , bits ) : res = yield from self . _pigpio_aio_command ( _PI_CMD_BS1 , bits , 0 ) return _u2i ( res )
3,819
https://github.com/PierreRust/apigpio/blob/2b969f40e06219b43a43498d8baf87f5935ceab2/apigpio/apigpio.py#L767-L782
[ "def", "list_configs", "(", ")", ":", "try", ":", "configs", "=", "snapper", ".", "ListConfigs", "(", ")", "return", "dict", "(", "(", "config", "[", "0", "]", ",", "config", "[", "2", "]", ")", "for", "config", "in", "configs", ")", "except", "dbus", ".", "DBusException", "as", "exc", ":", "raise", "CommandExecutionError", "(", "'Error encountered while listing configurations: {0}'", ".", "format", "(", "_dbus_exception_to_reason", "(", "exc", ",", "locals", "(", ")", ")", ")", ")" ]
Sets the gpio mode .
def set_mode ( self , gpio , mode ) : res = yield from self . _pigpio_aio_command ( _PI_CMD_MODES , gpio , mode ) return _u2i ( res )
3,820
https://github.com/PierreRust/apigpio/blob/2b969f40e06219b43a43498d8baf87f5935ceab2/apigpio/apigpio.py#L785-L799
[ "def", "DeleteNotifications", "(", "self", ",", "session_ids", ",", "start", "=", "None", ",", "end", "=", "None", ")", ":", "if", "not", "session_ids", ":", "return", "for", "session_id", "in", "session_ids", ":", "if", "not", "isinstance", "(", "session_id", ",", "rdfvalue", ".", "SessionID", ")", ":", "raise", "RuntimeError", "(", "\"Can only delete notifications for rdfvalue.SessionIDs.\"", ")", "if", "start", "is", "None", ":", "start", "=", "0", "else", ":", "start", "=", "int", "(", "start", ")", "if", "end", "is", "None", ":", "end", "=", "self", ".", "frozen_timestamp", "or", "rdfvalue", ".", "RDFDatetime", ".", "Now", "(", ")", "for", "queue", ",", "ids", "in", "iteritems", "(", "collection", ".", "Group", "(", "session_ids", ",", "lambda", "session_id", ":", "session_id", ".", "Queue", "(", ")", ")", ")", ":", "queue_shards", "=", "self", ".", "GetAllNotificationShards", "(", "queue", ")", "self", ".", "data_store", ".", "DeleteNotifications", "(", "queue_shards", ",", "ids", ",", "start", ",", "end", ")" ]
Returns the gpio mode .
def get_mode ( self , gpio ) : res = yield from self . _pigpio_aio_command ( _PI_CMD_MODEG , gpio , 0 ) return _u2i ( res )
3,821
https://github.com/PierreRust/apigpio/blob/2b969f40e06219b43a43498d8baf87f5935ceab2/apigpio/apigpio.py#L817-L842
[ "def", "DeleteNotifications", "(", "self", ",", "session_ids", ",", "start", "=", "None", ",", "end", "=", "None", ")", ":", "if", "not", "session_ids", ":", "return", "for", "session_id", "in", "session_ids", ":", "if", "not", "isinstance", "(", "session_id", ",", "rdfvalue", ".", "SessionID", ")", ":", "raise", "RuntimeError", "(", "\"Can only delete notifications for rdfvalue.SessionIDs.\"", ")", "if", "start", "is", "None", ":", "start", "=", "0", "else", ":", "start", "=", "int", "(", "start", ")", "if", "end", "is", "None", ":", "end", "=", "self", ".", "frozen_timestamp", "or", "rdfvalue", ".", "RDFDatetime", ".", "Now", "(", ")", "for", "queue", ",", "ids", "in", "iteritems", "(", "collection", ".", "Group", "(", "session_ids", ",", "lambda", "session_id", ":", "session_id", ".", "Queue", "(", ")", ")", ")", ":", "queue_shards", "=", "self", ".", "GetAllNotificationShards", "(", "queue", ")", "self", ".", "data_store", ".", "DeleteNotifications", "(", "queue_shards", ",", "ids", ",", "start", ",", "end", ")" ]
Sets the gpio level .
def write ( self , gpio , level ) : res = yield from self . _pigpio_aio_command ( _PI_CMD_WRITE , gpio , level ) return _u2i ( res )
3,822
https://github.com/PierreRust/apigpio/blob/2b969f40e06219b43a43498d8baf87f5935ceab2/apigpio/apigpio.py#L845-L868
[ "def", "get_success_url", "(", "self", ")", ":", "messages", ".", "success", "(", "self", ".", "request", ",", "\"Successfully deleted ({})\"", ".", "format", "(", "self", ".", "object", ")", ")", "if", "self", ".", "success_url", ":", "return", "reverse", "(", "self", ".", "success_url", ")", "if", "'app'", "in", "self", ".", "kwargs", "and", "'model'", "in", "self", ".", "kwargs", ":", "return", "reverse", "(", "'trionyx:model-list'", ",", "kwargs", "=", "{", "'app'", ":", "self", ".", "kwargs", ".", "get", "(", "'app'", ")", ",", "'model'", ":", "self", ".", "kwargs", ".", "get", "(", "'model'", ")", ",", "}", ")", "return", "'/'" ]
Converts a camelcase string to a list .
def camelcase2list ( s , lower = False ) : s = re . findall ( r'([A-Z][a-z0-9]+)' , s ) return [ w . lower ( ) for w in s ] if lower else s
3,823
https://github.com/kyzima-spb/flask-pony/blob/6cf28d70b7ebf415d58fa138fcc70b8dd57432c7/flask_pony/utils.py#L27-L30
[ "def", "update", "(", "self", ",", "data", ")", ":", "self", ".", "_md", ".", "update", "(", "data", ")", "bufpos", "=", "self", ".", "_nbytes", "&", "63", "self", ".", "_nbytes", "+=", "len", "(", "data", ")", "if", "self", ".", "_rarbug", "and", "len", "(", "data", ")", ">", "64", ":", "dpos", "=", "self", ".", "block_size", "-", "bufpos", "while", "dpos", "+", "self", ".", "block_size", "<=", "len", "(", "data", ")", ":", "self", ".", "_corrupt", "(", "data", ",", "dpos", ")", "dpos", "+=", "self", ".", "block_size" ]
Returns parameter names from the route .
def get_route_param_names ( endpoint ) : try : g = current_app . url_map . iter_rules ( endpoint ) return next ( g ) . arguments except KeyError : return { }
3,824
https://github.com/kyzima-spb/flask-pony/blob/6cf28d70b7ebf415d58fa138fcc70b8dd57432c7/flask_pony/utils.py#L33-L39
[ "def", "_intersection", "(", "self", ",", "keys", ",", "rows", ")", ":", "# If there are no other keys with start and end date (i.e. nothing to merge) return immediately.", "if", "not", "keys", ":", "return", "rows", "ret", "=", "list", "(", ")", "for", "row", "in", "rows", ":", "start_date", "=", "row", "[", "self", ".", "_key_start_date", "]", "end_date", "=", "row", "[", "self", ".", "_key_end_date", "]", "for", "key_start_date", ",", "key_end_date", "in", "keys", ":", "start_date", ",", "end_date", "=", "Type2JoinHelper", ".", "_intersect", "(", "start_date", ",", "end_date", ",", "row", "[", "key_start_date", "]", ",", "row", "[", "key_end_date", "]", ")", "if", "not", "start_date", ":", "break", "if", "key_start_date", "not", "in", "[", "self", ".", "_key_start_date", ",", "self", ".", "_key_end_date", "]", ":", "del", "row", "[", "key_start_date", "]", "if", "key_end_date", "not", "in", "[", "self", ".", "_key_start_date", ",", "self", ".", "_key_end_date", "]", ":", "del", "row", "[", "key_end_date", "]", "if", "start_date", ":", "row", "[", "self", ".", "_key_start_date", "]", "=", "start_date", "row", "[", "self", ".", "_key_end_date", "]", "=", "end_date", "ret", ".", "append", "(", "row", ")", "return", "ret" ]
Extract metadata from myself
def update_meta_info ( self ) : result = super ( BaseStructuredCalibration , self ) . update_meta_info ( ) result [ 'instrument' ] = self . instrument result [ 'uuid' ] = self . uuid result [ 'tags' ] = self . tags result [ 'type' ] = self . name ( ) minfo = self . meta_info try : result [ 'mode' ] = minfo [ 'mode_name' ] origin = minfo [ 'origin' ] date_obs = origin [ 'date_obs' ] except KeyError : origin = { } date_obs = "1970-01-01T00:00:00.00" result [ 'observation_date' ] = conv . convert_date ( date_obs ) result [ 'origin' ] = origin return result
3,825
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/types/structured.py#L197-L218
[ "def", "_write_ccr", "(", "self", ",", "f", ",", "g", ",", "level", ":", "int", ")", ":", "f", ".", "seek", "(", "8", ")", "data", "=", "f", ".", "read", "(", ")", "uSize", "=", "len", "(", "data", ")", "section_type", "=", "CDF", ".", "CCR_", "rfuA", "=", "0", "cData", "=", "gzip", ".", "compress", "(", "data", ",", "level", ")", "block_size", "=", "CDF", ".", "CCR_BASE_SIZE64", "+", "len", "(", "cData", ")", "cprOffset", "=", "0", "ccr1", "=", "bytearray", "(", "32", ")", "#ccr1[0:4] = binascii.unhexlify(CDF.V3magicNUMBER_1)", "#ccr1[4:8] = binascii.unhexlify(CDF.V3magicNUMBER_2c)", "ccr1", "[", "0", ":", "8", "]", "=", "struct", ".", "pack", "(", "'>q'", ",", "block_size", ")", "ccr1", "[", "8", ":", "12", "]", "=", "struct", ".", "pack", "(", "'>i'", ",", "section_type", ")", "ccr1", "[", "12", ":", "20", "]", "=", "struct", ".", "pack", "(", "'>q'", ",", "cprOffset", ")", "ccr1", "[", "20", ":", "28", "]", "=", "struct", ".", "pack", "(", "'>q'", ",", "uSize", ")", "ccr1", "[", "28", ":", "32", "]", "=", "struct", ".", "pack", "(", "'>i'", ",", "rfuA", ")", "g", ".", "seek", "(", "0", ",", "2", ")", "g", ".", "write", "(", "ccr1", ")", "g", ".", "write", "(", "cData", ")", "cprOffset", "=", "self", ".", "_write_cpr", "(", "g", ",", "CDF", ".", "GZIP_COMPRESSION", ",", "level", ")", "self", ".", "_update_offset_value", "(", "g", ",", "20", ",", "8", ",", "cprOffset", ")" ]
Call a Gnuplot script passing it arguments and datasets .
def gnuplot ( script_name , args_dict = { } , data = [ ] , silent = True ) : gnuplot_command = 'gnuplot' if data : assert 'data' not in args_dict , 'Can\'t use \'data\' variable twice.' data_temp = _GnuplotDataTemp ( * data ) args_dict [ 'data' ] = data_temp . name if args_dict : gnuplot_command += ' -e "' for arg in args_dict . items ( ) : gnuplot_command += arg [ 0 ] + '=' if isinstance ( arg [ 1 ] , str ) : gnuplot_command += '\'' + arg [ 1 ] + '\'' elif isinstance ( arg [ 1 ] , bool ) : if arg [ 1 ] is True : gnuplot_command += '1' else : gnuplot_command += '0' elif hasattr ( arg [ 1 ] , '__iter__' ) : gnuplot_command += '\'' + ' ' . join ( [ str ( v ) for v in arg [ 1 ] ] ) + '\'' else : gnuplot_command += str ( arg [ 1 ] ) gnuplot_command += '; ' gnuplot_command = gnuplot_command [ : - 1 ] gnuplot_command += '"' gnuplot_command += ' ' + script_name if silent : gnuplot_command += ' > /dev/null 2>&1' os . system ( gnuplot_command ) return gnuplot_command
3,826
https://github.com/jtambasco/gnuplotpy/blob/0e67fa0b839f94981f8e18dfd42c30f98b68f500/gnuplotpy/gnuplot.py#L39-L96
[ "def", "replace_memory_object", "(", "self", ",", "old", ",", "new_content", ")", ":", "if", "old", ".", "object", ".", "size", "(", ")", "!=", "new_content", ".", "size", "(", ")", ":", "raise", "SimMemoryError", "(", "\"memory objects can only be replaced by the same length content\"", ")", "new", "=", "SimMemoryObject", "(", "new_content", ",", "old", ".", "base", ",", "byte_width", "=", "self", ".", "byte_width", ")", "for", "p", "in", "self", ".", "_containing_pages_mo", "(", "old", ")", ":", "self", ".", "_get_page", "(", "p", "//", "self", ".", "_page_size", ",", "write", "=", "True", ")", ".", "replace_mo", "(", "self", ".", "state", ",", "old", ",", "new", ")", "if", "isinstance", "(", "new", ".", "object", ",", "claripy", ".", "ast", ".", "BV", ")", ":", "for", "b", "in", "range", "(", "old", ".", "base", ",", "old", ".", "base", "+", "old", ".", "length", ")", ":", "self", ".", "_update_mappings", "(", "b", ",", "new", ".", "object", ")", "return", "new" ]
Function to produce a general 2D plot .
def gnuplot_2d ( x , y , filename , title = '' , x_label = '' , y_label = '' ) : _ , ext = os . path . splitext ( filename ) if ext != '.png' : filename += '.png' gnuplot_cmds = ''' set datafile separator "," set term pngcairo size 30cm,25cm set out filename unset key set border lw 1.5 set grid lt -1 lc rgb "gray80" set title title set xlabel x_label set ylabel y_label plot filename_data u 1:2 w lp pt 6 ps 0.5 ''' scr = _GnuplotScriptTemp ( gnuplot_cmds ) data = _GnuplotDataTemp ( x , y ) args_dict = { 'filename' : filename , 'filename_data' : data . name , 'title' : title , 'x_label' : x_label , 'y_label' : y_label } gnuplot ( scr . name , args_dict )
3,827
https://github.com/jtambasco/gnuplotpy/blob/0e67fa0b839f94981f8e18dfd42c30f98b68f500/gnuplotpy/gnuplot.py#L98-L140
[ "def", "start", "(", "self", ",", "device_uuid", ")", ":", "status_code", ",", "_", ",", "session", "=", "self", ".", "http_client", ".", "post", "(", "'/sync/start'", ",", "body", "=", "None", ",", "headers", "=", "self", ".", "build_headers", "(", "device_uuid", ")", ")", "return", "None", "if", "status_code", "==", "204", "else", "session" ]
Function to produce a general 3D plot from a 2D matrix .
def gnuplot_3d_matrix ( z_matrix , filename , title = '' , x_label = '' , y_label = '' ) : _ , ext = os . path . splitext ( filename ) if ext != '.png' : filename += '.png' gnuplot_cmds = ''' set datafile separator "," set term pngcairo size 30cm,25cm set out filename unset key set border lw 1.5 set view map set title title set xlabel x_label set ylabel y_label splot filename_data matrix w pm3d ''' scr = _GnuplotScriptTemp ( gnuplot_cmds ) data = _GnuplotDataZMatrixTemp ( z_matrix ) args_dict = { 'filename' : filename , 'filename_data' : data . name , 'title' : title , 'x_label' : x_label , 'y_label' : y_label } gnuplot ( scr . name , args_dict )
3,828
https://github.com/jtambasco/gnuplotpy/blob/0e67fa0b839f94981f8e18dfd42c30f98b68f500/gnuplotpy/gnuplot.py#L190-L231
[ "def", "ttl", "(", "self", ",", "value", ")", ":", "# get timer", "timer", "=", "getattr", "(", "self", ",", "Annotation", ".", "__TIMER", ",", "None", ")", "# if timer is running, stop the timer", "if", "timer", "is", "not", "None", ":", "timer", ".", "cancel", "(", ")", "# initialize timestamp", "timestamp", "=", "None", "# if value is None", "if", "value", "is", "None", ":", "# nonify timer", "timer", "=", "None", "else", ":", "# else, renew a timer", "# get timestamp", "timestamp", "=", "time", "(", ")", "+", "value", "# start a new timer", "timer", "=", "Timer", "(", "value", ",", "self", ".", "__del__", ")", "timer", ".", "start", "(", ")", "# set/update attributes", "setattr", "(", "self", ",", "Annotation", ".", "__TIMER", ",", "timer", ")", "setattr", "(", "self", ",", "Annotation", ".", "__TS", ",", "timestamp", ")" ]
Get reactions from folders .
def read ( self , skip = [ ] , goto_metal = None , goto_reaction = None ) : if len ( skip ) > 0 : for skip_f in skip : self . omit_folders . append ( skip_f ) """ If publication level is input""" if os . path . isfile ( self . data_base + '/publication.txt' ) : self . user_base_level -= 1 self . stdout . write ( '---------------------- \n' ) self . stdout . write ( 'Starting folderreader! \n' ) self . stdout . write ( '---------------------- \n' ) found_reaction = False for root , dirs , files in os . walk ( self . user_base ) : for omit_folder in self . omit_folders : # user specified omit_folder if omit_folder in dirs : dirs . remove ( omit_folder ) level = len ( root . split ( "/" ) ) - self . user_base_level if level == self . pub_level : self . read_pub ( root ) if level == self . DFT_level : self . DFT_code = os . path . basename ( root ) if level == self . XC_level : self . DFT_functional = os . path . basename ( root ) self . gas_folder = root + '/gas/' self . read_gas ( ) if level == self . reference_level : if 'gas' in os . path . basename ( root ) : continue if goto_metal is not None : if os . path . basename ( root ) == goto_metal : goto_metal = None else : dirs [ : ] = [ ] # don't read any sub_dirs continue self . read_bulk ( root ) if level == self . slab_level : self . read_slab ( root ) if level == self . reaction_level : if goto_reaction is not None : if os . path . basename ( root ) == goto_reaction : goto_reaction = None else : dirs [ : ] = [ ] # don't read any sub_dirs continue self . read_reaction ( root ) if level == self . final_level : self . root = root self . read_energies ( root ) if self . key_value_pairs_reaction is not None : yield self . key_value_pairs_reaction
3,829
https://github.com/SUNCAT-Center/CatHub/blob/324625d1d8e740673f139658b2de4c9e1059739e/cathub/folderreader.py#L79-L150
[ "def", "get_doc", "(", "logger", "=", "None", ",", "plugin", "=", "None", ",", "reporthook", "=", "None", ")", ":", "from", "ginga", ".", "GingaPlugin", "import", "GlobalPlugin", ",", "LocalPlugin", "if", "isinstance", "(", "plugin", ",", "GlobalPlugin", ")", ":", "plugin_page", "=", "'plugins_global'", "plugin_name", "=", "str", "(", "plugin", ")", "elif", "isinstance", "(", "plugin", ",", "LocalPlugin", ")", ":", "plugin_page", "=", "'plugins_local'", "plugin_name", "=", "str", "(", "plugin", ")", "else", ":", "plugin_page", "=", "None", "plugin_name", "=", "None", "try", ":", "index_html", "=", "_download_rtd_zip", "(", "reporthook", "=", "reporthook", ")", "# Download failed, use online resource", "except", "Exception", "as", "e", ":", "url", "=", "'https://ginga.readthedocs.io/en/latest/'", "if", "plugin_name", "is", "not", "None", ":", "if", "toolkit", ".", "family", ".", "startswith", "(", "'qt'", ")", ":", "# This displays plugin docstring.", "url", "=", "None", "else", ":", "# This redirects to online doc.", "url", "+=", "'manual/{}/{}.html'", ".", "format", "(", "plugin_page", ",", "plugin_name", ")", "if", "logger", "is", "not", "None", ":", "logger", ".", "error", "(", "str", "(", "e", ")", ")", "# Use local resource", "else", ":", "pfx", "=", "'file:'", "url", "=", "'{}{}'", ".", "format", "(", "pfx", ",", "index_html", ")", "# https://github.com/rtfd/readthedocs.org/issues/2803", "if", "plugin_name", "is", "not", "None", ":", "url", "+=", "'#{}'", ".", "format", "(", "plugin_name", ")", "return", "url" ]
Return an slice with a symmetric region around center .
def slice_create ( center , block , start = 0 , stop = None ) : do = coor_to_pix_1d ( center - block ) up = coor_to_pix_1d ( center + block ) l = max ( start , do ) if stop is not None : h = min ( up + 1 , stop ) else : h = up + 1 return slice ( l , h , 1 )
3,830
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/utils.py#L40-L53
[ "def", "get_player_summaries", "(", "self", ",", "steamids", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "not", "isinstance", "(", "steamids", ",", "collections", ".", "Iterable", ")", ":", "steamids", "=", "[", "steamids", "]", "base64_ids", "=", "list", "(", "map", "(", "convert_to_64_bit", ",", "filter", "(", "lambda", "x", ":", "x", "is", "not", "None", ",", "steamids", ")", ")", ")", "if", "'steamids'", "not", "in", "kwargs", ":", "kwargs", "[", "'steamids'", "]", "=", "base64_ids", "url", "=", "self", ".", "__build_url", "(", "urls", ".", "GET_PLAYER_SUMMARIES", ",", "*", "*", "kwargs", ")", "req", "=", "self", ".", "executor", "(", "url", ")", "if", "self", ".", "logger", ":", "self", ".", "logger", ".", "info", "(", "'URL: {0}'", ".", "format", "(", "url", ")", ")", "if", "not", "self", ".", "__check_http_err", "(", "req", ".", "status_code", ")", ":", "return", "response", ".", "build", "(", "req", ",", "url", ",", "self", ".", "raw_mode", ")" ]
Create a region of size box around a center in a image of shape .
def image_box ( center , shape , box ) : return tuple ( slice_create ( c , b , stop = s ) for c , s , b in zip ( center , shape , box ) )
3,831
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/utils.py#L56-L59
[ "def", "makecsvdiffs", "(", "thediffs", ",", "dtls", ",", "n1", ",", "n2", ")", ":", "def", "ishere", "(", "val", ")", ":", "if", "val", "==", "None", ":", "return", "\"not here\"", "else", ":", "return", "\"is here\"", "rows", "=", "[", "]", "rows", ".", "append", "(", "[", "'file1 = %s'", "%", "(", "n1", ",", ")", "]", ")", "rows", ".", "append", "(", "[", "'file2 = %s'", "%", "(", "n2", ",", ")", "]", ")", "rows", ".", "append", "(", "''", ")", "rows", ".", "append", "(", "theheader", "(", "n1", ",", "n2", ")", ")", "keys", "=", "list", "(", "thediffs", ".", "keys", "(", ")", ")", "# ensures sorting by Name", "keys", ".", "sort", "(", ")", "# sort the keys in the same order as in the idd", "dtlssorter", "=", "DtlsSorter", "(", "dtls", ")", "keys", "=", "sorted", "(", "keys", ",", "key", "=", "dtlssorter", ".", "getkey", ")", "for", "key", "in", "keys", ":", "if", "len", "(", "key", ")", "==", "2", ":", "rw2", "=", "[", "''", "]", "+", "[", "ishere", "(", "i", ")", "for", "i", "in", "thediffs", "[", "key", "]", "]", "else", ":", "rw2", "=", "list", "(", "thediffs", "[", "key", "]", ")", "rw1", "=", "list", "(", "key", ")", "rows", ".", "append", "(", "rw1", "+", "rw2", ")", "return", "rows" ]
Apply expend_slice on a tuple of slices
def expand_region ( tuple_of_s , a , b , start = 0 , stop = None ) : return tuple ( expand_slice ( s , a , b , start = start , stop = stop ) for s in tuple_of_s )
3,832
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/utils.py#L81-L84
[ "def", "get_region_from_metadata", "(", ")", ":", "global", "__Location__", "if", "__Location__", "==", "'do-not-get-from-metadata'", ":", "log", ".", "debug", "(", "'Previously failed to get AWS region from metadata. Not trying again.'", ")", "return", "None", "# Cached region", "if", "__Location__", "!=", "''", ":", "return", "__Location__", "try", ":", "# Connections to instance meta-data must fail fast and never be proxied", "result", "=", "requests", ".", "get", "(", "\"http://169.254.169.254/latest/dynamic/instance-identity/document\"", ",", "proxies", "=", "{", "'http'", ":", "''", "}", ",", "timeout", "=", "AWS_METADATA_TIMEOUT", ",", ")", "except", "requests", ".", "exceptions", ".", "RequestException", ":", "log", ".", "warning", "(", "'Failed to get AWS region from instance metadata.'", ",", "exc_info", "=", "True", ")", "# Do not try again", "__Location__", "=", "'do-not-get-from-metadata'", "return", "None", "try", ":", "region", "=", "result", ".", "json", "(", ")", "[", "'region'", "]", "__Location__", "=", "region", "return", "__Location__", "except", "(", "ValueError", ",", "KeyError", ")", ":", "log", ".", "warning", "(", "'Failed to decode JSON from instance metadata.'", ")", "return", "None", "return", "None" ]
Adapt obsres after file copy
def adapt_obsres ( self , obsres ) : _logger . debug ( 'adapt observation result for work dir' ) for f in obsres . images : # Remove path components f . filename = os . path . basename ( f . filename ) return obsres
3,833
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/user/helpers.py#L326-L333
[ "def", "devices", "(", "self", ",", "timeout", "=", "None", ")", ":", "# b313b945 device usb:1-7 product:d2vzw model:SCH_I535 device:d2vzw", "# from Android system/core/adb/transport.c statename()", "re_device_info", "=", "re", ".", "compile", "(", "r'([^\\s]+)\\s+(offline|bootloader|device|host|recovery|sideload|no permissions|unauthorized|unknown)'", ")", "devices", "=", "[", "]", "lines", "=", "self", ".", "command_output", "(", "[", "\"devices\"", ",", "\"-l\"", "]", ",", "timeout", "=", "timeout", ")", ".", "split", "(", "'\\n'", ")", "for", "line", "in", "lines", ":", "if", "line", "==", "'List of devices attached '", ":", "continue", "match", "=", "re_device_info", ".", "match", "(", "line", ")", "if", "match", ":", "device", "=", "{", "'device_serial'", ":", "match", ".", "group", "(", "1", ")", ",", "'state'", ":", "match", ".", "group", "(", "2", ")", "}", "remainder", "=", "line", "[", "match", ".", "end", "(", "2", ")", ":", "]", ".", "strip", "(", ")", "if", "remainder", ":", "try", ":", "device", ".", "update", "(", "dict", "(", "[", "j", ".", "split", "(", "':'", ")", "for", "j", "in", "remainder", ".", "split", "(", "' '", ")", "]", ")", ")", "except", "ValueError", ":", "self", ".", "_logger", ".", "warning", "(", "'devices: Unable to parse '", "'remainder for device %s'", "%", "line", ")", "devices", ".", "append", "(", "device", ")", "return", "devices" ]
Store the values of the completed task .
def store ( self , completed_task , resultsdir ) : with working_directory ( resultsdir ) : _logger . info ( 'storing result' ) return completed_task . store ( self )
3,834
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/user/helpers.py#L396-L401
[ "async", "def", "jsk_curl", "(", "self", ",", "ctx", ":", "commands", ".", "Context", ",", "url", ":", "str", ")", ":", "# remove embed maskers if present", "url", "=", "url", ".", "lstrip", "(", "\"<\"", ")", ".", "rstrip", "(", "\">\"", ")", "async", "with", "ReplResponseReactor", "(", "ctx", ".", "message", ")", ":", "async", "with", "aiohttp", ".", "ClientSession", "(", ")", "as", "session", ":", "async", "with", "session", ".", "get", "(", "url", ")", "as", "response", ":", "data", "=", "await", "response", ".", "read", "(", ")", "hints", "=", "(", "response", ".", "content_type", ",", "url", ")", "code", "=", "response", ".", "status", "if", "not", "data", ":", "return", "await", "ctx", ".", "send", "(", "f\"HTTP response was empty (status code {code}).\"", ")", "try", ":", "paginator", "=", "WrappedFilePaginator", "(", "io", ".", "BytesIO", "(", "data", ")", ",", "language_hints", "=", "hints", ",", "max_size", "=", "1985", ")", "except", "UnicodeDecodeError", ":", "return", "await", "ctx", ".", "send", "(", "f\"Couldn't determine the encoding of the response. (status code {code})\"", ")", "except", "ValueError", "as", "exc", ":", "return", "await", "ctx", ".", "send", "(", "f\"Couldn't read response (status code {code}), {exc}\"", ")", "interface", "=", "PaginatorInterface", "(", "ctx", ".", "bot", ",", "paginator", ",", "owner", "=", "ctx", ".", "author", ")", "await", "interface", ".", "send_to", "(", "ctx", ")" ]
Validate convertibility to internal representation
def validate ( self , obj ) : if not isinstance ( obj , self . internal_type ) : raise ValidationError ( obj , self . internal_type ) return True
3,835
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/types/datatype.py#L50-L66
[ "def", "ParsedSections", "(", "file_val", ")", ":", "try", ":", "template_dict", "=", "{", "}", "cur_section", "=", "''", "for", "val", "in", "file_val", ".", "split", "(", "'\\n'", ")", ":", "val", "=", "val", ".", "strip", "(", ")", "if", "val", "!=", "''", ":", "section_match", "=", "re", ".", "match", "(", "r'\\[.+\\]'", ",", "val", ")", "if", "section_match", ":", "cur_section", "=", "section_match", ".", "group", "(", ")", "[", "1", ":", "-", "1", "]", "template_dict", "[", "cur_section", "]", "=", "{", "}", "else", ":", "option", ",", "value", "=", "val", ".", "split", "(", "'='", ",", "1", ")", "option", "=", "option", ".", "strip", "(", ")", "value", "=", "value", ".", "strip", "(", ")", "if", "option", ".", "startswith", "(", "'#'", ")", ":", "template_dict", "[", "cur_section", "]", "[", "val", "]", "=", "''", "else", ":", "template_dict", "[", "cur_section", "]", "[", "option", "]", "=", "value", "except", "Exception", ":", "# pragma: no cover", "template_dict", "=", "{", "}", "return", "template_dict" ]
Delete user and all data
def delete_user ( self , user ) : assert self . user == 'catroot' or self . user == 'postgres' assert not user == 'public' con = self . connection or self . _connect ( ) cur = con . cursor ( ) cur . execute ( 'DROP SCHEMA {user} CASCADE;' . format ( user = user ) ) cur . execute ( 'REVOKE USAGE ON SCHEMA public FROM {user};' . format ( user = user ) ) cur . execute ( 'REVOKE SELECT ON ALL TABLES IN SCHEMA public FROM {user};' . format ( user = user ) ) cur . execute ( 'DROP ROLE {user};' . format ( user = user ) ) self . stdout . write ( 'REMOVED USER {user}\n' . format ( user = user ) ) if self . connection is None : con . commit ( ) con . close ( ) return self
3,836
https://github.com/SUNCAT-Center/CatHub/blob/324625d1d8e740673f139658b2de4c9e1059739e/cathub/postgresql.py#L320-L341
[ "def", "update_host_password", "(", "host", ",", "username", ",", "password", ",", "new_password", ",", "protocol", "=", "None", ",", "port", "=", "None", ")", ":", "service_instance", "=", "salt", ".", "utils", ".", "vmware", ".", "get_service_instance", "(", "host", "=", "host", ",", "username", "=", "username", ",", "password", "=", "password", ",", "protocol", "=", "protocol", ",", "port", "=", "port", ")", "# Get LocalAccountManager object", "account_manager", "=", "salt", ".", "utils", ".", "vmware", ".", "get_inventory", "(", "service_instance", ")", ".", "accountManager", "# Create user account specification object and assign id and password attributes", "user_account", "=", "vim", ".", "host", ".", "LocalAccountManager", ".", "AccountSpecification", "(", ")", "user_account", ".", "id", "=", "username", "user_account", ".", "password", "=", "new_password", "# Update the password", "try", ":", "account_manager", ".", "UpdateUser", "(", "user_account", ")", "except", "vmodl", ".", "fault", ".", "SystemError", "as", "err", ":", "raise", "CommandExecutionError", "(", "err", ".", "msg", ")", "except", "vim", ".", "fault", ".", "UserNotFound", ":", "raise", "CommandExecutionError", "(", "'\\'vsphere.update_host_password\\' failed for host {0}: '", "'User was not found.'", ".", "format", "(", "host", ")", ")", "# If the username and password already exist, we don't need to do anything.", "except", "vim", ".", "fault", ".", "AlreadyExists", ":", "pass", "return", "True" ]
Will delete all data in schema . Only for test use!
def truncate_schema ( self ) : assert self . server == 'localhost' con = self . connection or self . _connect ( ) self . _initialize ( con ) cur = con . cursor ( ) cur . execute ( 'DELETE FROM publication;' ) cur . execute ( 'TRUNCATE systems CASCADE;' ) con . commit ( ) con . close ( ) return
3,837
https://github.com/SUNCAT-Center/CatHub/blob/324625d1d8e740673f139658b2de4c9e1059739e/cathub/postgresql.py#L772-L786
[ "def", "add_annotation", "(", "self", ",", "entity", ",", "annotation", ",", "value", ")", ":", "url", "=", "self", ".", "base_path", "+", "'term/add-annotation'", "data", "=", "{", "'tid'", ":", "entity", "[", "'id'", "]", ",", "'annotation_tid'", ":", "annotation", "[", "'id'", "]", ",", "'value'", ":", "value", ",", "'term_version'", ":", "entity", "[", "'version'", "]", ",", "'annotation_term_version'", ":", "annotation", "[", "'version'", "]", "}", "return", "self", ".", "post", "(", "url", ",", "data", ")" ]
Call the stream s write method without linebreaks at line endings .
def write ( self , * args , * * kwargs ) : return self . stream . write ( ending = "" , * args , * * kwargs )
3,838
https://github.com/druids/django-chamber/blob/eef4169923557e96877a664fa254e8c0814f3f23/chamber/commands/__init__.py#L19-L23
[ "async", "def", "services", "(", "self", ",", "*", ",", "dc", "=", "None", ",", "watch", "=", "None", ",", "consistency", "=", "None", ")", ":", "params", "=", "{", "\"dc\"", ":", "dc", "}", "response", "=", "await", "self", ".", "_api", ".", "get", "(", "\"/v1/catalog/services\"", ",", "params", "=", "params", ",", "watch", "=", "watch", ",", "consistency", "=", "consistency", ")", "return", "consul", "(", "response", ")" ]
Initialize the 1D interpolation .
def _update ( self ) : if self . strains . size and self . strains . size == self . values . size : x = np . log ( self . strains ) y = self . values if x . size < 4 : self . _interpolater = interp1d ( x , y , 'linear' , bounds_error = False , fill_value = ( y [ 0 ] , y [ - 1 ] ) ) else : self . _interpolater = interp1d ( x , y , 'cubic' , bounds_error = False , fill_value = ( y [ 0 ] , y [ - 1 ] ) )
3,839
https://github.com/arkottke/pysra/blob/c72fd389d6c15203c0c00728ac00f101bae6369d/pysra/site.py#L129-L149
[ "def", "devices", "(", "self", ",", "timeout", "=", "None", ")", ":", "# b313b945 device usb:1-7 product:d2vzw model:SCH_I535 device:d2vzw", "# from Android system/core/adb/transport.c statename()", "re_device_info", "=", "re", ".", "compile", "(", "r'([^\\s]+)\\s+(offline|bootloader|device|host|recovery|sideload|no permissions|unauthorized|unknown)'", ")", "devices", "=", "[", "]", "lines", "=", "self", ".", "command_output", "(", "[", "\"devices\"", ",", "\"-l\"", "]", ",", "timeout", "=", "timeout", ")", ".", "split", "(", "'\\n'", ")", "for", "line", "in", "lines", ":", "if", "line", "==", "'List of devices attached '", ":", "continue", "match", "=", "re_device_info", ".", "match", "(", "line", ")", "if", "match", ":", "device", "=", "{", "'device_serial'", ":", "match", ".", "group", "(", "1", ")", ",", "'state'", ":", "match", ".", "group", "(", "2", ")", "}", "remainder", "=", "line", "[", "match", ".", "end", "(", "2", ")", ":", "]", ".", "strip", "(", ")", "if", "remainder", ":", "try", ":", "device", ".", "update", "(", "dict", "(", "[", "j", ".", "split", "(", "':'", ")", "for", "j", "in", "remainder", ".", "split", "(", "' '", ")", "]", ")", ")", "except", "ValueError", ":", "self", ".", "_logger", ".", "warning", "(", "'devices: Unable to parse '", "'remainder for device %s'", "%", "line", ")", "devices", ".", "append", "(", "device", ")", "return", "devices" ]
If nonlinear properties are specified .
def is_nonlinear ( self ) : return any ( isinstance ( p , NonlinearProperty ) for p in [ self . mod_reduc , self . damping ] )
3,840
https://github.com/arkottke/pysra/blob/c72fd389d6c15203c0c00728ac00f101bae6369d/pysra/site.py#L194-L198
[ "def", "volumes_delete", "(", "storage_pool", ",", "logger", ")", ":", "try", ":", "for", "vol_name", "in", "storage_pool", ".", "listVolumes", "(", ")", ":", "try", ":", "vol", "=", "storage_pool", ".", "storageVolLookupByName", "(", "vol_name", ")", "vol", ".", "delete", "(", "0", ")", "except", "libvirt", ".", "libvirtError", ":", "logger", ".", "exception", "(", "\"Unable to delete storage volume %s.\"", ",", "vol_name", ")", "except", "libvirt", ".", "libvirtError", ":", "logger", ".", "exception", "(", "\"Unable to delete storage volumes.\"", ")" ]
The relative error in percent between the two iterations .
def relative_error ( self ) : if self . previous is not None : # FIXME # Use the maximum strain value -- this is important for error # calculation with frequency dependent properties # prev = np.max(self.previous) # value = np.max(self.value) try : err = 100. * np . max ( ( self . previous - self . value ) / self . value ) except ZeroDivisionError : err = np . inf else : err = 0 return err
3,841
https://github.com/arkottke/pysra/blob/c72fd389d6c15203c0c00728ac00f101bae6369d/pysra/site.py#L563-L578
[ "def", "namedtuple_storable", "(", "namedtuple", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "default_storable", "(", "namedtuple", ",", "namedtuple", ".", "_fields", ",", "*", "args", ",", "*", "*", "kwargs", ")" ]
Create a copy of the layer .
def duplicate ( cls , other ) : return cls ( other . soil_type , other . thickness , other . shear_vel )
3,842
https://github.com/arkottke/pysra/blob/c72fd389d6c15203c0c00728ac00f101bae6369d/pysra/site.py#L630-L632
[ "def", "parse_journal", "(", "journal", ")", ":", "events", "=", "[", "e", "for", "e", "in", "journal", "if", "not", "isinstance", "(", "e", ",", "CorruptedUsnRecord", ")", "]", "keyfunc", "=", "lambda", "e", ":", "str", "(", "e", ".", "file_reference_number", ")", "+", "e", ".", "file_name", "+", "e", ".", "timestamp", "event_groups", "=", "(", "tuple", "(", "g", ")", "for", "k", ",", "g", "in", "groupby", "(", "events", ",", "key", "=", "keyfunc", ")", ")", "if", "len", "(", "events", ")", "<", "len", "(", "list", "(", "journal", ")", ")", ":", "LOGGER", ".", "debug", "(", "\"Corrupted records in UsnJrnl, some events might be missing.\"", ")", "return", "[", "journal_event", "(", "g", ")", "for", "g", "in", "event_groups", "]" ]
Strain - compatible damping .
def damping ( self ) : try : value = self . _damping . value except AttributeError : value = self . _damping return value
3,843
https://github.com/arkottke/pysra/blob/c72fd389d6c15203c0c00728ac00f101bae6369d/pysra/site.py#L640-L646
[ "def", "__getBio", "(", "self", ",", "web", ")", ":", "bio", "=", "web", ".", "find_all", "(", "\"div\"", ",", "{", "\"class\"", ":", "\"user-profile-bio\"", "}", ")", "if", "bio", ":", "try", ":", "bio", "=", "bio", "[", "0", "]", ".", "text", "if", "bio", "and", "GitHubUser", ".", "isASCII", "(", "bio", ")", ":", "bioText", "=", "bio", ".", "replace", "(", "\"\\n\"", ",", "\"\"", ")", "bioText", "=", "bioText", ".", "replace", "(", "\"\\t\"", ",", "\" \"", ")", ".", "replace", "(", "\"\\\"\"", ",", "\"\"", ")", "bioText", "=", "bioText", ".", "replace", "(", "\"\\'\"", ",", "\"\"", ")", ".", "replace", "(", "\"\\\\\"", ",", "\"\"", ")", "self", ".", "bio", "=", "bioText", "else", ":", "self", ".", "bio", "=", "\"\"", "except", "IndexError", "as", "error", ":", "print", "(", "\"There was an error with the user \"", "+", "self", ".", "name", ")", "print", "(", "error", ")", "except", "AttributeError", "as", "error", ":", "print", "(", "\"There was an error with the user \"", "+", "self", ".", "name", ")", "print", "(", "error", ")" ]
Subdivide the layers to capture strain variation .
def auto_discretize ( self , max_freq = 50. , wave_frac = 0.2 ) : layers = [ ] for l in self : if l . soil_type . is_nonlinear : opt_thickness = l . shear_vel / max_freq * wave_frac count = np . ceil ( l . thickness / opt_thickness ) . astype ( int ) thickness = l . thickness / count for _ in range ( count ) : layers . append ( Layer ( l . soil_type , thickness , l . shear_vel ) ) else : layers . append ( l ) return Profile ( layers , wt_depth = self . wt_depth )
3,844
https://github.com/arkottke/pysra/blob/c72fd389d6c15203c0c00728ac00f101bae6369d/pysra/site.py#L866-L892
[ "def", "load_config", "(", "self", ",", "config_path", "=", "None", ")", ":", "self", ".", "loaded", "=", "True", "config", "=", "copy", ".", "deepcopy", "(", "DEFAULTS", ")", "if", "config_path", "is", "None", ":", "if", "\"FEDORA_MESSAGING_CONF\"", "in", "os", ".", "environ", ":", "config_path", "=", "os", ".", "environ", "[", "\"FEDORA_MESSAGING_CONF\"", "]", "else", ":", "config_path", "=", "\"/etc/fedora-messaging/config.toml\"", "if", "os", ".", "path", ".", "exists", "(", "config_path", ")", ":", "_log", ".", "info", "(", "\"Loading configuration from {}\"", ".", "format", "(", "config_path", ")", ")", "with", "open", "(", "config_path", ")", "as", "fd", ":", "try", ":", "file_config", "=", "toml", ".", "load", "(", "fd", ")", "for", "key", "in", "file_config", ":", "config", "[", "key", ".", "lower", "(", ")", "]", "=", "file_config", "[", "key", "]", "except", "toml", ".", "TomlDecodeError", "as", "e", ":", "msg", "=", "\"Failed to parse {}: error at line {}, column {}: {}\"", ".", "format", "(", "config_path", ",", "e", ".", "lineno", ",", "e", ".", "colno", ",", "e", ".", "msg", ")", "raise", "exceptions", ".", "ConfigurationException", "(", "msg", ")", "else", ":", "_log", ".", "info", "(", "\"The configuration file, {}, does not exist.\"", ".", "format", "(", "config_path", ")", ")", "self", ".", "update", "(", "config", ")", "self", ".", "_validate", "(", ")", "return", "self" ]
Create a Location for a specific depth .
def location ( self , wave_field , depth = None , index = None ) : if not isinstance ( wave_field , WaveField ) : wave_field = WaveField [ wave_field ] if index is None and depth is not None : for i , layer in enumerate ( self [ : - 1 ] ) : if layer . depth <= depth < layer . depth_base : depth_within = depth - layer . depth break else : # Bedrock i = len ( self ) - 1 layer = self [ - 1 ] depth_within = 0 elif index is not None and depth is None : layer = self [ index ] i = self . index ( layer ) depth_within = 0 else : raise NotImplementedError return Location ( i , layer , wave_field , depth_within )
3,845
https://github.com/arkottke/pysra/blob/c72fd389d6c15203c0c00728ac00f101bae6369d/pysra/site.py#L910-L950
[ "def", "_convert_strls", "(", "self", ",", "data", ")", ":", "convert_cols", "=", "[", "col", "for", "i", ",", "col", "in", "enumerate", "(", "data", ")", "if", "self", ".", "typlist", "[", "i", "]", "==", "32768", "or", "col", "in", "self", ".", "_convert_strl", "]", "if", "convert_cols", ":", "ssw", "=", "StataStrLWriter", "(", "data", ",", "convert_cols", ")", "tab", ",", "new_data", "=", "ssw", ".", "generate_table", "(", ")", "data", "=", "new_data", "self", ".", "_strl_blob", "=", "ssw", ".", "generate_blob", "(", "tab", ")", "return", "data" ]
Calculate the time - average velocity .
def time_average_vel ( self , depth ) : depths = [ l . depth for l in self ] # Final layer is infinite and is treated separately travel_times = [ 0 ] + [ l . travel_time for l in self [ : - 1 ] ] # If needed, add the final layer to the required depth if depths [ - 1 ] < depth : depths . append ( depth ) travel_times . append ( ( depth - self [ - 1 ] . depth ) / self [ - 1 ] . shear_vel ) total_travel_times = np . cumsum ( travel_times ) # Interpolate the travel time to the depth of interest avg_shear_vel = depth / np . interp ( depth , depths , total_travel_times ) return avg_shear_vel
3,846
https://github.com/arkottke/pysra/blob/c72fd389d6c15203c0c00728ac00f101bae6369d/pysra/site.py#L952-L976
[ "def", "_connect", "(", "dbapi_connection", ",", "connection_record", ")", ":", "# If back end is sqlite", "if", "type", "(", "dbapi_connection", ")", "is", "sqlite3", ".", "Connection", ":", "# Respect foreign key constraints by default", "cursor", "=", "dbapi_connection", ".", "cursor", "(", ")", "cursor", ".", "execute", "(", "\"PRAGMA foreign_keys=ON\"", ")", "cursor", ".", "close", "(", ")" ]
Simplified Rayliegh velocity of the site .
def simplified_rayliegh_vel ( self ) : # FIXME: What if last layer has no thickness? thicks = np . array ( [ l . thickness for l in self ] ) depths_mid = np . array ( [ l . depth_mid for l in self ] ) shear_vels = np . array ( [ l . shear_vel for l in self ] ) mode_incr = depths_mid * thicks / shear_vels ** 2 # Mode shape is computed as the sumation from the base of # the profile. Need to append a 0 for the roll performed in the next # step shape = np . r_ [ np . cumsum ( mode_incr [ : : - 1 ] ) [ : : - 1 ] , 0 ] freq_fund = np . sqrt ( 4 * np . sum ( thicks * depths_mid ** 2 / shear_vels ** 2 ) / np . sum ( thicks * # Roll is used to offset the mode_shape so that the sum # can be calculated for two adjacent layers np . sum ( np . c_ [ shape , np . roll ( shape , - 1 ) ] , axis = 1 ) [ : - 1 ] ** 2 ) ) period_fun = 2 * np . pi / freq_fund rayleigh_vel = 4 * thicks . sum ( ) / period_fun return rayleigh_vel
3,847
https://github.com/arkottke/pysra/blob/c72fd389d6c15203c0c00728ac00f101bae6369d/pysra/site.py#L978-L1008
[ "def", "export_public_keys", "(", "self", ",", "identities", ")", ":", "public_keys", "=", "[", "]", "with", "self", ".", "device", ":", "for", "i", "in", "identities", ":", "pubkey", "=", "self", ".", "device", ".", "pubkey", "(", "identity", "=", "i", ")", "vk", "=", "formats", ".", "decompress_pubkey", "(", "pubkey", "=", "pubkey", ",", "curve_name", "=", "i", ".", "curve_name", ")", "public_key", "=", "formats", ".", "export_public_key", "(", "vk", "=", "vk", ",", "label", "=", "i", ".", "to_string", "(", ")", ")", "public_keys", ".", "append", "(", "public_key", ")", "return", "public_keys" ]
Iterate over the varied thicknesses .
def iter_thickness ( self , depth_total ) : total = 0 depth_prev = 0 while depth_prev < depth_total : # Add a random exponential increment total += np . random . exponential ( 1.0 ) # Convert between x and depth using the inverse of \Lambda(t) depth = np . power ( ( self . c_2 * total ) / self . c_3 + total / self . c_3 + np . power ( self . c_1 , self . c_2 + 1 ) , 1 / ( self . c_2 + 1 ) ) - self . c_1 thickness = depth - depth_prev if depth > depth_total : thickness = ( depth_total - depth_prev ) depth = depth_prev + thickness depth_mid = ( depth_prev + depth ) / 2 yield thickness , depth_mid depth_prev = depth
3,848
https://github.com/arkottke/pysra/blob/c72fd389d6c15203c0c00728ac00f101bae6369d/pysra/variation.py#L149-L194
[ "def", "logs", "(", "self", ",", "container", ",", "stdout", "=", "True", ",", "stderr", "=", "True", ",", "stream", "=", "False", ",", "timestamps", "=", "False", ",", "tail", "=", "'all'", ",", "since", "=", "None", ",", "follow", "=", "None", ",", "until", "=", "None", ")", ":", "if", "follow", "is", "None", ":", "follow", "=", "stream", "params", "=", "{", "'stderr'", ":", "stderr", "and", "1", "or", "0", ",", "'stdout'", ":", "stdout", "and", "1", "or", "0", ",", "'timestamps'", ":", "timestamps", "and", "1", "or", "0", ",", "'follow'", ":", "follow", "and", "1", "or", "0", ",", "}", "if", "tail", "!=", "'all'", "and", "(", "not", "isinstance", "(", "tail", ",", "int", ")", "or", "tail", "<", "0", ")", ":", "tail", "=", "'all'", "params", "[", "'tail'", "]", "=", "tail", "if", "since", "is", "not", "None", ":", "if", "isinstance", "(", "since", ",", "datetime", ")", ":", "params", "[", "'since'", "]", "=", "utils", ".", "datetime_to_timestamp", "(", "since", ")", "elif", "(", "isinstance", "(", "since", ",", "int", ")", "and", "since", ">", "0", ")", ":", "params", "[", "'since'", "]", "=", "since", "else", ":", "raise", "errors", ".", "InvalidArgument", "(", "'since value should be datetime or positive int, '", "'not {}'", ".", "format", "(", "type", "(", "since", ")", ")", ")", "if", "until", "is", "not", "None", ":", "if", "utils", ".", "version_lt", "(", "self", ".", "_version", ",", "'1.35'", ")", ":", "raise", "errors", ".", "InvalidVersion", "(", "'until is not supported for API version < 1.35'", ")", "if", "isinstance", "(", "until", ",", "datetime", ")", ":", "params", "[", "'until'", "]", "=", "utils", ".", "datetime_to_timestamp", "(", "until", ")", "elif", "(", "isinstance", "(", "until", ",", "int", ")", "and", "until", ">", "0", ")", ":", "params", "[", "'until'", "]", "=", "until", "else", ":", "raise", "errors", ".", "InvalidArgument", "(", "'until value should be datetime or positive int, '", "'not {}'", ".", "format", "(", "type", "(", "until", ")", ")", ")", "url", "=", "self", ".", "_url", "(", "\"/containers/{0}/logs\"", ",", "container", ")", "res", "=", "self", ".", "_get", "(", "url", ",", "params", "=", "params", ",", "stream", "=", "stream", ")", "output", "=", "self", ".", "_get_result", "(", "container", ",", "stream", ",", "res", ")", "if", "stream", ":", "return", "CancellableStream", "(", "output", ",", "res", ")", "else", ":", "return", "output" ]
Calculate the covariance matrix .
def _calc_covar_matrix ( self , profile ) : corr = self . _calc_corr ( profile ) std = self . _calc_ln_std ( profile ) # Modify the standard deviation by the truncated norm scale std *= randnorm . scale var = std ** 2 covar = corr * std [ : - 1 ] * std [ 1 : ] # Main diagonal is the variance mat = diags ( [ covar , var , covar ] , [ - 1 , 0 , 1 ] ) . toarray ( ) return mat
3,849
https://github.com/arkottke/pysra/blob/c72fd389d6c15203c0c00728ac00f101bae6369d/pysra/variation.py#L265-L289
[ "def", "to_vobject", "(", "self", ",", "filename", "=", "None", ",", "uid", "=", "None", ")", ":", "self", ".", "_update", "(", ")", "cal", "=", "iCalendar", "(", ")", "if", "uid", ":", "self", ".", "_gen_vevent", "(", "self", ".", "_reminders", "[", "filename", "]", "[", "uid", "]", ",", "cal", ".", "add", "(", "'vevent'", ")", ")", "elif", "filename", ":", "for", "event", "in", "self", ".", "_reminders", "[", "filename", "]", ".", "values", "(", ")", ":", "self", ".", "_gen_vevent", "(", "event", ",", "cal", ".", "add", "(", "'vevent'", ")", ")", "else", ":", "for", "filename", "in", "self", ".", "_reminders", ":", "for", "event", "in", "self", ".", "_reminders", "[", "filename", "]", ".", "values", "(", ")", ":", "self", ".", "_gen_vevent", "(", "event", ",", "cal", ".", "add", "(", "'vevent'", ")", ")", "return", "cal" ]
Compute the adjacent - layer correlations
def _calc_corr ( self , profile ) : depth = np . array ( [ l . depth_mid for l in profile [ : - 1 ] ] ) thick = np . diff ( depth ) depth = depth [ 1 : ] # Depth dependent correlation corr_depth = ( self . rho_200 * np . power ( ( depth + self . rho_0 ) / ( 200 + self . rho_0 ) , self . b ) ) corr_depth [ depth > 200 ] = self . rho_200 # Thickness dependent correlation corr_thick = self . rho_0 * np . exp ( - thick / self . delta ) # Final correlation # Correlation coefficient corr = ( 1 - corr_depth ) * corr_thick + corr_depth # Bedrock is perfectly correlated with layer above it corr = np . r_ [ corr , 1 ] return corr
3,850
https://github.com/arkottke/pysra/blob/c72fd389d6c15203c0c00728ac00f101bae6369d/pysra/variation.py#L419-L451
[ "def", "launcher", "(", ")", ":", "parser", "=", "OptionParser", "(", ")", "parser", ".", "add_option", "(", "'-f'", ",", "'--file'", ",", "dest", "=", "'filename'", ",", "default", "=", "'agents.csv'", ",", "help", "=", "'snmposter configuration file'", ")", "options", ",", "args", "=", "parser", ".", "parse_args", "(", ")", "factory", "=", "SNMPosterFactory", "(", ")", "snmpd_status", "=", "subprocess", ".", "Popen", "(", "[", "\"service\"", ",", "\"snmpd\"", ",", "\"status\"", "]", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", ".", "communicate", "(", ")", "[", "0", "]", "if", "\"is running\"", "in", "snmpd_status", ":", "message", "=", "\"snmd service is running. Please stop it and try again.\"", "print", ">>", "sys", ".", "stderr", ",", "message", "sys", ".", "exit", "(", "1", ")", "try", ":", "factory", ".", "configure", "(", "options", ".", "filename", ")", "except", "IOError", ":", "print", ">>", "sys", ".", "stderr", ",", "\"Error opening %s.\"", "%", "options", ".", "filename", "sys", ".", "exit", "(", "1", ")", "factory", ".", "start", "(", ")" ]
Use generic model parameters based on site class .
def generic_model ( cls , site_class , * * kwds ) : p = dict ( cls . PARAMS [ site_class ] ) p . update ( kwds ) return cls ( * * p )
3,851
https://github.com/arkottke/pysra/blob/c72fd389d6c15203c0c00728ac00f101bae6369d/pysra/variation.py#L486-L521
[ "def", "fetch", "(", "dataset", ",", "annot", ",", "cat", "=", "(", "0", ",", "0", ",", "0", ",", "0", ")", ",", "evt_type", "=", "None", ",", "stage", "=", "None", ",", "cycle", "=", "None", ",", "chan_full", "=", "None", ",", "epoch", "=", "None", ",", "epoch_dur", "=", "30", ",", "epoch_overlap", "=", "0", ",", "epoch_step", "=", "None", ",", "reject_epoch", "=", "False", ",", "reject_artf", "=", "False", ",", "min_dur", "=", "0", ",", "buffer", "=", "0", ")", ":", "bundles", "=", "get_times", "(", "annot", ",", "evt_type", "=", "evt_type", ",", "stage", "=", "stage", ",", "cycle", "=", "cycle", ",", "chan", "=", "chan_full", ",", "exclude", "=", "reject_epoch", ",", "buffer", "=", "buffer", ")", "# Remove artefacts", "if", "reject_artf", "and", "bundles", ":", "for", "bund", "in", "bundles", ":", "bund", "[", "'times'", "]", "=", "remove_artf_evts", "(", "bund", "[", "'times'", "]", ",", "annot", ",", "bund", "[", "'chan'", "]", ",", "min_dur", "=", "0", ")", "# Divide bundles into segments to be concatenated", "if", "bundles", ":", "if", "'locked'", "==", "epoch", ":", "bundles", "=", "_divide_bundles", "(", "bundles", ")", "elif", "'unlocked'", "==", "epoch", ":", "if", "epoch_step", "is", "not", "None", ":", "step", "=", "epoch_step", "else", ":", "step", "=", "epoch_dur", "-", "(", "epoch_dur", "*", "epoch_overlap", ")", "bundles", "=", "_concat", "(", "bundles", ",", "cat", ")", "bundles", "=", "_find_intervals", "(", "bundles", ",", "epoch_dur", ",", "step", ")", "elif", "not", "epoch", ":", "bundles", "=", "_concat", "(", "bundles", ",", "cat", ")", "# Minimum duration", "bundles", "=", "_longer_than", "(", "bundles", ",", "min_dur", ")", "segments", "=", "Segments", "(", "dataset", ")", "segments", ".", "segments", "=", "bundles", "return", "segments" ]
Calculate the standard deviation as a function of damping in decimal .
def calc_std_damping ( damping ) : damping = np . asarray ( damping ) . astype ( float ) std = ( np . exp ( - 5 ) + np . exp ( - 0.25 ) * np . sqrt ( 100 * damping ) ) / 100. return std
3,852
https://github.com/arkottke/pysra/blob/c72fd389d6c15203c0c00728ac00f101bae6369d/pysra/variation.py#L615-L632
[ "def", "_mark_grid_bounds", "(", "self", ",", "plane", ",", "region_bbox", ")", ":", "# Grid boundaries", "vbars", "=", "np", ".", "zeros", "(", "[", "self", ".", "num_rows", ",", "self", ".", "num_cols", "+", "1", "]", ",", "dtype", "=", "np", ".", "bool", ")", "hbars", "=", "np", ".", "zeros", "(", "[", "self", ".", "num_rows", "+", "1", ",", "self", ".", "num_cols", "]", ",", "dtype", "=", "np", ".", "bool", ")", "def", "closest_idx", "(", "arr", ",", "elem", ")", ":", "left", "=", "bisect", ".", "bisect_left", "(", "arr", ",", "elem", ")", "-", "1", "right", "=", "bisect", ".", "bisect_right", "(", "arr", ",", "elem", ")", "-", "1", "return", "left", "if", "abs", "(", "arr", "[", "left", "]", "-", "elem", ")", "<", "abs", "(", "arr", "[", "right", "]", "-", "elem", ")", "else", "right", "# Figure out which separating segments are missing, i.e. merge cells", "for", "row", ",", "(", "y0", ",", "y1", ")", "in", "enumerate", "(", "self", ".", "yranges", ")", ":", "yc", "=", "(", "y0", "+", "y1", ")", "//", "2", "for", "l", "in", "plane", ".", "find", "(", "(", "region_bbox", ".", "x0", ",", "yc", ",", "region_bbox", ".", "x1", ",", "yc", ")", ")", ":", "vbars", "[", "row", ",", "closest_idx", "(", "self", ".", "xs", ",", "l", ".", "xc", ")", "]", "=", "True", "for", "col", ",", "(", "x0", ",", "x1", ")", "in", "enumerate", "(", "self", ".", "xranges", ")", ":", "xc", "=", "(", "x0", "+", "x1", ")", "//", "2", "for", "l", "in", "plane", ".", "find", "(", "(", "xc", ",", "region_bbox", ".", "y0", ",", "xc", ",", "region_bbox", ".", "y1", ")", ")", ":", "hbars", "[", "closest_idx", "(", "self", ".", "ys", ",", "l", ".", "yc", ")", ",", "col", "]", "=", "True", "return", "vbars", ",", "hbars" ]
Append the element to the field of the record .
def _append_to ( self , field , element ) : if element not in EMPTIES : self . obj . setdefault ( field , [ ] ) self . obj . get ( field ) . append ( element )
3,853
https://github.com/inspirehep/inspire-schemas/blob/34bc124b62fba565b6b40d1a3c15103a23a05edb/inspire_schemas/builders/authors.py#L64-L77
[ "def", "get", "(", "self", ",", "accountID", ",", "*", "*", "kwargs", ")", ":", "request", "=", "Request", "(", "'GET'", ",", "'/v3/accounts/{accountID}/pricing'", ")", "request", ".", "set_path_param", "(", "'accountID'", ",", "accountID", ")", "request", ".", "set_param", "(", "'instruments'", ",", "kwargs", ".", "get", "(", "'instruments'", ")", ")", "request", ".", "set_param", "(", "'since'", ",", "kwargs", ".", "get", "(", "'since'", ")", ")", "request", ".", "set_param", "(", "'includeUnitsAvailable'", ",", "kwargs", ".", "get", "(", "'includeUnitsAvailable'", ")", ")", "request", ".", "set_param", "(", "'includeHomeConversions'", ",", "kwargs", ".", "get", "(", "'includeHomeConversions'", ")", ")", "response", "=", "self", ".", "ctx", ".", "request", "(", "request", ")", "if", "response", ".", "content_type", "is", "None", ":", "return", "response", "if", "not", "response", ".", "content_type", ".", "startswith", "(", "\"application/json\"", ")", ":", "return", "response", "jbody", "=", "json", ".", "loads", "(", "response", ".", "raw_body", ")", "parsed_body", "=", "{", "}", "#", "# Parse responses as defined by the API specification", "#", "if", "str", "(", "response", ".", "status", ")", "==", "\"200\"", ":", "if", "jbody", ".", "get", "(", "'prices'", ")", "is", "not", "None", ":", "parsed_body", "[", "'prices'", "]", "=", "[", "self", ".", "ctx", ".", "pricing", ".", "ClientPrice", ".", "from_dict", "(", "d", ",", "self", ".", "ctx", ")", "for", "d", "in", "jbody", ".", "get", "(", "'prices'", ")", "]", "if", "jbody", ".", "get", "(", "'homeConversions'", ")", "is", "not", "None", ":", "parsed_body", "[", "'homeConversions'", "]", "=", "[", "self", ".", "ctx", ".", "pricing", ".", "HomeConversions", ".", "from_dict", "(", "d", ",", "self", ".", "ctx", ")", "for", "d", "in", "jbody", ".", "get", "(", "'homeConversions'", ")", "]", "if", "jbody", ".", "get", "(", "'time'", ")", "is", "not", "None", ":", "parsed_body", "[", "'time'", "]", "=", "jbody", ".", "get", "(", "'time'", ")", "elif", "str", "(", "response", ".", "status", ")", "==", "\"400\"", ":", "if", "jbody", ".", "get", "(", "'errorCode'", ")", "is", "not", "None", ":", "parsed_body", "[", "'errorCode'", "]", "=", "jbody", ".", "get", "(", "'errorCode'", ")", "if", "jbody", ".", "get", "(", "'errorMessage'", ")", "is", "not", "None", ":", "parsed_body", "[", "'errorMessage'", "]", "=", "jbody", ".", "get", "(", "'errorMessage'", ")", "elif", "str", "(", "response", ".", "status", ")", "==", "\"401\"", ":", "if", "jbody", ".", "get", "(", "'errorCode'", ")", "is", "not", "None", ":", "parsed_body", "[", "'errorCode'", "]", "=", "jbody", ".", "get", "(", "'errorCode'", ")", "if", "jbody", ".", "get", "(", "'errorMessage'", ")", "is", "not", "None", ":", "parsed_body", "[", "'errorMessage'", "]", "=", "jbody", ".", "get", "(", "'errorMessage'", ")", "elif", "str", "(", "response", ".", "status", ")", "==", "\"404\"", ":", "if", "jbody", ".", "get", "(", "'errorCode'", ")", "is", "not", "None", ":", "parsed_body", "[", "'errorCode'", "]", "=", "jbody", ".", "get", "(", "'errorCode'", ")", "if", "jbody", ".", "get", "(", "'errorMessage'", ")", "is", "not", "None", ":", "parsed_body", "[", "'errorMessage'", "]", "=", "jbody", ".", "get", "(", "'errorMessage'", ")", "elif", "str", "(", "response", ".", "status", ")", "==", "\"405\"", ":", "if", "jbody", ".", "get", "(", "'errorCode'", ")", "is", "not", "None", ":", "parsed_body", "[", "'errorCode'", "]", "=", "jbody", ".", "get", "(", "'errorCode'", ")", "if", "jbody", ".", "get", "(", "'errorMessage'", ")", "is", "not", "None", ":", "parsed_body", "[", "'errorMessage'", "]", "=", "jbody", ".", "get", "(", "'errorMessage'", ")", "#", "# Unexpected response status", "#", "else", ":", "parsed_body", "=", "jbody", "response", ".", "body", "=", "parsed_body", "return", "response" ]
Add name variant .
def add_name_variant ( self , name ) : self . _ensure_field ( 'name' , { } ) self . obj [ 'name' ] . setdefault ( 'name_variants' , [ ] ) . append ( name )
3,854
https://github.com/inspirehep/inspire-schemas/blob/34bc124b62fba565b6b40d1a3c15103a23a05edb/inspire_schemas/builders/authors.py#L102-L110
[ "def", "_parse_path", "(", "self", ",", "path", ")", ":", "handle", ",", "path", "=", "self", ".", "_split_path", "(", "path", ")", "if", "self", ".", "_machine", "is", "not", "None", ":", "handle", "=", "self", ".", "_connect_hive", "(", "handle", ")", "return", "handle", ",", "path" ]
Add native name .
def add_native_name ( self , name ) : self . _ensure_field ( 'name' , { } ) self . obj [ 'name' ] . setdefault ( 'native_names' , [ ] ) . append ( name )
3,855
https://github.com/inspirehep/inspire-schemas/blob/34bc124b62fba565b6b40d1a3c15103a23a05edb/inspire_schemas/builders/authors.py#L113-L121
[ "def", "OnAdjustVolume", "(", "self", ",", "event", ")", ":", "self", ".", "volume", "=", "self", ".", "player", ".", "audio_get_volume", "(", ")", "if", "event", ".", "GetWheelRotation", "(", ")", "<", "0", ":", "self", ".", "volume", "=", "max", "(", "0", ",", "self", ".", "volume", "-", "10", ")", "elif", "event", ".", "GetWheelRotation", "(", ")", ">", "0", ":", "self", ".", "volume", "=", "min", "(", "200", ",", "self", ".", "volume", "+", "10", ")", "self", ".", "player", ".", "audio_set_volume", "(", "self", ".", "volume", ")" ]
Add previous name .
def add_previous_name ( self , name ) : self . _ensure_field ( 'name' , { } ) self . obj [ 'name' ] . setdefault ( 'previous_names' , [ ] ) . append ( name )
3,856
https://github.com/inspirehep/inspire-schemas/blob/34bc124b62fba565b6b40d1a3c15103a23a05edb/inspire_schemas/builders/authors.py#L124-L132
[ "def", "OnAdjustVolume", "(", "self", ",", "event", ")", ":", "self", ".", "volume", "=", "self", ".", "player", ".", "audio_get_volume", "(", ")", "if", "event", ".", "GetWheelRotation", "(", ")", "<", "0", ":", "self", ".", "volume", "=", "max", "(", "0", ",", "self", ".", "volume", "-", "10", ")", "elif", "event", ".", "GetWheelRotation", "(", ")", ">", "0", ":", "self", ".", "volume", "=", "min", "(", "200", ",", "self", ".", "volume", "+", "10", ")", "self", ".", "player", ".", "audio_set_volume", "(", "self", ".", "volume", ")" ]
Add email address .
def add_email_address ( self , email , hidden = None ) : existing_emails = get_value ( self . obj , 'email_addresses' , [ ] ) found_email = next ( ( existing_email for existing_email in existing_emails if existing_email . get ( 'value' ) == email ) , None ) if found_email is None : new_email = { 'value' : email } if hidden is not None : new_email [ 'hidden' ] = hidden self . _append_to ( 'email_addresses' , new_email ) elif hidden is not None : found_email [ 'hidden' ] = hidden
3,857
https://github.com/inspirehep/inspire-schemas/blob/34bc124b62fba565b6b40d1a3c15103a23a05edb/inspire_schemas/builders/authors.py#L135-L156
[ "def", "_generate_noise_system", "(", "dimensions_tr", ",", "spatial_sd", ",", "temporal_sd", ",", "spatial_noise_type", "=", "'gaussian'", ",", "temporal_noise_type", "=", "'gaussian'", ",", ")", ":", "def", "noise_volume", "(", "dimensions", ",", "noise_type", ",", ")", ":", "if", "noise_type", "==", "'rician'", ":", "# Generate the Rician noise (has an SD of 1)", "noise", "=", "stats", ".", "rice", ".", "rvs", "(", "b", "=", "0", ",", "loc", "=", "0", ",", "scale", "=", "1.527", ",", "size", "=", "dimensions", ")", "elif", "noise_type", "==", "'exponential'", ":", "# Make an exponential distribution (has an SD of 1)", "noise", "=", "stats", ".", "expon", ".", "rvs", "(", "0", ",", "scale", "=", "1", ",", "size", "=", "dimensions", ")", "elif", "noise_type", "==", "'gaussian'", ":", "noise", "=", "np", ".", "random", ".", "randn", "(", "np", ".", "prod", "(", "dimensions", ")", ")", ".", "reshape", "(", "dimensions", ")", "# Return the noise", "return", "noise", "# Get just the xyz coordinates", "dimensions", "=", "np", ".", "asarray", "(", "[", "dimensions_tr", "[", "0", "]", ",", "dimensions_tr", "[", "1", "]", ",", "dimensions_tr", "[", "2", "]", ",", "1", "]", ")", "# Generate noise", "spatial_noise", "=", "noise_volume", "(", "dimensions", ",", "spatial_noise_type", ")", "temporal_noise", "=", "noise_volume", "(", "dimensions_tr", ",", "temporal_noise_type", ")", "# Make the system noise have a specific spatial variability", "spatial_noise", "*=", "spatial_sd", "# Set the size of the noise", "temporal_noise", "*=", "temporal_sd", "# The mean in time of system noise needs to be zero, so subtract the", "# means of the temporal noise in time", "temporal_noise_mean", "=", "np", ".", "mean", "(", "temporal_noise", ",", "3", ")", ".", "reshape", "(", "dimensions", "[", "0", "]", ",", "dimensions", "[", "1", "]", ",", "dimensions", "[", "2", "]", ",", "1", ")", "temporal_noise", "=", "temporal_noise", "-", "temporal_noise_mean", "# Save the combination", "system_noise", "=", "spatial_noise", "+", "temporal_noise", "return", "system_noise" ]
Add a personal website .
def add_url ( self , url , description = None ) : url = { 'value' : url , } if description : url [ 'description' ] = description self . _append_to ( 'urls' , url )
3,858
https://github.com/inspirehep/inspire-schemas/blob/34bc124b62fba565b6b40d1a3c15103a23a05edb/inspire_schemas/builders/authors.py#L169-L184
[ "def", "union", "(", "self", ",", "*", "dstreams", ")", ":", "if", "not", "dstreams", ":", "raise", "ValueError", "(", "\"should have at least one DStream to union\"", ")", "if", "len", "(", "dstreams", ")", "==", "1", ":", "return", "dstreams", "[", "0", "]", "if", "len", "(", "set", "(", "s", ".", "_jrdd_deserializer", "for", "s", "in", "dstreams", ")", ")", ">", "1", ":", "raise", "ValueError", "(", "\"All DStreams should have same serializer\"", ")", "if", "len", "(", "set", "(", "s", ".", "_slideDuration", "for", "s", "in", "dstreams", ")", ")", ">", "1", ":", "raise", "ValueError", "(", "\"All DStreams should have same slide duration\"", ")", "cls", "=", "SparkContext", ".", "_jvm", ".", "org", ".", "apache", ".", "spark", ".", "streaming", ".", "api", ".", "java", ".", "JavaDStream", "jdstreams", "=", "SparkContext", ".", "_gateway", ".", "new_array", "(", "cls", ",", "len", "(", "dstreams", ")", ")", "for", "i", "in", "range", "(", "0", ",", "len", "(", "dstreams", ")", ")", ":", "jdstreams", "[", "i", "]", "=", "dstreams", "[", "i", "]", ".", "_jdstream", "return", "DStream", "(", "self", ".", "_jssc", ".", "union", "(", "jdstreams", ")", ",", "self", ",", "dstreams", "[", "0", "]", ".", "_jrdd_deserializer", ")" ]
Add an experiment that the person worked on .
def add_project ( self , name , record = None , start_date = None , end_date = None , curated = False , current = False ) : new_experiment = { } new_experiment [ 'name' ] = name if start_date : new_experiment [ 'start_date' ] = normalize_date ( start_date ) if end_date : new_experiment [ 'end_date' ] = normalize_date ( end_date ) if record : new_experiment [ 'record' ] = record new_experiment [ 'curated_relation' ] = curated new_experiment [ 'current' ] = current self . _append_to ( 'project_membership' , new_experiment ) self . obj [ 'project_membership' ] . sort ( key = self . _get_work_priority_tuple , reverse = True )
3,859
https://github.com/inspirehep/inspire-schemas/blob/34bc124b62fba565b6b40d1a3c15103a23a05edb/inspire_schemas/builders/authors.py#L306-L339
[ "def", "delete_container_service", "(", "access_token", ",", "subscription_id", ",", "resource_group", ",", "service_name", ")", ":", "endpoint", "=", "''", ".", "join", "(", "[", "get_rm_endpoint", "(", ")", ",", "'/subscriptions/'", ",", "subscription_id", ",", "'/resourcegroups/'", ",", "resource_group", ",", "'/providers/Microsoft.ContainerService/ContainerServices/'", ",", "service_name", ",", "'?api-version='", ",", "ACS_API", "]", ")", "return", "do_delete", "(", "endpoint", ",", "access_token", ")" ]
Add an advisor .
def add_advisor ( self , name , ids = None , degree_type = None , record = None , curated = False ) : new_advisor = { } new_advisor [ 'name' ] = normalize_name ( name ) if ids : new_advisor [ 'ids' ] = force_list ( ids ) if degree_type : new_advisor [ 'degree_type' ] = degree_type if record : new_advisor [ 'record' ] = record new_advisor [ 'curated_relation' ] = curated self . _append_to ( 'advisors' , new_advisor )
3,860
https://github.com/inspirehep/inspire-schemas/blob/34bc124b62fba565b6b40d1a3c15103a23a05edb/inspire_schemas/builders/authors.py#L350-L378
[ "async", "def", "delete_sticker_from_set", "(", "self", ",", "sticker", ":", "base", ".", "String", ")", "->", "base", ".", "Boolean", ":", "payload", "=", "generate_payload", "(", "*", "*", "locals", "(", ")", ")", "result", "=", "await", "self", ".", "request", "(", "api", ".", "Methods", ".", "DELETE_STICKER_FROM_SET", ",", "payload", ")", "return", "result" ]
Add a private note .
def add_private_note ( self , note , source = None ) : note = { 'value' : note , } if source : note [ 'source' ] = source self . _append_to ( '_private_notes' , note )
3,861
https://github.com/inspirehep/inspire-schemas/blob/34bc124b62fba565b6b40d1a3c15103a23a05edb/inspire_schemas/builders/authors.py#L381-L396
[ "def", "configure", "(", "self", ",", "organization", ",", "base_url", "=", "''", ",", "ttl", "=", "''", ",", "max_ttl", "=", "''", ",", "mount_point", "=", "DEFAULT_MOUNT_POINT", ")", ":", "params", "=", "{", "'organization'", ":", "organization", ",", "'base_url'", ":", "base_url", ",", "'ttl'", ":", "ttl", ",", "'max_ttl'", ":", "max_ttl", ",", "}", "api_path", "=", "'/v1/auth/{mount_point}/config'", ".", "format", "(", "mount_point", "=", "mount_point", ")", "return", "self", ".", "_adapter", ".", "post", "(", "url", "=", "api_path", ",", "json", "=", "params", ",", ")" ]
Return the weight corresponding to single power .
def _compute_value ( power , wg ) : if power not in wg : p1 , p2 = power # y power if p1 == 0 : yy = wg [ ( 0 , - 1 ) ] wg [ power ] = numpy . power ( yy , p2 / 2 ) . sum ( ) / len ( yy ) # x power else : xx = wg [ ( - 1 , 0 ) ] wg [ power ] = numpy . power ( xx , p1 / 2 ) . sum ( ) / len ( xx ) return wg [ power ]
3,862
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/imsurfit.py#L25-L37
[ "def", "_parse", "(", "self", ",", "roi", "=", "None", ",", "filenames", "=", "None", ")", ":", "if", "(", "roi", "is", "not", "None", ")", "and", "(", "filenames", "is", "not", "None", ")", ":", "msg", "=", "\"Cannot take both roi and filenames\"", "raise", "Exception", "(", "msg", ")", "if", "roi", "is", "not", "None", ":", "pixels", "=", "roi", ".", "getCatalogPixels", "(", ")", "filenames", "=", "self", ".", "config", ".", "getFilenames", "(", ")", "[", "'catalog'", "]", "[", "pixels", "]", "elif", "filenames", "is", "None", ":", "filenames", "=", "self", ".", "config", ".", "getFilenames", "(", ")", "[", "'catalog'", "]", ".", "compressed", "(", ")", "else", ":", "filenames", "=", "np", ".", "atleast_1d", "(", "filenames", ")", "if", "len", "(", "filenames", ")", "==", "0", ":", "msg", "=", "\"No catalog files found.\"", "raise", "Exception", "(", "msg", ")", "# Load the data", "self", ".", "data", "=", "load_infiles", "(", "filenames", ")", "# Apply a selection cut", "self", ".", "_applySelection", "(", ")", "# Cast data to recarray (historical reasons)", "self", ".", "data", "=", "self", ".", "data", ".", "view", "(", "np", ".", "recarray", ")" ]
Return the weight corresponding to given powers .
def _compute_weight ( powers , wg ) : # split pow1 = ( powers [ 0 ] , 0 ) pow2 = ( 0 , powers [ 1 ] ) cal1 = _compute_value ( pow1 , wg ) cal2 = _compute_value ( pow2 , wg ) return cal1 * cal2
3,863
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/imsurfit.py#L40-L49
[ "def", "_parse", "(", "self", ",", "roi", "=", "None", ",", "filenames", "=", "None", ")", ":", "if", "(", "roi", "is", "not", "None", ")", "and", "(", "filenames", "is", "not", "None", ")", ":", "msg", "=", "\"Cannot take both roi and filenames\"", "raise", "Exception", "(", "msg", ")", "if", "roi", "is", "not", "None", ":", "pixels", "=", "roi", ".", "getCatalogPixels", "(", ")", "filenames", "=", "self", ".", "config", ".", "getFilenames", "(", ")", "[", "'catalog'", "]", "[", "pixels", "]", "elif", "filenames", "is", "None", ":", "filenames", "=", "self", ".", "config", ".", "getFilenames", "(", ")", "[", "'catalog'", "]", ".", "compressed", "(", ")", "else", ":", "filenames", "=", "np", ".", "atleast_1d", "(", "filenames", ")", "if", "len", "(", "filenames", ")", "==", "0", ":", "msg", "=", "\"No catalog files found.\"", "raise", "Exception", "(", "msg", ")", "# Load the data", "self", ".", "data", "=", "load_infiles", "(", "filenames", ")", "# Apply a selection cut", "self", ".", "_applySelection", "(", ")", "# Cast data to recarray (historical reasons)", "self", ".", "data", "=", "self", ".", "data", ".", "view", "(", "np", ".", "recarray", ")" ]
Fit a bidimensional polynomial to an image .
def imsurfit ( data , order , output_fit = False ) : # we create a grid with the same number of points # between -1 and 1 c0 = complex ( 0 , data . shape [ 0 ] ) c1 = complex ( 0 , data . shape [ 1 ] ) xx , yy = numpy . ogrid [ - 1 : 1 : c0 , - 1 : 1 : c1 ] ncoeff = ( order + 1 ) * ( order + 2 ) // 2 powerlist = list ( _powers ( order ) ) # Array with ncoff x,y moments of the data bb = numpy . zeros ( ncoeff ) # Moments for idx , powers in enumerate ( powerlist ) : p1 , p2 = powers bb [ idx ] = ( data * xx ** p1 * yy ** p2 ) . sum ( ) / data . size # Now computing aa matrix # it contains \sum x^a y^b # most of the terms are zero # only those with a and b even remain # aa is symmetric x = xx [ : , 0 ] y = yy [ 0 ] # weights are stored so we compute them only once wg = { ( 0 , 0 ) : 1 , ( - 1 , 0 ) : x ** 2 , ( 0 , - 1 ) : y ** 2 } # wg[(2,0)] = wg[(-1,0)].sum() / len(x) # wg[(0,2)] = wg[(0,-1)].sum() / len(y) aa = numpy . zeros ( ( ncoeff , ncoeff ) ) for j , ci in enumerate ( powerlist ) : for i , ri in enumerate ( powerlist [ j : ] ) : p1 = ci [ 0 ] + ri [ 0 ] p2 = ci [ 1 ] + ri [ 1 ] if p1 % 2 == 0 and p2 % 2 == 0 : # val = (x ** p1).sum() / len(x) * (y ** p2).sum() / len(y) val = _compute_weight ( ( p1 , p2 ) , wg ) aa [ j , i + j ] = val # Making symmetric the array aa += numpy . triu ( aa , k = 1 ) . T polycoeff = numpy . linalg . solve ( aa , bb ) if output_fit : index = 0 result = 0 for o in range ( order + 1 ) : for b in range ( o + 1 ) : a = o - b result += polycoeff [ index ] * ( xx ** a ) * ( yy ** b ) index += 1 return polycoeff , result return ( polycoeff , )
3,864
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/imsurfit.py#L52-L125
[ "def", "is_registration_possible", "(", "self", ",", "user_info", ")", ":", "return", "self", ".", "get_accessibility", "(", ")", ".", "is_open", "(", ")", "and", "self", ".", "_registration", ".", "is_open", "(", ")", "and", "self", ".", "is_user_accepted_by_access_control", "(", "user_info", ")" ]
Fetch data from Yahoo! Return a dict if successfull or None .
def _yql_query ( yql ) : url = _YAHOO_BASE_URL . format ( urlencode ( { 'q' : yql } ) ) # send request _LOGGER . debug ( "Send request to url: %s" , url ) try : request = urlopen ( url ) rawData = request . read ( ) # parse jason data = json . loads ( rawData . decode ( "utf-8" ) ) _LOGGER . debug ( "Query data from yahoo: %s" , str ( data ) ) return data . get ( "query" , { } ) . get ( "results" , { } ) except ( urllib . error . HTTPError , urllib . error . URLError ) : _LOGGER . info ( "Can't fetch data from Yahoo!" ) return None
3,865
https://github.com/pvizeli/yahooweather/blob/42e59510fc20b84afc8efadfbc3a30c15675b327/yahooweather.py#L22-L41
[ "def", "create_binding", "(", "self", ",", "vhost", ",", "exchange", ",", "queue", ",", "rt_key", "=", "None", ",", "args", "=", "None", ")", ":", "vhost", "=", "quote", "(", "vhost", ",", "''", ")", "exchange", "=", "quote", "(", "exchange", ",", "''", ")", "queue", "=", "quote", "(", "queue", ",", "''", ")", "body", "=", "json", ".", "dumps", "(", "{", "'routing_key'", ":", "rt_key", ",", "'arguments'", ":", "args", "or", "[", "]", "}", ")", "path", "=", "Client", ".", "urls", "[", "'bindings_between_exch_queue'", "]", "%", "(", "vhost", ",", "exchange", ",", "queue", ")", "binding", "=", "self", ".", "_call", "(", "path", ",", "'POST'", ",", "body", "=", "body", ",", "headers", "=", "Client", ".", "json_headers", ")", "return", "binding" ]
Ask Yahoo! who is the woeid from GPS position .
def get_woeid ( lat , lon ) : yql = _YQL_WOEID . format ( lat , lon ) # send request tmpData = _yql_query ( yql ) if tmpData is None : _LOGGER . error ( "No woid is received!" ) return None # found woid? return tmpData . get ( "place" , { } ) . get ( "woeid" , None )
3,866
https://github.com/pvizeli/yahooweather/blob/42e59510fc20b84afc8efadfbc3a30c15675b327/yahooweather.py#L44-L56
[ "def", "get_covariance_table", "(", "self", ",", "chain", "=", "0", ",", "parameters", "=", "None", ",", "caption", "=", "\"Parameter Covariance\"", ",", "label", "=", "\"tab:parameter_covariance\"", ")", ":", "parameters", ",", "cov", "=", "self", ".", "get_covariance", "(", "chain", "=", "chain", ",", "parameters", "=", "parameters", ")", "return", "self", ".", "_get_2d_latex_table", "(", "parameters", ",", "cov", ",", "caption", ",", "label", ")" ]
Fetch weather data from Yahoo! True if success .
def updateWeather ( self ) : yql = _YQL_WEATHER . format ( self . _woeid , self . _unit ) # send request tmpData = _yql_query ( yql ) # data exists if tmpData is not None and "channel" in tmpData : self . _data = tmpData [ "channel" ] return True _LOGGER . error ( "Fetch no weather data Yahoo!" ) self . _data = { } return False
3,867
https://github.com/pvizeli/yahooweather/blob/42e59510fc20b84afc8efadfbc3a30c15675b327/yahooweather.py#L68-L82
[ "def", "create_binding", "(", "self", ",", "vhost", ",", "exchange", ",", "queue", ",", "rt_key", "=", "None", ",", "args", "=", "None", ")", ":", "vhost", "=", "quote", "(", "vhost", ",", "''", ")", "exchange", "=", "quote", "(", "exchange", ",", "''", ")", "queue", "=", "quote", "(", "queue", ",", "''", ")", "body", "=", "json", ".", "dumps", "(", "{", "'routing_key'", ":", "rt_key", ",", "'arguments'", ":", "args", "or", "[", "]", "}", ")", "path", "=", "Client", ".", "urls", "[", "'bindings_between_exch_queue'", "]", "%", "(", "vhost", ",", "exchange", ",", "queue", ")", "binding", "=", "self", ".", "_call", "(", "path", ",", "'POST'", ",", "body", "=", "body", ",", "headers", "=", "Client", ".", "json_headers", ")", "return", "binding" ]
Potential energy for a list of atoms objects
def get_energies ( atoms_list ) : if len ( atoms_list ) == 1 : return atoms_list [ 0 ] . get_potential_energy ( ) elif len ( atoms_list ) > 1 : energies = [ ] for atoms in atoms_list : energies . append ( atoms . get_potential_energy ( ) ) return energies
3,868
https://github.com/SUNCAT-Center/CatHub/blob/324625d1d8e740673f139658b2de4c9e1059739e/cathub/ase_tools/__init__.py#L174-L182
[ "def", "logout", "(", "self", ")", ":", "# Check if all transfers are complete before logout", "self", ".", "transfers_complete", "payload", "=", "{", "'apikey'", ":", "self", ".", "config", ".", "get", "(", "'apikey'", ")", ",", "'logintoken'", ":", "self", ".", "session", ".", "cookies", ".", "get", "(", "'logintoken'", ")", "}", "method", ",", "url", "=", "get_URL", "(", "'logout'", ")", "res", "=", "getattr", "(", "self", ".", "session", ",", "method", ")", "(", "url", ",", "params", "=", "payload", ")", "if", "res", ".", "status_code", "==", "200", ":", "self", ".", "session", ".", "cookies", "[", "'logintoken'", "]", "=", "None", "return", "True", "hellraiser", "(", "res", ")" ]
Check if entry is allready in ASE db
def check_in_ase ( atoms , ase_db , energy = None ) : db_ase = ase . db . connect ( ase_db ) if energy is None : energy = atoms . get_potential_energy ( ) formula = get_chemical_formula ( atoms ) rows = db_ase . select ( energy = energy ) n = 0 ids = [ ] for row in rows : if formula == row . formula : n += 1 ids . append ( row . id ) if n > 0 : id = ids [ 0 ] unique_id = db_ase . get ( id ) [ 'unique_id' ] return id , unique_id else : return None , None
3,869
https://github.com/SUNCAT-Center/CatHub/blob/324625d1d8e740673f139658b2de4c9e1059739e/cathub/ase_tools/__init__.py#L322-L341
[ "def", "write", "(", "self", ",", "filename", ",", "filetype", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "filetype", "is", "not", "None", ":", "filetype", "=", "filetype", ".", "lower", "(", ")", "else", ":", "filetype", "=", "self", ".", "_guess_file_type", "(", "filename", ")", "if", "filetype", "==", "'fits'", ":", "from", ".", "io", ".", "fits", "import", "write_moc_fits", "write_moc_fits", "(", "self", ",", "filename", ",", "*", "*", "kwargs", ")", "elif", "filetype", "==", "'json'", ":", "from", ".", "io", ".", "json", "import", "write_moc_json", "write_moc_json", "(", "self", ",", "filename", ",", "*", "*", "kwargs", ")", "elif", "filetype", "==", "'ascii'", "or", "filetype", "==", "'text'", ":", "from", ".", "io", ".", "ascii", "import", "write_moc_ascii", "write_moc_ascii", "(", "self", ",", "filename", ",", "*", "*", "kwargs", ")", "else", ":", "raise", "ValueError", "(", "'Unknown MOC file type {0}'", ".", "format", "(", "filetype", ")", ")" ]
Define a new task .
def task ( name , deps = None , fn = None ) : if callable ( deps ) : fn = deps deps = None if not deps and not fn : logger . log ( logger . red ( "The task '%s' is empty" % name ) ) else : tasks [ name ] = [ fn , deps ]
3,870
https://github.com/pylp/pylp/blob/7ebaa55fbaf61cb8175f211dd41ef2928c22d4d4/pylp/lib/tasks.py#L18-L27
[ "def", "_device_expiry_callback", "(", "self", ")", ":", "expired", "=", "0", "for", "adapters", "in", "self", ".", "_devices", ".", "values", "(", ")", ":", "to_remove", "=", "[", "]", "now", "=", "monotonic", "(", ")", "for", "adapter_id", ",", "dev", "in", "adapters", ".", "items", "(", ")", ":", "if", "'expires'", "not", "in", "dev", ":", "continue", "if", "now", ">", "dev", "[", "'expires'", "]", ":", "to_remove", ".", "append", "(", "adapter_id", ")", "local_conn", "=", "\"adapter/%d/%s\"", "%", "(", "adapter_id", ",", "dev", "[", "'connection_string'", "]", ")", "if", "local_conn", "in", "self", ".", "_conn_strings", ":", "del", "self", ".", "_conn_strings", "[", "local_conn", "]", "for", "entry", "in", "to_remove", ":", "del", "adapters", "[", "entry", "]", "expired", "+=", "1", "if", "expired", ">", "0", ":", "self", ".", "_logger", ".", "info", "(", "'Expired %d devices'", ",", "expired", ")" ]
Return a model of the sum of N Gaussians and a constant background .
def sum_of_gaussian_factory ( N ) : name = "SumNGauss%d" % N attr = { } # parameters for i in range ( N ) : key = "amplitude_%d" % i attr [ key ] = Parameter ( key ) key = "center_%d" % i attr [ key ] = Parameter ( key ) key = "stddev_%d" % i attr [ key ] = Parameter ( key ) attr [ 'background' ] = Parameter ( 'background' , default = 0.0 ) def fit_eval ( self , x , * args ) : result = x * 0 + args [ - 1 ] for i in range ( N ) : result += args [ 3 * i ] * np . exp ( - 0.5 * ( x - args [ 3 * i + 1 ] ) ** 2 / args [ 3 * i + 2 ] ** 2 ) return result attr [ 'evaluate' ] = fit_eval def deriv ( self , x , * args ) : d_result = np . ones ( ( ( 3 * N + 1 ) , len ( x ) ) ) for i in range ( N ) : d_result [ 3 * i ] = ( np . exp ( - 0.5 / args [ 3 * i + 2 ] ** 2 * ( x - args [ 3 * i + 1 ] ) ** 2 ) ) d_result [ 3 * i + 1 ] = args [ 3 * i ] * d_result [ 3 * i ] * ( x - args [ 3 * i + 1 ] ) / args [ 3 * i + 2 ] ** 2 d_result [ 3 * i + 2 ] = args [ 3 * i ] * d_result [ 3 * i ] * ( x - args [ 3 * i + 1 ] ) ** 2 / args [ 3 * i + 2 ] ** 3 return d_result attr [ 'fit_deriv' ] = deriv klass = type ( name , ( Fittable1DModel , ) , attr ) return klass
3,871
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/modeling/sumofgauss.py#L14-L56
[ "def", "_update_job_info", "(", "cls", ",", "job_dir", ")", ":", "meta_file", "=", "os", ".", "path", ".", "join", "(", "job_dir", ",", "JOB_META_FILE", ")", "meta", "=", "parse_json", "(", "meta_file", ")", "if", "meta", ":", "logging", ".", "debug", "(", "\"Update job info for %s\"", "%", "meta", "[", "\"job_id\"", "]", ")", "JobRecord", ".", "objects", ".", "filter", "(", "job_id", "=", "meta", "[", "\"job_id\"", "]", ")", ".", "update", "(", "end_time", "=", "timestamp2date", "(", "meta", "[", "\"end_time\"", "]", ")", ")" ]
Simple debouncing decorator for apigpio callbacks .
def Debounce ( threshold = 100 ) : threshold *= 1000 max_tick = 0xFFFFFFFF class _decorated ( object ) : def __init__ ( self , pigpio_cb ) : self . _fn = pigpio_cb self . last = 0 self . is_method = False def __call__ ( self , * args , * * kwargs ) : if self . is_method : tick = args [ 3 ] else : tick = args [ 2 ] if self . last > tick : delay = max_tick - self . last + tick else : delay = tick - self . last if delay > threshold : self . _fn ( * args , * * kwargs ) print ( 'call passed by debouncer {} {} {}' . format ( tick , self . last , threshold ) ) self . last = tick else : print ( 'call filtered out by debouncer {} {} {}' . format ( tick , self . last , threshold ) ) def __get__ ( self , instance , type = None ) : # with is called when an instance of `_decorated` is used as a class # attribute, which is the case when decorating a method in a class self . is_method = True return functools . partial ( self , instance ) return _decorated
3,872
https://github.com/PierreRust/apigpio/blob/2b969f40e06219b43a43498d8baf87f5935ceab2/apigpio/utils.py#L4-L56
[ "def", "CleanClientVersions", "(", "clients", "=", "None", ",", "dry_run", "=", "True", ",", "token", "=", "None", ")", ":", "if", "not", "clients", ":", "index", "=", "client_index", ".", "CreateClientIndex", "(", "token", "=", "token", ")", "clients", "=", "index", ".", "LookupClients", "(", "[", "\".\"", "]", ")", "clients", ".", "sort", "(", ")", "with", "data_store", ".", "DB", ".", "GetMutationPool", "(", ")", "as", "pool", ":", "logging", ".", "info", "(", "\"checking %d clients\"", ",", "len", "(", "clients", ")", ")", "# TODO(amoser): This only works on datastores that use the Bigtable scheme.", "client_infos", "=", "data_store", ".", "DB", ".", "MultiResolvePrefix", "(", "clients", ",", "\"aff4:type\"", ",", "data_store", ".", "DB", ".", "ALL_TIMESTAMPS", ")", "for", "client", ",", "type_list", "in", "client_infos", ":", "logging", ".", "info", "(", "\"%s: has %d versions\"", ",", "client", ",", "len", "(", "type_list", ")", ")", "cleared", "=", "0", "kept", "=", "1", "last_kept", "=", "type_list", "[", "0", "]", "[", "2", "]", "for", "_", ",", "_", ",", "ts", "in", "type_list", "[", "1", ":", "]", ":", "if", "last_kept", "-", "ts", ">", "60", "*", "60", "*", "1000000", ":", "# 1 hour", "last_kept", "=", "ts", "kept", "+=", "1", "else", ":", "if", "not", "dry_run", ":", "pool", ".", "DeleteAttributes", "(", "client", ",", "[", "\"aff4:type\"", "]", ",", "start", "=", "ts", ",", "end", "=", "ts", ")", "cleared", "+=", "1", "if", "pool", ".", "Size", "(", ")", ">", "10000", ":", "pool", ".", "Flush", "(", ")", "logging", ".", "info", "(", "\"%s: kept %d and cleared %d\"", ",", "client", ",", "kept", ",", "cleared", ")" ]
Wrapper around JWTIdentityPolicy . verify_refresh which verify if the request to refresh the token is valid . If valid it returns the userid which can be used to create to create an updated identity with remember_identity . Otherwise it raises an exception based on InvalidTokenError .
def verify_refresh_request ( request ) : jwtauth_settings = request . app . settings . jwtauth . __dict__ . copy ( ) identity_policy = JWTIdentityPolicy ( * * jwtauth_settings ) return identity_policy . verify_refresh ( request )
3,873
https://github.com/morepath/more.jwtauth/blob/1c3c5731612069a092e44cf612641c05edf1f083/more/jwtauth/refresh.py#L4-L21
[ "def", "get_hist", "(", "self", ",", "observable", ":", "Any", ",", "*", "*", "kwargs", ":", "Dict", "[", "str", ",", "Any", "]", ")", "->", "Any", ":", "return", "observable" ]
Compute a baseline trend of a signal
def detrend ( arr , x = None , deg = 5 , tol = 1e-3 , maxloop = 10 ) : xx = numpy . arange ( len ( arr ) ) if x is None else x base = arr . copy ( ) trend = base pol = numpy . ones ( ( deg + 1 , ) ) for _ in range ( maxloop ) : pol_new = numpy . polyfit ( xx , base , deg ) pol_norm = numpy . linalg . norm ( pol ) diff_pol_norm = numpy . linalg . norm ( pol - pol_new ) if diff_pol_norm / pol_norm < tol : break pol = pol_new trend = numpy . polyval ( pol , xx ) base = numpy . minimum ( base , trend ) return trend
3,874
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/peaks/detrend.py#L13-L29
[ "def", "_swap_rows", "(", "self", ",", "i", ",", "j", ")", ":", "L", "=", "np", ".", "eye", "(", "3", ",", "dtype", "=", "'intc'", ")", "L", "[", "i", ",", "i", "]", "=", "0", "L", "[", "j", ",", "j", "]", "=", "0", "L", "[", "i", ",", "j", "]", "=", "1", "L", "[", "j", ",", "i", "]", "=", "1", "self", ".", "_L", ".", "append", "(", "L", ".", "copy", "(", ")", ")", "self", ".", "_A", "=", "np", ".", "dot", "(", "L", ",", "self", ".", "_A", ")" ]
Compute the pseudo - acceleration spectral response of an oscillator with a specific frequency and damping .
def calc_osc_accels ( self , osc_freqs , osc_damping = 0.05 , tf = None ) : if tf is None : tf = np . ones_like ( self . freqs ) else : tf = np . asarray ( tf ) . astype ( complex ) resp = np . array ( [ self . calc_peak ( tf * self . _calc_sdof_tf ( of , osc_damping ) ) for of in osc_freqs ] ) return resp
3,875
https://github.com/arkottke/pysra/blob/c72fd389d6c15203c0c00728ac00f101bae6369d/pysra/motion.py#L141-L170
[ "def", "get_hostname", "(", "cls", ",", "container_name", ",", "client_name", "=", "None", ")", ":", "base_name", "=", "container_name", "for", "old", ",", "new", "in", "cls", ".", "hostname_replace", ":", "base_name", "=", "base_name", ".", "replace", "(", "old", ",", "new", ")", "if", "not", "client_name", "or", "client_name", "==", "cls", ".", "default_client_name", ":", "return", "base_name", "client_suffix", "=", "client_name", "for", "old", ",", "new", "in", "cls", ".", "hostname_replace", ":", "client_suffix", "=", "client_suffix", ".", "replace", "(", "old", ",", "new", ")", "return", "'{0}-{1}'", ".", "format", "(", "base_name", ",", "client_suffix", ")" ]
Compute the Fourier Amplitude Spectrum of the time series .
def _calc_fourier_spectrum ( self , fa_length = None ) : if fa_length is None : # Use the next power of 2 for the length n = 1 while n < self . accels . size : n <<= 1 else : n = fa_length self . _fourier_amps = np . fft . rfft ( self . _accels , n ) freq_step = 1. / ( 2 * self . _time_step * ( n / 2 ) ) self . _freqs = freq_step * np . arange ( 1 + n / 2 )
3,876
https://github.com/arkottke/pysra/blob/c72fd389d6c15203c0c00728ac00f101bae6369d/pysra/motion.py#L172-L186
[ "def", "filter_grounded_only", "(", "stmts_in", ",", "*", "*", "kwargs", ")", ":", "remove_bound", "=", "kwargs", ".", "get", "(", "'remove_bound'", ",", "False", ")", "logger", ".", "info", "(", "'Filtering %d statements for grounded agents...'", "%", "len", "(", "stmts_in", ")", ")", "stmts_out", "=", "[", "]", "score_threshold", "=", "kwargs", ".", "get", "(", "'score_threshold'", ")", "for", "st", "in", "stmts_in", ":", "grounded", "=", "True", "for", "agent", "in", "st", ".", "agent_list", "(", ")", ":", "if", "agent", "is", "not", "None", ":", "criterion", "=", "lambda", "x", ":", "_agent_is_grounded", "(", "x", ",", "score_threshold", ")", "if", "not", "criterion", "(", "agent", ")", ":", "grounded", "=", "False", "break", "if", "not", "isinstance", "(", "agent", ",", "Agent", ")", ":", "continue", "if", "remove_bound", ":", "_remove_bound_conditions", "(", "agent", ",", "criterion", ")", "elif", "_any_bound_condition_fails_criterion", "(", "agent", ",", "criterion", ")", ":", "grounded", "=", "False", "break", "if", "grounded", ":", "stmts_out", ".", "append", "(", "st", ")", "logger", ".", "info", "(", "'%d statements after filter...'", "%", "len", "(", "stmts_out", ")", ")", "dump_pkl", "=", "kwargs", ".", "get", "(", "'save'", ")", "if", "dump_pkl", ":", "dump_statements", "(", "stmts_out", ",", "dump_pkl", ")", "return", "stmts_out" ]
Compute the transfer function for a single - degree - of - freedom oscillator .
def _calc_sdof_tf ( self , osc_freq , damping = 0.05 ) : return ( - osc_freq ** 2. / ( np . square ( self . freqs ) - np . square ( osc_freq ) - 2.j * damping * osc_freq * self . freqs ) )
3,877
https://github.com/arkottke/pysra/blob/c72fd389d6c15203c0c00728ac00f101bae6369d/pysra/motion.py#L188-L208
[ "def", "s3_connection", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'cached_connection'", ")", ":", "self", ".", "check_prerequisites", "(", ")", "with", "PatchedBotoConfig", "(", ")", ":", "import", "boto", "from", "boto", ".", "exception", "import", "BotoClientError", ",", "BotoServerError", ",", "NoAuthHandlerFound", "from", "boto", ".", "s3", ".", "connection", "import", "S3Connection", ",", "SubdomainCallingFormat", ",", "OrdinaryCallingFormat", "try", ":", "# Configure the number of retries and the socket timeout used", "# by Boto. Based on the snippet given in the following email:", "# https://groups.google.com/d/msg/boto-users/0osmP0cUl5Y/X4NdlMGWKiEJ", "if", "not", "boto", ".", "config", ".", "has_section", "(", "BOTO_CONFIG_SECTION", ")", ":", "boto", ".", "config", ".", "add_section", "(", "BOTO_CONFIG_SECTION", ")", "boto", ".", "config", ".", "set", "(", "BOTO_CONFIG_SECTION", ",", "BOTO_CONFIG_NUM_RETRIES_OPTION", ",", "str", "(", "self", ".", "config", ".", "s3_cache_retries", ")", ")", "boto", ".", "config", ".", "set", "(", "BOTO_CONFIG_SECTION", ",", "BOTO_CONFIG_SOCKET_TIMEOUT_OPTION", ",", "str", "(", "self", ".", "config", ".", "s3_cache_timeout", ")", ")", "logger", ".", "debug", "(", "\"Connecting to Amazon S3 API ..\"", ")", "endpoint", "=", "urlparse", "(", "self", ".", "config", ".", "s3_cache_url", ")", "host", ",", "_", ",", "port", "=", "endpoint", ".", "netloc", ".", "partition", "(", "':'", ")", "kw", "=", "dict", "(", "host", "=", "host", ",", "port", "=", "int", "(", "port", ")", "if", "port", "else", "None", ",", "is_secure", "=", "(", "endpoint", ".", "scheme", "==", "'https'", ")", ",", "calling_format", "=", "(", "SubdomainCallingFormat", "(", ")", "if", "host", "==", "S3Connection", ".", "DefaultHost", "else", "OrdinaryCallingFormat", "(", ")", ")", ",", ")", "try", ":", "self", ".", "cached_connection", "=", "S3Connection", "(", "*", "*", "kw", ")", "except", "NoAuthHandlerFound", ":", "logger", ".", "debug", "(", "\"Amazon S3 API credentials missing, retrying with anonymous connection ..\"", ")", "self", ".", "cached_connection", "=", "S3Connection", "(", "anon", "=", "True", ",", "*", "*", "kw", ")", "except", "(", "BotoClientError", ",", "BotoServerError", ")", ":", "raise", "CacheBackendError", "(", "\"\"\"\n Failed to connect to the Amazon S3 API! Most likely your\n credentials are not correctly configured. The Amazon S3\n cache backend will be disabled for now.\n \"\"\"", ")", "return", "self", ".", "cached_connection" ]
Read an AT2 formatted time series .
def load_at2_file ( cls , filename ) : with open ( filename ) as fp : next ( fp ) description = next ( fp ) . strip ( ) next ( fp ) parts = next ( fp ) . split ( ) time_step = float ( parts [ 1 ] ) accels = [ float ( p ) for l in fp for p in l . split ( ) ] return cls ( filename , description , time_step , accels )
3,878
https://github.com/arkottke/pysra/blob/c72fd389d6c15203c0c00728ac00f101bae6369d/pysra/motion.py#L211-L229
[ "def", "self_consistent_update", "(", "u_kn", ",", "N_k", ",", "f_k", ")", ":", "u_kn", ",", "N_k", ",", "f_k", "=", "validate_inputs", "(", "u_kn", ",", "N_k", ",", "f_k", ")", "states_with_samples", "=", "(", "N_k", ">", "0", ")", "# Only the states with samples can contribute to the denominator term.", "log_denominator_n", "=", "logsumexp", "(", "f_k", "[", "states_with_samples", "]", "-", "u_kn", "[", "states_with_samples", "]", ".", "T", ",", "b", "=", "N_k", "[", "states_with_samples", "]", ",", "axis", "=", "1", ")", "# All states can contribute to the numerator term.", "return", "-", "1.", "*", "logsumexp", "(", "-", "log_denominator_n", "-", "u_kn", ",", "axis", "=", "1", ")" ]
Read an SMC formatted time series .
def load_smc_file ( cls , filename ) : from . tools import parse_fixed_width with open ( filename ) as fp : lines = list ( fp ) # 11 lines of strings lines_str = [ lines . pop ( 0 ) for _ in range ( 11 ) ] if lines_str [ 0 ] . strip ( ) != '2 CORRECTED ACCELEROGRAM' : raise RuntimeWarning ( "Loading uncorrected SMC file." ) m = re . search ( 'station =(.+)component=(.+)' , lines_str [ 5 ] ) description = '; ' . join ( [ g . strip ( ) for g in m . groups ( ) ] ) # 6 lines of (8i10) formatted integers values_int = parse_fixed_width ( 48 * [ ( 10 , int ) ] , [ lines . pop ( 0 ) for _ in range ( 6 ) ] ) count_comment = values_int [ 15 ] count = values_int [ 16 ] # 10 lines of (5e15.7) formatted floats values_float = parse_fixed_width ( 50 * [ ( 15 , float ) ] , [ lines . pop ( 0 ) for _ in range ( 10 ) ] ) time_step = 1 / values_float [ 1 ] # Skip comments lines = lines [ count_comment : ] accels = np . array ( parse_fixed_width ( count * [ ( 10 , float ) , ] , lines ) ) return TimeSeriesMotion ( filename , description , time_step , accels )
3,879
https://github.com/arkottke/pysra/blob/c72fd389d6c15203c0c00728ac00f101bae6369d/pysra/motion.py#L232-L276
[ "def", "can_user_update_settings", "(", "request", ",", "view", ",", "obj", "=", "None", ")", ":", "if", "obj", "is", "None", ":", "return", "# TODO [TM:3/21/17] clean it up after WAL-634. Clean up service settings update tests as well.", "if", "obj", ".", "customer", "and", "not", "obj", ".", "shared", ":", "return", "permissions", ".", "is_owner", "(", "request", ",", "view", ",", "obj", ")", "else", ":", "return", "permissions", ".", "is_staff", "(", "request", ",", "view", ",", "obj", ")" ]
Return surface reconstruction as well as primary and secondary adsorption site labels
def get_info ( self ) : reconstructed = self . is_reconstructed ( ) site , site_type = self . get_site ( ) return reconstructed , site , site_type
3,880
https://github.com/SUNCAT-Center/CatHub/blob/324625d1d8e740673f139658b2de4c9e1059739e/cathub/classification.py#L48-L56
[ "def", "recv", "(", "self", ")", ":", "LOGGER", ".", "debug", "(", "'Receiving'", ")", "try", ":", "message_length", "=", "struct", ".", "unpack", "(", "'>i'", ",", "self", ".", "_socket", ".", "recv", "(", "4", ")", ")", "[", "0", "]", "message_length", "-=", "Connection", ".", "COMM_LENGTH", "LOGGER", ".", "debug", "(", "'Length: %i'", ",", "message_length", ")", "except", "socket", ".", "timeout", ":", "return", "None", "comm_status", "=", "struct", ".", "unpack", "(", "'>i'", ",", "self", ".", "_socket", ".", "recv", "(", "4", ")", ")", "[", "0", "]", "LOGGER", ".", "debug", "(", "'Status: %i'", ",", "comm_status", ")", "bytes_received", "=", "0", "message", "=", "b\"\"", "while", "bytes_received", "<", "message_length", ":", "if", "message_length", "-", "bytes_received", ">=", "1024", ":", "recv_len", "=", "1024", "else", ":", "recv_len", "=", "message_length", "-", "bytes_received", "bytes_received", "+=", "recv_len", "LOGGER", ".", "debug", "(", "'Received %i'", ",", "bytes_received", ")", "message", "+=", "self", ".", "_socket", ".", "recv", "(", "recv_len", ")", "if", "comm_status", "==", "0", ":", "message", "=", "self", ".", "_crypt", ".", "decrypt", "(", "message", ")", "else", ":", "return", "Message", "(", "len", "(", "message", ")", ",", "Connection", ".", "COMM_ERROR", ",", "message", ")", "msg", "=", "Message", "(", "message_length", ",", "comm_status", ",", "message", ")", "return", "msg" ]
Check if adsorbate dissociates
def check_dissociated ( self , cutoff = 1.2 ) : dissociated = False if not len ( self . B ) > self . nslab + 1 : # only one adsorbate return dissociated adsatoms = [ atom for atom in self . B [ self . nslab : ] ] ads0 , ads1 = set ( atom . symbol for atom in adsatoms ) bond_dist = get_ads_dist ( self . B , ads0 , ads1 ) Cradii = [ cradii [ atom . number ] for atom in [ ase . Atom ( ads0 ) , ase . Atom ( ads1 ) ] ] bond_dist0 = sum ( Cradii ) if bond_dist > cutoff * bond_dist0 : print ( 'DISSOCIATED: {} Ang > 1.2 * {} Ang' . format ( bond_dist , bond_dist0 ) ) dissociated = True return dissociated
3,881
https://github.com/SUNCAT-Center/CatHub/blob/324625d1d8e740673f139658b2de4c9e1059739e/cathub/classification.py#L58-L77
[ "def", "write_record", "(", "self", ",", "event_str", ")", ":", "header", "=", "struct", ".", "pack", "(", "'Q'", ",", "len", "(", "event_str", ")", ")", "header", "+=", "struct", ".", "pack", "(", "'I'", ",", "masked_crc32c", "(", "header", ")", ")", "footer", "=", "struct", ".", "pack", "(", "'I'", ",", "masked_crc32c", "(", "event_str", ")", ")", "self", ".", "_writer", ".", "write", "(", "header", "+", "event_str", "+", "footer", ")" ]
Compare initial and final slab configuration to determine if slab reconstructs during relaxation
def is_reconstructed ( self , xy_cutoff = 0.3 , z_cutoff = 0.4 ) : assert self . A , 'Initial slab geometry needed to classify reconstruction' # remove adsorbate A = self . A [ : - 1 ] . copy ( ) B = self . B [ : - 1 ] . copy ( ) # Order wrt x-positions x_indices = np . argsort ( A . positions [ : , 0 ] ) A = A [ x_indices ] B = B [ x_indices ] a = A . positions b = B . positions allowed_z_movement = z_cutoff * cradii [ A . get_atomic_numbers ( ) ] allowed_xy_movement = xy_cutoff * np . mean ( cradii [ A . get_atomic_numbers ( ) ] ) D , D_len = get_distances ( p1 = a , p2 = b , cell = A . cell , pbc = True ) d_xy = np . linalg . norm ( np . diagonal ( D ) [ : 2 ] , axis = 0 ) d_z = np . diagonal ( D ) [ 2 : ] [ 0 ] cond1 = np . all ( d_xy < allowed_xy_movement ) cond2 = np . all ( [ d_z [ i ] < allowed_z_movement [ i ] for i in range ( len ( a ) ) ] ) if cond1 and cond2 : # not reconstructed return False else : return True
3,882
https://github.com/SUNCAT-Center/CatHub/blob/324625d1d8e740673f139658b2de4c9e1059739e/cathub/classification.py#L105-L145
[ "def", "chars", "(", "self", ",", "font", ",", "block", ")", ":", "if", "font", ":", "font_files", "=", "self", ".", "_getFont", "(", "font", ")", "else", ":", "font_files", "=", "fc", ".", "query", "(", ")", "code_points", "=", "self", ".", "_getFontChars", "(", "font_files", ")", "if", "not", "block", ":", "blocks", "=", "all_blocks", "ranges_column", "=", "map", "(", "itemgetter", "(", "3", ")", ",", "blocks", ")", "overlapped", "=", "Ranges", "(", "code_points", ")", ".", "getOverlappedList", "(", "ranges_column", ")", "else", ":", "blocks", "=", "[", "block", "]", "overlapped", "=", "[", "Ranges", "(", "code_points", ")", ".", "getOverlapped", "(", "block", "[", "3", "]", ")", "]", "if", "self", ".", "_display", "[", "'group'", "]", ":", "char_count", "=", "block_count", "=", "0", "for", "i", ",", "block", "in", "enumerate", "(", "blocks", ")", ":", "o_count", "=", "len", "(", "overlapped", "[", "i", "]", ")", "if", "o_count", ":", "block_count", "+=", "1", "char_count", "+=", "o_count", "total", "=", "sum", "(", "len", "(", "r", ")", "for", "r", "in", "block", "[", "3", "]", ")", "percent", "=", "0", "if", "total", "==", "0", "else", "o_count", "/", "total", "print", "(", "\"{0:>6} {1:47} {2:>4.0%} ({3}/{4})\"", ".", "format", "(", "block", "[", "0", "]", ",", "block", "[", "2", "]", ",", "percent", ",", "o_count", ",", "total", ")", ")", "if", "self", ".", "_display", "[", "'list'", "]", ":", "for", "point", "in", "overlapped", "[", "i", "]", ":", "self", ".", "_charInfo", "(", "point", ",", "padding", "=", "9", ")", "self", ".", "_charSummary", "(", "char_count", ",", "block_count", ")", "else", ":", "for", "point", "in", "code_points", ":", "self", ".", "_charInfo", "(", "point", ",", "padding", "=", "7", ")", "self", ".", "_charSummary", "(", "len", "(", "code_points", ")", ")" ]
Return element closest to the adsorbate in the subsurface layer
def get_under_bridge ( self ) : C0 = self . B [ - 1 : ] * ( 3 , 3 , 1 ) ads_pos = C0 . positions [ 4 ] C = self . get_subsurface_layer ( ) * ( 3 , 3 , 1 ) dis = self . B . cell [ 0 ] [ 0 ] * 2 ret = None for ele in C : new_dis = np . linalg . norm ( ads_pos - ele . position ) if new_dis < dis : dis = new_dis ret = ele . symbol return ret
3,883
https://github.com/SUNCAT-Center/CatHub/blob/324625d1d8e740673f139658b2de4c9e1059739e/cathub/classification.py#L260-L276
[ "def", "main", "(", "arguments", "=", "None", ",", "config", "=", "None", ")", ":", "# Parse options, initialize gathered stats", "options", "=", "LoggOptions", "(", "arguments", "=", "arguments", ")", ".", "parse", "(", ")", "# FIXME: pass in only config; set config.journal = options.journal", "if", "not", "config", ":", "config", "=", "options", ".", "config_file", "logg", "=", "Logg", "(", "config", ",", "options", ".", "journal", ")", "return", "logg", ".", "logg_record", "(", "options", ".", "logg", ",", "options", ".", "date", ")" ]
Return HCP if an atom is present below the adsorbate in the subsurface layer and FCC if not
def get_under_hollow ( self ) : C0 = self . B [ - 1 : ] * ( 3 , 3 , 1 ) ads_pos = C0 . positions [ 4 ] C = self . get_subsurface_layer ( ) * ( 3 , 3 , 1 ) ret = 'FCC' if np . any ( [ np . linalg . norm ( ads_pos [ : 2 ] - ele . position [ : 2 ] ) < 0.5 * cradii [ ele . number ] for ele in C ] ) : ret = 'HCP' return ret
3,884
https://github.com/SUNCAT-Center/CatHub/blob/324625d1d8e740673f139658b2de4c9e1059739e/cathub/classification.py#L278-L291
[ "def", "show_progress", "(", "total_duration", ")", ":", "with", "tqdm", "(", "total", "=", "round", "(", "total_duration", ",", "2", ")", ")", "as", "bar", ":", "def", "handler", "(", "key", ",", "value", ")", ":", "if", "key", "==", "'out_time_ms'", ":", "time", "=", "round", "(", "float", "(", "value", ")", "/", "1000000.", ",", "2", ")", "bar", ".", "update", "(", "time", "-", "bar", ".", "n", ")", "elif", "key", "==", "'progress'", "and", "value", "==", "'end'", ":", "bar", ".", "update", "(", "bar", ".", "total", "-", "bar", ".", "n", ")", "with", "_watch_progress", "(", "handler", ")", "as", "socket_filename", ":", "yield", "socket_filename" ]
Evaluate the 2D polynomial transformation .
def fmap ( order , aij , bij , x , y ) : u = np . zeros_like ( x ) v = np . zeros_like ( y ) k = 0 for i in range ( order + 1 ) : for j in range ( i + 1 ) : u += aij [ k ] * ( x ** ( i - j ) ) * ( y ** j ) v += bij [ k ] * ( x ** ( i - j ) ) * ( y ** j ) k += 1 return u , v
3,885
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/distortion.py#L184-L224
[ "def", "SetBackingStore", "(", "cls", ",", "backing", ")", ":", "if", "backing", "not", "in", "[", "'json'", ",", "'sqlite'", ",", "'memory'", "]", ":", "raise", "ArgumentError", "(", "\"Unknown backing store type that is not json or sqlite\"", ",", "backing", "=", "backing", ")", "if", "backing", "==", "'json'", ":", "cls", ".", "BackingType", "=", "JSONKVStore", "cls", ".", "BackingFileName", "=", "'component_registry.json'", "elif", "backing", "==", "'memory'", ":", "cls", ".", "BackingType", "=", "InMemoryKVStore", "cls", ".", "BackingFileName", "=", "None", "else", ":", "cls", ".", "BackingType", "=", "SQLiteKVStore", "cls", ".", "BackingFileName", "=", "'component_registry.db'" ]
Expected number of coefficients in a 2D transformation of a given order .
def ncoef_fmap ( order ) : ncoef = 0 for i in range ( order + 1 ) : for j in range ( i + 1 ) : ncoef += 1 return ncoef
3,886
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/distortion.py#L227-L246
[ "def", "keep_alive", "(", "self", ",", "val", ":", "bool", ")", "->", "None", ":", "self", ".", "_keepalive", "=", "val", "if", "self", ".", "_keepalive_handle", ":", "self", ".", "_keepalive_handle", ".", "cancel", "(", ")", "self", ".", "_keepalive_handle", "=", "None" ]
Compute order corresponding to a given number of coefficients .
def order_fmap ( ncoef ) : loop = True order = 1 while loop : loop = not ( ncoef == ncoef_fmap ( order ) ) if loop : order += 1 if order > NMAX_ORDER : print ( 'No. of coefficients: ' , ncoef ) raise ValueError ( "order > " + str ( NMAX_ORDER ) + " not implemented" ) return order
3,887
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/array/distortion.py#L249-L274
[ "def", "_post_tags", "(", "self", ",", "fileobj", ")", ":", "page", "=", "OggPage", ".", "find_last", "(", "fileobj", ",", "self", ".", "serial", ",", "finishing", "=", "True", ")", "if", "page", "is", "None", ":", "raise", "OggVorbisHeaderError", "self", ".", "length", "=", "page", ".", "position", "/", "float", "(", "self", ".", "sample_rate", ")" ]
Returns the name of the template .
def get_template_name ( self ) : if self . template_name is None : name = camelcase2list ( self . __class__ . __name__ ) name = '{}/{}.html' . format ( name . pop ( 0 ) , '_' . join ( name ) ) self . template_name = name . lower ( ) return self . template_name
3,888
https://github.com/kyzima-spb/flask-pony/blob/6cf28d70b7ebf415d58fa138fcc70b8dd57432c7/flask_pony/views.py#L131-L148
[ "def", "correlator", "(", "A", ",", "B", ")", ":", "correlators", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "A", ")", ")", ":", "correlator_row", "=", "[", "]", "for", "j", "in", "range", "(", "len", "(", "B", ")", ")", ":", "corr", "=", "0", "for", "k", "in", "range", "(", "len", "(", "A", "[", "i", "]", ")", ")", ":", "for", "l", "in", "range", "(", "len", "(", "B", "[", "j", "]", ")", ")", ":", "if", "k", "==", "l", ":", "corr", "+=", "A", "[", "i", "]", "[", "k", "]", "*", "B", "[", "j", "]", "[", "l", "]", "else", ":", "corr", "-=", "A", "[", "i", "]", "[", "k", "]", "*", "B", "[", "j", "]", "[", "l", "]", "correlator_row", ".", "append", "(", "corr", ")", "correlators", ".", "append", "(", "correlator_row", ")", "return", "correlators" ]
Append a new file in the stream .
def append_file ( self , file ) : self . files . append ( file ) if self . transformer : future = asyncio . ensure_future ( self . transformer . transform ( file ) ) future . add_done_callback ( self . handle_transform )
3,889
https://github.com/pylp/pylp/blob/7ebaa55fbaf61cb8175f211dd41ef2928c22d4d4/pylp/lib/stream.py#L33-L39
[ "def", "get_alt_texts_metadata", "(", "self", ")", ":", "metadata", "=", "dict", "(", "self", ".", "_alt_texts_metadata", ")", "metadata", ".", "update", "(", "{", "'existing_string_values'", ":", "[", "t", "[", "'text'", "]", "for", "t", "in", "self", ".", "my_osid_object_form", ".", "_my_map", "[", "'altTexts'", "]", "]", "}", ")", "return", "Metadata", "(", "*", "*", "metadata", ")" ]
Call flush function if all files have been transformed .
def flush_if_ended ( self ) : if self . ended and self . next and len ( self . files ) == self . transformed : future = asyncio . ensure_future ( self . transformer . flush ( ) ) future . add_done_callback ( lambda x : self . next . end_of_stream ( ) )
3,890
https://github.com/pylp/pylp/blob/7ebaa55fbaf61cb8175f211dd41ef2928c22d4d4/pylp/lib/stream.py#L42-L46
[ "def", "OpenHandle", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "'handle'", ")", ":", "return", "self", ".", "handle", "else", ":", "handle", "=", "c_void_p", "(", ")", "ret", "=", "vmGuestLib", ".", "VMGuestLib_OpenHandle", "(", "byref", "(", "handle", ")", ")", "if", "ret", "!=", "VMGUESTLIB_ERROR_SUCCESS", ":", "raise", "VMGuestLibException", "(", "ret", ")", "return", "handle" ]
Handle a transform callback .
def handle_transform ( self , task ) : self . transformed += 1 file = task . result ( ) if file : self . next . append_file ( file ) self . flush_if_ended ( )
3,891
https://github.com/pylp/pylp/blob/7ebaa55fbaf61cb8175f211dd41ef2928c22d4d4/pylp/lib/stream.py#L49-L57
[ "def", "_init_libcrypto", "(", ")", ":", "libcrypto", "=", "_load_libcrypto", "(", ")", "try", ":", "libcrypto", ".", "OPENSSL_init_crypto", "(", ")", "except", "AttributeError", ":", "# Support for OpenSSL < 1.1 (OPENSSL_API_COMPAT < 0x10100000L)", "libcrypto", ".", "OPENSSL_no_config", "(", ")", "libcrypto", ".", "OPENSSL_add_all_algorithms_noconf", "(", ")", "libcrypto", ".", "RSA_new", ".", "argtypes", "=", "(", ")", "libcrypto", ".", "RSA_new", ".", "restype", "=", "c_void_p", "libcrypto", ".", "RSA_free", ".", "argtypes", "=", "(", "c_void_p", ",", ")", "libcrypto", ".", "RSA_size", ".", "argtype", "=", "(", "c_void_p", ")", "libcrypto", ".", "BIO_new_mem_buf", ".", "argtypes", "=", "(", "c_char_p", ",", "c_int", ")", "libcrypto", ".", "BIO_new_mem_buf", ".", "restype", "=", "c_void_p", "libcrypto", ".", "BIO_free", ".", "argtypes", "=", "(", "c_void_p", ",", ")", "libcrypto", ".", "PEM_read_bio_RSAPrivateKey", ".", "argtypes", "=", "(", "c_void_p", ",", "c_void_p", ",", "c_void_p", ",", "c_void_p", ")", "libcrypto", ".", "PEM_read_bio_RSAPrivateKey", ".", "restype", "=", "c_void_p", "libcrypto", ".", "PEM_read_bio_RSA_PUBKEY", ".", "argtypes", "=", "(", "c_void_p", ",", "c_void_p", ",", "c_void_p", ",", "c_void_p", ")", "libcrypto", ".", "PEM_read_bio_RSA_PUBKEY", ".", "restype", "=", "c_void_p", "libcrypto", ".", "RSA_private_encrypt", ".", "argtypes", "=", "(", "c_int", ",", "c_char_p", ",", "c_char_p", ",", "c_void_p", ",", "c_int", ")", "libcrypto", ".", "RSA_public_decrypt", ".", "argtypes", "=", "(", "c_int", ",", "c_char_p", ",", "c_char_p", ",", "c_void_p", ",", "c_int", ")", "return", "libcrypto" ]
Pipe this stream to another .
def pipe ( self , transformer ) : if self . next : return stream = Stream ( ) self . next = stream stream . prev = self self . transformer = transformer transformer . stream = self transformer . piped ( ) for file in self . files : future = asyncio . ensure_future ( self . transformer . transform ( file ) ) future . add_done_callback ( self . handle_transform ) self . onpiped . set_result ( None ) self . flush_if_ended ( ) return stream
3,892
https://github.com/pylp/pylp/blob/7ebaa55fbaf61cb8175f211dd41ef2928c22d4d4/pylp/lib/stream.py#L66-L86
[ "def", "_get_options", "(", "ret", "=", "None", ")", ":", "attrs", "=", "{", "'url'", ":", "'url'", ",", "'db'", ":", "'db'", ",", "'user'", ":", "'user'", ",", "'passwd'", ":", "'passwd'", ",", "'redact_pws'", ":", "'redact_pws'", ",", "'minimum_return'", ":", "'minimum_return'", "}", "_options", "=", "salt", ".", "returners", ".", "get_returner_options", "(", "__virtualname__", ",", "ret", ",", "attrs", ",", "__salt__", "=", "__salt__", ",", "__opts__", "=", "__opts__", ")", "if", "'url'", "not", "in", "_options", ":", "log", ".", "debug", "(", "\"Using default url.\"", ")", "_options", "[", "'url'", "]", "=", "\"http://salt:5984/\"", "if", "'db'", "not", "in", "_options", ":", "log", ".", "debug", "(", "\"Using default database.\"", ")", "_options", "[", "'db'", "]", "=", "\"salt\"", "if", "'user'", "not", "in", "_options", ":", "log", ".", "debug", "(", "\"Not athenticating with a user.\"", ")", "_options", "[", "'user'", "]", "=", "None", "if", "'passwd'", "not", "in", "_options", ":", "log", ".", "debug", "(", "\"Not athenticating with a password.\"", ")", "_options", "[", "'passwd'", "]", "=", "None", "if", "'redact_pws'", "not", "in", "_options", ":", "log", ".", "debug", "(", "\"Not redacting passwords.\"", ")", "_options", "[", "'redact_pws'", "]", "=", "None", "if", "'minimum_return'", "not", "in", "_options", ":", "log", ".", "debug", "(", "\"Not minimizing the return object.\"", ")", "_options", "[", "'minimum_return'", "]", "=", "None", "return", "_options" ]
Pipe several transformers end to end .
def pipes ( stream , * transformers ) : for transformer in transformers : stream = stream . pipe ( transformer ) return stream
3,893
https://github.com/pylp/pylp/blob/7ebaa55fbaf61cb8175f211dd41ef2928c22d4d4/pylp/utils/pipes.py#L11-L15
[ "def", "create", "(", "self", ",", "name", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "try", ":", "return", "super", "(", "ImageMemberManager", ",", "self", ")", ".", "create", "(", "name", ",", "*", "args", ",", "*", "*", "kwargs", ")", "except", "Exception", "as", "e", ":", "if", "e", ".", "http_status", "==", "403", ":", "raise", "exc", ".", "UnsharableImage", "(", "\"You cannot share a public image.\"", ")", "else", ":", "raise" ]
Convert input values to type values .
def convert ( self , val ) : pre = super ( Parameter , self ) . convert ( val ) if self . custom_validator is not None : post = self . custom_validator ( pre ) else : post = pre return post
3,894
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/core/dataholders.py#L342-L350
[ "def", "add_string", "(", "self", ",", "data", ")", ":", "lines", "=", "[", "]", "while", "data", ":", "match", "=", "self", ".", "_line_end_re", ".", "search", "(", "data", ")", "if", "match", "is", "None", ":", "chunk", "=", "data", "else", ":", "chunk", "=", "data", "[", ":", "match", ".", "end", "(", ")", "]", "data", "=", "data", "[", "len", "(", "chunk", ")", ":", "]", "if", "self", ".", "_buf", "and", "self", ".", "_buf", "[", "-", "1", "]", ".", "endswith", "(", "b", "(", "'\\r'", ")", ")", "and", "not", "chunk", ".", "startswith", "(", "b", "(", "'\\n'", ")", ")", ":", "# if we get a carriage return followed by something other than", "# a newline then we assume that we're overwriting the current", "# line (ie. a progress bar)", "#", "# We don't terminate lines that end with a carriage return until", "# we see what's coming next so we can distinguish between a", "# progress bar situation and a Windows line terminator.", "#", "# TODO(adrian): some day these hacks should be replaced with", "# real terminal emulation", "lines", ".", "append", "(", "self", ".", "_finish_line", "(", ")", ")", "self", ".", "_buf", ".", "append", "(", "chunk", ")", "if", "chunk", ".", "endswith", "(", "b", "(", "'\\n'", ")", ")", ":", "lines", ".", "append", "(", "self", ".", "_finish_line", "(", ")", ")", "return", "lines" ]
Validate values according to the requirement
def validate ( self , val ) : if self . validation : self . type . validate ( val ) if self . custom_validator is not None : self . custom_validator ( val ) return True
3,895
https://github.com/guaix-ucm/numina/blob/6c829495df8937f77c2de9383c1038ffb3e713e3/numina/core/dataholders.py#L352-L360
[ "def", "row_value", "(", "self", ",", "row", ")", ":", "irow", "=", "int", "(", "row", ")", "i", "=", "self", ".", "_get_key_index", "(", "irow", ")", "if", "i", "==", "-", "1", ":", "return", "0.0", "# Are we dealing with the last key?", "if", "i", "==", "len", "(", "self", ".", "keys", ")", "-", "1", ":", "return", "self", ".", "keys", "[", "-", "1", "]", ".", "value", "return", "TrackKey", ".", "interpolate", "(", "self", ".", "keys", "[", "i", "]", ",", "self", ".", "keys", "[", "i", "+", "1", "]", ",", "row", ")" ]
Decorator for the View classes .
def route ( obj , rule , * args , * * kwargs ) : def decorator ( cls ) : endpoint = kwargs . get ( 'endpoint' , camel_to_snake ( cls . __name__ ) ) kwargs [ 'view_func' ] = cls . as_view ( endpoint ) obj . add_url_rule ( rule , * args , * * kwargs ) return cls return decorator
3,896
https://github.com/kyzima-spb/flask-pony/blob/6cf28d70b7ebf415d58fa138fcc70b8dd57432c7/flask_pony/decorators.py#L20-L27
[ "def", "add_intern_pattern", "(", "self", ",", "url", "=", "None", ")", ":", "try", ":", "pat", "=", "self", ".", "get_intern_pattern", "(", "url", "=", "url", ")", "if", "pat", ":", "log", ".", "debug", "(", "LOG_CHECK", ",", "\"Add intern pattern %r\"", ",", "pat", ")", "self", ".", "aggregate", ".", "config", "[", "'internlinks'", "]", ".", "append", "(", "get_link_pat", "(", "pat", ")", ")", "except", "UnicodeError", "as", "msg", ":", "res", "=", "_", "(", "\"URL has unparsable domain name: %(domain)s\"", ")", "%", "{", "\"domain\"", ":", "msg", "}", "self", ".", "set_result", "(", "res", ",", "valid", "=", "False", ")" ]
Fit to a target crustal amplification or site term .
def fit ( self , target_type , target , adjust_thickness = False , adjust_site_atten = False , adjust_source_vel = False ) : density = self . profile . density nl = len ( density ) # Slowness bounds slowness = self . profile . slowness thickness = self . profile . thickness site_atten = self . _site_atten # Slowness initial = slowness bounds = 1 / np . tile ( ( 4000 , 100 ) , ( nl , 1 ) ) if not adjust_source_vel : bounds [ - 1 ] = ( initial [ - 1 ] , initial [ - 1 ] ) # Thickness bounds if adjust_thickness : bounds = np . r_ [ bounds , [ [ t / 2 , 2 * t ] for t in thickness ] ] initial = np . r_ [ initial , thickness ] # Site attenuation bounds if adjust_site_atten : bounds = np . r_ [ bounds , [ [ 0.0001 , 0.200 ] ] ] initial = np . r_ [ initial , self . site_atten ] def calc_rmse ( this , that ) : return np . mean ( ( ( this - that ) / that ) ** 2 ) def err ( x ) : _slowness = x [ 0 : nl ] if adjust_thickness : _thickness = x [ nl : ( 2 * nl ) ] else : _thickness = thickness if adjust_site_atten : self . _site_atten = x [ - 1 ] crustal_amp , site_term = self . _calc_amp ( density , _thickness , _slowness ) calc = crustal_amp if target_type == 'crustal_amp' else site_term err = 10 * calc_rmse ( target , calc ) # Prefer the original values so add the difference to the error err += calc_rmse ( slowness , _slowness ) if adjust_thickness : err += calc_rmse ( thickness , _thickness ) if adjust_site_atten : err += calc_rmse ( self . _site_atten , site_atten ) return err res = minimize ( err , initial , method = 'L-BFGS-B' , bounds = bounds ) slowness = res . x [ 0 : nl ] if adjust_thickness : thickness = res . x [ nl : ( 2 * nl ) ] profile = Profile ( [ Layer ( l . soil_type , t , 1 / s ) for l , t , s in zip ( self . profile , thickness , slowness ) ] , self . profile . wt_depth ) # Update the calculated amplificaiton return ( self . motion , profile , self . loc_input )
3,897
https://github.com/arkottke/pysra/blob/c72fd389d6c15203c0c00728ac00f101bae6369d/pysra/propagation.py#L153-L247
[ "def", "get_archive", "(", "self", ",", "container", ",", "path", ",", "chunk_size", "=", "DEFAULT_DATA_CHUNK_SIZE", ")", ":", "params", "=", "{", "'path'", ":", "path", "}", "url", "=", "self", ".", "_url", "(", "'/containers/{0}/archive'", ",", "container", ")", "res", "=", "self", ".", "_get", "(", "url", ",", "params", "=", "params", ",", "stream", "=", "True", ")", "self", ".", "_raise_for_status", "(", "res", ")", "encoded_stat", "=", "res", ".", "headers", ".", "get", "(", "'x-docker-container-path-stat'", ")", "return", "(", "self", ".", "_stream_raw_result", "(", "res", ",", "chunk_size", ",", "False", ")", ",", "utils", ".", "decode_json_header", "(", "encoded_stat", ")", "if", "encoded_stat", "else", "None", ")" ]
Compute the wave field at specific location .
def wave_at_location ( self , l ) : cterm = 1j * self . _wave_nums [ l . index ] * l . depth_within if l . wave_field == WaveField . within : return ( self . _waves_a [ l . index ] * np . exp ( cterm ) + self . _waves_b [ l . index ] * np . exp ( - cterm ) ) elif l . wave_field == WaveField . outcrop : return 2 * self . _waves_a [ l . index ] * np . exp ( cterm ) elif l . wave_field == WaveField . incoming_only : return self . _waves_a [ l . index ] * np . exp ( cterm ) else : raise NotImplementedError
3,898
https://github.com/arkottke/pysra/blob/c72fd389d6c15203c0c00728ac00f101bae6369d/pysra/propagation.py#L340-L363
[ "def", "render_meta", "(", "meta", ",", "fn", "=", "\"meta.pandas.html\"", ",", "title", "=", "\"Project Metadata - MSMBuilder\"", ",", "pandas_kwargs", "=", "None", ")", ":", "if", "pandas_kwargs", "is", "None", ":", "pandas_kwargs", "=", "{", "}", "kwargs_with_defaults", "=", "{", "'classes'", ":", "(", "'table'", ",", "'table-condensed'", ",", "'table-hover'", ")", ",", "}", "kwargs_with_defaults", ".", "update", "(", "*", "*", "pandas_kwargs", ")", "env", "=", "Environment", "(", "loader", "=", "PackageLoader", "(", "'msmbuilder'", ",", "'io_templates'", ")", ")", "templ", "=", "env", ".", "get_template", "(", "\"twitter-bootstrap.html\"", ")", "rendered", "=", "templ", ".", "render", "(", "title", "=", "title", ",", "content", "=", "meta", ".", "to_html", "(", "*", "*", "kwargs_with_defaults", ")", ")", "# Ugh, pandas hardcodes border=\"1\"", "rendered", "=", "re", ".", "sub", "(", "r' border=\"1\"'", ",", "''", ",", "rendered", ")", "backup", "(", "fn", ")", "with", "open", "(", "fn", ",", "'w'", ")", "as", "f", ":", "f", ".", "write", "(", "rendered", ")" ]
Compute the acceleration transfer function .
def calc_accel_tf ( self , lin , lout ) : tf = self . wave_at_location ( lout ) / self . wave_at_location ( lin ) return tf
3,899
https://github.com/arkottke/pysra/blob/c72fd389d6c15203c0c00728ac00f101bae6369d/pysra/propagation.py#L365-L378
[ "def", "add_scheduling_block", "(", "config", ")", ":", "try", ":", "DB", ".", "add_sbi", "(", "config", ")", "except", "jsonschema", ".", "ValidationError", "as", "error", ":", "error_dict", "=", "error", ".", "__dict__", "for", "key", "in", "error_dict", ":", "error_dict", "[", "key", "]", "=", "error_dict", "[", "key", "]", ".", "__str__", "(", ")", "error_response", "=", "dict", "(", "message", "=", "\"Failed to add scheduling block\"", ",", "reason", "=", "\"JSON validation error\"", ",", "details", "=", "error_dict", ")", "return", "error_response", ",", "HTTPStatus", ".", "BAD_REQUEST", "response", "=", "dict", "(", "config", "=", "config", ",", "message", "=", "'Successfully registered scheduling block '", "'instance with ID: {}'", ".", "format", "(", "config", "[", "'id'", "]", ")", ")", "response", "[", "'links'", "]", "=", "{", "'self'", ":", "'{}scheduling-block/{}'", ".", "format", "(", "request", ".", "url_root", ",", "config", "[", "'id'", "]", ")", ",", "'list'", ":", "'{}'", ".", "format", "(", "request", ".", "url", ")", ",", "'home'", ":", "'{}'", ".", "format", "(", "request", ".", "url_root", ")", "}", "return", "response", ",", "HTTPStatus", ".", "ACCEPTED" ]