query stringlengths 5 1.23k | positive stringlengths 53 15.2k | id_ int64 0 252k | task_name stringlengths 87 242 | negative listlengths 20 553 |
|---|---|---|---|---|
Add names to all of the Endpoint s Arguments . | def _fix_up_fields ( cls ) : cls . _arguments = dict ( ) if cls . __module__ == __name__ : # skip the classes in this file return for name in set ( dir ( cls ) ) : attr = getattr ( cls , name , None ) if isinstance ( attr , BaseArgument ) : if name . startswith ( '_' ) : raise TypeError ( "Endpoint argument %s cannot begin with " "an underscore, as these attributes are reserved " "for instance variables of the endpoint object, " "rather than for arguments to your HTTP Endpoint." % name ) attr . _fix_up ( cls , name ) cls . _arguments [ attr . name ] = attr | 8,100 | https://github.com/Loudr/pale/blob/dc002ee6032c856551143af222ff8f71ed9853fe/pale/endpoint.py#L68-L87 | [
"def",
"scrnaseq_concatenate_metadata",
"(",
"samples",
")",
":",
"barcodes",
"=",
"{",
"}",
"counts",
"=",
"\"\"",
"metadata",
"=",
"{",
"}",
"has_sample_barcodes",
"=",
"False",
"for",
"sample",
"in",
"dd",
".",
"sample_data_iterator",
"(",
"samples",
")",
":",
"if",
"dd",
".",
"get_sample_barcodes",
"(",
"sample",
")",
":",
"has_sample_barcodes",
"=",
"True",
"with",
"open",
"(",
"dd",
".",
"get_sample_barcodes",
"(",
"sample",
")",
")",
"as",
"inh",
":",
"for",
"line",
"in",
"inh",
":",
"cols",
"=",
"line",
".",
"strip",
"(",
")",
".",
"split",
"(",
"\",\"",
")",
"if",
"len",
"(",
"cols",
")",
"==",
"1",
":",
"# Assign sample name in case of missing in barcodes",
"cols",
".",
"append",
"(",
"\"NaN\"",
")",
"barcodes",
"[",
"(",
"dd",
".",
"get_sample_name",
"(",
"sample",
")",
",",
"cols",
"[",
"0",
"]",
")",
"]",
"=",
"cols",
"[",
"1",
":",
"]",
"else",
":",
"barcodes",
"[",
"(",
"dd",
".",
"get_sample_name",
"(",
"sample",
")",
",",
"\"NaN\"",
")",
"]",
"=",
"[",
"dd",
".",
"get_sample_name",
"(",
"sample",
")",
",",
"\"NaN\"",
"]",
"counts",
"=",
"dd",
".",
"get_combined_counts",
"(",
"sample",
")",
"meta",
"=",
"map",
"(",
"str",
",",
"list",
"(",
"sample",
"[",
"\"metadata\"",
"]",
".",
"values",
"(",
")",
")",
")",
"meta_cols",
"=",
"list",
"(",
"sample",
"[",
"\"metadata\"",
"]",
".",
"keys",
"(",
")",
")",
"meta",
"=",
"[",
"\"NaN\"",
"if",
"not",
"v",
"else",
"v",
"for",
"v",
"in",
"meta",
"]",
"metadata",
"[",
"dd",
".",
"get_sample_name",
"(",
"sample",
")",
"]",
"=",
"meta",
"metadata_fn",
"=",
"counts",
"+",
"\".metadata\"",
"if",
"file_exists",
"(",
"metadata_fn",
")",
":",
"return",
"samples",
"with",
"file_transaction",
"(",
"metadata_fn",
")",
"as",
"tx_metadata_fn",
":",
"with",
"open",
"(",
"tx_metadata_fn",
",",
"'w'",
")",
"as",
"outh",
":",
"outh",
".",
"write",
"(",
"\",\"",
".",
"join",
"(",
"[",
"\"sample\"",
"]",
"+",
"meta_cols",
")",
"+",
"'\\n'",
")",
"with",
"open",
"(",
"counts",
"+",
"\".colnames\"",
")",
"as",
"inh",
":",
"for",
"line",
"in",
"inh",
":",
"sample",
"=",
"line",
".",
"split",
"(",
"\":\"",
")",
"[",
"0",
"]",
"if",
"has_sample_barcodes",
":",
"barcode",
"=",
"sample",
".",
"split",
"(",
"\"-\"",
")",
"[",
"1",
"]",
"else",
":",
"barcode",
"=",
"\"NaN\"",
"outh",
".",
"write",
"(",
"\",\"",
".",
"join",
"(",
"barcodes",
"[",
"(",
"sample",
",",
"barcode",
")",
"]",
"+",
"metadata",
"[",
"sample",
"]",
")",
"+",
"'\\n'",
")",
"return",
"samples"
] |
The top - level execute function for the endpoint . | def _execute ( self , request , * * kwargs ) : try : self . _create_context ( request ) self . _authenticate ( ) context = get_current_context ( ) self . _parse_args ( ) if hasattr ( self , '_before_handlers' ) and isinstance ( self . _before_handlers , ( list , tuple ) ) : for handler in self . _before_handlers : handler ( context ) context . handler_result = self . _handle ( context ) if hasattr ( self , '_after_handlers' ) and isinstance ( self . _after_handlers , ( list , tuple ) ) : for handler in self . _after_handlers : handler ( context ) self . _render ( ) response = context . response # After calling ._render(), the response is ready to go, so we # shouldn't need to handle any other exceptions beyond this point. except AuthenticationError as e : if hasattr ( e , 'message' ) and e . message is not None : message = e . message else : message = "You don't have permission to do that." err = APIError . Forbidden ( message ) response = self . _response_class ( * err . response ) response . headers [ "Content-Type" ] = 'application/json' except ArgumentError as e : err = APIError . UnprocessableEntity ( e . message ) response = self . _response_class ( * err . response ) response . headers [ "Content-Type" ] = 'application/json' except APIError as e : response = self . _response_class ( * e . response ) response . headers [ "Content-Type" ] = 'application/json' except PaleRaisedResponse as r : response = self . _response_class ( * r . response ) response . headers [ "Content-Type" ] = 'application/json' except Exception as e : logging . exception ( "Failed to handle Pale Endpoint %s: %r" , self . __class__ . __name__ , e ) err = APIError . Exception ( repr ( e ) ) response = self . _response_class ( * err . response ) response . headers [ "Content-Type" ] = 'application/json' allow_cors = getattr ( self , "_allow_cors" , None ) if allow_cors is True : response . headers [ 'Access-Control-Allow-Origin' ] = '*' elif isinstance ( allow_cors , basestring ) : response . headers [ 'Access-Control-Allow-Origin' ] = allow_cors context . response = response try : if hasattr ( self , '_after_response_handlers' ) and isinstance ( self . _after_response_handlers , ( list , tuple ) ) : for handler in self . _after_response_handlers : handler ( context , response ) except Exception as e : logging . exception ( "Failed to process _after_response_handlers for Endpoint %s" , self . __class__ . __name__ ) raise return response | 8,101 | https://github.com/Loudr/pale/blob/dc002ee6032c856551143af222ff8f71ed9853fe/pale/endpoint.py#L122-L286 | [
"def",
"create_gtk_grid",
"(",
"self",
",",
"row_spacing",
"=",
"6",
",",
"col_spacing",
"=",
"6",
",",
"row_homogenous",
"=",
"False",
",",
"col_homogenous",
"=",
"True",
")",
":",
"grid_lang",
"=",
"Gtk",
".",
"Grid",
"(",
")",
"grid_lang",
".",
"set_column_spacing",
"(",
"row_spacing",
")",
"grid_lang",
".",
"set_row_spacing",
"(",
"col_spacing",
")",
"grid_lang",
".",
"set_border_width",
"(",
"12",
")",
"grid_lang",
".",
"set_row_homogeneous",
"(",
"row_homogenous",
")",
"grid_lang",
".",
"set_column_homogeneous",
"(",
"col_homogenous",
")",
"return",
"grid_lang"
] |
Constructs the Concierge Request Header lxml object to be used as the _soapheaders argument for WSDL methods . | def construct_concierge_header ( self , url ) : concierge_request_header = ( etree . Element ( etree . QName ( XHTML_NAMESPACE , "ConciergeRequestHeader" ) , nsmap = { 'sch' : XHTML_NAMESPACE } ) ) if self . session_id : session = ( etree . SubElement ( concierge_request_header , etree . QName ( XHTML_NAMESPACE , "SessionId" ) ) ) session . text = self . session_id access_key = ( etree . SubElement ( concierge_request_header , etree . QName ( XHTML_NAMESPACE , "AccessKeyId" ) ) ) access_key . text = self . access_key association_id = ( etree . SubElement ( concierge_request_header , etree . QName ( XHTML_NAMESPACE , "AssociationId" ) ) ) association_id . text = self . association_id signature = ( etree . SubElement ( concierge_request_header , etree . QName ( XHTML_NAMESPACE , "Signature" ) ) ) signature . text = self . get_hashed_signature ( url = url ) return concierge_request_header | 8,102 | https://github.com/AASHE/python-membersuite-api-client/blob/221f5ed8bc7d4424237a4669c5af9edc11819ee9/membersuite_api_client/client.py#L65-L96 | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"status",
":",
"self",
".",
"status",
"==",
"Event",
".",
"RegStatus",
".",
"hidden",
"super",
"(",
"PrivateLessonEvent",
",",
"self",
")",
".",
"save",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] |
Return arguments for CLI invocation of kal . | def options_string_builder ( option_mapping , args ) : options_string = "" for option , flag in option_mapping . items ( ) : if option in args : options_string += str ( " %s %s" % ( flag , str ( args [ option ] ) ) ) return options_string | 8,103 | https://github.com/ashmastaflash/kal-wrapper/blob/80ee03ab7bd3172ac26b769d6b442960f3424b0e/kalibrate/fn.py#L6-L12 | [
"def",
"showRejectionMessage",
"(",
"worksheet",
")",
":",
"if",
"hasattr",
"(",
"worksheet",
",",
"'replaced_by'",
")",
":",
"uc",
"=",
"getToolByName",
"(",
"worksheet",
",",
"'uid_catalog'",
")",
"uid",
"=",
"getattr",
"(",
"worksheet",
",",
"'replaced_by'",
")",
"_ws",
"=",
"uc",
"(",
"UID",
"=",
"uid",
")",
"[",
"0",
"]",
".",
"getObject",
"(",
")",
"msg",
"=",
"_",
"(",
"\"This worksheet has been rejected. The replacement worksheet is ${ws_id}\"",
",",
"mapping",
"=",
"{",
"'ws_id'",
":",
"_ws",
".",
"getId",
"(",
")",
"}",
")",
"worksheet",
".",
"plone_utils",
".",
"addPortalMessage",
"(",
"msg",
")",
"if",
"hasattr",
"(",
"worksheet",
",",
"'replaces_rejected_worksheet'",
")",
":",
"uc",
"=",
"getToolByName",
"(",
"worksheet",
",",
"'uid_catalog'",
")",
"uid",
"=",
"getattr",
"(",
"worksheet",
",",
"'replaces_rejected_worksheet'",
")",
"_ws",
"=",
"uc",
"(",
"UID",
"=",
"uid",
")",
"[",
"0",
"]",
".",
"getObject",
"(",
")",
"msg",
"=",
"_",
"(",
"\"This worksheet has been created to replace the rejected \"",
"\"worksheet at ${ws_id}\"",
",",
"mapping",
"=",
"{",
"'ws_id'",
":",
"_ws",
".",
"getId",
"(",
")",
"}",
")",
"worksheet",
".",
"plone_utils",
".",
"addPortalMessage",
"(",
"msg",
")"
] |
Return string for CLI invocation of kal for band scan . | def build_kal_scan_band_string ( kal_bin , band , args ) : option_mapping = { "gain" : "-g" , "device" : "-d" , "error" : "-e" } if not sanity . scan_band_is_valid ( band ) : err_txt = "Unsupported band designation: %" % band raise ValueError ( err_txt ) base_string = "%s -v -s %s" % ( kal_bin , band ) base_string += options_string_builder ( option_mapping , args ) return ( base_string ) | 8,104 | https://github.com/ashmastaflash/kal-wrapper/blob/80ee03ab7bd3172ac26b769d6b442960f3424b0e/kalibrate/fn.py#L15-L25 | [
"def",
"object_present",
"(",
"container",
",",
"name",
",",
"path",
",",
"profile",
")",
":",
"existing_object",
"=",
"__salt__",
"[",
"'libcloud_storage.get_container_object'",
"]",
"(",
"container",
",",
"name",
",",
"profile",
")",
"if",
"existing_object",
"is",
"not",
"None",
":",
"return",
"state_result",
"(",
"True",
",",
"\"Object already present\"",
",",
"name",
",",
"{",
"}",
")",
"else",
":",
"result",
"=",
"__salt__",
"[",
"'libcloud_storage.upload_object'",
"]",
"(",
"path",
",",
"container",
",",
"name",
",",
"profile",
")",
"return",
"state_result",
"(",
"result",
",",
"\"Uploaded object\"",
",",
"name",
",",
"{",
"}",
")"
] |
Return string for CLI invocation of kal for channel scan . | def build_kal_scan_channel_string ( kal_bin , channel , args ) : option_mapping = { "gain" : "-g" , "device" : "-d" , "error" : "-e" } base_string = "%s -v -c %s" % ( kal_bin , channel ) base_string += options_string_builder ( option_mapping , args ) return ( base_string ) | 8,105 | https://github.com/ashmastaflash/kal-wrapper/blob/80ee03ab7bd3172ac26b769d6b442960f3424b0e/kalibrate/fn.py#L28-L35 | [
"def",
"set_batch",
"(",
"self",
",",
"data",
")",
":",
"# fetch existing documents to get current revisions",
"rows",
"=",
"self",
".",
"bucket",
".",
"view",
"(",
"\"_all_docs\"",
",",
"keys",
"=",
"data",
".",
"keys",
"(",
")",
",",
"include_docs",
"=",
"True",
")",
"existing",
"=",
"{",
"}",
"for",
"row",
"in",
"rows",
":",
"key",
"=",
"row",
".",
"id",
"if",
"key",
"and",
"not",
"data",
"[",
"key",
"]",
".",
"has_key",
"(",
"\"_rev\"",
")",
":",
"data",
"[",
"key",
"]",
"[",
"\"_rev\"",
"]",
"=",
"row",
".",
"doc",
"[",
"\"_rev\"",
"]",
"for",
"id",
",",
"item",
"in",
"data",
".",
"items",
"(",
")",
":",
"data",
"[",
"id",
"]",
"[",
"\"_id\"",
"]",
"=",
"id",
"revs",
"=",
"{",
"}",
"for",
"success",
",",
"docid",
",",
"rev_or_exc",
"in",
"self",
".",
"bucket",
".",
"update",
"(",
"data",
".",
"values",
"(",
")",
")",
":",
"if",
"not",
"success",
"and",
"self",
".",
"logger",
":",
"self",
".",
"logger",
".",
"error",
"(",
"\"Document update conflict (batch) '%s', %s\"",
"%",
"(",
"docid",
",",
"rev_or_exc",
")",
")",
"elif",
"success",
":",
"revs",
"[",
"docid",
"]",
"=",
"rev_or_exc",
"return",
"revs"
] |
Return integer for frequency . | def determine_final_freq ( base , direction , modifier ) : result = 0 if direction == "+" : result = base + modifier elif direction == "-" : result = base - modifier return ( result ) | 8,106 | https://github.com/ashmastaflash/kal-wrapper/blob/80ee03ab7bd3172ac26b769d6b442960f3424b0e/kalibrate/fn.py#L55-L62 | [
"def",
"_create_download_failed_message",
"(",
"exception",
",",
"url",
")",
":",
"message",
"=",
"'Failed to download from:\\n{}\\nwith {}:\\n{}'",
".",
"format",
"(",
"url",
",",
"exception",
".",
"__class__",
".",
"__name__",
",",
"exception",
")",
"if",
"_is_temporal_problem",
"(",
"exception",
")",
":",
"if",
"isinstance",
"(",
"exception",
",",
"requests",
".",
"ConnectionError",
")",
":",
"message",
"+=",
"'\\nPlease check your internet connection and try again.'",
"else",
":",
"message",
"+=",
"'\\nThere might be a problem in connection or the server failed to process '",
"'your request. Please try again.'",
"elif",
"isinstance",
"(",
"exception",
",",
"requests",
".",
"HTTPError",
")",
":",
"try",
":",
"server_message",
"=",
"''",
"for",
"elem",
"in",
"decode_data",
"(",
"exception",
".",
"response",
".",
"content",
",",
"MimeType",
".",
"XML",
")",
":",
"if",
"'ServiceException'",
"in",
"elem",
".",
"tag",
"or",
"'Message'",
"in",
"elem",
".",
"tag",
":",
"server_message",
"+=",
"elem",
".",
"text",
".",
"strip",
"(",
"'\\n\\t '",
")",
"except",
"ElementTree",
".",
"ParseError",
":",
"server_message",
"=",
"exception",
".",
"response",
".",
"text",
"message",
"+=",
"'\\nServer response: \"{}\"'",
".",
"format",
"(",
"server_message",
")",
"return",
"message"
] |
Return number in engineering notation . | def to_eng ( num_in ) : x = decimal . Decimal ( str ( num_in ) ) eng_not = x . normalize ( ) . to_eng_string ( ) return ( eng_not ) | 8,107 | https://github.com/ashmastaflash/kal-wrapper/blob/80ee03ab7bd3172ac26b769d6b442960f3424b0e/kalibrate/fn.py#L65-L69 | [
"def",
"weighted_variance",
"(",
"image",
",",
"mask",
",",
"binary_image",
")",
":",
"if",
"not",
"np",
".",
"any",
"(",
"mask",
")",
":",
"return",
"0",
"#",
"# Clamp the dynamic range of the foreground",
"#",
"minval",
"=",
"np",
".",
"max",
"(",
"image",
"[",
"mask",
"]",
")",
"/",
"256",
"if",
"minval",
"==",
"0",
":",
"return",
"0",
"fg",
"=",
"np",
".",
"log2",
"(",
"np",
".",
"maximum",
"(",
"image",
"[",
"binary_image",
"&",
"mask",
"]",
",",
"minval",
")",
")",
"bg",
"=",
"np",
".",
"log2",
"(",
"np",
".",
"maximum",
"(",
"image",
"[",
"(",
"~",
"binary_image",
")",
"&",
"mask",
"]",
",",
"minval",
")",
")",
"nfg",
"=",
"np",
".",
"product",
"(",
"fg",
".",
"shape",
")",
"nbg",
"=",
"np",
".",
"product",
"(",
"bg",
".",
"shape",
")",
"if",
"nfg",
"==",
"0",
":",
"return",
"np",
".",
"var",
"(",
"bg",
")",
"elif",
"nbg",
"==",
"0",
":",
"return",
"np",
".",
"var",
"(",
"fg",
")",
"else",
":",
"return",
"(",
"np",
".",
"var",
"(",
"fg",
")",
"*",
"nfg",
"+",
"np",
".",
"var",
"(",
"bg",
")",
"*",
"nbg",
")",
"/",
"(",
"nfg",
"+",
"nbg",
")"
] |
Extract and return device from scan results . | def determine_device ( kal_out ) : device = "" while device == "" : for line in kal_out . splitlines ( ) : if "Using device " in line : device = str ( line . split ( ' ' , 2 ) [ - 1 ] ) if device == "" : device = None return device | 8,108 | https://github.com/ashmastaflash/kal-wrapper/blob/80ee03ab7bd3172ac26b769d6b442960f3424b0e/kalibrate/fn.py#L81-L90 | [
"def",
"guess_peb_size",
"(",
"path",
")",
":",
"file_offset",
"=",
"0",
"offsets",
"=",
"[",
"]",
"f",
"=",
"open",
"(",
"path",
",",
"'rb'",
")",
"f",
".",
"seek",
"(",
"0",
",",
"2",
")",
"file_size",
"=",
"f",
".",
"tell",
"(",
")",
"+",
"1",
"f",
".",
"seek",
"(",
"0",
")",
"for",
"_",
"in",
"range",
"(",
"0",
",",
"file_size",
",",
"FILE_CHUNK_SZ",
")",
":",
"buf",
"=",
"f",
".",
"read",
"(",
"FILE_CHUNK_SZ",
")",
"for",
"m",
"in",
"re",
".",
"finditer",
"(",
"UBI_EC_HDR_MAGIC",
",",
"buf",
")",
":",
"start",
"=",
"m",
".",
"start",
"(",
")",
"if",
"not",
"file_offset",
":",
"file_offset",
"=",
"start",
"idx",
"=",
"start",
"else",
":",
"idx",
"=",
"start",
"+",
"file_offset",
"offsets",
".",
"append",
"(",
"idx",
")",
"file_offset",
"+=",
"FILE_CHUNK_SZ",
"f",
".",
"close",
"(",
")",
"occurances",
"=",
"{",
"}",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"offsets",
")",
")",
":",
"try",
":",
"diff",
"=",
"offsets",
"[",
"i",
"]",
"-",
"offsets",
"[",
"i",
"-",
"1",
"]",
"except",
":",
"diff",
"=",
"offsets",
"[",
"i",
"]",
"if",
"diff",
"not",
"in",
"occurances",
":",
"occurances",
"[",
"diff",
"]",
"=",
"0",
"occurances",
"[",
"diff",
"]",
"+=",
"1",
"most_frequent",
"=",
"0",
"block_size",
"=",
"None",
"for",
"offset",
"in",
"occurances",
":",
"if",
"occurances",
"[",
"offset",
"]",
">",
"most_frequent",
":",
"most_frequent",
"=",
"occurances",
"[",
"offset",
"]",
"block_size",
"=",
"offset",
"return",
"block_size"
] |
Return value parsed from output . | def extract_value_from_output ( canary , split_offset , kal_out ) : retval = "" while retval == "" : for line in kal_out . splitlines ( ) : if canary in line : retval = str ( line . split ( ) [ split_offset ] ) if retval == "" : retval = None return retval | 8,109 | https://github.com/ashmastaflash/kal-wrapper/blob/80ee03ab7bd3172ac26b769d6b442960f3424b0e/kalibrate/fn.py#L103-L118 | [
"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",
")"
] |
Return channel detect threshold from kal output . | def determine_chan_detect_threshold ( kal_out ) : channel_detect_threshold = "" while channel_detect_threshold == "" : for line in kal_out . splitlines ( ) : if "channel detect threshold: " in line : channel_detect_threshold = str ( line . split ( ) [ - 1 ] ) if channel_detect_threshold == "" : print ( "Unable to parse sample rate" ) channel_detect_threshold = None return channel_detect_threshold | 8,110 | https://github.com/ashmastaflash/kal-wrapper/blob/80ee03ab7bd3172ac26b769d6b442960f3424b0e/kalibrate/fn.py#L127-L137 | [
"async",
"def",
"open_session",
"(",
"self",
",",
"request",
":",
"BaseRequestWebsocket",
")",
"->",
"Session",
":",
"return",
"await",
"ensure_coroutine",
"(",
"self",
".",
"session_interface",
".",
"open_session",
")",
"(",
"self",
",",
"request",
")"
] |
Return band channel target frequency from kal output . | def determine_band_channel ( kal_out ) : band = "" channel = "" tgt_freq = "" while band == "" : for line in kal_out . splitlines ( ) : if "Using " in line and " channel " in line : band = str ( line . split ( ) [ 1 ] ) channel = str ( line . split ( ) [ 3 ] ) tgt_freq = str ( line . split ( ) [ 4 ] ) . replace ( "(" , "" ) . replace ( ")" , "" ) if band == "" : band = None return ( band , channel , tgt_freq ) | 8,111 | https://github.com/ashmastaflash/kal-wrapper/blob/80ee03ab7bd3172ac26b769d6b442960f3424b0e/kalibrate/fn.py#L140-L154 | [
"def",
"database_backup",
"(",
"self",
",",
"data_directory",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"upload_good",
"=",
"False",
"backup_stop_good",
"=",
"False",
"while_offline",
"=",
"False",
"start_backup_info",
"=",
"None",
"if",
"'while_offline'",
"in",
"kwargs",
":",
"while_offline",
"=",
"kwargs",
".",
"pop",
"(",
"'while_offline'",
")",
"try",
":",
"if",
"not",
"while_offline",
":",
"start_backup_info",
"=",
"PgBackupStatements",
".",
"run_start_backup",
"(",
")",
"version",
"=",
"PgBackupStatements",
".",
"pg_version",
"(",
")",
"[",
"'version'",
"]",
"else",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"data_directory",
",",
"'postmaster.pid'",
")",
")",
":",
"hint",
"=",
"(",
"'Shut down postgres. '",
"'If there is a stale lockfile, '",
"'then remove it after being very sure postgres '",
"'is not running.'",
")",
"raise",
"UserException",
"(",
"msg",
"=",
"'while_offline set, but pg looks to be running'",
",",
"detail",
"=",
"'Found a postmaster.pid lockfile, and aborting'",
",",
"hint",
"=",
"hint",
")",
"ctrl_data",
"=",
"PgControlDataParser",
"(",
"data_directory",
")",
"start_backup_info",
"=",
"ctrl_data",
".",
"last_xlog_file_name_and_offset",
"(",
")",
"version",
"=",
"ctrl_data",
".",
"pg_version",
"(",
")",
"ret_tuple",
"=",
"self",
".",
"_upload_pg_cluster_dir",
"(",
"start_backup_info",
",",
"data_directory",
",",
"version",
"=",
"version",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"spec",
",",
"uploaded_to",
",",
"expanded_size_bytes",
"=",
"ret_tuple",
"upload_good",
"=",
"True",
"finally",
":",
"if",
"not",
"upload_good",
":",
"logger",
".",
"warning",
"(",
"'blocking on sending WAL segments'",
",",
"detail",
"=",
"(",
"'The backup was not completed successfully, '",
"'but we have to wait anyway. '",
"'See README: TODO about pg_cancel_backup'",
")",
")",
"if",
"not",
"while_offline",
":",
"stop_backup_info",
"=",
"PgBackupStatements",
".",
"run_stop_backup",
"(",
")",
"else",
":",
"stop_backup_info",
"=",
"start_backup_info",
"backup_stop_good",
"=",
"True",
"# XXX: Ugly, this is more of a 'worker' task because it might",
"# involve retries and error messages, something that is not",
"# treated by the \"operator\" category of modules. So",
"# basically, if this small upload fails, the whole upload",
"# fails!",
"if",
"upload_good",
"and",
"backup_stop_good",
":",
"# Try to write a sentinel file to the cluster backup",
"# directory that indicates that the base backup upload has",
"# definitely run its course and also communicates what WAL",
"# segments are needed to get to consistency.",
"sentinel_content",
"=",
"json",
".",
"dumps",
"(",
"{",
"'wal_segment_backup_stop'",
":",
"stop_backup_info",
"[",
"'file_name'",
"]",
",",
"'wal_segment_offset_backup_stop'",
":",
"stop_backup_info",
"[",
"'file_offset'",
"]",
",",
"'expanded_size_bytes'",
":",
"expanded_size_bytes",
",",
"'spec'",
":",
"spec",
"}",
")",
"# XXX: should use the storage operators.",
"#",
"# XXX: distinguish sentinels by *PREFIX* not suffix,",
"# which makes searching harder. (For the next version",
"# bump).",
"uri_put_file",
"(",
"self",
".",
"creds",
",",
"uploaded_to",
"+",
"'_backup_stop_sentinel.json'",
",",
"BytesIO",
"(",
"sentinel_content",
".",
"encode",
"(",
"\"utf8\"",
")",
")",
",",
"content_type",
"=",
"'application/json'",
")",
"else",
":",
"# NB: Other exceptions should be raised before this that",
"# have more informative results, it is intended that this",
"# exception never will get raised.",
"raise",
"UserCritical",
"(",
"'could not complete backup process'",
")"
] |
Parse kal band scan output . | def parse_kal_scan ( kal_out ) : kal_data = [ ] scan_band = determine_scan_band ( kal_out ) scan_gain = determine_scan_gain ( kal_out ) scan_device = determine_device ( kal_out ) sample_rate = determine_sample_rate ( kal_out ) chan_detect_threshold = determine_chan_detect_threshold ( kal_out ) for line in kal_out . splitlines ( ) : if "chan:" in line : p_line = line . split ( ' ' ) chan = str ( p_line [ 1 ] ) modifier = str ( p_line [ 3 ] ) power = str ( p_line [ 5 ] ) mod_raw = str ( p_line [ 4 ] ) . replace ( ')\tpower:' , '' ) base_raw = str ( ( p_line [ 2 ] ) . replace ( '(' , '' ) ) mod_freq = herz_me ( mod_raw ) base_freq = herz_me ( base_raw ) final_freq = to_eng ( determine_final_freq ( base_freq , modifier , mod_freq ) ) kal_run = { "channel" : chan , "base_freq" : base_freq , "mod_freq" : mod_freq , "modifier" : modifier , "final_freq" : final_freq , "power" : power , "band" : scan_band , "gain" : scan_gain , "device" : scan_device , "sample_rate" : sample_rate , "channel_detect_threshold" : chan_detect_threshold } kal_data . append ( kal_run . copy ( ) ) return kal_data | 8,112 | https://github.com/ashmastaflash/kal-wrapper/blob/80ee03ab7bd3172ac26b769d6b442960f3424b0e/kalibrate/fn.py#L157-L189 | [
"def",
"features_keep_using_features",
"(",
"obj",
",",
"bounds",
")",
":",
"# Build an R-tree index of bound features and their shapes.",
"bounds_shapes",
"=",
"[",
"(",
"feature",
",",
"shapely",
".",
"geometry",
".",
"shape",
"(",
"feature",
"[",
"'geometry'",
"]",
")",
")",
"for",
"feature",
"in",
"tqdm",
"(",
"bounds",
"[",
"'features'",
"]",
")",
"if",
"feature",
"[",
"'geometry'",
"]",
"is",
"not",
"None",
"]",
"index",
"=",
"rtree",
".",
"index",
".",
"Index",
"(",
")",
"for",
"i",
"in",
"tqdm",
"(",
"range",
"(",
"len",
"(",
"bounds_shapes",
")",
")",
")",
":",
"(",
"feature",
",",
"shape",
")",
"=",
"bounds_shapes",
"[",
"i",
"]",
"index",
".",
"insert",
"(",
"i",
",",
"shape",
".",
"bounds",
")",
"features_keep",
"=",
"[",
"]",
"for",
"feature",
"in",
"tqdm",
"(",
"obj",
"[",
"'features'",
"]",
")",
":",
"if",
"'geometry'",
"in",
"feature",
"and",
"'coordinates'",
"in",
"feature",
"[",
"'geometry'",
"]",
":",
"coordinates",
"=",
"feature",
"[",
"'geometry'",
"]",
"[",
"'coordinates'",
"]",
"if",
"any",
"(",
"[",
"shape",
".",
"contains",
"(",
"shapely",
".",
"geometry",
".",
"Point",
"(",
"lon",
",",
"lat",
")",
")",
"for",
"(",
"lon",
",",
"lat",
")",
"in",
"coordinates",
"for",
"(",
"feature",
",",
"shape",
")",
"in",
"[",
"bounds_shapes",
"[",
"i",
"]",
"for",
"i",
"in",
"index",
".",
"nearest",
"(",
"(",
"lon",
",",
"lat",
",",
"lon",
",",
"lat",
")",
",",
"1",
")",
"]",
"]",
")",
":",
"features_keep",
".",
"append",
"(",
"feature",
")",
"continue",
"obj",
"[",
"'features'",
"]",
"=",
"features_keep",
"return",
"obj"
] |
Parse kal channel scan output . | def parse_kal_channel ( kal_out ) : scan_band , scan_channel , tgt_freq = determine_band_channel ( kal_out ) kal_data = { "device" : determine_device ( kal_out ) , "sample_rate" : determine_sample_rate ( kal_out ) , "gain" : determine_scan_gain ( kal_out ) , "band" : scan_band , "channel" : scan_channel , "frequency" : tgt_freq , "avg_absolute_error" : determine_avg_absolute_error ( kal_out ) , "measurements" : get_measurements_from_kal_scan ( kal_out ) , "raw_scan_result" : kal_out } return kal_data | 8,113 | https://github.com/ashmastaflash/kal-wrapper/blob/80ee03ab7bd3172ac26b769d6b442960f3424b0e/kalibrate/fn.py#L192-L204 | [
"def",
"initialize_communities_bucket",
"(",
")",
":",
"bucket_id",
"=",
"UUID",
"(",
"current_app",
".",
"config",
"[",
"'COMMUNITIES_BUCKET_UUID'",
"]",
")",
"if",
"Bucket",
".",
"query",
".",
"get",
"(",
"bucket_id",
")",
":",
"raise",
"FilesException",
"(",
"\"Bucket with UUID {} already exists.\"",
".",
"format",
"(",
"bucket_id",
")",
")",
"else",
":",
"storage_class",
"=",
"current_app",
".",
"config",
"[",
"'FILES_REST_DEFAULT_STORAGE_CLASS'",
"]",
"location",
"=",
"Location",
".",
"get_default",
"(",
")",
"bucket",
"=",
"Bucket",
"(",
"id",
"=",
"bucket_id",
",",
"location",
"=",
"location",
",",
"default_storage_class",
"=",
"storage_class",
")",
"db",
".",
"session",
".",
"add",
"(",
"bucket",
")",
"db",
".",
"session",
".",
"commit",
"(",
")"
] |
Return a list of all measurements from kalibrate channel scan . | def get_measurements_from_kal_scan ( kal_out ) : result = [ ] for line in kal_out . splitlines ( ) : if "offset " in line : p_line = line . split ( ' ' ) result . append ( p_line [ - 1 ] ) return result | 8,114 | https://github.com/ashmastaflash/kal-wrapper/blob/80ee03ab7bd3172ac26b769d6b442960f3424b0e/kalibrate/fn.py#L206-L213 | [
"def",
"assign_license",
"(",
"license_key",
",",
"license_name",
",",
"entity",
",",
"entity_display_name",
",",
"safety_checks",
"=",
"True",
",",
"service_instance",
"=",
"None",
")",
":",
"log",
".",
"trace",
"(",
"'Assigning license %s to entity %s'",
",",
"license_key",
",",
"entity",
")",
"_validate_entity",
"(",
"entity",
")",
"if",
"safety_checks",
":",
"licenses",
"=",
"salt",
".",
"utils",
".",
"vmware",
".",
"get_licenses",
"(",
"service_instance",
")",
"if",
"not",
"[",
"l",
"for",
"l",
"in",
"licenses",
"if",
"l",
".",
"licenseKey",
"==",
"license_key",
"]",
":",
"raise",
"VMwareObjectRetrievalError",
"(",
"'License \\'{0}\\' wasn\\'t found'",
"''",
".",
"format",
"(",
"license_name",
")",
")",
"salt",
".",
"utils",
".",
"vmware",
".",
"assign_license",
"(",
"service_instance",
",",
"license_key",
",",
"license_name",
",",
"entity_ref",
"=",
"_get_entity",
"(",
"service_instance",
",",
"entity",
")",
",",
"entity_name",
"=",
"entity_display_name",
")"
] |
The default field renderer . | def render ( self , obj , name , context ) : if self . value_lambda is not None : val = self . value_lambda ( obj ) else : attr_name = name if self . property_name is not None : attr_name = self . property_name if isinstance ( obj , dict ) : val = obj . get ( attr_name , None ) else : val = getattr ( obj , attr_name , None ) if callable ( val ) : try : val = val ( ) except : logging . exception ( "Attempted to call `%s` on obj of type %s." , attr_name , type ( obj ) ) raise return val | 8,115 | https://github.com/Loudr/pale/blob/dc002ee6032c856551143af222ff8f71ed9853fe/pale/fields/base.py#L58-L93 | [
"def",
"auto_detect_serial_win32",
"(",
"preferred_list",
"=",
"[",
"'*'",
"]",
")",
":",
"try",
":",
"from",
"serial",
".",
"tools",
".",
"list_ports_windows",
"import",
"comports",
"list",
"=",
"sorted",
"(",
"comports",
"(",
")",
")",
"except",
":",
"return",
"[",
"]",
"ret",
"=",
"[",
"]",
"others",
"=",
"[",
"]",
"for",
"port",
",",
"description",
",",
"hwid",
"in",
"list",
":",
"matches",
"=",
"False",
"p",
"=",
"SerialPort",
"(",
"port",
",",
"description",
"=",
"description",
",",
"hwid",
"=",
"hwid",
")",
"for",
"preferred",
"in",
"preferred_list",
":",
"if",
"fnmatch",
".",
"fnmatch",
"(",
"description",
",",
"preferred",
")",
"or",
"fnmatch",
".",
"fnmatch",
"(",
"hwid",
",",
"preferred",
")",
":",
"matches",
"=",
"True",
"if",
"matches",
":",
"ret",
".",
"append",
"(",
"p",
")",
"else",
":",
"others",
".",
"append",
"(",
"p",
")",
"if",
"len",
"(",
"ret",
")",
">",
"0",
":",
"return",
"ret",
"# now the rest",
"ret",
".",
"extend",
"(",
"others",
")",
"return",
"ret"
] |
Generate the documentation for this field . | def doc_dict ( self ) : doc = { 'type' : self . value_type , 'description' : self . description , 'extended_description' : self . details } return doc | 8,116 | https://github.com/Loudr/pale/blob/dc002ee6032c856551143af222ff8f71ed9853fe/pale/fields/base.py#L96-L103 | [
"def",
"schedule_snapshot",
"(",
"self",
")",
":",
"# Notes:",
"# - Snapshots are not immediate.",
"# - Snapshots will be cached for predefined amount",
"# of time.",
"# - Snapshots are not balanced. To get a better",
"# image, it must be taken from the stream, a few",
"# seconds after stream start.",
"url",
"=",
"SNAPSHOTS_ENDPOINT",
"params",
"=",
"SNAPSHOTS_BODY",
"params",
"[",
"'from'",
"]",
"=",
"\"{0}_web\"",
".",
"format",
"(",
"self",
".",
"user_id",
")",
"params",
"[",
"'to'",
"]",
"=",
"self",
".",
"device_id",
"params",
"[",
"'resource'",
"]",
"=",
"\"cameras/{0}\"",
".",
"format",
"(",
"self",
".",
"device_id",
")",
"params",
"[",
"'transId'",
"]",
"=",
"\"web!{0}\"",
".",
"format",
"(",
"self",
".",
"xcloud_id",
")",
"# override headers",
"headers",
"=",
"{",
"'xCloudId'",
":",
"self",
".",
"xcloud_id",
"}",
"_LOGGER",
".",
"debug",
"(",
"\"Snapshot device %s\"",
",",
"self",
".",
"name",
")",
"_LOGGER",
".",
"debug",
"(",
"\"Device params %s\"",
",",
"params",
")",
"_LOGGER",
".",
"debug",
"(",
"\"Device headers %s\"",
",",
"headers",
")",
"ret",
"=",
"self",
".",
"_session",
".",
"query",
"(",
"url",
",",
"method",
"=",
"'POST'",
",",
"extra_params",
"=",
"params",
",",
"extra_headers",
"=",
"headers",
")",
"_LOGGER",
".",
"debug",
"(",
"\"Snapshot results %s\"",
",",
"ret",
")",
"return",
"ret",
"is",
"not",
"None",
"and",
"ret",
".",
"get",
"(",
"'success'",
")"
] |
Return capability by its name | def capability ( self , cap_name ) : if cap_name in self . __class_capabilities__ : function_name = self . __class_capabilities__ [ cap_name ] return getattr ( self , function_name ) | 8,117 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/capability.py#L100-L108 | [
"def",
"initialize_schema",
"(",
"connection",
")",
":",
"cursor",
"=",
"connection",
".",
"cursor",
"(",
")",
"cursor",
".",
"execute",
"(",
"\"PRAGMA application_id={}\"",
".",
"format",
"(",
"_TENSORBOARD_APPLICATION_ID",
")",
")",
"cursor",
".",
"execute",
"(",
"\"PRAGMA user_version={}\"",
".",
"format",
"(",
"_TENSORBOARD_USER_VERSION",
")",
")",
"with",
"connection",
":",
"for",
"statement",
"in",
"_SCHEMA_STATEMENTS",
":",
"lines",
"=",
"statement",
".",
"strip",
"(",
"'\\n'",
")",
".",
"split",
"(",
"'\\n'",
")",
"message",
"=",
"lines",
"[",
"0",
"]",
"+",
"(",
"'...'",
"if",
"len",
"(",
"lines",
")",
">",
"1",
"else",
"''",
")",
"logger",
".",
"debug",
"(",
"'Running DB init statement: %s'",
",",
"message",
")",
"cursor",
".",
"execute",
"(",
"statement",
")"
] |
Check if class has all of the specified capabilities | def has_capabilities ( self , * cap_names ) : for name in cap_names : if name not in self . __class_capabilities__ : return False return True | 8,118 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/capability.py#L111-L121 | [
"def",
"run",
"(",
"self",
")",
":",
"port",
",",
"tensorboard_process",
"=",
"self",
".",
"create_tensorboard_process",
"(",
")",
"LOGGER",
".",
"info",
"(",
"'TensorBoard 0.1.7 at http://localhost:{}'",
".",
"format",
"(",
"port",
")",
")",
"while",
"not",
"self",
".",
"estimator",
".",
"checkpoint_path",
":",
"self",
".",
"event",
".",
"wait",
"(",
"1",
")",
"with",
"self",
".",
"_temporary_directory",
"(",
")",
"as",
"aws_sync_dir",
":",
"while",
"not",
"self",
".",
"event",
".",
"is_set",
"(",
")",
":",
"args",
"=",
"[",
"'aws'",
",",
"'s3'",
",",
"'sync'",
",",
"self",
".",
"estimator",
".",
"checkpoint_path",
",",
"aws_sync_dir",
"]",
"subprocess",
".",
"call",
"(",
"args",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
")",
"self",
".",
"_sync_directories",
"(",
"aws_sync_dir",
",",
"self",
".",
"logdir",
")",
"self",
".",
"event",
".",
"wait",
"(",
"10",
")",
"tensorboard_process",
".",
"terminate",
"(",
")"
] |
Attach nested entity errors Accepts a list errors coming from validators attached directly or a dict of errors produced by a nested schema . | def add_entity_errors ( self , property_name , direct_errors = None , schema_errors = None ) : if direct_errors is None and schema_errors is None : return self # direct errors if direct_errors is not None : if property_name not in self . errors : self . errors [ property_name ] = dict ( ) if 'direct' not in self . errors [ property_name ] : self . errors [ property_name ] [ 'direct' ] = [ ] if type ( direct_errors ) is not list : direct_errors = [ direct_errors ] for error in direct_errors : if not isinstance ( error , Error ) : err = 'Error must be of type {}' raise x . InvalidErrorType ( err . format ( Error ) ) self . errors [ property_name ] [ 'direct' ] . append ( error ) # schema errors if schema_errors is not None : if isinstance ( schema_errors , Result ) : schema_errors = schema_errors . errors if not schema_errors : return self if property_name not in self . errors : self . errors [ property_name ] = dict ( ) if 'schema' not in self . errors [ property_name ] : self . errors [ property_name ] [ 'schema' ] = schema_errors else : self . errors [ property_name ] [ 'schema' ] = self . merge_errors ( self . errors [ property_name ] [ 'schema' ] , schema_errors ) return self | 8,119 | https://github.com/projectshift/shift-schema/blob/07787b540d3369bb37217ffbfbe629118edaf0eb/shiftschema/result.py#L106-L161 | [
"def",
"create_bmi_config_file",
"(",
"self",
",",
"filename",
":",
"str",
"=",
"\"bmi_config.txt\"",
")",
"->",
"None",
":",
"s0",
"=",
"self",
".",
"construct_default_initial_state",
"(",
")",
"s0",
".",
"to_csv",
"(",
"filename",
",",
"index_label",
"=",
"\"variable\"",
")"
] |
Add collection errors Accepts a list errors coming from validators attached directly or a list of schema results for each item in the collection . | def add_collection_errors ( self , property_name , direct_errors = None , collection_errors = None ) : if direct_errors is None and collection_errors is None : return self # direct errors if direct_errors is not None : if type ( direct_errors ) is not list : direct_errors = [ direct_errors ] if property_name not in self . errors : self . errors [ property_name ] = dict ( ) if 'direct' not in self . errors [ property_name ] : self . errors [ property_name ] [ 'direct' ] = [ ] for error in direct_errors : if not isinstance ( error , Error ) : err = 'Error must be of type {}' raise x . InvalidErrorType ( err . format ( Error ) ) self . errors [ property_name ] [ 'direct' ] . append ( error ) # collection errors if collection_errors : enum = enumerate ( collection_errors ) errors_dict = { i : e for i , e in enum if not bool ( e ) } if not errors_dict : return self if property_name not in self . errors : self . errors [ property_name ] = dict ( ) if 'collection' not in self . errors [ property_name ] : self . errors [ property_name ] [ 'collection' ] = errors_dict else : local = self . errors [ property_name ] [ 'collection' ] remote = errors_dict for index , result in remote . items ( ) : if index not in local : self . errors [ property_name ] [ 'collection' ] [ index ] = result else : merged = self . merge_errors ( local [ index ] . errors , remote [ index ] . errors ) self . errors [ property_name ] [ 'collection' ] [ index ] = merged return self | 8,120 | https://github.com/projectshift/shift-schema/blob/07787b540d3369bb37217ffbfbe629118edaf0eb/shiftschema/result.py#L163-L220 | [
"def",
"from_pandas_dataframe",
"(",
"cls",
",",
"bqm_df",
",",
"offset",
"=",
"0.0",
",",
"interactions",
"=",
"None",
")",
":",
"if",
"interactions",
"is",
"None",
":",
"interactions",
"=",
"[",
"]",
"bqm",
"=",
"cls",
"(",
"{",
"}",
",",
"{",
"}",
",",
"offset",
",",
"Vartype",
".",
"BINARY",
")",
"for",
"u",
",",
"row",
"in",
"bqm_df",
".",
"iterrows",
"(",
")",
":",
"for",
"v",
",",
"bias",
"in",
"row",
".",
"iteritems",
"(",
")",
":",
"if",
"u",
"==",
"v",
":",
"bqm",
".",
"add_variable",
"(",
"u",
",",
"bias",
")",
"elif",
"bias",
":",
"bqm",
".",
"add_interaction",
"(",
"u",
",",
"v",
",",
"bias",
")",
"for",
"u",
",",
"v",
"in",
"interactions",
":",
"bqm",
".",
"add_interaction",
"(",
"u",
",",
"v",
",",
"0.0",
")",
"return",
"bqm"
] |
Merge errors Recursively traverses error graph to merge remote errors into local errors to return a new joined graph . | def merge_errors ( self , errors_local , errors_remote ) : for prop in errors_remote : # create if doesn't exist if prop not in errors_local : errors_local [ prop ] = errors_remote [ prop ] continue local = errors_local [ prop ] local = local . errors if isinstance ( local , Result ) else local remote = errors_remote [ prop ] remote = remote . errors if isinstance ( remote , Result ) else remote # check compatibility if not isinstance ( local , type ( remote ) ) : msg = 'Type mismatch on property [{}] when merging errors. ' msg += 'Unable to merge [{}] into [{}]' raise x . UnableToMergeResultsType ( msg . format ( prop , type ( errors_remote [ prop ] ) , type ( self . errors [ prop ] ) ) ) mismatch = 'Unable to merge nested entity errors with nested ' mismatch += 'collection errors on property [{}]' if 'schema' in local and 'collection' in remote : raise x . UnableToMergeResultsType ( mismatch . format ( prop ) ) if 'collection' in local and 'schema' in remote : raise x . UnableToMergeResultsType ( mismatch . format ( prop ) ) # merge simple & state if type ( remote ) is list : errors_local [ prop ] . extend ( remote ) continue # merge direct errors on nested entities and collection if 'direct' in remote and 'direct' in local : errors_local [ prop ] [ 'direct' ] . extend ( remote [ 'direct' ] ) # merge nested schema errors if 'schema' in remote and 'schema' in local : errors_local [ prop ] [ 'schema' ] = self . merge_errors ( errors_local [ prop ] [ 'schema' ] , remote [ 'schema' ] ) # merge nested collections errors if 'collection' in remote and 'collection' in local : for index , result in remote [ 'collection' ] . items ( ) : if index not in local [ 'collection' ] : errors_local [ prop ] [ 'collection' ] [ index ] = result else : merged = self . merge_errors ( errors_local [ prop ] [ 'collection' ] [ index ] . errors , errors_remote [ prop ] [ 'collection' ] [ index ] . errors , ) errors_local [ prop ] [ 'collection' ] [ index ] = merged # and return return errors_local | 8,121 | https://github.com/projectshift/shift-schema/blob/07787b540d3369bb37217ffbfbe629118edaf0eb/shiftschema/result.py#L222-L290 | [
"def",
"write_events",
"(",
"stream",
",",
"events",
")",
":",
"for",
"event",
"in",
"events",
":",
"data",
"=",
"event",
".",
"SerializeToString",
"(",
")",
"len_field",
"=",
"struct",
".",
"pack",
"(",
"'<Q'",
",",
"len",
"(",
"data",
")",
")",
"len_crc",
"=",
"struct",
".",
"pack",
"(",
"'<I'",
",",
"masked_crc",
"(",
"len_field",
")",
")",
"data_crc",
"=",
"struct",
".",
"pack",
"(",
"'<I'",
",",
"masked_crc",
"(",
"data",
")",
")",
"stream",
".",
"write",
"(",
"len_field",
")",
"stream",
".",
"write",
"(",
"len_crc",
")",
"stream",
".",
"write",
"(",
"data",
")",
"stream",
".",
"write",
"(",
"data_crc",
")"
] |
Merges another validation result graph into itself | def merge ( self , another ) : if isinstance ( another , Result ) : another = another . errors self . errors = self . merge_errors ( self . errors , another ) | 8,122 | https://github.com/projectshift/shift-schema/blob/07787b540d3369bb37217ffbfbe629118edaf0eb/shiftschema/result.py#L292-L296 | [
"def",
"_create_modulename",
"(",
"cdef_sources",
",",
"source",
",",
"sys_version",
")",
":",
"key",
"=",
"'\\x00'",
".",
"join",
"(",
"[",
"sys_version",
"[",
":",
"3",
"]",
",",
"source",
",",
"cdef_sources",
"]",
")",
"key",
"=",
"key",
".",
"encode",
"(",
"'utf-8'",
")",
"k1",
"=",
"hex",
"(",
"binascii",
".",
"crc32",
"(",
"key",
"[",
"0",
":",
":",
"2",
"]",
")",
"&",
"0xffffffff",
")",
"k1",
"=",
"k1",
".",
"lstrip",
"(",
"'0x'",
")",
".",
"rstrip",
"(",
"'L'",
")",
"k2",
"=",
"hex",
"(",
"binascii",
".",
"crc32",
"(",
"key",
"[",
"1",
":",
":",
"2",
"]",
")",
"&",
"0xffffffff",
")",
"k2",
"=",
"k2",
".",
"lstrip",
"(",
"'0'",
")",
".",
"rstrip",
"(",
"'L'",
")",
"return",
"'_xprintidle_cffi_{0}{1}'",
".",
"format",
"(",
"k1",
",",
"k2",
")"
] |
Get a dictionary of translated messages | def get_messages ( self , locale = None ) : if locale is None : locale = self . locale if self . translator : def translate ( error ) : return self . translator . translate ( error , locale ) else : def translate ( error ) : return error errors = deepcopy ( self . errors ) errors = self . _translate_errors ( errors , translate ) return errors | 8,123 | https://github.com/projectshift/shift-schema/blob/07787b540d3369bb37217ffbfbe629118edaf0eb/shiftschema/result.py#L298-L312 | [
"def",
"maybe_rate_limit",
"(",
"client",
",",
"headers",
",",
"atexit",
"=",
"False",
")",
":",
"# pylint: disable=fixme",
"# pylint: disable=global-statement",
"# FIXME: Yes, I know this is not great. We'll fix it later. :-)",
"global",
"LAST_CLIENT",
",",
"LAST_HEADERS",
"if",
"LAST_CLIENT",
"and",
"LAST_HEADERS",
":",
"# Wait based on previous client/headers",
"rate_limit",
"(",
"LAST_CLIENT",
",",
"LAST_HEADERS",
",",
"atexit",
"=",
"atexit",
")",
"LAST_CLIENT",
"=",
"copy",
".",
"copy",
"(",
"client",
")",
"LAST_HEADERS",
"=",
"copy",
".",
"copy",
"(",
"headers",
")"
] |
Recursively apply translate callback to each error message | def _translate_errors ( self , errors , translate ) : for prop in errors : prop_errors = errors [ prop ] # state and simple if type ( prop_errors ) is list : for index , error in enumerate ( prop_errors ) : message = translate ( error . message ) message = self . format_error ( message , error . kwargs ) errors [ prop ] [ index ] = message # entity and collection direct if type ( prop_errors ) is dict and 'direct' in prop_errors : for index , error in enumerate ( prop_errors [ 'direct' ] ) : message = translate ( error . message ) message = self . format_error ( message , error . kwargs ) errors [ prop ] [ 'direct' ] [ index ] = message # entity schema if type ( prop_errors ) is dict and 'schema' in prop_errors : errors [ prop ] [ 'schema' ] = self . _translate_errors ( prop_errors [ 'schema' ] , translate ) # collection schema if type ( prop_errors ) is dict and 'collection' in prop_errors : translated = dict ( ) for index , result in prop_errors [ 'collection' ] . items ( ) : translated [ index ] = self . _translate_errors ( result . errors , translate ) errors [ prop ] [ 'collection' ] = translated return errors | 8,124 | https://github.com/projectshift/shift-schema/blob/07787b540d3369bb37217ffbfbe629118edaf0eb/shiftschema/result.py#L314-L350 | [
"def",
"wnfetd",
"(",
"window",
",",
"n",
")",
":",
"assert",
"isinstance",
"(",
"window",
",",
"stypes",
".",
"SpiceCell",
")",
"assert",
"window",
".",
"dtype",
"==",
"1",
"n",
"=",
"ctypes",
".",
"c_int",
"(",
"n",
")",
"left",
"=",
"ctypes",
".",
"c_double",
"(",
")",
"right",
"=",
"ctypes",
".",
"c_double",
"(",
")",
"libspice",
".",
"wnfetd_c",
"(",
"ctypes",
".",
"byref",
"(",
"window",
")",
",",
"n",
",",
"ctypes",
".",
"byref",
"(",
"left",
")",
",",
"ctypes",
".",
"byref",
"(",
"right",
")",
")",
"return",
"left",
".",
"value",
",",
"right",
".",
"value"
] |
Gets a full URL from just path . | def make_url ( self , path , api_root = u'/v2/' ) : return urljoin ( urljoin ( self . url , api_root ) , path ) | 8,125 | https://github.com/sublee/etc/blob/f2be64604da5af0d7739cfacf36f55712f0fc5cb/etc/adapters/etcd.py#L40-L42 | [
"def",
"compose",
"(",
"list_of_files",
",",
"destination_file",
",",
"files_metadata",
"=",
"None",
",",
"content_type",
"=",
"None",
",",
"retry_params",
"=",
"None",
",",
"_account_id",
"=",
"None",
")",
":",
"api",
"=",
"storage_api",
".",
"_get_storage_api",
"(",
"retry_params",
"=",
"retry_params",
",",
"account_id",
"=",
"_account_id",
")",
"if",
"os",
".",
"getenv",
"(",
"'SERVER_SOFTWARE'",
")",
".",
"startswith",
"(",
"'Dev'",
")",
":",
"def",
"_temp_func",
"(",
"file_list",
",",
"destination_file",
",",
"content_type",
")",
":",
"bucket",
"=",
"'/'",
"+",
"destination_file",
".",
"split",
"(",
"'/'",
")",
"[",
"1",
"]",
"+",
"'/'",
"with",
"open",
"(",
"destination_file",
",",
"'w'",
",",
"content_type",
"=",
"content_type",
")",
"as",
"gcs_merge",
":",
"for",
"source_file",
"in",
"file_list",
":",
"with",
"open",
"(",
"bucket",
"+",
"source_file",
"[",
"'Name'",
"]",
",",
"'r'",
")",
"as",
"gcs_source",
":",
"gcs_merge",
".",
"write",
"(",
"gcs_source",
".",
"read",
"(",
")",
")",
"compose_object",
"=",
"_temp_func",
"else",
":",
"compose_object",
"=",
"api",
".",
"compose_object",
"file_list",
",",
"_",
"=",
"_validate_compose_list",
"(",
"destination_file",
",",
"list_of_files",
",",
"files_metadata",
",",
"32",
")",
"compose_object",
"(",
"file_list",
",",
"destination_file",
",",
"content_type",
")"
] |
Gets a URL for a key . | def make_key_url ( self , key ) : if type ( key ) is bytes : key = key . decode ( 'utf-8' ) buf = io . StringIO ( ) buf . write ( u'keys' ) if not key . startswith ( u'/' ) : buf . write ( u'/' ) buf . write ( key ) return self . make_url ( buf . getvalue ( ) ) | 8,126 | https://github.com/sublee/etc/blob/f2be64604da5af0d7739cfacf36f55712f0fc5cb/etc/adapters/etcd.py#L44-L53 | [
"def",
"write",
"(",
"self",
",",
"basename",
"=",
"None",
",",
"write_separate_manifests",
"=",
"True",
")",
":",
"self",
".",
"check_files",
"(",
")",
"n",
"=",
"0",
"for",
"manifest",
"in",
"self",
".",
"partition_dumps",
"(",
")",
":",
"dumpbase",
"=",
"\"%s%05d\"",
"%",
"(",
"basename",
",",
"n",
")",
"dumpfile",
"=",
"\"%s.%s\"",
"%",
"(",
"dumpbase",
",",
"self",
".",
"format",
")",
"if",
"(",
"write_separate_manifests",
")",
":",
"manifest",
".",
"write",
"(",
"basename",
"=",
"dumpbase",
"+",
"'.xml'",
")",
"if",
"(",
"self",
".",
"format",
"==",
"'zip'",
")",
":",
"self",
".",
"write_zip",
"(",
"manifest",
".",
"resources",
",",
"dumpfile",
")",
"elif",
"(",
"self",
".",
"format",
"==",
"'warc'",
")",
":",
"self",
".",
"write_warc",
"(",
"manifest",
".",
"resources",
",",
"dumpfile",
")",
"else",
":",
"raise",
"DumpError",
"(",
"\"Unknown dump format requested (%s)\"",
"%",
"(",
"self",
".",
"format",
")",
")",
"n",
"+=",
"1",
"self",
".",
"logger",
".",
"info",
"(",
"\"Wrote %d dump files\"",
"%",
"(",
"n",
")",
")",
"return",
"(",
"n",
")"
] |
Requests to get a node by the given key . | def get ( self , key , recursive = False , sorted = False , quorum = False , wait = False , wait_index = None , timeout = None ) : url = self . make_key_url ( key ) params = self . build_args ( { 'recursive' : ( bool , recursive or None ) , 'sorted' : ( bool , sorted or None ) , 'quorum' : ( bool , quorum or None ) , 'wait' : ( bool , wait or None ) , 'waitIndex' : ( int , wait_index ) , } ) if timeout is None : # Try again when :exc:`TimedOut` thrown. while True : try : try : res = self . session . get ( url , params = params ) except : self . erred ( ) except ( TimedOut , ChunkedEncodingError ) : continue else : break else : try : res = self . session . get ( url , params = params , timeout = timeout ) except ChunkedEncodingError : raise TimedOut except : self . erred ( ) return self . wrap_response ( res ) | 8,127 | https://github.com/sublee/etc/blob/f2be64604da5af0d7739cfacf36f55712f0fc5cb/etc/adapters/etcd.py#L155-L185 | [
"def",
"rmarkdown_draft",
"(",
"filename",
",",
"template",
",",
"package",
")",
":",
"if",
"file_exists",
"(",
"filename",
")",
":",
"return",
"filename",
"draft_template",
"=",
"Template",
"(",
"'rmarkdown::draft(\"$filename\", template=\"$template\", package=\"$package\", edit=FALSE)'",
")",
"draft_string",
"=",
"draft_template",
".",
"substitute",
"(",
"filename",
"=",
"filename",
",",
"template",
"=",
"template",
",",
"package",
"=",
"package",
")",
"report_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"filename",
")",
"rcmd",
"=",
"Rscript_cmd",
"(",
")",
"with",
"chdir",
"(",
"report_dir",
")",
":",
"do",
".",
"run",
"(",
"[",
"rcmd",
",",
"\"--no-environ\"",
",",
"\"-e\"",
",",
"draft_string",
"]",
",",
"\"Creating bcbioRNASeq quality control template.\"",
")",
"do",
".",
"run",
"(",
"[",
"\"sed\"",
",",
"\"-i\"",
",",
"\"s/YYYY-MM-DD\\///g\"",
",",
"filename",
"]",
",",
"\"Editing bcbioRNAseq quality control template.\"",
")",
"return",
"filename"
] |
Requests to delete a node by the given key . | def delete ( self , key , dir = False , recursive = False , prev_value = None , prev_index = None , timeout = None ) : url = self . make_key_url ( key ) params = self . build_args ( { 'dir' : ( bool , dir or None ) , 'recursive' : ( bool , recursive or None ) , 'prevValue' : ( six . text_type , prev_value ) , 'prevIndex' : ( int , prev_index ) , } ) try : res = self . session . delete ( url , params = params , timeout = timeout ) except : self . erred ( ) return self . wrap_response ( res ) | 8,128 | https://github.com/sublee/etc/blob/f2be64604da5af0d7739cfacf36f55712f0fc5cb/etc/adapters/etcd.py#L220-L234 | [
"def",
"configure_db",
"(",
"app",
")",
":",
"models",
".",
"db",
".",
"init_app",
"(",
"app",
")",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"'ara.webapp.configure_db'",
")",
"log",
".",
"debug",
"(",
"'Setting up database...'",
")",
"if",
"app",
".",
"config",
".",
"get",
"(",
"'ARA_AUTOCREATE_DATABASE'",
")",
":",
"with",
"app",
".",
"app_context",
"(",
")",
":",
"migrations",
"=",
"app",
".",
"config",
"[",
"'DB_MIGRATIONS'",
"]",
"flask_migrate",
".",
"Migrate",
"(",
"app",
",",
"models",
".",
"db",
",",
"directory",
"=",
"migrations",
")",
"config",
"=",
"app",
".",
"extensions",
"[",
"'migrate'",
"]",
".",
"migrate",
".",
"get_config",
"(",
"migrations",
")",
"# Verify if the database tables have been created at all",
"inspector",
"=",
"Inspector",
".",
"from_engine",
"(",
"models",
".",
"db",
".",
"engine",
")",
"if",
"len",
"(",
"inspector",
".",
"get_table_names",
"(",
")",
")",
"==",
"0",
":",
"log",
".",
"info",
"(",
"'Initializing new DB from scratch'",
")",
"flask_migrate",
".",
"upgrade",
"(",
"directory",
"=",
"migrations",
")",
"# Get current alembic head revision",
"script",
"=",
"ScriptDirectory",
".",
"from_config",
"(",
"config",
")",
"head",
"=",
"script",
".",
"get_current_head",
"(",
")",
"# Get current revision, if available",
"connection",
"=",
"models",
".",
"db",
".",
"engine",
".",
"connect",
"(",
")",
"context",
"=",
"MigrationContext",
".",
"configure",
"(",
"connection",
")",
"current",
"=",
"context",
".",
"get_current_revision",
"(",
")",
"if",
"not",
"current",
":",
"log",
".",
"info",
"(",
"'Unstable DB schema, stamping original revision'",
")",
"flask_migrate",
".",
"stamp",
"(",
"directory",
"=",
"migrations",
",",
"revision",
"=",
"'da9459a1f71c'",
")",
"if",
"head",
"!=",
"current",
":",
"log",
".",
"info",
"(",
"'DB schema out of date, upgrading'",
")",
"flask_migrate",
".",
"upgrade",
"(",
"directory",
"=",
"migrations",
")"
] |
Log username into the MemberSuite Portal . | def login_to_portal ( username , password , client , retries = 2 , delay = 0 ) : if not client . session_id : client . request_session ( ) concierge_request_header = client . construct_concierge_header ( url = ( "http://membersuite.com/contracts/IConciergeAPIService/" "LoginToPortal" ) ) attempts = 0 while attempts < retries : if attempts : time . sleep ( delay ) result = client . client . service . LoginToPortal ( _soapheaders = [ concierge_request_header ] , portalUserName = username , portalPassword = password ) login_to_portal_result = result [ "body" ] [ "LoginToPortalResult" ] if login_to_portal_result [ "Success" ] : portal_user = login_to_portal_result [ "ResultValue" ] [ "PortalUser" ] session_id = get_session_id ( result = result ) return PortalUser ( membersuite_object_data = portal_user , session_id = session_id ) else : attempts += 1 try : error_code = login_to_portal_result [ "Errors" ] [ "ConciergeError" ] [ 0 ] [ "Code" ] except IndexError : # Not a ConciergeError continue else : if attempts < retries and error_code == "GeneralException" : continue raise LoginToPortalError ( result = result ) | 8,129 | https://github.com/AASHE/python-membersuite-api-client/blob/221f5ed8bc7d4424237a4669c5af9edc11819ee9/membersuite_api_client/security/services.py#L10-L56 | [
"def",
"get_or_generate_vocabulary",
"(",
"data_dir",
",",
"tmp_dir",
",",
"data_prefix",
",",
"max_page_size_exp",
",",
"approx_vocab_size",
"=",
"32768",
",",
"strip",
"=",
"True",
")",
":",
"num_pages_for_vocab_generation",
"=",
"approx_vocab_size",
"//",
"3",
"vocab_file",
"=",
"vocab_filename",
"(",
"approx_vocab_size",
",",
"strip",
")",
"def",
"my_generator",
"(",
"data_prefix",
")",
":",
"\"\"\"Line generator for vocab.\"\"\"",
"count",
"=",
"0",
"for",
"page",
"in",
"corpus_page_generator",
"(",
"all_corpus_files",
"(",
"data_prefix",
")",
"[",
":",
":",
"-",
"1",
"]",
",",
"tmp_dir",
",",
"max_page_size_exp",
")",
":",
"revisions",
"=",
"page",
"[",
"\"revisions\"",
"]",
"if",
"revisions",
":",
"text",
"=",
"get_text",
"(",
"revisions",
"[",
"-",
"1",
"]",
",",
"strip",
"=",
"strip",
")",
"yield",
"text",
"count",
"+=",
"1",
"if",
"count",
"%",
"100",
"==",
"0",
":",
"tf",
".",
"logging",
".",
"info",
"(",
"\"reading pages for vocab %d\"",
"%",
"count",
")",
"if",
"count",
">",
"num_pages_for_vocab_generation",
":",
"break",
"return",
"generator_utils",
".",
"get_or_generate_vocab_inner",
"(",
"data_dir",
",",
"vocab_file",
",",
"approx_vocab_size",
",",
"my_generator",
"(",
"data_prefix",
")",
")"
] |
Log out the currently logged - in user . | def logout ( client ) : if not client . session_id : client . request_session ( ) concierge_request_header = client . construct_concierge_header ( url = ( "http://membersuite.com/contracts/IConciergeAPIService/" "Logout" ) ) logout_result = client . client . service . Logout ( _soapheaders = [ concierge_request_header ] ) result = logout_result [ "body" ] [ "LogoutResult" ] if result [ "SessionID" ] is None : # Success! client . session_id = None else : # Failure . . . raise LogoutError ( result = result ) | 8,130 | https://github.com/AASHE/python-membersuite-api-client/blob/221f5ed8bc7d4424237a4669c5af9edc11819ee9/membersuite_api_client/security/services.py#L59-L82 | [
"def",
"_get_vqa_v2_annotations",
"(",
"directory",
",",
"annotation_url",
",",
"annotation_filename",
"=",
"\"vqa_v2.tar.gz\"",
")",
":",
"annotation_file",
"=",
"generator_utils",
".",
"maybe_download_from_drive",
"(",
"directory",
",",
"annotation_filename",
",",
"annotation_url",
")",
"with",
"tarfile",
".",
"open",
"(",
"annotation_file",
",",
"\"r:gz\"",
")",
"as",
"annotation_tar",
":",
"annotation_tar",
".",
"extractall",
"(",
"directory",
")"
] |
Returns a User for membersuite_entity . | def get_user_for_membersuite_entity ( membersuite_entity ) : user = None user_created = False # First, try to match on username. user_username = generate_username ( membersuite_entity ) try : user = User . objects . get ( username = user_username ) except User . DoesNotExist : pass # Next, try to match on email address. if not user : try : user = User . objects . filter ( email = membersuite_entity . email_address ) [ 0 ] except IndexError : pass # No match? Create one. if not user : user = User . objects . create ( username = user_username , email = membersuite_entity . email_address , first_name = membersuite_entity . first_name , last_name = membersuite_entity . last_name ) user_created = True return user , user_created | 8,131 | https://github.com/AASHE/python-membersuite-api-client/blob/221f5ed8bc7d4424237a4669c5af9edc11819ee9/membersuite_api_client/security/services.py#L89-L124 | [
"def",
"overlay_gateway_attach_rbridge_id",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"callback",
"=",
"kwargs",
".",
"pop",
"(",
"'callback'",
",",
"self",
".",
"_callback",
")",
"get_config",
"=",
"kwargs",
".",
"pop",
"(",
"'get'",
",",
"False",
")",
"delete",
"=",
"kwargs",
".",
"pop",
"(",
"'delete'",
",",
"False",
")",
"if",
"not",
"get_config",
":",
"gw_name",
"=",
"kwargs",
".",
"pop",
"(",
"'gw_name'",
")",
"rbridge_id",
"=",
"kwargs",
".",
"pop",
"(",
"'rbridge_id'",
")",
"if",
"delete",
"is",
"True",
":",
"gw_args",
"=",
"dict",
"(",
"name",
"=",
"gw_name",
",",
"rb_remove",
"=",
"rbridge_id",
")",
"overlay_gw",
"=",
"getattr",
"(",
"self",
".",
"_tunnels",
",",
"'overlay_gateway_'",
"'attach_rbridge_id_rb_remove'",
")",
"config",
"=",
"overlay_gw",
"(",
"*",
"*",
"gw_args",
")",
"else",
":",
"gw_args",
"=",
"dict",
"(",
"name",
"=",
"gw_name",
",",
"rb_add",
"=",
"rbridge_id",
")",
"overlay_gw",
"=",
"getattr",
"(",
"self",
".",
"_tunnels",
",",
"'overlay_gateway_'",
"'attach_rbridge_id_rb_add'",
")",
"config",
"=",
"overlay_gw",
"(",
"*",
"*",
"gw_args",
")",
"if",
"get_config",
":",
"overlay_gw",
"=",
"getattr",
"(",
"self",
".",
"_tunnels",
",",
"'overlay_gateway_'",
"'attach_rbridge_id_rb_add'",
")",
"config",
"=",
"overlay_gw",
"(",
"name",
"=",
"''",
",",
"rb_add",
"=",
"''",
")",
"output",
"=",
"callback",
"(",
"config",
",",
"handler",
"=",
"'get_config'",
")",
"if",
"output",
".",
"data",
".",
"find",
"(",
"'.//{*}name'",
")",
"is",
"not",
"None",
":",
"if",
"output",
".",
"data",
".",
"find",
"(",
"'.//{*}attach'",
")",
"is",
"not",
"None",
":",
"output",
".",
"data",
".",
"find",
"(",
"'.//{*}name'",
")",
".",
"text",
"rb_id",
"=",
"output",
".",
"data",
".",
"find",
"(",
"'.//{*}rb-add'",
")",
".",
"text",
"return",
"rb_id",
"else",
":",
"return",
"None",
"else",
":",
"return",
"None",
"return",
"callback",
"(",
"config",
")"
] |
Add validator to property | def add_validator ( self , validator ) : if not isinstance ( validator , AbstractValidator ) : err = 'Validator must be of type {}' . format ( AbstractValidator ) raise InvalidValidator ( err ) self . validators . append ( validator ) return self | 8,132 | https://github.com/projectshift/shift-schema/blob/07787b540d3369bb37217ffbfbe629118edaf0eb/shiftschema/property.py#L42-L54 | [
"def",
"devices",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"# b313b945 device usb:1-7 product:d2vzw model:SCH_I535 device:d2vzw",
"# from Android system/core/adb/transport.c statename()",
"re_device_info",
"=",
"re",
".",
"compile",
"(",
"r'([^\\s]+)\\s+(offline|bootloader|device|host|recovery|sideload|no permissions|unauthorized|unknown)'",
")",
"devices",
"=",
"[",
"]",
"lines",
"=",
"self",
".",
"command_output",
"(",
"[",
"\"devices\"",
",",
"\"-l\"",
"]",
",",
"timeout",
"=",
"timeout",
")",
".",
"split",
"(",
"'\\n'",
")",
"for",
"line",
"in",
"lines",
":",
"if",
"line",
"==",
"'List of devices attached '",
":",
"continue",
"match",
"=",
"re_device_info",
".",
"match",
"(",
"line",
")",
"if",
"match",
":",
"device",
"=",
"{",
"'device_serial'",
":",
"match",
".",
"group",
"(",
"1",
")",
",",
"'state'",
":",
"match",
".",
"group",
"(",
"2",
")",
"}",
"remainder",
"=",
"line",
"[",
"match",
".",
"end",
"(",
"2",
")",
":",
"]",
".",
"strip",
"(",
")",
"if",
"remainder",
":",
"try",
":",
"device",
".",
"update",
"(",
"dict",
"(",
"[",
"j",
".",
"split",
"(",
"':'",
")",
"for",
"j",
"in",
"remainder",
".",
"split",
"(",
"' '",
")",
"]",
")",
")",
"except",
"ValueError",
":",
"self",
".",
"_logger",
".",
"warning",
"(",
"'devices: Unable to parse '",
"'remainder for device %s'",
"%",
"line",
")",
"devices",
".",
"append",
"(",
"device",
")",
"return",
"devices"
] |
Sequentially applies all the filters to provided value | def filter ( self , value = None , model = None , context = None ) : if value is None : return value for filter_obj in self . filters : value = filter_obj . filter ( value = value , model = model , context = context if self . use_context else None ) return value | 8,133 | https://github.com/projectshift/shift-schema/blob/07787b540d3369bb37217ffbfbe629118edaf0eb/shiftschema/property.py#L56-L73 | [
"def",
"get_status",
"(",
"self",
")",
":",
"status",
"=",
"ctypes",
".",
"c_int32",
"(",
")",
"result",
"=",
"self",
".",
"library",
".",
"Par_GetStatus",
"(",
"self",
".",
"pointer",
",",
"ctypes",
".",
"byref",
"(",
"status",
")",
")",
"check_error",
"(",
"result",
",",
"\"partner\"",
")",
"return",
"status"
] |
Sequentially apply each validator to value and collect errors . | def validate ( self , value = None , model = None , context = None ) : errors = [ ] for validator in self . validators : if value is None and not isinstance ( validator , Required ) : continue error = validator . run ( value = value , model = model , context = context if self . use_context else None ) if error : errors . append ( error ) return errors | 8,134 | https://github.com/projectshift/shift-schema/blob/07787b540d3369bb37217ffbfbe629118edaf0eb/shiftschema/property.py#L75-L97 | [
"def",
"add_stickiness",
"(",
"self",
")",
":",
"stickiness_dict",
"=",
"{",
"}",
"env",
"=",
"boto3",
".",
"session",
".",
"Session",
"(",
"profile_name",
"=",
"self",
".",
"env",
",",
"region_name",
"=",
"self",
".",
"region",
")",
"elbclient",
"=",
"env",
".",
"client",
"(",
"'elb'",
")",
"elb_settings",
"=",
"self",
".",
"properties",
"[",
"'elb'",
"]",
"for",
"listener",
"in",
"elb_settings",
".",
"get",
"(",
"'ports'",
")",
":",
"if",
"listener",
".",
"get",
"(",
"\"stickiness\"",
")",
":",
"sticky_type",
"=",
"listener",
"[",
"'stickiness'",
"]",
"[",
"'type'",
"]",
".",
"lower",
"(",
")",
"externalport",
"=",
"int",
"(",
"listener",
"[",
"'loadbalancer'",
"]",
".",
"split",
"(",
"\":\"",
")",
"[",
"-",
"1",
"]",
")",
"policyname_tmp",
"=",
"\"{0}-{1}-{2}-{3}\"",
"if",
"sticky_type",
"==",
"'app'",
":",
"cookiename",
"=",
"listener",
"[",
"'stickiness'",
"]",
"[",
"'cookie_name'",
"]",
"policy_key",
"=",
"cookiename",
".",
"replace",
"(",
"'.'",
",",
"''",
")",
"policyname",
"=",
"policyname_tmp",
".",
"format",
"(",
"self",
".",
"app",
",",
"sticky_type",
",",
"externalport",
",",
"policy_key",
")",
"elbclient",
".",
"create_app_cookie_stickiness_policy",
"(",
"LoadBalancerName",
"=",
"self",
".",
"app",
",",
"PolicyName",
"=",
"policyname",
",",
"CookieName",
"=",
"cookiename",
")",
"stickiness_dict",
"[",
"externalport",
"]",
"=",
"policyname",
"elif",
"sticky_type",
"==",
"'elb'",
":",
"cookie_ttl",
"=",
"listener",
"[",
"'stickiness'",
"]",
".",
"get",
"(",
"'cookie_ttl'",
",",
"None",
")",
"policyname",
"=",
"policyname_tmp",
".",
"format",
"(",
"self",
".",
"app",
",",
"sticky_type",
",",
"externalport",
",",
"cookie_ttl",
")",
"if",
"cookie_ttl",
":",
"elbclient",
".",
"create_lb_cookie_stickiness_policy",
"(",
"LoadBalancerName",
"=",
"self",
".",
"app",
",",
"PolicyName",
"=",
"policyname",
",",
"CookieExpirationPeriod",
"=",
"cookie_ttl",
")",
"else",
":",
"elbclient",
".",
"create_lb_cookie_stickiness_policy",
"(",
"LoadBalancerName",
"=",
"self",
".",
"app",
",",
"PolicyName",
"=",
"policyname",
")",
"stickiness_dict",
"[",
"externalport",
"]",
"=",
"policyname",
"return",
"stickiness_dict"
] |
Perform model filtering with schema | def filter_with_schema ( self , model = None , context = None ) : if model is None or self . schema is None : return self . _schema . filter ( model = model , context = context if self . use_context else None ) | 8,135 | https://github.com/projectshift/shift-schema/blob/07787b540d3369bb37217ffbfbe629118edaf0eb/shiftschema/property.py#L125-L133 | [
"def",
"get_tuids_from_revision",
"(",
"self",
",",
"revision",
")",
":",
"result",
"=",
"[",
"]",
"URL_TO_FILES",
"=",
"self",
".",
"hg_url",
"/",
"self",
".",
"config",
".",
"hg",
".",
"branch",
"/",
"'json-info'",
"/",
"revision",
"try",
":",
"mozobject",
"=",
"http",
".",
"get_json",
"(",
"url",
"=",
"URL_TO_FILES",
",",
"retry",
"=",
"RETRY",
")",
"except",
"Exception",
"as",
"e",
":",
"Log",
".",
"warning",
"(",
"\"Unexpected error trying to get file list for revision {{revision}}\"",
",",
"cause",
"=",
"e",
")",
"return",
"None",
"files",
"=",
"mozobject",
"[",
"revision",
"]",
"[",
"'files'",
"]",
"results",
"=",
"self",
".",
"get_tuids",
"(",
"files",
",",
"revision",
")",
"return",
"results"
] |
Perform model validation with schema | def validate_with_schema ( self , model = None , context = None ) : if self . _schema is None or model is None : return result = self . _schema . validate ( model = model , context = context if self . use_context else None ) return result | 8,136 | https://github.com/projectshift/shift-schema/blob/07787b540d3369bb37217ffbfbe629118edaf0eb/shiftschema/property.py#L135-L144 | [
"def",
"_restart_session",
"(",
"self",
",",
"session",
")",
":",
"# remove old session key, if socket is None, that means the",
"# session was closed by user and there is no need to restart.",
"if",
"session",
".",
"socket",
"is",
"not",
"None",
":",
"self",
".",
"log",
".",
"info",
"(",
"\"Attempting restart session for Monitor Id %s.\"",
"%",
"session",
".",
"monitor_id",
")",
"del",
"self",
".",
"sessions",
"[",
"session",
".",
"socket",
".",
"fileno",
"(",
")",
"]",
"session",
".",
"stop",
"(",
")",
"session",
".",
"start",
"(",
")",
"self",
".",
"sessions",
"[",
"session",
".",
"socket",
".",
"fileno",
"(",
")",
"]",
"=",
"session"
] |
Perform collection items filtering with schema | def filter_with_schema ( self , collection = None , context = None ) : if collection is None or self . schema is None : return try : for item in collection : self . _schema . filter ( model = item , context = context if self . use_context else None ) except TypeError : pass | 8,137 | https://github.com/projectshift/shift-schema/blob/07787b540d3369bb37217ffbfbe629118edaf0eb/shiftschema/property.py#L155-L167 | [
"def",
"run_tensorboard",
"(",
"logdir",
",",
"listen_on",
"=",
"\"0.0.0.0\"",
",",
"port",
"=",
"0",
",",
"tensorboard_args",
"=",
"None",
",",
"timeout",
"=",
"10",
")",
":",
"if",
"tensorboard_args",
"is",
"None",
":",
"tensorboard_args",
"=",
"[",
"]",
"tensorboard_instance",
"=",
"Process",
".",
"create_process",
"(",
"TENSORBOARD_BINARY",
".",
"split",
"(",
"\" \"",
")",
"+",
"[",
"\"--logdir\"",
",",
"logdir",
",",
"\"--host\"",
",",
"listen_on",
",",
"\"--port\"",
",",
"str",
"(",
"port",
")",
"]",
"+",
"tensorboard_args",
")",
"try",
":",
"tensorboard_instance",
".",
"run",
"(",
")",
"except",
"FileNotFoundError",
"as",
"ex",
":",
"raise",
"TensorboardNotFoundError",
"(",
"ex",
")",
"# Wait for a message that signaliezes start of Tensorboard",
"start",
"=",
"time",
".",
"time",
"(",
")",
"data",
"=",
"\"\"",
"while",
"time",
".",
"time",
"(",
")",
"-",
"start",
"<",
"timeout",
":",
"line",
"=",
"tensorboard_instance",
".",
"read_line_stderr",
"(",
"time_limit",
"=",
"timeout",
")",
"data",
"+=",
"line",
"if",
"\"at http://\"",
"in",
"line",
":",
"port",
"=",
"parse_port_from_tensorboard_output",
"(",
"line",
")",
"# Good case",
"return",
"port",
"elif",
"\"TensorBoard attempted to bind to port\"",
"in",
"line",
":",
"break",
"tensorboard_instance",
".",
"terminate",
"(",
")",
"raise",
"UnexpectedOutputError",
"(",
"data",
",",
"expected",
"=",
"\"Confirmation that Tensorboard has started\"",
")"
] |
Validate each item in collection with our schema | def validate_with_schema ( self , collection = None , context = None ) : if self . _schema is None or not collection : return result = [ ] try : for index , item in enumerate ( collection ) : item_result = self . _schema . validate ( model = item , context = context if self . use_context else None ) result . append ( item_result ) except TypeError : pass return result | 8,138 | https://github.com/projectshift/shift-schema/blob/07787b540d3369bb37217ffbfbe629118edaf0eb/shiftschema/property.py#L169-L185 | [
"def",
"start_transmit",
"(",
"self",
",",
"blocking",
"=",
"False",
",",
"start_packet_groups",
"=",
"True",
",",
"*",
"ports",
")",
":",
"port_list",
"=",
"self",
".",
"set_ports_list",
"(",
"*",
"ports",
")",
"if",
"start_packet_groups",
":",
"port_list_for_packet_groups",
"=",
"self",
".",
"ports",
".",
"values",
"(",
")",
"port_list_for_packet_groups",
"=",
"self",
".",
"set_ports_list",
"(",
"*",
"port_list_for_packet_groups",
")",
"self",
".",
"api",
".",
"call_rc",
"(",
"'ixClearTimeStamp {}'",
".",
"format",
"(",
"port_list_for_packet_groups",
")",
")",
"self",
".",
"api",
".",
"call_rc",
"(",
"'ixStartPacketGroups {}'",
".",
"format",
"(",
"port_list_for_packet_groups",
")",
")",
"self",
".",
"api",
".",
"call_rc",
"(",
"'ixStartTransmit {}'",
".",
"format",
"(",
"port_list",
")",
")",
"time",
".",
"sleep",
"(",
"0.2",
")",
"if",
"blocking",
":",
"self",
".",
"wait_transmit",
"(",
"*",
"ports",
")"
] |
Computes a cross - kernel stable hash value for the given object . | def json_based_stable_hash ( obj ) : encoded_str = json . dumps ( obj = obj , skipkeys = False , ensure_ascii = False , check_circular = True , allow_nan = True , cls = None , indent = 0 , separators = ( ',' , ':' ) , default = None , sort_keys = True , ) . encode ( 'utf-8' ) return hashlib . sha256 ( encoded_str ) . hexdigest ( ) | 8,139 | https://github.com/shaypal5/strct/blob/f3a301692d052ddb79331230b3c00625db1d83fc/strct/hash/_hash.py#L86-L122 | [
"def",
"log_assist_response_without_audio",
"(",
"assist_response",
")",
":",
"if",
"logging",
".",
"getLogger",
"(",
")",
".",
"isEnabledFor",
"(",
"logging",
".",
"DEBUG",
")",
":",
"resp_copy",
"=",
"embedded_assistant_pb2",
".",
"AssistResponse",
"(",
")",
"resp_copy",
".",
"CopyFrom",
"(",
"assist_response",
")",
"has_audio_data",
"=",
"(",
"resp_copy",
".",
"HasField",
"(",
"'audio_out'",
")",
"and",
"len",
"(",
"resp_copy",
".",
"audio_out",
".",
"audio_data",
")",
">",
"0",
")",
"if",
"has_audio_data",
":",
"size",
"=",
"len",
"(",
"resp_copy",
".",
"audio_out",
".",
"audio_data",
")",
"resp_copy",
".",
"audio_out",
".",
"ClearField",
"(",
"'audio_data'",
")",
"if",
"resp_copy",
".",
"audio_out",
".",
"ListFields",
"(",
")",
":",
"logging",
".",
"debug",
"(",
"'AssistResponse: %s audio_data (%d bytes)'",
",",
"resp_copy",
",",
"size",
")",
"else",
":",
"logging",
".",
"debug",
"(",
"'AssistResponse: audio_data (%d bytes)'",
",",
"size",
")",
"return",
"logging",
".",
"debug",
"(",
"'AssistResponse: %s'",
",",
"resp_copy",
")"
] |
Read HTTP - request line | def read_request_line ( self , request_line ) : request = self . __request_cls . parse_request_line ( self , request_line ) protocol_version = self . protocol_version ( ) if protocol_version == '0.9' : if request . method ( ) != 'GET' : raise Exception ( 'HTTP/0.9 standard violation' ) elif protocol_version == '1.0' or protocol_version == '1.1' : pass elif protocol_version == '2' : pass else : raise RuntimeError ( 'Unsupported HTTP-protocol' ) | 8,140 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/web/session.py#L67-L88 | [
"def",
"extract_notebook_metatab",
"(",
"nb_path",
":",
"Path",
")",
":",
"from",
"metatab",
".",
"rowgenerators",
"import",
"TextRowGenerator",
"import",
"nbformat",
"with",
"nb_path",
".",
"open",
"(",
")",
"as",
"f",
":",
"nb",
"=",
"nbformat",
".",
"read",
"(",
"f",
",",
"as_version",
"=",
"4",
")",
"lines",
"=",
"'\\n'",
".",
"join",
"(",
"[",
"'Declare: metatab-latest'",
"]",
"+",
"[",
"get_cell_source",
"(",
"nb",
",",
"tag",
")",
"for",
"tag",
"in",
"[",
"'metadata'",
",",
"'resources'",
",",
"'schema'",
"]",
"]",
")",
"doc",
"=",
"MetapackDoc",
"(",
"TextRowGenerator",
"(",
"lines",
")",
")",
"doc",
"[",
"'Root'",
"]",
".",
"get_or_new_term",
"(",
"'Root.Title'",
")",
".",
"value",
"=",
"get_cell_source",
"(",
"nb",
",",
"'Title'",
")",
".",
"strip",
"(",
"'#'",
")",
".",
"strip",
"(",
")",
"doc",
"[",
"'Root'",
"]",
".",
"get_or_new_term",
"(",
"'Root.Description'",
")",
".",
"value",
"=",
"get_cell_source",
"(",
"nb",
",",
"'Description'",
")",
"doc",
"[",
"'Documentation'",
"]",
".",
"get_or_new_term",
"(",
"'Root.Readme'",
")",
".",
"value",
"=",
"get_cell_source",
"(",
"nb",
",",
"'readme'",
")",
"return",
"doc"
] |
Create the class using all metaclasses . | def metaclass ( * metaclasses ) : # type: (*type) -> Callable[[type], type] def _inner ( cls ) : # pragma pylint: disable=unused-variable metabases = tuple ( collections . OrderedDict ( # noqa: F841 ( c , None ) for c in ( metaclasses + ( type ( cls ) , ) ) ) . keys ( ) ) # pragma pylint: enable=unused-variable _Meta = metabases [ 0 ] for base in metabases [ 1 : ] : class _Meta ( base , _Meta ) : # pylint: disable=function-redefined pass return six . add_metaclass ( _Meta ) ( cls ) return _inner | 8,141 | https://github.com/contains-io/typet/blob/ad5087c567af84db299eca186776e1cee228e442/typet/meta.py#L38-L67 | [
"def",
"resume",
"(",
"env",
",",
"identifier",
")",
":",
"vsi",
"=",
"SoftLayer",
".",
"VSManager",
"(",
"env",
".",
"client",
")",
"vs_id",
"=",
"helpers",
".",
"resolve_id",
"(",
"vsi",
".",
"resolve_ids",
",",
"identifier",
",",
"'VS'",
")",
"env",
".",
"client",
"[",
"'Virtual_Guest'",
"]",
".",
"resume",
"(",
"id",
"=",
"vs_id",
")"
] |
Function for the Basic UI | def get_attrition_in_years ( self ) : attrition_of_nets = self . itn . find ( "attritionOfNets" ) function = attrition_of_nets . attrib [ "function" ] if function != "step" : return None L = attrition_of_nets . attrib [ "L" ] return L | 8,142 | https://github.com/vecnet/vecnet.openmalaria/blob/795bc9d1b81a6c664f14879edda7a7c41188e95a/vecnet/openmalaria/scenario/interventions.py#L374-L383 | [
"def",
"returnJobReqs",
"(",
"self",
",",
"jobReqs",
")",
":",
"# Since we are only reading this job's specific values from the state file, we don't",
"# need a lock",
"jobState",
"=",
"self",
".",
"_JobState",
"(",
"self",
".",
"_CacheState",
".",
"_load",
"(",
"self",
".",
"cacheStateFile",
")",
".",
"jobState",
"[",
"self",
".",
"jobID",
"]",
")",
"for",
"x",
"in",
"list",
"(",
"jobState",
".",
"jobSpecificFiles",
".",
"keys",
"(",
")",
")",
":",
"self",
".",
"deleteLocalFile",
"(",
"x",
")",
"with",
"self",
".",
"_CacheState",
".",
"open",
"(",
"self",
")",
"as",
"cacheInfo",
":",
"cacheInfo",
".",
"sigmaJob",
"-=",
"jobReqs"
] |
Add an intervention to vectorPop section . intervention is either ElementTree or xml snippet | def add ( self , intervention , name = None ) : if self . et is None : return assert isinstance ( intervention , six . string_types ) et = ElementTree . fromstring ( intervention ) vector_pop = VectorPopIntervention ( et ) assert isinstance ( vector_pop . name , six . string_types ) if name is not None : assert isinstance ( name , six . string_types ) et . attrib [ "name" ] = name index = len ( self . et . findall ( "intervention" ) ) self . et . insert ( index , et ) | 8,143 | https://github.com/vecnet/vecnet.openmalaria/blob/795bc9d1b81a6c664f14879edda7a7c41188e95a/vecnet/openmalaria/scenario/interventions.py#L1046-L1065 | [
"def",
"update",
"(",
"self",
",",
"friendly_name",
"=",
"values",
".",
"unset",
",",
"status",
"=",
"values",
".",
"unset",
")",
":",
"return",
"self",
".",
"_proxy",
".",
"update",
"(",
"friendly_name",
"=",
"friendly_name",
",",
"status",
"=",
"status",
",",
")"
] |
Add new record to history . Record will be added to the end | def add ( self , value ) : index = len ( self . __history ) self . __history . append ( value ) return index | 8,144 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/cli/cli.py#L69-L77 | [
"def",
"set_objective",
"(",
"self",
",",
"measured_metabolites",
")",
":",
"self",
".",
"clean_objective",
"(",
")",
"for",
"k",
",",
"v",
"in",
"measured_metabolites",
".",
"items",
"(",
")",
":",
"m",
"=",
"self",
".",
"model",
".",
"metabolites",
".",
"get_by_id",
"(",
"k",
")",
"total_stoichiometry",
"=",
"m",
".",
"total_stoichiometry",
"(",
"self",
".",
"without_transports",
")",
"for",
"r",
"in",
"m",
".",
"producers",
"(",
"self",
".",
"without_transports",
")",
":",
"update_rate",
"=",
"v",
"*",
"r",
".",
"metabolites",
"[",
"m",
"]",
"/",
"total_stoichiometry",
"r",
".",
"objective_coefficient",
"+=",
"update_rate"
] |
Start new session and prepare environment for new row editing process | def start_session ( self ) : self . __current_row = '' self . __history_mode = False self . __editable_history = deepcopy ( self . __history ) self . __prompt_show = True self . refresh_window ( ) | 8,145 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/cli/cli.py#L139-L148 | [
"def",
"_strip_ctype",
"(",
"name",
",",
"ctype",
",",
"protocol",
"=",
"2",
")",
":",
"# parse channel type from name (e.g. 'L1:GDS-CALIB_STRAIN,reduced')",
"try",
":",
"name",
",",
"ctypestr",
"=",
"name",
".",
"rsplit",
"(",
"','",
",",
"1",
")",
"except",
"ValueError",
":",
"pass",
"else",
":",
"ctype",
"=",
"Nds2ChannelType",
".",
"find",
"(",
"ctypestr",
")",
".",
"value",
"# NDS1 stores channels with trend suffix, so we put it back:",
"if",
"protocol",
"==",
"1",
"and",
"ctype",
"in",
"(",
"Nds2ChannelType",
".",
"STREND",
".",
"value",
",",
"Nds2ChannelType",
".",
"MTREND",
".",
"value",
")",
":",
"name",
"+=",
"',{0}'",
".",
"format",
"(",
"ctypestr",
")",
"return",
"name",
",",
"ctype"
] |
Finalize current session | def fin_session ( self ) : self . __prompt_show = False self . __history . add ( self . row ( ) ) self . exec ( self . row ( ) ) | 8,146 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/cli/cli.py#L150-L157 | [
"def",
"do_watch",
"(",
"self",
",",
"*",
"args",
")",
":",
"tables",
"=",
"[",
"]",
"if",
"not",
"self",
".",
"engine",
".",
"cached_descriptions",
":",
"self",
".",
"engine",
".",
"describe_all",
"(",
")",
"all_tables",
"=",
"list",
"(",
"self",
".",
"engine",
".",
"cached_descriptions",
")",
"for",
"arg",
"in",
"args",
":",
"candidates",
"=",
"set",
"(",
"(",
"t",
"for",
"t",
"in",
"all_tables",
"if",
"fnmatch",
"(",
"t",
",",
"arg",
")",
")",
")",
"for",
"t",
"in",
"sorted",
"(",
"candidates",
")",
":",
"if",
"t",
"not",
"in",
"tables",
":",
"tables",
".",
"append",
"(",
"t",
")",
"mon",
"=",
"Monitor",
"(",
"self",
".",
"engine",
",",
"tables",
")",
"mon",
".",
"start",
"(",
")"
] |
Return output data . Flags specifies what data to append . If no flags was specified nul - length string returned | def data ( self , previous_data = False , prompt = False , console_row = False , console_row_to_cursor = False , console_row_from_cursor = False ) : result = '' if previous_data : result += self . __previous_data if prompt or console_row or console_row_to_cursor : result += self . console ( ) . prompt ( ) if console_row or ( console_row_from_cursor and console_row_to_cursor ) : result += self . console ( ) . row ( ) elif console_row_to_cursor : result += self . console ( ) . row ( ) [ : self . cursor ( ) ] elif console_row_from_cursor : result += self . console ( ) . row ( ) [ self . cursor ( ) : ] return result | 8,147 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/cli/cli.py#L299-L332 | [
"def",
"unmount",
"(",
"self",
")",
":",
"self",
".",
"unmount_bindmounts",
"(",
")",
"self",
".",
"unmount_mounts",
"(",
")",
"self",
".",
"unmount_volume_groups",
"(",
")",
"self",
".",
"unmount_loopbacks",
"(",
")",
"self",
".",
"unmount_base_images",
"(",
")",
"self",
".",
"clean_dirs",
"(",
")"
] |
Write data from the specified line | def write_data ( self , data , start_position = 0 ) : if len ( data ) > self . height ( ) : raise ValueError ( 'Data too long (too many strings)' ) for i in range ( len ( data ) ) : self . write_line ( start_position + i , data [ i ] ) | 8,148 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/cli/cli.py#L359-L370 | [
"def",
"group_experiments_greedy",
"(",
"tomo_expt",
":",
"TomographyExperiment",
")",
":",
"diag_sets",
"=",
"_max_tpb_overlap",
"(",
"tomo_expt",
")",
"grouped_expt_settings_list",
"=",
"list",
"(",
"diag_sets",
".",
"values",
"(",
")",
")",
"grouped_tomo_expt",
"=",
"TomographyExperiment",
"(",
"grouped_expt_settings_list",
",",
"program",
"=",
"tomo_expt",
".",
"program",
")",
"return",
"grouped_tomo_expt"
] |
Store feedback . Keep specified feedback as previous output | def write_feedback ( self , feedback , cr = True ) : self . __previous_data += feedback if cr is True : self . __previous_data += '\n' | 8,149 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/cli/cli.py#L421-L430 | [
"def",
"delete_all_volumes",
"(",
"self",
")",
":",
"# Raise an exception if we are not a manager",
"if",
"not",
"self",
".",
"_manager",
":",
"raise",
"RuntimeError",
"(",
"'Volumes can only be deleted '",
"'on swarm manager nodes'",
")",
"volume_list",
"=",
"self",
".",
"get_volume_list",
"(",
")",
"for",
"volumes",
"in",
"volume_list",
":",
"# Remove all the services",
"self",
".",
"_api_client",
".",
"remove_volume",
"(",
"volumes",
",",
"force",
"=",
"True",
")"
] |
Refresh current window . Clear current window and redraw it with one of drawers | def refresh ( self , prompt_show = True ) : self . clear ( ) for drawer in self . __drawers : if drawer . suitable ( self , prompt_show = prompt_show ) : drawer . draw ( self , prompt_show = prompt_show ) return raise RuntimeError ( 'No suitable drawer was found' ) | 8,150 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/cli/cli.py#L484-L498 | [
"def",
"_process_cluster_health_data",
"(",
"self",
",",
"node_name",
",",
"node_stats",
",",
"tags",
")",
":",
"# Tags for service check",
"cluster_health_tags",
"=",
"list",
"(",
"tags",
")",
"+",
"[",
"'node:{}'",
".",
"format",
"(",
"node_name",
")",
"]",
"# Get the membership status of the node",
"cluster_membership",
"=",
"node_stats",
".",
"get",
"(",
"'clusterMembership'",
",",
"None",
")",
"membership_status",
"=",
"self",
".",
"NODE_MEMBERSHIP_TRANSLATION",
".",
"get",
"(",
"cluster_membership",
",",
"AgentCheck",
".",
"UNKNOWN",
")",
"self",
".",
"service_check",
"(",
"self",
".",
"NODE_CLUSTER_SERVICE_CHECK_NAME",
",",
"membership_status",
",",
"tags",
"=",
"cluster_health_tags",
")",
"# Get the health status of the node",
"health",
"=",
"node_stats",
".",
"get",
"(",
"'status'",
",",
"None",
")",
"health_status",
"=",
"self",
".",
"NODE_HEALTH_TRANSLATION",
".",
"get",
"(",
"health",
",",
"AgentCheck",
".",
"UNKNOWN",
")",
"self",
".",
"service_check",
"(",
"self",
".",
"NODE_HEALTH_SERVICE_CHECK_NAME",
",",
"health_status",
",",
"tags",
"=",
"cluster_health_tags",
")"
] |
Determine if a Path or string is a directory on the file system . | def is_dir ( path ) : try : return path . expanduser ( ) . absolute ( ) . is_dir ( ) except AttributeError : return os . path . isdir ( os . path . abspath ( os . path . expanduser ( str ( path ) ) ) ) | 8,151 | https://github.com/contains-io/typet/blob/ad5087c567af84db299eca186776e1cee228e442/typet/path.py#L30-L35 | [
"def",
"_update_mappings",
"(",
"self",
")",
":",
"headers",
"=",
"{",
"'Content-Type'",
":",
"'application/json'",
",",
"'DB-Method'",
":",
"'PUT'",
"}",
"url",
"=",
"'/v2/exchange/db/{}/{}/_mappings'",
".",
"format",
"(",
"self",
".",
"domain",
",",
"self",
".",
"data_type",
")",
"r",
"=",
"self",
".",
"tcex",
".",
"session",
".",
"post",
"(",
"url",
",",
"json",
"=",
"self",
".",
"mapping",
",",
"headers",
"=",
"headers",
")",
"self",
".",
"tcex",
".",
"log",
".",
"debug",
"(",
"'update mapping. status_code: {}, response: \"{}\".'",
".",
"format",
"(",
"r",
".",
"status_code",
",",
"r",
".",
"text",
")",
")"
] |
Determine if a Path or string is a file on the file system . | def is_file ( path ) : try : return path . expanduser ( ) . absolute ( ) . is_file ( ) except AttributeError : return os . path . isfile ( os . path . abspath ( os . path . expanduser ( str ( path ) ) ) ) | 8,152 | https://github.com/contains-io/typet/blob/ad5087c567af84db299eca186776e1cee228e442/typet/path.py#L38-L43 | [
"def",
"create_mappings",
"(",
"self",
",",
"config",
")",
":",
"mappings",
"=",
"{",
"}",
"for",
"name",
",",
"cfg",
"in",
"config",
".",
"items",
"(",
")",
":",
"# Ignore special config sections.",
"if",
"name",
"in",
"CONFIG_SPECIAL_SECTIONS",
":",
"continue",
"color",
"=",
"self",
".",
"get_config_attribute",
"(",
"name",
",",
"\"color\"",
")",
"if",
"hasattr",
"(",
"color",
",",
"\"none_setting\"",
")",
":",
"color",
"=",
"None",
"mappings",
"[",
"name",
"]",
"=",
"color",
"# Store mappings for later use.",
"self",
".",
"mappings_color",
"=",
"mappings"
] |
Determine if a Path or string is an existing path on the file system . | def exists ( path ) : try : return path . expanduser ( ) . absolute ( ) . exists ( ) except AttributeError : return os . path . exists ( os . path . abspath ( os . path . expanduser ( str ( path ) ) ) ) | 8,153 | https://github.com/contains-io/typet/blob/ad5087c567af84db299eca186776e1cee228e442/typet/path.py#L46-L51 | [
"def",
"convert",
"(",
"self",
",",
"request",
",",
"response",
",",
"data",
")",
":",
"result",
"=",
"[",
"]",
"for",
"conv",
",",
"datum",
"in",
"zip",
"(",
"self",
".",
"conversions",
",",
"data",
")",
":",
"# Only include conversion if it's allowed",
"if",
"conv",
".",
"modifier",
".",
"accept",
"(",
"response",
".",
"status_code",
")",
":",
"result",
".",
"append",
"(",
"conv",
".",
"convert",
"(",
"request",
",",
"response",
",",
"datum",
")",
")",
"else",
":",
"result",
".",
"append",
"(",
"'-'",
")",
"return",
"''",
".",
"join",
"(",
"result",
")"
] |
Enable yank - pop . | def enableHook ( self , msgObj ) : self . killListIdx = len ( qte_global . kill_list ) - 2 self . qteMain . qtesigKeyseqComplete . connect ( self . disableHook ) | 8,154 | https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/extensions/qtmacstextedit_macros.py#L483-L492 | [
"def",
"store_contents",
"(",
"self",
")",
":",
"string_buffer",
"=",
"os",
".",
"linesep",
".",
"join",
"(",
"map",
"(",
"lambda",
"x",
":",
"os",
".",
"linesep",
".",
"join",
"(",
"[",
"\"<begin_table>\"",
"]",
"+",
"[",
"x",
".",
"name",
"]",
"+",
"x",
".",
"columns",
"+",
"[",
"\"<end_table>\"",
"]",
")",
",",
"self",
".",
"tables",
")",
")",
"with",
"open",
"(",
"METADATA_FILE",
",",
"\"w\"",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"string_buffer",
")",
"for",
"i",
"in",
"self",
".",
"tables",
":",
"i",
".",
"store_contents",
"(",
")"
] |
Update the highlighting . | def cursorPositionChangedEvent ( self ) : # Determine the sender and cursor position. qteWidget = self . sender ( ) tc = qteWidget . textCursor ( ) origin = tc . position ( ) # Remove all the highlighting. Since this will move the # cursor, first disconnect this very routine to avoid an # infinite recursion. qteWidget . cursorPositionChanged . disconnect ( self . cursorPositionChangedEvent ) self . qteRemoveHighlighting ( qteWidget ) qteWidget . cursorPositionChanged . connect ( self . cursorPositionChangedEvent ) # If we are beyond the last character (for instance because # the cursor was explicitly moved to the end of the buffer) # then there is no character to the right and will result in # an error when trying to fetch it. if origin >= len ( qteWidget . toPlainText ( ) ) : return else : # It is save to retrieve the character to the right of the # cursor. char = qteWidget . toPlainText ( ) [ origin ] # Return if the character is not in the matching list. if char not in self . charToHighlight : return # Disconnect the 'cursorPositionChanged' signal from this # function because it will make changes to the cursor position # and would therefore immediately trigger itself, resulting in # an infinite recursion. qteWidget . cursorPositionChanged . disconnect ( self . cursorPositionChangedEvent ) # If we got until here "char" must be one of the two # characters to highlight. if char == self . charToHighlight [ 0 ] : start = origin # Found the first character, so now look for the second # one. If this second character does not exist the # function returns '-1' which is safe because the # ``self.highlightCharacter`` method can deal with this. stop = qteWidget . toPlainText ( ) . find ( self . charToHighlight [ 1 ] , start + 1 ) else : # Found the second character so the start index is indeed # the stop index. stop = origin # Search for the preceeding first character. start = qteWidget . toPlainText ( ) . rfind ( self . charToHighlight [ 0 ] , 0 , stop ) # Highlight the characters. oldCharFormats = self . highlightCharacters ( qteWidget , ( start , stop ) , QtCore . Qt . blue , 100 ) # Store the positions of the changed character in the # macroData structure of this widget. data = self . qteMacroData ( qteWidget ) data . matchingPositions = ( start , stop ) data . oldCharFormats = oldCharFormats self . qteSaveMacroData ( data , qteWidget ) # Reconnect the 'cursorPositionChanged' signal. qteWidget . cursorPositionChanged . connect ( self . cursorPositionChangedEvent ) | 8,155 | https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/extensions/qtmacstextedit_macros.py#L899-L991 | [
"def",
"unbind",
"(",
"self",
",",
"devices_to_unbind",
")",
":",
"if",
"self",
".",
"entity_api_key",
"==",
"\"\"",
":",
"return",
"{",
"'status'",
":",
"'failure'",
",",
"'response'",
":",
"'No API key found in request'",
"}",
"url",
"=",
"self",
".",
"base_url",
"+",
"\"api/0.1.0/subscribe/unbind\"",
"headers",
"=",
"{",
"\"apikey\"",
":",
"self",
".",
"entity_api_key",
"}",
"data",
"=",
"{",
"\"exchange\"",
":",
"\"amq.topic\"",
",",
"\"keys\"",
":",
"devices_to_unbind",
",",
"\"queue\"",
":",
"self",
".",
"entity_id",
"}",
"with",
"self",
".",
"no_ssl_verification",
"(",
")",
":",
"r",
"=",
"requests",
".",
"delete",
"(",
"url",
",",
"json",
"=",
"data",
",",
"headers",
"=",
"headers",
")",
"print",
"(",
"r",
")",
"response",
"=",
"dict",
"(",
")",
"if",
"\"No API key\"",
"in",
"str",
"(",
"r",
".",
"content",
".",
"decode",
"(",
"\"utf-8\"",
")",
")",
":",
"response",
"[",
"\"status\"",
"]",
"=",
"\"failure\"",
"r",
"=",
"json",
".",
"loads",
"(",
"r",
".",
"content",
".",
"decode",
"(",
"\"utf-8\"",
")",
")",
"[",
"'message'",
"]",
"elif",
"'unbind'",
"in",
"str",
"(",
"r",
".",
"content",
".",
"decode",
"(",
"\"utf-8\"",
")",
")",
":",
"response",
"[",
"\"status\"",
"]",
"=",
"\"success\"",
"r",
"=",
"r",
".",
"content",
".",
"decode",
"(",
"\"utf-8\"",
")",
"else",
":",
"response",
"[",
"\"status\"",
"]",
"=",
"\"failure\"",
"r",
"=",
"r",
".",
"content",
".",
"decode",
"(",
"\"utf-8\"",
")",
"response",
"[",
"\"response\"",
"]",
"=",
"str",
"(",
"r",
")",
"return",
"response"
] |
Remove the highlighting from previously highlighted characters . | def qteRemoveHighlighting ( self , widgetObj ) : # Retrieve the widget specific macro data. data = self . qteMacroData ( widgetObj ) if not data : return # If the data structure is empty then no previously # highlighted characters exist in this particular widget, so # do nothing. if not data . matchingPositions : return # Restore the original character formats, ie. undo the # highlighting changes. self . highlightCharacters ( widgetObj , data . matchingPositions , QtCore . Qt . black , 50 , data . oldCharFormats ) # Clear the data structure to indicate that no further # highlighted characters exist in this particular widget. data . matchingPositions = None data . oldCharFormats = None self . qteSaveMacroData ( data , widgetObj ) | 8,156 | https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/extensions/qtmacstextedit_macros.py#L993-L1034 | [
"def",
"_check_data",
"(",
"data",
")",
":",
"if",
"\"vibfreqs\"",
"in",
"data",
".",
"columns",
":",
"for",
"species",
"in",
"data",
".",
"index",
":",
"vibfreqs",
"=",
"data",
".",
"loc",
"[",
"species",
",",
"\"vibfreqs\"",
"]",
"nimagvibfreqs",
"=",
"_np",
".",
"sum",
"(",
"_np",
".",
"array",
"(",
"vibfreqs",
")",
"<",
"0",
")",
"if",
"species",
"[",
"-",
"1",
"]",
"==",
"'#'",
"and",
"nimagvibfreqs",
"!=",
"1",
":",
"_warnings",
".",
"warn",
"(",
"\"'{}' should have 1 imaginary vibfreqs but {} \"",
"\"found\"",
".",
"format",
"(",
"species",
",",
"nimagvibfreqs",
")",
")",
"elif",
"species",
"[",
"-",
"1",
"]",
"!=",
"'#'",
"and",
"nimagvibfreqs",
"!=",
"0",
":",
"_warnings",
".",
"warn",
"(",
"\"'{}' should have no imaginary vibfreqs but {} \"",
"\"found\"",
".",
"format",
"(",
"species",
",",
"nimagvibfreqs",
")",
")"
] |
Change the character format of one or more characters . | def highlightCharacters ( self , widgetObj , setPos , colorCode , fontWeight , charFormat = None ) : # Get the text cursor and character format. textCursor = widgetObj . textCursor ( ) oldPos = textCursor . position ( ) retVal = [ ] # Change the character formats of all the characters placed at # the positions ``setPos``. for ii , pos in enumerate ( setPos ) : # Extract the position of the character to modify. pos = setPos [ ii ] # Ignore invalid positions. This can happen if the second # character does not exist and the find-functions in the # ``cursorPositionChangedEvent`` method returned # '-1'. Also, store **None** as the format for this # non-existent character. if pos < 0 : retVal . append ( None ) continue # Move the text cursor to the specified character position # and store its original character format (necessary to # "undo" the highlighting once the cursor was moved away # again). textCursor . setPosition ( pos ) retVal . append ( textCursor . charFormat ( ) ) # Change the character format. Either use the supplied # one, or use a generic one. if charFormat : # Use a specific character format (usually used to # undo the changes a previous call to # 'highlightCharacters' has made). fmt = charFormat [ ii ] else : # Modify the color and weight of the current character format. fmt = textCursor . charFormat ( ) # Get the brush and specify its foreground color and # style. In order to see the characters it is # necessary to explicitly specify a solidPattern style # but I have no idea why. myBrush = fmt . foreground ( ) myBrush . setColor ( colorCode ) myBrush . setStyle ( QtCore . Qt . SolidPattern ) fmt . setForeground ( myBrush ) fmt . setFontWeight ( fontWeight ) # Select the character and apply the selected format. textCursor . movePosition ( QtGui . QTextCursor . NextCharacter , QtGui . QTextCursor . KeepAnchor ) textCursor . setCharFormat ( fmt ) # Apply the textcursor to the current element. textCursor . setPosition ( oldPos ) widgetObj . setTextCursor ( textCursor ) return retVal | 8,157 | https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/extensions/qtmacstextedit_macros.py#L1036-L1122 | [
"def",
"subclass_exception",
"(",
"name",
",",
"parents",
",",
"module",
",",
"attached_to",
"=",
"None",
")",
":",
"class_dict",
"=",
"{",
"'__module__'",
":",
"module",
"}",
"if",
"attached_to",
"is",
"not",
"None",
":",
"def",
"__reduce__",
"(",
"self",
")",
":",
"# Exceptions are special - they've got state that isn't",
"# in self.__dict__. We assume it is all in self.args.",
"return",
"(",
"unpickle_inner_exception",
",",
"(",
"attached_to",
",",
"name",
")",
",",
"self",
".",
"args",
")",
"def",
"__setstate__",
"(",
"self",
",",
"args",
")",
":",
"self",
".",
"args",
"=",
"args",
"class_dict",
"[",
"'__reduce__'",
"]",
"=",
"__reduce__",
"class_dict",
"[",
"'__setstate__'",
"]",
"=",
"__setstate__",
"return",
"type",
"(",
"name",
",",
"parents",
",",
"class_dict",
")"
] |
Generator function . Spits out scenarios for this experiment | def scenarios ( self , generate_seed = False ) : seed = prime_numbers ( 1000 ) sweeps_all = self . experiment [ "sweeps" ] . keys ( ) if "combinations" in self . experiment : if isinstance ( self . experiment [ "combinations" ] , list ) : # For backward compatibility with experiments1-4s combinations_in_experiment = { " " : self . experiment [ "combinations" ] } # if self.experiment["combinations"] == []: # # Special notation for fully-factorial experiments # combinations_in_experiment = {" ":[[],[]]} else : # Combinations must be a dictionary in this particular case combinations_in_experiment = self . experiment [ "combinations" ] else : # Support no combinations element: combinations_in_experiment = dict ( ) # empty dict # 1) calculate combinations_sweeps (depends on ALL combinations_ items) # Get the list of fully factorial sweeps all_combinations_sweeps = [ ] all_combinations = [ ] for key , combinations_ in combinations_in_experiment . items ( ) : # generate all permutations of all combinations if not combinations_ : # Fully factorial experiment, shortcut for "combinations":[[],[]] combinations_sweeps = [ ] combinations = [ [ ] ] else : # First item in combinations list is a list of sweeps combinations_sweeps = combinations_ [ 0 ] # then - all combinations combinations = combinations_ [ 1 : ] for item in combinations_sweeps : # TODO: error if sweep is already in this list? all_combinations_sweeps . append ( item ) all_combinations . append ( ( combinations_sweeps , combinations ) ) sweeps_fully_factorial = list ( set ( sweeps_all ) - set ( all_combinations_sweeps ) ) # print "fully fact: %s" % sweeps_fully_factorial # 2) produce a list of all combinations of fully factorial sweeps # First sets of "combinations": the fully-factorial sweeps for sweep in sweeps_fully_factorial : all_combinations . append ( ( [ sweep ] , [ [ x ] for x in self . experiment [ "sweeps" ] [ sweep ] . keys ( ) ] ) ) # 3) take the dot (inner) product of the list above (fully factorial arm combinations) # with the first combinations list, that with the second combination list, ... # step-by-step reduce the list of combinations to a single item # (dot-product of each list of combinations) # this could use a lot of memory... red_iter = 0 # print "all combinations:", red_iter, all_combinations while len ( all_combinations ) > 1 : comb1 = all_combinations [ 0 ] comb2 = all_combinations [ 1 ] new_sweeps = comb1 [ 0 ] + comb2 [ 0 ] new_combinations = [ x + y for x in comb1 [ 1 ] for y in comb2 [ 1 ] ] all_combinations = [ ( new_sweeps , new_combinations ) ] + all_combinations [ 2 : ] red_iter += 1 # print "all combinations:", red_iter, all_combinations # 4) write out the document for each in (3), which should specify one arm for each # sweep with no repetition of combinations sweep_names = all_combinations [ 0 ] [ 0 ] combinations = all_combinations [ 0 ] [ 1 ] for combination in combinations : scenario = Scenario ( self . _apply_combination ( self . experiment [ "base" ] , sweep_names , combination ) ) scenario . parameters = dict ( zip ( sweep_names , combination ) ) if generate_seed : # Replace seed if requested by the user if "@seed@" in scenario . xml : scenario . xml = scenario . xml . replace ( "@seed@" , str ( next ( seed ) ) ) else : raise ( RuntimeError ( "@seed@ placeholder is not found" ) ) yield scenario | 8,158 | https://github.com/vecnet/vecnet.openmalaria/blob/795bc9d1b81a6c664f14879edda7a7c41188e95a/vecnet/openmalaria/experiment.py#L99-L177 | [
"def",
"delete_entity",
"(",
"self",
",",
"entity_id",
",",
"mount_point",
"=",
"DEFAULT_MOUNT_POINT",
")",
":",
"api_path",
"=",
"'/v1/{mount_point}/entity/id/{id}'",
".",
"format",
"(",
"mount_point",
"=",
"mount_point",
",",
"id",
"=",
"entity_id",
",",
")",
"return",
"self",
".",
"_adapter",
".",
"delete",
"(",
"url",
"=",
"api_path",
",",
")"
] |
Call a program | def lvm_info ( self , name = None ) : cmd = [ ] if self . sudo ( ) is False else [ 'sudo' ] cmd . extend ( [ self . command ( ) , '-c' ] ) if name is not None : cmd . append ( name ) output = subprocess . check_output ( cmd , timeout = self . cmd_timeout ( ) ) output = output . decode ( ) result = [ ] fields_count = self . fields_count ( ) for line in output . split ( '\n' ) : line = line . strip ( ) fields = line . split ( ':' ) if len ( fields ) == fields_count : result . append ( fields ) if name is not None and len ( result ) != 1 : raise RuntimeError ( 'Unable to parse command result' ) return tuple ( result ) | 8,159 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/os/linux/lvm.py#L95-L119 | [
"def",
"vn_release",
"(",
"call",
"=",
"None",
",",
"kwargs",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The vn_reserve function must be called with -f or --function.'",
")",
"if",
"kwargs",
"is",
"None",
":",
"kwargs",
"=",
"{",
"}",
"vn_id",
"=",
"kwargs",
".",
"get",
"(",
"'vn_id'",
",",
"None",
")",
"vn_name",
"=",
"kwargs",
".",
"get",
"(",
"'vn_name'",
",",
"None",
")",
"path",
"=",
"kwargs",
".",
"get",
"(",
"'path'",
",",
"None",
")",
"data",
"=",
"kwargs",
".",
"get",
"(",
"'data'",
",",
"None",
")",
"if",
"vn_id",
":",
"if",
"vn_name",
":",
"log",
".",
"warning",
"(",
"'Both the \\'vn_id\\' and \\'vn_name\\' arguments were provided. '",
"'\\'vn_id\\' will take precedence.'",
")",
"elif",
"vn_name",
":",
"vn_id",
"=",
"get_vn_id",
"(",
"kwargs",
"=",
"{",
"'name'",
":",
"vn_name",
"}",
")",
"else",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The vn_release function requires a \\'vn_id\\' or a \\'vn_name\\' to '",
"'be provided.'",
")",
"if",
"data",
":",
"if",
"path",
":",
"log",
".",
"warning",
"(",
"'Both the \\'data\\' and \\'path\\' arguments were provided. '",
"'\\'data\\' will take precedence.'",
")",
"elif",
"path",
":",
"with",
"salt",
".",
"utils",
".",
"files",
".",
"fopen",
"(",
"path",
",",
"mode",
"=",
"'r'",
")",
"as",
"rfh",
":",
"data",
"=",
"rfh",
".",
"read",
"(",
")",
"else",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The vn_release function requires either \\'data\\' or a \\'path\\' to '",
"'be provided.'",
")",
"server",
",",
"user",
",",
"password",
"=",
"_get_xml_rpc",
"(",
")",
"auth",
"=",
"':'",
".",
"join",
"(",
"[",
"user",
",",
"password",
"]",
")",
"response",
"=",
"server",
".",
"one",
".",
"vn",
".",
"release",
"(",
"auth",
",",
"int",
"(",
"vn_id",
")",
",",
"data",
")",
"ret",
"=",
"{",
"'action'",
":",
"'vn.release'",
",",
"'released'",
":",
"response",
"[",
"0",
"]",
",",
"'resource_id'",
":",
"response",
"[",
"1",
"]",
",",
"'error_code'",
":",
"response",
"[",
"2",
"]",
",",
"}",
"return",
"ret"
] |
Return UUID of logical volume | def uuid ( self ) : uuid_file = '/sys/block/%s/dm/uuid' % os . path . basename ( os . path . realpath ( self . volume_path ( ) ) ) lv_uuid = open ( uuid_file ) . read ( ) . strip ( ) if lv_uuid . startswith ( 'LVM-' ) is True : return lv_uuid [ 4 : ] return lv_uuid | 8,160 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/os/linux/lvm.py#L457-L466 | [
"def",
"main",
"(",
")",
":",
"fmt",
"=",
"'svg'",
"title",
"=",
"\"\"",
"if",
"'-h'",
"in",
"sys",
".",
"argv",
":",
"print",
"(",
"main",
".",
"__doc__",
")",
"sys",
".",
"exit",
"(",
")",
"if",
"'-f'",
"in",
"sys",
".",
"argv",
":",
"ind",
"=",
"sys",
".",
"argv",
".",
"index",
"(",
"'-f'",
")",
"file",
"=",
"sys",
".",
"argv",
"[",
"ind",
"+",
"1",
"]",
"X",
"=",
"numpy",
".",
"loadtxt",
"(",
"file",
")",
"file",
"=",
"sys",
".",
"argv",
"[",
"ind",
"+",
"2",
"]",
"X2",
"=",
"numpy",
".",
"loadtxt",
"(",
"file",
")",
"# else:",
"# X=numpy.loadtxt(sys.stdin,dtype=numpy.float)",
"else",
":",
"print",
"(",
"'-f option required'",
")",
"print",
"(",
"main",
".",
"__doc__",
")",
"sys",
".",
"exit",
"(",
")",
"if",
"'-fmt'",
"in",
"sys",
".",
"argv",
":",
"ind",
"=",
"sys",
".",
"argv",
".",
"index",
"(",
"'-fmt'",
")",
"fmt",
"=",
"sys",
".",
"argv",
"[",
"ind",
"+",
"1",
"]",
"if",
"'-t'",
"in",
"sys",
".",
"argv",
":",
"ind",
"=",
"sys",
".",
"argv",
".",
"index",
"(",
"'-t'",
")",
"title",
"=",
"sys",
".",
"argv",
"[",
"ind",
"+",
"1",
"]",
"CDF",
"=",
"{",
"'X'",
":",
"1",
"}",
"pmagplotlib",
".",
"plot_init",
"(",
"CDF",
"[",
"'X'",
"]",
",",
"5",
",",
"5",
")",
"pmagplotlib",
".",
"plot_cdf",
"(",
"CDF",
"[",
"'X'",
"]",
",",
"X",
",",
"''",
",",
"'r'",
",",
"''",
")",
"pmagplotlib",
".",
"plot_cdf",
"(",
"CDF",
"[",
"'X'",
"]",
",",
"X2",
",",
"title",
",",
"'b'",
",",
"''",
")",
"D",
",",
"p",
"=",
"scipy",
".",
"stats",
".",
"ks_2samp",
"(",
"X",
",",
"X2",
")",
"if",
"p",
">=",
".05",
":",
"print",
"(",
"D",
",",
"p",
",",
"' not rejected at 95%'",
")",
"else",
":",
"print",
"(",
"D",
",",
"p",
",",
"' rejected at 95%'",
")",
"pmagplotlib",
".",
"draw_figs",
"(",
"CDF",
")",
"ans",
"=",
"input",
"(",
"'S[a]ve plot, <Return> to quit '",
")",
"if",
"ans",
"==",
"'a'",
":",
"files",
"=",
"{",
"'X'",
":",
"'CDF_.'",
"+",
"fmt",
"}",
"pmagplotlib",
".",
"save_plots",
"(",
"CDF",
",",
"files",
")"
] |
Create snapshot for this logical volume . | def create_snapshot ( self , snapshot_size , snapshot_suffix ) : size_extent = math . ceil ( self . extents_count ( ) * snapshot_size ) size_kb = self . volume_group ( ) . extent_size ( ) * size_extent snapshot_name = self . volume_name ( ) + snapshot_suffix lvcreate_cmd = [ 'sudo' ] if self . lvm_command ( ) . sudo ( ) is True else [ ] lvcreate_cmd . extend ( [ 'lvcreate' , '-L' , '%iK' % size_kb , '-s' , '-n' , snapshot_name , '-p' , 'r' , self . volume_path ( ) ] ) subprocess . check_output ( lvcreate_cmd , timeout = self . __class__ . __lvm_snapshot_create_cmd_timeout__ ) return WLogicalVolume ( self . volume_path ( ) + snapshot_suffix , sudo = self . lvm_command ( ) . sudo ( ) ) | 8,161 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/os/linux/lvm.py#L470-L490 | [
"def",
"zipkin_tween",
"(",
"handler",
",",
"registry",
")",
":",
"def",
"tween",
"(",
"request",
")",
":",
"zipkin_settings",
"=",
"_get_settings_from_request",
"(",
"request",
")",
"tracer",
"=",
"get_default_tracer",
"(",
")",
"tween_kwargs",
"=",
"dict",
"(",
"service_name",
"=",
"zipkin_settings",
".",
"service_name",
",",
"span_name",
"=",
"zipkin_settings",
".",
"span_name",
",",
"zipkin_attrs",
"=",
"zipkin_settings",
".",
"zipkin_attrs",
",",
"transport_handler",
"=",
"zipkin_settings",
".",
"transport_handler",
",",
"host",
"=",
"zipkin_settings",
".",
"host",
",",
"port",
"=",
"zipkin_settings",
".",
"port",
",",
"add_logging_annotation",
"=",
"zipkin_settings",
".",
"add_logging_annotation",
",",
"report_root_timestamp",
"=",
"zipkin_settings",
".",
"report_root_timestamp",
",",
"context_stack",
"=",
"zipkin_settings",
".",
"context_stack",
",",
"max_span_batch_size",
"=",
"zipkin_settings",
".",
"max_span_batch_size",
",",
"encoding",
"=",
"zipkin_settings",
".",
"encoding",
",",
"kind",
"=",
"Kind",
".",
"SERVER",
",",
")",
"if",
"zipkin_settings",
".",
"firehose_handler",
"is",
"not",
"None",
":",
"tween_kwargs",
"[",
"'firehose_handler'",
"]",
"=",
"zipkin_settings",
".",
"firehose_handler",
"with",
"tracer",
".",
"zipkin_span",
"(",
"*",
"*",
"tween_kwargs",
")",
"as",
"zipkin_context",
":",
"response",
"=",
"handler",
"(",
"request",
")",
"if",
"zipkin_settings",
".",
"use_pattern_as_span_name",
"and",
"request",
".",
"matched_route",
":",
"zipkin_context",
".",
"override_span_name",
"(",
"'{} {}'",
".",
"format",
"(",
"request",
".",
"method",
",",
"request",
".",
"matched_route",
".",
"pattern",
",",
")",
")",
"zipkin_context",
".",
"update_binary_annotations",
"(",
"get_binary_annotations",
"(",
"request",
",",
"response",
")",
",",
")",
"if",
"zipkin_settings",
".",
"post_handler_hook",
":",
"zipkin_settings",
".",
"post_handler_hook",
"(",
"request",
",",
"response",
")",
"return",
"response",
"return",
"tween"
] |
Remove this volume | def remove_volume ( self ) : lvremove_cmd = [ 'sudo' ] if self . lvm_command ( ) . sudo ( ) is True else [ ] lvremove_cmd . extend ( [ 'lvremove' , '-f' , self . volume_path ( ) ] ) subprocess . check_output ( lvremove_cmd , timeout = self . __class__ . __lvm_snapshot_remove_cmd_timeout__ ) | 8,162 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/os/linux/lvm.py#L492-L499 | [
"def",
"serverinfo",
"(",
"url",
"=",
"'http://localhost:8080/manager'",
",",
"timeout",
"=",
"180",
")",
":",
"data",
"=",
"_wget",
"(",
"'serverinfo'",
",",
"{",
"}",
",",
"url",
",",
"timeout",
"=",
"timeout",
")",
"if",
"data",
"[",
"'res'",
"]",
"is",
"False",
":",
"return",
"{",
"'error'",
":",
"data",
"[",
"'msg'",
"]",
"}",
"ret",
"=",
"{",
"}",
"data",
"[",
"'msg'",
"]",
".",
"pop",
"(",
"0",
")",
"for",
"line",
"in",
"data",
"[",
"'msg'",
"]",
":",
"tmp",
"=",
"line",
".",
"split",
"(",
"':'",
")",
"ret",
"[",
"tmp",
"[",
"0",
"]",
".",
"strip",
"(",
")",
"]",
"=",
"tmp",
"[",
"1",
"]",
".",
"strip",
"(",
")",
"return",
"ret"
] |
Return logical volume that stores the given path | def logical_volume ( cls , file_path , sudo = False ) : mp = WMountPoint . mount_point ( file_path ) if mp is not None : name_file = '/sys/block/%s/dm/name' % mp . device_name ( ) if os . path . exists ( name_file ) : lv_path = '/dev/mapper/%s' % open ( name_file ) . read ( ) . strip ( ) return WLogicalVolume ( lv_path , sudo = sudo ) | 8,163 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/os/linux/lvm.py#L524-L536 | [
"def",
"generate_changelog",
"(",
"context",
")",
":",
"changelog_content",
"=",
"[",
"'\\n## [%s](%s/compare/%s...%s)\\n\\n'",
"%",
"(",
"context",
".",
"new_version",
",",
"context",
".",
"repo_url",
",",
"context",
".",
"current_version",
",",
"context",
".",
"new_version",
",",
")",
"]",
"git_log_content",
"=",
"None",
"git_log",
"=",
"'log --oneline --no-merges --no-color'",
".",
"split",
"(",
"' '",
")",
"try",
":",
"git_log_tag",
"=",
"git_log",
"+",
"[",
"'%s..master'",
"%",
"context",
".",
"current_version",
"]",
"git_log_content",
"=",
"git",
"(",
"git_log_tag",
")",
"log",
".",
"debug",
"(",
"'content: %s'",
"%",
"git_log_content",
")",
"except",
"Exception",
":",
"log",
".",
"warn",
"(",
"'Error diffing previous version, initial release'",
")",
"git_log_content",
"=",
"git",
"(",
"git_log",
")",
"git_log_content",
"=",
"replace_sha_with_commit_link",
"(",
"context",
".",
"repo_url",
",",
"git_log_content",
")",
"# turn change log entries into markdown bullet points",
"if",
"git_log_content",
":",
"[",
"changelog_content",
".",
"append",
"(",
"'* %s\\n'",
"%",
"line",
")",
"if",
"line",
"else",
"line",
"for",
"line",
"in",
"git_log_content",
"[",
":",
"-",
"1",
"]",
"]",
"write_new_changelog",
"(",
"context",
".",
"repo_url",
",",
"'CHANGELOG.md'",
",",
"changelog_content",
",",
"dry_run",
"=",
"context",
".",
"dry_run",
")",
"log",
".",
"info",
"(",
"'Added content to CHANGELOG.md'",
")",
"context",
".",
"changelog_content",
"=",
"changelog_content"
] |
Encrypt and write data | def write ( self , b ) : self . __buffer += bytes ( b ) bytes_written = 0 while len ( self . __buffer ) >= self . __cipher_block_size : io . BufferedWriter . write ( self , self . __cipher . encrypt_block ( self . __buffer [ : self . __cipher_block_size ] ) ) self . __buffer = self . __buffer [ self . __cipher_block_size : ] bytes_written += self . __cipher_block_size return len ( b ) | 8,164 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/io.py#L205-L218 | [
"def",
"get_placement_solver",
"(",
"service_instance",
")",
":",
"stub",
"=",
"salt",
".",
"utils",
".",
"vmware",
".",
"get_new_service_instance_stub",
"(",
"service_instance",
",",
"ns",
"=",
"'pbm/2.0'",
",",
"path",
"=",
"'/pbm/sdk'",
")",
"pbm_si",
"=",
"pbm",
".",
"ServiceInstance",
"(",
"'ServiceInstance'",
",",
"stub",
")",
"try",
":",
"profile_manager",
"=",
"pbm_si",
".",
"RetrieveContent",
"(",
")",
".",
"placementSolver",
"except",
"vim",
".",
"fault",
".",
"NoPermission",
"as",
"exc",
":",
"log",
".",
"exception",
"(",
"exc",
")",
"raise",
"VMwareApiError",
"(",
"'Not enough permissions. Required privilege: '",
"'{0}'",
".",
"format",
"(",
"exc",
".",
"privilegeId",
")",
")",
"except",
"vim",
".",
"fault",
".",
"VimFault",
"as",
"exc",
":",
"log",
".",
"exception",
"(",
"exc",
")",
"raise",
"VMwareApiError",
"(",
"exc",
".",
"msg",
")",
"except",
"vmodl",
".",
"RuntimeFault",
"as",
"exc",
":",
"log",
".",
"exception",
"(",
"exc",
")",
"raise",
"VMwareRuntimeError",
"(",
"exc",
".",
"msg",
")",
"return",
"profile_manager"
] |
Unset component in this URI | def reset_component ( self , component ) : if isinstance ( component , str ) is True : component = WURI . Component ( component ) self . __components [ component ] = None | 8,165 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/uri.py#L137-L146 | [
"def",
"external_metadata",
"(",
"self",
",",
"datasource_type",
"=",
"None",
",",
"datasource_id",
"=",
"None",
")",
":",
"if",
"datasource_type",
"==",
"'druid'",
":",
"datasource",
"=",
"ConnectorRegistry",
".",
"get_datasource",
"(",
"datasource_type",
",",
"datasource_id",
",",
"db",
".",
"session",
")",
"elif",
"datasource_type",
"==",
"'table'",
":",
"database",
"=",
"(",
"db",
".",
"session",
".",
"query",
"(",
"Database",
")",
".",
"filter_by",
"(",
"id",
"=",
"request",
".",
"args",
".",
"get",
"(",
"'db_id'",
")",
")",
".",
"one",
"(",
")",
")",
"Table",
"=",
"ConnectorRegistry",
".",
"sources",
"[",
"'table'",
"]",
"datasource",
"=",
"Table",
"(",
"database",
"=",
"database",
",",
"table_name",
"=",
"request",
".",
"args",
".",
"get",
"(",
"'table_name'",
")",
",",
"schema",
"=",
"request",
".",
"args",
".",
"get",
"(",
"'schema'",
")",
"or",
"None",
",",
")",
"external_metadata",
"=",
"datasource",
".",
"external_metadata",
"(",
")",
"return",
"self",
".",
"json_response",
"(",
"external_metadata",
")"
] |
Parse URI - string and return WURI object | def parse ( cls , uri ) : uri_components = urlsplit ( uri ) adapter_fn = lambda x : x if x is not None and ( isinstance ( x , str ) is False or len ( x ) ) > 0 else None return cls ( scheme = adapter_fn ( uri_components . scheme ) , username = adapter_fn ( uri_components . username ) , password = adapter_fn ( uri_components . password ) , hostname = adapter_fn ( uri_components . hostname ) , port = adapter_fn ( uri_components . port ) , path = adapter_fn ( uri_components . path ) , query = adapter_fn ( uri_components . query ) , fragment = adapter_fn ( uri_components . fragment ) , ) | 8,166 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/uri.py#L150-L168 | [
"def",
"_parseDelayImportDirectory",
"(",
"self",
",",
"rva",
",",
"size",
",",
"magic",
"=",
"consts",
".",
"PE32",
")",
":",
"return",
"self",
".",
"getDataAtRva",
"(",
"rva",
",",
"size",
")"
] |
Add new parameter value to this query . New value will be appended to previously added values . | def add_parameter ( self , name , value = None ) : if name not in self . __query : self . __query [ name ] = [ value ] else : self . __query [ name ] . append ( value ) | 8,167 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/uri.py#L202-L212 | [
"def",
"etm_supported",
"(",
"self",
")",
":",
"res",
"=",
"self",
".",
"_dll",
".",
"JLINKARM_ETM_IsPresent",
"(",
")",
"if",
"(",
"res",
"==",
"1",
")",
":",
"return",
"True",
"# JLINKARM_ETM_IsPresent() only works on ARM 7/9 devices. This",
"# fallback checks if ETM is present by checking the Cortex ROM table",
"# for debugging information for ETM.",
"info",
"=",
"ctypes",
".",
"c_uint32",
"(",
"0",
")",
"index",
"=",
"enums",
".",
"JLinkROMTable",
".",
"ETM",
"res",
"=",
"self",
".",
"_dll",
".",
"JLINKARM_GetDebugInfo",
"(",
"index",
",",
"ctypes",
".",
"byref",
"(",
"info",
")",
")",
"if",
"(",
"res",
"==",
"1",
")",
":",
"return",
"False",
"return",
"True"
] |
Remove the specified parameter from this query | def remove_parameter ( self , name ) : if name in self . __query : self . __query . pop ( name ) | 8,168 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/uri.py#L215-L222 | [
"def",
"crossvalidate",
"(",
"self",
",",
"foldsfile",
")",
":",
"options",
"=",
"\"-F \"",
"+",
"self",
".",
"format",
"+",
"\" \"",
"+",
"self",
".",
"timbloptions",
"+",
"\" -t cross_validate\"",
"print",
"(",
"\"Instantiating Timbl API : \"",
"+",
"options",
",",
"file",
"=",
"stderr",
")",
"if",
"sys",
".",
"version",
"<",
"'3'",
":",
"self",
".",
"api",
"=",
"timblapi",
".",
"TimblAPI",
"(",
"b",
"(",
"options",
")",
",",
"b\"\"",
")",
"else",
":",
"self",
".",
"api",
"=",
"timblapi",
".",
"TimblAPI",
"(",
"options",
",",
"\"\"",
")",
"if",
"self",
".",
"debug",
":",
"print",
"(",
"\"Enabling debug for timblapi\"",
",",
"file",
"=",
"stderr",
")",
"self",
".",
"api",
".",
"enableDebug",
"(",
")",
"print",
"(",
"\"Calling Timbl Test : \"",
"+",
"options",
",",
"file",
"=",
"stderr",
")",
"if",
"sys",
".",
"version",
"<",
"'3'",
":",
"self",
".",
"api",
".",
"test",
"(",
"b",
"(",
"foldsfile",
")",
",",
"b''",
",",
"b''",
")",
"else",
":",
"self",
".",
"api",
".",
"test",
"(",
"u",
"(",
"foldsfile",
")",
",",
"''",
",",
"''",
")",
"a",
"=",
"self",
".",
"api",
".",
"getAccuracy",
"(",
")",
"del",
"self",
".",
"api",
"return",
"a"
] |
Parse string that represent query component from URI | def parse ( cls , query_str ) : parsed_query = parse_qs ( query_str , keep_blank_values = True , strict_parsing = True ) result = cls ( ) for parameter_name in parsed_query . keys ( ) : for parameter_value in parsed_query [ parameter_name ] : result . add_parameter ( parameter_name , parameter_value if len ( parameter_value ) > 0 else None ) return result | 8,169 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/uri.py#L261-L275 | [
"def",
"read",
"(",
"self",
",",
"length",
",",
"timeout",
"=",
"None",
")",
":",
"data",
"=",
"b\"\"",
"# Read length bytes if timeout is None",
"# Read up to length bytes if timeout is not None",
"while",
"True",
":",
"if",
"timeout",
"is",
"not",
"None",
":",
"# Select",
"(",
"rlist",
",",
"_",
",",
"_",
")",
"=",
"select",
".",
"select",
"(",
"[",
"self",
".",
"_fd",
"]",
",",
"[",
"]",
",",
"[",
"]",
",",
"timeout",
")",
"# If timeout",
"if",
"self",
".",
"_fd",
"not",
"in",
"rlist",
":",
"break",
"try",
":",
"data",
"+=",
"os",
".",
"read",
"(",
"self",
".",
"_fd",
",",
"length",
"-",
"len",
"(",
"data",
")",
")",
"except",
"OSError",
"as",
"e",
":",
"raise",
"SerialError",
"(",
"e",
".",
"errno",
",",
"\"Reading serial port: \"",
"+",
"e",
".",
"strerror",
")",
"if",
"len",
"(",
"data",
")",
"==",
"length",
":",
"break",
"return",
"data"
] |
Add a new query parameter specification . If this object already has a specification for the specified parameter - exception is raised . No checks for the specified or any parameter are made regarding specification appending | def add_specification ( self , specification ) : name = specification . name ( ) if name in self . __specs : raise ValueError ( 'WStrictURIQuery object already has specification for parameter "%s" ' % name ) self . __specs [ name ] = specification | 8,170 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/uri.py#L380-L391 | [
"def",
"create",
"(",
"cls",
",",
"destination",
")",
":",
"mdb_gz_b64",
"=",
"\"\"\"\\\n H4sICIenn1gC/25ldzIwMDMubWRiAO2de2wcRx3Hf7O7Pt/d3u6eLyEtVaOaqg+EkjQvuVVDwa9a\n jWXHdZxQQlCJ7fOrfp3OTpqkhVxTItFWIhVQVFBRVNIKRaColVpAUKGKRwwFqUAhKiBIpUaoVWP+\n qKgIIHL8Znb39u72znWJiWP3+9l473fzm/nNY3cdf2fmbBJEPdO9E+nebLq+fWC6vrWZOImen9D7\n 9sR+vPPNE0PZxo/TE5879mj+yNc3/OzAD2bXv3DmV9/o/8PZnxxr+/fDL2w79ulzN7e+/sS/zvzz\n w3+N1z28p3PTfQ3nfn/m2YmeFS2no89uWnvqwO5HUvd/5Phr938tes3j/zm5+qT41J8/P/iZx87/\n +qHrjgyduubG1t/+7eWB2XztTNuT+1clZt9c2/e7HRGizevWEwAAAAAAAACAhUEIwvE+PoRIO8K7\n FzT6obPPwTMBAAAAAAAAAABcfpzPXwya+Ispo1xlEO2KEEX9eaGyWnrqyKQ60tQ0AcNZRcR1RYuy\n +XZCxoqRzmaMI6cKGRJuJVrIEZUOQ9UrHStUYpyzKkdNmSPFDkM6aguhXMdVHCMuHXE2Suu4IFQJ\n l6CErNWUDouDlbdKOZIcrKLD4S5WdNhqIEodqlVaofKgVTHpiBQ6uLG0uaKsuYbf3IS8BmV1qFAm\n j1Z5Hbp06GWDKC+DTS00SRN8DFA/TXNfW6mXX3upj7+mOHWllzLAObN8du0gdSdlKO3ZcWqjMbaH\n uOQqtidViRF+P0HbOH2c3xm0lfMb1EH7uHZ5vp32c+ks+5PqfSeXS9NejjTAvZQpd7J3kuuJFqLE\n qYvuVa3Ocqk7OVXWNMFxZPRVtJ1zSXuCBrlkh+rjEF1Zlt5Dw6qN0xx5Bx3gGgbowVo56EIjkc9T\n xX9Jdd+5PKDOD6q3VQvwv7qiZ8st419cdYHlo6iuriF8X4HA590AsodXhvrsj0yMDPnAuI+ZvOrq\n 1o7K51Hdy7a8cdXNm5AedbfG5W3j3lOybxFZKb6zAgAAAAAAsNzQxAlbvnYJV3VcUU3/S2luBIKF\n ha+IlWp+wxW4IiRXRSXxKeNU1eOxUuUbSOIINbEM7WT506ZE3LASgCOeYJWCMcnCsI/u8eSsFEYR\n lnlbWa6+u0jTYqSkvuQL9G5CLFwTRBMAAAAAAAAAgMtW/79lyVdLKxW7oqDF3bXOniib0UD/m/xq\n loWqvFwt3DX/mrLNALIu3V35NkpK1JDmL+2XOmr9pf1gKiFY4I672wc0mveaf6zaenyKmljPT6t5\n hT7a6y13y0XqjFpwneJjRC0oRwvL3eUL2fHCcuyGIntjhTkDuZCd5Vc5j+HNUMyx+myYcpHW5YG5\n ZijUdbg2VFu4ZzzcHFM3seQLAAAAAAAAAMtc//9S6cm1emX97ytK1v81rHelhtfVfAFnseZXRdV9\n Ad7+dhGS5kbl3eqe/K8pU/nnYwX5X2VeoLbCZwHi7txD6aTELabnoLJ5AfPFC8JmFd3Pun+MlfM4\n q/846/4s62i5+8Dmc7EvSVN0UG2tL00p1uPXqZTt/G5QqX+5lbufz+mSctVzFce6upBrTG3Fd+cn\n pmiYrUyw8+GNfL4hn8/k83qZrVlyGzgPeqbhjcOqx7KMEZRpU/MPQ+rsldEtuYm8vExkznoMS+6b\n KC5TZRt8wVf4xEkFX4V5D/X2vYz1/EcR8yMAAAAAAACAJY0Qf/d3vLPUlb//b4Nzzv6W3Wevtl+1\n vmxts2LWTxOHErcm3jGfMUfNG0yMGQAAAAAAeJ/8rLwAMXIYRgCARFv8IIaYtKpGqCdqlN/2kupD\n /ob67qXhsi0lDh2Vp6728faO9tHuUflfWJ1wE0e6724f35XuG71r16Dr0FwH573by6rKi0N7RveN\n tnd6aTVBWrpjd3fnuJtsBMnDk90ju7zckSA5XGGtdGrK2dWhUnRcMgAAAAAAAAD4v2CIV6vqf82I\n Jusbcwsy7wkWSf/n1JQNq/Oc+uQGq/ecmsphYZ6Tn6XwRLjwxb7mTxDoakLgURUFshwAAAAAAAAA\n ljpCrHZ8W/f2/2NUAAAAAAAAAAAAhXH5RLm4IIbotqot7hbW/0MGWCp46/+pgpHwjZS3IyAlfMPy\n tgakNN+wfcPxNgukdN9I+kadt30gZfhGjW+s8I2V3s6CVNTbWZCK+Eatb3zAN1Z5mw5SMd+I+wZ+\n +QQAAAAAAAAA/K8IcdT27Zqi3/+HkQEAAAAAAAAAsGgkMQQLjSHqbQPDAAAAAAAAAAAALGuw/g8A\n AAAAAAAA4DJUqwsQI7cQDWlcLiMq1/9rcGMBAAAAAAAAAADLGuh/AAAAAAAAAAAA+h8AAAAAAAAA\n AABLHyHusDTPjtLzTtoxnRftUftqe8YatDA+AAAAAAAAAPDeqJN/KVt+et0R9PYnzz7W8PrZRv+V\n HblO6qEDNEXbaYDGqJemaYQmaYJThtnK8Gvzb1opfDRTPZmUlxUY86qgm/ZyFVkOOqCC3kLhoyEI\n qs8raBO10O0q3EYKH+uDcNq8wnVRH93D7evnYZhHG5kkB3a0OYO2ctCWV9ZR+FhT0l2HCzl6xVBz\n XZyPUvi4taTjcwRuVUF7uYW9HMy9MJspfGwMAoo5A+5Qwca8UHN2WogeU/fu0ito1vmjM+M85zzp\n fNG5zxl2djrNzk3O9+0m+yWrx2q0fpH4buJ4Yk3ig4lvmkfxx9gBAAAAAAC4OAylQfJ5h5pfSVCc\n f853gqSmWPSZux6xjUznltH2HT/flNu7++0NZ7/07cg/vnPbVu30y6d/NLvlabPh+j81v/Xc5g9l\n 1h2f+epn9+VPdN90OHHvU50fm94y/ZXvWQ/tP/yJG/NH3llz8A79tlNPG72DHSePHdzz2s3XPzVj\n vzSUvSHjVys1Rv5CSUv8pEvcEqkbV/KX35JaQ+npikmRS9o4rtYIt8RYnJa4Ou6SV6stTm+l7rcX\n q9qSy+23pCVIcgV/SZKuJj5CSRc4Y/PpkiesLJcI53J37NvFuQzv4peGL0/SypP+C+45xVAAMAEA\n \"\"\"",
"pristine",
"=",
"StringIO",
"(",
")",
"pristine",
".",
"write",
"(",
"base64",
".",
"b64decode",
"(",
"mdb_gz_b64",
")",
")",
"pristine",
".",
"seek",
"(",
"0",
")",
"pristine",
"=",
"gzip",
".",
"GzipFile",
"(",
"fileobj",
"=",
"pristine",
",",
"mode",
"=",
"'rb'",
")",
"with",
"open",
"(",
"destination",
",",
"'wb'",
")",
"as",
"handle",
":",
"shutil",
".",
"copyfileobj",
"(",
"pristine",
",",
"handle",
")",
"return",
"cls",
"(",
"destination",
")"
] |
Remove a specification that matches a query parameter . No checks for the specified or any parameter are made regarding specification removing | def remove_specification ( self , name ) : if name in self . __specs : self . __specs . pop ( name ) | 8,171 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/uri.py#L394-L402 | [
"def",
"start",
"(",
"self",
")",
":",
"self",
".",
"startTime",
"=",
"time",
".",
"time",
"(",
")",
"self",
".",
"configure",
"(",
"text",
"=",
"'{0:<d} s'",
".",
"format",
"(",
"0",
")",
")",
"self",
".",
"update",
"(",
")"
] |
Replace a query parameter values with a new value . If a new value does not match current specifications then exception is raised | def replace_parameter ( self , name , value = None ) : spec = self . __specs [ name ] if name in self . __specs else None if self . extra_parameters ( ) is False and spec is None : raise ValueError ( 'Extra parameters are forbidden for this WStrictURIQuery object' ) if spec is not None and spec . nullable ( ) is False and value is None : raise ValueError ( 'Nullable values is forbidden for parameter "%s"' % name ) if spec is not None and value is not None : re_obj = spec . re_obj ( ) if re_obj is not None and re_obj . match ( value ) is None : raise ValueError ( 'Value does not match regular expression' ) WURIQuery . replace_parameter ( self , name , value = value ) | 8,172 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/uri.py#L405-L425 | [
"def",
"clearAuxiliaryData",
"(",
"dirName",
")",
":",
"if",
"dirName",
"!=",
"None",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"dirName",
"+",
"'/auxiliary.npy'",
")",
":",
"os",
".",
"remove",
"(",
"dirName",
"+",
"'/auxiliary.npy'",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"dirName",
"+",
"'/totalCounts.p'",
")",
":",
"os",
".",
"remove",
"(",
"dirName",
"+",
"'/totalCounts.p'",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"dirName",
"+",
"'/totalCounts.npy'",
")",
":",
"os",
".",
"remove",
"(",
"dirName",
"+",
"'/totalCounts.npy'",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"dirName",
"+",
"'/fmIndex.npy'",
")",
":",
"os",
".",
"remove",
"(",
"dirName",
"+",
"'/fmIndex.npy'",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"dirName",
"+",
"'/comp_refIndex.npy'",
")",
":",
"os",
".",
"remove",
"(",
"dirName",
"+",
"'/comp_refIndex.npy'",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"dirName",
"+",
"'/comp_fmIndex.npy'",
")",
":",
"os",
".",
"remove",
"(",
"dirName",
"+",
"'/comp_fmIndex.npy'",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"dirName",
"+",
"'/backrefs.npy'",
")",
":",
"os",
".",
"remove",
"(",
"dirName",
"+",
"'/backrefs.npy'",
")"
] |
Remove parameter from this query . If a parameter is mandatory then exception is raised | def remove_parameter ( self , name ) : spec = self . __specs [ name ] if name in self . __specs else None if spec is not None and spec . optional ( ) is False : raise ValueError ( 'Unable to remove a required parameter "%s"' % name ) WURIQuery . remove_parameter ( self , name ) | 8,173 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/uri.py#L454-L464 | [
"def",
"on_batch_begin",
"(",
"self",
",",
"last_input",
",",
"last_target",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"acc_samples",
"+=",
"last_input",
".",
"shape",
"[",
"0",
"]",
"self",
".",
"acc_batches",
"+=",
"1"
] |
Check an URI for compatibility with this specification . Return True if the URI is compatible . | def validate ( self , uri ) : requirement = self . requirement ( ) uri_component = uri . component ( self . component ( ) ) if uri_component is None : return requirement != WURIComponentVerifier . Requirement . required if requirement == WURIComponentVerifier . Requirement . unsupported : return False re_obj = self . re_obj ( ) if re_obj is not None : return re_obj . match ( uri_component ) is not None return True | 8,174 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/uri.py#L537-L555 | [
"def",
"get_admin_metadata",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"\"Getting admin metdata\"",
")",
"text",
"=",
"self",
".",
"get_text",
"(",
"self",
".",
"get_admin_metadata_key",
"(",
")",
")",
"return",
"json",
".",
"loads",
"(",
"text",
")"
] |
Check that an query part of an URI is compatible with this descriptor . Return True if the URI is compatible . | def validate ( self , uri ) : if WURIComponentVerifier . validate ( self , uri ) is False : return False try : WStrictURIQuery ( WURIQuery . parse ( uri . component ( self . component ( ) ) ) , * self . __specs , extra_parameters = self . __extra_parameters ) except ValueError : return False return True | 8,175 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/uri.py#L576-L594 | [
"def",
"translate",
"(",
"self",
",",
"instruction",
")",
":",
"try",
":",
"trans_instrs",
"=",
"self",
".",
"__translate",
"(",
"instruction",
")",
"except",
"NotImplementedError",
":",
"unkn_instr",
"=",
"self",
".",
"_builder",
".",
"gen_unkn",
"(",
")",
"unkn_instr",
".",
"address",
"=",
"instruction",
".",
"address",
"<<",
"8",
"|",
"(",
"0x0",
"&",
"0xff",
")",
"trans_instrs",
"=",
"[",
"unkn_instr",
"]",
"self",
".",
"_log_not_supported_instruction",
"(",
"instruction",
")",
"except",
"Exception",
":",
"self",
".",
"_log_translation_exception",
"(",
"instruction",
")",
"raise",
"return",
"trans_instrs"
] |
Check if URI is compatible with this specification . Compatible URI has scheme name that matches specification scheme name has all of the required components does not have unsupported components and may have optional components | def is_compatible ( self , uri ) : for component , component_value in uri : if self . verifier ( component ) . validate ( uri ) is False : return False return True | 8,176 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/uri.py#L658-L670 | [
"async",
"def",
"_stream_raw_result",
"(",
"self",
",",
"res",
")",
":",
"async",
"with",
"res",
".",
"context",
"as",
"response",
":",
"response",
".",
"raise_for_status",
"(",
")",
"async",
"for",
"out",
"in",
"response",
".",
"content",
".",
"iter_chunked",
"(",
"1",
")",
":",
"yield",
"out",
".",
"decode",
"(",
")"
] |
Return handler which scheme name matches the specified one | def handler ( self , scheme_name = None ) : if scheme_name is None : return self . __default_handler_cls for handler in self . __handlers_cls : if handler . scheme_specification ( ) . scheme_name ( ) == scheme_name : return handler | 8,177 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/uri.py#L752-L762 | [
"def",
"interactive_shell",
"(",
")",
":",
"print",
"(",
"'You should be able to read and update the \"counter[0]\" variable from this shell.'",
")",
"try",
":",
"yield",
"from",
"embed",
"(",
"globals",
"=",
"globals",
"(",
")",
",",
"return_asyncio_coroutine",
"=",
"True",
",",
"patch_stdout",
"=",
"True",
")",
"except",
"EOFError",
":",
"# Stop the loop when quitting the repl. (Ctrl-D press.)",
"loop",
".",
"stop",
"(",
")"
] |
Return handler instance that matches the specified URI . WSchemeCollection . NoHandlerFound and WSchemeCollection . SchemeIncompatible may be raised . | def open ( self , uri , * * kwargs ) : handler = self . handler ( uri . scheme ( ) ) if handler is None : raise WSchemeCollection . NoHandlerFound ( uri ) if uri . scheme ( ) is None : uri . component ( 'scheme' , handler . scheme_specification ( ) . scheme_name ( ) ) if handler . scheme_specification ( ) . is_compatible ( uri ) is False : raise WSchemeCollection . SchemeIncompatible ( uri ) return handler . create_handler ( uri , * * kwargs ) | 8,178 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/uri.py#L765-L783 | [
"def",
"get_admin_metadata",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"\"Getting admin metdata\"",
")",
"text",
"=",
"self",
".",
"get_text",
"(",
"self",
".",
"get_admin_metadata_key",
"(",
")",
")",
"return",
"json",
".",
"loads",
"(",
"text",
")"
] |
Load the URL fileName . | def loadFile ( self , fileName ) : self . fileName = fileName self . qteWeb . load ( QtCore . QUrl ( fileName ) ) | 8,179 | https://github.com/olitheolix/qtmacs/blob/36253b082b82590f183fe154b053eb3a1e741be2/qtmacs/applets/webbrowser.py#L85-L90 | [
"def",
"blob_data_to_dict",
"(",
"stat_names",
",",
"blobs",
")",
":",
"# get the dtypes of each of the stats; we'll just take this from the",
"# first iteration and walker",
"dtypes",
"=",
"[",
"type",
"(",
"val",
")",
"for",
"val",
"in",
"blobs",
"[",
"0",
"]",
"[",
"0",
"]",
"]",
"assert",
"len",
"(",
"stat_names",
")",
"==",
"len",
"(",
"dtypes",
")",
",",
"(",
"\"number of stat names must match length of tuples in the blobs\"",
")",
"# convert to an array; to ensure that we get the dtypes correct, we'll",
"# cast to a structured array",
"raw_stats",
"=",
"numpy",
".",
"array",
"(",
"blobs",
",",
"dtype",
"=",
"zip",
"(",
"stat_names",
",",
"dtypes",
")",
")",
"# transpose so that it has shape nwalkers x niterations",
"raw_stats",
"=",
"raw_stats",
".",
"transpose",
"(",
")",
"# now return as a dictionary",
"return",
"{",
"stat",
":",
"raw_stats",
"[",
"stat",
"]",
"for",
"stat",
"in",
"stat_names",
"}"
] |
Returns a response with a template rendered with the given context . | def render_to_response ( self , context , * * response_kwargs ) : context [ "ajax_form_id" ] = self . ajax_form_id # context["base_template"] = "towel_bootstrap/modal.html" return self . response_class ( request = self . request , template = self . get_template_names ( ) , context = context , * * response_kwargs ) | 8,180 | https://github.com/weijia/djangoautoconf/blob/b7dbda2287ed8cb9de6d02cb3abaaa1c36b1ced0/djangoautoconf/class_based_views/ajax_views.py#L47-L58 | [
"def",
"tfidf_weight",
"(",
"X",
")",
":",
"X",
"=",
"coo_matrix",
"(",
"X",
")",
"# calculate IDF",
"N",
"=",
"float",
"(",
"X",
".",
"shape",
"[",
"0",
"]",
")",
"idf",
"=",
"log",
"(",
"N",
")",
"-",
"log1p",
"(",
"bincount",
"(",
"X",
".",
"col",
")",
")",
"# apply TF-IDF adjustment",
"X",
".",
"data",
"=",
"sqrt",
"(",
"X",
".",
"data",
")",
"*",
"idf",
"[",
"X",
".",
"col",
"]",
"return",
"X"
] |
Converts to unicode if self . encoding ! = None otherwise returns input without attempting to decode | def to_python ( self , value , resource ) : if value is None : return self . _transform ( value ) if isinstance ( value , six . text_type ) : return self . _transform ( value ) if self . encoding is None and isinstance ( value , ( six . text_type , six . binary_type ) ) : return self . _transform ( value ) if self . encoding is not None and isinstance ( value , six . binary_type ) : return self . _transform ( value . decode ( self . encoding ) ) return self . _transform ( six . text_type ( value ) ) | 8,181 | https://github.com/consbio/restle/blob/60d100da034c612d4910f4f79eaa57a76eb3dcc6/restle/fields.py#L72-L87 | [
"def",
"_getNearestMappingIndexList",
"(",
"fromValList",
",",
"toValList",
")",
":",
"indexList",
"=",
"[",
"]",
"for",
"fromTimestamp",
"in",
"fromValList",
":",
"smallestDiff",
"=",
"_getSmallestDifference",
"(",
"toValList",
",",
"fromTimestamp",
")",
"i",
"=",
"toValList",
".",
"index",
"(",
"smallestDiff",
")",
"indexList",
".",
"append",
"(",
"i",
")",
"return",
"indexList"
] |
Dictionary to Python object | def to_python ( self , value , resource ) : if isinstance ( value , dict ) : d = { self . aliases . get ( k , k ) : self . to_python ( v , resource ) if isinstance ( v , ( dict , list ) ) else v for k , v in six . iteritems ( value ) } return type ( self . class_name , ( ) , d ) elif isinstance ( value , list ) : return [ self . to_python ( x , resource ) if isinstance ( x , ( dict , list ) ) else x for x in value ] else : return value | 8,182 | https://github.com/consbio/restle/blob/60d100da034c612d4910f4f79eaa57a76eb3dcc6/restle/fields.py#L145-L157 | [
"def",
"_get_feed_cache",
"(",
"self",
")",
":",
"feed_cache",
"=",
"None",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"_feed_cache_file",
")",
":",
"maxage",
"=",
"datetime",
".",
"now",
"(",
")",
"-",
"timedelta",
"(",
"minutes",
"=",
"self",
".",
"_cachetime",
")",
"file_ts",
"=",
"datetime",
".",
"fromtimestamp",
"(",
"os",
".",
"stat",
"(",
"self",
".",
"_feed_cache_file",
")",
".",
"st_mtime",
")",
"if",
"file_ts",
">",
"maxage",
":",
"try",
":",
"with",
"open",
"(",
"self",
".",
"_feed_cache_file",
",",
"'rb'",
")",
"as",
"cache",
":",
"feed_cache",
"=",
"cache",
".",
"read",
"(",
")",
"finally",
":",
"pass",
"return",
"feed_cache"
] |
Python object to dictionary | def to_value ( self , obj , resource , visited = set ( ) ) : if id ( obj ) in visited : raise ValueError ( 'Circular reference detected when attempting to serialize object' ) if isinstance ( obj , ( list , tuple , set ) ) : return [ self . to_value ( x , resource ) if hasattr ( x , '__dict__' ) else x for x in obj ] elif hasattr ( obj , '__dict__' ) : attrs = obj . __dict__ . copy ( ) for key in six . iterkeys ( obj . __dict__ ) : if key . startswith ( '_' ) : del attrs [ key ] return { self . reverse_aliases . get ( k , k ) : self . to_value ( v , resource ) if hasattr ( v , '__dict__' ) or isinstance ( v , ( list , tuple , set ) ) else v for k , v in six . iteritems ( attrs ) } else : return obj | 8,183 | https://github.com/consbio/restle/blob/60d100da034c612d4910f4f79eaa57a76eb3dcc6/restle/fields.py#L159-L179 | [
"def",
"_psturng",
"(",
"q",
",",
"r",
",",
"v",
")",
":",
"if",
"q",
"<",
"0.",
":",
"raise",
"ValueError",
"(",
"'q should be >= 0'",
")",
"opt_func",
"=",
"lambda",
"p",
",",
"r",
",",
"v",
":",
"abs",
"(",
"_qsturng",
"(",
"p",
",",
"r",
",",
"v",
")",
"-",
"q",
")",
"if",
"v",
"==",
"1",
":",
"if",
"q",
"<",
"_qsturng",
"(",
".9",
",",
"r",
",",
"1",
")",
":",
"return",
".1",
"elif",
"q",
">",
"_qsturng",
"(",
".999",
",",
"r",
",",
"1",
")",
":",
"return",
".001",
"return",
"1.",
"-",
"fminbound",
"(",
"opt_func",
",",
".9",
",",
".999",
",",
"args",
"=",
"(",
"r",
",",
"v",
")",
")",
"else",
":",
"if",
"q",
"<",
"_qsturng",
"(",
".1",
",",
"r",
",",
"v",
")",
":",
"return",
".9",
"elif",
"q",
">",
"_qsturng",
"(",
".999",
",",
"r",
",",
"v",
")",
":",
"return",
".001",
"return",
"1.",
"-",
"fminbound",
"(",
"opt_func",
",",
".1",
",",
".999",
",",
"args",
"=",
"(",
"r",
",",
"v",
")",
")"
] |
Return message header . | def hello_message ( self , invert_hello = False ) : if invert_hello is False : return self . __gouverneur_message hello_message = [ ] for i in range ( len ( self . __gouverneur_message ) - 1 , - 1 , - 1 ) : hello_message . append ( self . __gouverneur_message [ i ] ) return bytes ( hello_message ) | 8,184 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/beacon/messenger.py#L200-L213 | [
"def",
"remove_observer",
"(",
"self",
",",
"observer",
")",
":",
"super",
"(",
"PowerManagement",
",",
"self",
")",
".",
"remove_observer",
"(",
"observer",
")",
"if",
"len",
"(",
"self",
".",
"_weak_observers",
")",
"==",
"0",
":",
"if",
"not",
"self",
".",
"_cf_run_loop",
":",
"PowerManagement",
".",
"notifications_observer",
".",
"removeObserver",
"(",
"self",
")",
"else",
":",
"CFRunLoopSourceInvalidate",
"(",
"self",
".",
"_source",
")",
"self",
".",
"_source",
"=",
"None"
] |
Read address from beacon message . If no address is specified then nullable WIPV4SocketInfo returns | def _message_address_parse ( self , message , invert_hello = False ) : message_header = self . hello_message ( invert_hello = invert_hello ) if message [ : len ( message_header ) ] != message_header : raise ValueError ( 'Invalid message header' ) message = message [ len ( message_header ) : ] message_parts = message . split ( WBeaconGouverneurMessenger . __message_splitter__ ) address = None port = None if len ( message_parts ) > 3 : raise ValueError ( 'Invalid message. Too many separators' ) elif len ( message_parts ) == 3 : address = WIPV4SocketInfo . parse_address ( message_parts [ 1 ] . decode ( 'ascii' ) ) port = WIPPort ( int ( message_parts [ 2 ] ) ) elif len ( message_parts ) == 2 and len ( message_parts [ 1 ] ) > 0 : address = WIPV4SocketInfo . parse_address ( message_parts [ 1 ] . decode ( 'ascii' ) ) return WIPV4SocketInfo ( address , port ) | 8,185 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/network/beacon/messenger.py#L254-L280 | [
"def",
"getCiphertextLen",
"(",
"self",
",",
"ciphertext",
")",
":",
"plaintext_length",
"=",
"self",
".",
"getPlaintextLen",
"(",
"ciphertext",
")",
"ciphertext_length",
"=",
"plaintext_length",
"+",
"Encrypter",
".",
"_CTXT_EXPANSION",
"return",
"ciphertext_length"
] |
Generate AES - cipher | def cipher ( self ) : #cipher = pyAES.new(*self.mode().aes_args(), **self.mode().aes_kwargs()) cipher = Cipher ( * self . mode ( ) . aes_args ( ) , * * self . mode ( ) . aes_kwargs ( ) ) return WAES . WAESCipher ( cipher ) | 8,186 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/crypto/aes.py#L491-L498 | [
"def",
"_error_messages",
"(",
"self",
",",
"driver_id",
")",
":",
"assert",
"isinstance",
"(",
"driver_id",
",",
"ray",
".",
"DriverID",
")",
"message",
"=",
"self",
".",
"redis_client",
".",
"execute_command",
"(",
"\"RAY.TABLE_LOOKUP\"",
",",
"ray",
".",
"gcs_utils",
".",
"TablePrefix",
".",
"ERROR_INFO",
",",
"\"\"",
",",
"driver_id",
".",
"binary",
"(",
")",
")",
"# If there are no errors, return early.",
"if",
"message",
"is",
"None",
":",
"return",
"[",
"]",
"gcs_entries",
"=",
"ray",
".",
"gcs_utils",
".",
"GcsTableEntry",
".",
"GetRootAsGcsTableEntry",
"(",
"message",
",",
"0",
")",
"error_messages",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"gcs_entries",
".",
"EntriesLength",
"(",
")",
")",
":",
"error_data",
"=",
"ray",
".",
"gcs_utils",
".",
"ErrorTableData",
".",
"GetRootAsErrorTableData",
"(",
"gcs_entries",
".",
"Entries",
"(",
"i",
")",
",",
"0",
")",
"assert",
"driver_id",
".",
"binary",
"(",
")",
"==",
"error_data",
".",
"DriverId",
"(",
")",
"error_message",
"=",
"{",
"\"type\"",
":",
"decode",
"(",
"error_data",
".",
"Type",
"(",
")",
")",
",",
"\"message\"",
":",
"decode",
"(",
"error_data",
".",
"ErrorMessage",
"(",
")",
")",
",",
"\"timestamp\"",
":",
"error_data",
".",
"Timestamp",
"(",
")",
",",
"}",
"error_messages",
".",
"append",
"(",
"error_message",
")",
"return",
"error_messages"
] |
Encrypt the given data with cipher that is got from AES . cipher call . | def encrypt ( self , data ) : padding = self . mode ( ) . padding ( ) if padding is not None : data = padding . pad ( data , WAESMode . __data_padding_length__ ) return self . cipher ( ) . encrypt_block ( data ) | 8,187 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/crypto/aes.py#L501-L511 | [
"def",
"_config_options",
"(",
"self",
")",
":",
"self",
".",
"_config_sortable",
"(",
"self",
".",
"_sortable",
")",
"self",
".",
"_config_drag_cols",
"(",
"self",
".",
"_drag_cols",
")"
] |
Decrypt the given data with cipher that is got from AES . cipher call . | def decrypt ( self , data , decode = False ) : #result = self.cipher().decrypt(data) result = self . cipher ( ) . decrypt_block ( data ) padding = self . mode ( ) . padding ( ) if padding is not None : result = padding . reverse_pad ( result , WAESMode . __data_padding_length__ ) return result . decode ( ) if decode else result | 8,188 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/crypto/aes.py#L515-L530 | [
"def",
"_config_options",
"(",
"self",
")",
":",
"self",
".",
"_config_sortable",
"(",
"self",
".",
"_sortable",
")",
"self",
".",
"_config_drag_cols",
"(",
"self",
".",
"_drag_cols",
")"
] |
Method is called whenever an exception is raised during registering a event | def thread_tracker_exception ( self , raised_exception ) : print ( 'Thread tracker execution was stopped by the exception. Exception: %s' % str ( raised_exception ) ) print ( 'Traceback:' ) print ( traceback . format_exc ( ) ) | 8,189 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/task/thread_tracker.py#L278-L287 | [
"def",
"get_draft_secret_key",
"(",
")",
":",
"# TODO: Per URL secret keys, so we can invalidate draft URLs for individual",
"# pages. For example, on publish.",
"draft_secret_key",
",",
"created",
"=",
"Text",
".",
"objects",
".",
"get_or_create",
"(",
"name",
"=",
"'DRAFT_SECRET_KEY'",
",",
"defaults",
"=",
"dict",
"(",
"value",
"=",
"get_random_string",
"(",
"50",
")",
",",
")",
")",
"return",
"draft_secret_key",
".",
"value"
] |
Save record in a internal storage | def __store_record ( self , record ) : if isinstance ( record , WSimpleTrackerStorage . Record ) is False : raise TypeError ( 'Invalid record type was' ) limit = self . record_limit ( ) if limit is not None and len ( self . __registry ) >= limit : self . __registry . pop ( 0 ) self . __registry . append ( record ) | 8,190 | https://github.com/a1ezzz/wasp-general/blob/1029839d33eb663f8dec76c1c46754d53c1de4a9/wasp_general/task/thread_tracker.py#L461-L473 | [
"def",
"get_source",
"(",
"source",
")",
":",
"def",
"extract_source",
"(",
"source",
",",
"destination",
")",
":",
"if",
"tarfile",
".",
"is_tarfile",
"(",
"source",
")",
":",
"_untar",
"(",
"source",
",",
"destination",
")",
"elif",
"zipfile",
".",
"is_zipfile",
"(",
"source",
")",
":",
"_unzip",
"(",
"source",
",",
"destination",
")",
"else",
":",
"raise",
"WagonError",
"(",
"'Failed to extract {0}. Please verify that the '",
"'provided file is a valid zip or tar.gz '",
"'archive'",
".",
"format",
"(",
"source",
")",
")",
"source",
"=",
"os",
".",
"path",
".",
"join",
"(",
"destination",
",",
"[",
"d",
"for",
"d",
"in",
"next",
"(",
"os",
".",
"walk",
"(",
"destination",
")",
")",
"[",
"1",
"]",
"]",
"[",
"0",
"]",
")",
"return",
"source",
"logger",
".",
"debug",
"(",
"'Retrieving source...'",
")",
"if",
"'://'",
"in",
"source",
":",
"split",
"=",
"source",
".",
"split",
"(",
"'://'",
")",
"schema",
"=",
"split",
"[",
"0",
"]",
"if",
"schema",
"in",
"[",
"'file'",
",",
"'http'",
",",
"'https'",
"]",
":",
"tmpdir",
"=",
"tempfile",
".",
"mkdtemp",
"(",
")",
"fd",
",",
"tmpfile",
"=",
"tempfile",
".",
"mkstemp",
"(",
")",
"os",
".",
"close",
"(",
"fd",
")",
"try",
":",
"_download_file",
"(",
"source",
",",
"tmpfile",
")",
"source",
"=",
"extract_source",
"(",
"tmpfile",
",",
"tmpdir",
")",
"finally",
":",
"os",
".",
"remove",
"(",
"tmpfile",
")",
"else",
":",
"raise",
"WagonError",
"(",
"'Source URL type {0} is not supported'",
".",
"format",
"(",
"schema",
")",
")",
"elif",
"os",
".",
"path",
".",
"isfile",
"(",
"source",
")",
":",
"tmpdir",
"=",
"tempfile",
".",
"mkdtemp",
"(",
")",
"source",
"=",
"extract_source",
"(",
"source",
",",
"tmpdir",
")",
"elif",
"os",
".",
"path",
".",
"isdir",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"source",
")",
")",
":",
"source",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"source",
")",
"elif",
"'=='",
"in",
"source",
":",
"base_name",
",",
"version",
"=",
"source",
".",
"split",
"(",
"'=='",
")",
"source",
"=",
"_get_package_info_from_pypi",
"(",
"base_name",
")",
"[",
"'name'",
"]",
"source",
"=",
"'{0}=={1}'",
".",
"format",
"(",
"source",
",",
"version",
")",
"else",
":",
"source",
"=",
"_get_package_info_from_pypi",
"(",
"source",
")",
"[",
"'name'",
"]",
"logger",
".",
"debug",
"(",
"'Source is: %s'",
",",
"source",
")",
"return",
"source"
] |
Put a value into nested dicts by the order of the given keys tuple . | def put_nested_val ( dict_obj , key_tuple , value ) : current_dict = dict_obj for key in key_tuple [ : - 1 ] : try : current_dict = current_dict [ key ] except KeyError : current_dict [ key ] = { } current_dict = current_dict [ key ] current_dict [ key_tuple [ - 1 ] ] = value | 8,191 | https://github.com/shaypal5/strct/blob/f3a301692d052ddb79331230b3c00625db1d83fc/strct/dicts/_dict.py#L131-L168 | [
"def",
"new_connection_status",
"(",
"self",
",",
"conn_status",
")",
":",
"if",
"conn_status",
".",
"status",
"==",
"CONNECTION_STATUS_CONNECTED",
":",
"self",
".",
"_mz",
".",
"update_members",
"(",
")",
"if",
"(",
"conn_status",
".",
"status",
"==",
"CONNECTION_STATUS_DISCONNECTED",
"or",
"conn_status",
".",
"status",
"==",
"CONNECTION_STATUS_LOST",
")",
":",
"self",
".",
"_mz",
".",
"reset_members",
"(",
")"
] |
Return a value from nested dicts by any path in the given keys tuple . | def get_alternative_nested_val ( key_tuple , dict_obj ) : # print('key_tuple: {}'.format(key_tuple)) # print('dict_obj: {}'.format(dict_obj)) top_keys = key_tuple [ 0 ] if isinstance ( key_tuple [ 0 ] , ( list , tuple ) ) else [ key_tuple [ 0 ] ] for key in top_keys : try : if len ( key_tuple ) < 2 : return dict_obj [ key ] return get_alternative_nested_val ( key_tuple [ 1 : ] , dict_obj [ key ] ) except ( KeyError , TypeError , IndexError ) : pass raise KeyError | 8,192 | https://github.com/shaypal5/strct/blob/f3a301692d052ddb79331230b3c00625db1d83fc/strct/dicts/_dict.py#L198-L230 | [
"def",
"is_labial",
"(",
"c",
",",
"lang",
")",
":",
"o",
"=",
"get_offset",
"(",
"c",
",",
"lang",
")",
"return",
"(",
"o",
">=",
"LABIAL_RANGE",
"[",
"0",
"]",
"and",
"o",
"<=",
"LABIAL_RANGE",
"[",
"1",
"]",
")"
] |
Returns a sub - dict composed solely of the given keys . | def subdict_by_keys ( dict_obj , keys ) : return { k : dict_obj [ k ] for k in set ( keys ) . intersection ( dict_obj . keys ( ) ) } | 8,193 | https://github.com/shaypal5/strct/blob/f3a301692d052ddb79331230b3c00625db1d83fc/strct/dicts/_dict.py#L289-L312 | [
"def",
"_log10_Inorm_extern_atmx",
"(",
"self",
",",
"Teff",
",",
"logg",
",",
"abun",
")",
":",
"log10_Inorm",
"=",
"libphoebe",
".",
"wd_atmint",
"(",
"Teff",
",",
"logg",
",",
"abun",
",",
"self",
".",
"extern_wd_idx",
",",
"self",
".",
"wd_data",
"[",
"\"planck_table\"",
"]",
",",
"self",
".",
"wd_data",
"[",
"\"atm_table\"",
"]",
")",
"return",
"log10_Inorm"
] |
Adds the given val to the set mapped by the given key . If the key is missing from the dict the given mapping is added . | def add_to_dict_val_set ( dict_obj , key , val ) : try : dict_obj [ key ] . add ( val ) except KeyError : dict_obj [ key ] = set ( [ val ] ) | 8,194 | https://github.com/shaypal5/strct/blob/f3a301692d052ddb79331230b3c00625db1d83fc/strct/dicts/_dict.py#L386-L403 | [
"def",
"_bsecurate_cli_component_file_refs",
"(",
"args",
")",
":",
"data",
"=",
"curate",
".",
"component_file_refs",
"(",
"args",
".",
"files",
")",
"s",
"=",
"''",
"for",
"cfile",
",",
"cdata",
"in",
"data",
".",
"items",
"(",
")",
":",
"s",
"+=",
"cfile",
"+",
"'\\n'",
"rows",
"=",
"[",
"]",
"for",
"el",
",",
"refs",
"in",
"cdata",
":",
"rows",
".",
"append",
"(",
"(",
"' '",
"+",
"el",
",",
"' '",
".",
"join",
"(",
"refs",
")",
")",
")",
"s",
"+=",
"'\\n'",
".",
"join",
"(",
"format_columns",
"(",
"rows",
")",
")",
"+",
"'\\n\\n'",
"return",
"s"
] |
Adds the given value list to the set mapped by the given key . If the key is missing from the dict the given mapping is added . | def add_many_to_dict_val_set ( dict_obj , key , val_list ) : try : dict_obj [ key ] . update ( val_list ) except KeyError : dict_obj [ key ] = set ( val_list ) | 8,195 | https://github.com/shaypal5/strct/blob/f3a301692d052ddb79331230b3c00625db1d83fc/strct/dicts/_dict.py#L406-L423 | [
"def",
"from_config",
"(",
"_config",
",",
"*",
"*",
"options",
")",
":",
"expected_args",
"=",
"(",
"'path'",
",",
")",
"rconfig",
".",
"check_config_options",
"(",
"\"SQLiteEventStore\"",
",",
"expected_args",
",",
"tuple",
"(",
")",
",",
"options",
")",
"return",
"SQLiteEventStore",
"(",
"options",
"[",
"'path'",
"]",
")"
] |
Adds the given value list to the list mapped by the given key . If the key is missing from the dict the given mapping is added . | def add_many_to_dict_val_list ( dict_obj , key , val_list ) : try : dict_obj [ key ] . extend ( val_list ) except KeyError : dict_obj [ key ] = list ( val_list ) | 8,196 | https://github.com/shaypal5/strct/blob/f3a301692d052ddb79331230b3c00625db1d83fc/strct/dicts/_dict.py#L426-L443 | [
"def",
"is_local_url",
"(",
"target",
")",
":",
"ref_url",
"=",
"urlparse",
"(",
"cfg",
".",
"get",
"(",
"'CFG_SITE_SECURE_URL'",
")",
")",
"test_url",
"=",
"urlparse",
"(",
"urljoin",
"(",
"cfg",
".",
"get",
"(",
"'CFG_SITE_SECURE_URL'",
")",
",",
"target",
")",
")",
"return",
"test_url",
".",
"scheme",
"in",
"(",
"'http'",
",",
"'https'",
")",
"and",
"ref_url",
".",
"netloc",
"==",
"test_url",
".",
"netloc"
] |
Returns the keys that maps to the top n max values in the given dict . | def get_keys_of_max_n ( dict_obj , n ) : return sorted ( [ item [ 0 ] for item in sorted ( dict_obj . items ( ) , key = lambda item : item [ 1 ] , reverse = True ) [ : n ] ] ) | 8,197 | https://github.com/shaypal5/strct/blob/f3a301692d052ddb79331230b3c00625db1d83fc/strct/dicts/_dict.py#L459-L473 | [
"def",
"set_led",
"(",
"self",
",",
"colorcode",
")",
":",
"data",
"=",
"[",
"]",
"data",
".",
"append",
"(",
"0x0A",
")",
"data",
".",
"append",
"(",
"self",
".",
"servoid",
")",
"data",
".",
"append",
"(",
"RAM_WRITE_REQ",
")",
"data",
".",
"append",
"(",
"LED_CONTROL_RAM",
")",
"data",
".",
"append",
"(",
"0x01",
")",
"data",
".",
"append",
"(",
"colorcode",
")",
"send_data",
"(",
"data",
")"
] |
Recursively merges the two given dicts into a single dict . | def deep_merge_dict ( base , priority ) : if not isinstance ( base , dict ) or not isinstance ( priority , dict ) : return priority result = copy . deepcopy ( base ) for key in priority . keys ( ) : if key in base : result [ key ] = deep_merge_dict ( base [ key ] , priority [ key ] ) else : result [ key ] = priority [ key ] return result | 8,198 | https://github.com/shaypal5/strct/blob/f3a301692d052ddb79331230b3c00625db1d83fc/strct/dicts/_dict.py#L539-L578 | [
"def",
"start",
"(",
"self",
",",
"device",
")",
":",
"super",
"(",
"NativeBLEVirtualInterface",
",",
"self",
")",
".",
"start",
"(",
"device",
")",
"self",
".",
"set_advertising",
"(",
"True",
")"
] |
Normalizes values in the given dict with int values . | def norm_int_dict ( int_dict ) : norm_dict = int_dict . copy ( ) val_sum = sum ( norm_dict . values ( ) ) for key in norm_dict : norm_dict [ key ] = norm_dict [ key ] / val_sum return norm_dict | 8,199 | https://github.com/shaypal5/strct/blob/f3a301692d052ddb79331230b3c00625db1d83fc/strct/dicts/_dict.py#L581-L606 | [
"def",
"guest_start",
"(",
"self",
",",
"userid",
")",
":",
"requestData",
"=",
"\"PowerVM \"",
"+",
"userid",
"+",
"\" on\"",
"with",
"zvmutils",
".",
"log_and_reraise_smt_request_failed",
"(",
")",
":",
"self",
".",
"_request",
"(",
"requestData",
")"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.