query stringlengths 5 1.23k | positive stringlengths 53 15.2k | id_ int64 0 252k | task_name stringlengths 87 242 | negative listlengths 20 553 |
|---|---|---|---|---|
Decode length based on given bytes . | def decodeLength ( length ) : bytes_length = len ( length ) if bytes_length < 2 : offset = b'\x00\x00\x00' XOR = 0 elif bytes_length < 3 : offset = b'\x00\x00' XOR = 0x8000 elif bytes_length < 4 : offset = b'\x00' XOR = 0xC00000 elif bytes_length < 5 : offset = b'' XOR = 0xE0000000 else : raise ConnectionError ( 'Unabl... | 250,800 | https://github.com/luqasz/librouteros/blob/59293eb49c07a339af87b0416e4619e78ca5176d/librouteros/connections.py#L88-L114 | [
"def",
"remove_stale_javascripts",
"(",
"portal",
")",
":",
"logger",
".",
"info",
"(",
"\"Removing stale javascripts ...\"",
")",
"for",
"js",
"in",
"JAVASCRIPTS_TO_REMOVE",
":",
"logger",
".",
"info",
"(",
"\"Unregistering JS %s\"",
"%",
"js",
")",
"portal",
"."... |
Write encoded sentence . | def writeSentence ( self , cmd , * words ) : encoded = self . encodeSentence ( cmd , * words ) self . log ( '<---' , cmd , * words ) self . transport . write ( encoded ) | 250,801 | https://github.com/luqasz/librouteros/blob/59293eb49c07a339af87b0416e4619e78ca5176d/librouteros/connections.py#L129-L138 | [
"def",
"_device_expiry_callback",
"(",
"self",
")",
":",
"expired",
"=",
"0",
"for",
"adapters",
"in",
"self",
".",
"_devices",
".",
"values",
"(",
")",
":",
"to_remove",
"=",
"[",
"]",
"now",
"=",
"monotonic",
"(",
")",
"for",
"adapter_id",
",",
"dev"... |
Read as many bytes from socket as specified in length . Loop as long as every byte is read unless exception is raised . | def read ( self , length ) : data = bytearray ( ) while len ( data ) != length : data += self . sock . recv ( ( length - len ( data ) ) ) if not data : raise ConnectionError ( 'Connection unexpectedly closed.' ) return data | 250,802 | https://github.com/luqasz/librouteros/blob/59293eb49c07a339af87b0416e4619e78ca5176d/librouteros/connections.py#L178-L188 | [
"def",
"getCanonicalRep",
"(",
"record_cluster",
")",
":",
"canonical_rep",
"=",
"{",
"}",
"keys",
"=",
"record_cluster",
"[",
"0",
"]",
".",
"keys",
"(",
")",
"for",
"key",
"in",
"keys",
":",
"key_values",
"=",
"[",
"]",
"for",
"record",
"in",
"record... |
Split given attribute word to key value pair . | def parseWord ( word ) : mapping = { 'yes' : True , 'true' : True , 'no' : False , 'false' : False } _ , key , value = word . split ( '=' , 2 ) try : value = int ( value ) except ValueError : value = mapping . get ( value , value ) return ( key , value ) | 250,803 | https://github.com/luqasz/librouteros/blob/59293eb49c07a339af87b0416e4619e78ca5176d/librouteros/protocol.py#L1-L16 | [
"def",
"GenerateGaussianNoise",
"(",
"PSD",
")",
":",
"Noise",
"=",
"np",
".",
"zeros",
"(",
"(",
"N_fd",
")",
",",
"complex",
")",
"# Generate noise from PSD ",
"Real",
"=",
"np",
".",
"random",
".",
"randn",
"(",
"N_fd",
")",
"*",
"np",
".",
"sqrt",
... |
Create a attribute word from key value pair . Values are casted to api equivalents . | def composeWord ( key , value ) : mapping = { True : 'yes' , False : 'no' } # this is necesary because 1 == True, 0 == False if type ( value ) == int : value = str ( value ) else : value = mapping . get ( value , str ( value ) ) return '={}={}' . format ( key , value ) | 250,804 | https://github.com/luqasz/librouteros/blob/59293eb49c07a339af87b0416e4619e78ca5176d/librouteros/protocol.py#L19-L30 | [
"def",
"fullLoad",
"(",
"self",
")",
":",
"self",
".",
"_parseDirectories",
"(",
"self",
".",
"ntHeaders",
".",
"optionalHeader",
".",
"dataDirectory",
",",
"self",
".",
"PE_TYPE",
")"
] |
Login using pre routeros 6 . 43 authorization method . | def login_token ( api , username , password ) : sentence = api ( '/login' ) token = tuple ( sentence ) [ 0 ] [ 'ret' ] encoded = encode_password ( token , password ) tuple ( api ( '/login' , * * { 'name' : username , 'response' : encoded } ) ) | 250,805 | https://github.com/luqasz/librouteros/blob/59293eb49c07a339af87b0416e4619e78ca5176d/librouteros/login.py#L15-L20 | [
"def",
"remove_users_from_organization",
"(",
"self",
",",
"organization_id",
",",
"users_list",
")",
":",
"log",
".",
"warning",
"(",
"'Removing users...'",
")",
"url",
"=",
"'rest/servicedeskapi/organization/{}/user'",
".",
"format",
"(",
"organization_id",
")",
"da... |
Recursive function which checks if a relation is valid . | def check_relations ( self , relations ) : for rel in relations : if not rel : continue fields = rel . split ( '.' , 1 ) local_field = fields [ 0 ] if local_field not in self . fields : raise ValueError ( 'Unknown field "{}"' . format ( local_field ) ) field = self . fields [ local_field ] if not isinstance ( field , B... | 250,806 | https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/schema.py#L102-L120 | [
"def",
"add_string",
"(",
"self",
",",
"data",
")",
":",
"lines",
"=",
"[",
"]",
"while",
"data",
":",
"match",
"=",
"self",
".",
"_line_end_re",
".",
"search",
"(",
"data",
")",
"if",
"match",
"is",
"None",
":",
"chunk",
"=",
"data",
"else",
":",
... |
Post - dump hook that formats serialized data as a top - level JSON API object . | def format_json_api_response ( self , data , many ) : ret = self . format_items ( data , many ) ret = self . wrap_response ( ret , many ) ret = self . render_included_data ( ret ) ret = self . render_meta_document ( ret ) return ret | 250,807 | https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/schema.py#L123-L132 | [
"def",
"setFlag",
"(",
"self",
",",
"flag",
",",
"state",
"=",
"True",
")",
":",
"if",
"state",
":",
"self",
".",
"__flags",
"|=",
"flag",
"else",
":",
"self",
".",
"__flags",
"&=",
"~",
"flag"
] |
Override marshmallow . Schema . _do_load for custom JSON API handling . | def _do_load ( self , data , many = None , * * kwargs ) : many = self . many if many is None else bool ( many ) # Store this on the instance so we have access to the included data # when processing relationships (``included`` is outside of the # ``data``). self . included_data = data . get ( 'included' , { } ) self . d... | 250,808 | https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/schema.py#L229-L260 | [
"def",
"stats",
"(",
"self",
")",
":",
"stats_online",
"=",
"CRef",
".",
"cint",
"(",
")",
"stats_ingame",
"=",
"CRef",
".",
"cint",
"(",
")",
"stats_chatting",
"=",
"CRef",
".",
"cint",
"(",
")",
"self",
".",
"_iface",
".",
"get_clan_stats",
"(",
"s... |
Extract included data matching the items in data . | def _extract_from_included ( self , data ) : return ( item for item in self . included_data if item [ 'type' ] == data [ 'type' ] and str ( item [ 'id' ] ) == str ( data [ 'id' ] ) ) | 250,809 | https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/schema.py#L262-L270 | [
"def",
"console",
"(",
"self",
",",
"console",
")",
":",
"if",
"console",
"==",
"self",
".",
"_console",
":",
"return",
"if",
"self",
".",
"_console_type",
"==",
"\"vnc\"",
"and",
"console",
"is",
"not",
"None",
"and",
"console",
"<",
"5900",
":",
"rai... |
Inflect text if the inflect class Meta option is defined otherwise do nothing . | def inflect ( self , text ) : return self . opts . inflect ( text ) if self . opts . inflect else text | 250,810 | https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/schema.py#L272-L276 | [
"def",
"write_to_stream",
"(",
"stream",
",",
"response",
",",
"block_len",
"=",
"1024",
")",
":",
"try",
":",
"i_start",
"=",
"0",
"i_end",
"=",
"block_len",
"while",
"True",
":",
"if",
"i_end",
">",
"len",
"(",
"response",
")",
":",
"stream",
"(",
... |
Format validation errors as JSON Error objects . | def format_errors ( self , errors , many ) : if not errors : return { } if isinstance ( errors , ( list , tuple ) ) : return { 'errors' : errors } formatted_errors = [ ] if many : for index , errors in iteritems ( errors ) : for field_name , field_errors in iteritems ( errors ) : formatted_errors . extend ( [ self . fo... | 250,811 | https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/schema.py#L280-L301 | [
"def",
"delete_classifier",
"(",
"self",
",",
"classifier_id",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"classifier_id",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'classifier_id must be provided'",
")",
"headers",
"=",
"{",
"}",
"if",
"'headers'",
"in",
... |
Override - able hook to format a single error message as an Error object . | def format_error ( self , field_name , message , index = None ) : pointer = [ '/data' ] if index is not None : pointer . append ( str ( index ) ) relationship = isinstance ( self . declared_fields . get ( field_name ) , BaseRelationship , ) if relationship : pointer . append ( 'relationships' ) elif field_name != 'id' ... | 250,812 | https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/schema.py#L303-L332 | [
"def",
"edit",
"(",
"self",
",",
"data_src",
",",
"value",
")",
":",
"# check if opening file",
"if",
"'filename'",
"in",
"value",
":",
"items",
"=",
"[",
"k",
"for",
"k",
",",
"v",
"in",
"self",
".",
"reg",
".",
"data_source",
".",
"iteritems",
"(",
... |
Format a single datum as a Resource object . | def format_item ( self , item ) : # http://jsonapi.org/format/#document-top-level # Primary data MUST be either... a single resource object, a single resource # identifier object, or null, for requests that target single resources if not item : return None ret = self . dict_class ( ) ret [ TYPE ] = self . opts . type_ ... | 250,813 | https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/schema.py#L334-L379 | [
"def",
"stop_experiment",
"(",
"args",
")",
":",
"experiment_id_list",
"=",
"parse_ids",
"(",
"args",
")",
"if",
"experiment_id_list",
":",
"experiment_config",
"=",
"Experiments",
"(",
")",
"experiment_dict",
"=",
"experiment_config",
".",
"get_all_experiments",
"(... |
Format data as a Resource object or list of Resource objects . | def format_items ( self , data , many ) : if many : return [ self . format_item ( item ) for item in data ] else : return self . format_item ( data ) | 250,814 | https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/schema.py#L381-L389 | [
"def",
"reset_game",
"(",
"self",
")",
":",
"self",
".",
"ms_game",
".",
"reset_game",
"(",
")",
"self",
".",
"update_grid",
"(",
")",
"self",
".",
"time",
"=",
"0",
"self",
".",
"timer",
".",
"start",
"(",
"1000",
")"
] |
Hook for adding links to the root of the response data . | def get_top_level_links ( self , data , many ) : self_link = None if many : if self . opts . self_url_many : self_link = self . generate_url ( self . opts . self_url_many ) else : if self . opts . self_url : self_link = data . get ( 'links' , { } ) . get ( 'self' , None ) return { 'self' : self_link } | 250,815 | https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/schema.py#L391-L402 | [
"def",
"ideal_gas",
"(",
"target",
",",
"pressure",
"=",
"'pore.pressure'",
",",
"temperature",
"=",
"'pore.temperature'",
")",
":",
"R",
"=",
"8.31447",
"P",
"=",
"target",
"[",
"pressure",
"]",
"T",
"=",
"target",
"[",
"temperature",
"]",
"value",
"=",
... |
Hook for adding links to a resource object . | def get_resource_links ( self , item ) : if self . opts . self_url : ret = self . dict_class ( ) kwargs = resolve_params ( item , self . opts . self_url_kwargs or { } ) ret [ 'self' ] = self . generate_url ( self . opts . self_url , * * kwargs ) return ret return None | 250,816 | https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/schema.py#L404-L411 | [
"def",
"stop_experiment",
"(",
"args",
")",
":",
"experiment_id_list",
"=",
"parse_ids",
"(",
"args",
")",
"if",
"experiment_id_list",
":",
"experiment_config",
"=",
"Experiments",
"(",
")",
"experiment_dict",
"=",
"experiment_config",
".",
"get_all_experiments",
"(... |
Wrap data and links according to the JSON API | def wrap_response ( self , data , many ) : ret = { 'data' : data } # self_url_many is still valid when there isn't any data, but self_url # may only be included if there is data in the ret if many or data : top_level_links = self . get_top_level_links ( data , many ) if top_level_links [ 'self' ] : ret [ 'links' ] = to... | 250,817 | https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/schema.py#L413-L422 | [
"def",
"get_token",
"(",
"filename",
"=",
"TOKEN_PATH",
",",
"envvar",
"=",
"TOKEN_ENVVAR",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"filename",
")",
":",
"with",
"open",
"(",
"filename",
")",
"as",
"token_file",
":",
"token",
"=",
"token... |
Extract the id key and validate the request structure . | def extract_value ( self , data ) : errors = [ ] if 'id' not in data : errors . append ( 'Must have an `id` field' ) if 'type' not in data : errors . append ( 'Must have a `type` field' ) elif data [ 'type' ] != self . type_ : errors . append ( 'Invalid `type` specified' ) if errors : raise ValidationError ( errors ) #... | 250,818 | https://github.com/marshmallow-code/marshmallow-jsonapi/blob/7183c9bb5cdeace4143e6678bab48d433ac439a1/marshmallow_jsonapi/fields.py#L183-L208 | [
"def",
"start",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"is_running",
"(",
")",
":",
"self",
".",
"websock_url",
"=",
"self",
".",
"chrome",
".",
"start",
"(",
"*",
"*",
"kwargs",
")",
"self",
".",
"websock",
"="... |
Temporary fill package digests stated in Pipfile . lock . | def fill_package_digests ( generated_project : Project ) -> Project : for package_version in chain ( generated_project . pipfile_lock . packages , generated_project . pipfile_lock . dev_packages ) : if package_version . hashes : # Already filled from the last run. continue if package_version . index : scanned_hashes = ... | 250,819 | https://github.com/thoth-station/python/blob/bd2a4a4f552faf54834ce9febea4e2834a1d0bab/thoth/python/helpers.py#L26-L50 | [
"def",
"get_queryset",
"(",
"self",
")",
":",
"qs",
"=",
"super",
"(",
")",
".",
"get_queryset",
"(",
")",
"kind",
"=",
"self",
".",
"get_event_kind",
"(",
")",
"if",
"kind",
"is",
"not",
"None",
":",
"qs",
"=",
"qs",
".",
"filter",
"(",
"kind",
... |
Fetch digests for the given package in specified version from the given package index . | def fetch_digests ( self , package_name : str , package_version : str ) -> dict : report = { } for source in self . _sources : try : report [ source . url ] = source . get_package_hashes ( package_name , package_version ) except NotFound as exc : _LOGGER . debug ( f"Package {package_name} in version {package_version} n... | 250,820 | https://github.com/thoth-station/python/blob/bd2a4a4f552faf54834ce9febea4e2834a1d0bab/thoth/python/digests_fetcher.py#L44-L57 | [
"def",
"win32_refresh_window",
"(",
"cls",
")",
":",
"# Get console handle",
"handle",
"=",
"windll",
".",
"kernel32",
".",
"GetConsoleWindow",
"(",
")",
"RDW_INVALIDATE",
"=",
"0x0001",
"windll",
".",
"user32",
".",
"RedrawWindow",
"(",
"handle",
",",
"None",
... |
An extremely entropy efficient passphrase generator . | def random_passphrase_from_wordlist ( phrase_length , wordlist ) : passphrase_words = [ ] numbytes_of_entropy = phrase_length * 2 entropy = list ( dev_random_entropy ( numbytes_of_entropy , fallback_to_urandom = True ) ) bytes_per_word = int ( ceil ( log ( len ( wordlist ) , 2 ) / 8 ) ) if ( phrase_length * bytes_per_w... | 250,821 | https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/passphrases/legacy.py#L15-L41 | [
"def",
"_broadcast_indexes",
"(",
"self",
",",
"key",
")",
":",
"key",
"=",
"self",
".",
"_item_key_to_tuple",
"(",
"key",
")",
"# key is a tuple",
"# key is a tuple of full size",
"key",
"=",
"indexing",
".",
"expanded_indexer",
"(",
"key",
",",
"self",
".",
... |
hash is in hex or binary format | def reverse_hash ( hash , hex_format = True ) : if not hex_format : hash = hexlify ( hash ) return "" . join ( reversed ( [ hash [ i : i + 2 ] for i in range ( 0 , len ( hash ) , 2 ) ] ) ) | 250,822 | https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/hash.py#L45-L50 | [
"def",
"list_distributions",
"(",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"retries",
"=",
"10",
"sleep",
"=",
"6",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
... |
Gets the number of words randomly selected from a given wordlist that would result in the number of bits of entropy specified . | def get_num_words_with_entropy ( bits_of_entropy , wordlist ) : entropy_per_word = math . log ( len ( wordlist ) ) / math . log ( 2 ) num_words = int ( math . ceil ( bits_of_entropy / entropy_per_word ) ) return num_words | 250,823 | https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/passphrases/passphrase.py#L29-L35 | [
"def",
"parse_schedules",
"(",
"username",
",",
"password",
",",
"importer",
",",
"progress",
",",
"utc_start",
"=",
"None",
",",
"utc_stop",
"=",
"None",
")",
":",
"file_obj",
"=",
"get_file_object",
"(",
"username",
",",
"password",
",",
"utc_start",
",",
... |
Creates a passphrase that has a certain number of bits of entropy OR a certain number of words . | def create_passphrase ( bits_of_entropy = None , num_words = None , language = 'english' , word_source = 'wiktionary' ) : wordlist = get_wordlist ( language , word_source ) if not num_words : if not bits_of_entropy : bits_of_entropy = 80 num_words = get_num_words_with_entropy ( bits_of_entropy , wordlist ) return ' ' .... | 250,824 | https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/passphrases/passphrase.py#L42-L54 | [
"def",
"add_linked_station",
"(",
"self",
",",
"datfile",
",",
"station",
",",
"location",
"=",
"None",
")",
":",
"if",
"datfile",
"not",
"in",
"self",
".",
"fixed_stations",
":",
"self",
".",
"fixed_stations",
"[",
"datfile",
"]",
"=",
"{",
"station",
"... |
Serializes a transaction input . | def serialize_input ( input , signature_script_hex = '' ) : if not ( isinstance ( input , dict ) and 'transaction_hash' in input and 'output_index' in input ) : raise Exception ( 'Required parameters: transaction_hash, output_index' ) if is_hex ( str ( input [ 'transaction_hash' ] ) ) and len ( str ( input [ 'transacti... | 250,825 | https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/serialize.py#L20-L42 | [
"def",
"get_settings",
"(",
")",
":",
"s",
"=",
"getattr",
"(",
"settings",
",",
"'CLAMAV_UPLOAD'",
",",
"{",
"}",
")",
"s",
"=",
"{",
"'CONTENT_TYPE_CHECK_ENABLED'",
":",
"s",
".",
"get",
"(",
"'CONTENT_TYPE_CHECK_ENABLED'",
",",
"False",
")",
",",
"# LAS... |
Serializes a transaction output . | def serialize_output ( output ) : if not ( 'value' in output and 'script_hex' in output ) : raise Exception ( 'Invalid output' ) return '' . join ( [ hexlify ( struct . pack ( '<Q' , output [ 'value' ] ) ) , # pack into 8 bites hexlify ( variable_length_int ( len ( output [ 'script_hex' ] ) / 2 ) ) , output [ 'script_h... | 250,826 | https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/serialize.py#L45-L55 | [
"def",
"_get_partition_info",
"(",
"storage_system",
",",
"device_path",
")",
":",
"try",
":",
"partition_infos",
"=",
"storage_system",
".",
"RetrieveDiskPartitionInfo",
"(",
"devicePath",
"=",
"[",
"device_path",
"]",
")",
"except",
"vim",
".",
"fault",
".",
"... |
Serializes a transaction . | def serialize_transaction ( inputs , outputs , lock_time = 0 , version = 1 ) : # add in the inputs serialized_inputs = '' . join ( [ serialize_input ( input ) for input in inputs ] ) # add in the outputs serialized_outputs = '' . join ( [ serialize_output ( output ) for output in outputs ] ) return '' . join ( [ # add ... | 250,827 | https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/serialize.py#L58-L81 | [
"def",
"get_listing",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'listing'",
")",
":",
"allEvents",
"=",
"self",
".",
"get_allEvents",
"(",
")",
"openEvents",
"=",
"allEvents",
".",
"filter",
"(",
"registrationOpen",
"=",
"True",
"... |
Given a serialized transaction return its inputs outputs locktime and version | def deserialize_transaction ( tx_hex ) : tx = bitcoin . deserialize ( str ( tx_hex ) ) inputs = tx [ "ins" ] outputs = tx [ "outs" ] ret_inputs = [ ] ret_outputs = [ ] for inp in inputs : ret_inp = { "transaction_hash" : inp [ "outpoint" ] [ "hash" ] , "output_index" : int ( inp [ "outpoint" ] [ "index" ] ) , } if "seq... | 250,828 | https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/serialize.py#L84-L130 | [
"def",
"_get_exception_class_from_status_code",
"(",
"status_code",
")",
":",
"if",
"status_code",
"==",
"'100'",
":",
"return",
"None",
"exc_class",
"=",
"STATUS_CODE_MAPPING",
".",
"get",
"(",
"status_code",
")",
"if",
"not",
"exc_class",
":",
"# No status code ma... |
Encodes integers into variable length integers which are used in Bitcoin in order to save space . | def variable_length_int ( i ) : if not isinstance ( i , ( int , long ) ) : raise Exception ( 'i must be an integer' ) if i < ( 2 ** 8 - 3 ) : return chr ( i ) # pack the integer into one byte elif i < ( 2 ** 16 ) : return chr ( 253 ) + struct . pack ( '<H' , i ) # pack into 2 bytes elif i < ( 2 ** 32 ) : return chr ( 2... | 250,829 | https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/utils.py#L25-L41 | [
"def",
"get_person_by_employee_id",
"(",
"self",
",",
"employee_id",
")",
":",
"if",
"not",
"self",
".",
"valid_employee_id",
"(",
"employee_id",
")",
":",
"raise",
"InvalidEmployeeID",
"(",
"employee_id",
")",
"url",
"=",
"\"{}.json?{}\"",
".",
"format",
"(",
... |
Takes in an address and returns the script | def make_pay_to_address_script ( address ) : hash160 = hexlify ( b58check_decode ( address ) ) script_string = 'OP_DUP OP_HASH160 %s OP_EQUALVERIFY OP_CHECKSIG' % hash160 return script_to_hex ( script_string ) | 250,830 | https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/scripts.py#L37-L42 | [
"def",
"unbounded",
"(",
"self",
")",
":",
"unbounded_dims",
"=",
"[",
"]",
"# Dimensioned streams do not need to be bounded",
"stream_params",
"=",
"set",
"(",
"util",
".",
"stream_parameters",
"(",
"self",
".",
"streams",
")",
")",
"for",
"kdim",
"in",
"self",... |
Takes in raw ascii data to be embedded and returns a script . | def make_op_return_script ( data , format = 'bin' ) : if format == 'hex' : assert ( is_hex ( data ) ) hex_data = data elif format == 'bin' : hex_data = hexlify ( data ) else : raise Exception ( "Format must be either 'hex' or 'bin'" ) num_bytes = count_bytes ( hex_data ) if num_bytes > MAX_BYTES_AFTER_OP_RETURN : raise... | 250,831 | https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/scripts.py#L44-L60 | [
"def",
"_reset_offset",
"(",
"self",
",",
"partition",
")",
":",
"timestamp",
"=",
"self",
".",
"_subscriptions",
".",
"assignment",
"[",
"partition",
"]",
".",
"reset_strategy",
"if",
"timestamp",
"is",
"OffsetResetStrategy",
".",
"EARLIEST",
":",
"strategy",
... |
create a bitcoind service proxy | def create_bitcoind_service_proxy ( rpc_username , rpc_password , server = '127.0.0.1' , port = 8332 , use_https = False ) : protocol = 'https' if use_https else 'http' uri = '%s://%s:%s@%s:%s' % ( protocol , rpc_username , rpc_password , server , port ) return AuthServiceProxy ( uri ) | 250,832 | https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/services/bitcoind.py#L21-L28 | [
"def",
"cmprss",
"(",
"delim",
",",
"n",
",",
"instr",
",",
"lenout",
"=",
"_default_len_out",
")",
":",
"delim",
"=",
"ctypes",
".",
"c_char",
"(",
"delim",
".",
"encode",
"(",
"encoding",
"=",
"'UTF-8'",
")",
")",
"n",
"=",
"ctypes",
".",
"c_int",
... |
Gets the unspent outputs for a given address . | def get_unspents ( address , blockchain_client = BlockchainInfoClient ( ) ) : if isinstance ( blockchain_client , BlockcypherClient ) : return blockcypher . get_unspents ( address , blockchain_client ) elif isinstance ( blockchain_client , BlockchainInfoClient ) : return blockchain_info . get_unspents ( address , block... | 250,833 | https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/network.py#L32-L48 | [
"def",
"pacl_term",
"(",
"DiamTube",
",",
"ConcClay",
",",
"ConcAl",
",",
"ConcNatOrgMat",
",",
"NatOrgMat",
",",
"coag",
",",
"material",
",",
"RatioHeightDiameter",
")",
":",
"return",
"(",
"gamma_coag",
"(",
"ConcClay",
",",
"ConcAl",
",",
"coag",
",",
... |
Dispatches a raw hex transaction to the network . | def broadcast_transaction ( hex_tx , blockchain_client ) : if isinstance ( blockchain_client , BlockcypherClient ) : return blockcypher . broadcast_transaction ( hex_tx , blockchain_client ) elif isinstance ( blockchain_client , BlockchainInfoClient ) : return blockchain_info . broadcast_transaction ( hex_tx , blockcha... | 250,834 | https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/network.py#L51-L67 | [
"def",
"get_settings",
"(",
")",
":",
"s",
"=",
"getattr",
"(",
"settings",
",",
"'CLAMAV_UPLOAD'",
",",
"{",
"}",
")",
"s",
"=",
"{",
"'CONTENT_TYPE_CHECK_ENABLED'",
":",
"s",
".",
"get",
"(",
"'CONTENT_TYPE_CHECK_ENABLED'",
",",
"False",
")",
",",
"# LAS... |
Builds and signs a send to address transaction . | def make_send_to_address_tx ( recipient_address , amount , private_key , blockchain_client = BlockchainInfoClient ( ) , fee = STANDARD_FEE , change_address = None ) : # get out the private key object, sending address, and inputs private_key_obj , from_address , inputs = analyze_private_key ( private_key , blockchain_cl... | 250,835 | https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/network.py#L87-L110 | [
"def",
"get_monitors",
"(",
"self",
",",
"condition",
"=",
"None",
",",
"page_size",
"=",
"1000",
")",
":",
"req_kwargs",
"=",
"{",
"}",
"if",
"condition",
":",
"req_kwargs",
"[",
"'condition'",
"]",
"=",
"condition",
".",
"compile",
"(",
")",
"for",
"... |
Builds and signs an OP_RETURN transaction . | def make_op_return_tx ( data , private_key , blockchain_client = BlockchainInfoClient ( ) , fee = OP_RETURN_FEE , change_address = None , format = 'bin' ) : # get out the private key object, sending address, and inputs private_key_obj , from_address , inputs = analyze_private_key ( private_key , blockchain_client ) # g... | 250,836 | https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/network.py#L113-L136 | [
"def",
"add_fluctuations",
"(",
"hdf5_file",
",",
"N_columns",
",",
"N_processes",
")",
":",
"random_state",
"=",
"np",
".",
"random",
".",
"RandomState",
"(",
"0",
")",
"slice_queue",
"=",
"multiprocessing",
".",
"JoinableQueue",
"(",
")",
"pid_list",
"=",
... |
Builds signs and dispatches a send to address transaction . | def send_to_address ( recipient_address , amount , private_key , blockchain_client = BlockchainInfoClient ( ) , fee = STANDARD_FEE , change_address = None ) : # build and sign the tx signed_tx = make_send_to_address_tx ( recipient_address , amount , private_key , blockchain_client , fee = fee , change_address = change_... | 250,837 | https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/network.py#L139-L151 | [
"def",
"update",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"_md",
".",
"update",
"(",
"data",
")",
"bufpos",
"=",
"self",
".",
"_nbytes",
"&",
"63",
"self",
".",
"_nbytes",
"+=",
"len",
"(",
"data",
")",
"if",
"self",
".",
"_rarbug",
"and"... |
Builds signs and dispatches an OP_RETURN transaction . | def embed_data_in_blockchain ( data , private_key , blockchain_client = BlockchainInfoClient ( ) , fee = OP_RETURN_FEE , change_address = None , format = 'bin' ) : # build and sign the tx signed_tx = make_op_return_tx ( data , private_key , blockchain_client , fee = fee , change_address = change_address , format = form... | 250,838 | https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/network.py#L154-L165 | [
"def",
"describe",
"(",
"self",
")",
":",
"stats",
"=",
"{",
"}",
"stats",
"[",
"'samples'",
"]",
"=",
"self",
".",
"shape",
"[",
"0",
"]",
"stats",
"[",
"'nulls'",
"]",
"=",
"self",
"[",
"np",
".",
"isnan",
"(",
"self",
")",
"]",
".",
"shape",... |
Sign a serialized transaction s unsigned inputs | def sign_all_unsigned_inputs ( hex_privkey , unsigned_tx_hex ) : inputs , outputs , locktime , version = deserialize_transaction ( unsigned_tx_hex ) tx_hex = unsigned_tx_hex for index in xrange ( 0 , len ( inputs ) ) : if len ( inputs [ index ] [ 'script_sig' ] ) == 0 : # tx with index i signed with privkey tx_hex = si... | 250,839 | https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/network.py#L187-L205 | [
"def",
"get_listing",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'listing'",
")",
":",
"allEvents",
"=",
"self",
".",
"get_allEvents",
"(",
")",
"openEvents",
"=",
"allEvents",
".",
"filter",
"(",
"registrationOpen",
"=",
"True",
"... |
takes in a list of binary hashes returns a binary hash | def calculate_merkle_root ( hashes , hash_function = bin_double_sha256 , hex_format = True ) : if hex_format : hashes = hex_to_bin_reversed_hashes ( hashes ) # keep moving up the merkle tree, constructing one row at a time while len ( hashes ) > 1 : hashes = calculate_merkle_pairs ( hashes , hash_function ) # get the m... | 250,840 | https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/merkle.py#L23-L38 | [
"def",
"describe_topic",
"(",
"name",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"topics",
"=",
"list_topics",
"(",
"region",
"=",
"region",
",",
"key",
"=",
"key",
",",
"k... |
Takes in a binary string and converts it to a base 58 check string . | def b58check_encode ( bin_s , version_byte = 0 ) : # append the version byte to the beginning bin_s = chr ( int ( version_byte ) ) + bin_s # calculate the number of leading zeros num_leading_zeros = len ( re . match ( r'^\x00*' , bin_s ) . group ( 0 ) ) # add in the checksum add the end bin_s = bin_s + bin_checksum ( b... | 250,841 | https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/b58check.py#L20-L33 | [
"def",
"session_ended",
"(",
"self",
",",
"f",
")",
":",
"self",
".",
"_session_ended_view_func",
"=",
"f",
"@",
"wraps",
"(",
"f",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"self",
".",
"_flask_view_func",
"(",
"*",
"... |
Builds the outputs for a pay to address transaction . | def make_pay_to_address_outputs ( to_address , send_amount , inputs , change_address , fee = STANDARD_FEE ) : return [ # main output { "script_hex" : make_pay_to_address_script ( to_address ) , "value" : send_amount } , # change output { "script_hex" : make_pay_to_address_script ( change_address ) , "value" : calculate... | 250,842 | https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/outputs.py#L23-L34 | [
"def",
"update",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"_md",
".",
"update",
"(",
"data",
")",
"bufpos",
"=",
"self",
".",
"_nbytes",
"&",
"63",
"self",
".",
"_nbytes",
"+=",
"len",
"(",
"data",
")",
"if",
"self",
".",
"_rarbug",
"and"... |
Builds the outputs for an OP_RETURN transaction . | def make_op_return_outputs ( data , inputs , change_address , fee = OP_RETURN_FEE , send_amount = 0 , format = 'bin' ) : return [ # main output { "script_hex" : make_op_return_script ( data , format = format ) , "value" : send_amount } , # change output { "script_hex" : make_pay_to_address_script ( change_address ) , "... | 250,843 | https://github.com/blockstack/pybitcoin/blob/92c8da63c40f7418594b1ce395990c3f5a4787cc/pybitcoin/transactions/outputs.py#L36-L47 | [
"def",
"add_fluctuations",
"(",
"hdf5_file",
",",
"N_columns",
",",
"N_processes",
")",
":",
"random_state",
"=",
"np",
".",
"random",
".",
"RandomState",
"(",
"0",
")",
"slice_queue",
"=",
"multiprocessing",
".",
"JoinableQueue",
"(",
")",
"pid_list",
"=",
... |
If the value is naive then the timezone is added to it . | def add_timezone ( value , tz = None ) : tz = tz or timezone . get_current_timezone ( ) try : if timezone . is_naive ( value ) : return timezone . make_aware ( value , tz ) except AttributeError : # 'datetime.date' object has no attribute 'tzinfo' dt = datetime . datetime . combine ( value , datetime . time ( ) ) retur... | 250,844 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/utils/__init__.py#L16-L28 | [
"def",
"delete",
"(",
"self",
",",
"story",
",",
"params",
"=",
"{",
"}",
",",
"*",
"*",
"options",
")",
":",
"path",
"=",
"\"/stories/%s\"",
"%",
"(",
"story",
")",
"return",
"self",
".",
"client",
".",
"delete",
"(",
"path",
",",
"params",
",",
... |
Returns the user s currently - active entry or None . | def get_active_entry ( user , select_for_update = False ) : entries = apps . get_model ( 'entries' , 'Entry' ) . no_join if select_for_update : entries = entries . select_for_update ( ) entries = entries . filter ( user = user , end_time__isnull = True ) if not entries . exists ( ) : return None if entries . count ( ) ... | 250,845 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/utils/__init__.py#L31-L42 | [
"def",
"get",
"(",
"code",
")",
":",
"instance",
"=",
"_cache",
".",
"get",
"(",
"code",
")",
"if",
"instance",
"is",
"None",
":",
"url",
"=",
"'{prefix}{code}.gml?download'",
".",
"format",
"(",
"prefix",
"=",
"EPSG_IO_URL",
",",
"code",
"=",
"code",
... |
Returns the first day of the given month . | def get_month_start ( day = None ) : day = add_timezone ( day or datetime . date . today ( ) ) return day . replace ( day = 1 ) | 250,846 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/utils/__init__.py#L64-L67 | [
"def",
"server_close",
"(",
"self",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"\"Closing the socket server connection.\"",
")",
"TCPServer",
".",
"server_close",
"(",
"self",
")",
"self",
".",
"queue_manager",
".",
"close",
"(",
")",
"self",
".",
"top... |
Returns the user - defined value for the setting or a default value . | def get_setting ( name , * * kwargs ) : if hasattr ( settings , name ) : # Try user-defined settings first. return getattr ( settings , name ) if 'default' in kwargs : # Fall back to a specified default value. return kwargs [ 'default' ] if hasattr ( defaults , name ) : # If that's not given, look in defaults file. ret... | 250,847 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/utils/__init__.py#L73-L82 | [
"def",
"disassociate_api_key_stagekeys",
"(",
"apiKey",
",",
"stagekeyslist",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"try",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",... |
Returns the Monday of the given week . | def get_week_start ( day = None ) : day = add_timezone ( day or datetime . date . today ( ) ) days_since_monday = day . weekday ( ) if days_since_monday != 0 : day = day - relativedelta ( days = days_since_monday ) return day | 250,848 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/utils/__init__.py#L85-L91 | [
"def",
"get_connection_details",
"(",
"session",
",",
"vcenter_resource_model",
",",
"resource_context",
")",
":",
"session",
"=",
"session",
"resource_context",
"=",
"resource_context",
"# get vCenter connection details from vCenter resource",
"user",
"=",
"vcenter_resource_mo... |
Returns January 1 of the given year . | def get_year_start ( day = None ) : day = add_timezone ( day or datetime . date . today ( ) ) return day . replace ( month = 1 ) . replace ( day = 1 ) | 250,849 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/utils/__init__.py#L94-L97 | [
"def",
"stop",
"(",
"self",
")",
":",
"self",
".",
"_hw_virtualization",
"=",
"False",
"yield",
"from",
"self",
".",
"_stop_ubridge",
"(",
")",
"yield",
"from",
"self",
".",
"_stop_remote_console",
"(",
")",
"vm_state",
"=",
"yield",
"from",
"self",
".",
... |
Transforms a date or datetime object into a date object . | def to_datetime ( date ) : return datetime . datetime ( date . year , date . month , date . day ) | 250,850 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/utils/__init__.py#L100-L102 | [
"def",
"_unregister_bundle_factories",
"(",
"self",
",",
"bundle",
")",
":",
"# type: (Bundle) -> None",
"with",
"self",
".",
"__factories_lock",
":",
"# Find out which factories must be removed",
"to_remove",
"=",
"[",
"factory_name",
"for",
"factory_name",
"in",
"self",... |
Idea from Software Estimation Demystifying the Black Art McConnel 2006 Fig 3 - 3 . | def report_estimation_accuracy ( request ) : contracts = ProjectContract . objects . filter ( status = ProjectContract . STATUS_COMPLETE , type = ProjectContract . PROJECT_FIXED ) data = [ ( 'Target (hrs)' , 'Actual (hrs)' , 'Point Label' ) ] for c in contracts : if c . contracted_hours ( ) == 0 : continue pt_label = "... | 250,851 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/reports/views.py#L468-L487 | [
"def",
"_wait_and_except_if_failed",
"(",
"self",
",",
"event",
",",
"timeout",
"=",
"None",
")",
":",
"event",
".",
"wait",
"(",
"timeout",
"or",
"self",
".",
"__sync_timeout",
")",
"self",
".",
"_except_if_failed",
"(",
"event",
")"
] |
Processes form data to get relevant entries & date_headers . | def get_context_data ( self , * * kwargs ) : context = super ( ReportMixin , self ) . get_context_data ( * * kwargs ) form = self . get_form ( ) if form . is_valid ( ) : data = form . cleaned_data start , end = form . save ( ) entryQ = self . get_entry_query ( start , end , data ) trunc = data [ 'trunc' ] if entryQ : v... | 250,852 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/reports/views.py#L36-L74 | [
"def",
"cancel_order",
"(",
"self",
",",
"order_id",
",",
"stock",
")",
":",
"url_fragment",
"=",
"'venues/{venue}/stocks/{stock}/orders/{order_id}'",
".",
"format",
"(",
"venue",
"=",
"self",
".",
"venue",
",",
"stock",
"=",
"stock",
",",
"order_id",
"=",
"or... |
Builds Entry query from form data . | def get_entry_query ( self , start , end , data ) : # Entry types. incl_billable = data . get ( 'billable' , True ) incl_nonbillable = data . get ( 'non_billable' , True ) incl_leave = data . get ( 'paid_leave' , True ) # If no types are selected, shortcut & return nothing. if not any ( ( incl_billable , incl_nonbillab... | 250,853 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/reports/views.py#L76-L121 | [
"def",
"translateprotocolheader",
"(",
"protocol",
")",
":",
"pcscprotocol",
"=",
"0",
"if",
"None",
"!=",
"protocol",
":",
"if",
"CardConnection",
".",
"T0_protocol",
"==",
"protocol",
":",
"pcscprotocol",
"=",
"SCARD_PCI_T0",
"if",
"CardConnection",
".",
"T1_p... |
Adjust date headers & get range headers . | def get_headers ( self , date_headers , from_date , to_date , trunc ) : date_headers = list ( date_headers ) # Earliest date should be no earlier than from_date. if date_headers and date_headers [ 0 ] < from_date : date_headers [ 0 ] = from_date # When organizing by week or month, create a list of the range for # each ... | 250,854 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/reports/views.py#L123-L142 | [
"def",
"delete_vm",
"(",
"name",
",",
"datacenter",
",",
"placement",
"=",
"None",
",",
"power_off",
"=",
"False",
",",
"service_instance",
"=",
"None",
")",
":",
"results",
"=",
"{",
"}",
"schema",
"=",
"ESXVirtualMachineDeleteSchema",
".",
"serialize",
"("... |
Returns date range for the previous full month . | def get_previous_month ( self ) : end = utils . get_month_start ( ) - relativedelta ( days = 1 ) end = utils . to_datetime ( end ) start = utils . get_month_start ( end ) return start , end | 250,855 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/reports/views.py#L144-L149 | [
"def",
"_unbind_topics",
"(",
"self",
",",
"topics",
")",
":",
"self",
".",
"client",
".",
"unsubscribe",
"(",
"topics",
".",
"status",
")",
"self",
".",
"client",
".",
"unsubscribe",
"(",
"topics",
".",
"tracing",
")",
"self",
".",
"client",
".",
"uns... |
Convert the context dictionary into a CSV file . | def convert_context_to_csv ( self , context ) : content = [ ] date_headers = context [ 'date_headers' ] headers = [ 'Name' ] headers . extend ( [ date . strftime ( '%m/%d/%Y' ) for date in date_headers ] ) headers . append ( 'Total' ) content . append ( headers ) summaries = context [ 'summaries' ] summary = summaries ... | 250,856 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/reports/views.py#L155-L177 | [
"def",
"get_entity_info",
"(",
"pdb_id",
")",
":",
"out",
"=",
"get_info",
"(",
"pdb_id",
",",
"url_root",
"=",
"'http://www.rcsb.org/pdb/rest/getEntityInfo?structureId='",
")",
"out",
"=",
"to_dict",
"(",
"out",
")",
"return",
"remove_at_sign",
"(",
"out",
"[",
... |
Default filter form data when no GET data is provided . | def defaults ( self ) : # Set default date span to previous week. ( start , end ) = get_week_window ( timezone . now ( ) - relativedelta ( days = 7 ) ) return { 'from_date' : start , 'to_date' : end , 'billable' : True , 'non_billable' : False , 'paid_leave' : False , 'trunc' : 'day' , 'projects' : [ ] , } | 250,857 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/reports/views.py#L180-L192 | [
"def",
"rewrite_file",
"(",
"self",
")",
"->",
"None",
":",
"if",
"not",
"self",
".",
"needs_rewriting",
":",
"return",
"self",
".",
"_info",
"(",
"\"Rewriting file\"",
")",
"with",
"open",
"(",
"self",
".",
"full_path",
",",
"\"w\"",
")",
"as",
"outfile... |
Sum billable and non - billable hours across all users . | def get_hours_data ( self , entries , date_headers ) : project_totals = get_project_totals ( entries , date_headers , total_column = False ) if entries else [ ] data_map = { } for rows , totals in project_totals : for user , user_id , periods in rows : for period in periods : day = period [ 'day' ] if day not in data_m... | 250,858 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/reports/views.py#L314-L329 | [
"def",
"_map_seqprop_resnums_to_structprop_chain_index",
"(",
"self",
",",
"resnums",
",",
"seqprop",
"=",
"None",
",",
"structprop",
"=",
"None",
",",
"chain_id",
"=",
"None",
",",
"use_representatives",
"=",
"False",
")",
":",
"resnums",
"=",
"ssbio",
".",
"... |
Appends URL - encoded parameters to the base URL . It appends after & if ? is found in the URL ; otherwise it appends using ? . Keep in mind that this tag does not take into account the value of existing params ; it is therefore possible to add another value for a pre - existing parameter . | def add_parameters ( url , parameters ) : if parameters : sep = '&' if '?' in url else '?' return '{0}{1}{2}' . format ( url , sep , urlencode ( parameters ) ) return url | 250,859 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/templatetags/timepiece_tags.py#L22-L41 | [
"def",
"decode_list_offset_response",
"(",
"cls",
",",
"response",
")",
":",
"return",
"[",
"kafka",
".",
"structs",
".",
"ListOffsetResponsePayload",
"(",
"topic",
",",
"partition",
",",
"error",
",",
"timestamp",
",",
"offset",
")",
"for",
"topic",
",",
"p... |
Return the largest number of hours worked or assigned on any project . | def get_max_hours ( context ) : progress = context [ 'project_progress' ] return max ( [ 0 ] + [ max ( p [ 'worked' ] , p [ 'assigned' ] ) for p in progress ] ) | 250,860 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/templatetags/timepiece_tags.py#L109-L112 | [
"def",
"_create_download_failed_message",
"(",
"exception",
",",
"url",
")",
":",
"message",
"=",
"'Failed to download from:\\n{}\\nwith {}:\\n{}'",
".",
"format",
"(",
"url",
",",
"exception",
".",
"__class__",
".",
"__name__",
",",
"exception",
")",
"if",
"_is_tem... |
Given an iterable of entries return the total hours that have not been invoiced . If billable is passed as billable or nonbillable limit to the corresponding entries . | def get_uninvoiced_hours ( entries , billable = None ) : statuses = ( 'invoiced' , 'not-invoiced' ) if billable is not None : billable = ( billable . lower ( ) == u'billable' ) entries = [ e for e in entries if e . activity . billable == billable ] hours = sum ( [ e . hours for e in entries if e . status not in statuse... | 250,861 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/templatetags/timepiece_tags.py#L116-L126 | [
"def",
"mock_xray_client",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"_wrapped",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"print",
"(",
"\"Starting X-Ray Patch\"",
")",
"old_xray_context_var",
"=",
"os",
".",
"environ",
".",
"... |
Given time in hours return a string representing the time . | def humanize_hours ( total_hours , frmt = '{hours:02d}:{minutes:02d}:{seconds:02d}' , negative_frmt = None ) : seconds = int ( float ( total_hours ) * 3600 ) return humanize_seconds ( seconds , frmt , negative_frmt ) | 250,862 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/templatetags/timepiece_tags.py#L130-L134 | [
"def",
"unbind",
"(",
"self",
",",
"devices_to_unbind",
")",
":",
"if",
"self",
".",
"entity_api_key",
"==",
"\"\"",
":",
"return",
"{",
"'status'",
":",
"'failure'",
",",
"'response'",
":",
"'No API key found in request'",
"}",
"url",
"=",
"self",
".",
"bas... |
Utility to create a time sheet URL with optional date parameters . | def _timesheet_url ( url_name , pk , date = None ) : url = reverse ( url_name , args = ( pk , ) ) if date : params = { 'month' : date . month , 'year' : date . year } return '?' . join ( ( url , urlencode ( params ) ) ) return url | 250,863 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/templatetags/timepiece_tags.py#L222-L228 | [
"def",
"on_augassign",
"(",
"self",
",",
"node",
")",
":",
"# ('target', 'op', 'value')",
"return",
"self",
".",
"on_assign",
"(",
"ast",
".",
"Assign",
"(",
"targets",
"=",
"[",
"node",
".",
"target",
"]",
",",
"value",
"=",
"ast",
".",
"BinOp",
"(",
... |
This allows admins to reject all entries instead of just one | def reject_user_timesheet ( request , user_id ) : form = YearMonthForm ( request . GET or request . POST ) user = User . objects . get ( pk = user_id ) if form . is_valid ( ) : from_date , to_date = form . save ( ) entries = Entry . no_join . filter ( status = Entry . VERIFIED , user = user , start_time__gte = from_dat... | 250,864 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/crm/views.py#L47-L77 | [
"def",
"elapsed",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"started",
"or",
"self",
".",
"_start_time",
"is",
"None",
":",
"return",
"0.0",
"return",
"self",
".",
"_timing_data",
"[",
"-",
"1",
"]",
"[",
"0",
"]",
"-",
"self",
".",
"_start_... |
Returns whether the line is a valid package requirement . | def _is_requirement ( line ) : line = line . strip ( ) return line and not ( line . startswith ( "-r" ) or line . startswith ( "#" ) ) | 250,865 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/setup.py#L4-L7 | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"created",
"is",
"None",
":",
"self",
".",
"created",
"=",
"tz_now",
"(",
")",
"if",
"self",
".",
"modified",
"is",
"None",
":",
"self",
".",
"m... |
When the user makes a search and there is only one result redirect to the result s detail page rather than rendering the list . | def render_to_response ( self , context ) : if self . redirect_if_one_result : if self . object_list . count ( ) == 1 and self . form . is_bound : return redirect ( self . object_list . get ( ) . get_absolute_url ( ) ) return super ( SearchMixin , self ) . render_to_response ( context ) | 250,866 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/utils/search.py#L61-L69 | [
"def",
"_CompressHistogram",
"(",
"self",
",",
"histo_ev",
")",
":",
"return",
"CompressedHistogramEvent",
"(",
"histo_ev",
".",
"wall_time",
",",
"histo_ev",
".",
"step",
",",
"compressor",
".",
"compress_histogram_proto",
"(",
"histo_ev",
".",
"histogram_value",
... |
Make sure that the start time doesn t come before the active entry | def clean_start_time ( self ) : start = self . cleaned_data . get ( 'start_time' ) if not start : return start active_entries = self . user . timepiece_entries . filter ( start_time__gte = start , end_time__isnull = True ) for entry in active_entries : output = ( 'The start time is on or before the current entry: ' '%s... | 250,867 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/entries/forms.py#L64-L78 | [
"def",
"to_decimal",
"(",
"number",
",",
"strip",
"=",
"'- '",
")",
":",
"if",
"isinstance",
"(",
"number",
",",
"six",
".",
"integer_types",
")",
":",
"return",
"str",
"(",
"number",
")",
"number",
"=",
"str",
"(",
"number",
")",
"number",
"=",
"re"... |
If we re not editing the active entry ensure that this entry doesn t conflict with or come after the active entry . | def clean ( self ) : active = utils . get_active_entry ( self . user ) start_time = self . cleaned_data . get ( 'start_time' , None ) end_time = self . cleaned_data . get ( 'end_time' , None ) if active and active . pk != self . instance . pk : if ( start_time and start_time > active . start_time ) or ( end_time and en... | 250,868 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/entries/forms.py#L145-L181 | [
"def",
"get_namespace",
"(",
"self",
",",
"namespace",
":",
"str",
",",
"lowercase",
":",
"bool",
"=",
"True",
",",
"trim_namespace",
":",
"bool",
"=",
"True",
",",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"config",
"=",
"{",
"}",
"for"... |
For clocking the user into a project . | def clock_in ( request ) : user = request . user # Lock the active entry for the duration of this transaction, to prevent # creating multiple active entries. active_entry = utils . get_active_entry ( user , select_for_update = True ) initial = dict ( [ ( k , v ) for k , v in request . GET . items ( ) ] ) data = request... | 250,869 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/entries/views.py#L139-L159 | [
"def",
"GetAttachmentIdFromMediaId",
"(",
"media_id",
")",
":",
"altchars",
"=",
"'+-'",
"if",
"not",
"six",
".",
"PY2",
":",
"altchars",
"=",
"altchars",
".",
"encode",
"(",
"'utf-8'",
")",
"# altchars for '+' and '/'. We keep '+' but replace '/' with '-'",
"buffer",... |
Allow the user to pause and unpause the active entry . | def toggle_pause ( request ) : entry = utils . get_active_entry ( request . user ) if not entry : raise Http404 # toggle the paused state entry . toggle_paused ( ) entry . save ( ) # create a message that can be displayed to the user action = 'paused' if entry . is_paused else 'resumed' message = 'Your entry, {0} on {1... | 250,870 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/entries/views.py#L189-L206 | [
"def",
"reconcile",
"(",
"constraint",
")",
":",
"if",
"isinstance",
"(",
"constraint",
".",
"subtype",
",",
"NamedType",
")",
":",
"if",
"isinstance",
"(",
"constraint",
".",
"supertype",
",",
"NamedType",
")",
":",
"if",
"constraint",
".",
"subtype",
"."... |
Admins can reject an entry that has been verified or approved but not invoiced to set its status to unverified for the user to fix . | def reject_entry ( request , entry_id ) : return_url = request . GET . get ( 'next' , reverse ( 'dashboard' ) ) try : entry = Entry . no_join . get ( pk = entry_id ) except : message = 'No such log entry.' messages . error ( request , message ) return redirect ( return_url ) if entry . status == Entry . UNVERIFIED or e... | 250,871 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/entries/views.py#L255-L282 | [
"def",
"construct_error_message",
"(",
"driver_id",
",",
"error_type",
",",
"message",
",",
"timestamp",
")",
":",
"builder",
"=",
"flatbuffers",
".",
"Builder",
"(",
"0",
")",
"driver_offset",
"=",
"builder",
".",
"CreateString",
"(",
"driver_id",
".",
"binar... |
Give the user the ability to delete a log entry with a confirmation beforehand . If this method is invoked via a GET request a form asking for a confirmation of intent will be presented to the user . If this method is invoked via a POST request the entry will be deleted . | def delete_entry ( request , entry_id ) : try : entry = Entry . no_join . get ( pk = entry_id , user = request . user ) except Entry . DoesNotExist : message = 'No such entry found.' messages . info ( request , message ) url = request . GET . get ( 'next' , reverse ( 'dashboard' ) ) return HttpResponseRedirect ( url ) ... | 250,872 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/entries/views.py#L286-L315 | [
"def",
"update",
"(",
"self",
",",
"other",
")",
":",
"self",
".",
"update_ttl",
"(",
"other",
".",
"ttl",
")",
"super",
"(",
"Rdataset",
",",
"self",
")",
".",
"update",
"(",
"other",
")"
] |
Retrieves the number of hours the user should work per week . | def get_hours_per_week ( self , user = None ) : try : profile = UserProfile . objects . get ( user = user or self . user ) except UserProfile . DoesNotExist : profile = None return profile . hours_per_week if profile else Decimal ( '40.00' ) | 250,873 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/entries/views.py#L57-L63 | [
"def",
"convert_complexFaultSource",
"(",
"self",
",",
"node",
")",
":",
"geom",
"=",
"node",
".",
"complexFaultGeometry",
"edges",
"=",
"self",
".",
"geo_lines",
"(",
"geom",
")",
"mfd",
"=",
"self",
".",
"convert_mfdist",
"(",
"node",
")",
"msr",
"=",
... |
Gets all ProjectHours entries in the 7 - day period beginning on week_start . | def get_hours_for_week ( self , week_start = None ) : week_start = week_start if week_start else self . week_start week_end = week_start + relativedelta ( days = 7 ) return ProjectHours . objects . filter ( week_start__gte = week_start , week_start__lt = week_end ) | 250,874 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/entries/views.py#L336-L345 | [
"def",
"run_fn_atomically",
"(",
"self",
",",
"request",
")",
":",
"fn",
"=",
"serializer",
".",
"loads_fn",
"(",
"request",
"[",
"Msgs",
".",
"info",
"]",
")",
"args",
",",
"kwargs",
"=",
"request",
"[",
"Msgs",
".",
"args",
"]",
",",
"request",
"["... |
Gets a list of the distinct users included in the project hours entries ordered by name . | def get_users_from_project_hours ( self , project_hours ) : name = ( 'user__first_name' , 'user__last_name' ) users = project_hours . values_list ( 'user__id' , * name ) . distinct ( ) . order_by ( * name ) return users | 250,875 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/entries/views.py#L357-L365 | [
"def",
"mount",
"(",
"self",
",",
"volume",
")",
":",
"# we have to make a ram-device to store the image, we keep 20% overhead",
"size_in_kb",
"=",
"int",
"(",
"(",
"volume",
".",
"size",
"/",
"1024",
")",
"*",
"1.2",
")",
"_util",
".",
"check_call_",
"(",
"[",
... |
Go through lists of entries find overlaps among each return the total | def check_all ( self , all_entries , * args , * * kwargs ) : all_overlaps = 0 while True : try : user_entries = all_entries . next ( ) except StopIteration : return all_overlaps else : user_total_overlaps = self . check_entry ( user_entries , * args , * * kwargs ) all_overlaps += user_total_overlaps | 250,876 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/management/commands/check_entries.py#L69-L82 | [
"def",
"setup_sighandlers",
"(",
"self",
")",
":",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGINT",
",",
"signal",
".",
"SIG_IGN",
")",
"signal",
".",
"signal",
"(",
"signal",
".",
"SIGTERM",
",",
"signal",
".",
"SIG_IGN",
")",
"signal",
".",
"si... |
With a list of entries check each entry against every other | def check_entry ( self , entries , * args , * * kwargs ) : verbosity = kwargs . get ( 'verbosity' , 1 ) user_total_overlaps = 0 user = '' for index_a , entry_a in enumerate ( entries ) : # Show the name the first time through if index_a == 0 : if args and verbosity >= 1 or verbosity >= 2 : self . show_name ( entry_a . ... | 250,877 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/management/commands/check_entries.py#L84-L110 | [
"def",
"FromData",
"(",
"cls",
",",
"stream",
",",
"json_data",
",",
"http",
",",
"auto_transfer",
"=",
"None",
",",
"gzip_encoded",
"=",
"False",
",",
"*",
"*",
"kwds",
")",
":",
"info",
"=",
"json",
".",
"loads",
"(",
"json_data",
")",
"missing_keys"... |
Determine the starting point of the query using CLI keyword arguments | def find_start ( self , * * kwargs ) : week = kwargs . get ( 'week' , False ) month = kwargs . get ( 'month' , False ) year = kwargs . get ( 'year' , False ) days = kwargs . get ( 'days' , 0 ) # If no flags are True, set to the beginning of last billing window # to assure we catch all recent violations start = timezone... | 250,878 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/management/commands/check_entries.py#L112-L133 | [
"def",
"find_mismatch",
"(",
"self",
",",
"other",
",",
"indent",
"=",
"''",
")",
":",
"if",
"self",
"!=",
"other",
":",
"mismatch",
"=",
"\"\\n{}{}\"",
".",
"format",
"(",
"indent",
",",
"type",
"(",
"self",
")",
".",
"__name__",
")",
"else",
":",
... |
Returns the users to search given names as args . Return all users if there are no args provided . | def find_users ( self , * args ) : if args : names = reduce ( lambda query , arg : query | ( Q ( first_name__icontains = arg ) | Q ( last_name__icontains = arg ) ) , args , Q ( ) ) # noqa users = User . objects . filter ( names ) # If no args given, check every user else : users = User . objects . all ( ) # Display err... | 250,879 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/management/commands/check_entries.py#L135-L155 | [
"def",
"readKerningElement",
"(",
"self",
",",
"kerningElement",
",",
"instanceObject",
")",
":",
"kerningLocation",
"=",
"self",
".",
"locationFromElement",
"(",
"kerningElement",
")",
"instanceObject",
".",
"addKerning",
"(",
"kerningLocation",
")"
] |
Find all entries for all users from a given starting point . If no starting point is provided all entries are returned . | def find_entries ( self , users , start , * args , * * kwargs ) : forever = kwargs . get ( 'all' , False ) for user in users : if forever : entries = Entry . objects . filter ( user = user ) . order_by ( 'start_time' ) else : entries = Entry . objects . filter ( user = user , start_time__gte = start ) . order_by ( 'sta... | 250,880 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/management/commands/check_entries.py#L157-L170 | [
"def",
"_prep_cnv_file",
"(",
"in_file",
",",
"work_dir",
",",
"somatic_info",
")",
":",
"out_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"work_dir",
",",
"\"%s-prep%s\"",
"%",
"utils",
".",
"splitext_plus",
"(",
"os",
".",
"path",
".",
"basename",
... |
Allows a function - based decorator to be used on a CBV . | def cbv_decorator ( function_decorator ) : def class_decorator ( View ) : View . dispatch = method_decorator ( function_decorator ) ( View . dispatch ) return View return class_decorator | 250,881 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/utils/views.py#L4-L10 | [
"def",
"set_trial_config",
"(",
"experiment_config",
",",
"port",
",",
"config_file_name",
")",
":",
"request_data",
"=",
"dict",
"(",
")",
"request_data",
"[",
"'trial_config'",
"]",
"=",
"experiment_config",
"[",
"'trial'",
"]",
"response",
"=",
"rest_put",
"(... |
Yield a user s name and a dictionary of their hours | def date_totals ( entries , by ) : date_dict = { } for date , date_entries in groupby ( entries , lambda x : x [ 'date' ] ) : if isinstance ( date , datetime . datetime ) : date = date . date ( ) d_entries = list ( date_entries ) if by == 'user' : name = ' ' . join ( ( d_entries [ 0 ] [ 'user__first_name' ] , d_entries... | 250,882 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/reports/utils.py#L12-L31 | [
"def",
"get_torrent",
"(",
"self",
",",
"torrent_id",
")",
":",
"params",
"=",
"{",
"'page'",
":",
"'download'",
",",
"'tid'",
":",
"torrent_id",
",",
"}",
"r",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"base_url",
",",
"params",
"=",
"params",
... |
Yield hour totals grouped by user and date . Optionally including overtime . | def get_project_totals ( entries , date_headers , hour_type = None , overtime = False , total_column = False , by = 'user' ) : totals = [ 0 for date in date_headers ] rows = [ ] for thing , thing_entries in groupby ( entries , lambda x : x [ by ] ) : name , thing_id , date_dict = date_totals ( thing_entries , by ) date... | 250,883 | https://github.com/caktus/django-timepiece/blob/52515dec027664890efbc535429e1ba1ee152f40/timepiece/reports/utils.py#L57-L93 | [
"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",
",",
")",
... |
Evaluate this model on validation_instances during training and output a report . | def validate ( self , validation_instances , metrics , iteration = None ) : if not validation_instances or not metrics : return { } split_id = 'val%s' % iteration if iteration is not None else 'val' train_results = evaluate . evaluate ( self , validation_instances , metrics = metrics , split_id = split_id ) output . ou... | 250,884 | https://github.com/stanfordnlp/stanza/blob/920c55d8eaa1e7105971059c66eb448a74c100d6/stanza/research/learner.py#L34-L55 | [
"def",
"_get_site_amplification_term",
"(",
"self",
",",
"C",
",",
"vs30",
")",
":",
"s_b",
",",
"s_c",
",",
"s_d",
"=",
"self",
".",
"_get_site_dummy_variables",
"(",
"vs30",
")",
"return",
"(",
"C",
"[",
"\"sB\"",
"]",
"*",
"s_b",
")",
"+",
"(",
"C... |
Return most likely outputs and scores for the particular set of outputs given in eval_instances as a tuple . Return value should be equivalent to the default implementation of | def predict_and_score ( self , eval_instances , random = False , verbosity = 0 ) : if hasattr ( self , '_using_default_separate' ) and self . _using_default_separate : raise NotImplementedError self . _using_default_combined = True return ( self . predict ( eval_instances , random = random , verbosity = verbosity ) , s... | 250,885 | https://github.com/stanfordnlp/stanza/blob/920c55d8eaa1e7105971059c66eb448a74c100d6/stanza/research/learner.py#L104-L135 | [
"def",
"dead_chips",
"(",
"self",
")",
":",
"for",
"x",
"in",
"range",
"(",
"self",
".",
"width",
")",
":",
"for",
"y",
"in",
"range",
"(",
"self",
".",
"height",
")",
":",
"if",
"(",
"x",
",",
"y",
")",
"not",
"in",
"self",
":",
"yield",
"("... |
Deserialize a model from a stored file . | def load ( self , infile ) : model = pickle . load ( infile ) self . __dict__ . update ( model . __dict__ ) | 250,886 | https://github.com/stanfordnlp/stanza/blob/920c55d8eaa1e7105971059c66eb448a74c100d6/stanza/research/learner.py#L153-L164 | [
"def",
"add_bonds",
"(",
"self",
",",
"neighbors",
",",
"center",
",",
"color",
"=",
"None",
",",
"opacity",
"=",
"None",
",",
"radius",
"=",
"0.1",
")",
":",
"points",
"=",
"vtk",
".",
"vtkPoints",
"(",
")",
"points",
".",
"InsertPoint",
"(",
"0",
... |
Given a sequence or iterable yield batches from that iterable until it runs out . Note that this function returns a generator and also each batch will be a generator . | def iter_batches ( iterable , batch_size ) : # http://stackoverflow.com/a/8290514/4481448 sourceiter = iter ( iterable ) while True : batchiter = islice ( sourceiter , batch_size ) yield chain ( [ batchiter . next ( ) ] , batchiter ) | 250,887 | https://github.com/stanfordnlp/stanza/blob/920c55d8eaa1e7105971059c66eb448a74c100d6/stanza/research/iterators.py#L4-L44 | [
"def",
"checkIsConsistent",
"(",
"self",
")",
":",
"if",
"is_an_array",
"(",
"self",
".",
"mask",
")",
"and",
"self",
".",
"mask",
".",
"shape",
"!=",
"self",
".",
"data",
".",
"shape",
":",
"raise",
"ConsistencyError",
"(",
"\"Shape mismatch mask={}, data={... |
Returns a generator object that yields batches from iterable . See iter_batches for more details and caveats . | def gen_batches ( iterable , batch_size ) : def batches_thunk ( ) : return iter_batches ( iterable , batch_size ) try : length = len ( iterable ) except TypeError : return batches_thunk ( ) num_batches = ( length - 1 ) // batch_size + 1 return SizedGenerator ( batches_thunk , length = num_batches ) | 250,888 | https://github.com/stanfordnlp/stanza/blob/920c55d8eaa1e7105971059c66eb448a74c100d6/stanza/research/iterators.py#L47-L76 | [
"def",
"setNetworkDataRequirement",
"(",
"self",
",",
"eDataRequirement",
")",
":",
"print",
"'%s call setNetworkDataRequirement'",
"%",
"self",
".",
"port",
"print",
"eDataRequirement",
"if",
"eDataRequirement",
"==",
"Device_Data_Requirement",
".",
"ALL_DATA",
":",
"s... |
Return a version of this instance with inputs replaced by outputs and vice versa . | def inverted ( self ) : return Instance ( input = self . output , output = self . input , annotated_input = self . annotated_output , annotated_output = self . annotated_input , alt_inputs = self . alt_outputs , alt_outputs = self . alt_inputs , source = self . source ) | 250,889 | https://github.com/stanfordnlp/stanza/blob/920c55d8eaa1e7105971059c66eb448a74c100d6/stanza/research/instance.py#L36-L45 | [
"def",
"not_storable",
"(",
"_type",
")",
":",
"return",
"Storable",
"(",
"_type",
",",
"handlers",
"=",
"StorableHandler",
"(",
"poke",
"=",
"fake_poke",
",",
"peek",
"=",
"fail_peek",
"(",
"_type",
")",
")",
")"
] |
Returns the data . if the data hasn t been downloaded then first download the data . | def get_data_or_download ( dir_name , file_name , url = '' , size = 'unknown' ) : dname = os . path . join ( stanza . DATA_DIR , dir_name ) fname = os . path . join ( dname , file_name ) if not os . path . isdir ( dname ) : assert url , 'Could not locate data {}, and url was not specified. Cannot retrieve data.' . form... | 250,890 | https://github.com/stanfordnlp/stanza/blob/920c55d8eaa1e7105971059c66eb448a74c100d6/stanza/util/resource.py#L16-L35 | [
"def",
"wrapping",
"(",
"self",
")",
":",
"value",
"=",
"self",
".",
"_wrapping",
"return",
"value",
"[",
"0",
"]",
"if",
"all",
"(",
"[",
"v",
"==",
"value",
"[",
"0",
"]",
"for",
"v",
"in",
"value",
"]",
")",
"else",
"value"
] |
Add a word to the vocabulary and return its index . | def add ( self , word , count = 1 ) : if word not in self : super ( Vocab , self ) . __setitem__ ( word , len ( self ) ) self . _counts [ word ] += count return self [ word ] | 250,891 | https://github.com/stanfordnlp/stanza/blob/920c55d8eaa1e7105971059c66eb448a74c100d6/stanza/text/vocab.py#L93-L108 | [
"def",
"_process_data",
"(",
"self",
",",
"*",
"*",
"data",
")",
"->",
"dict",
":",
"env_prefix",
"=",
"data",
".",
"pop",
"(",
"\"env_prefix\"",
",",
"None",
")",
"environs",
"=",
"self",
".",
"_get_environs",
"(",
"env_prefix",
")",
"if",
"environs",
... |
Get a new Vocab containing only the specified subset of words . | def subset ( self , words ) : v = self . __class__ ( unk = self . _unk ) unique = lambda seq : len ( set ( seq ) ) == len ( seq ) assert unique ( words ) for w in words : if w in self : v . add ( w , count = self . count ( w ) ) return v | 250,892 | https://github.com/stanfordnlp/stanza/blob/920c55d8eaa1e7105971059c66eb448a74c100d6/stanza/text/vocab.py#L136-L150 | [
"def",
"cli",
"(",
"sock",
",",
"configs",
",",
"modules",
",",
"files",
",",
"log",
",",
"debug",
")",
":",
"setup_logging",
"(",
"log",
",",
"debug",
")",
"config",
"=",
"join_configs",
"(",
"configs",
")",
"# load python modules",
"load_modules",
"(",
... |
Mapping from indices to words . | def _index2word ( self ) : # TODO(kelvinguu): it would be nice to just use `dict.viewkeys`, but unfortunately those are not indexable compute_index2word = lambda : self . keys ( ) # this works because self is an OrderedDict # create if it doesn't exist try : self . _index2word_cache except AttributeError : self . _inde... | 250,893 | https://github.com/stanfordnlp/stanza/blob/920c55d8eaa1e7105971059c66eb448a74c100d6/stanza/text/vocab.py#L153-L174 | [
"def",
"_process_data",
"(",
"self",
",",
"*",
"*",
"data",
")",
"->",
"dict",
":",
"env_prefix",
"=",
"data",
".",
"pop",
"(",
"\"env_prefix\"",
",",
"None",
")",
"environs",
"=",
"self",
".",
"_get_environs",
"(",
"env_prefix",
")",
"if",
"environs",
... |
Create Vocab from an existing string to integer dictionary . | def from_dict ( cls , word2index , unk , counts = None ) : try : if word2index [ unk ] != 0 : raise ValueError ( 'unk must be assigned index 0' ) except KeyError : raise ValueError ( 'word2index must have an entry for unk.' ) # check that word2index is a bijection vals = set ( word2index . values ( ) ) # unique indices... | 250,894 | https://github.com/stanfordnlp/stanza/blob/920c55d8eaa1e7105971059c66eb448a74c100d6/stanza/text/vocab.py#L205-L246 | [
"def",
"_get_max_sigma",
"(",
"self",
",",
"R",
")",
":",
"max_sigma",
"=",
"2.0",
"*",
"math",
".",
"pow",
"(",
"np",
".",
"nanmax",
"(",
"np",
".",
"std",
"(",
"R",
",",
"axis",
"=",
"0",
")",
")",
",",
"2",
")",
"return",
"max_sigma"
] |
Write vocab to a file . | def to_file ( self , f ) : for word in self . _index2word : count = self . _counts [ word ] f . write ( u'{}\t{}\n' . format ( word , count ) . encode ( 'utf-8' ) ) | 250,895 | https://github.com/stanfordnlp/stanza/blob/920c55d8eaa1e7105971059c66eb448a74c100d6/stanza/text/vocab.py#L248-L262 | [
"def",
"AND",
"(",
"queryArr",
",",
"exclude",
"=",
"None",
")",
":",
"assert",
"isinstance",
"(",
"queryArr",
",",
"list",
")",
",",
"\"provided argument as not a list\"",
"assert",
"len",
"(",
"queryArr",
")",
">",
"0",
",",
"\"queryArr had an empty list\"",
... |
Backfills an embedding matrix with the embedding for the unknown token . | def backfill_unk_emb ( self , E , filled_words ) : unk_emb = E [ self [ self . _unk ] ] for i , word in enumerate ( self ) : if word not in filled_words : E [ i ] = unk_emb | 250,896 | https://github.com/stanfordnlp/stanza/blob/920c55d8eaa1e7105971059c66eb448a74c100d6/stanza/text/vocab.py#L304-L315 | [
"def",
"color_lerp",
"(",
"c1",
":",
"Tuple",
"[",
"int",
",",
"int",
",",
"int",
"]",
",",
"c2",
":",
"Tuple",
"[",
"int",
",",
"int",
",",
"int",
"]",
",",
"a",
":",
"float",
")",
"->",
"Color",
":",
"return",
"Color",
".",
"_new_from_cdata",
... |
Return the name of a device to use either cpu or gpu0 gpu1 ... The least - used GPU with usage under the constant threshold will be chosen ; ties are broken randomly . | def best_gpu ( max_usage = USAGE_THRESHOLD , verbose = False ) : try : proc = subprocess . Popen ( "nvidia-smi" , stdout = subprocess . PIPE , stderr = subprocess . PIPE ) output , error = proc . communicate ( ) if error : raise Exception ( error ) except Exception , e : sys . stderr . write ( "Couldn't run nvidia-smi ... | 250,897 | https://github.com/stanfordnlp/stanza/blob/920c55d8eaa1e7105971059c66eb448a74c100d6/stanza/cluster/pick_gpu.py#L28-L67 | [
"def",
"sinterstore",
"(",
"self",
",",
"dest",
",",
"keys",
",",
"*",
"args",
")",
":",
"result",
"=",
"self",
".",
"sinter",
"(",
"keys",
",",
"*",
"args",
")",
"self",
".",
"redis",
"[",
"self",
".",
"_encode",
"(",
"dest",
")",
"]",
"=",
"r... |
Evaluate learner on the instances in eval_data according to each metric in metric and return a dictionary summarizing the values of the metrics . | def evaluate ( learner , eval_data , metrics , metric_names = None , split_id = None , write_data = False ) : if metric_names is None : metric_names = [ ( metric . __name__ if hasattr ( metric , '__name__' ) else ( 'm%d' % i ) ) for i , metric in enumerate ( metrics ) ] split_prefix = split_id + '.' if split_id else ''... | 250,898 | https://github.com/stanfordnlp/stanza/blob/920c55d8eaa1e7105971059c66eb448a74c100d6/stanza/research/evaluate.py#L7-L78 | [
"def",
"get_restricted_index",
"(",
"index",
",",
"length",
",",
"length_index_allowed",
"=",
"True",
")",
":",
"if",
"index",
"and",
"index",
">=",
"length",
":",
"index",
"=",
"length",
"if",
"length_index_allowed",
"else",
"length",
"-",
"1",
"return",
"g... |
convert JSON string to google . protobuf . descriptor instance | def json2pb ( pb , js , useFieldNumber = False ) : for field in pb . DESCRIPTOR . fields : if useFieldNumber : key = field . number else : key = field . name if key not in js : continue if field . type == FD . TYPE_MESSAGE : pass elif field . type in _js2ftype : ftype = _js2ftype [ field . type ] else : raise ParseErro... | 250,899 | https://github.com/stanfordnlp/stanza/blob/920c55d8eaa1e7105971059c66eb448a74c100d6/stanza/nlp/protobuf_json.py#L51-L79 | [
"def",
"handle_simulation_end",
"(",
"self",
",",
"data_portal",
")",
":",
"log",
".",
"info",
"(",
"'Simulated {} trading days\\n'",
"'first open: {}\\n'",
"'last close: {}'",
",",
"self",
".",
"_session_count",
",",
"self",
".",
"_trading_calendar",
".",
"session_op... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.