query
stringlengths
5
1.23k
positive
stringlengths
53
15.2k
id_
int64
0
252k
task_name
stringlengths
87
242
negative
listlengths
20
553
Extract member or element of obj according to pointer .
def extract ( obj , pointer , bypass_ref = False ) : return Pointer ( pointer ) . extract ( obj , bypass_ref )
5,800
https://github.com/johnnoone/json-spec/blob/f91981724cea0c366bd42a6670eb07bbe31c0e0c/src/jsonspec/pointer/__init__.py#L23-L33
[ "def", "async_refresh_state", "(", "self", ")", ":", "_LOGGER", ".", "debug", "(", "'Setting up extended status'", ")", "ext_status", "=", "ExtendedSend", "(", "address", "=", "self", ".", "_address", ",", "commandtuple", "=", "COMMAND_EXTENDED_GET_SET_0X2E_0X00", ",", "cmd2", "=", "0x02", ",", "userdata", "=", "Userdata", "(", ")", ")", "ext_status", ".", "set_crc", "(", ")", "_LOGGER", ".", "debug", "(", "'Sending ext status: %s'", ",", "ext_status", ")", "self", ".", "_send_msg", "(", "ext_status", ")", "_LOGGER", ".", "debug", "(", "'Sending temp status request'", ")", "self", ".", "temperature", ".", "async_refresh_state", "(", ")" ]
Calculate the amino acid frequencies in a set of SeqRecords .
def aa_counts ( aln , weights = None , gap_chars = '-.' ) : if weights is None : counts = Counter ( ) for rec in aln : seq_counts = Counter ( str ( rec . seq ) ) counts . update ( seq_counts ) else : if weights == True : # For convenience weights = sequence_weights ( aln ) else : assert len ( weights ) == len ( aln ) , ( "Length mismatch: weights = %d, alignment = %d" % ( len ( weights ) , len ( aln ) ) ) counts = defaultdict ( float ) for col in zip ( * aln ) : for aa , wt in zip ( col , weights ) : counts [ aa ] += wt # Don't count gaps for gap_char in gap_chars : if gap_char in counts : del counts [ gap_char ] return counts
5,801
https://github.com/etal/biofrills/blob/36684bb6c7632f96215e8b2b4ebc86640f331bcd/biofrills/alnutils.py#L13-L43
[ "def", "get_web_session_cookies", "(", "self", ")", ":", "if", "not", "self", ".", "logged_on", ":", "return", "None", "resp", "=", "self", ".", "send_job_and_wait", "(", "MsgProto", "(", "EMsg", ".", "ClientRequestWebAPIAuthenticateUserNonce", ")", ",", "timeout", "=", "7", ")", "if", "resp", "is", "None", ":", "return", "None", "skey", ",", "ekey", "=", "generate_session_key", "(", ")", "data", "=", "{", "'steamid'", ":", "self", ".", "steam_id", ",", "'sessionkey'", ":", "ekey", ",", "'encrypted_loginkey'", ":", "symmetric_encrypt", "(", "resp", ".", "webapi_authenticate_user_nonce", ".", "encode", "(", "'ascii'", ")", ",", "skey", ")", ",", "}", "try", ":", "resp", "=", "webapi", ".", "post", "(", "'ISteamUserAuth'", ",", "'AuthenticateUser'", ",", "1", ",", "params", "=", "data", ")", "except", "Exception", "as", "exp", ":", "self", ".", "_LOG", ".", "debug", "(", "\"get_web_session_cookies error: %s\"", "%", "str", "(", "exp", ")", ")", "return", "None", "return", "{", "'steamLogin'", ":", "resp", "[", "'authenticateuser'", "]", "[", "'token'", "]", ",", "'steamLoginSecure'", ":", "resp", "[", "'authenticateuser'", "]", "[", "'tokensecure'", "]", ",", "}" ]
Frequency of each residue type in an alignment .
def aa_frequencies ( aln , weights = None , gap_chars = '-.' ) : counts = aa_counts ( aln , weights , gap_chars ) # Reduce to frequencies scale = 1.0 / sum ( counts . values ( ) ) return dict ( ( aa , cnt * scale ) for aa , cnt in counts . iteritems ( ) )
5,802
https://github.com/etal/biofrills/blob/36684bb6c7632f96215e8b2b4ebc86640f331bcd/biofrills/alnutils.py#L46-L54
[ "def", "logout", "(", "self", ")", ":", "# Check if all transfers are complete before logout", "self", ".", "transfers_complete", "payload", "=", "{", "'apikey'", ":", "self", ".", "config", ".", "get", "(", "'apikey'", ")", ",", "'logintoken'", ":", "self", ".", "session", ".", "cookies", ".", "get", "(", "'logintoken'", ")", "}", "method", ",", "url", "=", "get_URL", "(", "'logout'", ")", "res", "=", "getattr", "(", "self", ".", "session", ",", "method", ")", "(", "url", ",", "params", "=", "payload", ")", "if", "res", ".", "status_code", "==", "200", ":", "self", ".", "session", ".", "cookies", "[", "'logintoken'", "]", "=", "None", "return", "True", "hellraiser", "(", "res", ")" ]
Remove gappy columns from an alignment .
def blocks ( aln , threshold = 0.5 , weights = None ) : assert len ( aln ) if weights == False : def pct_nongaps ( col ) : return 1 - ( float ( col . count ( '-' ) ) / len ( col ) ) else : if weights in ( None , True ) : weights = sequence_weights ( aln , 'avg1' ) def pct_nongaps ( col ) : assert len ( col ) == len ( weights ) ngaps = sum ( wt * ( c == '-' ) for wt , c in zip ( weights , col ) ) return 1 - ( ngaps / len ( col ) ) seqstrs = [ str ( rec . seq ) for rec in aln ] clean_cols = [ col for col in zip ( * seqstrs ) if pct_nongaps ( col ) >= threshold ] alphabet = aln [ 0 ] . seq . alphabet clean_seqs = [ Seq ( '' . join ( row ) , alphabet ) for row in zip ( * clean_cols ) ] clean_recs = [ ] for rec , seq in zip ( aln , clean_seqs ) : newrec = deepcopy ( rec ) newrec . seq = seq clean_recs . append ( newrec ) return MultipleSeqAlignment ( clean_recs , alphabet = alphabet )
5,803
https://github.com/etal/biofrills/blob/36684bb6c7632f96215e8b2b4ebc86640f331bcd/biofrills/alnutils.py#L57-L83
[ "def", "count_weights", "(", "scope", "=", "None", ",", "exclude", "=", "None", ",", "graph", "=", "None", ")", ":", "if", "scope", ":", "scope", "=", "scope", "if", "scope", ".", "endswith", "(", "'/'", ")", "else", "scope", "+", "'/'", "graph", "=", "graph", "or", "tf", ".", "get_default_graph", "(", ")", "vars_", "=", "graph", ".", "get_collection", "(", "tf", ".", "GraphKeys", ".", "TRAINABLE_VARIABLES", ")", "if", "scope", ":", "vars_", "=", "[", "var", "for", "var", "in", "vars_", "if", "var", ".", "name", ".", "startswith", "(", "scope", ")", "]", "if", "exclude", ":", "exclude", "=", "re", ".", "compile", "(", "exclude", ")", "vars_", "=", "[", "var", "for", "var", "in", "vars_", "if", "not", "exclude", ".", "match", "(", "var", ".", "name", ")", "]", "shapes", "=", "[", "var", ".", "get_shape", "(", ")", ".", "as_list", "(", ")", "for", "var", "in", "vars_", "]", "return", "int", "(", "sum", "(", "np", ".", "prod", "(", "shape", ")", "for", "shape", "in", "shapes", ")", ")" ]
Absolute counts of each residue type in a single column .
def col_counts ( col , weights = None , gap_chars = '-.' ) : cnt = defaultdict ( float ) for aa , wt in zip ( col , weights ) : if aa not in gap_chars : cnt [ aa ] += wt return cnt
5,804
https://github.com/etal/biofrills/blob/36684bb6c7632f96215e8b2b4ebc86640f331bcd/biofrills/alnutils.py#L86-L92
[ "async", "def", "upload", "(", "self", ",", "files", ":", "Sequence", "[", "Union", "[", "str", ",", "Path", "]", "]", ",", "basedir", ":", "Union", "[", "str", ",", "Path", "]", "=", "None", ",", "show_progress", ":", "bool", "=", "False", ")", ":", "params", "=", "{", "}", "if", "self", ".", "owner_access_key", ":", "params", "[", "'owner_access_key'", "]", "=", "self", ".", "owner_access_key", "base_path", "=", "(", "Path", ".", "cwd", "(", ")", "if", "basedir", "is", "None", "else", "Path", "(", "basedir", ")", ".", "resolve", "(", ")", ")", "files", "=", "[", "Path", "(", "file", ")", ".", "resolve", "(", ")", "for", "file", "in", "files", "]", "total_size", "=", "0", "for", "file_path", "in", "files", ":", "total_size", "+=", "file_path", ".", "stat", "(", ")", ".", "st_size", "tqdm_obj", "=", "tqdm", "(", "desc", "=", "'Uploading files'", ",", "unit", "=", "'bytes'", ",", "unit_scale", "=", "True", ",", "total", "=", "total_size", ",", "disable", "=", "not", "show_progress", ")", "with", "tqdm_obj", ":", "attachments", "=", "[", "]", "for", "file_path", "in", "files", ":", "try", ":", "attachments", ".", "append", "(", "AttachedFile", "(", "str", "(", "file_path", ".", "relative_to", "(", "base_path", ")", ")", ",", "ProgressReportingReader", "(", "str", "(", "file_path", ")", ",", "tqdm_instance", "=", "tqdm_obj", ")", ",", "'application/octet-stream'", ",", ")", ")", "except", "ValueError", ":", "msg", "=", "'File \"{0}\" is outside of the base directory \"{1}\".'", ".", "format", "(", "file_path", ",", "base_path", ")", "raise", "ValueError", "(", "msg", ")", "from", "None", "rqst", "=", "Request", "(", "self", ".", "session", ",", "'POST'", ",", "'/kernel/{}/upload'", ".", "format", "(", "self", ".", "kernel_id", ")", ",", "params", "=", "params", ")", "rqst", ".", "attach_files", "(", "attachments", ")", "async", "with", "rqst", ".", "fetch", "(", ")", "as", "resp", ":", "return", "resp" ]
Remove all - gap columns from aligned SeqRecords .
def remove_empty_cols ( records ) : # In case it's a generator, turn it into a list records = list ( records ) seqstrs = [ str ( rec . seq ) for rec in records ] clean_cols = [ col for col in zip ( * seqstrs ) if not all ( c == '-' for c in col ) ] clean_seqs = [ '' . join ( row ) for row in zip ( * clean_cols ) ] for rec , clean_seq in zip ( records , clean_seqs ) : yield SeqRecord ( Seq ( clean_seq , rec . seq . alphabet ) , id = rec . id , name = rec . name , description = rec . description , dbxrefs = rec . dbxrefs , features = rec . features , annotations = rec . annotations , letter_annotations = rec . letter_annotations )
5,805
https://github.com/etal/biofrills/blob/36684bb6c7632f96215e8b2b4ebc86640f331bcd/biofrills/alnutils.py#L103-L118
[ "def", "download_videos", "(", "cls", ",", "name", ",", "test_passed", "=", "True", ",", "maintain_default", "=", "False", ")", ":", "# Exclude first wrapper if the driver must be reused", "driver_wrappers", "=", "cls", ".", "driver_wrappers", "[", "1", ":", "]", "if", "maintain_default", "else", "cls", ".", "driver_wrappers", "video_name", "=", "'{}_driver{}'", "if", "len", "(", "driver_wrappers", ")", ">", "1", "else", "'{}'", "video_name", "=", "video_name", "if", "test_passed", "else", "'error_{}'", ".", "format", "(", "video_name", ")", "driver_index", "=", "1", "for", "driver_wrapper", "in", "driver_wrappers", ":", "if", "not", "driver_wrapper", ".", "driver", ":", "continue", "try", ":", "# Download video if necessary (error case or enabled video)", "if", "(", "not", "test_passed", "or", "driver_wrapper", ".", "config", ".", "getboolean_optional", "(", "'Server'", ",", "'video_enabled'", ",", "False", ")", ")", "and", "driver_wrapper", ".", "remote_node_video_enabled", ":", "if", "driver_wrapper", ".", "server_type", "in", "[", "'ggr'", ",", "'selenoid'", "]", ":", "name", "=", "get_valid_filename", "(", "video_name", ".", "format", "(", "name", ",", "driver_index", ")", ")", "Selenoid", "(", "driver_wrapper", ")", ".", "download_session_video", "(", "name", ")", "elif", "driver_wrapper", ".", "server_type", "==", "'grid'", ":", "# Download video from Grid Extras", "driver_wrapper", ".", "utils", ".", "download_remote_video", "(", "driver_wrapper", ".", "remote_node", ",", "driver_wrapper", ".", "session_id", ",", "video_name", ".", "format", "(", "name", ",", "driver_index", ")", ")", "except", "Exception", "as", "exc", ":", "# Capture exceptions to avoid errors in teardown method due to session timeouts", "driver_wrapper", ".", "logger", ".", "warn", "(", "'Error downloading videos: %s'", "%", "exc", ")", "driver_index", "+=", "1" ]
Weight aligned sequences to emphasize more divergent members .
def sequence_weights ( aln , scaling = 'none' , gap_chars = '-.' ) : # Probability is hard, let's estimate by sampling! # Sample k from a population of 20 with replacement; how many unique k were # chosen? Average of 10000 runs for k = 0..100 expectk = [ 0.0 , 1.0 , 1.953 , 2.861 , 3.705 , 4.524 , 5.304 , 6.026 , 6.724 , 7.397 , 8.04 , 8.622 , 9.191 , 9.739 , 10.264 , 10.758 , 11.194 , 11.635 , 12.049 , 12.468 , 12.806 , 13.185 , 13.539 , 13.863 , 14.177 , 14.466 , 14.737 , 15.005 , 15.245 , 15.491 , 15.681 , 15.916 , 16.12 , 16.301 , 16.485 , 16.671 , 16.831 , 16.979 , 17.151 , 17.315 , 17.427 , 17.559 , 17.68 , 17.791 , 17.914 , 18.009 , 18.113 , 18.203 , 18.298 , 18.391 , 18.46 , 18.547 , 18.617 , 18.669 , 18.77 , 18.806 , 18.858 , 18.934 , 18.978 , 19.027 , 19.085 , 19.119 , 19.169 , 19.202 , 19.256 , 19.291 , 19.311 , 19.357 , 19.399 , 19.416 , 19.456 , 19.469 , 19.5 , 19.53 , 19.553 , 19.562 , 19.602 , 19.608 , 19.629 , 19.655 , 19.67 , 19.681 , 19.7 , 19.716 , 19.724 , 19.748 , 19.758 , 19.765 , 19.782 , 19.791 , 19.799 , 19.812 , 19.82 , 19.828 , 19.844 , 19.846 , 19.858 , 19.863 , 19.862 , 19.871 , 19.882 ] def col_weight ( column ) : """Represent the diversity at a position. Award each different residue an equal share of the weight, and then divide that weight equally among the sequences sharing the same residue. So, if in a position of a multiple alignment, r different residues are represented, a residue represented in only one sequence contributes a score of 1/r to that sequence, whereas a residue represented in s sequences contributes a score of 1/rs to each of the s sequences. """ # Skip columns of all or mostly gaps (i.e. rare inserts) min_nongap = max ( 2 , .2 * len ( column ) ) if len ( [ c for c in column if c not in gap_chars ] ) < min_nongap : return ( [ 0 ] * len ( column ) , 0 ) # Count the number of occurrences of each residue type # (Treat gaps as a separate, 21st character) counts = Counter ( column ) # Get residue weights: 1/rs, where # r = nb. residue types, s = count of a particular residue type n_residues = len ( counts ) # r freqs = dict ( ( aa , 1.0 / ( n_residues * count ) ) for aa , count in counts . iteritems ( ) ) weights = [ freqs [ aa ] for aa in column ] return ( weights , n_residues ) seq_weights = [ 0 ] * len ( aln ) tot_nres = 0.0 # Expected no. different types in independent seqs # Sum the contributions from each position along each sequence # -> total weight for col in zip ( * aln ) : wts , nres = col_weight ( col ) assert sum ( wts ) <= 20 tot_nres += expectk [ nres ] if nres < len ( expectk ) else 20 for idx , wt in enumerate ( wts ) : seq_weights [ idx ] += wt # if tot_nres == 0: # raise ValueError("Alignment has no meaningful columns to weight") # Normalize w/ the given scaling criterion if scaling == 'none' : avg_seq_len = tot_nres / len ( aln ) return [ wt / avg_seq_len for wt in seq_weights ] if scaling == 'max1' : scale = 1.0 / max ( seq_weights ) elif scaling == 'sum1' : scale = 1.0 / sum ( seq_weights ) elif scaling == 'avg1' : scale = len ( aln ) / sum ( seq_weights ) elif scaling == 'andy' : # "Robust" strategy used in CHAIN (Neuwald 2003) scale = len ( aln ) / sum ( seq_weights ) return [ min ( scale * wt , 1.0 ) for wt in seq_weights ] else : raise ValueError ( "Unknown scaling scheme '%s'" % scaling ) return [ scale * wt for wt in seq_weights ]
5,806
https://github.com/etal/biofrills/blob/36684bb6c7632f96215e8b2b4ebc86640f331bcd/biofrills/alnutils.py#L121-L215
[ "def", "setChannel", "(", "self", ",", "channel", ",", "wifiInterfaceId", "=", "1", ",", "timeout", "=", "1", ")", ":", "namespace", "=", "Wifi", ".", "getServiceType", "(", "\"setChannel\"", ")", "+", "str", "(", "wifiInterfaceId", ")", "uri", "=", "self", ".", "getControlURL", "(", "namespace", ")", "self", ".", "execute", "(", "uri", ",", "namespace", ",", "\"SetChannel\"", ",", "timeout", "=", "timeout", ",", "NewChannel", "=", "channel", ")" ]
Create a NetworkX graph from a sequence alignment .
def to_graph ( alnfname , weight_func ) : import networkx G = networkx . Graph ( ) aln = AlignIO . read ( alnfname , 'fasta' ) for i , arec in enumerate ( aln ) : for brec in aln [ i + 1 : ] : ident = weight_func ( str ( arec . seq ) , str ( brec . seq ) ) G . add_edge ( arec . id , brec . id , weight = ident ) return G
5,807
https://github.com/etal/biofrills/blob/36684bb6c7632f96215e8b2b4ebc86640f331bcd/biofrills/alnutils.py#L218-L231
[ "def", "clear_stalled_files", "(", "self", ")", ":", "# FIXME: put lock in directory?", "CLEAR_AFTER", "=", "self", ".", "config", "[", "\"DELETE_STALLED_AFTER\"", "]", "minimum_age", "=", "time", ".", "time", "(", ")", "-", "CLEAR_AFTER", "for", "user_dir", "in", "self", ".", "UPLOAD_DIR", ".", "iterdir", "(", ")", ":", "if", "not", "user_dir", ".", "is_dir", "(", ")", ":", "logger", ".", "error", "(", "\"Found non-directory in upload dir: %r\"", ",", "bytes", "(", "user_dir", ")", ")", "continue", "for", "content", "in", "user_dir", ".", "iterdir", "(", ")", ":", "if", "not", "content", ".", "is_file", "(", ")", ":", "logger", ".", "error", "(", "\"Found non-file in user upload dir: %r\"", ",", "bytes", "(", "content", ")", ")", "continue", "if", "content", ".", "stat", "(", ")", ".", "st_ctime", "<", "minimum_age", ":", "content", ".", "unlink", "(", ")" ]
Return Met Office guidance regarding UV exposure based on UV index
def guidance_UV ( index ) : if 0 < index < 3 : guidance = "Low exposure. No protection required. You can safely stay outside" elif 2 < index < 6 : guidance = "Moderate exposure. Seek shade during midday hours, cover up and wear sunscreen" elif 5 < index < 8 : guidance = "High exposure. Seek shade during midday hours, cover up and wear sunscreen" elif 7 < index < 11 : guidance = "Very high. Avoid being outside during midday hours. Shirt, sunscreen and hat are essential" elif index > 10 : guidance = "Extreme. Avoid being outside during midday hours. Shirt, sunscreen and hat essential." else : guidance = None return guidance
5,808
https://github.com/sludgedesk/metoffer/blob/449748d31f913d961d6f0406542bb784e931a95b/metoffer.py#L158-L172
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "_mpoll", "is", "None", ":", "return", "for", "mpoll", "in", "self", ".", "_mpoll", ".", "values", "(", ")", ":", "mpoll", ".", "close", "(", ")", "self", ".", "_mpoll", ".", "clear", "(", ")", "self", ".", "_mpoll", "=", "None" ]
Return list of Site instances from retrieved sitelist data
def parse_sitelist ( sitelist ) : sites = [ ] for site in sitelist [ "Locations" ] [ "Location" ] : try : ident = site [ "id" ] name = site [ "name" ] except KeyError : ident = site [ "@id" ] # Difference between loc-spec and text for some reason name = site [ "@name" ] if "latitude" in site : lat = float ( site [ "latitude" ] ) lon = float ( site [ "longitude" ] ) else : lat = lon = None s = Site ( ident , name , lat , lon ) sites . append ( s ) return sites
5,809
https://github.com/sludgedesk/metoffer/blob/449748d31f913d961d6f0406542bb784e931a95b/metoffer.py#L323-L340
[ "def", "construct_error_message", "(", "driver_id", ",", "error_type", ",", "message", ",", "timestamp", ")", ":", "builder", "=", "flatbuffers", ".", "Builder", "(", "0", ")", "driver_offset", "=", "builder", ".", "CreateString", "(", "driver_id", ".", "binary", "(", ")", ")", "error_type_offset", "=", "builder", ".", "CreateString", "(", "error_type", ")", "message_offset", "=", "builder", ".", "CreateString", "(", "message", ")", "ray", ".", "core", ".", "generated", ".", "ErrorTableData", ".", "ErrorTableDataStart", "(", "builder", ")", "ray", ".", "core", ".", "generated", ".", "ErrorTableData", ".", "ErrorTableDataAddDriverId", "(", "builder", ",", "driver_offset", ")", "ray", ".", "core", ".", "generated", ".", "ErrorTableData", ".", "ErrorTableDataAddType", "(", "builder", ",", "error_type_offset", ")", "ray", ".", "core", ".", "generated", ".", "ErrorTableData", ".", "ErrorTableDataAddErrorMessage", "(", "builder", ",", "message_offset", ")", "ray", ".", "core", ".", "generated", ".", "ErrorTableData", ".", "ErrorTableDataAddTimestamp", "(", "builder", ",", "timestamp", ")", "error_data_offset", "=", "ray", ".", "core", ".", "generated", ".", "ErrorTableData", ".", "ErrorTableDataEnd", "(", "builder", ")", "builder", ".", "Finish", "(", "error_data_offset", ")", "return", "bytes", "(", "builder", ".", "Output", "(", ")", ")" ]
Request and return data from DataPoint RESTful API .
def _query ( self , data_category , resource_category , field , request , step , isotime = None ) : rest_url = "/" . join ( [ HOST , data_category , resource_category , field , DATA_TYPE , request ] ) query_string = "?" + "&" . join ( [ "res=" + step , "time=" + isotime if isotime is not None else "" , "key=" + self . key ] ) url = rest_url + query_string page = url_lib . urlopen ( url ) pg = page . read ( ) return pg
5,810
https://github.com/sludgedesk/metoffer/blob/449748d31f913d961d6f0406542bb784e931a95b/metoffer.py#L179-L188
[ "def", "rollback", "(", "*", "*", "kwargs", ")", ":", "id_", "=", "kwargs", ".", "pop", "(", "'id'", ",", "0", ")", "ret", "=", "{", "}", "conn", "=", "__proxy__", "[", "'junos.conn'", "]", "(", ")", "op", "=", "dict", "(", ")", "if", "'__pub_arg'", "in", "kwargs", ":", "if", "kwargs", "[", "'__pub_arg'", "]", ":", "if", "isinstance", "(", "kwargs", "[", "'__pub_arg'", "]", "[", "-", "1", "]", ",", "dict", ")", ":", "op", ".", "update", "(", "kwargs", "[", "'__pub_arg'", "]", "[", "-", "1", "]", ")", "else", ":", "op", ".", "update", "(", "kwargs", ")", "try", ":", "ret", "[", "'out'", "]", "=", "conn", ".", "cu", ".", "rollback", "(", "id_", ")", "except", "Exception", "as", "exception", ":", "ret", "[", "'message'", "]", "=", "'Rollback failed due to \"{0}\"'", ".", "format", "(", "exception", ")", "ret", "[", "'out'", "]", "=", "False", "return", "ret", "if", "ret", "[", "'out'", "]", ":", "ret", "[", "'message'", "]", "=", "'Rollback successful'", "else", ":", "ret", "[", "'message'", "]", "=", "'Rollback failed'", "return", "ret", "if", "'diffs_file'", "in", "op", "and", "op", "[", "'diffs_file'", "]", "is", "not", "None", ":", "diff", "=", "conn", ".", "cu", ".", "diff", "(", ")", "if", "diff", "is", "not", "None", ":", "with", "salt", ".", "utils", ".", "files", ".", "fopen", "(", "op", "[", "'diffs_file'", "]", ",", "'w'", ")", "as", "fp", ":", "fp", ".", "write", "(", "salt", ".", "utils", ".", "stringutils", ".", "to_str", "(", "diff", ")", ")", "else", ":", "log", ".", "info", "(", "'No diff between current configuration and \\\n rollbacked configuration, so no diff file created'", ")", "try", ":", "commit_ok", "=", "conn", ".", "cu", ".", "commit_check", "(", ")", "except", "Exception", "as", "exception", ":", "ret", "[", "'message'", "]", "=", "'Could not commit check due to \"{0}\"'", ".", "format", "(", "exception", ")", "ret", "[", "'out'", "]", "=", "False", "return", "ret", "if", "commit_ok", ":", "try", ":", "conn", ".", "cu", ".", "commit", "(", "*", "*", "op", ")", "ret", "[", "'out'", "]", "=", "True", "except", "Exception", "as", "exception", ":", "ret", "[", "'out'", "]", "=", "False", "ret", "[", "'message'", "]", "=", "'Rollback successful but commit failed with error \"{0}\"'", ".", "format", "(", "exception", ")", "return", "ret", "else", ":", "ret", "[", "'message'", "]", "=", "'Rollback succesfull but pre-commit check failed.'", "ret", "[", "'out'", "]", "=", "False", "return", "ret" ]
Returns capabilities data for stand alone imagery and includes URIs for the images .
def stand_alone_imagery ( self ) : return json . loads ( self . _query ( IMAGE , FORECAST , SURFACE_PRESSURE , CAPABILITIES , "" ) . decode ( errors = "replace" ) )
5,811
https://github.com/sludgedesk/metoffer/blob/449748d31f913d961d6f0406542bb784e931a95b/metoffer.py#L288-L293
[ "def", "run", "(", "self", ")", ":", "self", ".", "run_plugins", "(", ")", "while", "True", ":", "# Reload plugins and config if either the config file or plugin", "# directory are modified.", "if", "self", ".", "_config_mod_time", "!=", "os", ".", "path", ".", "getmtime", "(", "self", ".", "_config_file_path", ")", "or", "self", ".", "_plugin_mod_time", "!=", "os", ".", "path", ".", "getmtime", "(", "self", ".", "_plugin_path", ")", ":", "self", ".", "thread_manager", ".", "kill_all_threads", "(", ")", "self", ".", "output_dict", ".", "clear", "(", ")", "self", ".", "reload", "(", ")", "self", ".", "run_plugins", "(", ")", "self", ".", "output_to_bar", "(", "json", ".", "dumps", "(", "self", ".", "_remove_empty_output", "(", ")", ")", ")", "time", ".", "sleep", "(", "self", ".", "config", ".", "general", "[", "'interval'", "]", ")" ]
Returns capabilities data for forecast map overlays .
def map_overlay_forecast ( self ) : return json . loads ( self . _query ( LAYER , FORECAST , ALL , CAPABILITIES , "" ) . decode ( errors = "replace" ) )
5,812
https://github.com/sludgedesk/metoffer/blob/449748d31f913d961d6f0406542bb784e931a95b/metoffer.py#L295-L297
[ "def", "close", "(", "self", ")", ":", "if", "self", ".", "_access", "is", "not", "None", ":", "_logger", ".", "debug", "(", "\"Cleaning up\"", ")", "pci_cleanup", "(", "self", ".", "_access", ")", "self", ".", "_access", "=", "None" ]
Returns capabilities data for observation map overlays .
def map_overlay_obs ( self ) : return json . loads ( self . _query ( LAYER , OBSERVATIONS , ALL , CAPABILITIES , "" ) . decode ( errors = "replace" ) )
5,813
https://github.com/sludgedesk/metoffer/blob/449748d31f913d961d6f0406542bb784e931a95b/metoffer.py#L299-L301
[ "def", "auth_required", "(", "validator", ")", ":", "def", "_auth_required_decorator", "(", "handler", ")", ":", "if", "inspect", ".", "isclass", "(", "handler", ")", ":", "return", "_wrap_class", "(", "handler", ",", "validator", ")", "return", "_auth_required", "(", "handler", ",", "validator", ")", "return", "_auth_required_decorator" ]
load instrument from instrument_dict and append to instruments
def load_and_append ( instrument_dict , instruments = None , raise_errors = False ) : if instruments is None : instruments = { } updated_instruments = { } updated_instruments . update ( instruments ) loaded_failed = { } for instrument_name , instrument_class_name in instrument_dict . items ( ) : instrument_settings = None module = None # check if instrument already exists if instrument_name in list ( instruments . keys ( ) ) and instrument_class_name == instruments [ instrument_name ] . __name__ : print ( ( 'WARNING: instrument {:s} already exists. Did not load!' . format ( instrument_name ) ) ) loaded_failed [ instrument_name ] = instrument_name else : instrument_instance = None if isinstance ( instrument_class_name , dict ) : if 'settings' in instrument_class_name : instrument_settings = instrument_class_name [ 'settings' ] instrument_filepath = str ( instrument_class_name [ 'filepath' ] ) instrument_class_name = str ( instrument_class_name [ 'class' ] ) path_to_module , _ = module_name_from_path ( instrument_filepath ) module = import_module ( path_to_module ) class_of_instrument = getattr ( module , instrument_class_name ) try : if instrument_settings is None : # this creates an instance of the class with default settings instrument_instance = class_of_instrument ( name = instrument_name ) else : # this creates an instance of the class with custom settings instrument_instance = class_of_instrument ( name = instrument_name , settings = instrument_settings ) except Exception as e : loaded_failed [ instrument_name ] = e if raise_errors : raise e continue elif isinstance ( instrument_class_name , Instrument ) : instrument_class_name = instrument_class_name . __class__ instrument_filepath = os . path . dirname ( inspect . getfile ( instrument_class_name ) ) # here we should also create an instrument instance at some point as in the other cases... # instrument_instance = raise NotImplementedError elif issubclass ( instrument_class_name , Instrument ) : class_of_instrument = instrument_class_name if instrument_settings is None : # this creates an instance of the class with default settings instrument_instance = class_of_instrument ( name = instrument_name ) else : # this creates an instance of the class with custom settings instrument_instance = class_of_instrument ( name = instrument_name , settings = instrument_settings ) updated_instruments [ instrument_name ] = instrument_instance return updated_instruments , loaded_failed
5,814
https://github.com/LISE-B26/pylabcontrol/blob/67482e5157fcd1c40705e5c2cacfb93564703ed0/build/lib/pylabcontrol/src/core/instruments.py#L244-L349
[ "def", "calc_weighted_event_var", "(", "self", ",", "D", ",", "weights", ",", "event_pat", ")", ":", "Dz", "=", "stats", ".", "zscore", "(", "D", ",", "axis", "=", "1", ",", "ddof", "=", "1", ")", "ev_var", "=", "np", ".", "empty", "(", "event_pat", ".", "shape", "[", "1", "]", ")", "for", "e", "in", "range", "(", "event_pat", ".", "shape", "[", "1", "]", ")", ":", "# Only compute variances for weights > 0.1% of max weight", "nz", "=", "weights", "[", ":", ",", "e", "]", ">", "np", ".", "max", "(", "weights", "[", ":", ",", "e", "]", ")", "/", "1000", "sumsq", "=", "np", ".", "dot", "(", "weights", "[", "nz", ",", "e", "]", ",", "np", ".", "sum", "(", "np", ".", "square", "(", "Dz", "[", "nz", ",", ":", "]", "-", "event_pat", "[", ":", ",", "e", "]", ")", ",", "axis", "=", "1", ")", ")", "ev_var", "[", "e", "]", "=", "sumsq", "/", "(", "np", ".", "sum", "(", "weights", "[", "nz", ",", "e", "]", ")", "-", "np", ".", "sum", "(", "np", ".", "square", "(", "weights", "[", "nz", ",", "e", "]", ")", ")", "/", "np", ".", "sum", "(", "weights", "[", "nz", ",", "e", "]", ")", ")", "ev_var", "=", "ev_var", "/", "D", ".", "shape", "[", "1", "]", "return", "ev_var" ]
Called when validation fails .
def fail ( self , reason , obj , pointer = None ) : pointer = pointer_join ( pointer ) err = ValidationError ( reason , obj , pointer ) if self . fail_fast : raise err else : self . errors . append ( err ) return err
5,815
https://github.com/johnnoone/json-spec/blob/f91981724cea0c366bd42a6670eb07bbe31c0e0c/src/jsonspec/validators/draft04.py#L654-L664
[ "def", "OnAdjustVolume", "(", "self", ",", "event", ")", ":", "self", ".", "volume", "=", "self", ".", "player", ".", "audio_get_volume", "(", ")", "if", "event", ".", "GetWheelRotation", "(", ")", "<", "0", ":", "self", ".", "volume", "=", "max", "(", "0", ",", "self", ".", "volume", "-", "10", ")", "elif", "event", ".", "GetWheelRotation", "(", ")", ">", "0", ":", "self", ".", "volume", "=", "min", "(", "200", ",", "self", ".", "volume", "+", "10", ")", "self", ".", "player", ".", "audio_set_volume", "(", "self", ".", "volume", ")" ]
Gets the locus of the sequence by running blastn
def get_locus ( sequences , kir = False , verbose = False , refdata = None , evalue = 10 ) : if not refdata : refdata = ReferenceData ( ) file_id = str ( randomid ( ) ) input_fasta = file_id + ".fasta" output_xml = file_id + ".xml" SeqIO . write ( sequences , input_fasta , "fasta" ) blastn_cline = NcbiblastnCommandline ( query = input_fasta , db = refdata . blastdb , evalue = evalue , outfmt = 5 , reward = 1 , penalty = - 3 , gapopen = 5 , gapextend = 2 , dust = 'yes' , out = output_xml ) stdout , stderr = blastn_cline ( ) blast_qresult = SearchIO . read ( output_xml , 'blast-xml' ) # Delete files cleanup ( file_id ) if len ( blast_qresult . hits ) == 0 : return '' loci = [ ] for i in range ( 0 , 3 ) : if kir : loci . append ( blast_qresult [ i ] . id . split ( "*" ) [ 0 ] ) else : loci . append ( blast_qresult [ i ] . id . split ( "*" ) [ 0 ] ) locus = set ( loci ) if len ( locus ) == 1 : if has_hla ( loci [ 0 ] ) or kir : return loci [ 0 ] else : return "HLA-" + loci [ 0 ] else : return ''
5,816
https://github.com/nmdp-bioinformatics/SeqAnn/blob/5ce91559b0a4fbe4fb7758e034eb258202632463/seqann/blast_cmd.py#L187-L245
[ "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" ]
generate an address from pubkey
def address ( self ) -> str : return str ( self . _public_key . to_address ( net_query ( self . network ) ) )
5,817
https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/kutil.py#L51-L56
[ "def", "session", "(", "self", ")", ":", "if", "self", ".", "_session", "is", "None", ":", "self", ".", "_session", "=", "cachecontrol", ".", "CacheControl", "(", "requests", ".", "Session", "(", ")", ",", "cache", "=", "caches", ".", "FileCache", "(", "'.tvdb_cache'", ")", ")", "return", "self", ".", "_session" ]
sign the parent txn outputs P2PKH
def sign_transaction ( self , txins : Union [ TxOut ] , tx : MutableTransaction ) -> MutableTransaction : solver = P2pkhSolver ( self . _private_key ) return tx . spend ( txins , [ solver for i in txins ] )
5,818
https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/kutil.py#L64-L69
[ "def", "__audit_connections", "(", "self", ",", "ccallbacks", ")", ":", "while", "self", ".", "__quit_ev", ".", "is_set", "(", ")", "is", "False", ":", "# Remove any connections that are dead.", "self", ".", "__connections", "=", "filter", "(", "lambda", "(", "n", ",", "c", ",", "g", ")", ":", "not", "g", ".", "ready", "(", ")", ",", "self", ".", "__connections", ")", "connected_node_couplets_s", "=", "set", "(", "[", "(", "c", ".", "managed_connection", ".", "context", ",", "node", ")", "for", "(", "node", ",", "c", ",", "g", ")", "in", "self", ".", "__connections", "]", ")", "# Warn if there are any still-active connections that are no longer ", "# being advertised (probably where we were given some lookup servers ", "# that have dropped this particular *nsqd* server).", "lingering_nodes_s", "=", "connected_node_couplets_s", "-", "self", ".", "__node_couplets_s", "if", "lingering_nodes_s", ":", "_logger", ".", "warning", "(", "\"Server(s) are connected but no longer \"", "\"advertised: %s\"", ",", "lingering_nodes_s", ")", "# Connect any servers that don't currently have a connection.", "unused_nodes_s", "=", "self", ".", "__node_couplets_s", "-", "connected_node_couplets_s", "for", "(", "context", ",", "node", ")", "in", "unused_nodes_s", ":", "_logger", ".", "info", "(", "\"Trying to connect unconnected server: \"", "\"CONTEXT=[%s] NODE=[%s]\"", ",", "context", ",", "node", ")", "self", ".", "__start_connection", "(", "context", ",", "node", ",", "ccallbacks", ")", "else", ":", "# Are there both no unused servers and no connected servers?", "if", "not", "connected_node_couplets_s", ":", "_logger", ".", "error", "(", "\"All servers have gone away. Stopping \"", "\"client.\"", ")", "# Clear our list of servers, and squash the \"no servers!\" ", "# error so that we can shut things down in the right order.", "try", ":", "self", ".", "set_servers", "(", "[", "]", ")", "except", "EnvironmentError", ":", "pass", "self", ".", "__quit_ev", ".", "set", "(", ")", "return", "interval_s", "=", "nsq", ".", "config", ".", "client", ".", "GRANULAR_CONNECTION_AUDIT_SLEEP_STEP_TIME_S", "audit_wait_s", "=", "float", "(", "nsq", ".", "config", ".", "client", ".", "CONNECTION_AUDIT_WAIT_S", ")", "while", "audit_wait_s", ">", "0", "and", "self", ".", "__quit_ev", ".", "is_set", "(", ")", "is", "False", ":", "gevent", ".", "sleep", "(", "interval_s", ")", "audit_wait_s", "-=", "interval_s" ]
take care of specifics of cryptoid naming system
def format_name ( net : str ) -> str : if net . startswith ( 't' ) or 'testnet' in net : net = net [ 1 : ] + '-test' else : net = net return net
5,819
https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/provider/cryptoid.py#L33-L41
[ "def", "convert", "(", "self", ")", ":", "(", "width", ",", "height", ")", "=", "self", ".", "img", ".", "size", "bgcolor", "=", "utils", ".", "term", ".", "bgcolor", "self", ".", "img", ".", "load", "(", ")", "for", "y", "in", "range", "(", "height", ")", ":", "for", "x", "in", "range", "(", "width", ")", ":", "rgba", "=", "self", ".", "img", ".", "getpixel", "(", "(", "x", ",", "y", ")", ")", "if", "len", "(", "rgba", ")", "==", "4", "and", "rgba", "[", "3", "]", "==", "0", ":", "yield", "None", "elif", "len", "(", "rgba", ")", "==", "3", "or", "rgba", "[", "3", "]", "==", "255", ":", "yield", "xterm256", ".", "rgb_to_xterm", "(", "*", "rgba", "[", ":", "3", "]", ")", "else", ":", "color", "=", "grapefruit", ".", "Color", ".", "NewFromRgb", "(", "*", "[", "c", "/", "255.0", "for", "c", "in", "rgba", "]", ")", "rgba", "=", "grapefruit", ".", "Color", ".", "AlphaBlend", "(", "color", ",", "bgcolor", ")", ".", "rgb", "yield", "xterm256", ".", "rgb_to_xterm", "(", "*", "[", "int", "(", "c", "*", "255.0", ")", "for", "c", "in", "rgba", "]", ")", "yield", "\"EOL\"" ]
Perform a GET request for the url and return a dictionary parsed from the JSON response .
def get_url ( url : str ) -> Union [ dict , int , float , str ] : request = Request ( url , headers = { "User-Agent" : "pypeerassets" } ) response = cast ( HTTPResponse , urlopen ( request ) ) if response . status != 200 : raise Exception ( response . reason ) return json . loads ( response . read ( ) . decode ( ) )
5,820
https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/provider/cryptoid.py#L44-L52
[ "def", "delete_flag", "(", "self", ")", ":", "self", ".", "__status", "=", "Flag", ".", "NotFlagged", "self", ".", "__start", "=", "None", "self", ".", "__due_date", "=", "None", "self", ".", "__completed", "=", "None", "self", ".", "_track_changes", "(", ")" ]
Loop through all nodes of a single scope level .
def _scan_nodes ( nodelist , context , instance_types , current_block = None , ignore_blocks = None ) : results = [ ] for node in nodelist : # first check if this is the object instance to look for. if isinstance ( node , instance_types ) : results . append ( node ) # if it's a Constant Include Node ({% include "template_name.html" %}) # scan the child template elif isinstance ( node , IncludeNode ) : # if there's an error in the to-be-included template, node.template becomes None if node . template : # This is required for Django 1.7 but works on older version too # Check if it quacks like a template object, if not # presume is a template path and get the object out of it if not callable ( getattr ( node . template , 'render' , None ) ) : template = get_template ( node . template . var ) else : template = node . template if TemplateAdapter is not None and isinstance ( template , TemplateAdapter ) : # Django 1.8: received a new object, take original template template = template . template results += _scan_nodes ( template . nodelist , context , instance_types , current_block ) # handle {% extends ... %} tags elif isinstance ( node , ExtendsNode ) : results += _extend_nodelist ( node , context , instance_types ) # in block nodes we have to scan for super blocks elif isinstance ( node , VariableNode ) and current_block : if node . filter_expression . token == 'block.super' : # Found a {{ block.super }} line if not hasattr ( current_block . parent , 'nodelist' ) : raise TemplateSyntaxError ( "Cannot read {{{{ block.super }}}} for {{% block {0} %}}, " "the parent template doesn't have this block." . format ( current_block . name ) ) results += _scan_nodes ( current_block . parent . nodelist , context , instance_types , current_block . parent ) # ignore nested blocks which are already handled elif isinstance ( node , BlockNode ) and ignore_blocks and node . name in ignore_blocks : continue # if the node has the newly introduced 'child_nodelists' attribute, scan # those attributes for nodelists and recurse them elif hasattr ( node , 'child_nodelists' ) : for nodelist_name in node . child_nodelists : if hasattr ( node , nodelist_name ) : subnodelist = getattr ( node , nodelist_name ) if isinstance ( subnodelist , NodeList ) : if isinstance ( node , BlockNode ) : current_block = node results += _scan_nodes ( subnodelist , context , instance_types , current_block ) # else just scan the node for nodelist instance attributes else : for attr in dir ( node ) : obj = getattr ( node , attr ) if isinstance ( obj , NodeList ) : if isinstance ( node , BlockNode ) : current_block = node results += _scan_nodes ( obj , context , instance_types , current_block ) return results
5,821
https://github.com/edoburu/django-template-analyzer/blob/912916dadf68e5fb6bd3dbaa8e5dcad69d3086d0/template_analyzer/djangoanalyzer.py#L125-L191
[ "def", "generate_http_manifest", "(", "self", ")", ":", "base_path", "=", "os", ".", "path", ".", "dirname", "(", "self", ".", "translate_path", "(", "self", ".", "path", ")", ")", "self", ".", "dataset", "=", "dtoolcore", ".", "DataSet", ".", "from_uri", "(", "base_path", ")", "admin_metadata_fpath", "=", "os", ".", "path", ".", "join", "(", "base_path", ",", "\".dtool\"", ",", "\"dtool\"", ")", "with", "open", "(", "admin_metadata_fpath", ")", "as", "fh", ":", "admin_metadata", "=", "json", ".", "load", "(", "fh", ")", "http_manifest", "=", "{", "\"admin_metadata\"", ":", "admin_metadata", ",", "\"manifest_url\"", ":", "self", ".", "generate_url", "(", "\".dtool/manifest.json\"", ")", ",", "\"readme_url\"", ":", "self", ".", "generate_url", "(", "\"README.yml\"", ")", ",", "\"overlays\"", ":", "self", ".", "generate_overlay_urls", "(", ")", ",", "\"item_urls\"", ":", "self", ".", "generate_item_urls", "(", ")", "}", "return", "bytes", "(", "json", ".", "dumps", "(", "http_manifest", ")", ",", "\"utf-8\"", ")" ]
Find the nodes of a given instance .
def get_node_instances ( nodelist , instances ) : context = _get_main_context ( nodelist ) # The Django 1.8 loader returns an adapter class; it wraps the original Template in a new object to be API compatible if TemplateAdapter is not None and isinstance ( nodelist , TemplateAdapter ) : nodelist = nodelist . template return _scan_nodes ( nodelist , context , instances )
5,822
https://github.com/edoburu/django-template-analyzer/blob/912916dadf68e5fb6bd3dbaa8e5dcad69d3086d0/template_analyzer/djangoanalyzer.py#L224-L243
[ "def", "Run", "(", "self", ")", ":", "self", ".", "_GetArgs", "(", ")", "goodlogging", ".", "Log", ".", "Info", "(", "\"CLEAR\"", ",", "\"Using database: {0}\"", ".", "format", "(", "self", ".", "_databasePath", ")", ")", "self", ".", "_db", "=", "database", ".", "RenamerDB", "(", "self", ".", "_databasePath", ")", "if", "self", ".", "_dbPrint", "or", "self", ".", "_dbUpdate", ":", "goodlogging", ".", "Log", ".", "Seperator", "(", ")", "self", ".", "_db", ".", "PrintAllTables", "(", ")", "if", "self", ".", "_dbUpdate", ":", "goodlogging", ".", "Log", ".", "Seperator", "(", ")", "self", ".", "_db", ".", "ManualUpdateTables", "(", ")", "self", ".", "_GetDatabaseConfig", "(", ")", "if", "self", ".", "_enableExtract", ":", "goodlogging", ".", "Log", ".", "Seperator", "(", ")", "extractFileList", "=", "[", "]", "goodlogging", ".", "Log", ".", "Info", "(", "\"CLEAR\"", ",", "\"Parsing source directory for compressed files\"", ")", "goodlogging", ".", "Log", ".", "IncreaseIndent", "(", ")", "extract", ".", "GetCompressedFilesInDir", "(", "self", ".", "_sourceDir", ",", "extractFileList", ",", "self", ".", "_ignoredDirsList", ")", "goodlogging", ".", "Log", ".", "DecreaseIndent", "(", ")", "goodlogging", ".", "Log", ".", "Seperator", "(", ")", "extract", ".", "Extract", "(", "extractFileList", ",", "self", ".", "_supportedFormatsList", ",", "self", ".", "_archiveDir", ",", "self", ".", "_skipUserInputExtract", ")", "goodlogging", ".", "Log", ".", "Seperator", "(", ")", "tvFileList", "=", "[", "]", "goodlogging", ".", "Log", ".", "Info", "(", "\"CLEAR\"", ",", "\"Parsing source directory for compatible files\"", ")", "goodlogging", ".", "Log", ".", "IncreaseIndent", "(", ")", "self", ".", "_GetSupportedFilesInDir", "(", "self", ".", "_sourceDir", ",", "tvFileList", ",", "self", ".", "_supportedFormatsList", ",", "self", ".", "_ignoredDirsList", ")", "goodlogging", ".", "Log", ".", "DecreaseIndent", "(", ")", "tvRenamer", "=", "renamer", ".", "TVRenamer", "(", "self", ".", "_db", ",", "tvFileList", ",", "self", ".", "_archiveDir", ",", "guideName", "=", "'EPGUIDES'", ",", "tvDir", "=", "self", ".", "_tvDir", ",", "inPlaceRename", "=", "self", ".", "_inPlaceRename", ",", "forceCopy", "=", "self", ".", "_crossSystemCopyEnabled", ",", "skipUserInput", "=", "self", ".", "_skipUserInputRename", ")", "tvRenamer", ".", "Run", "(", ")" ]
Get model configuration file name from argv
def get_config_file ( ) : # type: () -> AnyStr parser = argparse . ArgumentParser ( description = "Read configuration file." ) parser . add_argument ( '-ini' , help = "Full path of configuration file" ) args = parser . parse_args ( ) ini_file = args . ini if not FileClass . is_file_exists ( ini_file ) : print ( "Usage: -ini <full path to the configuration file.>" ) exit ( - 1 ) return ini_file
5,823
https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/utils.py#L1013-L1023
[ "def", "local_regon_checksum", "(", "digits", ")", ":", "weights_for_check_digit", "=", "[", "2", ",", "4", ",", "8", ",", "5", ",", "0", ",", "9", ",", "7", ",", "3", ",", "6", ",", "1", ",", "2", ",", "4", ",", "8", "]", "check_digit", "=", "0", "for", "i", "in", "range", "(", "0", ",", "13", ")", ":", "check_digit", "+=", "weights_for_check_digit", "[", "i", "]", "*", "digits", "[", "i", "]", "check_digit", "%=", "11", "if", "check_digit", "==", "10", ":", "check_digit", "=", "0", "return", "check_digit" ]
Check the input x is numerical or not .
def isnumerical ( x ) : # type: (...) -> bool try : xx = float ( x ) except TypeError : return False except ValueError : return False except Exception : return False else : return True
5,824
https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/utils.py#L111-L139
[ "def", "_remove_vm", "(", "name", ",", "datacenter", ",", "service_instance", ",", "placement", "=", "None", ",", "power_off", "=", "None", ")", ":", "results", "=", "{", "}", "if", "placement", ":", "(", "resourcepool_object", ",", "placement_object", ")", "=", "salt", ".", "utils", ".", "vmware", ".", "get_placement", "(", "service_instance", ",", "datacenter", ",", "placement", ")", "else", ":", "placement_object", "=", "salt", ".", "utils", ".", "vmware", ".", "get_datacenter", "(", "service_instance", ",", "datacenter", ")", "if", "power_off", ":", "power_off_vm", "(", "name", ",", "datacenter", ",", "service_instance", ")", "results", "[", "'powered_off'", "]", "=", "True", "vm_ref", "=", "salt", ".", "utils", ".", "vmware", ".", "get_mor_by_property", "(", "service_instance", ",", "vim", ".", "VirtualMachine", ",", "name", ",", "property_name", "=", "'name'", ",", "container_ref", "=", "placement_object", ")", "if", "not", "vm_ref", ":", "raise", "salt", ".", "exceptions", ".", "VMwareObjectRetrievalError", "(", "'The virtual machine object {0} in datacenter '", "'{1} was not found'", ".", "format", "(", "name", ",", "datacenter", ")", ")", "return", "results", ",", "vm_ref" ]
Calculate Coefficient of determination .
def rsquare ( obsvalues , # type: Union[numpy.ndarray, List[Union[float, int]]] simvalues # type: Union[numpy.ndarray, List[Union[float, int]]] ) : # type: (...) -> Union[float, numpy.ScalarType] if len ( obsvalues ) != len ( simvalues ) : raise ValueError ( "The size of observed and simulated values must be " "the same for R-square calculation!" ) if not isinstance ( obsvalues , numpy . ndarray ) : obsvalues = numpy . array ( obsvalues ) if not isinstance ( simvalues , numpy . ndarray ) : simvalues = numpy . array ( simvalues ) obs_avg = numpy . mean ( obsvalues ) pred_avg = numpy . mean ( simvalues ) obs_minus_avg_sq = numpy . sum ( ( obsvalues - obs_avg ) ** 2 ) pred_minus_avg_sq = numpy . sum ( ( simvalues - pred_avg ) ** 2 ) obs_pred_minus_avgs = numpy . sum ( ( obsvalues - obs_avg ) * ( simvalues - pred_avg ) ) # Calculate R-square yy = obs_minus_avg_sq ** 0.5 * pred_minus_avg_sq ** 0.5 if MathClass . floatequal ( yy , 0. ) : return 1. return ( obs_pred_minus_avgs / yy ) ** 2.
5,825
https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/utils.py#L240-L284
[ "def", "register_keepalive", "(", "self", ",", "cmd", ",", "callback", ")", ":", "regid", "=", "random", ".", "random", "(", ")", "if", "self", ".", "_customkeepalives", "is", "None", ":", "self", ".", "_customkeepalives", "=", "{", "regid", ":", "(", "cmd", ",", "callback", ")", "}", "else", ":", "while", "regid", "in", "self", ".", "_customkeepalives", ":", "regid", "=", "random", ".", "random", "(", ")", "self", ".", "_customkeepalives", "[", "regid", "]", "=", "(", "cmd", ",", "callback", ")", "return", "regid" ]
Calculate RMSE .
def rmse ( obsvalues , # type: Union[numpy.ndarray, List[Union[float, int]]] simvalues # type: Union[numpy.ndarray, List[Union[float, int]]] ) : # type: (...) -> Union[float, numpy.ScalarType] if len ( obsvalues ) != len ( simvalues ) : raise ValueError ( "The size of observed and simulated values must be " "the same for R-square calculation!" ) if not isinstance ( obsvalues , numpy . ndarray ) : obsvalues = numpy . array ( obsvalues ) if not isinstance ( simvalues , numpy . ndarray ) : simvalues = numpy . array ( simvalues ) return numpy . sqrt ( numpy . mean ( ( obsvalues - simvalues ) ** 2. ) )
5,826
https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/utils.py#L287-L315
[ "def", "to_mapping", "(", "self", ",", "*", "*", "values", ")", ":", "strike", ",", "dip", ",", "rake", "=", "self", ".", "strike_dip_rake", "(", ")", "min", ",", "max", "=", "self", ".", "angular_errors", "(", ")", "try", ":", "disabled", "=", "self", ".", "disabled", "except", "AttributeError", ":", "disabled", "=", "False", "mapping", "=", "dict", "(", "uid", "=", "self", ".", "hash", ",", "axes", "=", "self", ".", "axes", ".", "tolist", "(", ")", ",", "hyperbolic_axes", "=", "self", ".", "hyperbolic_axes", ".", "tolist", "(", ")", ",", "max_angular_error", "=", "max", ",", "min_angular_error", "=", "min", ",", "strike", "=", "strike", ",", "dip", "=", "dip", ",", "rake", "=", "rake", ",", "disabled", "=", "disabled", ")", "# Add in user-provided-values, overwriting if", "# necessary", "for", "k", ",", "v", "in", "values", ".", "items", "(", ")", ":", "mapping", "[", "k", "]", "=", "v", "return", "mapping" ]
Calculate PBIAS or percent model bias .
def pbias ( obsvalues , # type: Union[numpy.ndarray, List[Union[float, int]]] simvalues # type: Union[numpy.ndarray, List[Union[float, int]]] ) : # type: (...) -> Union[float, numpy.ScalarType] if len ( obsvalues ) != len ( simvalues ) : raise ValueError ( "The size of observed and simulated values must be" " the same for PBIAS calculation!" ) return sum ( map ( lambda x , y : ( x - y ) * 100 , obsvalues , simvalues ) ) / sum ( obsvalues )
5,827
https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/utils.py#L318-L342
[ "def", "Run", "(", "self", ")", ":", "self", ".", "_GetArgs", "(", ")", "goodlogging", ".", "Log", ".", "Info", "(", "\"CLEAR\"", ",", "\"Using database: {0}\"", ".", "format", "(", "self", ".", "_databasePath", ")", ")", "self", ".", "_db", "=", "database", ".", "RenamerDB", "(", "self", ".", "_databasePath", ")", "if", "self", ".", "_dbPrint", "or", "self", ".", "_dbUpdate", ":", "goodlogging", ".", "Log", ".", "Seperator", "(", ")", "self", ".", "_db", ".", "PrintAllTables", "(", ")", "if", "self", ".", "_dbUpdate", ":", "goodlogging", ".", "Log", ".", "Seperator", "(", ")", "self", ".", "_db", ".", "ManualUpdateTables", "(", ")", "self", ".", "_GetDatabaseConfig", "(", ")", "if", "self", ".", "_enableExtract", ":", "goodlogging", ".", "Log", ".", "Seperator", "(", ")", "extractFileList", "=", "[", "]", "goodlogging", ".", "Log", ".", "Info", "(", "\"CLEAR\"", ",", "\"Parsing source directory for compressed files\"", ")", "goodlogging", ".", "Log", ".", "IncreaseIndent", "(", ")", "extract", ".", "GetCompressedFilesInDir", "(", "self", ".", "_sourceDir", ",", "extractFileList", ",", "self", ".", "_ignoredDirsList", ")", "goodlogging", ".", "Log", ".", "DecreaseIndent", "(", ")", "goodlogging", ".", "Log", ".", "Seperator", "(", ")", "extract", ".", "Extract", "(", "extractFileList", ",", "self", ".", "_supportedFormatsList", ",", "self", ".", "_archiveDir", ",", "self", ".", "_skipUserInputExtract", ")", "goodlogging", ".", "Log", ".", "Seperator", "(", ")", "tvFileList", "=", "[", "]", "goodlogging", ".", "Log", ".", "Info", "(", "\"CLEAR\"", ",", "\"Parsing source directory for compatible files\"", ")", "goodlogging", ".", "Log", ".", "IncreaseIndent", "(", ")", "self", ".", "_GetSupportedFilesInDir", "(", "self", ".", "_sourceDir", ",", "tvFileList", ",", "self", ".", "_supportedFormatsList", ",", "self", ".", "_ignoredDirsList", ")", "goodlogging", ".", "Log", ".", "DecreaseIndent", "(", ")", "tvRenamer", "=", "renamer", ".", "TVRenamer", "(", "self", ".", "_db", ",", "tvFileList", ",", "self", ".", "_archiveDir", ",", "guideName", "=", "'EPGUIDES'", ",", "tvDir", "=", "self", ".", "_tvDir", ",", "inPlaceRename", "=", "self", ".", "_inPlaceRename", ",", "forceCopy", "=", "self", ".", "_crossSystemCopyEnabled", ",", "skipUserInput", "=", "self", ".", "_skipUserInputRename", ")", "tvRenamer", ".", "Run", "(", ")" ]
Convert string to string integer or float . Support tuple or list .
def convert_str2num ( unicode_str # type: Union[AnyStr, int, float, List[Union[AnyStr, float, int]], Tuple[Union[AnyStr, float, int]]] ) : # type: (...) -> Union[AnyStr, int, float, List[Union[AnyStr, float, int]], Tuple[Union[AnyStr, float, int]]] if MathClass . isnumerical ( unicode_str ) : unicode_str = float ( unicode_str ) if unicode_str % 1. == 0. : unicode_str = int ( unicode_str ) return unicode_str elif is_string ( unicode_str ) : return str ( unicode_str ) elif isinstance ( unicode_str , tuple ) : return tuple ( StringClass . convert_str2num ( v ) for v in unicode_str ) elif isinstance ( unicode_str , list ) : return list ( StringClass . convert_str2num ( v ) for v in unicode_str ) else : return unicode_str
5,828
https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/utils.py#L387-L418
[ "def", "_compute_ogg_page_crc", "(", "page", ")", ":", "page_zero_crc", "=", "page", "[", ":", "OGG_FIRST_PAGE_HEADER_CRC_OFFSET", "]", "+", "b\"\\00\"", "*", "OGG_FIRST_PAGE_HEADER_CRC", ".", "size", "+", "page", "[", "OGG_FIRST_PAGE_HEADER_CRC_OFFSET", "+", "OGG_FIRST_PAGE_HEADER_CRC", ".", "size", ":", "]", "return", "ogg_page_crc", "(", "page_zero_crc", ")" ]
Is tmp_str in strlist case insensitive .
def string_in_list ( tmp_str , strlist ) : # type: (AnyStr, List[AnyStr]) -> bool new_str_list = strlist [ : ] for i , str_in_list in enumerate ( new_str_list ) : new_str_list [ i ] = str_in_list . lower ( ) return tmp_str . lower ( ) in new_str_list
5,829
https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/utils.py#L475-L481
[ "def", "get_physical_page_for_file", "(", "self", ",", "ocrd_file", ")", ":", "ret", "=", "self", ".", "_tree", ".", "getroot", "(", ")", ".", "xpath", "(", "'/mets:mets/mets:structMap[@TYPE=\"PHYSICAL\"]/mets:div[@TYPE=\"physSequence\"]/mets:div[@TYPE=\"page\"][./mets:fptr[@FILEID=\"%s\"]]/@ID'", "%", "ocrd_file", ".", "ID", ",", "namespaces", "=", "NS", ")", "if", "ret", ":", "return", "ret", "[", "0", "]" ]
Check the existence of file path .
def is_file_exists ( filename ) : # type: (AnyStr) -> bool if filename is None or not os . path . exists ( filename ) or not os . path . isfile ( filename ) : return False else : return True
5,830
https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/utils.py#L588-L594
[ "def", "register_dataframe_method", "(", "method", ")", ":", "def", "inner", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "class", "AccessorMethod", "(", "object", ")", ":", "def", "__init__", "(", "self", ",", "pandas_obj", ")", ":", "self", ".", "_obj", "=", "pandas_obj", "@", "wraps", "(", "method", ")", "def", "__call__", "(", "self", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "method", "(", "self", ".", "_obj", ",", "*", "args", ",", "*", "*", "kwargs", ")", "register_dataframe_accessor", "(", "method", ".", "__name__", ")", "(", "AccessorMethod", ")", "return", "method", "return", "inner", "(", ")" ]
Check the existence of folder path .
def is_dir_exists ( dirpath ) : # type: (AnyStr) -> bool if dirpath is None or not os . path . exists ( dirpath ) or not os . path . isdir ( dirpath ) : return False else : return True
5,831
https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/utils.py#L597-L603
[ "def", "_rows_event_to_dict", "(", "e", ",", "stream", ")", ":", "pk_cols", "=", "e", ".", "primary_key", "if", "isinstance", "(", "e", ".", "primary_key", ",", "(", "list", ",", "tuple", ")", ")", "else", "(", "e", ".", "primary_key", ",", ")", "if", "isinstance", "(", "e", ",", "row_event", ".", "UpdateRowsEvent", ")", ":", "sig", "=", "signals", ".", "rows_updated", "action", "=", "'update'", "row_converter", "=", "_convert_update_row", "elif", "isinstance", "(", "e", ",", "row_event", ".", "WriteRowsEvent", ")", ":", "sig", "=", "signals", ".", "rows_inserted", "action", "=", "'insert'", "row_converter", "=", "_convert_write_row", "elif", "isinstance", "(", "e", ",", "row_event", ".", "DeleteRowsEvent", ")", ":", "sig", "=", "signals", ".", "rows_deleted", "action", "=", "'delete'", "row_converter", "=", "_convert_write_row", "else", ":", "assert", "False", ",", "'Invalid binlog event'", "meta", "=", "{", "'time'", ":", "e", ".", "timestamp", ",", "'log_pos'", ":", "stream", ".", "log_pos", ",", "'log_file'", ":", "stream", ".", "log_file", ",", "'schema'", ":", "e", ".", "schema", ",", "'table'", ":", "e", ".", "table", ",", "'action'", ":", "action", ",", "}", "rows", "=", "list", "(", "map", "(", "row_converter", ",", "e", ".", "rows", ")", ")", "for", "row", "in", "rows", ":", "row", "[", "'keys'", "]", "=", "{", "k", ":", "row", "[", "'values'", "]", "[", "k", "]", "for", "k", "in", "pk_cols", "}", "return", "rows", ",", "meta" ]
Copy files with the same name and different suffixes such as ESRI Shapefile .
def copy_files ( filename , dstfilename ) : # type: (AnyStr, AnyStr) -> None FileClass . remove_files ( dstfilename ) dst_prefix = os . path . splitext ( dstfilename ) [ 0 ] pattern = os . path . splitext ( filename ) [ 0 ] + '.*' for f in glob . iglob ( pattern ) : ext = os . path . splitext ( f ) [ 1 ] dst = dst_prefix + ext copy ( f , dst )
5,832
https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/utils.py#L613-L622
[ "def", "start", "(", "self", ")", ":", "t", "=", "threading", ".", "Thread", "(", "target", "=", "self", ".", "_consume", ")", "t", ".", "start", "(", ")" ]
Delete all files with same root as fileName i . e . regardless of suffix such as ESRI shapefile
def remove_files ( filename ) : # type: (AnyStr) -> None pattern = os . path . splitext ( filename ) [ 0 ] + '.*' for f in glob . iglob ( pattern ) : os . remove ( f )
5,833
https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/utils.py#L625-L633
[ "def", "group_barh", "(", "self", ",", "column_label", ",", "*", "*", "vargs", ")", ":", "self", ".", "group", "(", "column_label", ")", ".", "barh", "(", "column_label", ",", "*", "*", "vargs", ")" ]
Return true if outfile exists and is no older than base datetime .
def is_up_to_date ( outfile , basedatetime ) : # type: (AnyStr, datetime) -> bool if os . path . exists ( outfile ) : if os . path . getmtime ( outfile ) >= basedatetime : return True return False
5,834
https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/utils.py#L636-L642
[ "def", "get_hyperedge_weight_matrix", "(", "H", ",", "hyperedge_ids_to_indices", ")", ":", "# Combined 2 methods into 1; this could be written better", "hyperedge_weights", "=", "{", "}", "for", "hyperedge_id", "in", "H", ".", "hyperedge_id_iterator", "(", ")", ":", "hyperedge_weights", ".", "update", "(", "{", "hyperedge_ids_to_indices", "[", "hyperedge_id", "]", ":", "H", ".", "get_hyperedge_weight", "(", "hyperedge_id", ")", "}", ")", "hyperedge_weight_vector", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "hyperedge_weights", ".", "keys", "(", ")", ")", ")", ":", "hyperedge_weight_vector", ".", "append", "(", "hyperedge_weights", ".", "get", "(", "i", ")", ")", "return", "sparse", ".", "diags", "(", "[", "hyperedge_weight_vector", "]", ",", "[", "0", "]", ")" ]
get the full path of a given executable name
def get_executable_fullpath ( name , dirname = None ) : # type: (AnyStr, Optional[AnyStr]) -> Optional[AnyStr] if name is None : return None if is_string ( name ) : name = str ( name ) else : raise RuntimeError ( 'The input function name or path must be string!' ) if dirname is not None : # check the given path first dirname = os . path . abspath ( dirname ) fpth = dirname + os . sep + name if os . path . isfile ( fpth ) : return fpth # If dirname is not specified, check the env then. if sysstr == 'Windows' : findout = UtilClass . run_command ( 'where %s' % name ) else : findout = UtilClass . run_command ( 'which %s' % name ) if not findout or len ( findout ) == 0 : print ( "%s is not included in the env path" % name ) exit ( - 1 ) first_path = findout [ 0 ] . split ( '\n' ) [ 0 ] if os . path . exists ( first_path ) : return first_path return None
5,835
https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/utils.py#L645-L670
[ "def", "compare_values", "(", "values0", ",", "values1", ")", ":", "values0", "=", "{", "v", "[", "0", "]", ":", "v", "[", "1", ":", "]", "for", "v", "in", "values0", "}", "values1", "=", "{", "v", "[", "0", "]", ":", "v", "[", "1", ":", "]", "for", "v", "in", "values1", "}", "created", "=", "[", "(", "k", ",", "v", "[", "0", "]", ",", "v", "[", "1", "]", ")", "for", "k", ",", "v", "in", "values1", ".", "items", "(", ")", "if", "k", "not", "in", "values0", "]", "deleted", "=", "[", "(", "k", ",", "v", "[", "0", "]", ",", "v", "[", "1", "]", ")", "for", "k", ",", "v", "in", "values0", ".", "items", "(", ")", "if", "k", "not", "in", "values1", "]", "modified", "=", "[", "(", "k", ",", "v", "[", "0", "]", ",", "v", "[", "1", "]", ")", "for", "k", ",", "v", "in", "values0", ".", "items", "(", ")", "if", "v", "!=", "values1", ".", "get", "(", "k", ",", "None", ")", "]", "return", "created", ",", "deleted", ",", "modified" ]
Return full path if available .
def get_file_fullpath ( name , dirname = None ) : # type: (AnyStr, Optional[AnyStr]) -> Optional[AnyStr] if name is None : return None if is_string ( name ) : name = str ( name ) else : raise RuntimeError ( 'The input function name or path must be string!' ) for sep in [ '\\' , '/' , os . sep ] : # Loop all possible separators if sep in name : # name is full path already name = os . path . abspath ( name ) return name if dirname is not None : dirname = os . path . abspath ( dirname ) name = dirname + os . sep + name return name
5,836
https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/utils.py#L673-L689
[ "def", "_put_bucket_logging", "(", "self", ")", ":", "logging_config", "=", "{", "}", "if", "self", ".", "s3props", "[", "'logging'", "]", "[", "'enabled'", "]", ":", "logging_config", "=", "{", "'LoggingEnabled'", ":", "{", "'TargetBucket'", ":", "self", ".", "s3props", "[", "'logging'", "]", "[", "'logging_bucket'", "]", ",", "'TargetGrants'", ":", "self", ".", "s3props", "[", "'logging'", "]", "[", "'logging_grants'", "]", ",", "'TargetPrefix'", ":", "self", ".", "s3props", "[", "'logging'", "]", "[", "'logging_bucket_prefix'", "]", "}", "}", "_response", "=", "self", ".", "s3client", ".", "put_bucket_logging", "(", "Bucket", "=", "self", ".", "bucket", ",", "BucketLoggingStatus", "=", "logging_config", ")", "LOG", ".", "debug", "(", "'Response setting up S3 logging: %s'", ",", "_response", ")", "LOG", ".", "info", "(", "'S3 logging configuration updated'", ")" ]
get file names with the given suffixes in the given directory
def get_filename_by_suffixes ( dir_src , suffixes ) : # type: (AnyStr, Union[AnyStr, List[AnyStr]]) -> Optional[List[AnyStr]] list_files = os . listdir ( dir_src ) re_files = list ( ) if is_string ( suffixes ) : suffixes = [ suffixes ] if not isinstance ( suffixes , list ) : return None for i , suf in enumerate ( suffixes ) : if len ( suf ) >= 1 and suf [ 0 ] != '.' : suffixes [ i ] = '.' + suf for f in list_files : name , ext = os . path . splitext ( f ) if StringClass . string_in_list ( ext , suffixes ) : re_files . append ( f ) return re_files
5,837
https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/utils.py#L692-L716
[ "def", "decodeLength", "(", "length", ")", ":", "bytes_length", "=", "len", "(", "length", ")", "if", "bytes_length", "<", "2", ":", "offset", "=", "b'\\x00\\x00\\x00'", "XOR", "=", "0", "elif", "bytes_length", "<", "3", ":", "offset", "=", "b'\\x00\\x00'", "XOR", "=", "0x8000", "elif", "bytes_length", "<", "4", ":", "offset", "=", "b'\\x00'", "XOR", "=", "0xC00000", "elif", "bytes_length", "<", "5", ":", "offset", "=", "b''", "XOR", "=", "0xE0000000", "else", ":", "raise", "ConnectionError", "(", "'Unable to decode length of {}'", ".", "format", "(", "length", ")", ")", "decoded", "=", "unpack", "(", "'!I'", ",", "(", "offset", "+", "length", ")", ")", "[", "0", "]", "decoded", "^=", "XOR", "return", "decoded" ]
get full file names with the given suffixes in the given directory
def get_full_filename_by_suffixes ( dir_src , suffixes ) : # type: (AnyStr, Union[AnyStr, List[AnyStr]]) -> Optional[List[AnyStr]] file_names = FileClass . get_filename_by_suffixes ( dir_src , suffixes ) if file_names is None : return None return list ( dir_src + os . sep + name for name in file_names )
5,838
https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/utils.py#L719-L733
[ "def", "decodeLength", "(", "length", ")", ":", "bytes_length", "=", "len", "(", "length", ")", "if", "bytes_length", "<", "2", ":", "offset", "=", "b'\\x00\\x00\\x00'", "XOR", "=", "0", "elif", "bytes_length", "<", "3", ":", "offset", "=", "b'\\x00\\x00'", "XOR", "=", "0x8000", "elif", "bytes_length", "<", "4", ":", "offset", "=", "b'\\x00'", "XOR", "=", "0xC00000", "elif", "bytes_length", "<", "5", ":", "offset", "=", "b''", "XOR", "=", "0xE0000000", "else", ":", "raise", "ConnectionError", "(", "'Unable to decode length of {}'", ".", "format", "(", "length", ")", ")", "decoded", "=", "unpack", "(", "'!I'", ",", "(", "offset", "+", "length", ")", ")", "[", "0", "]", "decoded", "^=", "XOR", "return", "decoded" ]
Return core file name without suffix .
def get_core_name_without_suffix ( file_path ) : # type: (AnyStr) -> AnyStr if '\\' in file_path : file_path = file_path . replace ( '\\' , '/' ) file_name = os . path . basename ( file_path ) core_names = file_name . split ( '.' ) if len ( core_names ) > 1 : core_names = core_names [ : - 1 ] if isinstance ( core_names , list ) : return str ( '.' . join ( core_names ) ) else : return str ( core_names )
5,839
https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/utils.py#L736-L765
[ "def", "import_from_dict", "(", "session", ",", "data", ",", "sync", "=", "[", "]", ")", ":", "if", "isinstance", "(", "data", ",", "dict", ")", ":", "logging", ".", "info", "(", "'Importing %d %s'", ",", "len", "(", "data", ".", "get", "(", "DATABASES_KEY", ",", "[", "]", ")", ")", ",", "DATABASES_KEY", ")", "for", "database", "in", "data", ".", "get", "(", "DATABASES_KEY", ",", "[", "]", ")", ":", "Database", ".", "import_from_dict", "(", "session", ",", "database", ",", "sync", "=", "sync", ")", "logging", ".", "info", "(", "'Importing %d %s'", ",", "len", "(", "data", ".", "get", "(", "DRUID_CLUSTERS_KEY", ",", "[", "]", ")", ")", ",", "DRUID_CLUSTERS_KEY", ")", "for", "datasource", "in", "data", ".", "get", "(", "DRUID_CLUSTERS_KEY", ",", "[", "]", ")", ":", "DruidCluster", ".", "import_from_dict", "(", "session", ",", "datasource", ",", "sync", "=", "sync", ")", "session", ".", "commit", "(", ")", "else", ":", "logging", ".", "info", "(", "'Supplied object is not a dictionary.'", ")" ]
Add postfix for a full file path .
def add_postfix ( file_path , postfix ) : # type: (AnyStr, AnyStr) -> AnyStr cur_sep = '' for sep in [ '\\' , '/' , os . sep ] : if sep in file_path : cur_sep = sep break corename = FileClass . get_core_name_without_suffix ( file_path ) tmpspliter = os . path . basename ( file_path ) . split ( '.' ) suffix = '' if len ( tmpspliter ) > 1 : suffix = tmpspliter [ - 1 ] newname = os . path . dirname ( file_path ) + cur_sep + corename + '_' + postfix if suffix != '' : newname += '.' + suffix return str ( newname )
5,840
https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/utils.py#L768-L793
[ "def", "remove_stale_javascripts", "(", "portal", ")", ":", "logger", ".", "info", "(", "\"Removing stale javascripts ...\"", ")", "for", "js", "in", "JAVASCRIPTS_TO_REMOVE", ":", "logger", ".", "info", "(", "\"Unregistering JS %s\"", "%", "js", ")", "portal", ".", "portal_javascripts", ".", "unregisterResource", "(", "js", ")" ]
Day index of year from 1 to 365 or 366
def day_of_year ( dt ) : # type: (int) -> int sec = time . mktime ( dt . timetuple ( ) ) t = time . localtime ( sec ) return t . tm_yday
5,841
https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/utils.py#L834-L839
[ "def", "touch", "(", "self", ",", "message_id", ",", "reservation_id", ",", "timeout", "=", "None", ")", ":", "url", "=", "\"queues/%s/messages/%s/touch\"", "%", "(", "self", ".", "name", ",", "message_id", ")", "qitems", "=", "{", "'reservation_id'", ":", "reservation_id", "}", "if", "timeout", "is", "not", "None", ":", "qitems", "[", "'timeout'", "]", "=", "timeout", "body", "=", "json", ".", "dumps", "(", "qitems", ")", "response", "=", "self", ".", "client", ".", "post", "(", "url", ",", "body", "=", "body", ",", "headers", "=", "{", "'Content-Type'", ":", "'application/json'", "}", ")", "return", "response", "[", "'body'", "]" ]
Execute external command and return the output lines list . In windows refers to handling - subprocess - crash - in - windows _ .
def run_command ( commands ) : # type: (Union[AnyStr, List[AnyStr]]) -> List[AnyStr] # commands = StringClass.convert_unicode2str(commands) # print(commands) use_shell = False subprocess_flags = 0 startupinfo = None if sysstr == 'Windows' : if isinstance ( commands , list ) : commands = ' ' . join ( str ( c ) for c in commands ) import ctypes SEM_NOGPFAULTERRORBOX = 0x0002 # From MSDN ctypes . windll . kernel32 . SetErrorMode ( SEM_NOGPFAULTERRORBOX ) subprocess_flags = 0x8000000 # win32con.CREATE_NO_WINDOW? # this startupinfo structure prevents a console window from popping up on Windows startupinfo = subprocess . STARTUPINFO ( ) startupinfo . dwFlags |= subprocess . STARTF_USESHOWWINDOW # not sure if node outputs on stderr or stdout so capture both else : # for Linux/Unix OS, commands is better to be a list. if is_string ( commands ) : use_shell = True # https://docs.python.org/2/library/subprocess.html # Using shell=True can be a security hazard. elif isinstance ( commands , list ) : # the executable path may be enclosed with quotes, if not windows, delete the quotes if commands [ 0 ] [ 0 ] == commands [ 0 ] [ - 1 ] == '"' or commands [ 0 ] [ 0 ] == commands [ 0 ] [ - 1 ] == "'" : commands [ 0 ] = commands [ 0 ] [ 1 : - 1 ] for idx , v in enumerate ( commands ) : if isinstance ( v , int ) or isinstance ( v , float ) : # Fix :TypeError: execv() arg 2 must contain only strings commands [ idx ] = repr ( v ) print ( commands ) process = subprocess . Popen ( commands , shell = use_shell , stdout = subprocess . PIPE , stdin = open ( os . devnull ) , stderr = subprocess . STDOUT , universal_newlines = True , startupinfo = startupinfo , creationflags = subprocess_flags ) out , err = process . communicate ( ) recode = process . returncode if out is None : return [ '' ] if recode is not None and recode != 0 : raise subprocess . CalledProcessError ( - 1 , commands , "ERROR occurred when running subprocess!" ) if '\n' in out : return out . split ( '\n' ) return [ out ]
5,842
https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/utils.py#L850-L912
[ "def", "update_dataset", "(", "self", ",", "dataset", ",", "fields", ",", "retry", "=", "DEFAULT_RETRY", ")", ":", "partial", "=", "dataset", ".", "_build_resource", "(", "fields", ")", "if", "dataset", ".", "etag", "is", "not", "None", ":", "headers", "=", "{", "\"If-Match\"", ":", "dataset", ".", "etag", "}", "else", ":", "headers", "=", "None", "api_response", "=", "self", ".", "_call_api", "(", "retry", ",", "method", "=", "\"PATCH\"", ",", "path", "=", "dataset", ".", "path", ",", "data", "=", "partial", ",", "headers", "=", "headers", ")", "return", "Dataset", ".", "from_api_repr", "(", "api_response", ")" ]
Get current path refers to how - do - i - get - the - path - of - the - current - executed - file - in - python _
def current_path ( local_function ) : from inspect import getsourcefile fpath = getsourcefile ( local_function ) if fpath is None : return None return os . path . dirname ( os . path . abspath ( fpath ) )
5,843
https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/utils.py#L915-L932
[ "def", "_sendMessage", "(", "self", ",", "msg", ")", ":", "if", "not", "msg", ":", "return", "msg", "=", "self", ".", "_collapseMsg", "(", "msg", ")", "self", ".", "sendStatus", "(", "msg", ")" ]
Make directory if not existed
def mkdir ( dir_path ) : # type: (AnyStr) -> None if not os . path . isdir ( dir_path ) or not os . path . exists ( dir_path ) : os . makedirs ( dir_path )
5,844
https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/utils.py#L935-L939
[ "def", "getMirrorTextureD3D11", "(", "self", ",", "eEye", ",", "pD3D11DeviceOrResource", ")", ":", "fn", "=", "self", ".", "function_table", ".", "getMirrorTextureD3D11", "ppD3D11ShaderResourceView", "=", "c_void_p", "(", ")", "result", "=", "fn", "(", "eEye", ",", "pD3D11DeviceOrResource", ",", "byref", "(", "ppD3D11ShaderResourceView", ")", ")", "return", "result", ",", "ppD3D11ShaderResourceView", ".", "value" ]
If directory existed then remove and make ; else make it .
def rmmkdir ( dir_path ) : # type: (AnyStr) -> None if not os . path . isdir ( dir_path ) or not os . path . exists ( dir_path ) : os . makedirs ( dir_path ) else : rmtree ( dir_path , True ) os . makedirs ( dir_path )
5,845
https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/utils.py#L942-L949
[ "def", "_send_register_payload", "(", "self", ",", "websocket", ")", ":", "file", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "HANDSHAKE_FILE_NAME", ")", "data", "=", "codecs", ".", "open", "(", "file", ",", "'r'", ",", "'utf-8'", ")", "raw_handshake", "=", "data", ".", "read", "(", ")", "handshake", "=", "json", ".", "loads", "(", "raw_handshake", ")", "handshake", "[", "'payload'", "]", "[", "'client-key'", "]", "=", "self", ".", "client_key", "yield", "from", "websocket", ".", "send", "(", "json", ".", "dumps", "(", "handshake", ")", ")", "raw_response", "=", "yield", "from", "websocket", ".", "recv", "(", ")", "response", "=", "json", ".", "loads", "(", "raw_response", ")", "if", "response", "[", "'type'", "]", "==", "'response'", "and", "response", "[", "'payload'", "]", "[", "'pairingType'", "]", "==", "'PROMPT'", ":", "raw_response", "=", "yield", "from", "websocket", ".", "recv", "(", ")", "response", "=", "json", ".", "loads", "(", "raw_response", ")", "if", "response", "[", "'type'", "]", "==", "'registered'", ":", "self", ".", "client_key", "=", "response", "[", "'payload'", "]", "[", "'client-key'", "]", "self", ".", "save_key_file", "(", ")" ]
concatenate message list as single string with line feed .
def print_msg ( contentlist ) : # type: (Union[AnyStr, List[AnyStr], Tuple[AnyStr]]) -> AnyStr if isinstance ( contentlist , list ) or isinstance ( contentlist , tuple ) : return '\n' . join ( contentlist ) else : # strings if len ( contentlist ) > 1 and contentlist [ - 1 ] != '\n' : contentlist += '\n' return contentlist
5,846
https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/utils.py#L952-L960
[ "def", "initialize_ray", "(", ")", ":", "if", "threading", ".", "current_thread", "(", ")", ".", "name", "==", "\"MainThread\"", ":", "plasma_directory", "=", "None", "object_store_memory", "=", "os", ".", "environ", ".", "get", "(", "\"MODIN_MEMORY\"", ",", "None", ")", "if", "os", ".", "environ", ".", "get", "(", "\"MODIN_OUT_OF_CORE\"", ",", "\"False\"", ")", ".", "title", "(", ")", "==", "\"True\"", ":", "from", "tempfile", "import", "gettempdir", "plasma_directory", "=", "gettempdir", "(", ")", "# We may have already set the memory from the environment variable, we don't", "# want to overwrite that value if we have.", "if", "object_store_memory", "is", "None", ":", "# Round down to the nearest Gigabyte.", "mem_bytes", "=", "ray", ".", "utils", ".", "get_system_memory", "(", ")", "//", "10", "**", "9", "*", "10", "**", "9", "# Default to 8x memory for out of core", "object_store_memory", "=", "8", "*", "mem_bytes", "# In case anything failed above, we can still improve the memory for Modin.", "if", "object_store_memory", "is", "None", ":", "# Round down to the nearest Gigabyte.", "object_store_memory", "=", "int", "(", "0.6", "*", "ray", ".", "utils", ".", "get_system_memory", "(", ")", "//", "10", "**", "9", "*", "10", "**", "9", ")", "# If the memory pool is smaller than 2GB, just use the default in ray.", "if", "object_store_memory", "==", "0", ":", "object_store_memory", "=", "None", "else", ":", "object_store_memory", "=", "int", "(", "object_store_memory", ")", "ray", ".", "init", "(", "include_webui", "=", "False", ",", "ignore_reinit_error", "=", "True", ",", "plasma_directory", "=", "plasma_directory", ",", "object_store_memory", "=", "object_store_memory", ",", ")", "# Register custom serializer for method objects to avoid warning message.", "# We serialize `MethodType` objects when we use AxisPartition operations.", "ray", ".", "register_custom_serializer", "(", "types", ".", "MethodType", ",", "use_pickle", "=", "True", ")" ]
Decode strings in dictionary which may contains unicode strings or numeric values .
def decode_strs_in_dict ( unicode_dict # type: Dict[Union[AnyStr, int], Union[int, float, AnyStr, List[Union[int, float, AnyStr]]]] ) : # type: (...) -> Dict[Union[AnyStr, int], Any] unicode_dict = { StringClass . convert_str2num ( k ) : StringClass . convert_str2num ( v ) for k , v in iteritems ( unicode_dict ) } for k , v in iteritems ( unicode_dict ) : if isinstance ( v , dict ) : unicode_dict [ k ] = UtilClass . decode_strs_in_dict ( v ) return unicode_dict
5,847
https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/pygeoc/utils.py#L987-L1010
[ "def", "wait_for_setting_value", "(", "self", ",", "section", ",", "setting", ",", "value", ",", "wait_time", "=", "5.0", ")", ":", "expire", "=", "time", ".", "time", "(", ")", "+", "wait_time", "ok", "=", "False", "while", "not", "ok", "and", "time", ".", "time", "(", ")", "<", "expire", ":", "settings", "=", "[", "x", "for", "x", "in", "self", ".", "settings", "if", "(", "x", "[", "0", "]", ",", "x", "[", "1", "]", ")", "==", "(", "section", ",", "setting", ")", "]", "# Check to see if the last setting has the value we want", "if", "len", "(", "settings", ")", ">", "0", ":", "ok", "=", "settings", "[", "-", "1", "]", "[", "2", "]", "==", "value", "time", ".", "sleep", "(", "0.1", ")", "return", "ok" ]
Rewind the game to the previous state .
def undo ( self ) : self . undo_manager . undo ( ) self . notify_observers ( ) logging . debug ( 'undo_manager undo stack={}' . format ( self . undo_manager . _undo_stack ) )
5,848
https://github.com/rosshamish/catan-py/blob/120438a8f16e39c13322c5d5930e1064e1d3f4be/catan/game.py#L91-L97
[ "def", "_proc_member", "(", "self", ",", "tarfile", ")", ":", "if", "self", ".", "type", "in", "(", "GNUTYPE_LONGNAME", ",", "GNUTYPE_LONGLINK", ")", ":", "return", "self", ".", "_proc_gnulong", "(", "tarfile", ")", "elif", "self", ".", "type", "==", "GNUTYPE_SPARSE", ":", "return", "self", ".", "_proc_sparse", "(", "tarfile", ")", "elif", "self", ".", "type", "in", "(", "XHDTYPE", ",", "XGLTYPE", ",", "SOLARIS_XHDTYPE", ")", ":", "return", "self", ".", "_proc_pax", "(", "tarfile", ")", "else", ":", "return", "self", ".", "_proc_builtin", "(", "tarfile", ")" ]
Redo the latest undone command .
def redo ( self ) : self . undo_manager . redo ( ) self . notify_observers ( ) logging . debug ( 'undo_manager redo stack={}' . format ( self . undo_manager . _redo_stack ) )
5,849
https://github.com/rosshamish/catan-py/blob/120438a8f16e39c13322c5d5930e1064e1d3f4be/catan/game.py#L99-L105
[ "def", "treat", "(", "request_body", ")", ":", "# Python 3+ support", "if", "isinstance", "(", "request_body", ",", "six", ".", "binary_type", ")", ":", "request_body", "=", "request_body", ".", "decode", "(", "'utf-8'", ")", "try", ":", "data", "=", "json", ".", "loads", "(", "request_body", ")", "except", "ValueError", ":", "raise", "exceptions", ".", "UnknownAPIResource", "(", "'Request body is malformed JSON.'", ")", "unsafe_api_resource", "=", "APIResource", ".", "factory", "(", "data", ")", "try", ":", "consistent_api_resource", "=", "unsafe_api_resource", ".", "get_consistent_resource", "(", ")", "except", "AttributeError", ":", "raise", "exceptions", ".", "UnknownAPIResource", "(", "'The API resource provided is invalid.'", ")", "return", "consistent_api_resource" ]
Find the NetworkParams for a network by its long or short name . Raises UnsupportedNetwork if no NetworkParams is found .
def net_query ( name : str ) -> Constants : for net_params in networks : if name in ( net_params . name , net_params . shortname , ) : return net_params raise UnsupportedNetwork
5,850
https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/networks.py#L100-L109
[ "def", "to_array", "(", "self", ")", ":", "array", "=", "super", "(", "ResponseParameters", ",", "self", ")", ".", "to_array", "(", ")", "if", "self", ".", "migrate_to_chat_id", "is", "not", "None", ":", "array", "[", "'migrate_to_chat_id'", "]", "=", "int", "(", "self", ".", "migrate_to_chat_id", ")", "# type int", "if", "self", ".", "retry_after", "is", "not", "None", ":", "array", "[", "'retry_after'", "]", "=", "int", "(", "self", ".", "retry_after", ")", "# type int", "return", "array" ]
If no port is found a new none port is made and added to self . ports .
def get_port_at ( self , tile_id , direction ) : for port in self . ports : if port . tile_id == tile_id and port . direction == direction : return port port = Port ( tile_id , direction , PortType . none ) self . ports . append ( port ) return port
5,851
https://github.com/rosshamish/catan-py/blob/120438a8f16e39c13322c5d5930e1064e1d3f4be/catan/board.py#L170-L185
[ "def", "get_virtual_cd_set_params_cmd", "(", "remote_image_server", ",", "remote_image_user_domain", ",", "remote_image_share_type", ",", "remote_image_share_name", ",", "remote_image_deploy_iso", ",", "remote_image_username", ",", "remote_image_user_password", ")", ":", "cmd", "=", "_VIRTUAL_MEDIA_CD_SETTINGS", "%", "(", "remote_image_server", ",", "remote_image_user_domain", ",", "remote_image_share_type", ",", "remote_image_share_name", ",", "remote_image_deploy_iso", ",", "remote_image_username", ",", "remote_image_user_password", ")", "return", "cmd" ]
Rotates the ports 90 degrees . Useful when using the default port setup but the spectator is watching at a rotated angle from true north .
def rotate_ports ( self ) : for port in self . ports : port . tile_id = ( ( port . tile_id + 1 ) % len ( hexgrid . coastal_tile_ids ( ) ) ) + 1 port . direction = hexgrid . rotate_direction ( hexgrid . EDGE , port . direction , ccw = True ) self . notify_observers ( )
5,852
https://github.com/rosshamish/catan-py/blob/120438a8f16e39c13322c5d5930e1064e1d3f4be/catan/board.py#L226-L234
[ "def", "fail", "(", "self", ",", "exception", ")", ":", "fail", "=", "failure", ".", "create", "(", "exception", ",", "self", ".", "_queue", ",", "self", ".", "_payload", ",", "self", ".", "_worker", ")", "fail", ".", "save", "(", "self", ".", "resq", ")", "return", "fail" ]
Extract SeqRecords from the index by matching keys .
def intersect_keys ( keys , reffile , cache = False , clean_accs = False ) : # Build/load the index of reference sequences index = None if cache : refcache = reffile + '.sqlite' if os . path . exists ( refcache ) : if os . stat ( refcache ) . st_mtime < os . stat ( reffile ) . st_mtime : logging . warn ( "Outdated cache; rebuilding index" ) else : try : index = ( SeqIO . index_db ( refcache , key_function = clean_accession ) if clean_accs else SeqIO . index_db ( refcache ) ) except Exception : logging . warn ( "Skipping corrupted cache; rebuilding index" ) index = None else : refcache = ':memory:' if index is None : # Rebuild the index, for whatever reason index = ( SeqIO . index_db ( refcache , [ reffile ] , 'fasta' , key_function = clean_accession ) if clean_accs else SeqIO . index_db ( refcache , [ reffile ] , 'fasta' ) ) # Extract records by key if clean_accs : keys = ( clean_accession ( k ) for k in keys ) for key in keys : try : record = index [ key ] except LookupError : # Missing keys are rare, so it's faster not to check every time logging . info ( "No match: %s" , repr ( key ) ) continue yield record
5,853
https://github.com/etal/biofrills/blob/36684bb6c7632f96215e8b2b4ebc86640f331bcd/biofrills/sequtils.py#L29-L73
[ "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" ]
Calculate the amino acid frequencies in a sequence set .
def aa_frequencies ( seq , gap_chars = '-.' ) : aa_counts = Counter ( seq ) # Don't count gaps for gap_char in gap_chars : if gap_char in aa_counts : del aa_counts [ gap_char ] # Reduce to frequencies scale = 1.0 / sum ( aa_counts . values ( ) ) return dict ( ( aa , cnt * scale ) for aa , cnt in aa_counts . iteritems ( ) )
5,854
https://github.com/etal/biofrills/blob/36684bb6c7632f96215e8b2b4ebc86640f331bcd/biofrills/sequtils.py#L76-L85
[ "def", "get_web_session_cookies", "(", "self", ")", ":", "if", "not", "self", ".", "logged_on", ":", "return", "None", "resp", "=", "self", ".", "send_job_and_wait", "(", "MsgProto", "(", "EMsg", ".", "ClientRequestWebAPIAuthenticateUserNonce", ")", ",", "timeout", "=", "7", ")", "if", "resp", "is", "None", ":", "return", "None", "skey", ",", "ekey", "=", "generate_session_key", "(", ")", "data", "=", "{", "'steamid'", ":", "self", ".", "steam_id", ",", "'sessionkey'", ":", "ekey", ",", "'encrypted_loginkey'", ":", "symmetric_encrypt", "(", "resp", ".", "webapi_authenticate_user_nonce", ".", "encode", "(", "'ascii'", ")", ",", "skey", ")", ",", "}", "try", ":", "resp", "=", "webapi", ".", "post", "(", "'ISteamUserAuth'", ",", "'AuthenticateUser'", ",", "1", ",", "params", "=", "data", ")", "except", "Exception", "as", "exp", ":", "self", ".", "_LOG", ".", "debug", "(", "\"get_web_session_cookies error: %s\"", "%", "str", "(", "exp", ")", ")", "return", "None", "return", "{", "'steamLogin'", ":", "resp", "[", "'authenticateuser'", "]", "[", "'token'", "]", ",", "'steamLoginSecure'", ":", "resp", "[", "'authenticateuser'", "]", "[", "'tokensecure'", "]", ",", "}" ]
Returns tuples corresponding to the number and type of each resource in the trade from giver - > getter
def giving ( self ) : logging . debug ( 'give={}' . format ( self . _give ) ) c = Counter ( self . _give . copy ( ) ) return [ ( n , t ) for t , n in c . items ( ) ]
5,855
https://github.com/rosshamish/catan-py/blob/120438a8f16e39c13322c5d5930e1064e1d3f4be/catan/trading.py#L54-L63
[ "def", "abort", "(", "self", ")", ":", "if", "(", "self", ".", "reply", "and", "self", ".", "reply", ".", "isRunning", "(", ")", ")", ":", "self", ".", "on_abort", "=", "True", "self", ".", "reply", ".", "abort", "(", ")" ]
Returns tuples corresponding to the number and type of each resource in the trade from getter - > giver
def getting ( self ) : c = Counter ( self . _get . copy ( ) ) return [ ( n , t ) for t , n in c . items ( ) ]
5,856
https://github.com/rosshamish/catan-py/blob/120438a8f16e39c13322c5d5930e1064e1d3f4be/catan/trading.py#L65-L73
[ "def", "abort", "(", "self", ")", ":", "if", "(", "self", ".", "reply", "and", "self", ".", "reply", ".", "isRunning", "(", ")", ")", ":", "self", ".", "on_abort", "=", "True", "self", ".", "reply", ".", "abort", "(", ")" ]
Check if the family members break the structure of the family . eg . nonexistent parent wrong sex on parent etc . Also extracts all trios found this is of help for many at the moment since GATK can only do phasing of trios and duos .
def family_check ( self ) : #TODO Make some tests for these self . logger . info ( "Checking family relations for {0}" . format ( self . family_id ) ) for individual_id in self . individuals : self . logger . debug ( "Checking individual {0}" . format ( individual_id ) ) individual = self . individuals [ individual_id ] self . logger . debug ( "Checking if individual {0} is affected" . format ( individual_id ) ) if individual . affected : self . logger . debug ( "Found affected individual {0}" . format ( individual_id ) ) self . affected_individuals . add ( individual_id ) father = individual . father mother = individual . mother if individual . has_parents : self . logger . debug ( "Individual {0} has parents" . format ( individual_id ) ) self . no_relations = False try : self . check_parent ( father , father = True ) self . check_parent ( mother , father = False ) except PedigreeError as e : self . logger . error ( e . message ) raise e # Check if there is a trio if individual . has_both_parents : self . trios . append ( set ( [ individual_id , father , mother ] ) ) elif father != '0' : self . duos . append ( set ( [ individual_id , father ] ) ) else : self . duos . append ( set ( [ individual_id , mother ] ) ) ##TODO self.check_grandparents(individual) # Annotate siblings: for individual_2_id in self . individuals : if individual_id != individual_2_id : if self . check_siblings ( individual_id , individual_2_id ) : individual . siblings . add ( individual_2_id )
5,857
https://github.com/moonso/ped_parser/blob/a7393e47139532782ea3c821aabea33d46f94323/ped_parser/family.py#L61-L116
[ "def", "get_next_revision", "(", "self", ",", "session_id", ",", "revision", ",", "delta", ")", ":", "session", "=", "self", ".", "sessions", "[", "session_id", "]", "session", ".", "state", "=", "State", ".", "connected", "if", "delta", "==", "revision", ":", "# Increment revision. Never decrement.", "session", ".", "revision", "=", "max", "(", "session", ".", "revision", ",", "revision", ")", "# Wait for next revision to become ready.", "self", ".", "next_revision_available", ".", "wait", "(", ")", "return", "self", ".", "revision" ]
Check if the parent info is correct . If an individual is not present in file raise exeption .
def check_parent ( self , parent_id , father = False ) : self . logger . debug ( "Checking parent {0}" . format ( parent_id ) ) if parent_id != '0' : if parent_id not in self . individuals : raise PedigreeError ( self . family_id , parent_id , 'Parent is not in family.' ) if father : if self . individuals [ parent_id ] . sex != 1 : raise PedigreeError ( self . family_id , parent_id , 'Father is not specified as male.' ) else : if self . individuals [ parent_id ] . sex != 2 : raise PedigreeError ( self . family_id , parent_id , 'Mother is not specified as female.' ) return
5,858
https://github.com/moonso/ped_parser/blob/a7393e47139532782ea3c821aabea33d46f94323/ped_parser/family.py#L120-L144
[ "def", "http", "(", "self", ")", ":", "if", "self", ".", "_use_cached_http", "and", "hasattr", "(", "self", ".", "_local", ",", "'http'", ")", ":", "return", "self", ".", "_local", ".", "http", "if", "self", ".", "_http_replay", "is", "not", "None", ":", "# httplib2 instance is not thread safe", "http", "=", "self", ".", "_http_replay", "else", ":", "http", "=", "_build_http", "(", ")", "authorized_http", "=", "google_auth_httplib2", ".", "AuthorizedHttp", "(", "self", ".", "_credentials", ",", "http", "=", "http", ")", "if", "self", ".", "_use_cached_http", ":", "self", ".", "_local", ".", "http", "=", "authorized_http", "return", "authorized_http" ]
Print the individuals of the family in ped format The header will be the original ped header plus all headers found in extra info of the individuals
def to_ped ( self , outfile = None ) : ped_header = [ '#FamilyID' , 'IndividualID' , 'PaternalID' , 'MaternalID' , 'Sex' , 'Phenotype' , ] extra_headers = [ 'InheritanceModel' , 'Proband' , 'Consultand' , 'Alive' ] for individual_id in self . individuals : individual = self . individuals [ individual_id ] for info in individual . extra_info : if info in extra_headers : if info not in ped_header : ped_header . append ( info ) self . logger . debug ( "Ped headers found: {0}" . format ( ', ' . join ( ped_header ) ) ) if outfile : outfile . write ( '\t' . join ( ped_header ) + '\n' ) else : print ( '\t' . join ( ped_header ) ) for individual in self . to_json ( ) : ped_info = [ ] ped_info . append ( individual [ 'family_id' ] ) ped_info . append ( individual [ 'id' ] ) ped_info . append ( individual [ 'father' ] ) ped_info . append ( individual [ 'mother' ] ) ped_info . append ( individual [ 'sex' ] ) ped_info . append ( individual [ 'phenotype' ] ) if len ( ped_header ) > 6 : for header in ped_header [ 6 : ] : ped_info . append ( individual [ 'extra_info' ] . get ( header , '.' ) ) if outfile : outfile . write ( '\t' . join ( ped_info ) + '\n' ) else : print ( '\t' . join ( ped_info ) )
5,859
https://github.com/moonso/ped_parser/blob/a7393e47139532782ea3c821aabea33d46f94323/ped_parser/family.py#L251-L307
[ "def", "refresh_table_metadata", "(", "self", ",", "keyspace", ",", "table", ",", "max_schema_agreement_wait", "=", "None", ")", ":", "if", "not", "self", ".", "control_connection", ".", "refresh_schema", "(", "target_type", "=", "SchemaTargetType", ".", "TABLE", ",", "keyspace", "=", "keyspace", ",", "table", "=", "table", ",", "schema_agreement_wait", "=", "max_schema_agreement_wait", ",", "force", "=", "True", ")", ":", "raise", "DriverException", "(", "\"Table metadata was not refreshed. See log for details.\"", ")" ]
Find specific deck by deck id .
def find_deck ( provider : Provider , key : str , version : int , prod : bool = True ) -> Optional [ Deck ] : pa_params = param_query ( provider . network ) if prod : p2th = pa_params . P2TH_addr else : p2th = pa_params . test_P2TH_addr rawtx = provider . getrawtransaction ( key , 1 ) deck = deck_parser ( ( provider , rawtx , 1 , p2th ) ) return deck
5,860
https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/__main__.py#L68-L80
[ "def", "get_SZ_orient", "(", "self", ")", ":", "tm_outdated", "=", "self", ".", "_tm_signature", "!=", "(", "self", ".", "radius", ",", "self", ".", "radius_type", ",", "self", ".", "wavelength", ",", "self", ".", "m", ",", "self", ".", "axis_ratio", ",", "self", ".", "shape", ",", "self", ".", "ddelt", ",", "self", ".", "ndgs", ")", "scatter_outdated", "=", "self", ".", "_scatter_signature", "!=", "(", "self", ".", "thet0", ",", "self", ".", "thet", ",", "self", ".", "phi0", ",", "self", ".", "phi", ",", "self", ".", "alpha", ",", "self", ".", "beta", ",", "self", ".", "orient", ")", "orient_outdated", "=", "self", ".", "_orient_signature", "!=", "(", "self", ".", "orient", ",", "self", ".", "or_pdf", ",", "self", ".", "n_alpha", ",", "self", ".", "n_beta", ")", "if", "orient_outdated", ":", "self", ".", "_init_orient", "(", ")", "outdated", "=", "tm_outdated", "or", "scatter_outdated", "or", "orient_outdated", "if", "outdated", ":", "(", "self", ".", "_S_orient", ",", "self", ".", "_Z_orient", ")", "=", "self", ".", "orient", "(", "self", ")", "self", ".", "_set_scatter_signature", "(", ")", "return", "(", "self", ".", "_S_orient", ",", "self", ".", "_Z_orient", ")" ]
Creates Deck spawn raw transaction .
def deck_spawn ( provider : Provider , deck : Deck , inputs : dict , change_address : str , locktime : int = 0 ) -> Transaction : network_params = net_query ( deck . network ) pa_params = param_query ( deck . network ) if deck . production : p2th_addr = pa_params . P2TH_addr else : p2th_addr = pa_params . test_P2TH_addr # first round of txn making is done by presuming minimal fee change_sum = Decimal ( inputs [ 'total' ] - network_params . min_tx_fee - pa_params . P2TH_fee ) txouts = [ tx_output ( network = deck . network , value = pa_params . P2TH_fee , n = 0 , script = p2pkh_script ( address = p2th_addr , network = deck . network ) ) , # p2th tx_output ( network = deck . network , value = Decimal ( 0 ) , n = 1 , script = nulldata_script ( deck . metainfo_to_protobuf ) ) , # op_return tx_output ( network = deck . network , value = change_sum , n = 2 , script = p2pkh_script ( address = change_address , network = deck . network ) ) # change ] unsigned_tx = make_raw_transaction ( network = deck . network , inputs = inputs [ 'utxos' ] , outputs = txouts , locktime = Locktime ( locktime ) ) return unsigned_tx
5,861
https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/__main__.py#L83-L125
[ "def", "validate_instance_password", "(", "self", ",", "password", ")", ":", "# 1-16 alphanumeric characters - first character must be a letter -", "# cannot be a reserved MySQL word", "if", "re", ".", "match", "(", "'[\\w-]+$'", ",", "password", ")", "is", "not", "None", ":", "if", "len", "(", "password", ")", "<=", "41", "and", "len", "(", "password", ")", ">=", "8", ":", "return", "True", "return", "'*** Error: Passwords must be 8-41 alphanumeric characters'" ]
get a single card transfer by it s id
def get_card_transfer ( provider : Provider , deck : Deck , txid : str , debug : bool = False ) -> Iterator : rawtx = provider . getrawtransaction ( txid , 1 ) bundle = card_bundler ( provider , deck , rawtx ) return card_bundle_parser ( bundle , debug )
5,862
https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/__main__.py#L199-L208
[ "def", "sync", "(", "self", ")", ":", "self", ".", "driver", ".", "create_schema", "(", ")", "self", ".", "driver", ".", "set_metadata", "(", "{", "'current_version'", ":", "Gauged", ".", "VERSION", ",", "'initial_version'", ":", "Gauged", ".", "VERSION", ",", "'block_size'", ":", "self", ".", "config", ".", "block_size", ",", "'resolution'", ":", "self", ".", "config", ".", "resolution", ",", "'created_at'", ":", "long", "(", "time", "(", ")", "*", "1000", ")", "}", ",", "replace", "=", "False", ")" ]
find all the valid cards on this deck filtering out cards which don t play nice with deck issue mode
def find_all_valid_cards ( provider : Provider , deck : Deck ) -> Generator : # validate_card_issue_modes must recieve a full list of cards, not batches unfiltered = ( card for batch in get_card_bundles ( provider , deck ) for card in batch ) for card in validate_card_issue_modes ( deck . issue_mode , list ( unfiltered ) ) : yield card
5,863
https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/__main__.py#L211-L219
[ "def", "FromMilliseconds", "(", "self", ",", "millis", ")", ":", "self", ".", "_NormalizeDuration", "(", "millis", "//", "_MILLIS_PER_SECOND", ",", "(", "millis", "%", "_MILLIS_PER_SECOND", ")", "*", "_NANOS_PER_MILLISECOND", ")" ]
Prepare the CardTransfer Transaction object
def card_transfer ( provider : Provider , card : CardTransfer , inputs : dict , change_address : str , locktime : int = 0 ) -> Transaction : network_params = net_query ( provider . network ) pa_params = param_query ( provider . network ) if card . deck_p2th is None : raise Exception ( "card.deck_p2th required for tx_output" ) outs = [ tx_output ( network = provider . network , value = pa_params . P2TH_fee , n = 0 , script = p2pkh_script ( address = card . deck_p2th , network = provider . network ) ) , # deck p2th tx_output ( network = provider . network , value = Decimal ( 0 ) , n = 1 , script = nulldata_script ( card . metainfo_to_protobuf ) ) # op_return ] for addr , index in zip ( card . receiver , range ( len ( card . receiver ) ) ) : outs . append ( # TxOut for each receiver, index + 2 because we have two outs already tx_output ( network = provider . network , value = Decimal ( 0 ) , n = index + 2 , script = p2pkh_script ( address = addr , network = provider . network ) ) ) # first round of txn making is done by presuming minimal fee change_sum = Decimal ( inputs [ 'total' ] - network_params . min_tx_fee - pa_params . P2TH_fee ) outs . append ( tx_output ( network = provider . network , value = change_sum , n = len ( outs ) + 1 , script = p2pkh_script ( address = change_address , network = provider . network ) ) ) unsigned_tx = make_raw_transaction ( network = provider . network , inputs = inputs [ 'utxos' ] , outputs = outs , locktime = Locktime ( locktime ) ) return unsigned_tx
5,864
https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/__main__.py#L222-L271
[ "def", "_search", "(", "prefix", "=", "\"latest/\"", ")", ":", "ret", "=", "{", "}", "linedata", "=", "http", ".", "query", "(", "os", ".", "path", ".", "join", "(", "HOST", ",", "prefix", ")", ",", "headers", "=", "True", ")", "if", "'body'", "not", "in", "linedata", ":", "return", "ret", "body", "=", "salt", ".", "utils", ".", "stringutils", ".", "to_unicode", "(", "linedata", "[", "'body'", "]", ")", "if", "linedata", "[", "'headers'", "]", ".", "get", "(", "'Content-Type'", ",", "'text/plain'", ")", "==", "'application/octet-stream'", ":", "return", "body", "for", "line", "in", "body", ".", "split", "(", "'\\n'", ")", ":", "if", "line", ".", "endswith", "(", "'/'", ")", ":", "ret", "[", "line", "[", ":", "-", "1", "]", "]", "=", "_search", "(", "prefix", "=", "os", ".", "path", ".", "join", "(", "prefix", ",", "line", ")", ")", "elif", "prefix", "==", "'latest/'", ":", "# (gtmanfred) The first level should have a forward slash since", "# they have stuff underneath. This will not be doubled up though,", "# because lines ending with a slash are checked first.", "ret", "[", "line", "]", "=", "_search", "(", "prefix", "=", "os", ".", "path", ".", "join", "(", "prefix", ",", "line", "+", "'/'", ")", ")", "elif", "line", ".", "endswith", "(", "(", "'dynamic'", ",", "'meta-data'", ")", ")", ":", "ret", "[", "line", "]", "=", "_search", "(", "prefix", "=", "os", ".", "path", ".", "join", "(", "prefix", ",", "line", ")", ")", "elif", "'='", "in", "line", ":", "key", ",", "value", "=", "line", ".", "split", "(", "'='", ")", "ret", "[", "value", "]", "=", "_search", "(", "prefix", "=", "os", ".", "path", ".", "join", "(", "prefix", ",", "key", ")", ")", "else", ":", "retdata", "=", "http", ".", "query", "(", "os", ".", "path", ".", "join", "(", "HOST", ",", "prefix", ",", "line", ")", ")", ".", "get", "(", "'body'", ",", "None", ")", "# (gtmanfred) This try except block is slightly faster than", "# checking if the string starts with a curly brace", "if", "isinstance", "(", "retdata", ",", "six", ".", "binary_type", ")", ":", "try", ":", "ret", "[", "line", "]", "=", "salt", ".", "utils", ".", "json", ".", "loads", "(", "salt", ".", "utils", ".", "stringutils", ".", "to_unicode", "(", "retdata", ")", ")", "except", "ValueError", ":", "ret", "[", "line", "]", "=", "salt", ".", "utils", ".", "stringutils", ".", "to_unicode", "(", "retdata", ")", "else", ":", "ret", "[", "line", "]", "=", "retdata", "return", "salt", ".", "utils", ".", "data", ".", "decode", "(", "ret", ")" ]
convert a rfc3339 date representation into a Python datetime
def rfc3339_to_datetime ( data ) : try : ts = time . strptime ( data , '%Y-%m-%d' ) return date ( * ts [ : 3 ] ) except ValueError : pass try : dt , _ , tz = data . partition ( 'Z' ) if tz : tz = offset ( tz ) else : tz = offset ( '00:00' ) if '.' in dt and dt . rsplit ( '.' , 1 ) [ - 1 ] . isdigit ( ) : ts = time . strptime ( dt , '%Y-%m-%dT%H:%M:%S.%f' ) else : ts = time . strptime ( dt , '%Y-%m-%dT%H:%M:%S' ) return datetime ( * ts [ : 6 ] , tzinfo = tz ) except ValueError : raise ValueError ( 'date-time {!r} is not a valid rfc3339 date representation' . format ( data ) )
5,865
https://github.com/johnnoone/json-spec/blob/f91981724cea0c366bd42a6670eb07bbe31c0e0c/src/jsonspec/validators/util.py#L92-L112
[ "def", "undefine", "(", "self", ")", ":", "if", "lib", ".", "EnvUndefglobal", "(", "self", ".", "_env", ",", "self", ".", "_glb", ")", "!=", "1", ":", "raise", "CLIPSError", "(", "self", ".", "_env", ")", "self", ".", "_env", "=", "None" ]
Set up logging the way I like it .
def log_config ( verbose = 1 ) : # ENH: # - do print levelname before DEBUG and WARNING # - instead of %module, name the currently running script # - make a subclass of logging.handlers.X instead? # - tweak %root? # - take __file__ as an argument? if verbose == 0 : level = logging . WARNING fmt = "%(module)s: %(message)s" elif verbose == 1 : level = logging . INFO fmt = "%(module)s [@%(lineno)s]: %(message)s" else : level = logging . DEBUG fmt = "%(module)s [%(lineno)s]: %(levelname)s: %(message)s" logging . basicConfig ( format = fmt , level = level )
5,866
https://github.com/etal/biofrills/blob/36684bb6c7632f96215e8b2b4ebc86640f331bcd/biofrills/cmdutils.py#L6-L23
[ "def", "get_applicable_content_pattern_names", "(", "self", ",", "path", ")", ":", "encodings", "=", "set", "(", ")", "applicable_content_pattern_names", "=", "set", "(", ")", "for", "path_pattern_name", ",", "content_pattern_names", "in", "self", ".", "_required_matches", ".", "items", "(", ")", ":", "m", "=", "self", ".", "_path_matchers", "[", "path_pattern_name", "]", "if", "m", ".", "matches", "(", "path", ")", ":", "encodings", ".", "add", "(", "m", ".", "content_encoding", ")", "applicable_content_pattern_names", ".", "update", "(", "content_pattern_names", ")", "if", "len", "(", "encodings", ")", ">", "1", ":", "raise", "ValueError", "(", "'Path matched patterns with multiple content encodings ({}): {}'", ".", "format", "(", "', '", ".", "join", "(", "sorted", "(", "encodings", ")", ")", ",", "path", ")", ")", "content_encoding", "=", "next", "(", "iter", "(", "encodings", ")", ")", "if", "encodings", "else", "None", "return", "applicable_content_pattern_names", ",", "content_encoding" ]
if self . tree_settings has been expanded ask instruments for their actual values
def refresh_instruments ( self ) : def list_access_nested_dict ( dict , somelist ) : """ Allows one to use a list to access a nested dictionary, for example: listAccessNestedDict({'a': {'b': 1}}, ['a', 'b']) returns 1 Args: dict: somelist: Returns: """ return reduce ( operator . getitem , somelist , dict ) def update ( item ) : if item . isExpanded ( ) : for index in range ( item . childCount ( ) ) : child = item . child ( index ) if child . childCount ( ) == 0 : instrument , path_to_instrument = child . get_instrument ( ) path_to_instrument . reverse ( ) try : #check if item is in probes value = instrument . read_probes ( path_to_instrument [ - 1 ] ) except AssertionError : #if item not in probes, get value from settings instead value = list_access_nested_dict ( instrument . settings , path_to_instrument ) child . value = value else : update ( child ) #need to block signals during update so that tree.itemChanged doesn't fire and the gui doesn't try to #reupdate the instruments to their current value self . tree_settings . blockSignals ( True ) for index in range ( self . tree_settings . topLevelItemCount ( ) ) : instrument = self . tree_settings . topLevelItem ( index ) update ( instrument ) self . tree_settings . blockSignals ( False )
5,867
https://github.com/LISE-B26/pylabcontrol/blob/67482e5157fcd1c40705e5c2cacfb93564703ed0/build/lib/pylabcontrol/gui/windows_and_widgets/main_window.py#L345-L386
[ "def", "delete", "(", "self", ",", "event", ")", ":", "super", "(", "CeleryReceiver", ",", "self", ")", ".", "delete", "(", "event", ")", "AsyncResult", "(", "event", ".", "id", ")", ".", "revoke", "(", "terminate", "=", "True", ")" ]
updates the internal dictionaries for scripts and instruments with values from the respective trees
def update_parameters ( self , treeWidget ) : if treeWidget == self . tree_settings : item = treeWidget . currentItem ( ) instrument , path_to_instrument = item . get_instrument ( ) # build nested dictionary to update instrument dictator = item . value for element in path_to_instrument : dictator = { element : dictator } # get old value from instrument old_value = instrument . settings path_to_instrument . reverse ( ) for element in path_to_instrument : old_value = old_value [ element ] # send new value from tree to instrument instrument . update ( dictator ) new_value = item . value if new_value is not old_value : msg = "changed parameter {:s} from {:s} to {:s} on {:s}" . format ( item . name , str ( old_value ) , str ( new_value ) , instrument . name ) else : msg = "did not change parameter {:s} on {:s}" . format ( item . name , instrument . name ) self . log ( msg ) elif treeWidget == self . tree_scripts : item = treeWidget . currentItem ( ) script , path_to_script , _ = item . get_script ( ) # check if changes value is from an instrument instrument , path_to_instrument = item . get_instrument ( ) if instrument is not None : new_value = item . value msg = "changed parameter {:s} to {:s} in {:s}" . format ( item . name , str ( new_value ) , script . name ) else : new_value = item . value msg = "changed parameter {:s} to {:s} in {:s}" . format ( item . name , str ( new_value ) , script . name ) self . log ( msg )
5,868
https://github.com/LISE-B26/pylabcontrol/blob/67482e5157fcd1c40705e5c2cacfb93564703ed0/build/lib/pylabcontrol/gui/windows_and_widgets/main_window.py#L889-L947
[ "def", "_ws_on_error", "(", "self", ",", "ws", ":", "websocket", ".", "WebSocketApp", ",", "error", ":", "Exception", ")", ":", "self", ".", "logger", ".", "error", "(", "f'Got error from websocket connection: {str(error)}'", ")" ]
waits for the script to emit the script_finshed signal
def script_finished ( self ) : script = self . current_script script . updateProgress . disconnect ( self . update_status ) self . script_thread . started . disconnect ( ) script . finished . disconnect ( ) self . current_script = None self . plot_script ( script ) self . progressBar . setValue ( 100 ) self . btn_start_script . setEnabled ( True ) self . btn_skip_subscript . setEnabled ( False )
5,869
https://github.com/LISE-B26/pylabcontrol/blob/67482e5157fcd1c40705e5c2cacfb93564703ed0/build/lib/pylabcontrol/gui/windows_and_widgets/main_window.py#L994-L1008
[ "def", "cache", "(", "self", ",", "private", "=", "False", ",", "max_age", "=", "31536000", ",", "s_maxage", "=", "None", ",", "no_cache", "=", "False", ",", "no_store", "=", "False", ",", "must_revalidate", "=", "False", ",", "*", "*", "overrides", ")", ":", "parts", "=", "(", "'private'", "if", "private", "else", "'public'", ",", "'max-age={0}'", ".", "format", "(", "max_age", ")", ",", "'s-maxage={0}'", ".", "format", "(", "s_maxage", ")", "if", "s_maxage", "is", "not", "None", "else", "None", ",", "no_cache", "and", "'no-cache'", ",", "no_store", "and", "'no-store'", ",", "must_revalidate", "and", "'must-revalidate'", ")", "return", "self", ".", "add_response_headers", "(", "{", "'cache-control'", ":", "', '", ".", "join", "(", "filter", "(", "bool", ",", "parts", ")", ")", "}", ",", "*", "*", "overrides", ")" ]
update the probe tree
def update_probes ( self , progress ) : new_values = self . read_probes . probes_values probe_count = len ( self . read_probes . probes ) if probe_count > self . tree_probes . topLevelItemCount ( ) : # when run for the first time, there are no probes in the tree, so we have to fill it first self . fill_treewidget ( self . tree_probes , new_values ) else : for x in range ( probe_count ) : topLvlItem = self . tree_probes . topLevelItem ( x ) for child_id in range ( topLvlItem . childCount ( ) ) : child = topLvlItem . child ( child_id ) child . value = new_values [ topLvlItem . name ] [ child . name ] child . setText ( 1 , str ( child . value ) ) if self . probe_to_plot is not None : self . probe_to_plot . plot ( self . matplotlibwidget_1 . axes ) self . matplotlibwidget_1 . draw ( ) if self . chk_probe_log . isChecked ( ) : data = ',' . join ( list ( np . array ( [ [ str ( p ) for p in list ( p_dict . values ( ) ) ] for instr , p_dict in new_values . items ( ) ] ) . flatten ( ) ) ) self . probe_file . write ( '{:s}\n' . format ( data ) )
5,870
https://github.com/LISE-B26/pylabcontrol/blob/67482e5157fcd1c40705e5c2cacfb93564703ed0/build/lib/pylabcontrol/gui/windows_and_widgets/main_window.py#L1022-L1047
[ "def", "data_from_dates", "(", "path", ",", "dates", ")", ":", "if", "path", "[", "-", "1", "]", "!=", "os", ".", "path", ".", "sep", ":", "path", "+=", "os", ".", "path", ".", "sep", "if", "not", "isinstance", "(", "dates", ",", "list", ")", ":", "dates", "=", "[", "dates", "]", "data", "=", "[", "]", "for", "d", "in", "dates", ":", "filepath", "=", "path", "+", "'datalog '", "+", "d", "+", "'.xls'", "data", ".", "append", "(", "remove_notes", "(", "pd", ".", "read_csv", "(", "filepath", ",", "delimiter", "=", "'\\t'", ")", ")", ")", "return", "data" ]
updates the script based on the information provided in item
def update_script_from_item ( self , item ) : script , path_to_script , script_item = item . get_script ( ) # build dictionary # get full information from script dictator = list ( script_item . to_dict ( ) . values ( ) ) [ 0 ] # there is only one item in the dictionary for instrument in list ( script . instruments . keys ( ) ) : # update instrument script . instruments [ instrument ] [ 'settings' ] = dictator [ instrument ] [ 'settings' ] # remove instrument del dictator [ instrument ] for sub_script_name in list ( script . scripts . keys ( ) ) : sub_script_item = script_item . get_subscript ( sub_script_name ) self . update_script_from_item ( sub_script_item ) del dictator [ sub_script_name ] script . update ( dictator ) # update datefolder path script . data_path = self . gui_settings [ 'data_folder' ]
5,871
https://github.com/LISE-B26/pylabcontrol/blob/67482e5157fcd1c40705e5c2cacfb93564703ed0/build/lib/pylabcontrol/gui/windows_and_widgets/main_window.py#L1049-L1079
[ "def", "console_set_default_foreground", "(", "con", ":", "tcod", ".", "console", ".", "Console", ",", "col", ":", "Tuple", "[", "int", ",", "int", ",", "int", "]", ")", "->", "None", ":", "lib", ".", "TCOD_console_set_default_foreground", "(", "_console", "(", "con", ")", ",", "col", ")" ]
Unsupported in the Bot API
def message_search ( self , text , on_success , peer = None , min_date = None , max_date = None , max_id = None , offset = 0 , limit = 255 ) : raise TWXUnsupportedMethod ( )
5,872
https://github.com/datamachine/twx/blob/d9633f12f3647b1e54ba87b70b39df3b7e02b4eb/twx/twx.py#L758-L762
[ "def", "prune_by_work_count", "(", "self", ",", "minimum", "=", "None", ",", "maximum", "=", "None", ",", "label", "=", "None", ")", ":", "self", ".", "_logger", ".", "info", "(", "'Pruning results by work count'", ")", "count_fieldname", "=", "'tmp_count'", "matches", "=", "self", ".", "_matches", "if", "label", "is", "not", "None", ":", "matches", "=", "matches", "[", "matches", "[", "constants", ".", "LABEL_FIELDNAME", "]", "==", "label", "]", "filtered", "=", "matches", "[", "matches", "[", "constants", ".", "COUNT_FIELDNAME", "]", ">", "0", "]", "grouped", "=", "filtered", ".", "groupby", "(", "constants", ".", "NGRAM_FIELDNAME", ",", "sort", "=", "False", ")", "counts", "=", "pd", ".", "DataFrame", "(", "grouped", "[", "constants", ".", "WORK_FIELDNAME", "]", ".", "nunique", "(", ")", ")", "counts", ".", "rename", "(", "columns", "=", "{", "constants", ".", "WORK_FIELDNAME", ":", "count_fieldname", "}", ",", "inplace", "=", "True", ")", "if", "minimum", ":", "counts", "=", "counts", "[", "counts", "[", "count_fieldname", "]", ">=", "minimum", "]", "if", "maximum", ":", "counts", "=", "counts", "[", "counts", "[", "count_fieldname", "]", "<=", "maximum", "]", "self", ".", "_matches", "=", "pd", ".", "merge", "(", "self", ".", "_matches", ",", "counts", ",", "left_on", "=", "constants", ".", "NGRAM_FIELDNAME", ",", "right_index", "=", "True", ")", "del", "self", ".", "_matches", "[", "count_fieldname", "]" ]
Remove element from sequence member from mapping .
def remove ( self , pointer ) : doc = deepcopy ( self . document ) parent , obj = None , doc try : # fetching for token in Pointer ( pointer ) : parent , obj = obj , token . extract ( obj , bypass_ref = True ) # removing if isinstance ( parent , Mapping ) : del parent [ token ] if isinstance ( parent , MutableSequence ) : parent . pop ( int ( token ) ) except Exception as error : raise Error ( * error . args ) return Target ( doc )
5,873
https://github.com/johnnoone/json-spec/blob/f91981724cea0c366bd42a6670eb07bbe31c0e0c/src/jsonspec/operations/bases.py#L47-L70
[ "def", "make_tstore_conn", "(", "params", ",", "*", "*", "kwargs", ")", ":", "log", ".", "setLevel", "(", "params", ".", "get", "(", "'log_level'", ",", "__LOG_LEVEL__", ")", ")", "log", ".", "debug", "(", "\"\\n%s\"", ",", "params", ")", "params", ".", "update", "(", "kwargs", ")", "try", ":", "vendor", "=", "RdfwConnections", "[", "'triplestore'", "]", "[", "params", ".", "get", "(", "'vendor'", ")", "]", "except", "KeyError", ":", "vendor", "=", "RdfwConnections", "[", "'triplestore'", "]", "[", "'blazegraph'", "]", "conn", "=", "vendor", "(", "*", "*", "params", ")", "return", "conn" ]
resolute network name required because some providers use shortnames and other use longnames .
def _netname ( name : str ) -> dict : try : long = net_query ( name ) . name short = net_query ( name ) . shortname except AttributeError : raise UnsupportedNetwork ( '''This blockchain network is not supported by the pypeerassets, check networks.py for list of supported networks.''' ) return { 'long' : long , 'short' : short }
5,874
https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/provider/common.py#L21-L32
[ "def", "IOR", "(", "classical_reg1", ",", "classical_reg2", ")", ":", "left", ",", "right", "=", "unpack_reg_val_pair", "(", "classical_reg1", ",", "classical_reg2", ")", "return", "ClassicalInclusiveOr", "(", "left", ",", "right", ")" ]
sendrawtransaction remote API
def sendrawtransaction ( cls , rawtxn : str ) -> str : if cls . is_testnet : url = 'https://testnet-explorer.peercoin.net/api/sendrawtransaction?hex={0}' . format ( rawtxn ) else : url = 'https://explorer.peercoin.net/api/sendrawtransaction?hex={0}' . format ( rawtxn ) resp = urllib . request . urlopen ( url ) return resp . read ( ) . decode ( 'utf-8' )
5,875
https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/provider/common.py#L62-L71
[ "def", "get_listing", "(", "self", ")", ":", "if", "not", "hasattr", "(", "self", ",", "'listing'", ")", ":", "allEvents", "=", "self", ".", "get_allEvents", "(", ")", "openEvents", "=", "allEvents", ".", "filter", "(", "registrationOpen", "=", "True", ")", "closedEvents", "=", "allEvents", ".", "filter", "(", "registrationOpen", "=", "False", ")", "publicEvents", "=", "allEvents", ".", "instance_of", "(", "PublicEvent", ")", "allSeries", "=", "allEvents", ".", "instance_of", "(", "Series", ")", "self", ".", "listing", "=", "{", "'allEvents'", ":", "allEvents", ",", "'openEvents'", ":", "openEvents", ",", "'closedEvents'", ":", "closedEvents", ",", "'publicEvents'", ":", "publicEvents", ",", "'allSeries'", ":", "allSeries", ",", "'regOpenEvents'", ":", "publicEvents", ".", "filter", "(", "registrationOpen", "=", "True", ")", ".", "filter", "(", "Q", "(", "publicevent__category__isnull", "=", "True", ")", "|", "Q", "(", "publicevent__category__separateOnRegistrationPage", "=", "False", ")", ")", ",", "'regClosedEvents'", ":", "publicEvents", ".", "filter", "(", "registrationOpen", "=", "False", ")", ".", "filter", "(", "Q", "(", "publicevent__category__isnull", "=", "True", ")", "|", "Q", "(", "publicevent__category__separateOnRegistrationPage", "=", "False", ")", ")", ",", "'categorySeparateEvents'", ":", "publicEvents", ".", "filter", "(", "publicevent__category__separateOnRegistrationPage", "=", "True", ")", ".", "order_by", "(", "'publicevent__category'", ")", ",", "'regOpenSeries'", ":", "allSeries", ".", "filter", "(", "registrationOpen", "=", "True", ")", ".", "filter", "(", "Q", "(", "series__category__isnull", "=", "True", ")", "|", "Q", "(", "series__category__separateOnRegistrationPage", "=", "False", ")", ")", ",", "'regClosedSeries'", ":", "allSeries", ".", "filter", "(", "registrationOpen", "=", "False", ")", ".", "filter", "(", "Q", "(", "series__category__isnull", "=", "True", ")", "|", "Q", "(", "series__category__separateOnRegistrationPage", "=", "False", ")", ")", ",", "'categorySeparateSeries'", ":", "allSeries", ".", "filter", "(", "series__category__separateOnRegistrationPage", "=", "True", ")", ".", "order_by", "(", "'series__category'", ")", ",", "}", "return", "self", ".", "listing" ]
Returns True if the passed address is valid False otherwise .
def validateaddress ( self , address : str ) -> bool : try : Address . from_string ( address , self . network_properties ) except InvalidAddress : return False return True
5,876
https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/provider/common.py#L116-L124
[ "def", "unpack_rawr_zip_payload", "(", "table_sources", ",", "payload", ")", ":", "# the io we get from S3 is streaming, so we can't seek on it, but zipfile", "# seems to require that. so we buffer it all in memory. RAWR tiles are", "# generally up to around 100MB in size, which should be safe to store in", "# RAM.", "from", "tilequeue", ".", "query", ".", "common", "import", "Table", "from", "io", "import", "BytesIO", "zfh", "=", "zipfile", ".", "ZipFile", "(", "BytesIO", "(", "payload", ")", ",", "'r'", ")", "def", "get_table", "(", "table_name", ")", ":", "# need to extract the whole compressed file from zip reader, as it", "# doesn't support .tell() on the filelike, which gzip requires.", "data", "=", "zfh", ".", "open", "(", "table_name", ",", "'r'", ")", ".", "read", "(", ")", "unpacker", "=", "Unpacker", "(", "file_like", "=", "BytesIO", "(", "data", ")", ")", "source", "=", "table_sources", "[", "table_name", "]", "return", "Table", "(", "source", ",", "unpacker", ")", "return", "get_table" ]
Generates n - sized chunks from the list l
def chunker ( l , n ) : for i in ranger ( 0 , len ( l ) , n ) : yield l [ i : i + n ]
5,877
https://github.com/bennylope/smartystreets.py/blob/f45e37dd52ea7cec8ed43ce2b64724beb6dbbb69/smartystreets/async.py#L24-L29
[ "def", "RunValidationOutputToConsole", "(", "feed", ",", "options", ")", ":", "accumulator", "=", "CountingConsoleProblemAccumulator", "(", "options", ".", "error_types_ignore_list", ")", "problems", "=", "transitfeed", ".", "ProblemReporter", "(", "accumulator", ")", "_", ",", "exit_code", "=", "RunValidation", "(", "feed", ",", "options", ",", "problems", ")", "return", "exit_code" ]
Executes most of the request .
def post ( self , endpoint , data , parallelism = 5 ) : headers = { "Content-Type" : "application/json" , "Accept" : "application/json" , "x-standardize-only" : "true" if self . standardize else "false" , "x-include-invalid" : "true" if self . invalid else "false" , "x-accept-keypair" : "true" if self . accept_keypair else "false" , } if not self . logging : headers [ "x-suppress-logging" ] = "false" params = { "auth-id" : self . auth_id , "auth-token" : self . auth_token } url = self . BASE_URL + endpoint rs = ( grequests . post ( url = url , data = json . dumps ( stringify ( data_chunk ) ) , params = params , headers = headers , ) for data_chunk in chunker ( data , 100 ) ) responses = grequests . imap ( rs , size = parallelism ) status_codes = { } addresses = AddressCollection ( [ ] ) for response in responses : if response . status_code not in status_codes . keys ( ) : status_codes [ response . status_code ] = 1 else : status_codes [ response . status_code ] += 1 if response . status_code == 200 : addresses [ 0 : 0 ] = AddressCollection ( response . json ( ) ) # Fast list insertion # If an auth error is raised, it's safe to say that this is # going to affect every request, so raise the exception immediately.. elif response . status_code == 401 : raise ERROR_CODES [ 401 ] # The return value or exception is simple if it is consistent. if len ( status_codes . keys ( ) ) == 1 : if 200 in status_codes : return addresses , status_codes else : raise ERROR_CODES . get ( status_codes . keys ( ) [ 0 ] , SmartyStreetsError ) # For any other mix not really sure of the best way to handle it. If it's a mix of 200 # and error codes, then returning the resultant addresses and status code dictionary # seems pretty sensible. But if it's a mix of all error codes (could be a mix of payment # error, input error, potentially server error) this will probably require careful # checking in the code using this interface. return addresses , status_codes
5,878
https://github.com/bennylope/smartystreets.py/blob/f45e37dd52ea7cec8ed43ce2b64724beb6dbbb69/smartystreets/async.py#L52-L120
[ "def", "materialize", "(", "self", ",", "ref", ",", "table_name", "=", "None", ",", "index_columns", "=", "None", ",", "logger", "=", "None", ")", ":", "from", "ambry", ".", "library", "import", "Library", "assert", "isinstance", "(", "self", ".", "_library", ",", "Library", ")", "logger", ".", "debug", "(", "'Materializing warehouse partition.\\n partition: {}'", ".", "format", "(", "ref", ")", ")", "partition", "=", "self", ".", "_library", ".", "partition", "(", "ref", ")", "connection", "=", "self", ".", "_backend", ".", "_get_connection", "(", ")", "return", "self", ".", "_backend", ".", "install", "(", "connection", ",", "partition", ",", "table_name", "=", "table_name", ",", "index_columns", "=", "index_columns", ",", "materialize", "=", "True", ",", "logger", "=", "logger", ")" ]
Initializes local cache from Django cache .
def _cache_init ( self ) : cache_ = cache . get ( self . CACHE_KEY ) if cache_ is None : cache_ = defaultdict ( dict ) self . _cache = cache_
5,879
https://github.com/idlesign/django-siteblocks/blob/7fdb3800f7330dd4143d55416393d83d01a09f73/siteblocks/siteblocksapp.py#L92-L97
[ "def", "open", "(", "self", ",", "file_path", ")", ":", "if", "self", ".", "is_opened", "(", ")", "and", "self", ".", "workbook", ".", "file_path", "==", "file_path", ":", "self", ".", "_logger", ".", "logger", ".", "debug", "(", "\"workbook already opened: {}\"", ".", "format", "(", "self", ".", "workbook", ".", "file_path", ")", ")", "return", "self", ".", "close", "(", ")", "self", ".", "_open", "(", "file_path", ")" ]
Returns contents of a static block .
def get_contents_static ( self , block_alias , context ) : if 'request' not in context : # No use in further actions as we won't ever know current URL. return '' current_url = context [ 'request' ] . path # Resolve current view name to support view names as block URLs. try : resolver_match = resolve ( current_url ) namespace = '' if resolver_match . namespaces : # More than one namespace, really? Hmm. namespace = resolver_match . namespaces [ 0 ] resolved_view_name = ':%s:%s' % ( namespace , resolver_match . url_name ) except Resolver404 : resolved_view_name = None self . _cache_init ( ) cache_entry_name = cache_get_key ( block_alias ) siteblocks_static = self . _cache_get ( cache_entry_name ) if not siteblocks_static : blocks = Block . objects . filter ( alias = block_alias , hidden = False ) . only ( 'url' , 'contents' ) siteblocks_static = [ defaultdict ( list ) , defaultdict ( list ) ] for block in blocks : if block . url == '*' : url_re = block . url elif block . url . startswith ( ':' ) : url_re = block . url # Normalize URL name to include namespace. if url_re . count ( ':' ) == 1 : url_re = ':%s' % url_re else : url_re = re . compile ( r'%s' % block . url ) if block . access_guest : siteblocks_static [ self . IDX_GUEST ] [ url_re ] . append ( block . contents ) elif block . access_loggedin : siteblocks_static [ self . IDX_AUTH ] [ url_re ] . append ( block . contents ) else : siteblocks_static [ self . IDX_GUEST ] [ url_re ] . append ( block . contents ) siteblocks_static [ self . IDX_AUTH ] [ url_re ] . append ( block . contents ) self . _cache_set ( cache_entry_name , siteblocks_static ) self . _cache_save ( ) user = getattr ( context [ 'request' ] , 'user' , None ) is_authenticated = getattr ( user , 'is_authenticated' , False ) if not DJANGO_2 : is_authenticated = is_authenticated ( ) if is_authenticated : lookup_area = siteblocks_static [ self . IDX_AUTH ] else : lookup_area = siteblocks_static [ self . IDX_GUEST ] static_block_contents = '' if '*' in lookup_area : static_block_contents = choice ( lookup_area [ '*' ] ) elif resolved_view_name in lookup_area : static_block_contents = choice ( lookup_area [ resolved_view_name ] ) else : for url , contents in lookup_area . items ( ) : if url . match ( current_url ) : static_block_contents = choice ( contents ) break return static_block_contents
5,880
https://github.com/idlesign/django-siteblocks/blob/7fdb3800f7330dd4143d55416393d83d01a09f73/siteblocks/siteblocksapp.py#L114-L188
[ "def", "url_to_resource", "(", "url", ",", "request", "=", "None", ")", ":", "if", "request", "is", "None", ":", "request", "=", "get_current_request", "(", ")", "# cnv = request.registry.getAdapter(request, IResourceUrlConverter)", "reg", "=", "get_current_registry", "(", ")", "cnv", "=", "reg", ".", "getAdapter", "(", "request", ",", "IResourceUrlConverter", ")", "return", "cnv", ".", "url_to_resource", "(", "url", ")" ]
Returns contents of a dynamic block .
def get_contents_dynamic ( self , block_alias , context ) : dynamic_block = get_dynamic_blocks ( ) . get ( block_alias , [ ] ) if not dynamic_block : return '' dynamic_block = choice ( dynamic_block ) return dynamic_block ( block_alias = block_alias , block_context = context )
5,881
https://github.com/idlesign/django-siteblocks/blob/7fdb3800f7330dd4143d55416393d83d01a09f73/siteblocks/siteblocksapp.py#L190-L197
[ "def", "url_to_resource", "(", "url", ",", "request", "=", "None", ")", ":", "if", "request", "is", "None", ":", "request", "=", "get_current_request", "(", ")", "# cnv = request.registry.getAdapter(request, IResourceUrlConverter)", "reg", "=", "get_current_registry", "(", ")", "cnv", "=", "reg", ".", "getAdapter", "(", "request", ",", "IResourceUrlConverter", ")", "return", "cnv", ".", "url_to_resource", "(", "url", ")" ]
Hash a set of leaves representing a valid full tree .
def hash_full_tree ( self , leaves ) : root_hash , hashes = self . _hash_full ( leaves , 0 , len ( leaves ) ) assert len ( hashes ) == count_bits_set ( len ( leaves ) ) assert ( self . _hash_fold ( hashes ) == root_hash if hashes else root_hash == self . hash_empty ( ) ) return root_hash
5,882
https://github.com/hyperledger-archives/indy-ledger/blob/7210c3b288e07f940eddad09b1dfc6a56be846df/ledger/tree_hasher.py#L63-L69
[ "def", "_sync_last_sale_prices", "(", "self", ",", "dt", "=", "None", ")", ":", "if", "dt", "is", "None", ":", "dt", "=", "self", ".", "datetime", "if", "dt", "!=", "self", ".", "_last_sync_time", ":", "self", ".", "metrics_tracker", ".", "sync_last_sale_prices", "(", "dt", ",", "self", ".", "data_portal", ",", ")", "self", ".", "_last_sync_time", "=", "dt" ]
Calculate model performance indexes .
def cal_model_performance ( obsl , siml ) : nse = MathClass . nashcoef ( obsl , siml ) r2 = MathClass . rsquare ( obsl , siml ) rmse = MathClass . rmse ( obsl , siml ) pbias = MathClass . pbias ( obsl , siml ) rsr = MathClass . rsr ( obsl , siml ) print ( 'NSE: %.2f, R-square: %.2f, PBIAS: %.2f%%, RMSE: %.2f, RSR: %.2f' % ( nse , r2 , pbias , rmse , rsr ) )
5,883
https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/examples/ex06_model_performace_index.py#L7-L15
[ "def", "_update_secret", "(", "namespace", ",", "name", ",", "data", ",", "apiserver_url", ")", ":", "# Prepare URL", "url", "=", "\"{0}/api/v1/namespaces/{1}/secrets/{2}\"", ".", "format", "(", "apiserver_url", ",", "namespace", ",", "name", ")", "# Prepare data", "data", "=", "[", "{", "\"op\"", ":", "\"replace\"", ",", "\"path\"", ":", "\"/data\"", ",", "\"value\"", ":", "data", "}", "]", "# Make request", "ret", "=", "_kpatch", "(", "url", ",", "data", ")", "if", "ret", ".", "get", "(", "\"status\"", ")", "==", "404", ":", "return", "\"Node {0} doesn't exist\"", ".", "format", "(", "url", ")", "return", "ret" ]
Loads all the known features from the feature service
def load_features ( self ) : # Loading all loci that # are in self.loci variable defined # when the pyGFE object is created for loc in self . loci : if self . verbose : self . logger . info ( self . logname + "Loading features for " + loc ) # Loading all features for loc from feature service self . all_feats . update ( { loc : self . locus_features ( loc ) } ) if self . verbose : self . logger . info ( self . logname + "Finished loading features for " + loc ) if self . verbose : mem = "{:4.4f}" . format ( sys . getsizeof ( self . all_feats ) / 1000000 ) self . logger . info ( self . logname + "Finished loading all features * all_feats = " + mem + " MB *" )
5,884
https://github.com/nmdp-bioinformatics/SeqAnn/blob/5ce91559b0a4fbe4fb7758e034eb258202632463/seqann/gfe.py#L100-L119
[ "def", "where", "(", "self", ",", "cond", ",", "other", ",", "*", "*", "kwargs", ")", ":", "assert", "isinstance", "(", "cond", ",", "type", "(", "self", ")", ")", ",", "\"Must have the same DataManager subclass to perform this operation\"", "if", "isinstance", "(", "other", ",", "type", "(", "self", ")", ")", ":", "# Note: Currently we are doing this with two maps across the entire", "# data. This can be done with a single map, but it will take a", "# modification in the `BlockPartition` class.", "# If this were in one pass it would be ~2x faster.", "# TODO (devin-petersohn) rewrite this to take one pass.", "def", "where_builder_first_pass", "(", "cond", ",", "other", ",", "*", "*", "kwargs", ")", ":", "return", "cond", ".", "where", "(", "cond", ",", "other", ",", "*", "*", "kwargs", ")", "def", "where_builder_second_pass", "(", "df", ",", "new_other", ",", "*", "*", "kwargs", ")", ":", "return", "df", ".", "where", "(", "new_other", ".", "eq", "(", "True", ")", ",", "new_other", ",", "*", "*", "kwargs", ")", "first_pass", "=", "cond", ".", "_inter_manager_operations", "(", "other", ",", "\"left\"", ",", "where_builder_first_pass", ")", "final_pass", "=", "self", ".", "_inter_manager_operations", "(", "first_pass", ",", "\"left\"", ",", "where_builder_second_pass", ")", "return", "self", ".", "__constructor__", "(", "final_pass", ".", "data", ",", "self", ".", "index", ",", "self", ".", "columns", ")", "else", ":", "axis", "=", "kwargs", ".", "get", "(", "\"axis\"", ",", "0", ")", "# Rather than serializing and passing in the index/columns, we will", "# just change this index to match the internal index.", "if", "isinstance", "(", "other", ",", "pandas", ".", "Series", ")", ":", "other", ".", "index", "=", "pandas", ".", "RangeIndex", "(", "len", "(", "other", ".", "index", ")", ")", "def", "where_builder_series", "(", "df", ",", "cond", ")", ":", "if", "axis", "==", "0", ":", "df", ".", "index", "=", "pandas", ".", "RangeIndex", "(", "len", "(", "df", ".", "index", ")", ")", "cond", ".", "index", "=", "pandas", ".", "RangeIndex", "(", "len", "(", "cond", ".", "index", ")", ")", "else", ":", "df", ".", "columns", "=", "pandas", ".", "RangeIndex", "(", "len", "(", "df", ".", "columns", ")", ")", "cond", ".", "columns", "=", "pandas", ".", "RangeIndex", "(", "len", "(", "cond", ".", "columns", ")", ")", "return", "df", ".", "where", "(", "cond", ",", "other", ",", "*", "*", "kwargs", ")", "reindexed_self", ",", "reindexed_cond", ",", "a", "=", "self", ".", "copartition", "(", "axis", ",", "cond", ",", "\"left\"", ",", "False", ")", "# Unwrap from list given by `copartition`", "reindexed_cond", "=", "reindexed_cond", "[", "0", "]", "new_data", "=", "reindexed_self", ".", "inter_data_operation", "(", "axis", ",", "lambda", "l", ",", "r", ":", "where_builder_series", "(", "l", ",", "r", ")", ",", "reindexed_cond", ")", "return", "self", ".", "__constructor__", "(", "new_data", ",", "self", ".", "index", ",", "self", ".", "columns", ")" ]
Returns all features associated with a locus
def locus_features ( self , locus ) : features = self . api . list_features ( locus = locus ) feat_dict = { ":" . join ( [ a . locus , str ( a . rank ) , a . term , a . sequence ] ) : a . accession for a in features } return feat_dict
5,885
https://github.com/nmdp-bioinformatics/SeqAnn/blob/5ce91559b0a4fbe4fb7758e034eb258202632463/seqann/gfe.py#L121-L131
[ "def", "_read_config_file", "(", "args", ")", ":", "stage", "=", "args", ".", "stage", "with", "open", "(", "args", ".", "config", ",", "'rt'", ")", "as", "f", ":", "config", "=", "yaml", ".", "safe_load", "(", "f", ".", "read", "(", ")", ")", "STATE", "[", "'stages'", "]", "=", "config", "[", "'stages'", "]", "config", "[", "'config'", "]", "=", "_decrypt_item", "(", "config", "[", "'config'", "]", ",", "stage", "=", "stage", ",", "key", "=", "''", ",", "render", "=", "True", ")", "return", "config", "[", "'stages'", "]", ",", "config", "[", "'config'", "]" ]
Process a tar file that contains DFT data .
def tarfile_to_pif ( filename , temp_root_dir = '' , verbose = 0 ) : temp_dir = temp_root_dir + str ( uuid . uuid4 ( ) ) os . makedirs ( temp_dir ) try : tar = tarfile . open ( filename , 'r' ) tar . extractall ( path = temp_dir ) tar . close ( ) for i in os . listdir ( temp_dir ) : cur_dir = temp_dir + '/' + i if os . path . isdir ( cur_dir ) : return directory_to_pif ( cur_dir , verbose = verbose ) return directory_to_pif ( temp_dir , verbose = verbose ) finally : shutil . rmtree ( temp_dir )
5,886
https://github.com/CitrineInformatics/pif-dft/blob/d5411dc1f6c6e8d454b132977ca7ab3bb8131a80/dfttopif/drivers.py#L59-L84
[ "def", "add_notification_listener", "(", "self", ",", "notification_type", ",", "notification_callback", ")", ":", "if", "notification_type", "not", "in", "self", ".", "notifications", ":", "self", ".", "notifications", "[", "notification_type", "]", "=", "[", "(", "self", ".", "notification_id", ",", "notification_callback", ")", "]", "else", ":", "if", "reduce", "(", "lambda", "a", ",", "b", ":", "a", "+", "1", ",", "filter", "(", "lambda", "tup", ":", "tup", "[", "1", "]", "==", "notification_callback", ",", "self", ".", "notifications", "[", "notification_type", "]", ")", ",", "0", ")", ">", "0", ":", "return", "-", "1", "self", ".", "notifications", "[", "notification_type", "]", ".", "append", "(", "(", "self", ".", "notification_id", ",", "notification_callback", ")", ")", "ret_val", "=", "self", ".", "notification_id", "self", ".", "notification_id", "+=", "1", "return", "ret_val" ]
Given a archive file that contains output from a DFT calculation parse the data and return a PIF object .
def archive_to_pif ( filename , verbose = 0 ) : if tarfile . is_tarfile ( filename ) : return tarfile_to_pif ( filename , verbose ) raise Exception ( 'Cannot process file type' )
5,887
https://github.com/CitrineInformatics/pif-dft/blob/d5411dc1f6c6e8d454b132977ca7ab3bb8131a80/dfttopif/drivers.py#L87-L101
[ "def", "break_bond", "(", "self", ",", "ind1", ",", "ind2", ",", "tol", "=", "0.2", ")", ":", "sites", "=", "self", ".", "_sites", "clusters", "=", "[", "[", "sites", "[", "ind1", "]", "]", ",", "[", "sites", "[", "ind2", "]", "]", "]", "sites", "=", "[", "site", "for", "i", ",", "site", "in", "enumerate", "(", "sites", ")", "if", "i", "not", "in", "(", "ind1", ",", "ind2", ")", "]", "def", "belongs_to_cluster", "(", "site", ",", "cluster", ")", ":", "for", "test_site", "in", "cluster", ":", "if", "CovalentBond", ".", "is_bonded", "(", "site", ",", "test_site", ",", "tol", "=", "tol", ")", ":", "return", "True", "return", "False", "while", "len", "(", "sites", ")", ">", "0", ":", "unmatched", "=", "[", "]", "for", "site", "in", "sites", ":", "for", "cluster", "in", "clusters", ":", "if", "belongs_to_cluster", "(", "site", ",", "cluster", ")", ":", "cluster", ".", "append", "(", "site", ")", "break", "else", ":", "unmatched", ".", "append", "(", "site", ")", "if", "len", "(", "unmatched", ")", "==", "len", "(", "sites", ")", ":", "raise", "ValueError", "(", "\"Not all sites are matched!\"", ")", "sites", "=", "unmatched", "return", "(", "self", ".", "__class__", ".", "from_sites", "(", "cluster", ")", "for", "cluster", "in", "clusters", ")" ]
Given a directory that contains output from a DFT calculation parse the data and return a pif object
def files_to_pif ( files , verbose = 0 , quality_report = True , inline = True ) : # Look for the first parser compatible with the directory found_parser = False for possible_parser in [ PwscfParser , VaspParser ] : try : parser = possible_parser ( files ) found_parser = True break except InvalidIngesterException : # Constructors fail when they cannot find appropriate files pass if not found_parser : raise Exception ( 'Directory is not in correct format for an existing parser' ) if verbose > 0 : print ( "Found a {} directory" . format ( parser . get_name ( ) ) ) # Get information about the chemical system chem = ChemicalSystem ( ) chem . chemical_formula = parser . get_composition ( ) # Get software information, to list as method software = Software ( name = parser . get_name ( ) , version = parser . get_version_number ( ) ) # Define the DFT method object method = Method ( name = 'Density Functional Theory' , software = [ software ] ) # Get the settings (aka. "conditions") of the DFT calculations conditions = [ ] for name , func in parser . get_setting_functions ( ) . items ( ) : # Get the condition cond = getattr ( parser , func ) ( ) # If the condition is None or False, skip it if cond is None : continue if inline and cond . files is not None : continue # Set the name cond . name = name # Set the types conditions . append ( cond ) # Get the properties of the system chem . properties = [ ] for name , func in parser . get_result_functions ( ) . items ( ) : # Get the property prop = getattr ( parser , func ) ( ) # If the property is None, skip it if prop is None : continue if inline and prop . files is not None : continue # Add name and other data prop . name = name prop . methods = [ method , ] prop . data_type = 'COMPUTATIONAL' if verbose > 0 and isinstance ( prop , Value ) : print ( name ) if prop . conditions is None : prop . conditions = conditions else : if not isinstance ( prop . conditions , list ) : prop . conditions = [ prop . conditions ] prop . conditions . extend ( conditions ) # Add it to the output chem . properties . append ( prop ) # Check to see if we should add the quality report if quality_report and isinstance ( parser , VaspParser ) : _add_quality_report ( parser , chem ) return chem
5,888
https://github.com/CitrineInformatics/pif-dft/blob/d5411dc1f6c6e8d454b132977ca7ab3bb8131a80/dfttopif/drivers.py#L104-L197
[ "def", "_add_column", "(", "self", ",", "label", ",", "field", ")", ":", "# Don't call this directly.", "assert", "self", ".", "headers", "is", "not", "None", "cols", "=", "0", "if", "len", "(", "self", ".", "_headers", ")", ">", "0", ":", "cols", "=", "max", "(", "[", "int", "(", "c", ".", "cell", ".", "col", ")", "for", "c", "in", "self", ".", "_headers", "]", ")", "new_col", "=", "cols", "+", "1", "if", "int", "(", "self", ".", "_ws", ".", "col_count", ".", "text", ")", "<", "new_col", ":", "self", ".", "_ws", ".", "col_count", ".", "text", "=", "str", "(", "new_col", ")", "self", ".", "_update_metadata", "(", ")", "cell", "=", "self", ".", "_service", ".", "UpdateCell", "(", "1", ",", "new_col", ",", "label", ",", "self", ".", "_ss", ".", "id", ",", "self", ".", "id", ")", "self", ".", "_headers", ".", "append", "(", "cell", ")" ]
Sleep on a loop until we see a confirmation of the transaction .
def wait_for_confirmation ( provider , transaction_id ) : while ( True ) : transaction = provider . gettransaction ( transaction_id ) if transaction [ "confirmations" ] > 0 : break time . sleep ( 10 )
5,889
https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/examples/once_issue_mode_example.py#L51-L57
[ "def", "revoke_local_roles_for", "(", "brain_or_object", ",", "roles", ",", "user", "=", "None", ")", ":", "user_id", "=", "get_user_id", "(", "user", ")", "obj", "=", "api", ".", "get_object", "(", "brain_or_object", ")", "valid_roles", "=", "get_valid_roles_for", "(", "obj", ")", "to_grant", "=", "list", "(", "get_local_roles_for", "(", "obj", ")", ")", "if", "isinstance", "(", "roles", ",", "basestring", ")", ":", "roles", "=", "[", "roles", "]", "for", "role", "in", "roles", ":", "if", "role", "in", "to_grant", ":", "if", "role", "not", "in", "valid_roles", ":", "raise", "ValueError", "(", "\"The Role '{}' is invalid.\"", ".", "format", "(", "role", ")", ")", "# Remove the role", "to_grant", ".", "remove", "(", "role", ")", "if", "len", "(", "to_grant", ")", ">", "0", ":", "obj", ".", "manage_setLocalRoles", "(", "user_id", ",", "to_grant", ")", "else", ":", "obj", ".", "manage_delLocalRoles", "(", "[", "user_id", "]", ")", "return", "get_local_roles_for", "(", "brain_or_object", ")" ]
validate cards against deck_issue modes
def validate_card_issue_modes ( issue_mode : int , cards : list ) -> list : supported_mask = 63 # sum of all issue_mode values if not bool ( issue_mode & supported_mask ) : return [ ] # return empty list for i in [ 1 << x for x in range ( len ( IssueMode ) ) ] : if bool ( i & issue_mode ) : try : parser_fn = cast ( Callable [ [ list ] , Optional [ list ] ] , parsers [ IssueMode ( i ) . name ] ) except ValueError : continue parsed_cards = parser_fn ( cards ) if not parsed_cards : return [ ] cards = parsed_cards return cards
5,890
https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/protocol.py#L365-L389
[ "def", "connected", "(", "self", ",", "client", ")", ":", "self", ".", "clients", ".", "add", "(", "client", ")", "self", ".", "_log_connected", "(", "client", ")", "self", ".", "_start_watching", "(", "client", ")", "self", ".", "send_msg", "(", "client", ",", "WELCOME", ",", "(", "self", ".", "pickle_protocol", ",", "__version__", ")", ",", "pickle_protocol", "=", "0", ")", "profiler", "=", "self", ".", "profiler", "while", "True", ":", "try", ":", "profiler", "=", "profiler", ".", "profiler", "except", "AttributeError", ":", "break", "self", ".", "send_msg", "(", "client", ",", "PROFILER", ",", "type", "(", "profiler", ")", ")", "if", "self", ".", "_latest_result_data", "is", "not", "None", ":", "try", ":", "self", ".", "_send", "(", "client", ",", "self", ".", "_latest_result_data", ")", "except", "socket", ".", "error", "as", "exc", ":", "if", "exc", ".", "errno", "in", "(", "EBADF", ",", "EPIPE", ")", ":", "self", ".", "disconnected", "(", "client", ")", "return", "raise", "if", "len", "(", "self", ".", "clients", ")", "==", "1", ":", "self", ".", "_start_profiling", "(", ")" ]
P2TH address of this deck
def p2th_address ( self ) -> Optional [ str ] : if self . id : return Kutil ( network = self . network , privkey = bytearray . fromhex ( self . id ) ) . address else : return None
5,891
https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/protocol.py#L89-L96
[ "def", "ProcessResponse", "(", "self", ",", "client_id", ",", "response", ")", ":", "precondition", ".", "AssertType", "(", "client_id", ",", "Text", ")", "downsampled", "=", "rdf_client_stats", ".", "ClientStats", ".", "Downsampled", "(", "response", ")", "if", "data_store", ".", "AFF4Enabled", "(", ")", ":", "urn", "=", "rdf_client", ".", "ClientURN", "(", "client_id", ")", ".", "Add", "(", "\"stats\"", ")", "with", "aff4", ".", "FACTORY", ".", "Create", "(", "urn", ",", "aff4_stats", ".", "ClientStats", ",", "token", "=", "self", ".", "token", ",", "mode", "=", "\"w\"", ")", "as", "stats_fd", ":", "# Only keep the average of all values that fall within one minute.", "stats_fd", ".", "AddAttribute", "(", "stats_fd", ".", "Schema", ".", "STATS", ",", "downsampled", ")", "if", "data_store", ".", "RelationalDBEnabled", "(", ")", ":", "data_store", ".", "REL_DB", ".", "WriteClientStats", "(", "client_id", ",", "downsampled", ")", "return", "downsampled" ]
P2TH privkey in WIF format
def p2th_wif ( self ) -> Optional [ str ] : if self . id : return Kutil ( network = self . network , privkey = bytearray . fromhex ( self . id ) ) . wif else : return None
5,892
https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/protocol.py#L99-L106
[ "def", "getErrorComponent", "(", "result", ",", "tag", ")", ":", "return", "math", ".", "sqrt", "(", "sum", "(", "(", "error", "*", "2", ")", "**", "2", "for", "(", "var", ",", "error", ")", "in", "result", ".", "error_components", "(", ")", ".", "items", "(", ")", "if", "var", ".", "tag", "==", "tag", ")", ")" ]
encode deck into dictionary
def metainfo_to_dict ( self ) -> dict : r = { "version" : self . version , "name" : self . name , "number_of_decimals" : self . number_of_decimals , "issue_mode" : self . issue_mode } if self . asset_specific_data : r . update ( { 'asset_specific_data' : self . asset_specific_data } ) return r
5,893
https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/protocol.py#L132-L145
[ "def", "connection", "(", "cls", ")", ":", "local", "=", "cls", ".", "_threadlocal", "if", "not", "getattr", "(", "local", ",", "'connection'", ",", "None", ")", ":", "# Make sure these variables are no longer affected by other threads.", "local", ".", "user", "=", "cls", ".", "user", "local", ".", "password", "=", "cls", ".", "password", "local", ".", "site", "=", "cls", ".", "site", "local", ".", "timeout", "=", "cls", ".", "timeout", "local", ".", "headers", "=", "cls", ".", "headers", "local", ".", "format", "=", "cls", ".", "format", "local", ".", "version", "=", "cls", ".", "version", "local", ".", "url", "=", "cls", ".", "url", "if", "cls", ".", "site", "is", "None", ":", "raise", "ValueError", "(", "\"No shopify session is active\"", ")", "local", ".", "connection", "=", "ShopifyConnection", "(", "cls", ".", "site", ",", "cls", ".", "user", ",", "cls", ".", "password", ",", "cls", ".", "timeout", ",", "cls", ".", "format", ")", "return", "local", ".", "connection" ]
export the Deck object to json - ready format
def to_json ( self ) -> dict : d = self . __dict__ d [ 'p2th_wif' ] = self . p2th_wif return d
5,894
https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/protocol.py#L147-L152
[ "def", "pop_no_diff_fields", "(", "latest_config", ",", "current_config", ")", ":", "for", "field", "in", "[", "'userIdentity'", ",", "'principalId'", ",", "'userAgent'", ",", "'sourceIpAddress'", ",", "'requestParameters'", ",", "'eventName'", "]", ":", "latest_config", ".", "pop", "(", "field", ",", "None", ")", "current_config", ".", "pop", "(", "field", ",", "None", ")" ]
encode card into dictionary
def metainfo_to_dict ( self ) -> dict : r = { "version" : self . version , "amount" : self . amount , "number_of_decimals" : self . number_of_decimals } if self . asset_specific_data : r . update ( { 'asset_specific_data' : self . asset_specific_data } ) return r
5,895
https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/protocol.py#L331-L343
[ "def", "_whiteNoise", "(", "self", ",", "size", ")", ":", "if", "self", ".", "noise", ">", "0.003921569", ":", "# 1./255.", "w", ",", "h", "=", "size", "pixel", "=", "(", "lambda", "noise", ":", "round", "(", "255", "*", "random", ".", "uniform", "(", "1", "-", "noise", ",", "1", ")", ")", ")", "n_image", "=", "Image", ".", "new", "(", "'RGB'", ",", "size", ",", "(", "0", ",", "0", ",", "0", ",", "0", ")", ")", "rnd_grid", "=", "map", "(", "lambda", "_", ":", "tuple", "(", "[", "pixel", "(", "self", ".", "noise", ")", "]", ")", "*", "3", ",", "[", "0", "]", "*", "w", "*", "h", ")", "n_image", ".", "putdata", "(", "list", "(", "rnd_grid", ")", ")", "return", "n_image", "else", ":", "return", "None" ]
sort cards by blocknum and blockseq
def _sort_cards ( self , cards : Generator ) -> list : return sorted ( [ card . __dict__ for card in cards ] , key = itemgetter ( 'blocknum' , 'blockseq' , 'cardseq' ) )
5,896
https://github.com/PeerAssets/pypeerassets/blob/8927b4a686887f44fe2cd9de777e2c827c948987/pypeerassets/protocol.py#L439-L443
[ "def", "unindex_layers_with_issues", "(", "self", ",", "use_cache", "=", "False", ")", ":", "from", "hypermap", ".", "aggregator", ".", "models", "import", "Issue", ",", "Layer", ",", "Service", "from", "django", ".", "contrib", ".", "contenttypes", ".", "models", "import", "ContentType", "layer_type", "=", "ContentType", ".", "objects", ".", "get_for_model", "(", "Layer", ")", "service_type", "=", "ContentType", ".", "objects", ".", "get_for_model", "(", "Service", ")", "for", "issue", "in", "Issue", ".", "objects", ".", "filter", "(", "content_type__pk", "=", "layer_type", ".", "id", ")", ":", "unindex_layer", "(", "issue", ".", "content_object", ".", "id", ",", "use_cache", ")", "for", "issue", "in", "Issue", ".", "objects", ".", "filter", "(", "content_type__pk", "=", "service_type", ".", "id", ")", ":", "for", "layer", "in", "issue", ".", "content_object", ".", "layer_set", ".", "all", "(", ")", ":", "unindex_layer", "(", "layer", ".", "id", ",", "use_cache", ")" ]
Read GeoTiff raster data and perform log transformation .
def main ( ) : input_tif = "../tests/data/Jamaica_dem.tif" output_tif = "../tests/data/tmp_results/log_dem.tif" rst = RasterUtilClass . read_raster ( input_tif ) # raster data (with noDataValue as numpy.nan) as numpy array rst_valid = rst . validValues output_data = np . log ( rst_valid ) # write output raster RasterUtilClass . write_gtiff_file ( output_tif , rst . nRows , rst . nCols , output_data , rst . geotrans , rst . srs , rst . noDataValue , rst . dataType )
5,897
https://github.com/lreis2415/PyGeoC/blob/9a92d1a229bb74298e3c57f27c97079980b5f729/examples/ex07_handling_raster_with_numpy.py#L10-L21
[ "def", "libvlc_vlm_set_loop", "(", "p_instance", ",", "psz_name", ",", "b_loop", ")", ":", "f", "=", "_Cfunctions", ".", "get", "(", "'libvlc_vlm_set_loop'", ",", "None", ")", "or", "_Cfunction", "(", "'libvlc_vlm_set_loop'", ",", "(", "(", "1", ",", ")", ",", "(", "1", ",", ")", ",", "(", "1", ",", ")", ",", ")", ",", "None", ",", "ctypes", ".", "c_int", ",", "Instance", ",", "ctypes", ".", "c_char_p", ",", "ctypes", ".", "c_int", ")", "return", "f", "(", "p_instance", ",", "psz_name", ",", "b_loop", ")" ]
return an instance of val that is of type datatype . keep track of exceptions so we can produce meaningful error messages .
def val_factory ( val , datatypes ) : exceptions = [ ] for dt in datatypes : try : if isinstance ( val , dt ) : return val return type_handler_object ( val , dt ) except Exception as e : exceptions . append ( str ( e ) ) # if we get here, we never found a valid value. raise an error raise ValueError ( 'val_factory: Unable to instantiate {val} from types {types}. Exceptions: {excs}' . format ( val = val , types = datatypes , excs = exceptions ) )
5,898
https://github.com/zero-os/zerotier_client/blob/03993da11e69d837a0308a2f41ae7b378692fd82/zerotier/client_support.py#L75-L90
[ "def", "merge_networks", "(", "output_file", "=", "\"merged_network.txt\"", ",", "*", "files", ")", ":", "contacts", "=", "dict", "(", ")", "for", "network_file", "in", "files", ":", "with", "open", "(", "network_file", ")", "as", "network_file_handle", ":", "for", "line", "in", "network_file_handle", ":", "id_a", ",", "id_b", ",", "n_contacts", "=", "line", ".", "split", "(", "\"\\t\"", ")", "pair", "=", "sorted", "(", "(", "id_a", ",", "id_b", ")", ")", "try", ":", "contacts", "[", "pair", "]", "+=", "n_contacts", "except", "KeyError", ":", "contacts", "[", "pair", "]", "=", "n_contacts", "sorted_contacts", "=", "sorted", "(", "contacts", ")", "with", "open", "(", "output_file", ",", "\"w\"", ")", "as", "output_handle", ":", "for", "index_pair", "in", "sorted_contacts", ":", "id_a", ",", "id_b", "=", "index_pair", "n_contacts", "=", "contacts", "[", "index_pair", "]", "output_handle", ".", "write", "(", "\"{}\\t{}\\t{}\\n\"", ".", "format", "(", "id_a", ",", "id_b", ",", "n_contacts", ")", ")" ]
return the handler for the object type
def handler_for ( obj ) : for handler_type in handlers : if isinstance ( obj , handler_type ) : return handlers [ handler_type ] try : for handler_type in handlers : if issubclass ( obj , handler_type ) : return handlers [ handler_type ] except TypeError : # if obj isn't a class, issubclass will raise a TypeError pass
5,899
https://github.com/zero-os/zerotier_client/blob/03993da11e69d837a0308a2f41ae7b378692fd82/zerotier/client_support.py#L189-L201
[ "def", "register_manifest", "(", "app", ",", "filename", "=", "'manifest.json'", ")", ":", "if", "current_app", ".", "config", ".", "get", "(", "'TESTING'", ")", ":", "return", "# Do not spend time here when testing", "if", "not", "has_manifest", "(", "app", ",", "filename", ")", ":", "msg", "=", "'{filename} not found for {app}'", ".", "format", "(", "*", "*", "locals", "(", ")", ")", "raise", "ValueError", "(", "msg", ")", "manifest", "=", "_manifests", ".", "get", "(", "app", ",", "{", "}", ")", "manifest", ".", "update", "(", "load_manifest", "(", "app", ",", "filename", ")", ")", "_manifests", "[", "app", "]", "=", "manifest" ]