query
stringlengths
5
1.23k
positive
stringlengths
53
15.2k
id_
int64
0
252k
task_name
stringlengths
87
242
negative
listlengths
20
553
Calculate degree minute second from decimal degree
def _calc_degreeminutes ( decimal_degree ) : sign = compare ( decimal_degree , 0 ) # Store whether the coordinate is negative or positive decimal_degree = abs ( decimal_degree ) degree = decimal_degree // 1 # Truncate degree to be an integer decimal_minute = ( decimal_degree - degree ) * 60. # Calculate the decimal minutes minute = decimal_minute // 1 # Truncate minute to be an integer second = ( decimal_minute - minute ) * 60. # Calculate the decimal seconds # Finally, re-impose the appropriate sign degree = degree * sign minute = minute * sign second = second * sign return ( degree , minute , decimal_minute , second )
7,300
https://github.com/hickeroar/LatLon23/blob/1ff728216ae51055034f4c915fa715446b34549f/LatLon23/__init__.py#L73-L87
[ "def", "virt_env", "(", "self", ")", ":", "if", "self", ".", "_virt_env", "is", "None", ":", "self", ".", "_virt_env", "=", "self", ".", "_create_virt_env", "(", ")", "return", "self", ".", "_virt_env" ]
Given a hemisphere identifier set the sign of the coordinate to match that hemisphere
def set_hemisphere ( self , hemi_str ) : if hemi_str == 'W' : self . degree = abs ( self . degree ) * - 1 self . minute = abs ( self . minute ) * - 1 self . second = abs ( self . second ) * - 1 self . _update ( ) elif hemi_str == 'E' : self . degree = abs ( self . degree ) self . minute = abs ( self . minute ) self . second = abs ( self . second ) self . _update ( ) else : raise ValueError ( 'Hemisphere identifier for longitudes must be E or W' )
7,301
https://github.com/hickeroar/LatLon23/blob/1ff728216ae51055034f4c915fa715446b34549f/LatLon23/__init__.py#L269-L284
[ "def", "iter", "(", "self", ",", "keyed", "=", "False", ",", "extended", "=", "False", ")", ":", "# Error if closed", "if", "self", ".", "closed", ":", "message", "=", "'Stream is closed. Please call \"stream.open()\" first.'", "raise", "exceptions", ".", "TabulatorException", "(", "message", ")", "# Create iterator", "iterator", "=", "chain", "(", "self", ".", "__sample_extended_rows", ",", "self", ".", "__parser", ".", "extended_rows", ")", "iterator", "=", "self", ".", "__apply_processors", "(", "iterator", ")", "# Yield rows from iterator", "for", "row_number", ",", "headers", ",", "row", "in", "iterator", ":", "if", "row_number", ">", "self", ".", "__row_number", ":", "self", ".", "__row_number", "=", "row_number", "if", "extended", ":", "yield", "(", "row_number", ",", "headers", ",", "row", ")", "elif", "keyed", ":", "yield", "dict", "(", "zip", "(", "headers", ",", "row", ")", ")", "else", ":", "yield", "row" ]
Return coordinates transformed to a given projection Projection should be a basemap or pyproj projection object or similar
def project ( self , projection ) : x , y = projection ( self . lon . decimal_degree , self . lat . decimal_degree ) return ( x , y )
7,302
https://github.com/hickeroar/LatLon23/blob/1ff728216ae51055034f4c915fa715446b34549f/LatLon23/__init__.py#L370-L376
[ "def", "assumed_state", "(", "self", ")", ":", "# pylint: disable=protected-access", "return", "(", "not", "self", ".", "_controller", ".", "car_online", "[", "self", ".", "id", "(", ")", "]", "and", "(", "self", ".", "_controller", ".", "_last_update_time", "[", "self", ".", "id", "(", ")", "]", "-", "self", ".", "_controller", ".", "_last_wake_up_time", "[", "self", ".", "id", "(", ")", "]", ">", "self", ".", "_controller", ".", "update_interval", ")", ")" ]
Perform Pyproj s inv operation on two LatLon objects Returns the initial heading and reverse heading in degrees and the distance in km .
def _pyproj_inv ( self , other , ellipse = 'WGS84' ) : lat1 , lon1 = self . lat . decimal_degree , self . lon . decimal_degree lat2 , lon2 = other . lat . decimal_degree , other . lon . decimal_degree g = pyproj . Geod ( ellps = ellipse ) heading_initial , heading_reverse , distance = g . inv ( lon1 , lat1 , lon2 , lat2 , radians = False ) distance = distance / 1000.0 if heading_initial == 0.0 : # Reverse heading not well handled for coordinates that are directly south heading_reverse = 180.0 return { 'heading_initial' : heading_initial , 'heading_reverse' : heading_reverse , 'distance' : distance }
7,303
https://github.com/hickeroar/LatLon23/blob/1ff728216ae51055034f4c915fa715446b34549f/LatLon23/__init__.py#L384-L397
[ "def", "set", "(", "self", ",", "data", "=", "None", ")", ":", "self", ".", "__data", "=", "data", "self", ".", "__exception", "=", "None", "self", ".", "__event", ".", "set", "(", ")" ]
Return string representation of lat and lon as a 2 - element tuple using the format specified by formatter
def to_string ( self , formatter = 'D' ) : return ( self . lat . to_string ( formatter ) , self . lon . to_string ( formatter ) )
7,304
https://github.com/hickeroar/LatLon23/blob/1ff728216ae51055034f4c915fa715446b34549f/LatLon23/__init__.py#L458-L463
[ "def", "client_connected", "(", "self", ",", "reader", ":", "asyncio", ".", "StreamReader", ",", "writer", ":", "asyncio", ".", "StreamWriter", ")", "->", "None", ":", "self", ".", "reader", "=", "reader", "self", ".", "writer", "=", "writer" ]
Called when subtracting a LatLon object from self
def _sub_latlon ( self , other ) : inv = self . _pyproj_inv ( other ) heading = inv [ 'heading_reverse' ] distance = inv [ 'distance' ] return GeoVector ( initial_heading = heading , distance = distance )
7,305
https://github.com/hickeroar/LatLon23/blob/1ff728216ae51055034f4c915fa715446b34549f/LatLon23/__init__.py#L474-L481
[ "def", "_write_cvvr", "(", "self", ",", "f", ",", "data", ")", ":", "f", ".", "seek", "(", "0", ",", "2", ")", "byte_loc", "=", "f", ".", "tell", "(", ")", "cSize", "=", "len", "(", "data", ")", "block_size", "=", "CDF", ".", "CVVR_BASE_SIZE64", "+", "cSize", "section_type", "=", "CDF", ".", "CVVR_", "rfuA", "=", "0", "cvvr1", "=", "bytearray", "(", "24", ")", "cvvr1", "[", "0", ":", "8", "]", "=", "struct", ".", "pack", "(", "'>q'", ",", "block_size", ")", "cvvr1", "[", "8", ":", "12", "]", "=", "struct", ".", "pack", "(", "'>i'", ",", "section_type", ")", "cvvr1", "[", "12", ":", "16", "]", "=", "struct", ".", "pack", "(", "'>i'", ",", "rfuA", ")", "cvvr1", "[", "16", ":", "24", "]", "=", "struct", ".", "pack", "(", "'>q'", ",", "cSize", ")", "f", ".", "write", "(", "cvvr1", ")", "f", ".", "write", "(", "data", ")", "return", "byte_loc" ]
Calculate heading and distance from dx and dy
def _update ( self ) : try : theta_radians = math . atan ( float ( self . dy ) / self . dx ) except ZeroDivisionError : if self . dy > 0 : theta_radians = 0.5 * math . pi elif self . dy < 0 : theta_radians = 1.5 * math . pi self . magnitude = self . dy else : self . magnitude = 1. / ( math . cos ( theta_radians ) ) * self . dx theta = math . degrees ( theta_radians ) self . heading = self . _angle_or_heading ( theta )
7,306
https://github.com/hickeroar/LatLon23/blob/1ff728216ae51055034f4c915fa715446b34549f/LatLon23/__init__.py#L608-L621
[ "def", "cli", "(", "env", ",", "identifier", ",", "crt", ",", "csr", ",", "icc", ",", "key", ",", "notes", ")", ":", "template", "=", "{", "'id'", ":", "identifier", "}", "if", "crt", ":", "template", "[", "'certificate'", "]", "=", "open", "(", "crt", ")", ".", "read", "(", ")", "if", "key", ":", "template", "[", "'privateKey'", "]", "=", "open", "(", "key", ")", ".", "read", "(", ")", "if", "csr", ":", "template", "[", "'certificateSigningRequest'", "]", "=", "open", "(", "csr", ")", ".", "read", "(", ")", "if", "icc", ":", "template", "[", "'intermediateCertificate'", "]", "=", "open", "(", "icc", ")", ".", "read", "(", ")", "if", "notes", ":", "template", "[", "'notes'", "]", "=", "notes", "manager", "=", "SoftLayer", ".", "SSLManager", "(", "env", ".", "client", ")", "manager", ".", "edit_certificate", "(", "template", ")" ]
Convert auth to str so that it can be hashed
def _authstr ( self , auth ) : if type ( auth ) is dict : return '{' + ',' . join ( [ "{0}:{1}" . format ( k , auth [ k ] ) for k in sorted ( auth . keys ( ) ) ] ) + '}' return auth
7,307
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/onep.py#L52-L56
[ "def", "_clear", "(", "self", ",", "fully", "=", "True", ")", ":", "pages", "=", "self", ".", "pages", "if", "not", "pages", ":", "return", "self", ".", "_keyframe", "=", "pages", "[", "0", "]", "if", "fully", ":", "# delete all but first TiffPage/TiffFrame", "for", "i", ",", "page", "in", "enumerate", "(", "pages", "[", "1", ":", "]", ")", ":", "if", "not", "isinstance", "(", "page", ",", "inttypes", ")", "and", "page", ".", "offset", "is", "not", "None", ":", "pages", "[", "i", "+", "1", "]", "=", "page", ".", "offset", "elif", "TiffFrame", "is", "not", "TiffPage", ":", "# delete only TiffFrames", "for", "i", ",", "page", "in", "enumerate", "(", "pages", ")", ":", "if", "isinstance", "(", "page", ",", "TiffFrame", ")", "and", "page", ".", "offset", "is", "not", "None", ":", "pages", "[", "i", "]", "=", "page", ".", "offset", "self", ".", "_cached", "=", "False" ]
Calls the Exosite One Platform RPC API .
def _call ( self , method , auth , arg , defer , notimeout = False ) : if defer : self . deferred . add ( auth , method , arg , notimeout = notimeout ) return True else : calls = self . _composeCalls ( [ ( method , arg ) ] ) return self . _callJsonRPC ( auth , calls , notimeout = notimeout )
7,308
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/onep.py#L221-L238
[ "def", "add_match", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "args", "=", "list", "(", "args", ")", "args", ".", "extend", "(", "_make_line", "(", "key", ",", "val", ")", "for", "key", ",", "val", "in", "kwargs", ".", "items", "(", ")", ")", "for", "arg", "in", "args", ":", "super", "(", "Reader", ",", "self", ")", ".", "add_match", "(", "arg", ")" ]
Create something in Exosite .
def create ( self , auth , type , desc , defer = False ) : return self . _call ( 'create' , auth , [ type , desc ] , defer )
7,309
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/onep.py#L279-L287
[ "def", "set_client_params", "(", "self", ",", "start_unsubscribed", "=", "None", ",", "clear_on_exit", "=", "None", ",", "unsubscribe_on_reload", "=", "None", ",", "announce_interval", "=", "None", ")", ":", "self", ".", "_set", "(", "'start-unsubscribed'", ",", "start_unsubscribed", ",", "cast", "=", "bool", ")", "self", ".", "_set", "(", "'subscription-clear-on-shutdown'", ",", "clear_on_exit", ",", "cast", "=", "bool", ")", "self", ".", "_set", "(", "'unsubscribe-on-graceful-reload'", ",", "unsubscribe_on_reload", ",", "cast", "=", "bool", ")", "self", ".", "_set", "(", "'subscribe-freq'", ",", "announce_interval", ")", "return", "self", ".", "_section" ]
Deletes the specified resource .
def drop ( self , auth , resource , defer = False ) : return self . _call ( 'drop' , auth , [ resource ] , defer )
7,310
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/onep.py#L310-L317
[ "def", "cublasZgemm", "(", "handle", ",", "transa", ",", "transb", ",", "m", ",", "n", ",", "k", ",", "alpha", ",", "A", ",", "lda", ",", "B", ",", "ldb", ",", "beta", ",", "C", ",", "ldc", ")", ":", "status", "=", "_libcublas", ".", "cublasZgemm_v2", "(", "handle", ",", "_CUBLAS_OP", "[", "transa", "]", ",", "_CUBLAS_OP", "[", "transb", "]", ",", "m", ",", "n", ",", "k", ",", "ctypes", ".", "byref", "(", "cuda", ".", "cuDoubleComplex", "(", "alpha", ".", "real", ",", "alpha", ".", "imag", ")", ")", ",", "int", "(", "A", ")", ",", "lda", ",", "int", "(", "B", ")", ",", "ldb", ",", "ctypes", ".", "byref", "(", "cuda", ".", "cuDoubleComplex", "(", "beta", ".", "real", ",", "beta", ".", "imag", ")", ")", ",", "int", "(", "C", ")", ",", "ldc", ")", "cublasCheckStatus", "(", "status", ")" ]
Empties the specified resource of data per specified constraints .
def flush ( self , auth , resource , options = None , defer = False ) : args = [ resource ] if options is not None : args . append ( options ) return self . _call ( 'flush' , auth , args , defer )
7,311
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/onep.py#L319-L330
[ "def", "cleanup_log_files", "(", "outputfile", ")", ":", "d", "=", "os", ".", "path", ".", "dirname", "(", "os", ".", "path", ".", "abspath", "(", "outputfile", ")", ")", "logfiles", "=", "[", "f", "for", "f", "in", "os", ".", "listdir", "(", "d", ")", "if", "f", ".", "endswith", "(", "'ogg.log'", ")", "]", "for", "f", "in", "logfiles", ":", "os", ".", "remove", "(", "f", ")" ]
Grant resources with specific permissions and return a token .
def grant ( self , auth , resource , permissions , ttl = None , defer = False ) : args = [ resource , permissions ] if ttl is not None : args . append ( { "ttl" : ttl } ) return self . _call ( 'grant' , auth , args , defer )
7,312
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/onep.py#L332-L344
[ "def", "reindex_multifiles", "(", "portal", ")", ":", "logger", ".", "info", "(", "\"Reindexing Multifiles ...\"", ")", "brains", "=", "api", ".", "search", "(", "dict", "(", "portal_type", "=", "\"Multifile\"", ")", ",", "\"bika_setup_catalog\"", ")", "total", "=", "len", "(", "brains", ")", "for", "num", ",", "brain", "in", "enumerate", "(", "brains", ")", ":", "if", "num", "%", "100", "==", "0", ":", "logger", ".", "info", "(", "\"Reindexing Multifile: {0}/{1}\"", ".", "format", "(", "num", ",", "total", ")", ")", "obj", "=", "api", ".", "get_object", "(", "brain", ")", "obj", ".", "reindexObject", "(", ")" ]
Request creation and usage information of specified resource according to the specified options .
def info ( self , auth , resource , options = { } , defer = False ) : return self . _call ( 'info' , auth , [ resource , options ] , defer )
7,313
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/onep.py#L346-L355
[ "def", "catch_post_mortem", "(", "host", "=", "''", ",", "port", "=", "5555", ",", "patch_stdstreams", "=", "False", ")", ":", "try", ":", "yield", "except", "Exception", ":", "post_mortem", "(", "None", ",", "host", ",", "port", ",", "patch_stdstreams", ")" ]
This provides backward compatibility with two previous variants of listing . To use the non - deprecated API pass both options and resource .
def listing ( self , auth , types , options = None , resource = None , defer = False ) : if options is None : # This variant is deprecated return self . _call ( 'listing' , auth , [ types ] , defer ) else : if resource is None : # This variant is deprecated, too return self . _call ( 'listing' , auth , [ types , options ] , defer ) else : # pass resource to use the non-deprecated variant return self . _call ( 'listing' , auth , [ resource , types , options ] , defer )
7,314
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/onep.py#L357-L376
[ "def", "compare", "(", "file1", ",", "file2", ")", ":", "if", "isinstance", "(", "file1", ",", "six", ".", "string_types", ")", ":", "# pragma: no branch", "file1", "=", "open", "(", "file1", ",", "'r'", ",", "True", ")", "if", "isinstance", "(", "file2", ",", "six", ".", "string_types", ")", ":", "# pragma: no branch", "file2", "=", "open", "(", "file2", ",", "'r'", ",", "True", ")", "file1_contents", "=", "file1", ".", "read", "(", ")", "file2_contents", "=", "file2", ".", "read", "(", ")", "return", "file1_contents", "==", "file2_contents" ]
Creates an alias for a resource .
def map ( self , auth , resource , alias , defer = False ) : return self . _call ( 'map' , auth , [ 'alias' , resource , alias ] , defer )
7,315
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/onep.py#L389-L397
[ "def", "serialize_table", "(", "ctx", ",", "document", ",", "table", ",", "root", ")", ":", "# What we should check really is why do we pass None as root element", "# There is a good chance some content is missing after the import", "if", "root", "is", "None", ":", "return", "root", "if", "ctx", ".", "ilvl", "!=", "None", ":", "root", "=", "close_list", "(", "ctx", ",", "root", ")", "ctx", ".", "ilvl", ",", "ctx", ".", "numid", "=", "None", ",", "None", "_table", "=", "etree", ".", "SubElement", "(", "root", ",", "'table'", ")", "_table", ".", "set", "(", "'border'", ",", "'1'", ")", "_table", ".", "set", "(", "'width'", ",", "'100%'", ")", "style", "=", "get_style", "(", "document", ",", "table", ")", "if", "style", ":", "_table", ".", "set", "(", "'class'", ",", "get_css_classes", "(", "document", ",", "style", ")", ")", "for", "rows", "in", "table", ".", "rows", ":", "_tr", "=", "etree", ".", "SubElement", "(", "_table", ",", "'tr'", ")", "for", "cell", "in", "rows", ":", "_td", "=", "etree", ".", "SubElement", "(", "_tr", ",", "'td'", ")", "if", "cell", ".", "grid_span", "!=", "1", ":", "_td", ".", "set", "(", "'colspan'", ",", "str", "(", "cell", ".", "grid_span", ")", ")", "if", "cell", ".", "row_span", "!=", "1", ":", "_td", ".", "set", "(", "'rowspan'", ",", "str", "(", "cell", ".", "row_span", ")", ")", "for", "elem", "in", "cell", ".", "elements", ":", "if", "isinstance", "(", "elem", ",", "doc", ".", "Paragraph", ")", ":", "_ser", "=", "ctx", ".", "get_serializer", "(", "elem", ")", "_td", "=", "_ser", "(", "ctx", ",", "document", ",", "elem", ",", "_td", ",", "embed", "=", "False", ")", "if", "ctx", ".", "ilvl", "!=", "None", ":", "# root = close_list(ctx, root)", "_td", "=", "close_list", "(", "ctx", ",", "_td", ")", "ctx", ".", "ilvl", ",", "ctx", ".", "numid", "=", "None", ",", "None", "fire_hooks", "(", "ctx", ",", "document", ",", "table", ",", "_td", ",", "ctx", ".", "get_hook", "(", "'td'", ")", ")", "fire_hooks", "(", "ctx", ",", "document", ",", "table", ",", "_td", ",", "ctx", ".", "get_hook", "(", "'tr'", ")", ")", "fire_hooks", "(", "ctx", ",", "document", ",", "table", ",", "_table", ",", "ctx", ".", "get_hook", "(", "'table'", ")", ")", "return", "root" ]
Moves a resource from one parent client to another .
def move ( self , auth , resource , destinationresource , options = { "aliases" : True } , defer = False ) : return self . _call ( 'move' , auth , [ resource , destinationresource , options ] , defer )
7,316
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/onep.py#L399-L407
[ "def", "clean_expired_user_attempts", "(", "attempt_time", ":", "datetime", "=", "None", ")", "->", "int", ":", "if", "settings", ".", "AXES_COOLOFF_TIME", "is", "None", ":", "log", ".", "debug", "(", "'AXES: Skipping clean for expired access attempts because no AXES_COOLOFF_TIME is configured'", ")", "return", "0", "threshold", "=", "get_cool_off_threshold", "(", "attempt_time", ")", "count", ",", "_", "=", "AccessAttempt", ".", "objects", ".", "filter", "(", "attempt_time__lt", "=", "threshold", ")", ".", "delete", "(", ")", "log", ".", "info", "(", "'AXES: Cleaned up %s expired access attempts from database that were older than %s'", ",", "count", ",", "threshold", ")", "return", "count" ]
Given an activation code the associated entity is revoked after which the activation code can no longer be used .
def revoke ( self , auth , codetype , code , defer = False ) : return self . _call ( 'revoke' , auth , [ codetype , code ] , defer )
7,317
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/onep.py#L451-L460
[ "def", "check_parameter_similarity", "(", "files_dict", ")", ":", "try", ":", "parameter_names", "=", "files_dict", ".", "itervalues", "(", ")", ".", "next", "(", ")", ".", "keys", "(", ")", "# get the parameter names of the first file, to check if these are the same in the other files", "except", "AttributeError", ":", "# if there is no parameter at all", "if", "any", "(", "i", "is", "not", "None", "for", "i", "in", "files_dict", ".", "itervalues", "(", ")", ")", ":", "# check if there is also no parameter for the other files", "return", "False", "else", ":", "return", "True", "if", "any", "(", "parameter_names", "!=", "i", ".", "keys", "(", ")", "for", "i", "in", "files_dict", ".", "itervalues", "(", ")", ")", ":", "return", "False", "return", "True" ]
Generates a share code for the given resource .
def share ( self , auth , resource , options = { } , defer = False ) : return self . _call ( 'share' , auth , [ resource , options ] , defer )
7,318
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/onep.py#L462-L470
[ "def", "parse_port_from_tensorboard_output", "(", "tensorboard_output", ":", "str", ")", "->", "int", ":", "search", "=", "re", ".", "search", "(", "\"at http://[^:]+:([0-9]+)\"", ",", "tensorboard_output", ")", "if", "search", "is", "not", "None", ":", "port", "=", "search", ".", "group", "(", "1", ")", "return", "int", "(", "port", ")", "else", ":", "raise", "UnexpectedOutputError", "(", "tensorboard_output", ",", "\"Address and port where Tensorboard has started,\"", "\" e.g. TensorBoard 1.8.0 at http://martin-VirtualBox:36869\"", ")" ]
Updates the description of the resource .
def update ( self , auth , resource , desc = { } , defer = False ) : return self . _call ( 'update' , auth , [ resource , desc ] , defer )
7,319
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/onep.py#L478-L486
[ "def", "_init_go2bordercolor", "(", "objcolors", ",", "*", "*", "kws", ")", ":", "go2bordercolor_ret", "=", "objcolors", ".", "get_bordercolor", "(", ")", "if", "'go2bordercolor'", "not", "in", "kws", ":", "return", "go2bordercolor_ret", "go2bordercolor_usr", "=", "kws", "[", "'go2bordercolor'", "]", "goids", "=", "set", "(", "go2bordercolor_ret", ")", ".", "intersection", "(", "go2bordercolor_usr", ")", "for", "goid", "in", "goids", ":", "go2bordercolor_usr", "[", "goid", "]", "=", "go2bordercolor_ret", "[", "goid", "]", "return", "go2bordercolor_usr" ]
Returns metric usage for client and its subhierarchy .
def usage ( self , auth , resource , metric , starttime , endtime , defer = False ) : return self . _call ( 'usage' , auth , [ resource , metric , starttime , endtime ] , defer )
7,320
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/onep.py#L488-L499
[ "def", "_init_polling", "(", "self", ")", ":", "with", "self", ".", "lock", ":", "if", "not", "self", ".", "running", ":", "return", "r", "=", "random", ".", "Random", "(", ")", "delay", "=", "r", ".", "random", "(", ")", "*", "self", ".", "refresh_interval", "self", ".", "channel", ".", "io_loop", ".", "call_later", "(", "delay", "=", "delay", ",", "callback", "=", "self", ".", "_delayed_polling", ")", "self", ".", "logger", ".", "info", "(", "'Delaying throttling credit polling by %d sec'", ",", "delay", ")" ]
This is a HTTP Long Polling API which allows a user to wait on specific resources to be updated .
def wait ( self , auth , resource , options , defer = False ) : # let the server control the timeout return self . _call ( 'wait' , auth , [ resource , options ] , defer , notimeout = True )
7,321
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/onep.py#L501-L512
[ "def", "addNoiseToVector", "(", "inputVector", ",", "noiseLevel", ",", "vectorType", ")", ":", "if", "vectorType", "==", "'sparse'", ":", "corruptSparseVector", "(", "inputVector", ",", "noiseLevel", ")", "elif", "vectorType", "==", "'dense'", ":", "corruptDenseVector", "(", "inputVector", ",", "noiseLevel", ")", "else", ":", "raise", "ValueError", "(", "\"vectorType must be 'sparse' or 'dense' \"", ")" ]
Writes a single value to the resource specified .
def write ( self , auth , resource , value , options = { } , defer = False ) : return self . _call ( 'write' , auth , [ resource , value , options ] , defer )
7,322
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/onep.py#L514-L523
[ "def", "cublasZgemm", "(", "handle", ",", "transa", ",", "transb", ",", "m", ",", "n", ",", "k", ",", "alpha", ",", "A", ",", "lda", ",", "B", ",", "ldb", ",", "beta", ",", "C", ",", "ldc", ")", ":", "status", "=", "_libcublas", ".", "cublasZgemm_v2", "(", "handle", ",", "_CUBLAS_OP", "[", "transa", "]", ",", "_CUBLAS_OP", "[", "transb", "]", ",", "m", ",", "n", ",", "k", ",", "ctypes", ".", "byref", "(", "cuda", ".", "cuDoubleComplex", "(", "alpha", ".", "real", ",", "alpha", ".", "imag", ")", ")", ",", "int", "(", "A", ")", ",", "lda", ",", "int", "(", "B", ")", ",", "ldb", ",", "ctypes", ".", "byref", "(", "cuda", ".", "cuDoubleComplex", "(", "beta", ".", "real", ",", "beta", ".", "imag", ")", ")", ",", "int", "(", "C", ")", ",", "ldc", ")", "cublasCheckStatus", "(", "status", ")" ]
Writes the given values for the respective resources in the list all writes have same timestamp .
def writegroup ( self , auth , entries , defer = False ) : return self . _call ( 'writegroup' , auth , [ entries ] , defer )
7,323
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/onep.py#L525-L533
[ "def", "bus_get", "(", "celf", ",", "type", ",", "private", ",", "error", "=", "None", ")", ":", "error", ",", "my_error", "=", "_get_error", "(", "error", ")", "result", "=", "(", "dbus", ".", "dbus_bus_get", ",", "dbus", ".", "dbus_bus_get_private", ")", "[", "private", "]", "(", "type", ",", "error", ".", "_dbobj", ")", "my_error", ".", "raise_if_set", "(", ")", "if", "result", "!=", "None", ":", "result", "=", "celf", "(", "result", ")", "#end if", "return", "result" ]
calculate pressure from 3rd order Birch - Murnathan equation
def bm3_p ( v , v0 , k0 , k0p , p_ref = 0.0 ) : return cal_p_bm3 ( v , [ v0 , k0 , k0p ] , p_ref = p_ref )
7,324
https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_bm3.py#L12-L23
[ "def", "Send", "(", "self", ",", "usb", ",", "timeout_ms", "=", "None", ")", ":", "usb", ".", "BulkWrite", "(", "self", ".", "Pack", "(", ")", ",", "timeout_ms", ")", "usb", ".", "BulkWrite", "(", "self", ".", "data", ",", "timeout_ms", ")" ]
calculate pressure from 3rd order Birch - Murnaghan equation
def cal_p_bm3 ( v , k , p_ref = 0.0 ) : vvr = v / k [ 0 ] p = ( p_ref - 0.5 * ( 3. * k [ 1 ] - 5. * p_ref ) * ( 1. - vvr ** ( - 2. / 3. ) ) + 9. / 8. * k [ 1 ] * ( k [ 2 ] - 4. + 35. / 9. * p_ref / k [ 1 ] ) * ( 1. - vvr ** ( - 2. / 3. ) ) ** 2. ) * vvr ** ( - 5. / 3. ) return p
7,325
https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_bm3.py#L26-L39
[ "def", "Send", "(", "self", ",", "usb", ",", "timeout_ms", "=", "None", ")", ":", "usb", ".", "BulkWrite", "(", "self", ".", "Pack", "(", ")", ",", "timeout_ms", ")", "usb", ".", "BulkWrite", "(", "self", ".", "data", ",", "timeout_ms", ")" ]
find volume at given pressure using brenth in scipy . optimize this is for single p value not vectorized this cannot handle uncertainties
def bm3_v_single ( p , v0 , k0 , k0p , p_ref = 0.0 , min_strain = 0.01 ) : if p <= 1.e-5 : return v0 def f_diff ( v , v0 , k0 , k0p , p , p_ref = 0.0 ) : return bm3_p ( v , v0 , k0 , k0p , p_ref = p_ref ) - p v = brenth ( f_diff , v0 , v0 * min_strain , args = ( v0 , k0 , k0p , p , p_ref ) ) return v
7,326
https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_bm3.py#L42-L62
[ "def", "_update_simulation_start", "(", "self", ",", "simulation_start", ")", ":", "self", ".", "simulation_start", "=", "simulation_start", "if", "self", ".", "simulation_duration", "is", "not", "None", "and", "self", ".", "simulation_start", "is", "not", "None", ":", "self", ".", "simulation_end", "=", "self", ".", "simulation_start", "+", "self", ".", "simulation_duration", "self", ".", "_update_simulation_start_cards", "(", ")" ]
calculate bulk modulus wrapper for cal_k_bm3 cannot handle uncertainties
def bm3_k ( p , v0 , k0 , k0p ) : return cal_k_bm3 ( p , [ v0 , k0 , k0p ] )
7,327
https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_bm3.py#L96-L107
[ "def", "download", "(", "self", ",", "path", ",", "progress_callback", "=", "None", ",", "chunk_size", "=", "1024", "**", "2", ")", ":", "if", "not", "self", ".", "download_url", "or", "self", ".", "state", "!=", "'complete'", ":", "raise", "DownloadError", "(", "\"Download not available\"", ")", "# ignore parsing the Content-Disposition header, since we know the name", "download_filename", "=", "\"{}.zip\"", ".", "format", "(", "self", ".", "name", ")", "fd", "=", "None", "if", "isinstance", "(", "getattr", "(", "path", ",", "'write'", ",", "None", ")", ",", "collections", ".", "Callable", ")", ":", "# already open file-like object", "fd", "=", "path", "elif", "os", ".", "path", ".", "isdir", "(", "path", ")", ":", "# directory to download to, using the export name", "path", "=", "os", ".", "path", ".", "join", "(", "path", ",", "download_filename", ")", "# do not allow overwriting", "if", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "raise", "DownloadError", "(", "\"Download file already exists: %s\"", "%", "path", ")", "elif", "path", ":", "# fully qualified file path", "# allow overwriting", "pass", "elif", "not", "path", ":", "raise", "DownloadError", "(", "\"Empty download file path\"", ")", "with", "contextlib", ".", "ExitStack", "(", ")", "as", "stack", ":", "if", "not", "fd", ":", "fd", "=", "open", "(", "path", ",", "'wb'", ")", "# only close a file we open", "stack", ".", "callback", "(", "fd", ".", "close", ")", "r", "=", "self", ".", "_manager", ".", "client", ".", "request", "(", "'GET'", ",", "self", ".", "download_url", ",", "stream", "=", "True", ")", "stack", ".", "callback", "(", "r", ".", "close", ")", "bytes_written", "=", "0", "try", ":", "bytes_total", "=", "int", "(", "r", ".", "headers", ".", "get", "(", "'content-length'", ",", "None", ")", ")", "except", "TypeError", ":", "bytes_total", "=", "None", "if", "progress_callback", ":", "# initial callback (0%)", "progress_callback", "(", "bytes_written", ",", "bytes_total", ")", "for", "chunk", "in", "r", ".", "iter_content", "(", "chunk_size", "=", "chunk_size", ")", ":", "fd", ".", "write", "(", "chunk", ")", "bytes_written", "+=", "len", "(", "chunk", ")", "if", "progress_callback", ":", "progress_callback", "(", "bytes_written", ",", "bytes_total", ")", "return", "download_filename" ]
calculate bulk modulus
def cal_k_bm3 ( p , k ) : v = cal_v_bm3 ( p , k ) return cal_k_bm3_from_v ( v , k )
7,328
https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_bm3.py#L143-L152
[ "def", "reserve_tcp_port", "(", "self", ",", "port", ",", "project", ",", "port_range_start", "=", "None", ",", "port_range_end", "=", "None", ")", ":", "# use the default range is not specific one is given", "if", "port_range_start", "is", "None", "and", "port_range_end", "is", "None", ":", "port_range_start", "=", "self", ".", "_console_port_range", "[", "0", "]", "port_range_end", "=", "self", ".", "_console_port_range", "[", "1", "]", "if", "port", "in", "self", ".", "_used_tcp_ports", ":", "old_port", "=", "port", "port", "=", "self", ".", "get_free_tcp_port", "(", "project", ",", "port_range_start", "=", "port_range_start", ",", "port_range_end", "=", "port_range_end", ")", "msg", "=", "\"TCP port {} already in use on host {}. Port has been replaced by {}\"", ".", "format", "(", "old_port", ",", "self", ".", "_console_host", ",", "port", ")", "log", ".", "debug", "(", "msg", ")", "#project.emit(\"log.warning\", {\"message\": msg})", "return", "port", "if", "port", "<", "port_range_start", "or", "port", ">", "port_range_end", ":", "old_port", "=", "port", "port", "=", "self", ".", "get_free_tcp_port", "(", "project", ",", "port_range_start", "=", "port_range_start", ",", "port_range_end", "=", "port_range_end", ")", "msg", "=", "\"TCP port {} is outside the range {}-{} on host {}. Port has been replaced by {}\"", ".", "format", "(", "old_port", ",", "port_range_start", ",", "port_range_end", ",", "self", ".", "_console_host", ",", "port", ")", "log", ".", "debug", "(", "msg", ")", "#project.emit(\"log.warning\", {\"message\": msg})", "return", "port", "try", ":", "PortManager", ".", "_check_port", "(", "self", ".", "_console_host", ",", "port", ",", "\"TCP\"", ")", "except", "OSError", ":", "old_port", "=", "port", "port", "=", "self", ".", "get_free_tcp_port", "(", "project", ",", "port_range_start", "=", "port_range_start", ",", "port_range_end", "=", "port_range_end", ")", "msg", "=", "\"TCP port {} already in use on host {}. Port has been replaced by {}\"", ".", "format", "(", "old_port", ",", "self", ".", "_console_host", ",", "port", ")", "log", ".", "debug", "(", "msg", ")", "#project.emit(\"log.warning\", {\"message\": msg})", "return", "port", "self", ".", "_used_tcp_ports", ".", "add", "(", "port", ")", "project", ".", "record_tcp_port", "(", "port", ")", "log", ".", "debug", "(", "\"TCP port {} has been reserved\"", ".", "format", "(", "port", ")", ")", "return", "port" ]
calculate shear modulus at given pressure . not fully tested with mdaap .
def bm3_g ( p , v0 , g0 , g0p , k0 , k0p ) : return cal_g_bm3 ( p , [ g0 , g0p ] , [ v0 , k0 , k0p ] )
7,329
https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_bm3.py#L168-L181
[ "def", "delete_logs", "(", "room", ")", ":", "from", "indico_chat", ".", "plugin", "import", "ChatPlugin", "base_url", "=", "ChatPlugin", ".", "settings", ".", "get", "(", "'log_url'", ")", "if", "not", "base_url", "or", "room", ".", "custom_server", ":", "return", "try", ":", "response", "=", "requests", ".", "get", "(", "posixpath", ".", "join", "(", "base_url", ",", "'delete'", ")", ",", "params", "=", "{", "'cr'", ":", "room", ".", "jid", "}", ")", ".", "json", "(", ")", "except", "(", "RequestException", ",", "ValueError", ")", ":", "current_plugin", ".", "logger", ".", "exception", "(", "'Could not delete logs for %s'", ",", "room", ".", "jid", ")", "return", "if", "not", "response", ".", "get", "(", "'success'", ")", ":", "current_plugin", ".", "logger", ".", "warning", "(", "'Could not delete logs for %s: %s'", ",", "room", ".", "jid", ",", "response", ".", "get", "(", "'error'", ")", ")" ]
calculate shear modulus at given pressure
def cal_g_bm3 ( p , g , k ) : v = cal_v_bm3 ( p , k ) v0 = k [ 0 ] k0 = k [ 1 ] kp = k [ 2 ] g0 = g [ 0 ] gp = g [ 1 ] f = 0.5 * ( ( v / v0 ) ** ( - 2. / 3. ) - 1. ) return ( 1. + 2. * f ) ** ( 5. / 2. ) * ( g0 + ( 3. * k0 * gp - 5. * g0 ) * f + ( 6. * k0 * gp - 24. * k0 - 14. * g0 + 9. / 2. * k0 * kp ) * f ** 2. )
7,330
https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_bm3.py#L184-L202
[ "def", "_remote_connection", "(", "server", ",", "opts", ",", "argparser_", ")", ":", "global", "CONN", "# pylint: disable=global-statement", "if", "opts", ".", "timeout", "is", "not", "None", ":", "if", "opts", ".", "timeout", "<", "0", "or", "opts", ".", "timeout", ">", "300", ":", "argparser_", ".", "error", "(", "'timeout option(%s) out of range'", "%", "opts", ".", "timeout", ")", "# mock only uses the namespace timeout and statistics options from the", "# original set of options. It ignores the url", "if", "opts", ".", "mock_server", ":", "CONN", "=", "FakedWBEMConnection", "(", "default_namespace", "=", "opts", ".", "namespace", ",", "timeout", "=", "opts", ".", "timeout", ",", "stats_enabled", "=", "opts", ".", "statistics", ")", "try", ":", "build_mock_repository", "(", "CONN", ",", "opts", ".", "mock_server", ",", "opts", ".", "verbose", ")", "except", "ValueError", "as", "ve", ":", "argparser_", ".", "error", "(", "'Build Repository failed: %s'", "%", "ve", ")", "return", "CONN", "if", "server", "[", "0", "]", "==", "'/'", ":", "url", "=", "server", "elif", "re", ".", "match", "(", "r\"^https{0,1}://\"", ",", "server", ")", "is", "not", "None", ":", "url", "=", "server", "elif", "re", ".", "match", "(", "r\"^[a-zA-Z0-9]+://\"", ",", "server", ")", "is", "not", "None", ":", "argparser_", ".", "error", "(", "'Invalid scheme on server argument.'", "' Use \"http\" or \"https\"'", ")", "else", ":", "url", "=", "'%s://%s'", "%", "(", "'https'", ",", "server", ")", "creds", "=", "None", "if", "opts", ".", "key_file", "is", "not", "None", "and", "opts", ".", "cert_file", "is", "None", ":", "argparser_", ".", "error", "(", "'keyfile option requires certfile option'", ")", "if", "opts", ".", "user", "is", "not", "None", "and", "opts", ".", "password", "is", "None", ":", "opts", ".", "password", "=", "_getpass", ".", "getpass", "(", "'Enter password for %s: '", "%", "opts", ".", "user", ")", "if", "opts", ".", "user", "is", "not", "None", "or", "opts", ".", "password", "is", "not", "None", ":", "creds", "=", "(", "opts", ".", "user", ",", "opts", ".", "password", ")", "# if client cert and key provided, create dictionary for", "# wbem connection", "x509_dict", "=", "None", "if", "opts", ".", "cert_file", "is", "not", "None", ":", "x509_dict", "=", "{", "\"cert_file\"", ":", "opts", ".", "cert_file", "}", "if", "opts", ".", "key_file", "is", "not", "None", ":", "x509_dict", ".", "update", "(", "{", "'key_file'", ":", "opts", ".", "key_file", "}", ")", "CONN", "=", "WBEMConnection", "(", "url", ",", "creds", ",", "default_namespace", "=", "opts", ".", "namespace", ",", "no_verification", "=", "opts", ".", "no_verify_cert", ",", "x509", "=", "x509_dict", ",", "ca_certs", "=", "opts", ".", "ca_certs", ",", "timeout", "=", "opts", ".", "timeout", ",", "stats_enabled", "=", "opts", ".", "statistics", ")", "CONN", ".", "debug", "=", "True", "return", "CONN" ]
calculate big F for linearlized form not fully tested
def bm3_big_F ( p , v , v0 ) : f = bm3_small_f ( v , v0 ) return cal_big_F ( p , f )
7,331
https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_bm3.py#L217-L227
[ "async", "def", "upload_file", "(", "self", ",", "Filename", ",", "Bucket", ",", "Key", ",", "ExtraArgs", "=", "None", ",", "Callback", "=", "None", ",", "Config", "=", "None", ")", ":", "with", "open", "(", "Filename", ",", "'rb'", ")", "as", "open_file", ":", "await", "upload_fileobj", "(", "self", ",", "open_file", ",", "Bucket", ",", "Key", ",", "ExtraArgs", "=", "ExtraArgs", ",", "Callback", "=", "Callback", ",", "Config", "=", "Config", ")" ]
Initialize poolmanager with cipher and Tlsv1
def init_poolmanager ( self , connections , maxsize , block = requests . adapters . DEFAULT_POOLBLOCK , * * pool_kwargs ) : context = create_urllib3_context ( ciphers = self . CIPHERS , ssl_version = ssl . PROTOCOL_TLSv1 ) pool_kwargs [ 'ssl_context' ] = context return super ( TLSv1Adapter , self ) . init_poolmanager ( connections , maxsize , block , * * pool_kwargs )
7,332
https://github.com/dingusdk/PythonIhcSdk/blob/7e2067e009fe7600b49f30bff1cf91dc72fc891e/ihcsdk/ihcsslconnection.py#L47-L55
[ "def", "_error_messages", "(", "self", ",", "driver_id", ")", ":", "assert", "isinstance", "(", "driver_id", ",", "ray", ".", "DriverID", ")", "message", "=", "self", ".", "redis_client", ".", "execute_command", "(", "\"RAY.TABLE_LOOKUP\"", ",", "ray", ".", "gcs_utils", ".", "TablePrefix", ".", "ERROR_INFO", ",", "\"\"", ",", "driver_id", ".", "binary", "(", ")", ")", "# If there are no errors, return early.", "if", "message", "is", "None", ":", "return", "[", "]", "gcs_entries", "=", "ray", ".", "gcs_utils", ".", "GcsTableEntry", ".", "GetRootAsGcsTableEntry", "(", "message", ",", "0", ")", "error_messages", "=", "[", "]", "for", "i", "in", "range", "(", "gcs_entries", ".", "EntriesLength", "(", ")", ")", ":", "error_data", "=", "ray", ".", "gcs_utils", ".", "ErrorTableData", ".", "GetRootAsErrorTableData", "(", "gcs_entries", ".", "Entries", "(", "i", ")", ",", "0", ")", "assert", "driver_id", ".", "binary", "(", ")", "==", "error_data", ".", "DriverId", "(", ")", "error_message", "=", "{", "\"type\"", ":", "decode", "(", "error_data", ".", "Type", "(", ")", ")", ",", "\"message\"", ":", "decode", "(", "error_data", ".", "ErrorMessage", "(", ")", ")", ",", "\"timestamp\"", ":", "error_data", ".", "Timestamp", "(", ")", ",", "}", "error_messages", ".", "append", "(", "error_message", ")", "return", "error_messages" ]
Ensure cipher and Tlsv1
def proxy_manager_for ( self , proxy , * * proxy_kwargs ) : context = create_urllib3_context ( ciphers = self . CIPHERS , ssl_version = ssl . PROTOCOL_TLSv1 ) proxy_kwargs [ 'ssl_context' ] = context return super ( TLSv1Adapter , self ) . proxy_manager_for ( proxy , * * proxy_kwargs )
7,333
https://github.com/dingusdk/PythonIhcSdk/blob/7e2067e009fe7600b49f30bff1cf91dc72fc891e/ihcsdk/ihcsslconnection.py#L57-L63
[ "def", "_archive_write_data", "(", "archive", ",", "data", ")", ":", "n", "=", "libarchive", ".", "calls", ".", "archive_write", ".", "c_archive_write_data", "(", "archive", ",", "ctypes", ".", "cast", "(", "ctypes", ".", "c_char_p", "(", "data", ")", ",", "ctypes", ".", "c_void_p", ")", ",", "len", "(", "data", ")", ")", "if", "n", "==", "0", ":", "message", "=", "c_archive_error_string", "(", "archive", ")", "raise", "ValueError", "(", "\"No bytes were written. Error? [%s]\"", "%", "(", "message", ")", ")" ]
Parse the formulae from the content written by the script to standard out .
def parse_stdout ( self , filelike ) : from aiida . orm import Dict formulae = { } content = filelike . read ( ) . strip ( ) if not content : return self . exit_codes . ERROR_EMPTY_OUTPUT_FILE try : for line in content . split ( '\n' ) : datablock , formula = re . split ( r'\s+' , line . strip ( ) , 1 ) formulae [ datablock ] = formula except Exception : # pylint: disable=broad-except self . logger . exception ( 'Failed to parse formulae from the stdout file\n%s' , traceback . format_exc ( ) ) return self . exit_codes . ERROR_PARSING_OUTPUT_DATA else : self . out ( 'formulae' , Dict ( dict = formulae ) ) return
7,334
https://github.com/aiidateam/aiida-codtools/blob/da5e4259b7a2e86cf0cc3f997e11dd36d445fa94/aiida_codtools/parsers/cif_cell_contents.py#L18-L42
[ "def", "set_key_color", "(", "self", ",", "color", ":", "Tuple", "[", "int", ",", "int", ",", "int", "]", ")", "->", "None", ":", "lib", ".", "TCOD_image_set_key_color", "(", "self", ".", "image_c", ",", "color", ")" ]
Return a new feature system from context string in the given format .
def make_features ( context , frmat = 'table' , str_maximal = False ) : config = Config . create ( context = context , format = frmat , str_maximal = str_maximal ) return FeatureSystem ( config )
7,335
https://github.com/xflr6/features/blob/f985304dd642da6ecdc66d85167d00daa4efe5f4/features/__init__.py#L31-L50
[ "def", "add_metadata", "(", "file_name", ",", "title", ",", "artist", ",", "album", ")", ":", "tags", "=", "EasyMP3", "(", "file_name", ")", "if", "title", ":", "tags", "[", "\"title\"", "]", "=", "title", "if", "artist", ":", "tags", "[", "\"artist\"", "]", "=", "artist", "if", "album", ":", "tags", "[", "\"album\"", "]", "=", "album", "tags", ".", "save", "(", ")", "return", "file_name" ]
calculate pressure from vinet equation
def vinet_p ( v , v0 , k0 , k0p ) : # unumpy.exp works for both numpy and unumpy # so I set uncertainty default. # if unumpy.exp is used for lmfit, it generates an error return cal_p_vinet ( v , [ v0 , k0 , k0p ] , uncertainties = isuncertainties ( [ v , v0 , k0 , k0p ] ) )
7,336
https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_vinet.py#L13-L27
[ "def", "roles", "(", "self", ",", "clear_features", "=", "True", ",", "*", "*", "field_roles", ")", ":", "field_roles", "=", "dict", "(", "(", "k", ",", "v", ".", "name", "if", "isinstance", "(", "v", ",", "SequenceExpr", ")", "else", "v", ")", "for", "k", ",", "v", "in", "six", ".", "iteritems", "(", "field_roles", ")", ")", "self", ".", "_assert_ml_fields_valid", "(", "*", "list", "(", "six", ".", "itervalues", "(", "field_roles", ")", ")", ")", "field_roles", "=", "dict", "(", "(", "_get_field_name", "(", "f", ")", ",", "MLField", ".", "translate_role_name", "(", "role", ")", ")", "for", "role", ",", "f", "in", "six", ".", "iteritems", "(", "field_roles", ")", ")", "if", "field_roles", ":", "return", "_change_singleton_roles", "(", "self", ",", "field_roles", ",", "clear_features", ")", "else", ":", "return", "self" ]
find volume at given pressure using brenth in scipy . optimize this is for single p value not vectorized
def vinet_v_single ( p , v0 , k0 , k0p , min_strain = 0.01 ) : if p <= 1.e-5 : return v0 def f_diff ( v , v0 , k0 , k0p , p ) : return vinet_p ( v , v0 , k0 , k0p ) - p v = brenth ( f_diff , v0 , v0 * min_strain , args = ( v0 , k0 , k0p , p ) ) return v
7,337
https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_vinet.py#L53-L71
[ "def", "_update_simulation_start", "(", "self", ",", "simulation_start", ")", ":", "self", ".", "simulation_start", "=", "simulation_start", "if", "self", ".", "simulation_duration", "is", "not", "None", "and", "self", ".", "simulation_start", "is", "not", "None", ":", "self", ".", "simulation_end", "=", "self", ".", "simulation_start", "+", "self", ".", "simulation_duration", "self", ".", "_update_simulation_start_cards", "(", ")" ]
find volume at given pressure
def vinet_v ( p , v0 , k0 , k0p , min_strain = 0.01 ) : if isuncertainties ( [ p , v0 , k0 , k0p ] ) : f_u = np . vectorize ( uct . wrap ( vinet_v_single ) , excluded = [ 1 , 2 , 3 , 4 ] ) return f_u ( p , v0 , k0 , k0p , min_strain = min_strain ) else : f_v = np . vectorize ( vinet_v_single , excluded = [ 1 , 2 , 3 , 4 ] ) return f_v ( p , v0 , k0 , k0p , min_strain = min_strain )
7,338
https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_vinet.py#L74-L91
[ "def", "get_files", "(", "cls", ",", "folder", ",", "session_id", "=", "''", ")", ":", "filelist", "=", "[", "]", "if", "folder", "is", "None", "or", "not", "os", ".", "path", ".", "isdir", "(", "folder", ")", ":", "return", "filelist", "if", "session_id", "is", "None", ":", "session_id", "=", "''", "for", "root", ",", "dirs", ",", "files", "in", "os", ".", "walk", "(", "folder", ")", ":", "for", "filename", "in", "files", ":", "if", "filename", ".", "startswith", "(", "'Session %s'", "%", "session_id", ")", "and", "filename", ".", "endswith", "(", "'.mqo'", ")", ":", "filename", "=", "os", ".", "path", ".", "join", "(", "root", ",", "filename", ")", "filelist", ".", "append", "(", "filename", ")", "return", "filelist" ]
calculate bulk modulus wrapper for cal_k_vinet cannot handle uncertainties
def vinet_k ( p , v0 , k0 , k0p , numerical = False ) : f_u = uct . wrap ( cal_k_vinet ) return f_u ( p , [ v0 , k0 , k0p ] )
7,339
https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_vinet.py#L106-L118
[ "def", "save", "(", "self_or_cls", ",", "obj", ",", "basename", ",", "fmt", "=", "'auto'", ",", "key", "=", "{", "}", ",", "info", "=", "{", "}", ",", "options", "=", "None", ",", "*", "*", "kwargs", ")", ":", "if", "info", "or", "key", ":", "raise", "Exception", "(", "'Renderer does not support saving metadata to file.'", ")", "if", "isinstance", "(", "obj", ",", "(", "Plot", ",", "NdWidget", ")", ")", ":", "plot", "=", "obj", "else", ":", "with", "StoreOptions", ".", "options", "(", "obj", ",", "options", ",", "*", "*", "kwargs", ")", ":", "plot", "=", "self_or_cls", ".", "get_plot", "(", "obj", ")", "if", "(", "fmt", "in", "list", "(", "self_or_cls", ".", "widgets", ".", "keys", "(", ")", ")", "+", "[", "'auto'", "]", ")", "and", "len", "(", "plot", ")", ">", "1", ":", "with", "StoreOptions", ".", "options", "(", "obj", ",", "options", ",", "*", "*", "kwargs", ")", ":", "if", "isinstance", "(", "basename", ",", "basestring", ")", ":", "basename", "=", "basename", "+", "'.html'", "self_or_cls", ".", "export_widgets", "(", "plot", ",", "basename", ",", "fmt", ")", "return", "rendered", "=", "self_or_cls", "(", "plot", ",", "fmt", ")", "if", "rendered", "is", "None", ":", "return", "(", "data", ",", "info", ")", "=", "rendered", "encoded", "=", "self_or_cls", ".", "encode", "(", "rendered", ")", "prefix", "=", "self_or_cls", ".", "_save_prefix", "(", "info", "[", "'file-ext'", "]", ")", "if", "prefix", ":", "encoded", "=", "prefix", "+", "encoded", "if", "isinstance", "(", "basename", ",", "(", "BytesIO", ",", "StringIO", ")", ")", ":", "basename", ".", "write", "(", "encoded", ")", "basename", ".", "seek", "(", "0", ")", "else", ":", "filename", "=", "'%s.%s'", "%", "(", "basename", ",", "info", "[", "'file-ext'", "]", ")", "with", "open", "(", "filename", ",", "'wb'", ")", "as", "f", ":", "f", ".", "write", "(", "encoded", ")" ]
This function is broken and needs to either be fixed or discarded .
def user_portals_picker ( self ) : # print("Getting Portals list. This could take a few seconds...") portals = self . get_portals_list ( ) done = False while not done : opts = [ ( i , p ) for i , p in enumerate ( portals ) ] # print('') for opt , portal in opts : print ( "\t{0} - {1}" . format ( opt , portal [ 1 ] ) ) # print('') valid_choices = [ o [ 0 ] for o in opts ] choice = _input ( "Enter choice ({0}): " . format ( valid_choices ) ) if int ( choice ) in valid_choices : done = True # loop through all portals until we find an 'id':'rid' match self . set_portal_name ( opts [ int ( choice ) ] [ 1 ] [ 1 ] ) self . set_portal_id ( opts [ int ( choice ) ] [ 1 ] [ 0 ] ) # self.set_portal_rid( opts[int(choice)][1][2][1]['info']['key'] ) # self.__portal_sn_rid_dict = opts[int(choice)][1][2][1]['info']['aliases'] else : print ( "'{0}' is not a valid choice. Please choose from {1}" . format ( choice , valid_choices ) )
7,340
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/portals/__init__.py#L59-L88
[ "def", "_read_configuration", "(", "config_filename", ")", ":", "config", "=", "ConfigParser", "(", ")", "config", ".", "read", "(", "config_filename", ")", "if", "'supplement'", "in", "config", "[", "'database'", "]", ":", "path", "=", "os", ".", "path", ".", "dirname", "(", "config_filename", ")", "+", "'/'", "+", "config", ".", "get", "(", "'database'", ",", "'supplement'", ")", "config_supplement", "=", "ConfigParser", "(", ")", "config_supplement", ".", "read", "(", "path", ")", "else", ":", "config_supplement", "=", "None", "return", "config", ",", "config_supplement" ]
Set active portal according to the name passed in portal_name .
def get_portal_by_name ( self , portal_name ) : portals = self . get_portals_list ( ) for p in portals : # print("Checking {!r}".format(p)) if portal_name == p [ 1 ] : # print("Found Portal!") self . set_portal_name ( p [ 1 ] ) self . set_portal_id ( p [ 0 ] ) self . set_portal_cik ( p [ 2 ] [ 1 ] [ 'info' ] [ 'key' ] ) # print("Active Portal Details:\nName: {0}\nId: {1}\nCIK: {2}".format( # self.portal_name(), # self.portal_id(), # self.portal_cik())) return p return None
7,341
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/portals/__init__.py#L91-L111
[ "def", "_generate_examples_validation", "(", "self", ",", "archive", ",", "labels", ")", ":", "# Get the current random seeds.", "numpy_st0", "=", "np", ".", "random", ".", "get_state", "(", ")", "# Set new random seeds.", "np", ".", "random", ".", "seed", "(", "135", ")", "logging", ".", "warning", "(", "'Overwriting cv2 RNG seed.'", ")", "tfds", ".", "core", ".", "lazy_imports", ".", "cv2", ".", "setRNGSeed", "(", "357", ")", "for", "example", "in", "super", "(", "Imagenet2012Corrupted", ",", "self", ")", ".", "_generate_examples_validation", "(", "archive", ",", "labels", ")", ":", "with", "tf", ".", "Graph", "(", ")", ".", "as_default", "(", ")", ":", "tf_img", "=", "tf", ".", "image", ".", "decode_jpeg", "(", "example", "[", "'image'", "]", ".", "read", "(", ")", ",", "channels", "=", "3", ")", "image_np", "=", "tfds", ".", "as_numpy", "(", "tf_img", ")", "example", "[", "'image'", "]", "=", "self", ".", "_get_corrupted_example", "(", "image_np", ")", "yield", "example", "# Reset the seeds back to their original values.", "np", ".", "random", ".", "set_state", "(", "numpy_st0", ")" ]
Deletes device object with given rid
def delete_device ( self , rid ) : headers = { 'User-Agent' : self . user_agent ( ) , 'Content-Type' : self . content_type ( ) } headers . update ( self . headers ( ) ) r = requests . delete ( self . portals_url ( ) + '/devices/' + rid , headers = headers , auth = self . auth ( ) ) if HTTP_STATUS . NO_CONTENT == r . status_code : print ( "Successfully deleted device with rid: {0}" . format ( rid ) ) return True else : print ( "Something went wrong: <{0}>: {1}" . format ( r . status_code , r . reason ) ) r . raise_for_status ( ) return False
7,342
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/portals/__init__.py#L272-L293
[ "def", "_get_manifest_list", "(", "self", ",", "image", ")", ":", "if", "image", "in", "self", ".", "manifest_list_cache", ":", "return", "self", ".", "manifest_list_cache", "[", "image", "]", "manifest_list", "=", "get_manifest_list", "(", "image", ",", "image", ".", "registry", ",", "insecure", "=", "self", ".", "parent_registry_insecure", ",", "dockercfg_path", "=", "self", ".", "parent_registry_dockercfg_path", ")", "if", "'@sha256:'", "in", "str", "(", "image", ")", "and", "not", "manifest_list", ":", "# we want to adjust the tag only for manifest list fetching", "image", "=", "image", ".", "copy", "(", ")", "try", ":", "config_blob", "=", "get_config_from_registry", "(", "image", ",", "image", ".", "registry", ",", "image", ".", "tag", ",", "insecure", "=", "self", ".", "parent_registry_insecure", ",", "dockercfg_path", "=", "self", ".", "parent_registry_dockercfg_path", ")", "except", "(", "HTTPError", ",", "RetryError", ",", "Timeout", ")", "as", "ex", ":", "self", ".", "log", ".", "warning", "(", "'Unable to fetch config for %s, got error %s'", ",", "image", ",", "ex", ".", "response", ".", "status_code", ")", "raise", "RuntimeError", "(", "'Unable to fetch config for base image'", ")", "release", "=", "config_blob", "[", "'config'", "]", "[", "'Labels'", "]", "[", "'release'", "]", "version", "=", "config_blob", "[", "'config'", "]", "[", "'Labels'", "]", "[", "'version'", "]", "docker_tag", "=", "\"%s-%s\"", "%", "(", "version", ",", "release", ")", "image", ".", "tag", "=", "docker_tag", "manifest_list", "=", "get_manifest_list", "(", "image", ",", "image", ".", "registry", ",", "insecure", "=", "self", ".", "parent_registry_insecure", ",", "dockercfg_path", "=", "self", ".", "parent_registry_dockercfg_path", ")", "self", ".", "manifest_list_cache", "[", "image", "]", "=", "manifest_list", "return", "self", ".", "manifest_list_cache", "[", "image", "]" ]
List data sources of a portal device with rid device_rid .
def list_device_data_sources ( self , device_rid ) : headers = { 'User-Agent' : self . user_agent ( ) , } headers . update ( self . headers ( ) ) r = requests . get ( self . portals_url ( ) + '/devices/' + device_rid + '/data-sources' , headers = headers , auth = self . auth ( ) ) if HTTP_STATUS . OK == r . status_code : return r . json ( ) else : print ( "Something went wrong: <{0}>: {1}" . format ( r . status_code , r . reason ) ) return None
7,343
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/portals/__init__.py#L317-L335
[ "def", "_get_cache_filename", "(", "name", ",", "filename", ")", ":", "filename", "=", "os", ".", "path", ".", "abspath", "(", "filename", ")", "[", "1", ":", "]", "home_folder", "=", "os", ".", "path", ".", "expanduser", "(", "'~'", ")", "base_cache_dir", "=", "os", ".", "path", ".", "join", "(", "home_folder", ",", "'.git-lint'", ",", "'cache'", ")", "return", "os", ".", "path", ".", "join", "(", "base_cache_dir", ",", "name", ",", "filename", ")" ]
This grabs each datasource and its multiple datapoints for a particular device .
def get_data_source_bulk_request ( self , rids , limit = 5 ) : headers = { 'User-Agent' : self . user_agent ( ) , 'Content-Type' : self . content_type ( ) } headers . update ( self . headers ( ) ) r = requests . get ( self . portals_url ( ) + '/data-sources/[' + "," . join ( rids ) + ']/data?limit=' + str ( limit ) , headers = headers , auth = self . auth ( ) ) if HTTP_STATUS . OK == r . status_code : return r . json ( ) else : print ( "Something went wrong: <{0}>: {1}" . format ( r . status_code , r . reason ) ) return { }
7,344
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/portals/__init__.py#L337-L357
[ "def", "cli", "(", "env", ",", "identifier", ",", "crt", ",", "csr", ",", "icc", ",", "key", ",", "notes", ")", ":", "template", "=", "{", "'id'", ":", "identifier", "}", "if", "crt", ":", "template", "[", "'certificate'", "]", "=", "open", "(", "crt", ")", ".", "read", "(", ")", "if", "key", ":", "template", "[", "'privateKey'", "]", "=", "open", "(", "key", ")", ".", "read", "(", ")", "if", "csr", ":", "template", "[", "'certificateSigningRequest'", "]", "=", "open", "(", "csr", ")", ".", "read", "(", ")", "if", "icc", ":", "template", "[", "'intermediateCertificate'", "]", "=", "open", "(", "icc", ")", ".", "read", "(", ")", "if", "notes", ":", "template", "[", "'notes'", "]", "=", "notes", "manager", "=", "SoftLayer", ".", "SSLManager", "(", "env", ".", "client", ")", "manager", ".", "edit_certificate", "(", "template", ")" ]
This loops through the get_multiple_devices method 10 rids at a time .
def get_all_devices_in_portal ( self ) : rids = self . get_portal_by_name ( self . portal_name ( ) ) [ 2 ] [ 1 ] [ 'info' ] [ 'aliases' ] # print("RIDS: {0}".format(rids)) device_rids = [ rid . strip ( ) for rid in rids ] blocks_of_ten = [ device_rids [ x : x + 10 ] for x in range ( 0 , len ( device_rids ) , 10 ) ] devices = [ ] for block_of_ten in blocks_of_ten : retval = self . get_multiple_devices ( block_of_ten ) if retval is not None : devices . extend ( retval ) else : print ( "Not adding to device list: {!r}" . format ( retval ) ) # Parse 'meta' key's raw string values for each device for device in devices : dictify_device_meta ( device ) return devices
7,345
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/portals/__init__.py#L366-L390
[ "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", ")" ]
A device object knows its rid but not its alias . A portal object knows its device rids and aliases .
def map_aliases_to_device_objects ( self ) : all_devices = self . get_all_devices_in_portal ( ) for dev_o in all_devices : dev_o [ 'portals_aliases' ] = self . get_portal_by_name ( self . portal_name ( ) ) [ 2 ] [ 1 ] [ 'info' ] [ 'aliases' ] [ dev_o [ 'rid' ] ] return all_devices
7,346
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/portals/__init__.py#L392-L405
[ "def", "_CompressHistogram", "(", "self", ",", "histo_ev", ")", ":", "return", "CompressedHistogramEvent", "(", "histo_ev", ".", "wall_time", ",", "histo_ev", ".", "step", ",", "compressor", ".", "compress_histogram_proto", "(", "histo_ev", ".", "histogram_value", ",", "self", ".", "_compression_bps", ")", ")" ]
Returns a list of device objects that match the serial number in param sn .
def search_for_devices_by_serial_number ( self , sn ) : import re sn_search = re . compile ( sn ) matches = [ ] for dev_o in self . get_all_devices_in_portal ( ) : # print("Checking {0}".format(dev_o['sn'])) try : if sn_search . match ( dev_o [ 'sn' ] ) : matches . append ( dev_o ) except TypeError as err : print ( "Problem checking device {!r}: {!r}" . format ( dev_o [ 'info' ] [ 'description' ] [ 'name' ] , str ( err ) ) ) return matches
7,347
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/portals/__init__.py#L407-L429
[ "def", "get_position", "(", "self", ",", ")", ":", "pos", "=", "QtGui", ".", "QCursor", ".", "pos", "(", ")", "if", "self", ".", "_alignment", "&", "QtCore", ".", "Qt", ".", "AlignLeft", "==", "QtCore", ".", "Qt", ".", "AlignLeft", ":", "pos", ".", "setX", "(", "pos", ".", "x", "(", ")", "-", "self", ".", "_offset", ")", "elif", "self", ".", "_alignment", "&", "QtCore", ".", "Qt", ".", "AlignRight", "==", "QtCore", ".", "Qt", ".", "AlignRight", ":", "pos", ".", "setX", "(", "pos", ".", "x", "(", ")", "-", "self", ".", "frameGeometry", "(", ")", ".", "width", "(", ")", "+", "self", ".", "_offset", ")", "elif", "self", ".", "_alignment", "&", "QtCore", ".", "Qt", ".", "AlignHCenter", "==", "QtCore", ".", "Qt", ".", "AlignHCenter", ":", "pos", ".", "setX", "(", "pos", ".", "x", "(", ")", "-", "self", ".", "frameGeometry", "(", ")", ".", "width", "(", ")", "/", "2", ")", "if", "self", ".", "_alignment", "&", "QtCore", ".", "Qt", ".", "AlignTop", "==", "QtCore", ".", "Qt", ".", "AlignTop", ":", "pos", ".", "setY", "(", "pos", ".", "y", "(", ")", "-", "self", ".", "_offset", ")", "elif", "self", ".", "_alignment", "&", "QtCore", ".", "Qt", ".", "AlignBottom", "==", "QtCore", ".", "Qt", ".", "AlignBottom", ":", "pos", ".", "setY", "(", "pos", ".", "y", "(", ")", "-", "self", ".", "frameGeometry", "(", ")", ".", "height", "(", ")", "+", "self", ".", "_offset", ")", "elif", "self", ".", "_alignment", "&", "QtCore", ".", "Qt", ".", "AlignVCenter", "==", "QtCore", ".", "Qt", ".", "AlignVCenter", ":", "pos", ".", "setY", "(", "pos", ".", "y", "(", ")", "-", "self", ".", "frameGeometry", "(", ")", ".", "height", "(", ")", "/", "2", ")", "return", "pos" ]
Optional parameter is a list of device objects . If omitted will just print all portal devices objects .
def print_device_list ( self , device_list = None ) : dev_list = device_list if device_list is not None else self . get_all_devices_in_portal ( ) for dev in dev_list : print ( '{0}\t\t{1}\t\t{2}' . format ( dev [ 'info' ] [ 'description' ] [ 'name' ] , dev [ 'sn' ] , dev [ 'portals_aliases' ] if len ( dev [ 'portals_aliases' ] ) != 1 else dev [ 'portals_aliases' ] [ 0 ] ) )
7,348
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/portals/__init__.py#L431-L446
[ "def", "make_library", "(", "*", "*", "kwargs", ")", ":", "library_yaml", "=", "kwargs", ".", "pop", "(", "'library'", ",", "'models/library.yaml'", ")", "comp_yaml", "=", "kwargs", ".", "pop", "(", "'comp'", ",", "'config/binning.yaml'", ")", "basedir", "=", "kwargs", ".", "pop", "(", "'basedir'", ",", "os", ".", "path", ".", "abspath", "(", "'.'", ")", ")", "model_man", "=", "kwargs", ".", "get", "(", "'ModelManager'", ",", "ModelManager", "(", "basedir", "=", "basedir", ")", ")", "model_comp_dict", "=", "model_man", ".", "make_library", "(", "library_yaml", ",", "library_yaml", ",", "comp_yaml", ")", "return", "dict", "(", "model_comp_dict", "=", "model_comp_dict", ",", "ModelManager", "=", "model_man", ")" ]
Takes in a sort key and prints the device list according to that sort .
def print_sorted_device_list ( self , device_list = None , sort_key = 'sn' ) : dev_list = device_list if device_list is not None else self . get_all_devices_in_portal ( ) sorted_dev_list = [ ] if sort_key == 'sn' : sort_keys = [ k [ sort_key ] for k in dev_list if k [ sort_key ] is not None ] sort_keys = sorted ( sort_keys ) for key in sort_keys : sorted_dev_list . extend ( [ d for d in dev_list if d [ 'sn' ] == key ] ) elif sort_key == 'name' : sort_keys = [ k [ 'info' ] [ 'description' ] [ sort_key ] for k in dev_list if k [ 'info' ] [ 'description' ] [ sort_key ] is not None ] sort_keys = sorted ( sort_keys ) for key in sort_keys : sorted_dev_list . extend ( [ d for d in dev_list if d [ 'info' ] [ 'description' ] [ sort_key ] == key ] ) elif sort_key == 'portals_aliases' : sort_keys = [ k [ sort_key ] for k in dev_list if k [ sort_key ] is not None ] sort_keys = sorted ( sort_keys ) for key in sort_keys : sorted_dev_list . extend ( [ d for d in dev_list if d [ sort_key ] == key ] ) else : print ( "Sort key {!r} not recognized." . format ( sort_key ) ) sort_keys = None self . print_device_list ( device_list = sorted_dev_list )
7,349
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/portals/__init__.py#L448-L489
[ "def", "oauth_error_handler", "(", "f", ")", ":", "@", "wraps", "(", "f", ")", "def", "inner", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# OAuthErrors should not happen, so they are not caught here. Hence", "# they will result in a 500 Internal Server Error which is what we", "# are interested in.", "try", ":", "return", "f", "(", "*", "args", ",", "*", "*", "kwargs", ")", "except", "OAuthClientError", "as", "e", ":", "current_app", ".", "logger", ".", "warning", "(", "e", ".", "message", ",", "exc_info", "=", "True", ")", "return", "oauth2_handle_error", "(", "e", ".", "remote", ",", "e", ".", "response", ",", "e", ".", "code", ",", "e", ".", "uri", ",", "e", ".", "description", ")", "except", "OAuthCERNRejectedAccountError", "as", "e", ":", "current_app", ".", "logger", ".", "warning", "(", "e", ".", "message", ",", "exc_info", "=", "True", ")", "flash", "(", "_", "(", "'CERN account not allowed.'", ")", ",", "category", "=", "'danger'", ")", "return", "redirect", "(", "'/'", ")", "except", "OAuthRejectedRequestError", ":", "flash", "(", "_", "(", "'You rejected the authentication request.'", ")", ",", "category", "=", "'info'", ")", "return", "redirect", "(", "'/'", ")", "except", "AlreadyLinkedError", ":", "flash", "(", "_", "(", "'External service is already linked to another account.'", ")", ",", "category", "=", "'danger'", ")", "return", "redirect", "(", "url_for", "(", "'invenio_oauthclient_settings.index'", ")", ")", "return", "inner" ]
Uses the get - all - user - accounts Portals API to retrieve the user - id by supplying an email .
def get_user_id_from_email ( self , email ) : accts = self . get_all_user_accounts ( ) for acct in accts : if acct [ 'email' ] == email : return acct [ 'id' ] return None
7,350
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/portals/__init__.py#L491-L499
[ "def", "build_synchronize_decorator", "(", ")", ":", "lock", "=", "threading", ".", "Lock", "(", ")", "def", "lock_decorator", "(", "fn", ")", ":", "@", "functools", ".", "wraps", "(", "fn", ")", "def", "lock_decorated", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "with", "lock", ":", "return", "fn", "(", "*", "args", ",", "*", "*", "kwargs", ")", "return", "lock_decorated", "return", "lock_decorator" ]
Returns a user s permissions object when given the user email .
def get_user_permission_from_email ( self , email ) : _id = self . get_user_id_from_email ( email ) return self . get_user_permission ( _id )
7,351
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/portals/__init__.py#L501-L504
[ "def", "delete_attachments", "(", "self", ",", "volumeID", ",", "attachmentsID", ")", ":", "log", ".", "debug", "(", "\"deleting attachments from volume '{}': {}\"", ".", "format", "(", "volumeID", ",", "attachmentsID", ")", ")", "rawVolume", "=", "self", ".", "_req_raw_volume", "(", "volumeID", ")", "insID", "=", "[", "a", "[", "'id'", "]", "for", "a", "in", "rawVolume", "[", "'_source'", "]", "[", "'_attachments'", "]", "]", "# check that all requested file are present", "for", "id", "in", "attachmentsID", ":", "if", "id", "not", "in", "insID", ":", "raise", "NotFoundException", "(", "\"could not found attachment '{}' of the volume '{}'\"", ".", "format", "(", "id", ",", "volumeID", ")", ")", "for", "index", ",", "id", "in", "enumerate", "(", "attachmentsID", ")", ":", "rawVolume", "[", "'_source'", "]", "[", "'_attachments'", "]", ".", "pop", "(", "insID", ".", "index", "(", "id", ")", ")", "self", ".", "_db", ".", "modify_book", "(", "volumeID", ",", "rawVolume", "[", "'_source'", "]", ",", "version", "=", "rawVolume", "[", "'_version'", "]", ")" ]
Adds the d_p_list permission to a user object when provided a user_email and portal_id .
def add_dplist_permission_for_user_on_portal ( self , user_email , portal_id ) : _id = self . get_user_id_from_email ( user_email ) print ( self . get_user_permission_from_email ( user_email ) ) retval = self . add_user_permission ( _id , json . dumps ( [ { 'access' : 'd_p_list' , 'oid' : { 'id' : portal_id , 'type' : 'Portal' } } ] ) ) print ( self . get_user_permission_from_email ( user_email ) ) return retval
7,352
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/portals/__init__.py#L506-L516
[ "def", "run", "(", "self", ")", ":", "port", ",", "tensorboard_process", "=", "self", ".", "create_tensorboard_process", "(", ")", "LOGGER", ".", "info", "(", "'TensorBoard 0.1.7 at http://localhost:{}'", ".", "format", "(", "port", ")", ")", "while", "not", "self", ".", "estimator", ".", "checkpoint_path", ":", "self", ".", "event", ".", "wait", "(", "1", ")", "with", "self", ".", "_temporary_directory", "(", ")", "as", "aws_sync_dir", ":", "while", "not", "self", ".", "event", ".", "is_set", "(", ")", ":", "args", "=", "[", "'aws'", ",", "'s3'", ",", "'sync'", ",", "self", ".", "estimator", ".", "checkpoint_path", ",", "aws_sync_dir", "]", "subprocess", ".", "call", "(", "args", ",", "stdout", "=", "subprocess", ".", "PIPE", ",", "stderr", "=", "subprocess", ".", "PIPE", ")", "self", ".", "_sync_directories", "(", "aws_sync_dir", ",", "self", ".", "logdir", ")", "self", ".", "event", ".", "wait", "(", "10", ")", "tensorboard_process", ".", "terminate", "(", ")" ]
Retrieves portal object according to portal_name and returns its cik .
def get_portal_cik ( self , portal_name ) : portal = self . get_portal_by_name ( portal_name ) cik = portal [ 2 ] [ 1 ] [ 'info' ] [ 'key' ] return cik
7,353
https://github.com/exosite-labs/pyonep/blob/d27b621b00688a542e0adcc01f3e3354c05238a1/pyonep/portals/__init__.py#L518-L523
[ "def", "stop", "(", "self", ")", ":", "self", ".", "_stopped", "=", "True", "threads", "=", "[", "self", ".", "_accept_thread", "]", "threads", ".", "extend", "(", "self", ".", "_server_threads", ")", "self", ".", "_listening_sock", ".", "close", "(", ")", "for", "sock", "in", "list", "(", "self", ".", "_server_socks", ")", ":", "try", ":", "sock", ".", "shutdown", "(", "socket", ".", "SHUT_RDWR", ")", "except", "socket", ".", "error", ":", "pass", "try", ":", "sock", ".", "close", "(", ")", "except", "socket", ".", "error", ":", "pass", "with", "self", ".", "_unlock", "(", ")", ":", "for", "thread", "in", "threads", ":", "thread", ".", "join", "(", "10", ")", "if", "self", ".", "_uds_path", ":", "try", ":", "os", ".", "unlink", "(", "self", ".", "_uds_path", ")", "except", "OSError", ":", "pass" ]
Initializes ES write index
def init_write_index ( es_write , es_write_index ) : logging . info ( "Initializing index: " + es_write_index ) es_write . indices . delete ( es_write_index , ignore = [ 400 , 404 ] ) es_write . indices . create ( es_write_index , body = MAPPING_GIT )
7,354
https://github.com/chaoss/grimoirelab-cereslib/blob/5110e6ca490a4f24bec3124286ebf51fd4e08bdd/examples/areas_code.py#L267-L272
[ "def", "get_license_assignment_manager", "(", "service_instance", ")", ":", "log", ".", "debug", "(", "'Retrieving license assignment manager'", ")", "try", ":", "lic_assignment_manager", "=", "service_instance", ".", "content", ".", "licenseManager", ".", "licenseAssignmentManager", "except", "vim", ".", "fault", ".", "NoPermission", "as", "exc", ":", "log", ".", "exception", "(", "exc", ")", "raise", "salt", ".", "exceptions", ".", "VMwareApiError", "(", "'Not enough permissions. Required privilege: '", "'{0}'", ".", "format", "(", "exc", ".", "privilegeId", ")", ")", "except", "vim", ".", "fault", ".", "VimFault", "as", "exc", ":", "log", ".", "exception", "(", "exc", ")", "raise", "salt", ".", "exceptions", ".", "VMwareApiError", "(", "exc", ".", "msg", ")", "except", "vmodl", ".", "RuntimeFault", "as", "exc", ":", "log", ".", "exception", "(", "exc", ")", "raise", "salt", ".", "exceptions", ".", "VMwareRuntimeError", "(", "exc", ".", "msg", ")", "if", "not", "lic_assignment_manager", ":", "raise", "salt", ".", "exceptions", ".", "VMwareObjectRetrievalError", "(", "'License assignment manager was not retrieved'", ")", "return", "lic_assignment_manager" ]
This class splits those commits where column1 and column2 values are different
def enrich ( self , column1 , column2 ) : if column1 not in self . commits . columns or column2 not in self . commits . columns : return self . commits # Select rows where values in column1 are different from # values in column2 pair_df = self . commits [ self . commits [ column1 ] != self . commits [ column2 ] ] new_values = list ( pair_df [ column2 ] ) # Update values from column2 pair_df [ column1 ] = new_values # This adds at the end of the original dataframe those rows duplicating # information and updating the values in column1 return self . commits . append ( pair_df )
7,355
https://github.com/chaoss/grimoirelab-cereslib/blob/5110e6ca490a4f24bec3124286ebf51fd4e08bdd/cereslib/enrich/enrich.py#L67-L95
[ "def", "shutdown", "(", "self", ")", ":", "vm", "=", "self", ".", "get_vm_failfast", "(", "self", ".", "config", "[", "'name'", "]", ")", "if", "vm", ".", "runtime", ".", "powerState", "==", "vim", ".", "VirtualMachinePowerState", ".", "poweredOff", ":", "print", "(", "\"%s already poweredOff\"", "%", "vm", ".", "name", ")", "else", ":", "if", "self", ".", "guestToolsRunning", "(", "vm", ")", ":", "timeout_minutes", "=", "10", "print", "(", "\"waiting for %s to shutdown \"", "\"(%s minutes before forced powerOff)\"", "%", "(", "vm", ".", "name", ",", "str", "(", "timeout_minutes", ")", ")", ")", "vm", ".", "ShutdownGuest", "(", ")", "if", "self", ".", "WaitForVirtualMachineShutdown", "(", "vm", ",", "timeout_minutes", "*", "60", ")", ":", "print", "(", "\"shutdown complete\"", ")", "print", "(", "\"%s poweredOff\"", "%", "vm", ".", "name", ")", "else", ":", "print", "(", "\"%s has not shutdown after %s minutes:\"", "\"will powerOff\"", "%", "(", "vm", ".", "name", ",", "str", "(", "timeout_minutes", ")", ")", ")", "self", ".", "powerOff", "(", ")", "else", ":", "print", "(", "\"GuestTools not running or not installed: will powerOff\"", ")", "self", ".", "powerOff", "(", ")" ]
This method adds a new column depending on the extension of the file .
def enrich ( self , column ) : if column not in self . data : return self . data # Insert a new column with default values self . data [ "filetype" ] = 'Other' # Insert 'Code' only in those rows that are # detected as being source code thanks to its extension reg = "\.c$|\.h$|\.cc$|\.cpp$|\.cxx$|\.c\+\+$|\.cp$|\.py$|\.js$|\.java$|\.rs$|\.go$" self . data . loc [ self . data [ column ] . str . contains ( reg ) , 'filetype' ] = 'Code' return self . data
7,356
https://github.com/chaoss/grimoirelab-cereslib/blob/5110e6ca490a4f24bec3124286ebf51fd4e08bdd/cereslib/enrich/enrich.py#L112-L135
[ "def", "get_robot_variables", "(", ")", ":", "prefix", "=", "'ROBOT_'", "variables", "=", "[", "]", "def", "safe_str", "(", "s", ")", ":", "if", "isinstance", "(", "s", ",", "six", ".", "text_type", ")", ":", "return", "s", "else", ":", "return", "six", ".", "text_type", "(", "s", ",", "'utf-8'", ",", "'ignore'", ")", "for", "key", "in", "os", ".", "environ", ":", "if", "key", ".", "startswith", "(", "prefix", ")", "and", "len", "(", "key", ")", ">", "len", "(", "prefix", ")", ":", "variables", ".", "append", "(", "safe_str", "(", "'%s:%s'", "%", "(", "key", "[", "len", "(", "prefix", ")", ":", "]", ",", "os", ".", "environ", "[", "key", "]", ")", ",", ")", ")", "return", "variables" ]
This method adds a new column named as project that contains information about the associated project that the event in column belongs to .
def enrich ( self , column , projects ) : if column not in self . data . columns : return self . data self . data = pandas . merge ( self . data , projects , how = 'left' , on = column ) return self . data
7,357
https://github.com/chaoss/grimoirelab-cereslib/blob/5110e6ca490a4f24bec3124286ebf51fd4e08bdd/cereslib/enrich/enrich.py#L224-L243
[ "def", "image_to_string", "(", "image", ",", "lang", "=", "None", ",", "boxes", "=", "False", ")", ":", "input_file_name", "=", "'%s.bmp'", "%", "tempnam", "(", ")", "output_file_name_base", "=", "tempnam", "(", ")", "if", "not", "boxes", ":", "output_file_name", "=", "'%s.txt'", "%", "output_file_name_base", "else", ":", "output_file_name", "=", "'%s.box'", "%", "output_file_name_base", "try", ":", "image", ".", "save", "(", "input_file_name", ")", "status", ",", "error_string", "=", "run_tesseract", "(", "input_file_name", ",", "output_file_name_base", ",", "lang", "=", "lang", ",", "boxes", "=", "boxes", ")", "if", "status", ":", "errors", "=", "get_errors", "(", "error_string", ")", "raise", "TesseractError", "(", "status", ",", "errors", ")", "f", "=", "file", "(", "output_file_name", ")", "try", ":", "return", "f", ".", "read", "(", ")", ".", "strip", "(", ")", "finally", ":", "f", ".", "close", "(", ")", "finally", ":", "cleanup", "(", "input_file_name", ")", "cleanup", "(", "output_file_name", ")" ]
Parse flags from a message
def __parse_flags ( self , body ) : flags = [ ] values = [ ] lines = body . split ( '\n' ) for l in lines : for name in self . FLAGS_REGEX : m = re . match ( self . FLAGS_REGEX [ name ] , l ) if m : flags . append ( name ) values . append ( m . group ( "value" ) . strip ( ) ) if flags == [ ] : flags = "" values = "" return flags , values
7,358
https://github.com/chaoss/grimoirelab-cereslib/blob/5110e6ca490a4f24bec3124286ebf51fd4e08bdd/cereslib/enrich/enrich.py#L341-L358
[ "def", "load_plugins", "(", "self", ",", "plugin_class_name", ")", ":", "# imp.findmodule('atomic_reactor') doesn't work", "plugins_dir", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "'plugins'", ")", "logger", ".", "debug", "(", "\"loading plugins from dir '%s'\"", ",", "plugins_dir", ")", "files", "=", "[", "os", ".", "path", ".", "join", "(", "plugins_dir", ",", "f", ")", "for", "f", "in", "os", ".", "listdir", "(", "plugins_dir", ")", "if", "f", ".", "endswith", "(", "\".py\"", ")", "]", "if", "self", ".", "plugin_files", ":", "logger", ".", "debug", "(", "\"loading additional plugins from files '%s'\"", ",", "self", ".", "plugin_files", ")", "files", "+=", "self", ".", "plugin_files", "plugin_class", "=", "globals", "(", ")", "[", "plugin_class_name", "]", "plugin_classes", "=", "{", "}", "for", "f", "in", "files", ":", "module_name", "=", "os", ".", "path", ".", "basename", "(", "f", ")", ".", "rsplit", "(", "'.'", ",", "1", ")", "[", "0", "]", "# Do not reload plugins", "if", "module_name", "in", "sys", ".", "modules", ":", "f_module", "=", "sys", ".", "modules", "[", "module_name", "]", "else", ":", "try", ":", "logger", ".", "debug", "(", "\"load file '%s'\"", ",", "f", ")", "f_module", "=", "imp", ".", "load_source", "(", "module_name", ",", "f", ")", "except", "(", "IOError", ",", "OSError", ",", "ImportError", ",", "SyntaxError", ")", "as", "ex", ":", "logger", ".", "warning", "(", "\"can't load module '%s': %r\"", ",", "f", ",", "ex", ")", "continue", "for", "name", "in", "dir", "(", "f_module", ")", ":", "binding", "=", "getattr", "(", "f_module", ",", "name", ",", "None", ")", "try", ":", "# if you try to compare binding and PostBuildPlugin, python won't match them", "# if you call this script directly b/c:", "# ! <class 'plugins.plugin_rpmqa.PostBuildRPMqaPlugin'> <= <class", "# '__main__.PostBuildPlugin'>", "# but", "# <class 'plugins.plugin_rpmqa.PostBuildRPMqaPlugin'> <= <class", "# 'atomic_reactor.plugin.PostBuildPlugin'>", "is_sub", "=", "issubclass", "(", "binding", ",", "plugin_class", ")", "except", "TypeError", ":", "is_sub", "=", "False", "if", "binding", "and", "is_sub", "and", "plugin_class", ".", "__name__", "!=", "binding", ".", "__name__", ":", "plugin_classes", "[", "binding", ".", "key", "]", "=", "binding", "return", "plugin_classes" ]
This enricher returns the same dataframe with a new column named domain . That column is the result of splitting the email address of another column . If there is not a proper email address an unknown domain is returned .
def enrich ( self , column ) : if column not in self . data . columns : return self . data self . data [ 'domain' ] = self . data [ column ] . apply ( lambda x : self . __parse_email ( x ) ) return self . data
7,359
https://github.com/chaoss/grimoirelab-cereslib/blob/5110e6ca490a4f24bec3124286ebf51fd4e08bdd/cereslib/enrich/enrich.py#L429-L445
[ "def", "releaseNativeOverlayHandle", "(", "self", ",", "ulOverlayHandle", ",", "pNativeTextureHandle", ")", ":", "fn", "=", "self", ".", "function_table", ".", "releaseNativeOverlayHandle", "result", "=", "fn", "(", "ulOverlayHandle", ",", "pNativeTextureHandle", ")", "return", "result" ]
Remove surrogates in the specified string
def __remove_surrogates ( self , s , method = 'replace' ) : if type ( s ) == list and len ( s ) == 1 : if self . __is_surrogate_escaped ( s [ 0 ] ) : return s [ 0 ] . encode ( 'utf-8' , method ) . decode ( 'utf-8' ) else : return "" if type ( s ) == list : return "" if type ( s ) != str : return "" if self . __is_surrogate_escaped ( s ) : return s . encode ( 'utf-8' , method ) . decode ( 'utf-8' ) return s
7,360
https://github.com/chaoss/grimoirelab-cereslib/blob/5110e6ca490a4f24bec3124286ebf51fd4e08bdd/cereslib/enrich/enrich.py#L452-L467
[ "def", "rank_types", "(", "types", ")", ":", "include_null", "=", "'0b0'", "in", "types", "sorted_types", "=", "deepcopy", "(", "types", ")", "for", "i", "in", "range", "(", "len", "(", "sorted_types", ")", ")", ":", "sorted_types", "[", "i", "]", "=", "int", "(", "sorted_types", "[", "i", "]", ",", "2", ")", "sorted_types", ".", "sort", "(", ")", "ranks", "=", "{", "}", "for", "t", "in", "types", ":", "ranks", "[", "t", "]", "=", "sorted_types", ".", "index", "(", "eval", "(", "t", ")", ")", "+", "int", "(", "not", "include_null", ")", "return", "ranks" ]
Checks if surrogate is escaped
def __is_surrogate_escaped ( self , text ) : try : text . encode ( 'utf-8' ) except UnicodeEncodeError as e : if e . reason == 'surrogates not allowed' : return True return False
7,361
https://github.com/chaoss/grimoirelab-cereslib/blob/5110e6ca490a4f24bec3124286ebf51fd4e08bdd/cereslib/enrich/enrich.py#L469-L478
[ "def", "get_available_options", "(", "self", ",", "service_name", ")", ":", "options", "=", "{", "}", "for", "data_dir", "in", "self", ".", "data_dirs", ":", "# Traverse all the directories trying to find the best match.", "service_glob", "=", "\"{0}-*.json\"", ".", "format", "(", "service_name", ")", "path", "=", "os", ".", "path", ".", "join", "(", "data_dir", ",", "service_glob", ")", "found", "=", "glob", ".", "glob", "(", "path", ")", "for", "match", "in", "found", ":", "# Rip apart the path to determine the API version.", "base", "=", "os", ".", "path", ".", "basename", "(", "match", ")", "bits", "=", "os", ".", "path", ".", "splitext", "(", "base", ")", "[", "0", "]", ".", "split", "(", "'-'", ",", "1", ")", "if", "len", "(", "bits", ")", "<", "2", ":", "continue", "api_version", "=", "bits", "[", "1", "]", "options", ".", "setdefault", "(", "api_version", ",", "[", "]", ")", "options", "[", "api_version", "]", ".", "append", "(", "match", ")", "return", "options" ]
This method convert to utf - 8 the provided columns
def enrich ( self , columns ) : for column in columns : if column not in self . data . columns : return self . data for column in columns : a = self . data [ column ] . apply ( self . __remove_surrogates ) self . data [ column ] = a return self . data
7,362
https://github.com/chaoss/grimoirelab-cereslib/blob/5110e6ca490a4f24bec3124286ebf51fd4e08bdd/cereslib/enrich/enrich.py#L489-L506
[ "def", "on_end_validation", "(", "self", ",", "event", ")", ":", "self", ".", "Enable", "(", ")", "self", ".", "Show", "(", ")", "self", ".", "magic_gui_frame", ".", "Destroy", "(", ")" ]
Parse email addresses
def __parse_addr ( self , addr ) : from email . utils import parseaddr value = parseaddr ( addr ) return value [ 0 ] , value [ 1 ]
7,363
https://github.com/chaoss/grimoirelab-cereslib/blob/5110e6ca490a4f24bec3124286ebf51fd4e08bdd/cereslib/enrich/enrich.py#L515-L522
[ "def", "get_samples", "(", "self", ",", "n", ")", ":", "normalized_w", "=", "self", ".", "weights", "/", "np", ".", "sum", "(", "self", ".", "weights", ")", "get_rand_index", "=", "st", ".", "rv_discrete", "(", "values", "=", "(", "range", "(", "self", ".", "N", ")", ",", "normalized_w", ")", ")", ".", "rvs", "(", "size", "=", "n", ")", "samples", "=", "np", ".", "zeros", "(", "n", ")", "k", "=", "0", "j", "=", "0", "while", "(", "k", "<", "n", ")", ":", "i", "=", "get_rand_index", "[", "j", "]", "j", "=", "j", "+", "1", "if", "(", "j", "==", "n", ")", ":", "get_rand_index", "=", "st", ".", "rv_discrete", "(", "values", "=", "(", "range", "(", "self", ".", "N", ")", ",", "normalized_w", ")", ")", ".", "rvs", "(", "size", "=", "n", ")", "j", "=", "0", "v", "=", "np", ".", "random", ".", "normal", "(", "loc", "=", "self", ".", "points", "[", "i", "]", ",", "scale", "=", "self", ".", "sigma", "[", "i", "]", ")", "if", "(", "v", ">", "self", ".", "max_limit", "or", "v", "<", "self", ".", "min_limit", ")", ":", "continue", "else", ":", "samples", "[", "k", "]", "=", "v", "k", "=", "k", "+", "1", "if", "(", "k", "==", "n", ")", ":", "break", "return", "samples" ]
This method appends at the end of the dataframe as many rows as items are found in the list of elemnents in the provided columns .
def enrich ( self , columns ) : for column in columns : if column not in self . data . columns : return self . data # Looking for the rows with columns with lists of more # than one element first_column = list ( self . data [ columns [ 0 ] ] ) count = 0 append_df = pandas . DataFrame ( ) for cell in first_column : if len ( cell ) >= 1 : # Interested in those lists with more # than one element df = pandas . DataFrame ( ) # Create a dataframe of N rows from the list for column in columns : df [ column ] = self . data . loc [ count , column ] # Repeat the original rows N times extra_df = pandas . DataFrame ( [ self . data . loc [ count ] ] * len ( df ) ) for column in columns : extra_df [ column ] = list ( df [ column ] ) append_df = append_df . append ( extra_df , ignore_index = True ) extra_df = pandas . DataFrame ( ) count = count + 1 self . data = self . data . append ( append_df , ignore_index = True ) return self . data
7,364
https://github.com/chaoss/grimoirelab-cereslib/blob/5110e6ca490a4f24bec3124286ebf51fd4e08bdd/cereslib/enrich/enrich.py#L569-L622
[ "def", "map_", "(", "cache", ":", "Mapping", "[", "Domain", ",", "Range", "]", ")", "->", "Operator", "[", "Map", "[", "Domain", ",", "Range", "]", "]", ":", "def", "wrapper", "(", "function", ":", "Map", "[", "Domain", ",", "Range", "]", ")", "->", "Map", "[", "Domain", ",", "Range", "]", ":", "@", "wraps", "(", "function", ")", "def", "wrapped", "(", "argument", ":", "Domain", ")", "->", "Range", ":", "try", ":", "return", "cache", "[", "argument", "]", "except", "KeyError", ":", "return", "function", "(", "argument", ")", "return", "wrapped", "return", "wrapper" ]
This method calculates the maximum and minimum value of a given set of columns depending on another column . This is the usual group by clause in SQL .
def enrich ( self , columns , groupby ) : for column in columns : if column not in self . data . columns : return self . data for column in columns : df_grouped = self . data . groupby ( [ groupby ] ) . agg ( { column : 'max' } ) df_grouped = df_grouped . reset_index ( ) df_grouped . rename ( columns = { column : 'max_' + column } , inplace = True ) self . data = pandas . merge ( self . data , df_grouped , how = 'left' , on = [ groupby ] ) df_grouped = self . data . groupby ( [ groupby ] ) . agg ( { column : 'min' } ) df_grouped = df_grouped . reset_index ( ) df_grouped . rename ( columns = { column : 'min_' + column } , inplace = True ) self . data = pandas . merge ( self . data , df_grouped , how = 'left' , on = [ groupby ] ) return self . data
7,365
https://github.com/chaoss/grimoirelab-cereslib/blob/5110e6ca490a4f24bec3124286ebf51fd4e08bdd/cereslib/enrich/enrich.py#L640-L665
[ "def", "log_analyzer2", "(", "path", ")", ":", "with", "handle", "(", "MalformedLogEntryError", ",", "lambda", "(", "c", ")", ":", "invoke_restart", "(", "'reparse'", ",", "'ERROR: '", "+", "c", ".", "text", ")", ")", ":", "for", "filename", "in", "find_all_logs", "(", "path", ")", ":", "analyze_log", "(", "filename", ")" ]
This method calculates thanks to the genderize . io API the gender of a given name .
def enrich ( self , column ) : if column not in self . data . columns : return self . data splits = self . data [ column ] . str . split ( " " ) splits = splits . str [ 0 ] self . data [ "gender_analyzed_name" ] = splits . fillna ( "noname" ) self . data [ "gender_probability" ] = 0 self . data [ "gender" ] = "Unknown" self . data [ "gender_count" ] = 0 names = list ( self . data [ "gender_analyzed_name" ] . unique ( ) ) for name in names : if name in self . gender . keys ( ) : gender_result = self . gender [ name ] else : try : # TODO: some errors found due to encode utf-8 issues. # Adding a try-except in the meantime. gender_result = self . connection . get ( [ name ] ) [ 0 ] except Exception : continue # Store info in the list of users self . gender [ name ] = gender_result # Update current dataset if gender_result [ "gender" ] is None : gender_result [ "gender" ] = "NotKnown" self . data . loc [ self . data [ "gender_analyzed_name" ] == name , 'gender' ] = gender_result [ "gender" ] if "probability" in gender_result . keys ( ) : self . data . loc [ self . data [ "gender_analyzed_name" ] == name , 'gender_probability' ] = gender_result [ "probability" ] self . data . loc [ self . data [ "gender_analyzed_name" ] == name , 'gender_count' ] = gender_result [ "count" ] self . data . fillna ( "noname" ) return self . data
7,366
https://github.com/chaoss/grimoirelab-cereslib/blob/5110e6ca490a4f24bec3124286ebf51fd4e08bdd/cereslib/enrich/enrich.py#L710-L772
[ "def", "reset", "(", ")", "->", "None", ":", "from", "wdom", ".", "document", "import", "get_new_document", ",", "set_document", "from", "wdom", ".", "element", "import", "Element", "from", "wdom", ".", "server", "import", "_tornado", "from", "wdom", ".", "window", "import", "customElements", "set_document", "(", "get_new_document", "(", ")", ")", "_tornado", ".", "connections", ".", "clear", "(", ")", "_tornado", ".", "set_application", "(", "_tornado", ".", "Application", "(", ")", ")", "Element", ".", "_elements_with_id", ".", "clear", "(", ")", "Element", ".", "_element_buffer", ".", "clear", "(", ")", "customElements", ".", "reset", "(", ")" ]
Merges the original dataframe with corresponding entity uuids based on the given columns . Also merges other additional information associated to uuids provided in the uuids dataframe if any .
def enrich ( self , columns ) : for column in columns : if column not in self . data . columns : return self . data self . data = pandas . merge ( self . data , self . uuids_df , how = 'left' , on = columns ) self . data = self . data . fillna ( "notavailable" ) return self . data
7,367
https://github.com/chaoss/grimoirelab-cereslib/blob/5110e6ca490a4f24bec3124286ebf51fd4e08bdd/cereslib/enrich/enrich.py#L850-L870
[ "def", "checkpoint", "(", "global_model", ",", "local_model", "=", "None", ")", ":", "sglobal", "=", "pickle", ".", "dumps", "(", "global_model", ")", "if", "local_model", "is", "None", ":", "_LIB", ".", "RabitCheckPoint", "(", "sglobal", ",", "len", "(", "sglobal", ")", ",", "None", ",", "0", ")", "del", "sglobal", "else", ":", "slocal", "=", "pickle", ".", "dumps", "(", "local_model", ")", "_LIB", ".", "RabitCheckPoint", "(", "sglobal", ",", "len", "(", "sglobal", ")", ",", "slocal", ",", "len", "(", "slocal", ")", ")", "del", "slocal", "del", "sglobal" ]
Echo the string to standard out prefixed with the current date and time in UTC format .
def echo_utc ( string ) : from datetime import datetime click . echo ( '{} | {}' . format ( datetime . utcnow ( ) . isoformat ( ) , string ) )
7,368
https://github.com/aiidateam/aiida-codtools/blob/da5e4259b7a2e86cf0cc3f997e11dd36d445fa94/aiida_codtools/common/cli.py#L16-L22
[ "def", "_combine_transfers", "(", "self", ",", "result", ")", ":", "transfers", "=", "{", "}", "for", "reaction_id", ",", "c1", ",", "c2", ",", "form", "in", "result", ":", "key", "=", "reaction_id", ",", "c1", ",", "c2", "combined_form", "=", "transfers", ".", "setdefault", "(", "key", ",", "Formula", "(", ")", ")", "transfers", "[", "key", "]", "=", "combined_form", "|", "form", "for", "(", "reaction_id", ",", "c1", ",", "c2", ")", ",", "form", "in", "iteritems", "(", "transfers", ")", ":", "yield", "reaction_id", ",", "c1", ",", "c2", ",", "form" ]
Parse a single string representing all command line parameters .
def from_string ( cls , string ) : if string is None : string = '' if not isinstance ( string , six . string_types ) : raise TypeError ( 'string has to be a string type, got: {}' . format ( type ( string ) ) ) dictionary = { } tokens = [ token . strip ( ) for token in shlex . split ( string ) ] def list_tuples ( some_iterable ) : items , nexts = itertools . tee ( some_iterable , 2 ) nexts = itertools . chain ( itertools . islice ( nexts , 1 , None ) , [ None ] ) return list ( zip ( items , nexts ) ) for token_current , token_next in list_tuples ( tokens ) : # If current token starts with a dash, it is a value so we skip it if not token_current . startswith ( '-' ) : continue # If the next token is None or starts with a dash, the current token must be a flag, so the value is True if not token_next or token_next . startswith ( '-' ) : dictionary [ token_current . lstrip ( '-' ) ] = True # Otherwise the current token is an option with the next token being its value else : dictionary [ token_current . lstrip ( '-' ) ] = token_next return cls . from_dictionary ( dictionary )
7,369
https://github.com/aiidateam/aiida-codtools/blob/da5e4259b7a2e86cf0cc3f997e11dd36d445fa94/aiida_codtools/common/cli.py#L59-L89
[ "def", "list_to_compare_dict", "(", "self", ",", "list_form", ")", ":", "compare_dict", "=", "{", "}", "for", "field", "in", "list_form", ":", "if", "field", "[", "'name'", "]", "in", "compare_dict", ":", "self", ".", "pr_dbg", "(", "\"List has duplicate field %s:\\n%s\"", "%", "(", "field", "[", "'name'", "]", ",", "compare_dict", "[", "field", "[", "'name'", "]", "]", ")", ")", "if", "compare_dict", "[", "field", "[", "'name'", "]", "]", "!=", "field", ":", "self", ".", "pr_dbg", "(", "\"And values are different:\\n%s\"", "%", "field", ")", "return", "None", "compare_dict", "[", "field", "[", "'name'", "]", "]", "=", "field", "for", "ign_f", "in", "self", ".", "mappings_ignore", ":", "compare_dict", "[", "field", "[", "'name'", "]", "]", "[", "ign_f", "]", "=", "0", "return", "compare_dict" ]
Parse a dictionary representing all command line parameters .
def from_dictionary ( cls , dictionary ) : if not isinstance ( dictionary , dict ) : raise TypeError ( 'dictionary has to be a dict type, got: {}' . format ( type ( dictionary ) ) ) return cls ( dictionary )
7,370
https://github.com/aiidateam/aiida-codtools/blob/da5e4259b7a2e86cf0cc3f997e11dd36d445fa94/aiida_codtools/common/cli.py#L92-L97
[ "def", "red_workshift", "(", "request", ",", "message", "=", "None", ")", ":", "if", "message", ":", "messages", ".", "add_message", "(", "request", ",", "messages", ".", "ERROR", ",", "message", ")", "return", "HttpResponseRedirect", "(", "reverse", "(", "'workshift:view_semester'", ")", ")" ]
Return the command line parameters as a list of options their values and arguments .
def get_list ( self ) : result = [ ] for key , value in self . parameters . items ( ) : if value is None : continue if not isinstance ( value , list ) : value = [ value ] if len ( key ) == 1 : string_key = '-{}' . format ( key ) else : string_key = '--{}' . format ( key ) for sub_value in value : if isinstance ( sub_value , bool ) and sub_value is False : continue result . append ( string_key ) if not isinstance ( sub_value , bool ) : if ' ' in sub_value : string_value = "'{}'" . format ( sub_value ) else : string_value = sub_value result . append ( str ( string_value ) ) return result
7,371
https://github.com/aiidateam/aiida-codtools/blob/da5e4259b7a2e86cf0cc3f997e11dd36d445fa94/aiida_codtools/common/cli.py#L99-L134
[ "def", "weighted_hamming", "(", "b1", ",", "b2", ")", ":", "assert", "(", "len", "(", "b1", ")", "==", "len", "(", "b2", ")", ")", "hamming", "=", "0", "for", "i", "in", "range", "(", "len", "(", "b1", ")", ")", ":", "if", "b1", "[", "i", "]", "!=", "b2", "[", "i", "]", ":", "# differences at more significant (leftward) bits", "# are more important", "if", "i", ">", "0", ":", "hamming", "+=", "1", "+", "1.0", "/", "i", "# This weighting is completely arbitrary", "return", "hamming" ]
Launch the process with the given inputs by default running in the current interpreter .
def run ( self , daemon = False ) : from aiida . engine import launch # If daemon is True, submit the process and return if daemon : node = launch . submit ( self . process , * * self . inputs ) echo . echo_info ( 'Submitted {}<{}>' . format ( self . process_name , node . pk ) ) return # Otherwise we run locally and wait for the process to finish echo . echo_info ( 'Running {}' . format ( self . process_name ) ) try : _ , node = launch . run_get_node ( self . process , * * self . inputs ) except Exception as exception : # pylint: disable=broad-except echo . echo_critical ( 'an exception occurred during execution: {}' . format ( str ( exception ) ) ) if node . is_killed : echo . echo_critical ( '{}<{}> was killed' . format ( self . process_name , node . pk ) ) elif not node . is_finished_ok : arguments = [ self . process_name , node . pk , node . exit_status , node . exit_message ] echo . echo_warning ( '{}<{}> failed with exit status {}: {}' . format ( * arguments ) ) else : output = [ ] echo . echo_success ( '{}<{}> finished successfully\n' . format ( self . process_name , node . pk ) ) for triple in sorted ( node . get_outgoing ( ) . all ( ) , key = lambda triple : triple . link_label ) : output . append ( [ triple . link_label , '{}<{}>' . format ( triple . node . __class__ . __name__ , triple . node . pk ) ] ) echo . echo ( tabulate . tabulate ( output , headers = [ 'Output label' , 'Node' ] ) )
7,372
https://github.com/aiidateam/aiida-codtools/blob/da5e4259b7a2e86cf0cc3f997e11dd36d445fa94/aiida_codtools/common/cli.py#L170-L200
[ "def", "event_availability_array", "(", "events", ")", ":", "array", "=", "np", ".", "ones", "(", "(", "len", "(", "events", ")", ",", "len", "(", "events", ")", ")", ")", "for", "row", ",", "event", "in", "enumerate", "(", "events", ")", ":", "for", "col", ",", "other_event", "in", "enumerate", "(", "events", ")", ":", "if", "row", "!=", "col", ":", "tags", "=", "set", "(", "event", ".", "tags", ")", "events_share_tag", "=", "len", "(", "tags", ".", "intersection", "(", "other_event", ".", "tags", ")", ")", ">", "0", "if", "(", "other_event", "in", "event", ".", "unavailability", ")", "or", "events_share_tag", ":", "array", "[", "row", ",", "col", "]", "=", "0", "array", "[", "col", ",", "row", "]", "=", "0", "return", "array" ]
Returns a default Dict given certain information
def _xpathDict ( xml , xpath , cls , parent , * * kwargs ) : children = [ ] for child in xml . xpath ( xpath , namespaces = XPATH_NAMESPACES ) : children . append ( cls . parse ( resource = child , parent = parent , * * kwargs ) ) return children
7,373
https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resources/collections/cts.py#L79-L100
[ "def", "_line", "(", "self", ",", "text", ",", "indent", "=", "0", ")", ":", "leading_space", "=", "' '", "*", "indent", "while", "len", "(", "leading_space", ")", "+", "len", "(", "text", ")", ">", "self", ".", "width", ":", "# The text is too wide; wrap if possible.", "# Find the rightmost space that would obey our width constraint and", "# that's not an escaped space.", "available_space", "=", "self", ".", "width", "-", "len", "(", "leading_space", ")", "-", "len", "(", "' $'", ")", "space", "=", "available_space", "while", "True", ":", "space", "=", "text", ".", "rfind", "(", "' '", ",", "0", ",", "space", ")", "if", "(", "space", "<", "0", "or", "self", ".", "_count_dollars_before_index", "(", "text", ",", "space", ")", "%", "2", "==", "0", ")", ":", "break", "if", "space", "<", "0", ":", "# No such space; just use the first unescaped space we can find.", "space", "=", "available_space", "-", "1", "while", "True", ":", "space", "=", "text", ".", "find", "(", "' '", ",", "space", "+", "1", ")", "if", "(", "space", "<", "0", "or", "self", ".", "_count_dollars_before_index", "(", "text", ",", "space", ")", "%", "2", "==", "0", ")", ":", "break", "if", "space", "<", "0", ":", "# Give up on breaking.", "break", "self", ".", "output", ".", "write", "(", "leading_space", "+", "text", "[", "0", ":", "space", "]", "+", "' $\\n'", ")", "text", "=", "text", "[", "space", "+", "1", ":", "]", "# Subsequent lines are continuations, so indent them.", "leading_space", "=", "' '", "*", "(", "indent", "+", "2", ")", "self", ".", "output", ".", "write", "(", "leading_space", "+", "text", "+", "'\\n'", ")" ]
Parse an XML object for structured metadata
def _parse_structured_metadata ( obj , xml ) : for metadata in xml . xpath ( "cpt:structured-metadata/*" , namespaces = XPATH_NAMESPACES ) : tag = metadata . tag if "{" in tag : ns , tag = tuple ( tag . split ( "}" ) ) tag = URIRef ( ns [ 1 : ] + tag ) s_m = str ( metadata ) if s_m . startswith ( "urn:" ) or s_m . startswith ( "http:" ) or s_m . startswith ( "https:" ) or s_m . startswith ( "hdl:" ) : obj . metadata . add ( tag , URIRef ( metadata ) ) elif '{http://www.w3.org/XML/1998/namespace}lang' in metadata . attrib : obj . metadata . add ( tag , s_m , lang = metadata . attrib [ '{http://www.w3.org/XML/1998/namespace}lang' ] ) else : if "{http://www.w3.org/1999/02/22-rdf-syntax-ns#}datatype" in metadata . attrib : datatype = metadata . attrib [ "{http://www.w3.org/1999/02/22-rdf-syntax-ns#}datatype" ] if not datatype . startswith ( "http" ) and ":" in datatype : datatype = expand_namespace ( metadata . nsmap , datatype ) obj . metadata . add ( tag , Literal ( s_m , datatype = URIRef ( datatype ) ) ) elif isinstance ( metadata , IntElement ) : obj . metadata . add ( tag , Literal ( int ( metadata ) , datatype = XSD . integer ) ) elif isinstance ( metadata , FloatElement ) : obj . metadata . add ( tag , Literal ( float ( metadata ) , datatype = XSD . float ) ) else : obj . metadata . add ( tag , s_m )
7,374
https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resources/collections/cts.py#L103-L137
[ "def", "find_best_frametype", "(", "channel", ",", "start", ",", "end", ",", "frametype_match", "=", "None", ",", "allow_tape", "=", "True", ",", "connection", "=", "None", ",", "host", "=", "None", ",", "port", "=", "None", ")", ":", "try", ":", "return", "find_frametype", "(", "channel", ",", "gpstime", "=", "(", "start", ",", "end", ")", ",", "frametype_match", "=", "frametype_match", ",", "allow_tape", "=", "allow_tape", ",", "on_gaps", "=", "'error'", ",", "connection", "=", "connection", ",", "host", "=", "host", ",", "port", "=", "port", ")", "except", "RuntimeError", ":", "# gaps (or something else went wrong)", "ftout", "=", "find_frametype", "(", "channel", ",", "gpstime", "=", "(", "start", ",", "end", ")", ",", "frametype_match", "=", "frametype_match", ",", "return_all", "=", "True", ",", "allow_tape", "=", "allow_tape", ",", "on_gaps", "=", "'ignore'", ",", "connection", "=", "connection", ",", "host", "=", "host", ",", "port", "=", "port", ")", "try", ":", "if", "isinstance", "(", "ftout", ",", "dict", ")", ":", "return", "{", "key", ":", "ftout", "[", "key", "]", "[", "0", "]", "for", "key", "in", "ftout", "}", "return", "ftout", "[", "0", "]", "except", "IndexError", ":", "raise", "ValueError", "(", "\"Cannot find any valid frametypes for channel(s)\"", ")" ]
Ingest xml to create a citation
def ingest ( cls , resource , element = None , xpath = "ti:citation" ) : # Reuse of of find citation results = resource . xpath ( xpath , namespaces = XPATH_NAMESPACES ) if len ( results ) > 0 : citation = cls ( name = results [ 0 ] . get ( "label" ) , xpath = results [ 0 ] . get ( "xpath" ) , scope = results [ 0 ] . get ( "scope" ) ) if isinstance ( element , cls ) : element . child = citation cls . ingest ( resource = results [ 0 ] , element = element . child ) else : element = citation cls . ingest ( resource = results [ 0 ] , element = element ) return citation return None
7,375
https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resources/collections/cts.py#L43-L76
[ "def", "_clear_stats", "(", "self", ")", ":", "for", "stat", "in", "(", "STAT_BYTES_RECEIVED", ",", "STAT_BYTES_SENT", ",", "STAT_MSG_RECEIVED", ",", "STAT_MSG_SENT", ",", "STAT_CLIENTS_MAXIMUM", ",", "STAT_CLIENTS_CONNECTED", ",", "STAT_CLIENTS_DISCONNECTED", ",", "STAT_PUBLISH_RECEIVED", ",", "STAT_PUBLISH_SENT", ")", ":", "self", ".", "_stats", "[", "stat", "]", "=", "0" ]
Parse a resource to feed the object
def parse_metadata ( cls , obj , xml ) : for child in xml . xpath ( "ti:description" , namespaces = XPATH_NAMESPACES ) : lg = child . get ( "{http://www.w3.org/XML/1998/namespace}lang" ) if lg is not None : obj . set_cts_property ( "description" , child . text , lg ) for child in xml . xpath ( "ti:label" , namespaces = XPATH_NAMESPACES ) : lg = child . get ( "{http://www.w3.org/XML/1998/namespace}lang" ) if lg is not None : obj . set_cts_property ( "label" , child . text , lg ) obj . citation = cls . CLASS_CITATION . ingest ( xml , obj . citation , "ti:online/ti:citationMapping/ti:citation" ) # Added for commentary for child in xml . xpath ( "ti:about" , namespaces = XPATH_NAMESPACES ) : obj . set_link ( RDF_NAMESPACES . CTS . term ( "about" ) , child . get ( 'urn' ) ) _parse_structured_metadata ( obj , xml ) """ online = xml.xpath("ti:online", namespaces=NS) if len(online) > 0: online = online[0] obj.docname = online.get("docname") for validate in online.xpath("ti:validate", namespaces=NS): obj.validate = validate.get("schema") for namespaceMapping in online.xpath("ti:namespaceMapping", namespaces=NS): obj.metadata["namespaceMapping"][namespaceMapping.get("abbreviation")] = namespaceMapping.get("nsURI") """
7,376
https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resources/collections/cts.py#L156-L192
[ "def", "remove", "(", "self", ",", "experiment", ")", ":", "try", ":", "project_path", "=", "self", ".", "projects", "[", "self", "[", "experiment", "]", "[", "'project'", "]", "]", "[", "'root'", "]", "except", "KeyError", ":", "return", "config_path", "=", "osp", ".", "join", "(", "project_path", ",", "'.project'", ",", "experiment", "+", "'.yml'", ")", "for", "f", "in", "[", "config_path", ",", "config_path", "+", "'~'", ",", "config_path", "+", "'.lck'", "]", ":", "if", "os", ".", "path", ".", "exists", "(", "f", ")", ":", "os", ".", "remove", "(", "f", ")", "del", "self", "[", "experiment", "]" ]
Parse a textgroup resource
def parse ( cls , resource , parent = None ) : xml = xmlparser ( resource ) o = cls ( urn = xml . get ( "urn" ) , parent = parent ) for child in xml . xpath ( "ti:groupname" , namespaces = XPATH_NAMESPACES ) : lg = child . get ( "{http://www.w3.org/XML/1998/namespace}lang" ) if lg is not None : o . set_cts_property ( "groupname" , child . text , lg ) # Parse Works _xpathDict ( xml = xml , xpath = 'ti:work' , cls = cls . CLASS_WORK , parent = o ) _parse_structured_metadata ( o , xml ) return o
7,377
https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/resources/collections/cts.py#L305-L324
[ "def", "returnJobReqs", "(", "self", ",", "jobReqs", ")", ":", "# Since we are only reading this job's specific values from the state file, we don't", "# need a lock", "jobState", "=", "self", ".", "_JobState", "(", "self", ".", "_CacheState", ".", "_load", "(", "self", ".", "cacheStateFile", ")", ".", "jobState", "[", "self", ".", "jobID", "]", ")", "for", "x", "in", "list", "(", "jobState", ".", "jobSpecificFiles", ".", "keys", "(", ")", ")", ":", "self", ".", "deleteLocalFile", "(", "x", ")", "with", "self", ".", "_CacheState", ".", "open", "(", "self", ")", "as", "cacheInfo", ":", "cacheInfo", ".", "sigmaJob", "-=", "jobReqs" ]
Utility function to store a new . plist file and load it
def install ( label , plist ) : fname = launchd . plist . write ( label , plist ) launchd . load ( fname )
7,378
https://github.com/infothrill/python-launchd/blob/2cd50579e808851b116f5a26f9b871a32b65ce0e/example.py#L12-L20
[ "def", "find_sink_variables", "(", "self", ")", ":", "# First we assume all variables are sinks", "is_sink", "=", "{", "name", ":", "True", "for", "name", "in", "self", ".", "variables", ".", "keys", "(", ")", "}", "# Then, we remove those variables which are inputs of some operators", "for", "operator", "in", "self", ".", "operators", ".", "values", "(", ")", ":", "for", "variable", "in", "operator", ".", "inputs", ":", "is_sink", "[", "variable", ".", "onnx_name", "]", "=", "False", "return", "[", "variable", "for", "name", ",", "variable", "in", "self", ".", "variables", ".", "items", "(", ")", "if", "is_sink", "[", "name", "]", "]" ]
Utility function to remove a . plist file and unload it
def uninstall ( label ) : if launchd . LaunchdJob ( label ) . exists ( ) : fname = launchd . plist . discover_filename ( label ) launchd . unload ( fname ) os . unlink ( fname )
7,379
https://github.com/infothrill/python-launchd/blob/2cd50579e808851b116f5a26f9b871a32b65ce0e/example.py#L23-L32
[ "def", "_on_motion", "(", "self", ",", "event", ")", ":", "if", "not", "self", ".", "_visual_drag", ".", "winfo_ismapped", "(", ")", ":", "return", "if", "self", ".", "_drag_cols", "and", "self", ".", "_dragged_col", "is", "not", "None", ":", "self", ".", "_drag_col", "(", "event", ")", "elif", "self", ".", "_drag_rows", "and", "self", ".", "_dragged_row", "is", "not", "None", ":", "self", ".", "_drag_row", "(", "event", ")" ]
Write the content of buf out in a hexdump style
def write_hex ( fout , buf , offset , width = 16 ) : skipped_zeroes = 0 for i , chunk in enumerate ( chunk_iter ( buf , width ) ) : # zero skipping if chunk == ( b"\x00" * width ) : skipped_zeroes += 1 continue elif skipped_zeroes != 0 : fout . write ( " -- skipped zeroes: {}\n" . format ( skipped_zeroes ) ) skipped_zeroes = 0 # starting address of the current line fout . write ( "{:016x} " . format ( i * width + offset ) ) # bytes column column = " " . join ( [ " " . join ( [ "{:02x}" . format ( c ) for c in subchunk ] ) for subchunk in chunk_iter ( chunk , 8 ) ] ) w = width * 2 + ( width - 1 ) + ( ( width // 8 ) - 1 ) if len ( column ) != w : column += " " * ( w - len ( column ) ) fout . write ( column ) # ASCII character column fout . write ( " |" ) for c in chunk : if c in PRINTABLE_CHARS : fout . write ( chr ( c ) ) else : fout . write ( "." ) if len ( chunk ) < width : fout . write ( " " * ( width - len ( chunk ) ) ) fout . write ( "|" ) fout . write ( "\n" )
7,380
https://github.com/Grumbel/procmem/blob/a832a02c4ac79c15f108c72b251820e959a16639/procmem/hexdump.py#L26-L68
[ "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", "]" ]
returns the config as a dict .
def _read_config ( self ) : default_config_filepath = Path2 ( os . path . dirname ( __file__ ) , DEAFULT_CONFIG_FILENAME ) log . debug ( "Read defaults from: '%s'" % default_config_filepath ) if not default_config_filepath . is_file ( ) : raise RuntimeError ( "Internal error: Can't locate the default .ini file here: '%s'" % default_config_filepath ) config = self . _read_and_convert ( default_config_filepath , all_values = True ) log . debug ( "Defaults: %s" , pprint . pformat ( config ) ) self . ini_filepath = get_ini_filepath ( ) if not self . ini_filepath : # No .ini file made by user found # -> Create one into user home self . ini_filepath = get_user_ini_filepath ( ) # We don't use shutil.copyfile here, so the line endings will # be converted e.g. under windows from \n to \n\r with default_config_filepath . open ( "r" ) as infile : with self . ini_filepath . open ( "w" ) as outfile : outfile . write ( infile . read ( ) ) print ( "\n*************************************************************" ) print ( "Default config file was created into your home:" ) print ( "\t%s" % self . ini_filepath ) print ( "Change it for your needs ;)" ) print ( "*************************************************************\n" ) else : print ( "\nread user configuration from:" ) print ( "\t%s\n" % self . ini_filepath ) config . update ( self . _read_and_convert ( self . ini_filepath , all_values = False ) ) log . debug ( "RawConfig changed to: %s" , pprint . pformat ( config ) ) return config
7,381
https://github.com/jedie/PyHardLinkBackup/blob/be28666834d2d9e3d8aac1b661cb2d5bd4056c29/PyHardLinkBackup/phlb/config.py#L197-L233
[ "def", "reserve_udp_port", "(", "self", ",", "port", ",", "project", ")", ":", "if", "port", "in", "self", ".", "_used_udp_ports", ":", "raise", "HTTPConflict", "(", "text", "=", "\"UDP port {} already in use on host {}\"", ".", "format", "(", "port", ",", "self", ".", "_console_host", ")", ")", "if", "port", "<", "self", ".", "_udp_port_range", "[", "0", "]", "or", "port", ">", "self", ".", "_udp_port_range", "[", "1", "]", ":", "raise", "HTTPConflict", "(", "text", "=", "\"UDP port {} is outside the range {}-{}\"", ".", "format", "(", "port", ",", "self", ".", "_udp_port_range", "[", "0", "]", ",", "self", ".", "_udp_port_range", "[", "1", "]", ")", ")", "self", ".", "_used_udp_ports", ".", "add", "(", "port", ")", "project", ".", "record_udp_port", "(", "port", ")", "log", ".", "debug", "(", "\"UDP port {} has been reserved\"", ".", "format", "(", "port", ")", ")" ]
Bind a graph with generic MyCapytain prefixes
def bind_graph ( graph = None ) : if graph is None : graph = Graph ( ) for prefix , ns in GRAPH_BINDINGS . items ( ) : graph . bind ( prefix , ns , True ) return graph
7,382
https://github.com/Capitains/MyCapytain/blob/b11bbf6b6ae141fc02be70471e3fbf6907be6593/MyCapytain/common/constants.py#L123-L133
[ "def", "bench", "(", "image", ",", "thread_count", ")", ":", "threads", "=", "[", "threading", ".", "Thread", "(", "target", "=", "lambda", ":", "encoder", ".", "encode_png", "(", "image", ")", ")", "for", "_", "in", "xrange", "(", "thread_count", ")", "]", "start_time", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "for", "thread", "in", "threads", ":", "thread", ".", "start", "(", ")", "for", "thread", "in", "threads", ":", "thread", ".", "join", "(", ")", "end_time", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "delta", "=", "(", "end_time", "-", "start_time", ")", ".", "total_seconds", "(", ")", "return", "delta" ]
calculate electronic contributions in pressure for the Zharkov equation the equation can be found in Sokolova and Dorogokupets 2013
def zharkov_pel ( v , temp , v0 , e0 , g , n , z , t_ref = 300. , three_r = 3. * constants . R ) : v_mol = vol_uc2mol ( v , z ) x = v / v0 # a = a0 * np.power(x, m) def f ( t ) : return three_r * n / 2. * e0 * np . power ( x , g ) * np . power ( t , 2. ) * g / v_mol * 1.e-9 return f ( temp ) - f ( t_ref )
7,383
https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_electronic.py#L6-L30
[ "def", "determine_final_config", "(", "config_module", ")", ":", "config", "=", "Config", "(", "DEFAULT_LIBRARY_RC_ADDITIONS", ",", "DEFAULT_LIBRARY_RC_REPLACEMENTS", ",", "DEFAULT_TEST_RC_ADDITIONS", ",", "DEFAULT_TEST_RC_REPLACEMENTS", ")", "for", "field", "in", "config", ".", "_fields", ":", "if", "hasattr", "(", "config_module", ",", "field", ")", ":", "config", "=", "config", ".", "_replace", "(", "*", "*", "{", "field", ":", "getattr", "(", "config_module", ",", "field", ")", "}", ")", "return", "config" ]
calculate electronic contributions in pressure for the Tsuchiya equation
def tsuchiya_pel ( v , temp , v0 , a , b , c , d , n , z , three_r = 3. * constants . R , t_ref = 300. ) : def f ( temp ) : return a + b * temp + c * np . power ( temp , 2. ) + d * np . power ( temp , 3. ) return f ( temp ) - f ( t_ref )
7,384
https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_electronic.py#L33-L55
[ "def", "encode", "(", "data", ")", ":", "res", "=", "\"\"", "for", "i", "in", "range", "(", "0", ",", "len", "(", "data", ")", ",", "3", ")", ":", "if", "(", "i", "+", "2", "==", "len", "(", "data", ")", ")", ":", "res", "+=", "_encode3bytes", "(", "ord", "(", "data", "[", "i", "]", ")", ",", "ord", "(", "data", "[", "i", "+", "1", "]", ")", ",", "0", ")", "elif", "(", "i", "+", "1", "==", "len", "(", "data", ")", ")", ":", "res", "+=", "_encode3bytes", "(", "ord", "(", "data", "[", "i", "]", ")", ",", "0", ",", "0", ")", "else", ":", "res", "+=", "_encode3bytes", "(", "ord", "(", "data", "[", "i", "]", ")", ",", "ord", "(", "data", "[", "i", "+", "1", "]", ")", ",", "ord", "(", "data", "[", "i", "+", "2", "]", ")", ")", "return", "res" ]
Validate the resources defined in the options .
def _validate_resources ( self ) : resources = self . options . resources for key in [ 'num_machines' , 'num_mpiprocs_per_machine' , 'tot_num_mpiprocs' ] : if key in resources and resources [ key ] != 1 : raise exceptions . FeatureNotAvailable ( "Cannot set resource '{}' to value '{}' for {}: parallelization is not supported, " "only a value of '1' is accepted." . format ( key , resources [ key ] , self . __class__ . __name__ ) )
7,385
https://github.com/aiidateam/aiida-codtools/blob/da5e4259b7a2e86cf0cc3f997e11dd36d445fa94/aiida_codtools/calculations/cif_base.py#L58-L66
[ "def", "cublasZsyrk", "(", "handle", ",", "uplo", ",", "trans", ",", "n", ",", "k", ",", "alpha", ",", "A", ",", "lda", ",", "beta", ",", "C", ",", "ldc", ")", ":", "status", "=", "_libcublas", ".", "cublasZsyrk_v2", "(", "handle", ",", "_CUBLAS_FILL_MODE", "[", "uplo", "]", ",", "_CUBLAS_OP", "[", "trans", "]", ",", "n", ",", "k", ",", "ctypes", ".", "byref", "(", "cuda", ".", "cuDoubleComplex", "(", "alpha", ".", "real", ",", "alpha", ".", "imag", ")", ")", ",", "int", "(", "A", ")", ",", "lda", ",", "ctypes", ".", "byref", "(", "cuda", ".", "cuDoubleComplex", "(", "beta", ".", "real", ",", "beta", ".", "imag", ")", ")", ",", "int", "(", "C", ")", ",", "ldc", ")", "cublasCheckStatus", "(", "status", ")" ]
This method is called prior to job submission with a set of calculation input nodes .
def prepare_for_submission ( self , folder ) : from aiida_codtools . common . cli import CliParameters try : parameters = self . inputs . parameters . get_dict ( ) except AttributeError : parameters = { } self . _validate_resources ( ) cli_parameters = copy . deepcopy ( self . _default_cli_parameters ) cli_parameters . update ( parameters ) codeinfo = datastructures . CodeInfo ( ) codeinfo . code_uuid = self . inputs . code . uuid codeinfo . cmdline_params = CliParameters . from_dictionary ( cli_parameters ) . get_list ( ) codeinfo . stdin_name = self . options . input_filename codeinfo . stdout_name = self . options . output_filename codeinfo . stderr_name = self . options . error_filename calcinfo = datastructures . CalcInfo ( ) calcinfo . uuid = str ( self . uuid ) calcinfo . codes_info = [ codeinfo ] calcinfo . retrieve_list = [ self . options . output_filename , self . options . error_filename ] calcinfo . local_copy_list = [ ( self . inputs . cif . uuid , self . inputs . cif . filename , self . options . input_filename ) ] calcinfo . remote_copy_list = [ ] return calcinfo
7,386
https://github.com/aiidateam/aiida-codtools/blob/da5e4259b7a2e86cf0cc3f997e11dd36d445fa94/aiida_codtools/calculations/cif_base.py#L68-L104
[ "def", "arff_to_orange_table", "(", "arff", ")", ":", "with", "tempfile", ".", "NamedTemporaryFile", "(", "suffix", "=", "'.arff'", ",", "delete", "=", "True", ")", "as", "f", ":", "f", ".", "write", "(", "arff", ")", "f", ".", "flush", "(", ")", "table", "=", "orange", ".", "ExampleTable", "(", "f", ".", "name", ")", "return", "table" ]
calculate pressure along a Hugoniot
def hugoniot_p ( rho , rho0 , c0 , s ) : eta = 1. - ( rho0 / rho ) Ph = rho0 * c0 * c0 * eta / np . power ( ( 1. - s * eta ) , 2. ) return Ph
7,387
https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_hugoniot.py#L10-L22
[ "def", "make_random_models_table", "(", "n_sources", ",", "param_ranges", ",", "random_state", "=", "None", ")", ":", "prng", "=", "check_random_state", "(", "random_state", ")", "sources", "=", "Table", "(", ")", "for", "param_name", ",", "(", "lower", ",", "upper", ")", "in", "param_ranges", ".", "items", "(", ")", ":", "# Generate a column for every item in param_ranges, even if it", "# is not in the model (e.g. flux). However, such columns will", "# be ignored when rendering the image.", "sources", "[", "param_name", "]", "=", "prng", ".", "uniform", "(", "lower", ",", "upper", ",", "n_sources", ")", "return", "sources" ]
internal function for calculation of temperature along a Hugoniot
def _dT_h_delta ( T_in_kK , eta , k , threenk , c_v ) : rho0 = k [ 0 ] # g/m^3 gamma0 = k [ 3 ] # no unit q = k [ 4 ] # no unit theta0_in_kK = k [ 5 ] # K, see Jamieson 1983 for detail rho = rho0 / ( 1. - eta ) c0 = k [ 1 ] # km/s s = k [ 2 ] # no unit dPhdelta_H = rho0 * c0 * c0 * ( 1. + s * eta ) / np . power ( ( 1. - s * eta ) , 3. ) # [g/cm^3][km/s]^2 = 1e9[kg m^2/s^2] = [GPa] Ph = hugoniot_p ( rho , rho0 , c0 , s ) # in [GPa] # calculate Cv gamma = gamma0 * np . power ( ( 1. - eta ) , q ) theta_in_kK = theta0_in_kK * np . exp ( ( gamma0 - gamma ) / q ) x = theta_in_kK / T_in_kK debye3 = debye_E ( x ) if c_v == 0. : c_v = threenk * ( 4. * debye3 - 3. * x / ( np . exp ( x ) - 1. ) ) # [J/g/K] # calculate dYdX dYdX = ( gamma / ( 1. - eta ) * T_in_kK ) + ( dPhdelta_H * eta - Ph ) / ( 2. * c_v * rho0 ) # print('dYdX', dYdX) return dYdX
7,388
https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_hugoniot.py#L25-L60
[ "def", "filter_pem", "(", "data", ")", ":", "assert", "isinstance", "(", "data", ",", "bytes", ")", ",", "'Expect bytes. Got {}.'", ".", "format", "(", "type", "(", "data", ")", ")", "certs", "=", "set", "(", ")", "new_list", "=", "[", "]", "in_pem_block", "=", "False", "for", "line", "in", "re", ".", "split", "(", "br'[\\r\\n]+'", ",", "data", ")", ":", "if", "line", "==", "b'-----BEGIN CERTIFICATE-----'", ":", "assert", "not", "in_pem_block", "in_pem_block", "=", "True", "elif", "line", "==", "b'-----END CERTIFICATE-----'", ":", "assert", "in_pem_block", "in_pem_block", "=", "False", "content", "=", "b''", ".", "join", "(", "new_list", ")", "content", "=", "rewrap_bytes", "(", "content", ")", "certs", ".", "add", "(", "b'-----BEGIN CERTIFICATE-----\\n'", "+", "content", "+", "b'\\n-----END CERTIFICATE-----\\n'", ")", "new_list", "=", "[", "]", "elif", "in_pem_block", ":", "new_list", ".", "append", "(", "line", ")", "return", "certs" ]
internal function to calculate pressure along Hugoniot
def hugoniot_t_single ( rho , rho0 , c0 , s , gamma0 , q , theta0 , n , mass , three_r = 3. * constants . R , t_ref = 300. , c_v = 0. ) : eta = 1. - rho0 / rho if eta == 0.0 : return 300. threenk = three_r / mass * n # [J/mol/K] / [g/mol] = [J/g/K] k = [ rho0 , c0 , s , gamma0 , q , theta0 / 1.e3 ] t_h = odeint ( _dT_h_delta , t_ref / 1.e3 , [ 0. , eta ] , args = ( k , threenk , c_v ) , full_output = 1 ) temp_h = np . squeeze ( t_h [ 0 ] [ 1 ] ) return temp_h * 1.e3
7,389
https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_hugoniot.py#L63-L91
[ "def", "clusterstatus", "(", "self", ")", ":", "res", "=", "self", ".", "cluster_status_raw", "(", ")", "cluster", "=", "res", "[", "'cluster'", "]", "[", "'collections'", "]", "out", "=", "{", "}", "try", ":", "for", "collection", "in", "cluster", ":", "out", "[", "collection", "]", "=", "{", "}", "for", "shard", "in", "cluster", "[", "collection", "]", "[", "'shards'", "]", ":", "out", "[", "collection", "]", "[", "shard", "]", "=", "{", "}", "for", "replica", "in", "cluster", "[", "collection", "]", "[", "'shards'", "]", "[", "shard", "]", "[", "'replicas'", "]", ":", "out", "[", "collection", "]", "[", "shard", "]", "[", "replica", "]", "=", "cluster", "[", "collection", "]", "[", "'shards'", "]", "[", "shard", "]", "[", "'replicas'", "]", "[", "replica", "]", "if", "out", "[", "collection", "]", "[", "shard", "]", "[", "replica", "]", "[", "'state'", "]", "!=", "'active'", ":", "out", "[", "collection", "]", "[", "shard", "]", "[", "replica", "]", "[", "'doc_count'", "]", "=", "False", "else", ":", "out", "[", "collection", "]", "[", "shard", "]", "[", "replica", "]", "[", "'doc_count'", "]", "=", "self", ".", "_get_collection_counts", "(", "out", "[", "collection", "]", "[", "shard", "]", "[", "replica", "]", ")", "except", "Exception", "as", "e", ":", "self", ".", "logger", ".", "error", "(", "\"Couldn't parse response from clusterstatus API call\"", ")", "self", ".", "logger", ".", "exception", "(", "e", ")", "return", "out" ]
calculate temperature along a hugoniot
def hugoniot_t ( rho , rho0 , c0 , s , gamma0 , q , theta0 , n , mass , three_r = 3. * constants . R , t_ref = 300. , c_v = 0. ) : if isuncertainties ( [ rho , rho0 , c0 , s , gamma0 , q , theta0 ] ) : f_v = np . vectorize ( uct . wrap ( hugoniot_t_single ) , excluded = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 ] ) else : f_v = np . vectorize ( hugoniot_t_single , excluded = [ 1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9 , 10 , 11 ] ) return f_v ( rho , rho0 , c0 , s , gamma0 , q , theta0 , n , mass , three_r = three_r , t_ref = t_ref , c_v = c_v )
7,390
https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/eqn_hugoniot.py#L94-L121
[ "def", "clear_bucket_props", "(", "self", ",", "bucket", ")", ":", "bucket_type", "=", "self", ".", "_get_bucket_type", "(", "bucket", ".", "bucket_type", ")", "url", "=", "self", ".", "bucket_properties_path", "(", "bucket", ".", "name", ",", "bucket_type", "=", "bucket_type", ")", "url", "=", "self", ".", "bucket_properties_path", "(", "bucket", ".", "name", ")", "headers", "=", "{", "'Content-Type'", ":", "'application/json'", "}", "# Run the request...", "status", ",", "_", ",", "_", "=", "self", ".", "_request", "(", "'DELETE'", ",", "url", ",", "headers", ",", "None", ")", "if", "status", "==", "204", ":", "return", "True", "elif", "status", "==", "405", ":", "return", "False", "else", ":", "raise", "RiakError", "(", "'Error %s clearing bucket properties.'", "%", "status", ")" ]
Consumes the wrapper and returns a Python string . Afterwards is not necessary to destruct it as it has already been consumed .
def to_str ( self ) : val = c_backend . pystring_get_str ( self . _ptr ) delattr ( self , '_ptr' ) setattr ( self , 'to_str' , _dangling_pointer ) return val . decode ( "utf-8" )
7,391
https://github.com/iduartgomez/rustypy/blob/971701a4e18aeffceda16f2538f3a846713e65ff/src/rustypy/rswrapper/pytypes.py#L39-L46
[ "def", "set_threshold", "(", "self", ",", "threshold", ")", ":", "self", ".", "explorer", ".", "set_threshold", "(", "threshold", ")", "self", ".", "protocoler", ".", "set_threshold", "(", "threshold", ")" ]
Fetch list of servers that can be connected to .
def servers ( self , server = 'api.telldus.com' , port = http . HTTPS_PORT ) : logging . debug ( "Fetching server list from %s:%d" , server , port ) conn = http . HTTPSConnection ( server , port , context = self . ssl_context ( ) ) conn . request ( 'GET' , "/server/assign?protocolVersion=2" ) response = conn . getresponse ( ) if response . status != http . OK : raise RuntimeError ( "Could not connect to {}:{}: {} {}" . format ( server , port , response . status , response . reason ) ) servers = [ ] def extract_servers ( name , attributes ) : if name == "server" : servers . append ( ( attributes [ 'address' ] , int ( attributes [ 'port' ] ) ) ) parser = expat . ParserCreate ( ) parser . StartElementHandler = extract_servers parser . ParseFile ( response ) logging . debug ( "Found %d available servers" , len ( servers ) ) return servers
7,392
https://github.com/erijo/tellive-py/blob/a84ebb1eb29ee4c69a085e55e523ac5fff0087fc/tellive/tellstick.py#L56-L83
[ "def", "retrieve_log_trace", "(", "self", ",", "filename", "=", "None", ",", "dir", "=", "None", ")", ":", "if", "hasattr", "(", "self", ",", "\"applicationLogTrace\"", ")", "and", "self", ".", "applicationLogTrace", "is", "not", "None", ":", "logger", ".", "debug", "(", "\"Retrieving application logs from: \"", "+", "self", ".", "applicationLogTrace", ")", "if", "not", "filename", ":", "filename", "=", "_file_name", "(", "'job'", ",", "self", ".", "id", ",", "'.tar.gz'", ")", "return", "self", ".", "rest_client", ".", "_retrieve_file", "(", "self", ".", "applicationLogTrace", ",", "filename", ",", "dir", ",", "'application/x-compressed'", ")", "else", ":", "return", "None" ]
Run a shell command and return stdout
def execute ( cmd ) : proc = Popen ( cmd , stdout = PIPE ) stdout , _ = proc . communicate ( ) if proc . returncode != 0 : raise CalledProcessError ( proc . returncode , " " . join ( cmd ) ) return stdout . decode ( 'utf8' )
7,393
https://github.com/ChrisBeaumont/smother/blob/65d1ea6ae0060d213b0dcbb983c5aa8e7fee07bb/smother/git.py#L11-L18
[ "def", "parse_from_json", "(", "json_str", ")", ":", "try", ":", "message_dict", "=", "json", ".", "loads", "(", "json_str", ")", "except", "ValueError", ":", "raise", "ParseError", "(", "\"Mal-formed JSON input.\"", ")", "upload_keys", "=", "message_dict", ".", "get", "(", "'uploadKeys'", ",", "False", ")", "if", "upload_keys", "is", "False", ":", "raise", "ParseError", "(", "\"uploadKeys does not exist. At minimum, an empty array is required.\"", ")", "elif", "not", "isinstance", "(", "upload_keys", ",", "list", ")", ":", "raise", "ParseError", "(", "\"uploadKeys must be an array object.\"", ")", "upload_type", "=", "message_dict", "[", "'resultType'", "]", "try", ":", "if", "upload_type", "==", "'orders'", ":", "return", "orders", ".", "parse_from_dict", "(", "message_dict", ")", "elif", "upload_type", "==", "'history'", ":", "return", "history", ".", "parse_from_dict", "(", "message_dict", ")", "else", ":", "raise", "ParseError", "(", "'Unified message has unknown upload_type: %s'", "%", "upload_type", ")", "except", "TypeError", "as", "exc", ":", "# MarketOrder and HistoryEntry both raise TypeError exceptions if", "# invalid input is encountered.", "raise", "ParseError", "(", "exc", ".", "message", ")" ]
check if the input list contains any elements with uncertainties class
def isuncertainties ( arg_list ) : for arg in arg_list : if isinstance ( arg , ( list , tuple ) ) and isinstance ( arg [ 0 ] , uct . UFloat ) : return True elif isinstance ( arg , np . ndarray ) and isinstance ( np . atleast_1d ( arg ) [ 0 ] , uct . UFloat ) : return True elif isinstance ( arg , ( float , uct . UFloat ) ) and isinstance ( arg , uct . UFloat ) : return True return False
7,394
https://github.com/SHDShim/pytheos/blob/be079624405e92fbec60c5ead253eb5917e55237/pytheos/etc.py#L5-L21
[ "def", "pair", "(", "args", ")", ":", "p", "=", "OptionParser", "(", "pair", ".", "__doc__", ")", "opts", ",", "args", "=", "p", ".", "parse_args", "(", "args", ")", "if", "len", "(", "args", ")", "!=", "1", ":", "sys", ".", "exit", "(", "p", ".", "print_help", "(", ")", ")", "def", "callback", "(", "s", ")", ":", "print", "(", "s", ".", "pairline", ")", "Sam", "(", "args", "[", "0", "]", ",", "callback", "=", "callback", ")" ]
Returns a list of tuples for names that are tz data files .
def filter_tzfiles ( name_list ) : for src_name in name_list : # pytz-2012j/pytz/zoneinfo/Indian/Christmas parts = src_name . split ( '/' ) if len ( parts ) > 3 and parts [ 2 ] == 'zoneinfo' : dst_name = '/' . join ( parts [ 2 : ] ) yield src_name , dst_name
7,395
https://github.com/potatolondon/gae-pytz/blob/24741951a7af3e79cd8727ae3f79265decc93fef/makezoneinfo.py#L15-L22
[ "def", "GetAdGroups", "(", "self", ",", "client_customer_id", ",", "campaign_id", ")", ":", "self", ".", "client", ".", "SetClientCustomerId", "(", "client_customer_id", ")", "selector", "=", "{", "'fields'", ":", "[", "'Id'", ",", "'Name'", ",", "'Status'", "]", ",", "'predicates'", ":", "[", "{", "'field'", ":", "'CampaignId'", ",", "'operator'", ":", "'EQUALS'", ",", "'values'", ":", "[", "campaign_id", "]", "}", ",", "{", "'field'", ":", "'Status'", ",", "'operator'", ":", "'NOT_EQUALS'", ",", "'values'", ":", "[", "'REMOVED'", "]", "}", "]", "}", "adgroups", "=", "self", ".", "client", ".", "GetService", "(", "'AdGroupService'", ")", ".", "get", "(", "selector", ")", "if", "int", "(", "adgroups", "[", "'totalNumEntries'", "]", ")", ">", "0", ":", "return", "adgroups", "[", "'entries'", "]", "else", ":", "return", "None" ]
Initialize the application .
def setup ( self , app ) : super ( ) . setup ( app ) self . handlers = OrderedDict ( ) # Connect admin templates app . ps . jinja2 . cfg . template_folders . append ( op . join ( PLUGIN_ROOT , 'templates' ) ) @ app . ps . jinja2 . filter def admtest ( value , a , b = None ) : return a if value else b @ app . ps . jinja2 . filter def admeq ( a , b , result = True ) : return result if a == b else not result @ app . ps . jinja2 . register def admurl ( request , prefix ) : qs = { k : v for k , v in request . query . items ( ) if not k . startswith ( prefix ) } if not qs : qs = { 'ap' : 0 } return "%s?%s" % ( request . path , urlparse . urlencode ( qs ) ) if self . cfg . name is None : self . cfg . name = "%s admin" % app . name . title ( ) # Register a base view if not callable ( self . cfg . home ) : def admin_home ( request ) : yield from self . authorize ( request ) return app . ps . jinja2 . render ( self . cfg . template_home , active = None ) self . cfg . home = admin_home app . register ( self . cfg . prefix ) ( self . cfg . home ) if not self . cfg . i18n : app . ps . jinja2 . env . globals . update ( { '_' : lambda s : s , 'gettext' : lambda s : s , 'ngettext' : lambda s , p , n : ( n != 1 and ( p , ) or ( s , ) ) [ 0 ] , } ) return if 'babel' not in app . ps or not isinstance ( app . ps . babel , BPlugin ) : raise PluginException ( 'Plugin `%s` requires for plugin `%s` to be installed to the application.' % ( self . name , BPlugin ) ) # Connect admin locales app . ps . babel . cfg . locales_dirs . append ( op . join ( PLUGIN_ROOT , 'locales' ) ) if not app . ps . babel . locale_selector_func : app . ps . babel . locale_selector_func = app . ps . babel . select_locale_by_request
7,396
https://github.com/klen/muffin-admin/blob/404dc8e5107e943b7c42fa21c679c34ddb4de1d5/muffin_admin/plugin.py#L44-L99
[ "def", "_assign_numbers", "(", "self", ")", ":", "first", "=", "self", ".", "select_related", "(", "'point_of_sales'", ",", "'receipt_type'", ")", ".", "first", "(", ")", "next_num", "=", "Receipt", ".", "objects", ".", "fetch_last_receipt_number", "(", "first", ".", "point_of_sales", ",", "first", ".", "receipt_type", ",", ")", "+", "1", "for", "receipt", "in", "self", ".", "filter", "(", "receipt_number__isnull", "=", "True", ")", ":", "# Atomically update receipt number", "Receipt", ".", "objects", ".", "filter", "(", "pk", "=", "receipt", ".", "id", ",", "receipt_number__isnull", "=", "True", ",", ")", ".", "update", "(", "receipt_number", "=", "next_num", ",", ")", "next_num", "+=", "1" ]
Ensure that handler is not registered .
def register ( self , * handlers , * * params ) : for handler in handlers : if issubclass ( handler , PWModel ) : handler = type ( handler . _meta . db_table . title ( ) + 'Admin' , ( PWAdminHandler , ) , dict ( model = handler , * * params ) ) self . app . register ( handler ) continue name = handler . name . lower ( ) self . handlers [ name ] = handler
7,397
https://github.com/klen/muffin-admin/blob/404dc8e5107e943b7c42fa21c679c34ddb4de1d5/muffin_admin/plugin.py#L101-L113
[ "def", "configure_materials_manager", "(", "graph", ",", "key_provider", ")", ":", "if", "graph", ".", "config", ".", "materials_manager", ".", "enable_cache", ":", "return", "CachingCryptoMaterialsManager", "(", "cache", "=", "LocalCryptoMaterialsCache", "(", "graph", ".", "config", ".", "materials_manager", ".", "cache_capacity", ")", ",", "master_key_provider", "=", "key_provider", ",", "max_age", "=", "graph", ".", "config", ".", "materials_manager", ".", "cache_max_age", ",", "max_messages_encrypted", "=", "graph", ".", "config", ".", "materials_manager", ".", "cache_max_messages_encrypted", ",", ")", "return", "DefaultCryptoMaterialsManager", "(", "master_key_provider", "=", "key_provider", ")" ]
Define a authorization process .
def authorization ( self , func ) : if self . app is None : raise PluginException ( 'The plugin must be installed to application.' ) self . authorize = muffin . to_coroutine ( func ) return func
7,398
https://github.com/klen/muffin-admin/blob/404dc8e5107e943b7c42fa21c679c34ddb4de1d5/muffin_admin/plugin.py#L115-L121
[ "def", "dropout_with_broadcast_dims", "(", "x", ",", "keep_prob", ",", "broadcast_dims", "=", "None", ",", "*", "*", "kwargs", ")", ":", "assert", "\"noise_shape\"", "not", "in", "kwargs", "if", "broadcast_dims", ":", "shape", "=", "tf", ".", "shape", "(", "x", ")", "ndims", "=", "len", "(", "x", ".", "get_shape", "(", ")", ")", "# Allow dimensions like \"-1\" as well.", "broadcast_dims", "=", "[", "dim", "+", "ndims", "if", "dim", "<", "0", "else", "dim", "for", "dim", "in", "broadcast_dims", "]", "kwargs", "[", "\"noise_shape\"", "]", "=", "[", "1", "if", "i", "in", "broadcast_dims", "else", "shape", "[", "i", "]", "for", "i", "in", "range", "(", "ndims", ")", "]", "return", "tf", ".", "nn", ".", "dropout", "(", "x", ",", "keep_prob", ",", "*", "*", "kwargs", ")" ]
yields only directories with the given deep limit
def scandir_limited ( top , limit , deep = 0 ) : deep += 1 try : scandir_it = Path2 ( top ) . scandir ( ) except PermissionError as err : log . error ( "scandir error: %s" % err ) return for entry in scandir_it : if entry . is_dir ( follow_symlinks = False ) : if deep < limit : yield from scandir_limited ( entry . path , limit , deep ) else : yield entry
7,399
https://github.com/jedie/PyHardLinkBackup/blob/be28666834d2d9e3d8aac1b661cb2d5bd4056c29/PyHardLinkBackup/phlb/filesystem_walk.py#L42-L63
[ "def", "_insert", "(", "self", ",", "namespace", ",", "stream", ",", "events", ",", "configuration", ")", ":", "index", "=", "self", ".", "index_manager", ".", "get_index", "(", "namespace", ")", "start_dts_to_add", "=", "set", "(", ")", "def", "actions", "(", ")", ":", "for", "_id", ",", "event", "in", "events", ":", "dt", "=", "kronos_time_to_datetime", "(", "uuid_to_kronos_time", "(", "_id", ")", ")", "start_dts_to_add", ".", "add", "(", "_round_datetime_down", "(", "dt", ")", ")", "event", "[", "'_index'", "]", "=", "index", "event", "[", "'_type'", "]", "=", "stream", "event", "[", "LOGSTASH_TIMESTAMP_FIELD", "]", "=", "dt", ".", "isoformat", "(", ")", "yield", "event", "list", "(", "es_helpers", ".", "streaming_bulk", "(", "self", ".", "es", ",", "actions", "(", ")", ",", "chunk_size", "=", "1000", ",", "refresh", "=", "self", ".", "force_refresh", ")", ")", "self", ".", "index_manager", ".", "add_aliases", "(", "namespace", ",", "index", ",", "start_dts_to_add", ")" ]