query
stringlengths 5
1.23k
| positive
stringlengths 53
15.2k
| id_
int64 0
252k
| task_name
stringlengths 87
242
| negative
listlengths 20
553
|
|---|---|---|---|---|
Get an action cache key string .
|
def get_action_cache_key ( name , argument ) : tokens = [ str ( name ) ] if argument : tokens . append ( str ( argument ) ) return '::' . join ( tokens )
| 2,700
|
https://github.com/inveniosoftware/invenio-access/blob/3b033a4bdc110eb2f7e9f08f0744a780884bfc80/invenio_access/models.py#L200-L205
|
[
"def",
"write",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"bool",
")",
":",
"raise",
"TypeError",
"(",
"\"Invalid value type, should be bool.\"",
")",
"# Write value",
"try",
":",
"if",
"value",
":",
"os",
".",
"write",
"(",
"self",
".",
"_fd",
",",
"b\"1\\n\"",
")",
"else",
":",
"os",
".",
"write",
"(",
"self",
".",
"_fd",
",",
"b\"0\\n\"",
")",
"except",
"OSError",
"as",
"e",
":",
"raise",
"GPIOError",
"(",
"e",
".",
"errno",
",",
"\"Writing GPIO: \"",
"+",
"e",
".",
"strerror",
")",
"# Rewind",
"try",
":",
"os",
".",
"lseek",
"(",
"self",
".",
"_fd",
",",
"0",
",",
"os",
".",
"SEEK_SET",
")",
"except",
"OSError",
"as",
"e",
":",
"raise",
"GPIOError",
"(",
"e",
".",
"errno",
",",
"\"Rewinding GPIO: \"",
"+",
"e",
".",
"strerror",
")"
] |
Remove the action from cache when an item is inserted or deleted .
|
def removed_or_inserted_action ( mapper , connection , target ) : current_access . delete_action_cache ( get_action_cache_key ( target . action , target . argument ) )
| 2,701
|
https://github.com/inveniosoftware/invenio-access/blob/3b033a4bdc110eb2f7e9f08f0744a780884bfc80/invenio_access/models.py#L208-L211
|
[
"def",
"_OpenFile",
"(",
"self",
",",
"path",
")",
":",
"if",
"not",
"self",
".",
"_registry_file_reader",
":",
"return",
"None",
"return",
"self",
".",
"_registry_file_reader",
".",
"Open",
"(",
"path",
",",
"ascii_codepage",
"=",
"self",
".",
"_ascii_codepage",
")"
] |
Remove the action from cache when an item is updated .
|
def changed_action ( mapper , connection , target ) : action_history = get_history ( target , 'action' ) argument_history = get_history ( target , 'argument' ) owner_history = get_history ( target , 'user' if isinstance ( target , ActionUsers ) else 'role' if isinstance ( target , ActionRoles ) else 'role_name' ) if action_history . has_changes ( ) or argument_history . has_changes ( ) or owner_history . has_changes ( ) : current_access . delete_action_cache ( get_action_cache_key ( target . action , target . argument ) ) current_access . delete_action_cache ( get_action_cache_key ( action_history . deleted [ 0 ] if action_history . deleted else target . action , argument_history . deleted [ 0 ] if argument_history . deleted else target . argument ) )
| 2,702
|
https://github.com/inveniosoftware/invenio-access/blob/3b033a4bdc110eb2f7e9f08f0744a780884bfc80/invenio_access/models.py#L214-L233
|
[
"def",
"Output",
"(",
"self",
")",
":",
"self",
".",
"Open",
"(",
")",
"self",
".",
"Header",
"(",
")",
"self",
".",
"Body",
"(",
")",
"self",
".",
"Footer",
"(",
")"
] |
Allow the given action need .
|
def allow ( cls , action , * * kwargs ) : return cls . create ( action , exclude = False , * * kwargs )
| 2,703
|
https://github.com/inveniosoftware/invenio-access/blob/3b033a4bdc110eb2f7e9f08f0744a780884bfc80/invenio_access/models.py#L62-L68
|
[
"def",
"volumes_delete",
"(",
"storage_pool",
",",
"logger",
")",
":",
"try",
":",
"for",
"vol_name",
"in",
"storage_pool",
".",
"listVolumes",
"(",
")",
":",
"try",
":",
"vol",
"=",
"storage_pool",
".",
"storageVolLookupByName",
"(",
"vol_name",
")",
"vol",
".",
"delete",
"(",
"0",
")",
"except",
"libvirt",
".",
"libvirtError",
":",
"logger",
".",
"exception",
"(",
"\"Unable to delete storage volume %s.\"",
",",
"vol_name",
")",
"except",
"libvirt",
".",
"libvirtError",
":",
"logger",
".",
"exception",
"(",
"\"Unable to delete storage volumes.\"",
")"
] |
Deny the given action need .
|
def deny ( cls , action , * * kwargs ) : return cls . create ( action , exclude = True , * * kwargs )
| 2,704
|
https://github.com/inveniosoftware/invenio-access/blob/3b033a4bdc110eb2f7e9f08f0744a780884bfc80/invenio_access/models.py#L71-L77
|
[
"def",
"volumes_delete",
"(",
"storage_pool",
",",
"logger",
")",
":",
"try",
":",
"for",
"vol_name",
"in",
"storage_pool",
".",
"listVolumes",
"(",
")",
":",
"try",
":",
"vol",
"=",
"storage_pool",
".",
"storageVolLookupByName",
"(",
"vol_name",
")",
"vol",
".",
"delete",
"(",
"0",
")",
"except",
"libvirt",
".",
"libvirtError",
":",
"logger",
".",
"exception",
"(",
"\"Unable to delete storage volume %s.\"",
",",
"vol_name",
")",
"except",
"libvirt",
".",
"libvirtError",
":",
"logger",
".",
"exception",
"(",
"\"Unable to delete storage volumes.\"",
")"
] |
Prepare query object with filtered action .
|
def query_by_action ( cls , action , argument = None ) : query = cls . query . filter_by ( action = action . value ) argument = argument or getattr ( action , 'argument' , None ) if argument is not None : query = query . filter ( db . or_ ( cls . argument == str ( argument ) , cls . argument . is_ ( None ) , ) ) else : query = query . filter ( cls . argument . is_ ( None ) ) return query
| 2,705
|
https://github.com/inveniosoftware/invenio-access/blob/3b033a4bdc110eb2f7e9f08f0744a780884bfc80/invenio_access/models.py#L80-L98
|
[
"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",
")"
] |
Predict binding for each peptide in peptfile to allele using the IEDB mhci binding prediction tool .
|
def predict_mhci_binding ( job , peptfile , allele , peplen , univ_options , mhci_options ) : work_dir = os . getcwd ( ) input_files = { 'peptfile.faa' : peptfile } input_files = get_files_from_filestore ( job , input_files , work_dir , docker = True ) peptides = read_peptide_file ( os . path . join ( os . getcwd ( ) , 'peptfile.faa' ) ) if not peptides : return job . fileStore . writeGlobalFile ( job . fileStore . getLocalTempFile ( ) ) parameters = [ mhci_options [ 'pred' ] , allele , peplen , input_files [ 'peptfile.faa' ] ] with open ( '/' . join ( [ work_dir , 'predictions.tsv' ] ) , 'w' ) as predfile : docker_call ( tool = 'mhci' , tool_parameters = parameters , work_dir = work_dir , dockerhub = univ_options [ 'dockerhub' ] , outfile = predfile , interactive = True , tool_version = mhci_options [ 'version' ] ) output_file = job . fileStore . writeGlobalFile ( predfile . name ) job . fileStore . logToMaster ( 'Ran mhci on %s:%s:%s successfully' % ( univ_options [ 'patient' ] , allele , peplen ) ) return output_file
| 2,706
|
https://github.com/BD2KGenomics/protect/blob/06310682c50dcf8917b912c8e551299ff7ee41ce/src/protect/binding_prediction/mhci.py#L23-L54
|
[
"def",
"gc_velocity_update",
"(",
"particle",
",",
"social",
",",
"state",
")",
":",
"gbest",
"=",
"state",
".",
"swarm",
"[",
"gbest_idx",
"(",
"state",
".",
"swarm",
")",
"]",
".",
"position",
"if",
"not",
"np",
".",
"array_equal",
"(",
"gbest",
",",
"particle",
".",
"position",
")",
":",
"return",
"std_velocity",
"(",
"particle",
",",
"social",
",",
"state",
")",
"rho",
"=",
"state",
".",
"params",
"[",
"'rho'",
"]",
"inertia",
"=",
"state",
".",
"params",
"[",
"'inertia'",
"]",
"v_max",
"=",
"state",
".",
"params",
"[",
"'v_max'",
"]",
"size",
"=",
"particle",
".",
"position",
".",
"size",
"r2",
"=",
"state",
".",
"rng",
".",
"uniform",
"(",
"0.0",
",",
"1.0",
",",
"size",
")",
"velocity",
"=",
"__gc_velocity_equation__",
"(",
"inertia",
",",
"rho",
",",
"r2",
",",
"particle",
",",
"gbest",
")",
"return",
"__clamp__",
"(",
"velocity",
",",
"v_max",
")"
] |
Yield file contents by block then close the file .
|
def iter_and_close ( file_like , block_size ) : while 1 : try : block = file_like . read ( block_size ) if block : yield block else : raise StopIteration except StopIteration : file_like . close ( ) return
| 2,707
|
https://github.com/rmohr/static3/blob/e5f88c5e91789bd4db7fde0cf59e4a15c3326f11/static.py#L239-L250
|
[
"def",
"setup_catalog_mappings",
"(",
"portal",
")",
":",
"logger",
".",
"info",
"(",
"\"*** Setup Catalog Mappings ***\"",
")",
"at",
"=",
"api",
".",
"get_tool",
"(",
"\"archetype_tool\"",
")",
"for",
"portal_type",
",",
"catalogs",
"in",
"CATALOG_MAPPINGS",
":",
"at",
".",
"setCatalogsByType",
"(",
"portal_type",
",",
"catalogs",
")"
] |
Return a Cling that serves from the given package and dir_name .
|
def cling_wrap ( package_name , dir_name , * * kw ) : resource = Requirement . parse ( package_name ) return Cling ( resource_filename ( resource , dir_name ) , * * kw )
| 2,708
|
https://github.com/rmohr/static3/blob/e5f88c5e91789bd4db7fde0cf59e4a15c3326f11/static.py#L253-L264
|
[
"def",
"_encode_wiki_sections",
"(",
"sections",
",",
"vocab",
")",
":",
"ids",
"=",
"[",
"]",
"section_boundaries",
"=",
"[",
"]",
"for",
"i",
",",
"section",
"in",
"enumerate",
"(",
"sections",
")",
":",
"if",
"i",
">",
"0",
":",
"# Skip including article title",
"ids",
".",
"extend",
"(",
"vocab",
".",
"encode",
"(",
"_format_title",
"(",
"_normalize_text",
"(",
"section",
".",
"title",
")",
")",
")",
")",
"ids",
".",
"extend",
"(",
"vocab",
".",
"encode",
"(",
"_normalize_text",
"(",
"section",
".",
"text",
")",
")",
")",
"section_boundaries",
".",
"append",
"(",
"len",
"(",
"ids",
")",
")",
"return",
"ids",
",",
"section_boundaries"
] |
Guard against arbitrary file retrieval .
|
def _is_under_root ( self , full_path ) : if ( path . abspath ( full_path ) + path . sep ) . startswith ( path . abspath ( self . root ) + path . sep ) : return True else : return False
| 2,709
|
https://github.com/rmohr/static3/blob/e5f88c5e91789bd4db7fde0cf59e4a15c3326f11/static.py#L200-L206
|
[
"def",
"_on_client_connect",
"(",
"self",
",",
"data",
")",
":",
"client",
"=",
"None",
"if",
"data",
".",
"get",
"(",
"'id'",
")",
"in",
"self",
".",
"_clients",
":",
"client",
"=",
"self",
".",
"_clients",
"[",
"data",
".",
"get",
"(",
"'id'",
")",
"]",
"client",
".",
"update_connected",
"(",
"True",
")",
"else",
":",
"client",
"=",
"Snapclient",
"(",
"self",
",",
"data",
".",
"get",
"(",
"'client'",
")",
")",
"self",
".",
"_clients",
"[",
"data",
".",
"get",
"(",
"'id'",
")",
"]",
"=",
"client",
"if",
"self",
".",
"_new_client_callback_func",
"and",
"callable",
"(",
"self",
".",
"_new_client_callback_func",
")",
":",
"self",
".",
"_new_client_callback_func",
"(",
"client",
")",
"_LOGGER",
".",
"info",
"(",
"'client %s connected'",
",",
"client",
".",
"friendly_name",
")"
] |
Return the first magic that matches this path or None .
|
def _match_magic ( self , full_path ) : for magic in self . magics : if magic . matches ( full_path ) : return magic
| 2,710
|
https://github.com/rmohr/static3/blob/e5f88c5e91789bd4db7fde0cf59e4a15c3326f11/static.py#L296-L300
|
[
"def",
"video_bitwise_bottom",
"(",
"x",
",",
"model_hparams",
",",
"vocab_size",
")",
":",
"pixel_embedding_size",
"=",
"64",
"inputs",
"=",
"x",
"with",
"tf",
".",
"variable_scope",
"(",
"\"video_modality_bitwise\"",
",",
"reuse",
"=",
"tf",
".",
"AUTO_REUSE",
")",
":",
"common_layers",
".",
"summarize_video",
"(",
"inputs",
",",
"\"bottom\"",
")",
"# Embed bitwise.",
"assert",
"vocab_size",
"==",
"256",
"embedded",
"=",
"discretization",
".",
"int_to_bit_embed",
"(",
"inputs",
",",
"8",
",",
"pixel_embedding_size",
")",
"# Project.",
"return",
"tf",
".",
"layers",
".",
"dense",
"(",
"embedded",
",",
"model_hparams",
".",
"hidden_size",
",",
"name",
"=",
"\"merge_pixel_embedded_frames\"",
")"
] |
Return the full path from which to read .
|
def _full_path ( self , path_info ) : full_path = self . root + path_info if path . exists ( full_path ) : return full_path else : for magic in self . magics : if path . exists ( magic . new_path ( full_path ) ) : return magic . new_path ( full_path ) else : return full_path
| 2,711
|
https://github.com/rmohr/static3/blob/e5f88c5e91789bd4db7fde0cf59e4a15c3326f11/static.py#L302-L312
|
[
"def",
"_aggregate",
"(",
"self",
",",
"instanceId",
",",
"container",
",",
"value",
",",
"subKey",
"=",
"None",
")",
":",
"# Get the aggregator.",
"if",
"instanceId",
"not",
"in",
"self",
".",
"_aggregators",
":",
"self",
".",
"_aggregators",
"[",
"instanceId",
"]",
"=",
"_Stats",
".",
"getAggregator",
"(",
"instanceId",
",",
"self",
".",
"__name",
")",
"aggregator",
"=",
"self",
".",
"_aggregators",
"[",
"instanceId",
"]",
"# If we are aggregating, get the old value.",
"if",
"aggregator",
":",
"oldValue",
"=",
"container",
".",
"get",
"(",
"self",
".",
"__name",
")",
"if",
"subKey",
":",
"oldValue",
"=",
"oldValue",
"[",
"subKey",
"]",
"aggregator",
"[",
"0",
"]",
".",
"update",
"(",
"aggregator",
"[",
"1",
"]",
",",
"oldValue",
",",
"value",
",",
"subKey",
")",
"else",
":",
"aggregator",
"[",
"0",
"]",
".",
"update",
"(",
"aggregator",
"[",
"1",
"]",
",",
"oldValue",
",",
"value",
")"
] |
Guess the mime type magically or using the mimetypes module .
|
def _guess_type ( self , full_path ) : magic = self . _match_magic ( full_path ) if magic is not None : return ( mimetypes . guess_type ( magic . old_path ( full_path ) ) [ 0 ] or 'text/plain' ) else : return mimetypes . guess_type ( full_path ) [ 0 ] or 'text/plain'
| 2,712
|
https://github.com/rmohr/static3/blob/e5f88c5e91789bd4db7fde0cf59e4a15c3326f11/static.py#L314-L321
|
[
"def",
"getStartingApplication",
"(",
"self",
",",
"pchAppKeyBuffer",
",",
"unAppKeyBufferLen",
")",
":",
"fn",
"=",
"self",
".",
"function_table",
".",
"getStartingApplication",
"result",
"=",
"fn",
"(",
"pchAppKeyBuffer",
",",
"unAppKeyBufferLen",
")",
"return",
"result"
] |
Return Etag and Last - Modified values defaults to now for both .
|
def _conditions ( self , full_path , environ ) : magic = self . _match_magic ( full_path ) if magic is not None : return magic . conditions ( full_path , environ ) else : mtime = stat ( full_path ) . st_mtime return str ( mtime ) , rfc822 . formatdate ( mtime )
| 2,713
|
https://github.com/rmohr/static3/blob/e5f88c5e91789bd4db7fde0cf59e4a15c3326f11/static.py#L323-L330
|
[
"def",
"_get_pooler",
"(",
"self",
",",
"units",
",",
"prefix",
")",
":",
"with",
"self",
".",
"name_scope",
"(",
")",
":",
"pooler",
"=",
"nn",
".",
"Dense",
"(",
"units",
"=",
"units",
",",
"flatten",
"=",
"False",
",",
"activation",
"=",
"'tanh'",
",",
"prefix",
"=",
"prefix",
")",
"return",
"pooler"
] |
Return the appropriate file object .
|
def _file_like ( self , full_path ) : magic = self . _match_magic ( full_path ) if magic is not None : return magic . file_like ( full_path , self . encoding ) else : return open ( full_path , 'rb' )
| 2,714
|
https://github.com/rmohr/static3/blob/e5f88c5e91789bd4db7fde0cf59e4a15c3326f11/static.py#L332-L338
|
[
"def",
"_get_dL2L",
"(",
"self",
",",
"imt_per",
")",
":",
"if",
"imt_per",
"<",
"0.18",
":",
"dL2L",
"=",
"-",
"0.06",
"elif",
"0.18",
"<=",
"imt_per",
"<",
"0.35",
":",
"dL2L",
"=",
"self",
".",
"_interp_function",
"(",
"0.12",
",",
"-",
"0.06",
",",
"0.35",
",",
"0.18",
",",
"imt_per",
")",
"elif",
"0.35",
"<=",
"imt_per",
"<=",
"10",
":",
"dL2L",
"=",
"self",
".",
"_interp_function",
"(",
"0.65",
",",
"0.12",
",",
"10",
",",
"0.35",
",",
"imt_per",
")",
"else",
":",
"dL2L",
"=",
"0",
"return",
"dL2L"
] |
Remove self . extension from path or raise MagicError .
|
def old_path ( self , full_path ) : if self . matches ( full_path ) : return full_path [ : - len ( self . extension ) ] else : raise MagicError ( "Path does not match this magic." )
| 2,715
|
https://github.com/rmohr/static3/blob/e5f88c5e91789bd4db7fde0cf59e4a15c3326f11/static.py#L374-L379
|
[
"def",
"_threaded_copy_data",
"(",
"instream",
",",
"outstream",
")",
":",
"copy_thread",
"=",
"threading",
".",
"Thread",
"(",
"target",
"=",
"_copy_data",
",",
"args",
"=",
"(",
"instream",
",",
"outstream",
")",
")",
"copy_thread",
".",
"setDaemon",
"(",
"True",
")",
"log",
".",
"debug",
"(",
"'%r, %r, %r'",
",",
"copy_thread",
",",
"instream",
",",
"outstream",
")",
"copy_thread",
".",
"start",
"(",
")",
"return",
"copy_thread"
] |
Pass environ and self . variables in to template .
|
def body ( self , environ , file_like ) : variables = environ . copy ( ) variables . update ( self . variables ) template = string . Template ( file_like . read ( ) ) if self . safe is True : return [ template . safe_substitute ( variables ) ] else : return [ template . substitute ( variables ) ]
| 2,716
|
https://github.com/rmohr/static3/blob/e5f88c5e91789bd4db7fde0cf59e4a15c3326f11/static.py#L414-L426
|
[
"def",
"_calibrate",
"(",
"self",
",",
"data",
",",
"labels",
")",
":",
"# network calibration",
"classifier",
"=",
"defaultdict",
"(",
"Counter",
")",
"for",
"(",
"i",
",",
"j",
")",
",",
"label",
"in",
"zip",
"(",
"self",
".",
"_bmus",
",",
"labels",
")",
":",
"classifier",
"[",
"i",
",",
"j",
"]",
"[",
"label",
"]",
"+=",
"1",
"self",
".",
"classifier",
"=",
"{",
"}",
"for",
"ij",
",",
"cnt",
"in",
"classifier",
".",
"items",
"(",
")",
":",
"maxi",
"=",
"max",
"(",
"cnt",
".",
"items",
"(",
")",
",",
"key",
"=",
"itemgetter",
"(",
"1",
")",
")",
"nb",
"=",
"sum",
"(",
"cnt",
".",
"values",
"(",
")",
")",
"self",
".",
"classifier",
"[",
"ij",
"]",
"=",
"maxi",
"[",
"0",
"]",
",",
"maxi",
"[",
"1",
"]",
"/",
"nb"
] |
Get current market rate for currency
|
def get_rate_for ( self , currency : str , to : str , reverse : bool = False ) -> Number : # Return 1 when currencies match if currency . upper ( ) == to . upper ( ) : return self . _format_number ( '1.0' ) # Set base and quote currencies base , quote = currency , to if reverse : base , quote = to , currency try : # Get rate from source rate = self . _get_rate ( base , quote ) except Exception as e : raise ConverterRateError ( self . name ) from e # Convert rate to number rate = self . _format_number ( rate ) try : # Validate rate value assert isinstance ( rate , ( float , Decimal ) ) assert rate > 0 except AssertionError as e : raise ConverterValidationError ( self . name , rate ) from e # Return market rate if reverse : return self . _format_number ( '1.0' ) / rate return rate
| 2,717
|
https://github.com/budacom/trading-bots/blob/8cb68bb8d0b5f822108db1cc5dae336e3d3c3452/trading_bots/contrib/converters/base.py#L45-L74
|
[
"def",
"block_diag",
"(",
"*",
"blocks",
":",
"np",
".",
"ndarray",
")",
"->",
"np",
".",
"ndarray",
":",
"for",
"b",
"in",
"blocks",
":",
"if",
"b",
".",
"shape",
"[",
"0",
"]",
"!=",
"b",
".",
"shape",
"[",
"1",
"]",
":",
"raise",
"ValueError",
"(",
"'Blocks must be square.'",
")",
"if",
"not",
"blocks",
":",
"return",
"np",
".",
"zeros",
"(",
"(",
"0",
",",
"0",
")",
",",
"dtype",
"=",
"np",
".",
"complex128",
")",
"n",
"=",
"sum",
"(",
"b",
".",
"shape",
"[",
"0",
"]",
"for",
"b",
"in",
"blocks",
")",
"dtype",
"=",
"functools",
".",
"reduce",
"(",
"_merge_dtypes",
",",
"(",
"b",
".",
"dtype",
"for",
"b",
"in",
"blocks",
")",
")",
"result",
"=",
"np",
".",
"zeros",
"(",
"shape",
"=",
"(",
"n",
",",
"n",
")",
",",
"dtype",
"=",
"dtype",
")",
"i",
"=",
"0",
"for",
"b",
"in",
"blocks",
":",
"j",
"=",
"i",
"+",
"b",
".",
"shape",
"[",
"0",
"]",
"result",
"[",
"i",
":",
"j",
",",
"i",
":",
"j",
"]",
"=",
"b",
"i",
"=",
"j",
"return",
"result"
] |
Convert amount to another currency
|
def convert ( self , amount : Number , currency : str , to : str , reverse : bool = False ) -> Number : rate = self . get_rate_for ( currency , to , reverse ) if self . return_decimal : amount = Decimal ( amount ) return amount * rate
| 2,718
|
https://github.com/budacom/trading-bots/blob/8cb68bb8d0b5f822108db1cc5dae336e3d3c3452/trading_bots/contrib/converters/base.py#L76-L81
|
[
"def",
"_get_env_var",
"(",
"env_var_name",
")",
":",
"if",
"env_var_name",
"in",
"os",
".",
"environ",
":",
"return",
"os",
".",
"environ",
"[",
"env_var_name",
"]",
"fname",
"=",
"os",
".",
"path",
".",
"join",
"(",
"get_home",
"(",
")",
",",
"'.tangorc'",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"fname",
")",
":",
"if",
"os",
".",
"name",
"==",
"'posix'",
":",
"fname",
"=",
"\"/etc/tangorc\"",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"fname",
")",
":",
"return",
"None",
"for",
"line",
"in",
"open",
"(",
"fname",
")",
":",
"strippedline",
"=",
"line",
".",
"split",
"(",
"'#'",
",",
"1",
")",
"[",
"0",
"]",
".",
"strip",
"(",
")",
"if",
"not",
"strippedline",
":",
"# empty line",
"continue",
"tup",
"=",
"strippedline",
".",
"split",
"(",
"'='",
",",
"1",
")",
"if",
"len",
"(",
"tup",
")",
"!=",
"2",
":",
"# illegal line!",
"continue",
"key",
",",
"val",
"=",
"map",
"(",
"str",
".",
"strip",
",",
"tup",
")",
"if",
"key",
"==",
"env_var_name",
":",
"return",
"val"
] |
Convert money to another currency
|
def convert_money ( self , money : Money , to : str , reverse : bool = False ) -> Money : converted = self . convert ( money . amount , money . currency , to , reverse ) return Money ( converted , to )
| 2,719
|
https://github.com/budacom/trading-bots/blob/8cb68bb8d0b5f822108db1cc5dae336e3d3c3452/trading_bots/contrib/converters/base.py#L83-L86
|
[
"def",
"_get_env_var",
"(",
"env_var_name",
")",
":",
"if",
"env_var_name",
"in",
"os",
".",
"environ",
":",
"return",
"os",
".",
"environ",
"[",
"env_var_name",
"]",
"fname",
"=",
"os",
".",
"path",
".",
"join",
"(",
"get_home",
"(",
")",
",",
"'.tangorc'",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"fname",
")",
":",
"if",
"os",
".",
"name",
"==",
"'posix'",
":",
"fname",
"=",
"\"/etc/tangorc\"",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"fname",
")",
":",
"return",
"None",
"for",
"line",
"in",
"open",
"(",
"fname",
")",
":",
"strippedline",
"=",
"line",
".",
"split",
"(",
"'#'",
",",
"1",
")",
"[",
"0",
"]",
".",
"strip",
"(",
")",
"if",
"not",
"strippedline",
":",
"# empty line",
"continue",
"tup",
"=",
"strippedline",
".",
"split",
"(",
"'='",
",",
"1",
")",
"if",
"len",
"(",
"tup",
")",
"!=",
"2",
":",
"# illegal line!",
"continue",
"key",
",",
"val",
"=",
"map",
"(",
"str",
".",
"strip",
",",
"tup",
")",
"if",
"key",
"==",
"env_var_name",
":",
"return",
"val"
] |
Add Icon Widget
|
def add_icon_widget ( self , ref , x = 1 , y = 1 , name = "heart" ) : if ref not in self . widgets : widget = IconWidget ( screen = self , ref = ref , x = x , y = y , name = name ) self . widgets [ ref ] = widget return self . widgets [ ref ]
| 2,720
|
https://github.com/jinglemansweep/lcdproc/blob/973628fc326177c9deaf3f2e1a435159eb565ae0/lcdproc/screen.py#L179-L186
|
[
"def",
"_openResources",
"(",
"self",
")",
":",
"try",
":",
"rate",
",",
"data",
"=",
"scipy",
".",
"io",
".",
"wavfile",
".",
"read",
"(",
"self",
".",
"_fileName",
",",
"mmap",
"=",
"True",
")",
"except",
"Exception",
"as",
"ex",
":",
"logger",
".",
"warning",
"(",
"ex",
")",
"logger",
".",
"warning",
"(",
"\"Unable to read wav with memmory mapping. Trying without now.\"",
")",
"rate",
",",
"data",
"=",
"scipy",
".",
"io",
".",
"wavfile",
".",
"read",
"(",
"self",
".",
"_fileName",
",",
"mmap",
"=",
"False",
")",
"self",
".",
"_array",
"=",
"data",
"self",
".",
"attributes",
"[",
"'rate'",
"]",
"=",
"rate"
] |
Add Scroller Widget
|
def add_scroller_widget ( self , ref , left = 1 , top = 1 , right = 20 , bottom = 1 , direction = "h" , speed = 1 , text = "Message" ) : if ref not in self . widgets : widget = ScrollerWidget ( screen = self , ref = ref , left = left , top = top , right = right , bottom = bottom , direction = direction , speed = speed , text = text ) self . widgets [ ref ] = widget return self . widgets [ ref ]
| 2,721
|
https://github.com/jinglemansweep/lcdproc/blob/973628fc326177c9deaf3f2e1a435159eb565ae0/lcdproc/screen.py#L189-L196
|
[
"def",
"_generate_examples_validation",
"(",
"self",
",",
"archive",
",",
"labels",
")",
":",
"# Get the current random seeds.",
"numpy_st0",
"=",
"np",
".",
"random",
".",
"get_state",
"(",
")",
"# Set new random seeds.",
"np",
".",
"random",
".",
"seed",
"(",
"135",
")",
"logging",
".",
"warning",
"(",
"'Overwriting cv2 RNG seed.'",
")",
"tfds",
".",
"core",
".",
"lazy_imports",
".",
"cv2",
".",
"setRNGSeed",
"(",
"357",
")",
"for",
"example",
"in",
"super",
"(",
"Imagenet2012Corrupted",
",",
"self",
")",
".",
"_generate_examples_validation",
"(",
"archive",
",",
"labels",
")",
":",
"with",
"tf",
".",
"Graph",
"(",
")",
".",
"as_default",
"(",
")",
":",
"tf_img",
"=",
"tf",
".",
"image",
".",
"decode_jpeg",
"(",
"example",
"[",
"'image'",
"]",
".",
"read",
"(",
")",
",",
"channels",
"=",
"3",
")",
"image_np",
"=",
"tfds",
".",
"as_numpy",
"(",
"tf_img",
")",
"example",
"[",
"'image'",
"]",
"=",
"self",
".",
"_get_corrupted_example",
"(",
"image_np",
")",
"yield",
"example",
"# Reset the seeds back to their original values.",
"np",
".",
"random",
".",
"set_state",
"(",
"numpy_st0",
")"
] |
Returns application installation path .
|
def install_dir ( self ) : max_len = 500 directory = self . _get_str ( self . _iface . get_install_dir , [ self . app_id ] , max_len = max_len ) if not directory : # Fallback to restricted interface (can only be used by approved apps). directory = self . _get_str ( self . _iface_list . get_install_dir , [ self . app_id ] , max_len = max_len ) return directory
| 2,722
|
https://github.com/idlesign/steampak/blob/cb3f2c737e272b0360802d947e388df7e34f50f3/steampak/libsteam/resources/apps.py#L73-L90
|
[
"def",
"compare_values",
"(",
"values0",
",",
"values1",
")",
":",
"values0",
"=",
"{",
"v",
"[",
"0",
"]",
":",
"v",
"[",
"1",
":",
"]",
"for",
"v",
"in",
"values0",
"}",
"values1",
"=",
"{",
"v",
"[",
"0",
"]",
":",
"v",
"[",
"1",
":",
"]",
"for",
"v",
"in",
"values1",
"}",
"created",
"=",
"[",
"(",
"k",
",",
"v",
"[",
"0",
"]",
",",
"v",
"[",
"1",
"]",
")",
"for",
"k",
",",
"v",
"in",
"values1",
".",
"items",
"(",
")",
"if",
"k",
"not",
"in",
"values0",
"]",
"deleted",
"=",
"[",
"(",
"k",
",",
"v",
"[",
"0",
"]",
",",
"v",
"[",
"1",
"]",
")",
"for",
"k",
",",
"v",
"in",
"values0",
".",
"items",
"(",
")",
"if",
"k",
"not",
"in",
"values1",
"]",
"modified",
"=",
"[",
"(",
"k",
",",
"v",
"[",
"0",
"]",
",",
"v",
"[",
"1",
"]",
")",
"for",
"k",
",",
"v",
"in",
"values0",
".",
"items",
"(",
")",
"if",
"v",
"!=",
"values1",
".",
"get",
"(",
"k",
",",
"None",
")",
"]",
"return",
"created",
",",
"deleted",
",",
"modified"
] |
Date and time of app purchase .
|
def purchase_time ( self ) : ts = self . _iface . get_purchase_time ( self . app_id ) return datetime . utcfromtimestamp ( ts )
| 2,723
|
https://github.com/idlesign/steampak/blob/cb3f2c737e272b0360802d947e388df7e34f50f3/steampak/libsteam/resources/apps.py#L93-L99
|
[
"def",
"remove_volume",
"(",
"self",
",",
"volume_name",
")",
":",
"logger",
".",
"info",
"(",
"\"removing volume '%s'\"",
",",
"volume_name",
")",
"try",
":",
"self",
".",
"d",
".",
"remove_volume",
"(",
"volume_name",
")",
"except",
"APIError",
"as",
"ex",
":",
"if",
"ex",
".",
"response",
".",
"status_code",
"==",
"requests",
".",
"codes",
".",
"CONFLICT",
":",
"logger",
".",
"debug",
"(",
"\"ignoring a conflict when removing volume %s\"",
",",
"volume_name",
")",
"else",
":",
"raise",
"ex"
] |
Use this context manager to add arguments to an argparse object with the add_argument method . Arguments must be defined before the command is defined . Note that no - clean and resume are added upon exit and should not be added in the context manager . For more info about these default arguments see below .
|
def get_args ( self ) : parser = argparse . ArgumentParser ( description = self . _desc , formatter_class = MyUniversalHelpFormatter ) # default args if self . _no_clean : parser . add_argument ( '--no-clean' , action = 'store_true' , help = 'If this flag is used, temporary work directory is not ' 'cleaned.' ) if self . _resume : parser . add_argument ( '--resume' , action = 'store_true' , help = 'If this flag is used, a previously uncleaned workflow in the' ' same directory will be resumed' ) return parser
| 2,724
|
https://github.com/BD2KGenomics/protect/blob/06310682c50dcf8917b912c8e551299ff7ee41ce/docker/pipelineWrapper.py#L170-L188
|
[
"def",
"percent_cb",
"(",
"name",
",",
"complete",
",",
"total",
")",
":",
"logger",
".",
"debug",
"(",
"\"{}: {} transferred out of {}\"",
".",
"format",
"(",
"name",
",",
"sizeof_fmt",
"(",
"complete",
")",
",",
"sizeof_fmt",
"(",
"total",
")",
")",
")",
"progress",
".",
"update_target",
"(",
"name",
",",
"complete",
",",
"total",
")"
] |
A wrapper for boost_ranks .
|
def wrap_rankboost ( job , rsem_files , merged_mhc_calls , transgene_out , univ_options , rankboost_options ) : rankboost = job . addChildJobFn ( boost_ranks , rsem_files [ 'rsem.isoforms.results' ] , merged_mhc_calls , transgene_out , univ_options , rankboost_options ) return rankboost . rv ( )
| 2,725
|
https://github.com/BD2KGenomics/protect/blob/06310682c50dcf8917b912c8e551299ff7ee41ce/src/protect/rankboost.py#L21-L42
|
[
"def",
"destroy_page",
"(",
"self",
",",
"tab_dict",
")",
":",
"# logger.info(\"destroy page %s\" % tab_dict['controller'].model.state.get_path())",
"if",
"tab_dict",
"[",
"'source_code_changed_handler_id'",
"]",
"is",
"not",
"None",
":",
"handler_id",
"=",
"tab_dict",
"[",
"'source_code_changed_handler_id'",
"]",
"if",
"tab_dict",
"[",
"'controller'",
"]",
".",
"view",
".",
"source_view",
".",
"get_buffer",
"(",
")",
".",
"handler_is_connected",
"(",
"handler_id",
")",
":",
"tab_dict",
"[",
"'controller'",
"]",
".",
"view",
".",
"source_view",
".",
"get_buffer",
"(",
")",
".",
"disconnect",
"(",
"handler_id",
")",
"else",
":",
"logger",
".",
"warning",
"(",
"\"Source code changed handler of state {0} was already removed.\"",
".",
"format",
"(",
"tab_dict",
"[",
"'state_m'",
"]",
")",
")",
"self",
".",
"remove_controller",
"(",
"tab_dict",
"[",
"'controller'",
"]",
")"
] |
Attempt to determine bot s filesystem path from its module .
|
def _path_from_module ( module ) : # Convert paths to list because Python's _NamespacePath doesn't support # indexing. paths = list ( getattr ( module , '__path__' , [ ] ) ) if len ( paths ) != 1 : filename = getattr ( module , '__file__' , None ) if filename is not None : paths = [ os . path . dirname ( filename ) ] else : # For unknown reasons, sometimes the list returned by __path__ # contains duplicates that must be removed. paths = list ( set ( paths ) ) if len ( paths ) > 1 : raise ImproperlyConfigured ( "The bot module %r has multiple filesystem locations (%r); " "you must configure this bot with an AppConfig subclass " "with a 'path' class attribute." % ( module , paths ) ) elif not paths : raise ImproperlyConfigured ( "The bot module %r has no filesystem location, " "you must configure this bot with an AppConfig subclass " "with a 'path' class attribute." % ( module , ) ) return paths [ 0 ]
| 2,726
|
https://github.com/budacom/trading-bots/blob/8cb68bb8d0b5f822108db1cc5dae336e3d3c3452/trading_bots/bots/registry.py#L58-L81
|
[
"def",
"compare_values",
"(",
"values0",
",",
"values1",
")",
":",
"values0",
"=",
"{",
"v",
"[",
"0",
"]",
":",
"v",
"[",
"1",
":",
"]",
"for",
"v",
"in",
"values0",
"}",
"values1",
"=",
"{",
"v",
"[",
"0",
"]",
":",
"v",
"[",
"1",
":",
"]",
"for",
"v",
"in",
"values1",
"}",
"created",
"=",
"[",
"(",
"k",
",",
"v",
"[",
"0",
"]",
",",
"v",
"[",
"1",
"]",
")",
"for",
"k",
",",
"v",
"in",
"values1",
".",
"items",
"(",
")",
"if",
"k",
"not",
"in",
"values0",
"]",
"deleted",
"=",
"[",
"(",
"k",
",",
"v",
"[",
"0",
"]",
",",
"v",
"[",
"1",
"]",
")",
"for",
"k",
",",
"v",
"in",
"values0",
".",
"items",
"(",
")",
"if",
"k",
"not",
"in",
"values1",
"]",
"modified",
"=",
"[",
"(",
"k",
",",
"v",
"[",
"0",
"]",
",",
"v",
"[",
"1",
"]",
")",
"for",
"k",
",",
"v",
"in",
"values0",
".",
"items",
"(",
")",
"if",
"v",
"!=",
"values1",
".",
"get",
"(",
"k",
",",
"None",
")",
"]",
"return",
"created",
",",
"deleted",
",",
"modified"
] |
Factory that creates an bot config from an entry in INSTALLED_APPS .
|
def create ( cls , entry ) : # trading_bots.example.bot.ExampleBot try : # If import_module succeeds, entry is a path to a bot module, # which may specify a bot class with a default_bot attribute. # Otherwise, entry is a path to a bot class or an error. module = import_module ( entry ) except ImportError : # Track that importing as a bot module failed. If importing as a # bot class fails too, we'll trigger the ImportError again. module = None mod_path , _ , cls_name = entry . rpartition ( '.' ) # Raise the original exception when entry cannot be a path to an # bot config class. if not mod_path : raise else : try : # If this works, the bot module specifies a bot class. entry = module . default_bot except AttributeError : # Otherwise, it simply uses the default bot registry class. return cls ( f'{entry}.Bot' , module ) else : mod_path , _ , cls_name = entry . rpartition ( '.' ) # If we're reaching this point, we must attempt to load the bot # class located at <mod_path>.<cls_name> mod = import_module ( mod_path ) try : bot_cls = getattr ( mod , cls_name ) except AttributeError : if module is None : # If importing as an bot module failed, that error probably # contains the most informative traceback. Trigger it again. import_module ( entry ) raise # Check for obvious errors. (This check prevents duck typing, but # it could be removed if it became a problem in practice.) if not issubclass ( bot_cls , Bot ) : raise ImproperlyConfigured ( "'%s' isn't a subclass of Bot." % entry ) # Entry is a path to an bot config class. return cls ( entry , mod , bot_cls . label )
| 2,727
|
https://github.com/budacom/trading-bots/blob/8cb68bb8d0b5f822108db1cc5dae336e3d3c3452/trading_bots/bots/registry.py#L84-L136
|
[
"def",
"discard_events",
"(",
"library",
",",
"session",
",",
"event_type",
",",
"mechanism",
")",
":",
"return",
"library",
".",
"viDiscardEvents",
"(",
"session",
",",
"event_type",
",",
"mechanism",
")"
] |
Return the config with the given case - insensitive config_name . Raise LookupError if no config exists with this name .
|
def get_config ( self , config_name , require_ready = True ) : if require_ready : self . bots . check_configs_ready ( ) else : self . bots . check_bots_ready ( ) return self . configs . get ( config_name . lower ( ) , { } )
| 2,728
|
https://github.com/budacom/trading-bots/blob/8cb68bb8d0b5f822108db1cc5dae336e3d3c3452/trading_bots/bots/registry.py#L138-L148
|
[
"def",
"delete",
"(",
"self",
")",
":",
"key",
"=",
"'https://plex.tv/devices/%s.xml'",
"%",
"self",
".",
"id",
"self",
".",
"_server",
".",
"query",
"(",
"key",
",",
"self",
".",
"_server",
".",
"_session",
".",
"delete",
")"
] |
Return an iterable of models .
|
def get_configs ( self ) : self . bots . check_models_ready ( ) for config in self . configs . values ( ) : yield config
| 2,729
|
https://github.com/budacom/trading-bots/blob/8cb68bb8d0b5f822108db1cc5dae336e3d3c3452/trading_bots/bots/registry.py#L150-L156
|
[
"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",
")"
] |
Load bots . Import each bot module . It is thread - safe and idempotent but not re - entrant .
|
def populate ( self , installed_bots = None ) : if self . ready : return # populate() might be called by two threads in parallel on servers # that create threads before initializing the WSGI callable. with self . _lock : if self . ready : return # An RLock prevents other threads from entering this section. The # compare and set operation below is atomic. if self . loading : # Prevent re-entrant calls to avoid running AppConfig.ready() # methods twice. raise RuntimeError ( "populate() isn't re-entrant" ) self . loading = True # Phase 1: Initialize bots for entry in installed_bots or { } : if isinstance ( entry , Bot ) : cls = entry entry = '.' . join ( [ cls . __module__ , cls . __name__ ] ) bot_reg = BotRegistry . create ( entry ) if bot_reg . label in self . bots : raise ImproperlyConfigured ( "Bot labels aren't unique, " "duplicates: %s" % bot_reg . label ) self . bots [ bot_reg . label ] = bot_reg bot_reg . bots = self # Check for duplicate bot names. counts = Counter ( bot_reg . name for bot_reg in self . bots . values ( ) ) duplicates = [ name for name , count in counts . most_common ( ) if count > 1 ] if duplicates : raise ImproperlyConfigured ( "Bot names aren't unique, " "duplicates: %s" % ", " . join ( duplicates ) ) self . bots_ready = True # Phase 2: import config files for bot in self . bots . values ( ) : bot . import_configs ( ) self . configs_ready = True self . ready = True
| 2,730
|
https://github.com/budacom/trading-bots/blob/8cb68bb8d0b5f822108db1cc5dae336e3d3c3452/trading_bots/bots/registry.py#L199-L254
|
[
"def",
"set_default",
"(",
"self",
",",
"channels",
"=",
"None",
")",
":",
"if",
"not",
"channels",
":",
"channels",
"=",
"self",
".",
"_ch_cal",
".",
"keys",
"(",
")",
"for",
"channel",
"in",
"channels",
":",
"self",
".",
"set_voltage",
"(",
"channel",
",",
"self",
".",
"_ch_cal",
"[",
"channel",
"]",
"[",
"'default'",
"]",
",",
"unit",
"=",
"'V'",
")"
] |
Import all bots and returns a bot class for the given label . Raise LookupError if no bot exists with this label .
|
def get_bot ( self , bot_label ) : self . check_bots_ready ( ) try : return self . bots [ bot_label ] except KeyError : message = "No installed bot with label '%s'." % bot_label for bot_cls in self . get_bots ( ) : if bot_cls . name == bot_label : message += " Did you mean '%s'?" % bot_cls . label break raise LookupError ( message )
| 2,731
|
https://github.com/budacom/trading-bots/blob/8cb68bb8d0b5f822108db1cc5dae336e3d3c3452/trading_bots/bots/registry.py#L271-L285
|
[
"def",
"swd_sync",
"(",
"self",
",",
"pad",
"=",
"False",
")",
":",
"if",
"pad",
":",
"self",
".",
"_dll",
".",
"JLINK_SWD_SyncBytes",
"(",
")",
"else",
":",
"self",
".",
"_dll",
".",
"JLINK_SWD_SyncBits",
"(",
")",
"return",
"None"
] |
Return a list of all installed configs .
|
def get_configs ( self ) : self . check_configs_ready ( ) result = [ ] for bot in self . bots . values ( ) : result . extend ( list ( bot . get_models ( ) ) ) return result
| 2,732
|
https://github.com/budacom/trading-bots/blob/8cb68bb8d0b5f822108db1cc5dae336e3d3c3452/trading_bots/bots/registry.py#L287-L296
|
[
"def",
"translateprotocolmask",
"(",
"protocol",
")",
":",
"pcscprotocol",
"=",
"0",
"if",
"None",
"!=",
"protocol",
":",
"if",
"CardConnection",
".",
"T0_protocol",
"&",
"protocol",
":",
"pcscprotocol",
"|=",
"SCARD_PROTOCOL_T0",
"if",
"CardConnection",
".",
"T1_protocol",
"&",
"protocol",
":",
"pcscprotocol",
"|=",
"SCARD_PROTOCOL_T1",
"if",
"CardConnection",
".",
"RAW_protocol",
"&",
"protocol",
":",
"pcscprotocol",
"|=",
"SCARD_PROTOCOL_RAW",
"if",
"CardConnection",
".",
"T15_protocol",
"&",
"protocol",
":",
"pcscprotocol",
"|=",
"SCARD_PROTOCOL_T15",
"return",
"pcscprotocol"
] |
Return the config matching the given bot_label and config_name . config_name is case - insensitive . Raise LookupError if no bot exists with this label or no config exists with this name in the bot . Raise ValueError if called with a single argument that doesn t contain exactly one dot .
|
def get_config ( self , bot_label , config_name = None , require_ready = True ) : if require_ready : self . check_configs_ready ( ) else : self . check_bots_ready ( ) if config_name is None : config_name = defaults . BOT_CONFIG bot = self . get_bot ( bot_label ) if not require_ready and bot . configs is None : bot . import_configs ( ) return bot . get_config ( config_name , require_ready = require_ready )
| 2,733
|
https://github.com/budacom/trading-bots/blob/8cb68bb8d0b5f822108db1cc5dae336e3d3c3452/trading_bots/bots/registry.py#L298-L319
|
[
"def",
"SetHeaders",
"(",
"self",
",",
"soap_headers",
",",
"http_headers",
")",
":",
"self",
".",
"suds_client",
".",
"set_options",
"(",
"soapheaders",
"=",
"soap_headers",
",",
"headers",
"=",
"http_headers",
")"
] |
Convert val into float with digits decimal .
|
def __to_float ( val , digits ) : try : return round ( float ( val ) , digits ) except ( ValueError , TypeError ) : return float ( 0 )
| 2,734
|
https://github.com/mjj4791/python-buienradar/blob/a70436f54e007ce921d5210cb296cf3e4adf9d09/buienradar/buienradar_json.py#L97-L102
|
[
"def",
"avail_images",
"(",
"call",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The avail_images function must be called with '",
"'-f or --function, or with the --list-images option.'",
")",
"templates",
"=",
"{",
"}",
"vm_properties",
"=",
"[",
"\"name\"",
",",
"\"config.template\"",
",",
"\"config.guestFullName\"",
",",
"\"config.hardware.numCPU\"",
",",
"\"config.hardware.memoryMB\"",
"]",
"vm_list",
"=",
"salt",
".",
"utils",
".",
"vmware",
".",
"get_mors_with_properties",
"(",
"_get_si",
"(",
")",
",",
"vim",
".",
"VirtualMachine",
",",
"vm_properties",
")",
"for",
"vm",
"in",
"vm_list",
":",
"if",
"\"config.template\"",
"in",
"vm",
"and",
"vm",
"[",
"\"config.template\"",
"]",
":",
"templates",
"[",
"vm",
"[",
"\"name\"",
"]",
"]",
"=",
"{",
"'name'",
":",
"vm",
"[",
"\"name\"",
"]",
",",
"'guest_fullname'",
":",
"vm",
"[",
"\"config.guestFullName\"",
"]",
"if",
"\"config.guestFullName\"",
"in",
"vm",
"else",
"\"N/A\"",
",",
"'cpus'",
":",
"vm",
"[",
"\"config.hardware.numCPU\"",
"]",
"if",
"\"config.hardware.numCPU\"",
"in",
"vm",
"else",
"\"N/A\"",
",",
"'ram'",
":",
"vm",
"[",
"\"config.hardware.memoryMB\"",
"]",
"if",
"\"config.hardware.memoryMB\"",
"in",
"vm",
"else",
"\"N/A\"",
"}",
"return",
"templates"
] |
Get buienradar json data and return results .
|
def get_json_data ( latitude = 52.091579 , longitude = 5.119734 ) : final_result = { SUCCESS : False , MESSAGE : None , CONTENT : None , RAINCONTENT : None } log . info ( "Getting buienradar json data for latitude=%s, longitude=%s" , latitude , longitude ) result = __get_ws_data ( ) if result [ SUCCESS ] : # store json data: final_result [ CONTENT ] = result [ CONTENT ] final_result [ SUCCESS ] = True else : if STATUS_CODE in result and MESSAGE in result : msg = "Status: %d, Msg: %s" % ( result [ STATUS_CODE ] , result [ MESSAGE ] ) elif MESSAGE in result : msg = "Msg: %s" % ( result [ MESSAGE ] ) else : msg = "Something went wrong (reason unknown)." log . warning ( msg ) final_result [ MESSAGE ] = msg # load forecasted precipitation: result = __get_precipfc_data ( latitude , longitude ) if result [ SUCCESS ] : final_result [ RAINCONTENT ] = result [ CONTENT ] else : if STATUS_CODE in result and MESSAGE in result : msg = "Status: %d, Msg: %s" % ( result [ STATUS_CODE ] , result [ MESSAGE ] ) elif MESSAGE in result : msg = "Msg: %s" % ( result [ MESSAGE ] ) else : msg = "Something went wrong (reason unknown)." log . warning ( msg ) final_result [ MESSAGE ] = msg return final_result
| 2,735
|
https://github.com/mjj4791/python-buienradar/blob/a70436f54e007ce921d5210cb296cf3e4adf9d09/buienradar/buienradar_json.py#L194-L238
|
[
"def",
"sync",
"(",
"self",
",",
"vault_client",
")",
":",
"if",
"self",
".",
"present",
"and",
"not",
"self",
".",
"existing",
":",
"LOG",
".",
"info",
"(",
"\"Writing new %s to %s\"",
",",
"self",
".",
"secret_format",
",",
"self",
")",
"self",
".",
"write",
"(",
"vault_client",
")",
"elif",
"self",
".",
"present",
"and",
"self",
".",
"existing",
":",
"if",
"self",
".",
"diff",
"(",
")",
"==",
"CHANGED",
"or",
"self",
".",
"diff",
"(",
")",
"==",
"OVERWRITE",
":",
"LOG",
".",
"info",
"(",
"\"Updating %s in %s\"",
",",
"self",
".",
"secret_format",
",",
"self",
")",
"self",
".",
"write",
"(",
"vault_client",
")",
"elif",
"not",
"self",
".",
"present",
"and",
"not",
"self",
".",
"existing",
":",
"LOG",
".",
"info",
"(",
"\"No %s to remove from %s\"",
",",
"self",
".",
"secret_format",
",",
"self",
")",
"elif",
"not",
"self",
".",
"present",
"and",
"self",
".",
"existing",
":",
"LOG",
".",
"info",
"(",
"\"Removing %s from %s\"",
",",
"self",
".",
"secret_format",
",",
"self",
")",
"self",
".",
"delete",
"(",
"vault_client",
")"
] |
Get buienradar forecasted precipitation .
|
def __get_precipfc_data ( latitude , longitude ) : url = 'https://gpsgadget.buienradar.nl/data/raintext?lat={}&lon={}' # rounding coordinates prevents unnecessary redirects/calls url = url . format ( round ( latitude , 2 ) , round ( longitude , 2 ) ) result = __get_url ( url ) return result
| 2,736
|
https://github.com/mjj4791/python-buienradar/blob/a70436f54e007ce921d5210cb296cf3e4adf9d09/buienradar/buienradar_json.py#L276-L285
|
[
"def",
"_get_unmanaged_files",
"(",
"self",
",",
"managed",
",",
"system_all",
")",
":",
"m_files",
",",
"m_dirs",
",",
"m_links",
"=",
"managed",
"s_files",
",",
"s_dirs",
",",
"s_links",
"=",
"system_all",
"return",
"(",
"sorted",
"(",
"list",
"(",
"set",
"(",
"s_files",
")",
".",
"difference",
"(",
"m_files",
")",
")",
")",
",",
"sorted",
"(",
"list",
"(",
"set",
"(",
"s_dirs",
")",
".",
"difference",
"(",
"m_dirs",
")",
")",
")",
",",
"sorted",
"(",
"list",
"(",
"set",
"(",
"s_links",
")",
".",
"difference",
"(",
"m_links",
")",
")",
")",
")"
] |
Load json data from url and return result .
|
def __get_url ( url ) : log . info ( "Retrieving weather data (%s)..." , url ) result = { SUCCESS : False , MESSAGE : None } try : r = requests . get ( url ) result [ STATUS_CODE ] = r . status_code result [ HEADERS ] = r . headers result [ CONTENT ] = r . text if ( 200 == r . status_code ) : result [ SUCCESS ] = True else : result [ MESSAGE ] = "Got http statuscode: %d." % ( r . status_code ) return result except requests . RequestException as ose : result [ MESSAGE ] = 'Error getting url data. %s' % ose log . error ( result [ MESSAGE ] ) return result
| 2,737
|
https://github.com/mjj4791/python-buienradar/blob/a70436f54e007ce921d5210cb296cf3e4adf9d09/buienradar/buienradar_json.py#L288-L306
|
[
"def",
"ensure_compatible_admin",
"(",
"view",
")",
":",
"def",
"wrapper",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"user_roles",
"=",
"request",
".",
"user",
".",
"user_data",
".",
"get",
"(",
"'roles'",
",",
"[",
"]",
")",
"if",
"len",
"(",
"user_roles",
")",
"!=",
"1",
":",
"context",
"=",
"{",
"'message'",
":",
"'I need to be able to manage user accounts. '",
"'My username is %s'",
"%",
"request",
".",
"user",
".",
"username",
"}",
"return",
"render",
"(",
"request",
",",
"'mtp_common/user_admin/incompatible-admin.html'",
",",
"context",
"=",
"context",
")",
"return",
"view",
"(",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"wrapper"
] |
Parse the buienradar json and rain data .
|
def __parse_ws_data ( jsondata , latitude = 52.091579 , longitude = 5.119734 ) : log . info ( "Parse ws data: latitude: %s, longitude: %s" , latitude , longitude ) result = { SUCCESS : False , MESSAGE : None , DATA : None } # select the nearest weather station loc_data = __select_nearest_ws ( jsondata , latitude , longitude ) # process current weather data from selected weatherstation if not loc_data : result [ MESSAGE ] = 'No location selected.' return result if not __is_valid ( loc_data ) : result [ MESSAGE ] = 'Location data is invalid.' return result # add distance to weatherstation log . debug ( "Raw location data: %s" , loc_data ) result [ DISTANCE ] = __get_ws_distance ( loc_data , latitude , longitude ) result = __parse_loc_data ( loc_data , result ) # extract weather forecast try : fc_data = jsondata [ __FORECAST ] [ __FIVEDAYFORECAST ] except ( json . JSONDecodeError , KeyError ) : result [ MESSAGE ] = 'Unable to extract forecast data.' log . exception ( result [ MESSAGE ] ) return result if fc_data : # result = __parse_fc_data(fc_data, result) log . debug ( "Raw forecast data: %s" , fc_data ) # pylint: disable=unsupported-assignment-operation result [ DATA ] [ FORECAST ] = __parse_fc_data ( fc_data ) return result
| 2,738
|
https://github.com/mjj4791/python-buienradar/blob/a70436f54e007ce921d5210cb296cf3e4adf9d09/buienradar/buienradar_json.py#L309-L344
|
[
"def",
"move_point_num",
"(",
"point",
",",
"to_clust",
",",
"from_clust",
",",
"cl_attr_sum",
",",
"cl_memb_sum",
")",
":",
"# Update sum of attributes in cluster.",
"for",
"iattr",
",",
"curattr",
"in",
"enumerate",
"(",
"point",
")",
":",
"cl_attr_sum",
"[",
"to_clust",
"]",
"[",
"iattr",
"]",
"+=",
"curattr",
"cl_attr_sum",
"[",
"from_clust",
"]",
"[",
"iattr",
"]",
"-=",
"curattr",
"# Update sums of memberships in cluster",
"cl_memb_sum",
"[",
"to_clust",
"]",
"+=",
"1",
"cl_memb_sum",
"[",
"from_clust",
"]",
"-=",
"1",
"return",
"cl_attr_sum",
",",
"cl_memb_sum"
] |
Parse the json data from selected weatherstation .
|
def __parse_loc_data ( loc_data , result ) : result [ DATA ] = { ATTRIBUTION : ATTRIBUTION_INFO , FORECAST : [ ] , PRECIPITATION_FORECAST : None } for key , [ value , func ] in SENSOR_TYPES . items ( ) : result [ DATA ] [ key ] = None try : sens_data = loc_data [ value ] if key == CONDITION : # update weather symbol & status text desc = loc_data [ __WEATHERDESCRIPTION ] result [ DATA ] [ CONDITION ] = __cond_from_desc ( desc ) result [ DATA ] [ CONDITION ] [ IMAGE ] = loc_data [ __ICONURL ] continue if key == STATIONNAME : result [ DATA ] [ key ] = __getStationName ( loc_data [ __STATIONNAME ] , loc_data [ __STATIONID ] ) continue # update all other data: if func is not None : result [ DATA ] [ key ] = func ( sens_data ) else : result [ DATA ] [ key ] = sens_data except KeyError : if result [ MESSAGE ] is None : result [ MESSAGE ] = "Missing key(s) in br data: " result [ MESSAGE ] += "%s " % value log . warning ( "Data element with key='%s' " "not loaded from br data!" , key ) result [ SUCCESS ] = True return result
| 2,739
|
https://github.com/mjj4791/python-buienradar/blob/a70436f54e007ce921d5210cb296cf3e4adf9d09/buienradar/buienradar_json.py#L347-L379
|
[
"def",
"_enforce_max_region_size",
"(",
"in_file",
",",
"data",
")",
":",
"max_size",
"=",
"20000",
"overlap_size",
"=",
"250",
"def",
"_has_larger_regions",
"(",
"f",
")",
":",
"return",
"any",
"(",
"r",
".",
"stop",
"-",
"r",
".",
"start",
">",
"max_size",
"for",
"r",
"in",
"pybedtools",
".",
"BedTool",
"(",
"f",
")",
")",
"out_file",
"=",
"\"%s-regionlimit%s\"",
"%",
"utils",
".",
"splitext_plus",
"(",
"in_file",
")",
"if",
"not",
"utils",
".",
"file_exists",
"(",
"out_file",
")",
":",
"if",
"_has_larger_regions",
"(",
"in_file",
")",
":",
"with",
"file_transaction",
"(",
"data",
",",
"out_file",
")",
"as",
"tx_out_file",
":",
"pybedtools",
".",
"BedTool",
"(",
")",
".",
"window_maker",
"(",
"w",
"=",
"max_size",
",",
"s",
"=",
"max_size",
"-",
"overlap_size",
",",
"b",
"=",
"pybedtools",
".",
"BedTool",
"(",
"in_file",
")",
")",
".",
"saveas",
"(",
"tx_out_file",
")",
"else",
":",
"utils",
".",
"symlink_plus",
"(",
"in_file",
",",
"out_file",
")",
"return",
"out_file"
] |
Parse the forecast data from the json section .
|
def __parse_fc_data ( fc_data ) : fc = [ ] for day in fc_data : fcdata = { CONDITION : __cond_from_desc ( __get_str ( day , __WEATHERDESCRIPTION ) ) , TEMPERATURE : __get_float ( day , __MAXTEMPERATURE ) , MIN_TEMP : __get_float ( day , __MINTEMPERATURE ) , MAX_TEMP : __get_float ( day , __MAXTEMPERATURE ) , SUN_CHANCE : __get_int ( day , __SUNCHANCE ) , RAIN_CHANCE : __get_int ( day , __RAINCHANCE ) , RAIN : __get_float ( day , __MMRAINMAX ) , MIN_RAIN : __get_float ( day , __MMRAINMIN ) , # new MAX_RAIN : __get_float ( day , __MMRAINMAX ) , # new SNOW : 0 , # for compatibility WINDFORCE : __get_int ( day , __WIND ) , WINDDIRECTION : __get_str ( day , __WINDDIRECTION ) , # new DATETIME : __to_localdatetime ( __get_str ( day , __DAY ) ) , } fcdata [ CONDITION ] [ IMAGE ] = day [ __ICONURL ] fc . append ( fcdata ) return fc
| 2,740
|
https://github.com/mjj4791/python-buienradar/blob/a70436f54e007ce921d5210cb296cf3e4adf9d09/buienradar/buienradar_json.py#L382-L408
|
[
"def",
"factor_aug",
"(",
"z",
",",
"DPhival",
",",
"G",
",",
"A",
")",
":",
"M",
",",
"N",
"=",
"G",
".",
"shape",
"P",
",",
"N",
"=",
"A",
".",
"shape",
"\"\"\"Multiplier for inequality constraints\"\"\"",
"l",
"=",
"z",
"[",
"N",
"+",
"P",
":",
"N",
"+",
"P",
"+",
"M",
"]",
"\"\"\"Slacks\"\"\"",
"s",
"=",
"z",
"[",
"N",
"+",
"P",
"+",
"M",
":",
"]",
"\"\"\"Sigma matrix\"\"\"",
"SIG",
"=",
"diags",
"(",
"l",
"/",
"s",
",",
"0",
")",
"# SIG = diags(l*s, 0)",
"\"\"\"Convert A\"\"\"",
"if",
"not",
"issparse",
"(",
"A",
")",
":",
"A",
"=",
"csr_matrix",
"(",
"A",
")",
"\"\"\"Convert G\"\"\"",
"if",
"not",
"issparse",
"(",
"G",
")",
":",
"G",
"=",
"csr_matrix",
"(",
"G",
")",
"\"\"\"Since we expect symmetric DPhival, we need to change A\"\"\"",
"sign",
"=",
"np",
".",
"zeros",
"(",
"N",
")",
"sign",
"[",
"0",
":",
"N",
"//",
"2",
"]",
"=",
"1.0",
"sign",
"[",
"N",
"//",
"2",
":",
"]",
"=",
"-",
"1.0",
"T",
"=",
"diags",
"(",
"sign",
",",
"0",
")",
"A_new",
"=",
"A",
".",
"dot",
"(",
"T",
")",
"W",
"=",
"AugmentedSystem",
"(",
"DPhival",
",",
"G",
",",
"SIG",
",",
"A_new",
")",
"return",
"W"
] |
Get the forecasted float from json section .
|
def __get_float ( section , name ) : try : return float ( section [ name ] ) except ( ValueError , TypeError , KeyError ) : return float ( 0 )
| 2,741
|
https://github.com/mjj4791/python-buienradar/blob/a70436f54e007ce921d5210cb296cf3e4adf9d09/buienradar/buienradar_json.py#L419-L424
|
[
"def",
"factor_aug",
"(",
"z",
",",
"DPhival",
",",
"G",
",",
"A",
")",
":",
"M",
",",
"N",
"=",
"G",
".",
"shape",
"P",
",",
"N",
"=",
"A",
".",
"shape",
"\"\"\"Multiplier for inequality constraints\"\"\"",
"l",
"=",
"z",
"[",
"N",
"+",
"P",
":",
"N",
"+",
"P",
"+",
"M",
"]",
"\"\"\"Slacks\"\"\"",
"s",
"=",
"z",
"[",
"N",
"+",
"P",
"+",
"M",
":",
"]",
"\"\"\"Sigma matrix\"\"\"",
"SIG",
"=",
"diags",
"(",
"l",
"/",
"s",
",",
"0",
")",
"# SIG = diags(l*s, 0)",
"\"\"\"Convert A\"\"\"",
"if",
"not",
"issparse",
"(",
"A",
")",
":",
"A",
"=",
"csr_matrix",
"(",
"A",
")",
"\"\"\"Convert G\"\"\"",
"if",
"not",
"issparse",
"(",
"G",
")",
":",
"G",
"=",
"csr_matrix",
"(",
"G",
")",
"\"\"\"Since we expect symmetric DPhival, we need to change A\"\"\"",
"sign",
"=",
"np",
".",
"zeros",
"(",
"N",
")",
"sign",
"[",
"0",
":",
"N",
"//",
"2",
"]",
"=",
"1.0",
"sign",
"[",
"N",
"//",
"2",
":",
"]",
"=",
"-",
"1.0",
"T",
"=",
"diags",
"(",
"sign",
",",
"0",
")",
"A_new",
"=",
"A",
".",
"dot",
"(",
"T",
")",
"W",
"=",
"AugmentedSystem",
"(",
"DPhival",
",",
"G",
",",
"SIG",
",",
"A_new",
")",
"return",
"W"
] |
Parse the forecasted precipitation data .
|
def __parse_precipfc_data ( data , timeframe ) : result = { AVERAGE : None , TOTAL : None , TIMEFRAME : None } log . debug ( "Precipitation data: %s" , data ) lines = data . splitlines ( ) index = 1 totalrain = 0 numberoflines = 0 nrlines = min ( len ( lines ) , round ( float ( timeframe ) / 5 ) + 1 ) # looping through lines of forecasted precipitation data and # not using the time data (HH:MM) int the data. This is to allow for # correct data in case we are running in a different timezone. while index < nrlines : line = lines [ index ] log . debug ( "__parse_precipfc_data: line: %s" , line ) # pylint: disable=unused-variable ( val , key ) = line . split ( "|" ) # See buienradar documentation for this api, attribution # https://www.buienradar.nl/overbuienradar/gratis-weerdata # # Op basis van de door u gewenste coordinaten (latitude en longitude) # kunt u de neerslag tot twee uur vooruit ophalen in tekstvorm. De # data wordt iedere 5 minuten geupdatet. Op deze pagina kunt u de # neerslag in tekst vinden. De waarde 0 geeft geen neerslag aan (droog) # de waarde 255 geeft zware neerslag aan. Gebruik de volgende formule # voor het omrekenen naar de neerslagintensiteit in de eenheid # millimeter per uur (mm/u): # # Neerslagintensiteit = 10^((waarde-109)/32) # # Ter controle: een waarde van 77 is gelijk aan een neerslagintensiteit # van 0,1 mm/u. mmu = 10 ** ( float ( ( int ( val ) - 109 ) ) / 32 ) totalrain = totalrain + float ( mmu ) numberoflines = numberoflines + 1 index += 1 if numberoflines > 0 : result [ AVERAGE ] = round ( ( totalrain / numberoflines ) , 2 ) else : result [ AVERAGE ] = 0 result [ TOTAL ] = round ( totalrain / 12 , 2 ) result [ TIMEFRAME ] = timeframe return result
| 2,742
|
https://github.com/mjj4791/python-buienradar/blob/a70436f54e007ce921d5210cb296cf3e4adf9d09/buienradar/buienradar_json.py#L435-L480
|
[
"def",
"rotate_bitmaps_to_roots",
"(",
"bitmaps",
",",
"roots",
")",
":",
"abs_bitmaps",
"=",
"[",
"]",
"for",
"bitmap",
",",
"chord_root",
"in",
"zip",
"(",
"bitmaps",
",",
"roots",
")",
":",
"abs_bitmaps",
".",
"append",
"(",
"rotate_bitmap_to_root",
"(",
"bitmap",
",",
"chord_root",
")",
")",
"return",
"np",
".",
"asarray",
"(",
"abs_bitmaps",
")"
] |
Get the condition name from the condition description .
|
def __cond_from_desc ( desc ) : # '{ 'code': 'conditon', 'detailed', 'exact', 'exact_nl'} for code , [ condition , detailed , exact , exact_nl ] in __BRCONDITIONS . items ( ) : if exact_nl == desc : return { CONDCODE : code , CONDITION : condition , DETAILED : detailed , EXACT : exact , EXACTNL : exact_nl } return None
| 2,743
|
https://github.com/mjj4791/python-buienradar/blob/a70436f54e007ce921d5210cb296cf3e4adf9d09/buienradar/buienradar_json.py#L483-L494
|
[
"def",
"_set_final_freeness",
"(",
"self",
",",
"flag",
")",
":",
"if",
"flag",
":",
"self",
".",
"state",
".",
"memory",
".",
"store",
"(",
"self",
".",
"heap_base",
"+",
"self",
".",
"heap_size",
"-",
"self",
".",
"_chunk_size_t_size",
",",
"~",
"CHUNK_P_MASK",
")",
"else",
":",
"self",
".",
"state",
".",
"memory",
".",
"store",
"(",
"self",
".",
"heap_base",
"+",
"self",
".",
"heap_size",
"-",
"self",
".",
"_chunk_size_t_size",
",",
"CHUNK_P_MASK",
")"
] |
Get the distance to the weatherstation from wstation section of json .
|
def __get_ws_distance ( wstation , latitude , longitude ) : if wstation : try : wslat = float ( wstation [ __LAT ] ) wslon = float ( wstation [ __LON ] ) dist = vincenty ( ( latitude , longitude ) , ( wslat , wslon ) ) log . debug ( "calc distance: %s (latitude: %s, longitude: " "%s, wslat: %s, wslon: %s)" , dist , latitude , longitude , wslat , wslon ) return dist except ( ValueError , TypeError , KeyError ) : # value does not exist, or is not a float return None else : return None
| 2,744
|
https://github.com/mjj4791/python-buienradar/blob/a70436f54e007ce921d5210cb296cf3e4adf9d09/buienradar/buienradar_json.py#L538-L559
|
[
"def",
"retino_colors",
"(",
"vcolorfn",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"0",
":",
"def",
"_retino_color_pass",
"(",
"*",
"args",
",",
"*",
"*",
"new_kwargs",
")",
":",
"return",
"retino_colors",
"(",
"vcolorfn",
",",
"*",
"args",
",",
"*",
"*",
"{",
"k",
":",
"(",
"new_kwargs",
"[",
"k",
"]",
"if",
"k",
"in",
"new_kwargs",
"else",
"kwargs",
"[",
"k",
"]",
")",
"for",
"k",
"in",
"set",
"(",
"kwargs",
".",
"keys",
"(",
")",
"+",
"new_kwargs",
".",
"keys",
"(",
")",
")",
"}",
")",
"return",
"_retino_color_pass",
"elif",
"len",
"(",
"args",
")",
">",
"1",
":",
"raise",
"ValueError",
"(",
"'retinotopy color functions accepts at most one argument'",
")",
"m",
"=",
"args",
"[",
"0",
"]",
"# we need to handle the arguments",
"if",
"isinstance",
"(",
"m",
",",
"(",
"geo",
".",
"VertexSet",
",",
"pimms",
".",
"ITable",
")",
")",
":",
"tbl",
"=",
"m",
".",
"properties",
"if",
"isinstance",
"(",
"m",
",",
"geo",
".",
"VertexSet",
")",
"else",
"m",
"n",
"=",
"tbl",
".",
"row_count",
"# if the weight or property arguments are lists, we need to thread these along",
"if",
"'property'",
"in",
"kwargs",
":",
"props",
"=",
"kwargs",
"[",
"'property'",
"]",
"del",
"kwargs",
"[",
"'property'",
"]",
"if",
"not",
"(",
"pimms",
".",
"is_vector",
"(",
"props",
")",
"or",
"pimms",
".",
"is_matrix",
"(",
"props",
")",
")",
":",
"props",
"=",
"[",
"props",
"for",
"_",
"in",
"range",
"(",
"n",
")",
"]",
"else",
":",
"props",
"=",
"None",
"if",
"'weight'",
"in",
"kwargs",
":",
"ws",
"=",
"kwargs",
"[",
"'weight'",
"]",
"del",
"kwargs",
"[",
"'weight'",
"]",
"if",
"not",
"pimms",
".",
"is_vector",
"(",
"ws",
")",
"and",
"not",
"pimms",
".",
"is_matrix",
"(",
"ws",
")",
":",
"ws",
"=",
"[",
"ws",
"for",
"_",
"in",
"range",
"(",
"n",
")",
"]",
"else",
":",
"ws",
"=",
"None",
"vcolorfn0",
"=",
"vcolorfn",
"(",
"Ellipsis",
",",
"*",
"*",
"kwargs",
")",
"if",
"len",
"(",
"kwargs",
")",
">",
"0",
"else",
"vcolorfn",
"if",
"props",
"is",
"None",
"and",
"ws",
"is",
"None",
":",
"vcfn",
"=",
"lambda",
"m",
",",
"k",
":",
"vcolorfn0",
"(",
"m",
")",
"elif",
"props",
"is",
"None",
":",
"vcfn",
"=",
"lambda",
"m",
",",
"k",
":",
"vcolorfn0",
"(",
"m",
",",
"weight",
"=",
"ws",
"[",
"k",
"]",
")",
"elif",
"ws",
"is",
"None",
":",
"vcfn",
"=",
"lambda",
"m",
",",
"k",
":",
"vcolorfn0",
"(",
"m",
",",
"property",
"=",
"props",
"[",
"k",
"]",
")",
"else",
":",
"vcfn",
"=",
"lambda",
"m",
",",
"k",
":",
"vcolorfn0",
"(",
"m",
",",
"property",
"=",
"props",
"[",
"k",
"]",
",",
"weight",
"=",
"ws",
"[",
"k",
"]",
")",
"return",
"np",
".",
"asarray",
"(",
"[",
"vcfn",
"(",
"r",
",",
"kk",
")",
"for",
"(",
"kk",
",",
"r",
")",
"in",
"enumerate",
"(",
"tbl",
".",
"rows",
")",
"]",
")",
"else",
":",
"return",
"vcolorfn",
"(",
"m",
",",
"*",
"*",
"kwargs",
")"
] |
Construct a staiion name .
|
def __getStationName ( name , id ) : name = name . replace ( "Meetstation" , "" ) name = name . strip ( ) name += " (%s)" % id return name
| 2,745
|
https://github.com/mjj4791/python-buienradar/blob/a70436f54e007ce921d5210cb296cf3e4adf9d09/buienradar/buienradar_json.py#L575-L580
|
[
"def",
"swd_sync",
"(",
"self",
",",
"pad",
"=",
"False",
")",
":",
"if",
"pad",
":",
"self",
".",
"_dll",
".",
"JLINK_SWD_SyncBytes",
"(",
")",
"else",
":",
"self",
".",
"_dll",
".",
"JLINK_SWD_SyncBits",
"(",
")",
"return",
"None"
] |
This method is used within urls . py to create unique formwizard instances for every request . We need to override this method because we add some kwargs which are needed to make the formwizard usable .
|
def as_view ( cls , * args , * * kwargs ) : initkwargs = cls . get_initkwargs ( * args , * * kwargs ) return super ( WizardView , cls ) . as_view ( * * initkwargs )
| 2,746
|
https://github.com/stephrdev/django-formwizard/blob/7b35165f0340aae4e8302d5b05b0cb443f6c9904/formwizard/views.py#L103-L110
|
[
"def",
"marching_cubes",
"(",
"self",
")",
":",
"meshed",
"=",
"matrix_to_marching_cubes",
"(",
"matrix",
"=",
"self",
".",
"matrix",
",",
"pitch",
"=",
"self",
".",
"pitch",
",",
"origin",
"=",
"self",
".",
"origin",
")",
"return",
"meshed"
] |
Creates a dict with all needed parameters for the form wizard instances .
|
def get_initkwargs ( cls , form_list , initial_dict = None , instance_dict = None , condition_dict = None , * args , * * kwargs ) : kwargs . update ( { 'initial_dict' : initial_dict or { } , 'instance_dict' : instance_dict or { } , 'condition_dict' : condition_dict or { } , } ) init_form_list = SortedDict ( ) assert len ( form_list ) > 0 , 'at least one form is needed' # walk through the passed form list for i , form in enumerate ( form_list ) : if isinstance ( form , ( list , tuple ) ) : # if the element is a tuple, add the tuple to the new created # sorted dictionary. init_form_list [ unicode ( form [ 0 ] ) ] = form [ 1 ] else : # if not, add the form with a zero based counter as unicode init_form_list [ unicode ( i ) ] = form # walk through the ne created list of forms for form in init_form_list . itervalues ( ) : if issubclass ( form , formsets . BaseFormSet ) : # if the element is based on BaseFormSet (FormSet/ModelFormSet) # we need to override the form variable. form = form . form # check if any form contains a FileField, if yes, we need a # file_storage added to the formwizard (by subclassing). for field in form . base_fields . itervalues ( ) : if ( isinstance ( field , forms . FileField ) and not hasattr ( cls , 'file_storage' ) ) : raise NoFileStorageConfigured # build the kwargs for the formwizard instances kwargs [ 'form_list' ] = init_form_list return kwargs
| 2,747
|
https://github.com/stephrdev/django-formwizard/blob/7b35165f0340aae4e8302d5b05b0cb443f6c9904/formwizard/views.py#L113-L170
|
[
"def",
"setOverlayTexelAspect",
"(",
"self",
",",
"ulOverlayHandle",
",",
"fTexelAspect",
")",
":",
"fn",
"=",
"self",
".",
"function_table",
".",
"setOverlayTexelAspect",
"result",
"=",
"fn",
"(",
"ulOverlayHandle",
",",
"fTexelAspect",
")",
"return",
"result"
] |
This method gets called by the routing engine . The first argument is request which contains a HttpRequest instance . The request is stored in self . request for later use . The storage instance is stored in self . storage .
|
def dispatch ( self , request , * args , * * kwargs ) : # add the storage engine to the current formwizard instance self . wizard_name = self . get_wizard_name ( ) self . prefix = self . get_prefix ( ) self . storage = get_storage ( self . storage_name , self . prefix , request , getattr ( self , 'file_storage' , None ) ) self . steps = StepsHelper ( self ) response = super ( WizardView , self ) . dispatch ( request , * args , * * kwargs ) # update the response (e.g. adding cookies) self . storage . update_response ( response ) return response
| 2,748
|
https://github.com/stephrdev/django-formwizard/blob/7b35165f0340aae4e8302d5b05b0cb443f6c9904/formwizard/views.py#L202-L222
|
[
"def",
"getError",
"(",
"self",
",",
"device",
"=",
"DEFAULT_DEVICE_ID",
",",
"message",
"=",
"True",
")",
":",
"return",
"self",
".",
"_getError",
"(",
"device",
",",
"message",
")"
] |
This method handles GET requests .
|
def get ( self , request , * args , * * kwargs ) : self . storage . reset ( ) # reset the current step to the first step. self . storage . current_step = self . steps . first return self . render ( self . get_form ( ) )
| 2,749
|
https://github.com/stephrdev/django-formwizard/blob/7b35165f0340aae4e8302d5b05b0cb443f6c9904/formwizard/views.py#L224-L236
|
[
"def",
"_maybe_set_message_age",
"(",
"self",
")",
":",
"if",
"self",
".",
"_message",
".",
"properties",
".",
"timestamp",
":",
"message_age",
"=",
"float",
"(",
"max",
"(",
"self",
".",
"_message",
".",
"properties",
".",
"timestamp",
",",
"time",
".",
"time",
"(",
")",
")",
"-",
"self",
".",
"_message",
".",
"properties",
".",
"timestamp",
")",
"if",
"message_age",
">",
"0",
":",
"self",
".",
"measurement",
".",
"add_duration",
"(",
"self",
".",
"message_age_key",
"(",
")",
",",
"message_age",
")"
] |
This method handles POST requests .
|
def post ( self , * args , * * kwargs ) : # Look for a wizard_prev_step element in the posted data which # contains a valid step name. If one was found, render the requested # form. (This makes stepping back a lot easier). wizard_prev_step = self . request . POST . get ( 'wizard_prev_step' , None ) if wizard_prev_step and wizard_prev_step in self . get_form_list ( ) : self . storage . current_step = wizard_prev_step form = self . get_form ( data = self . storage . get_step_data ( self . steps . current ) , files = self . storage . get_step_files ( self . steps . current ) ) return self . render ( form ) # Check if form was refreshed management_form = ManagementForm ( self . request . POST , prefix = self . prefix ) if not management_form . is_valid ( ) : raise ValidationError ( 'ManagementForm data is missing or has been tampered.' ) form_current_step = management_form . cleaned_data [ 'current_step' ] if ( form_current_step != self . steps . current and self . storage . current_step is not None ) : # form refreshed, change current step self . storage . current_step = form_current_step # get the form for the current step form = self . get_form ( data = self . request . POST , files = self . request . FILES ) # and try to validate if form . is_valid ( ) : # if the form is valid, store the cleaned data and files. self . storage . set_step_data ( self . steps . current , self . process_step ( form ) ) self . storage . set_step_files ( self . steps . current , self . process_step_files ( form ) ) # check if the current step is the last step if self . steps . current == self . steps . last : # no more steps, render done view return self . render_done ( form , * * kwargs ) else : # proceed to the next step return self . render_next_step ( form ) return self . render ( form )
| 2,750
|
https://github.com/stephrdev/django-formwizard/blob/7b35165f0340aae4e8302d5b05b0cb443f6c9904/formwizard/views.py#L238-L285
|
[
"def",
"get_random",
"(",
"self",
")",
":",
"import",
"random",
"Statement",
"=",
"self",
".",
"get_model",
"(",
"'statement'",
")",
"session",
"=",
"self",
".",
"Session",
"(",
")",
"count",
"=",
"self",
".",
"count",
"(",
")",
"if",
"count",
"<",
"1",
":",
"raise",
"self",
".",
"EmptyDatabaseException",
"(",
")",
"random_index",
"=",
"random",
".",
"randrange",
"(",
"0",
",",
"count",
")",
"random_statement",
"=",
"session",
".",
"query",
"(",
"Statement",
")",
"[",
"random_index",
"]",
"statement",
"=",
"self",
".",
"model_to_object",
"(",
"random_statement",
")",
"session",
".",
"close",
"(",
")",
"return",
"statement"
] |
This method gets called when all forms passed . The method should also re - validate all steps to prevent manipulation . If any form don t validate render_revalidation_failure should get called . If everything is fine call done .
|
def render_done ( self , form , * * kwargs ) : final_form_list = [ ] # walk through the form list and try to validate the data again. for form_key in self . get_form_list ( ) : form_obj = self . get_form ( step = form_key , data = self . storage . get_step_data ( form_key ) , files = self . storage . get_step_files ( form_key ) ) if not form_obj . is_valid ( ) : return self . render_revalidation_failure ( form_key , form_obj , * * kwargs ) final_form_list . append ( form_obj ) # render the done view and reset the wizard before returning the # response. This is needed to prevent from rendering done with the # same data twice. done_response = self . done ( final_form_list , * * kwargs ) self . storage . reset ( ) return done_response
| 2,751
|
https://github.com/stephrdev/django-formwizard/blob/7b35165f0340aae4e8302d5b05b0cb443f6c9904/formwizard/views.py#L303-L325
|
[
"def",
"_record_offset",
"(",
"self",
")",
":",
"offset",
"=",
"self",
".",
"blob_file",
".",
"tell",
"(",
")",
"self",
".",
"event_offsets",
".",
"append",
"(",
"offset",
")"
] |
Returns the prefix which will be used when calling the actual form for the given step . step contains the step - name form the form which will be called with the returned prefix .
|
def get_form_prefix ( self , step = None , form = None ) : if step is None : step = self . steps . current return str ( step )
| 2,752
|
https://github.com/stephrdev/django-formwizard/blob/7b35165f0340aae4e8302d5b05b0cb443f6c9904/formwizard/views.py#L327-L338
|
[
"def",
"update",
"(",
"self",
",",
"other",
")",
":",
"self",
".",
"update_ttl",
"(",
"other",
".",
"ttl",
")",
"super",
"(",
"Rdataset",
",",
"self",
")",
".",
"update",
"(",
"other",
")"
] |
Constructs the form for a given step . If no step is defined the current step will be determined automatically .
|
def get_form ( self , step = None , data = None , files = None ) : if step is None : step = self . steps . current # prepare the kwargs for the form instance. kwargs = self . get_form_kwargs ( step ) kwargs . update ( { 'data' : data , 'files' : files , 'prefix' : self . get_form_prefix ( step , self . form_list [ step ] ) , 'initial' : self . get_form_initial ( step ) , } ) if issubclass ( self . form_list [ step ] , forms . ModelForm ) : # If the form is based on ModelForm, add instance if available. kwargs . update ( { 'instance' : self . get_form_instance ( step ) } ) elif issubclass ( self . form_list [ step ] , forms . models . BaseModelFormSet ) : # If the form is based on ModelFormSet, add queryset if available. kwargs . update ( { 'queryset' : self . get_form_instance ( step ) } ) return self . form_list [ step ] ( * * kwargs )
| 2,753
|
https://github.com/stephrdev/django-formwizard/blob/7b35165f0340aae4e8302d5b05b0cb443f6c9904/formwizard/views.py#L363-L388
|
[
"def",
"put_resource",
"(",
"self",
",",
"resource",
")",
":",
"rtracker",
"=",
"self",
".",
"_get_tracker",
"(",
"resource",
")",
"try",
":",
"self",
".",
"_put",
"(",
"rtracker",
")",
"except",
"PoolFullError",
":",
"self",
".",
"_remove",
"(",
"rtracker",
")"
] |
Gets called when a form doesn t validate when rendering the done view . By default it changed the current step to failing forms step and renders the form .
|
def render_revalidation_failure ( self , step , form , * * kwargs ) : self . storage . current_step = step return self . render ( form , * * kwargs )
| 2,754
|
https://github.com/stephrdev/django-formwizard/blob/7b35165f0340aae4e8302d5b05b0cb443f6c9904/formwizard/views.py#L404-L411
|
[
"def",
"get_stocks",
"(",
"self",
",",
"symbols",
":",
"List",
"[",
"str",
"]",
")",
"->",
"List",
"[",
"Commodity",
"]",
":",
"query",
"=",
"(",
"self",
".",
"query",
".",
"filter",
"(",
"Commodity",
".",
"mnemonic",
".",
"in_",
"(",
"symbols",
")",
")",
")",
".",
"order_by",
"(",
"Commodity",
".",
"namespace",
",",
"Commodity",
".",
"mnemonic",
")",
"return",
"query",
".",
"all",
"(",
")"
] |
Returns a merged dictionary of all step cleaned_data dictionaries . If a step contains a FormSet the key will be prefixed with formset and contain a list of the formset cleaned_data dictionaries .
|
def get_all_cleaned_data ( self ) : cleaned_data = { } for form_key in self . get_form_list ( ) : form_obj = self . get_form ( step = form_key , data = self . storage . get_step_data ( form_key ) , files = self . storage . get_step_files ( form_key ) ) if form_obj . is_valid ( ) : if isinstance ( form_obj . cleaned_data , ( tuple , list ) ) : cleaned_data . update ( { 'formset-%s' % form_key : form_obj . cleaned_data } ) else : cleaned_data . update ( form_obj . cleaned_data ) return cleaned_data
| 2,755
|
https://github.com/stephrdev/django-formwizard/blob/7b35165f0340aae4e8302d5b05b0cb443f6c9904/formwizard/views.py#L427-L447
|
[
"def",
"set_max_order_count",
"(",
"self",
",",
"max_count",
",",
"on_error",
"=",
"'fail'",
")",
":",
"control",
"=",
"MaxOrderCount",
"(",
"on_error",
",",
"max_count",
")",
"self",
".",
"register_trading_control",
"(",
"control",
")"
] |
Returns the cleaned data for a given step . Before returning the cleaned data the stored values are being revalidated through the form . If the data doesn t validate None will be returned .
|
def get_cleaned_data_for_step ( self , step ) : if step in self . form_list : form_obj = self . get_form ( step = step , data = self . storage . get_step_data ( step ) , files = self . storage . get_step_files ( step ) ) if form_obj . is_valid ( ) : return form_obj . cleaned_data return None
| 2,756
|
https://github.com/stephrdev/django-formwizard/blob/7b35165f0340aae4e8302d5b05b0cb443f6c9904/formwizard/views.py#L449-L461
|
[
"def",
"correspondence",
"(",
"soup",
")",
":",
"correspondence",
"=",
"[",
"]",
"author_notes_nodes",
"=",
"raw_parser",
".",
"author_notes",
"(",
"soup",
")",
"if",
"author_notes_nodes",
":",
"corresp_nodes",
"=",
"raw_parser",
".",
"corresp",
"(",
"author_notes_nodes",
")",
"for",
"tag",
"in",
"corresp_nodes",
":",
"correspondence",
".",
"append",
"(",
"tag",
".",
"text",
")",
"return",
"correspondence"
] |
Returns the index for the given step name . If no step is given the current step will be used to get the index .
|
def get_step_index ( self , step = None ) : if step is None : step = self . steps . current return self . get_form_list ( ) . keyOrder . index ( step )
| 2,757
|
https://github.com/stephrdev/django-formwizard/blob/7b35165f0340aae4e8302d5b05b0cb443f6c9904/formwizard/views.py#L491-L498
|
[
"def",
"close",
"(",
"self",
")",
":",
"publish",
"=",
"False",
"exporterid",
"=",
"rsid",
"=",
"exception",
"=",
"export_ref",
"=",
"ed",
"=",
"None",
"with",
"self",
".",
"__lock",
":",
"if",
"not",
"self",
".",
"__closed",
":",
"exporterid",
"=",
"self",
".",
"__exportref",
".",
"get_export_container_id",
"(",
")",
"export_ref",
"=",
"self",
".",
"__exportref",
"rsid",
"=",
"self",
".",
"__exportref",
".",
"get_remoteservice_id",
"(",
")",
"ed",
"=",
"self",
".",
"__exportref",
".",
"get_description",
"(",
")",
"exception",
"=",
"self",
".",
"__exportref",
".",
"get_exception",
"(",
")",
"self",
".",
"__closed",
"=",
"True",
"publish",
"=",
"self",
".",
"__exportref",
".",
"close",
"(",
"self",
")",
"self",
".",
"__exportref",
"=",
"None",
"# pylint: disable=W0212",
"if",
"publish",
"and",
"export_ref",
"and",
"self",
".",
"__rsa",
":",
"self",
".",
"__rsa",
".",
"_publish_event",
"(",
"RemoteServiceAdminEvent",
".",
"fromexportunreg",
"(",
"self",
".",
"__rsa",
".",
"_get_bundle",
"(",
")",
",",
"exporterid",
",",
"rsid",
",",
"export_ref",
",",
"exception",
",",
"ed",
",",
")",
")",
"self",
".",
"__rsa",
"=",
"None"
] |
Returns a HttpResponse containing a all needed context data .
|
def render ( self , form = None , * * kwargs ) : form = form or self . get_form ( ) context = self . get_context_data ( form , * * kwargs ) return self . render_to_response ( context )
| 2,758
|
https://github.com/stephrdev/django-formwizard/blob/7b35165f0340aae4e8302d5b05b0cb443f6c9904/formwizard/views.py#L533-L539
|
[
"def",
"add_reference",
"(",
"self",
",",
"source",
",",
"target",
",",
"*",
"*",
"kwargs",
")",
":",
"# Tweak keyword arguments for addReference",
"addRef_kw",
"=",
"kwargs",
".",
"copy",
"(",
")",
"addRef_kw",
".",
"setdefault",
"(",
"\"referenceClass\"",
",",
"self",
".",
"referenceClass",
")",
"if",
"\"schema\"",
"in",
"addRef_kw",
":",
"del",
"addRef_kw",
"[",
"\"schema\"",
"]",
"uid",
"=",
"api",
".",
"get_uid",
"(",
"target",
")",
"rc",
"=",
"api",
".",
"get_tool",
"(",
"\"reference_catalog\"",
")",
"# throws IndexError if uid is invalid",
"rc",
".",
"addReference",
"(",
"source",
",",
"uid",
",",
"self",
".",
"relationship",
",",
"*",
"*",
"addRef_kw",
")",
"# link the version of the reference",
"self",
".",
"link_version",
"(",
"source",
",",
"target",
")"
] |
We require a url_name to reverse URLs later . Additionally users can pass a done_step_name to change the URL name of the done view .
|
def get_initkwargs ( cls , * args , * * kwargs ) : assert 'url_name' in kwargs , 'URL name is needed to resolve correct wizard URLs' extra_kwargs = { 'done_step_name' : kwargs . pop ( 'done_step_name' , 'done' ) , 'url_name' : kwargs . pop ( 'url_name' ) , } initkwargs = super ( NamedUrlWizardView , cls ) . get_initkwargs ( * args , * * kwargs ) initkwargs . update ( extra_kwargs ) assert initkwargs [ 'done_step_name' ] not in initkwargs [ 'form_list' ] , 'step name "%s" is reserved for "done" view' % initkwargs [ 'done_step_name' ] return initkwargs
| 2,759
|
https://github.com/stephrdev/django-formwizard/blob/7b35165f0340aae4e8302d5b05b0cb443f6c9904/formwizard/views.py#L572-L588
|
[
"def",
"checkIsConsistent",
"(",
"self",
")",
":",
"if",
"is_an_array",
"(",
"self",
".",
"mask",
")",
"and",
"self",
".",
"mask",
".",
"shape",
"!=",
"self",
".",
"data",
".",
"shape",
":",
"raise",
"ConsistencyError",
"(",
"\"Shape mismatch mask={}, data={}\"",
".",
"format",
"(",
"self",
".",
"mask",
".",
"shape",
"!=",
"self",
".",
"data",
".",
"shape",
")",
")"
] |
This renders the form or if needed does the http redirects .
|
def get ( self , * args , * * kwargs ) : step_url = kwargs . get ( 'step' , None ) if step_url is None : if 'reset' in self . request . GET : self . storage . reset ( ) self . storage . current_step = self . steps . first if self . request . GET : query_string = "?%s" % self . request . GET . urlencode ( ) else : query_string = "" next_step_url = reverse ( self . url_name , kwargs = { 'step' : self . steps . current , } ) + query_string return redirect ( next_step_url ) # is the current step the "done" name/view? elif step_url == self . done_step_name : last_step = self . steps . last return self . render_done ( self . get_form ( step = last_step , data = self . storage . get_step_data ( last_step ) , files = self . storage . get_step_files ( last_step ) ) , * * kwargs ) # is the url step name not equal to the step in the storage? # if yes, change the step in the storage (if name exists) elif step_url == self . steps . current : # URL step name and storage step name are equal, render! return self . render ( self . get_form ( data = self . storage . current_step_data , files = self . storage . current_step_data , ) , * * kwargs ) elif step_url in self . get_form_list ( ) : self . storage . current_step = step_url return self . render ( self . get_form ( data = self . storage . current_step_data , files = self . storage . current_step_data , ) , * * kwargs ) # invalid step name, reset to first and redirect. else : self . storage . current_step = self . steps . first return redirect ( self . url_name , step = self . steps . first )
| 2,760
|
https://github.com/stephrdev/django-formwizard/blob/7b35165f0340aae4e8302d5b05b0cb443f6c9904/formwizard/views.py#L590-L635
|
[
"def",
"pivot_wavelength",
"(",
"self",
")",
":",
"wl",
"=",
"self",
".",
"registry",
".",
"_pivot_wavelengths",
".",
"get",
"(",
"(",
"self",
".",
"telescope",
",",
"self",
".",
"band",
")",
")",
"if",
"wl",
"is",
"not",
"None",
":",
"return",
"wl",
"wl",
"=",
"self",
".",
"calc_pivot_wavelength",
"(",
")",
"self",
".",
"registry",
".",
"register_pivot_wavelength",
"(",
"self",
".",
"telescope",
",",
"self",
".",
"band",
",",
"wl",
")",
"return",
"wl"
] |
Do a redirect if user presses the prev . step button . The rest of this is super d from FormWizard .
|
def post ( self , * args , * * kwargs ) : prev_step = self . request . POST . get ( 'wizard_prev_step' , None ) if prev_step and prev_step in self . get_form_list ( ) : self . storage . current_step = prev_step return redirect ( self . url_name , step = prev_step ) return super ( NamedUrlWizardView , self ) . post ( * args , * * kwargs )
| 2,761
|
https://github.com/stephrdev/django-formwizard/blob/7b35165f0340aae4e8302d5b05b0cb443f6c9904/formwizard/views.py#L637-L646
|
[
"def",
"update",
"(",
"self",
",",
"other",
")",
":",
"self",
".",
"update_ttl",
"(",
"other",
".",
"ttl",
")",
"super",
"(",
"Rdataset",
",",
"self",
")",
".",
"update",
"(",
"other",
")"
] |
When using the NamedUrlFormWizard we have to redirect to update the browser s URL to match the shown step .
|
def render_next_step ( self , form , * * kwargs ) : next_step = self . get_next_step ( ) self . storage . current_step = next_step return redirect ( self . url_name , step = next_step )
| 2,762
|
https://github.com/stephrdev/django-formwizard/blob/7b35165f0340aae4e8302d5b05b0cb443f6c9904/formwizard/views.py#L648-L655
|
[
"def",
"get_correlation_table",
"(",
"self",
",",
"chain",
"=",
"0",
",",
"parameters",
"=",
"None",
",",
"caption",
"=",
"\"Parameter Correlations\"",
",",
"label",
"=",
"\"tab:parameter_correlations\"",
")",
":",
"parameters",
",",
"cor",
"=",
"self",
".",
"get_correlations",
"(",
"chain",
"=",
"chain",
",",
"parameters",
"=",
"parameters",
")",
"return",
"self",
".",
"_get_2d_latex_table",
"(",
"parameters",
",",
"cor",
",",
"caption",
",",
"label",
")"
] |
When a step fails we have to redirect the user to the first failing step .
|
def render_revalidation_failure ( self , failed_step , form , * * kwargs ) : self . storage . current_step = failed_step return redirect ( self . url_name , step = failed_step )
| 2,763
|
https://github.com/stephrdev/django-formwizard/blob/7b35165f0340aae4e8302d5b05b0cb443f6c9904/formwizard/views.py#L657-L663
|
[
"def",
"hash_to_unsigned",
"(",
"data",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"string_types",
")",
":",
"# Return a CRC32 value identical across Python versions and platforms",
"# by stripping the sign bit as on",
"# http://docs.python.org/library/zlib.html.",
"return",
"crc32",
"(",
"data",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"&",
"0xffffffff",
"else",
":",
"return",
"int",
"(",
"data",
")"
] |
Get and configure the storage backend
|
def get_store ( logger : Logger = None ) -> 'Store' : from trading_bots . conf import settings store_settings = settings . storage store = store_settings . get ( 'name' , 'json' ) if store == 'json' : store = 'trading_bots.core.storage.JSONStore' elif store == 'redis' : store = 'trading_bots.core.storage.RedisStore' store_cls = load_class_by_name ( store ) kwargs = store_cls . configure ( store_settings ) return store_cls ( logger = logger , * * kwargs )
| 2,764
|
https://github.com/budacom/trading-bots/blob/8cb68bb8d0b5f822108db1cc5dae336e3d3c3452/trading_bots/core/storage.py#L15-L26
|
[
"def",
"_prt_py_sections",
"(",
"self",
",",
"sec2d_nt",
",",
"prt",
"=",
"sys",
".",
"stdout",
",",
"doc",
"=",
"None",
")",
":",
"if",
"doc",
"is",
"None",
":",
"doc",
"=",
"'Sections variable'",
"prt",
".",
"write",
"(",
"'\"\"\"{DOC}\"\"\"\\n\\n'",
".",
"format",
"(",
"DOC",
"=",
"doc",
")",
")",
"self",
".",
"prt_ver",
"(",
"prt",
")",
"prt",
".",
"write",
"(",
"\"# pylint: disable=line-too-long\\n\"",
")",
"strcnt",
"=",
"self",
".",
"get_summary_str",
"(",
"sec2d_nt",
")",
"prt",
".",
"write",
"(",
"\"SECTIONS = [ # {CNTS}\\n\"",
".",
"format",
"(",
"CNTS",
"=",
"strcnt",
")",
")",
"prt",
".",
"write",
"(",
"' # (\"New Section\", [\\n'",
")",
"prt",
".",
"write",
"(",
"' # ]),\\n'",
")",
"for",
"section_name",
",",
"nthdrgos",
"in",
"sec2d_nt",
":",
"self",
".",
"_prt_py_section",
"(",
"prt",
",",
"section_name",
",",
"nthdrgos",
")",
"prt",
".",
"write",
"(",
"\"]\\n\"",
")"
] |
convert headers in human readable format
|
def parse_request_headers ( headers ) : request_header_keys = set ( headers . keys ( lower = True ) ) request_meta_keys = set ( XHEADERS_TO_ARGS_DICT . keys ( ) ) data_header_keys = request_header_keys . intersection ( request_meta_keys ) return dict ( ( [ XHEADERS_TO_ARGS_DICT [ key ] , headers . get ( key , None ) ] for key in data_header_keys ) )
| 2,765
|
https://github.com/coyo8/parinx/blob/6493798ceba8089345d970f71be4a896eb6b081d/parinx/parser.py#L48-L59
|
[
"def",
"get",
"(",
"self",
",",
"uid",
",",
"filters",
"=",
"None",
")",
":",
"filters",
"=",
"self",
".",
"__format_filters",
"(",
"filters",
")",
"r",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"apiurl",
"+",
"\"/users/{}/library-entries\"",
".",
"format",
"(",
"uid",
")",
",",
"headers",
"=",
"self",
".",
"header",
",",
"params",
"=",
"filters",
")",
"if",
"r",
".",
"status_code",
"!=",
"200",
":",
"raise",
"ServerError",
"jsd",
"=",
"r",
".",
"json",
"(",
")",
"if",
"jsd",
"[",
"'meta'",
"]",
"[",
"'count'",
"]",
":",
"return",
"SearchWrapper",
"(",
"jsd",
"[",
"'data'",
"]",
",",
"jsd",
"[",
"'links'",
"]",
"[",
"'next'",
"]",
"if",
"'next'",
"in",
"jsd",
"[",
"'links'",
"]",
"else",
"None",
",",
"self",
".",
"header",
")",
"else",
":",
"return",
"None"
] |
Separates the method s description and paramter s
|
def split_docstring ( docstring ) : docstring_list = [ line . strip ( ) for line in docstring . splitlines ( ) ] description_list = list ( takewhile ( lambda line : not ( line . startswith ( ':' ) or line . startswith ( '@inherit' ) ) , docstring_list ) ) description = ' ' . join ( description_list ) . strip ( ) first_field_line_number = len ( description_list ) fields = [ ] if first_field_line_number >= len ( docstring_list ) : return description , fields # only description, without any field last_field_lines = [ docstring_list [ first_field_line_number ] ] for line in docstring_list [ first_field_line_number + 1 : ] : if line . strip ( ) . startswith ( ':' ) or line . strip ( ) . startswith ( '@inherit' ) : fields . append ( ' ' . join ( last_field_lines ) ) last_field_lines = [ line ] else : last_field_lines . append ( line ) fields . append ( ' ' . join ( last_field_lines ) ) return description , fields
| 2,766
|
https://github.com/coyo8/parinx/blob/6493798ceba8089345d970f71be4a896eb6b081d/parinx/parser.py#L125-L151
|
[
"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",
")"
] |
return method docstring if method docstring is empty we get docstring from parent
|
def get_method_docstring ( cls , method_name ) : method = getattr ( cls , method_name , None ) if method is None : return docstrign = inspect . getdoc ( method ) if docstrign is None : for base in cls . __bases__ : docstrign = get_method_docstring ( base , method_name ) if docstrign : return docstrign else : return None return docstrign
| 2,767
|
https://github.com/coyo8/parinx/blob/6493798ceba8089345d970f71be4a896eb6b081d/parinx/parser.py#L154-L176
|
[
"def",
"combine",
"(",
"self",
")",
":",
"self",
".",
"pair",
",",
"setup",
"=",
"self",
".",
"combining_setup",
"(",
")",
"self",
".",
"cube",
"(",
"setup",
")",
"actual",
"=",
"self",
".",
"combining_search",
"(",
")",
"self",
".",
"cube",
"(",
"actual",
")",
"return",
"setup",
"+",
"actual"
] |
Get the condition name from the condition code .
|
def condition_from_code ( condcode ) : if condcode in __BRCONDITIONS : cond_data = __BRCONDITIONS [ condcode ] return { CONDCODE : condcode , CONDITION : cond_data [ 0 ] , DETAILED : cond_data [ 1 ] , EXACT : cond_data [ 2 ] , EXACTNL : cond_data [ 3 ] , } return None
| 2,768
|
https://github.com/mjj4791/python-buienradar/blob/a70436f54e007ce921d5210cb296cf3e4adf9d09/buienradar/buienradar.py#L41-L52
|
[
"def",
"Draw",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"reset",
"(",
")",
"output",
"=",
"None",
"while",
"self",
".",
"_rollover",
"(",
")",
":",
"if",
"output",
"is",
"None",
":",
"# Make our own copy of the drawn histogram",
"output",
"=",
"self",
".",
"_tree",
".",
"Draw",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"output",
"is",
"not",
"None",
":",
"output",
"=",
"output",
".",
"Clone",
"(",
")",
"# Make it memory resident (histograms)",
"if",
"hasattr",
"(",
"output",
",",
"'SetDirectory'",
")",
":",
"output",
".",
"SetDirectory",
"(",
"0",
")",
"else",
":",
"newoutput",
"=",
"self",
".",
"_tree",
".",
"Draw",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"newoutput",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"output",
",",
"_GraphBase",
")",
":",
"output",
".",
"Append",
"(",
"newoutput",
")",
"else",
":",
"# histogram",
"output",
"+=",
"newoutput",
"return",
"output"
] |
Validates a submission file
|
def validate ( self , * * kwargs ) : try : submission_file_schema = json . load ( open ( self . default_schema_file , 'r' ) ) additional_file_section_schema = json . load ( open ( self . additional_info_schema , 'r' ) ) # even though we are using the yaml package to load, # it supports JSON and YAML data = kwargs . pop ( "data" , None ) file_path = kwargs . pop ( "file_path" , None ) if file_path is None : raise LookupError ( "file_path argument must be supplied" ) if data is None : data = yaml . load_all ( open ( file_path , 'r' ) , Loader = Loader ) for data_item_index , data_item in enumerate ( data ) : if data_item is None : continue try : if not data_item_index and 'data_file' not in data_item : validate ( data_item , additional_file_section_schema ) else : validate ( data_item , submission_file_schema ) except ValidationError as ve : self . add_validation_message ( ValidationMessage ( file = file_path , message = ve . message + ' in ' + str ( ve . instance ) ) ) if self . has_errors ( file_path ) : return False else : return True except ScannerError as se : # pragma: no cover self . add_validation_message ( # pragma: no cover ValidationMessage ( file = file_path , message = 'There was a problem parsing the file. ' 'This can be because you forgot spaces ' 'after colons in your YAML file for instance. ' 'Diagnostic information follows.\n' + str ( se ) ) ) return False except Exception as e : self . add_validation_message ( ValidationMessage ( file = file_path , message = e . __str__ ( ) ) ) return False
| 2,769
|
https://github.com/HEPData/hepdata-validator/blob/d0b0cab742a009c8f0e8aac9f8c8e434a524d43c/hepdata_validator/submission_file_validator.py#L26-L80
|
[
"def",
"load_toml_rest_api_config",
"(",
"filename",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"filename",
")",
":",
"LOGGER",
".",
"info",
"(",
"\"Skipping rest api loading from non-existent config file: %s\"",
",",
"filename",
")",
"return",
"RestApiConfig",
"(",
")",
"LOGGER",
".",
"info",
"(",
"\"Loading rest api information from config: %s\"",
",",
"filename",
")",
"try",
":",
"with",
"open",
"(",
"filename",
")",
"as",
"fd",
":",
"raw_config",
"=",
"fd",
".",
"read",
"(",
")",
"except",
"IOError",
"as",
"e",
":",
"raise",
"RestApiConfigurationError",
"(",
"\"Unable to load rest api configuration file: {}\"",
".",
"format",
"(",
"str",
"(",
"e",
")",
")",
")",
"toml_config",
"=",
"toml",
".",
"loads",
"(",
"raw_config",
")",
"invalid_keys",
"=",
"set",
"(",
"toml_config",
".",
"keys",
"(",
")",
")",
".",
"difference",
"(",
"[",
"'bind'",
",",
"'connect'",
",",
"'timeout'",
",",
"'opentsdb_db'",
",",
"'opentsdb_url'",
",",
"'opentsdb_username'",
",",
"'opentsdb_password'",
",",
"'client_max_size'",
"]",
")",
"if",
"invalid_keys",
":",
"raise",
"RestApiConfigurationError",
"(",
"\"Invalid keys in rest api config: {}\"",
".",
"format",
"(",
"\", \"",
".",
"join",
"(",
"sorted",
"(",
"list",
"(",
"invalid_keys",
")",
")",
")",
")",
")",
"config",
"=",
"RestApiConfig",
"(",
"bind",
"=",
"toml_config",
".",
"get",
"(",
"\"bind\"",
",",
"None",
")",
",",
"connect",
"=",
"toml_config",
".",
"get",
"(",
"'connect'",
",",
"None",
")",
",",
"timeout",
"=",
"toml_config",
".",
"get",
"(",
"'timeout'",
",",
"None",
")",
",",
"opentsdb_url",
"=",
"toml_config",
".",
"get",
"(",
"'opentsdb_url'",
",",
"None",
")",
",",
"opentsdb_db",
"=",
"toml_config",
".",
"get",
"(",
"'opentsdb_db'",
",",
"None",
")",
",",
"opentsdb_username",
"=",
"toml_config",
".",
"get",
"(",
"'opentsdb_username'",
",",
"None",
")",
",",
"opentsdb_password",
"=",
"toml_config",
".",
"get",
"(",
"'opentsdb_password'",
",",
"None",
")",
",",
"client_max_size",
"=",
"toml_config",
".",
"get",
"(",
"'client_max_size'",
",",
"None",
")",
")",
"return",
"config"
] |
Given a dotted path returns the class
|
def load_class_by_name ( name : str ) : mod_path , _ , cls_name = name . rpartition ( '.' ) mod = importlib . import_module ( mod_path ) cls = getattr ( mod , cls_name ) return cls
| 2,770
|
https://github.com/budacom/trading-bots/blob/8cb68bb8d0b5f822108db1cc5dae336e3d3c3452/trading_bots/core/utils.py#L7-L12
|
[
"def",
"make_random_models_table",
"(",
"n_sources",
",",
"param_ranges",
",",
"random_state",
"=",
"None",
")",
":",
"prng",
"=",
"check_random_state",
"(",
"random_state",
")",
"sources",
"=",
"Table",
"(",
")",
"for",
"param_name",
",",
"(",
"lower",
",",
"upper",
")",
"in",
"param_ranges",
".",
"items",
"(",
")",
":",
"# Generate a column for every item in param_ranges, even if it",
"# is not in the model (e.g. flux). However, such columns will",
"# be ignored when rendering the image.",
"sources",
"[",
"param_name",
"]",
"=",
"prng",
".",
"uniform",
"(",
"lower",
",",
"upper",
",",
"n_sources",
")",
"return",
"sources"
] |
Load a YAML file from path
|
def load_yaml_file ( file_path : str ) : with codecs . open ( file_path , 'r' ) as f : return yaml . safe_load ( f )
| 2,771
|
https://github.com/budacom/trading-bots/blob/8cb68bb8d0b5f822108db1cc5dae336e3d3c3452/trading_bots/core/utils.py#L15-L18
|
[
"def",
"getByteStatistic",
"(",
"self",
",",
"wanInterfaceId",
"=",
"1",
",",
"timeout",
"=",
"1",
")",
":",
"namespace",
"=",
"Wan",
".",
"getServiceType",
"(",
"\"getByteStatistic\"",
")",
"+",
"str",
"(",
"wanInterfaceId",
")",
"uri",
"=",
"self",
".",
"getControlURL",
"(",
"namespace",
")",
"results",
"=",
"self",
".",
"execute",
"(",
"uri",
",",
"namespace",
",",
"\"GetTotalBytesSent\"",
",",
"timeout",
"=",
"timeout",
")",
"results2",
"=",
"self",
".",
"execute",
"(",
"uri",
",",
"namespace",
",",
"\"GetTotalBytesReceived\"",
",",
"timeout",
"=",
"timeout",
")",
"return",
"[",
"int",
"(",
"results",
"[",
"\"NewTotalBytesSent\"",
"]",
")",
",",
"int",
"(",
"results2",
"[",
"\"NewTotalBytesReceived\"",
"]",
")",
"]"
] |
A wrapper for assess_itx_resistance .
|
def run_itx_resistance_assessment ( job , rsem_files , univ_options , reports_options ) : return job . addChildJobFn ( assess_itx_resistance , rsem_files [ 'rsem.genes.results' ] , univ_options , reports_options ) . rv ( )
| 2,772
|
https://github.com/BD2KGenomics/protect/blob/06310682c50dcf8917b912c8e551299ff7ee41ce/src/protect/addons/assess_immunotherapy_resistance.py#L26-L37
|
[
"def",
"public_broadcaster",
"(",
")",
":",
"while",
"__websocket_server_running__",
":",
"pipein",
"=",
"open",
"(",
"PUBLIC_PIPE",
",",
"'r'",
")",
"line",
"=",
"pipein",
".",
"readline",
"(",
")",
".",
"replace",
"(",
"'\\n'",
",",
"''",
")",
".",
"replace",
"(",
"'\\r'",
",",
"''",
")",
"if",
"line",
"!=",
"''",
":",
"WebSocketHandler",
".",
"broadcast",
"(",
"line",
")",
"print",
"line",
"remaining_lines",
"=",
"pipein",
".",
"read",
"(",
")",
"pipein",
".",
"close",
"(",
")",
"pipeout",
"=",
"open",
"(",
"PUBLIC_PIPE",
",",
"'w'",
")",
"pipeout",
".",
"write",
"(",
"remaining_lines",
")",
"pipeout",
".",
"close",
"(",
")",
"else",
":",
"pipein",
".",
"close",
"(",
")",
"time",
".",
"sleep",
"(",
"0.05",
")"
] |
Redis result backend config
|
def CELERY_RESULT_BACKEND ( self ) : # allow specify directly configured = get ( 'CELERY_RESULT_BACKEND' , None ) if configured : return configured if not self . _redis_available ( ) : return None host , port = self . REDIS_HOST , self . REDIS_PORT if host and port : default = "redis://{host}:{port}/{db}" . format ( host = host , port = port , db = self . CELERY_REDIS_RESULT_DB ) return default
| 2,773
|
https://github.com/APSL/django-kaio/blob/b74b109bcfba31d973723bc419e2c95d190b80b7/kaio/mixins/celeryconf.py#L35-L53
|
[
"async",
"def",
"_update_firmware",
"(",
"filename",
",",
"loop",
")",
":",
"try",
":",
"from",
"opentrons",
"import",
"robot",
"except",
"ModuleNotFoundError",
":",
"res",
"=",
"\"Unable to find module `opentrons`--not updating firmware\"",
"rc",
"=",
"1",
"log",
".",
"error",
"(",
"res",
")",
"else",
":",
"# ensure there is a reference to the port",
"if",
"not",
"robot",
".",
"is_connected",
"(",
")",
":",
"robot",
".",
"connect",
"(",
")",
"# get port name",
"port",
"=",
"str",
"(",
"robot",
".",
"_driver",
".",
"port",
")",
"# set smoothieware into programming mode",
"robot",
".",
"_driver",
".",
"_smoothie_programming_mode",
"(",
")",
"# close the port so other application can access it",
"robot",
".",
"_driver",
".",
"_connection",
".",
"close",
"(",
")",
"# run lpc21isp, THIS WILL TAKE AROUND 1 MINUTE TO COMPLETE",
"update_cmd",
"=",
"'lpc21isp -wipe -donotstart {0} {1} {2} 12000'",
".",
"format",
"(",
"filename",
",",
"port",
",",
"robot",
".",
"config",
".",
"serial_speed",
")",
"proc",
"=",
"await",
"asyncio",
".",
"create_subprocess_shell",
"(",
"update_cmd",
",",
"stdout",
"=",
"asyncio",
".",
"subprocess",
".",
"PIPE",
",",
"loop",
"=",
"loop",
")",
"rd",
"=",
"await",
"proc",
".",
"stdout",
".",
"read",
"(",
")",
"res",
"=",
"rd",
".",
"decode",
"(",
")",
".",
"strip",
"(",
")",
"await",
"proc",
".",
"communicate",
"(",
")",
"rc",
"=",
"proc",
".",
"returncode",
"if",
"rc",
"==",
"0",
":",
"# re-open the port",
"robot",
".",
"_driver",
".",
"_connection",
".",
"open",
"(",
")",
"# reset smoothieware",
"robot",
".",
"_driver",
".",
"_smoothie_reset",
"(",
")",
"# run setup gcodes",
"robot",
".",
"_driver",
".",
"_setup",
"(",
")",
"return",
"res",
",",
"rc"
] |
Custom setting allowing switch between rabbitmq redis
|
def BROKER_TYPE ( self ) : broker_type = get ( 'BROKER_TYPE' , DEFAULT_BROKER_TYPE ) if broker_type not in SUPPORTED_BROKER_TYPES : log . warn ( "Specified BROKER_TYPE {} not supported. Backing to default {}" . format ( broker_type , DEFAULT_BROKER_TYPE ) ) return DEFAULT_BROKER_TYPE else : return broker_type
| 2,774
|
https://github.com/APSL/django-kaio/blob/b74b109bcfba31d973723bc419e2c95d190b80b7/kaio/mixins/celeryconf.py#L76-L85
|
[
"def",
"getOverlayTransformTrackedDeviceComponent",
"(",
"self",
",",
"ulOverlayHandle",
",",
"pchComponentName",
",",
"unComponentNameSize",
")",
":",
"fn",
"=",
"self",
".",
"function_table",
".",
"getOverlayTransformTrackedDeviceComponent",
"punDeviceIndex",
"=",
"TrackedDeviceIndex_t",
"(",
")",
"result",
"=",
"fn",
"(",
"ulOverlayHandle",
",",
"byref",
"(",
"punDeviceIndex",
")",
",",
"pchComponentName",
",",
"unComponentNameSize",
")",
"return",
"result",
",",
"punDeviceIndex"
] |
Sets BROKER_URL depending on redis or rabbitmq settings
|
def BROKER_URL ( self ) : # also allow specify broker_url broker_url = get ( 'BROKER_URL' , None ) if broker_url : log . info ( "Using BROKER_URL setting: {}" . format ( broker_url ) ) return broker_url redis_available = self . _redis_available ( ) broker_type = self . BROKER_TYPE if broker_type == 'redis' and not redis_available : log . warn ( "Choosed broker type is redis, but redis not available. \
Check redis package, and REDIS_HOST, REDIS_PORT settings" ) if broker_type == 'redis' and redis_available : return 'redis://{host}:{port}/{db}' . format ( host = self . REDIS_HOST , port = self . REDIS_PORT , db = self . CELERY_REDIS_BROKER_DB ) elif broker_type == 'rabbitmq' : return 'amqp://{user}:{passwd}@{host}:{port}/{vhost}' . format ( user = self . RABBITMQ_USER , passwd = self . RABBITMQ_PASSWD , host = self . RABBITMQ_HOST , port = self . RABBITMQ_PORT , vhost = self . RABBITMQ_VHOST ) else : return DEFAULT_BROKER_URL
| 2,775
|
https://github.com/APSL/django-kaio/blob/b74b109bcfba31d973723bc419e2c95d190b80b7/kaio/mixins/celeryconf.py#L122-L152
|
[
"def",
"_get_image_paths",
"(",
"im1",
",",
"im2",
")",
":",
"paths",
"=",
"[",
"]",
"for",
"im",
"in",
"[",
"im1",
",",
"im2",
"]",
":",
"if",
"im",
"is",
"None",
":",
"# Groupwise registration: only one image (ndim+1 dimensions)",
"paths",
".",
"append",
"(",
"paths",
"[",
"0",
"]",
")",
"continue",
"if",
"isinstance",
"(",
"im",
",",
"str",
")",
":",
"# Given a location",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"im1",
")",
":",
"paths",
".",
"append",
"(",
"im",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'Image location does not exist.'",
")",
"elif",
"isinstance",
"(",
"im",
",",
"np",
".",
"ndarray",
")",
":",
"# Given a numpy array",
"id",
"=",
"len",
"(",
"paths",
")",
"+",
"1",
"p",
"=",
"_write_image_data",
"(",
"im",
",",
"id",
")",
"paths",
".",
"append",
"(",
"p",
")",
"else",
":",
"# Given something else ...",
"raise",
"ValueError",
"(",
"'Invalid input image.'",
")",
"# Done",
"return",
"tuple",
"(",
"paths",
")"
] |
Generates market Item objects for each inventory item .
|
def traverse_inventory ( self , item_filter = None ) : not self . _intentory_raw and self . _get_inventory_raw ( ) for item in self . _intentory_raw [ 'rgDescriptions' ] . values ( ) : tags = item [ 'tags' ] for tag in tags : internal_name = tag [ 'internal_name' ] if item_filter is None or internal_name == item_filter : item_type = Item if internal_name == TAG_ITEM_CLASS_CARD : item_type = Card appid = item [ 'market_fee_app' ] title = item [ 'name' ] yield item_type ( appid , title )
| 2,776
|
https://github.com/idlesign/steampak/blob/cb3f2c737e272b0360802d947e388df7e34f50f3/steampak/webapi/resources/user.py#L36-L57
|
[
"def",
"stop_capture",
"(",
"self",
")",
":",
"if",
"self",
".",
"_capture_node",
":",
"yield",
"from",
"self",
".",
"_capture_node",
"[",
"\"node\"",
"]",
".",
"post",
"(",
"\"/adapters/{adapter_number}/ports/{port_number}/stop_capture\"",
".",
"format",
"(",
"adapter_number",
"=",
"self",
".",
"_capture_node",
"[",
"\"adapter_number\"",
"]",
",",
"port_number",
"=",
"self",
".",
"_capture_node",
"[",
"\"port_number\"",
"]",
")",
")",
"self",
".",
"_capture_node",
"=",
"None",
"yield",
"from",
"super",
"(",
")",
".",
"stop_capture",
"(",
")"
] |
Validates a data file
|
def validate ( self , * * kwargs ) : default_data_schema = json . load ( open ( self . default_schema_file , 'r' ) ) # even though we are using the yaml package to load, # it supports JSON and YAML data = kwargs . pop ( "data" , None ) file_path = kwargs . pop ( "file_path" , None ) if file_path is None : raise LookupError ( "file_path argument must be supplied" ) if data is None : try : data = yaml . load ( open ( file_path , 'r' ) , Loader = Loader ) except Exception as e : self . add_validation_message ( ValidationMessage ( file = file_path , message = 'There was a problem parsing the file.\n' + e . __str__ ( ) ) ) return False try : if 'type' in data : custom_schema = self . load_custom_schema ( data [ 'type' ] ) json_validate ( data , custom_schema ) else : json_validate ( data , default_data_schema ) except ValidationError as ve : self . add_validation_message ( ValidationMessage ( file = file_path , message = ve . message + ' in ' + str ( ve . instance ) ) ) if self . has_errors ( file_path ) : return False else : return True
| 2,777
|
https://github.com/HEPData/hepdata-validator/blob/d0b0cab742a009c8f0e8aac9f8c8e434a524d43c/hepdata_validator/data_file_validator.py#L74-L119
|
[
"def",
"indication",
"(",
"self",
",",
"apdu",
")",
":",
"if",
"_debug",
":",
"ServerSSM",
".",
"_debug",
"(",
"\"indication %r\"",
",",
"apdu",
")",
"if",
"self",
".",
"state",
"==",
"IDLE",
":",
"self",
".",
"idle",
"(",
"apdu",
")",
"elif",
"self",
".",
"state",
"==",
"SEGMENTED_REQUEST",
":",
"self",
".",
"segmented_request",
"(",
"apdu",
")",
"elif",
"self",
".",
"state",
"==",
"AWAIT_RESPONSE",
":",
"self",
".",
"await_response",
"(",
"apdu",
")",
"elif",
"self",
".",
"state",
"==",
"SEGMENTED_RESPONSE",
":",
"self",
".",
"segmented_response",
"(",
"apdu",
")",
"else",
":",
"if",
"_debug",
":",
"ServerSSM",
".",
"_debug",
"(",
"\" - invalid state\"",
")"
] |
Conversion to bytes
|
def b ( s ) : if sys . version < '3' : if isinstance ( s , unicode ) : #pylint: disable=undefined-variable return s . encode ( 'utf-8' ) else : return s
| 2,778
|
https://github.com/proycon/python-timbl/blob/e3c876711fa7f60648cfb1e4066c421a65faf524/timbl.py#L35-L41
|
[
"def",
"make_random_models_table",
"(",
"n_sources",
",",
"param_ranges",
",",
"random_state",
"=",
"None",
")",
":",
"prng",
"=",
"check_random_state",
"(",
"random_state",
")",
"sources",
"=",
"Table",
"(",
")",
"for",
"param_name",
",",
"(",
"lower",
",",
"upper",
")",
"in",
"param_ranges",
".",
"items",
"(",
")",
":",
"# Generate a column for every item in param_ranges, even if it",
"# is not in the model (e.g. flux). However, such columns will",
"# be ignored when rendering the image.",
"sources",
"[",
"param_name",
"]",
"=",
"prng",
".",
"uniform",
"(",
"lower",
",",
"upper",
",",
"n_sources",
")",
"return",
"sources"
] |
Returns features in validated form or raises an Exception . Mostly for internal use
|
def validatefeatures ( self , features ) : validatedfeatures = [ ] for feature in features : if isinstance ( feature , int ) or isinstance ( feature , float ) : validatedfeatures . append ( str ( feature ) ) elif self . delimiter in feature and not self . sklearn : raise ValueError ( "Feature contains delimiter: " + feature ) elif self . sklearn and isinstance ( feature , str ) : #then is sparse added together validatedfeatures . append ( feature ) else : validatedfeatures . append ( feature ) return validatedfeatures
| 2,779
|
https://github.com/proycon/python-timbl/blob/e3c876711fa7f60648cfb1e4066c421a65faf524/timbl.py#L102-L114
|
[
"def",
"transform",
"(",
"self",
",",
"X",
")",
":",
"assert",
"np",
".",
"shape",
"(",
"X",
")",
"[",
"0",
"]",
"==",
"len",
"(",
"self",
".",
"_weights",
")",
",",
"(",
"'BlendingOptimizer: Number of models to blend its predictions and weights does not match: '",
"'n_models={}, weights_len={}'",
".",
"format",
"(",
"np",
".",
"shape",
"(",
"X",
")",
"[",
"0",
"]",
",",
"len",
"(",
"self",
".",
"_weights",
")",
")",
")",
"blended_predictions",
"=",
"np",
".",
"average",
"(",
"np",
".",
"power",
"(",
"X",
",",
"self",
".",
"_power",
")",
",",
"weights",
"=",
"self",
".",
"_weights",
",",
"axis",
"=",
"0",
")",
"**",
"(",
"1.0",
"/",
"self",
".",
"_power",
")",
"return",
"{",
"'y_pred'",
":",
"blended_predictions",
"}"
] |
Adds an instance to a specific file . Especially suitable for generating test files
|
def addinstance ( self , testfile , features , classlabel = "?" ) : features = self . validatefeatures ( features ) if self . delimiter in classlabel : raise ValueError ( "Class label contains delimiter: " + self . delimiter ) f = io . open ( testfile , 'a' , encoding = self . encoding ) f . write ( self . delimiter . join ( features ) + self . delimiter + classlabel + "\n" ) f . close ( )
| 2,780
|
https://github.com/proycon/python-timbl/blob/e3c876711fa7f60648cfb1e4066c421a65faf524/timbl.py#L247-L258
|
[
"def",
"delete_annotation",
"(",
"self",
",",
"term_ilx_id",
":",
"str",
",",
"annotation_type_ilx_id",
":",
"str",
",",
"annotation_value",
":",
"str",
")",
"->",
"dict",
":",
"term_data",
"=",
"self",
".",
"get_entity",
"(",
"term_ilx_id",
")",
"if",
"not",
"term_data",
"[",
"'id'",
"]",
":",
"exit",
"(",
"'term_ilx_id: '",
"+",
"term_ilx_id",
"+",
"' does not exist'",
")",
"anno_data",
"=",
"self",
".",
"get_entity",
"(",
"annotation_type_ilx_id",
")",
"if",
"not",
"anno_data",
"[",
"'id'",
"]",
":",
"exit",
"(",
"'annotation_type_ilx_id: '",
"+",
"annotation_type_ilx_id",
"+",
"' does not exist'",
")",
"entity_annotations",
"=",
"self",
".",
"get_annotation_via_tid",
"(",
"term_data",
"[",
"'id'",
"]",
")",
"annotation_id",
"=",
"''",
"for",
"annotation",
"in",
"entity_annotations",
":",
"if",
"str",
"(",
"annotation",
"[",
"'tid'",
"]",
")",
"==",
"str",
"(",
"term_data",
"[",
"'id'",
"]",
")",
":",
"if",
"str",
"(",
"annotation",
"[",
"'annotation_tid'",
"]",
")",
"==",
"str",
"(",
"anno_data",
"[",
"'id'",
"]",
")",
":",
"if",
"str",
"(",
"annotation",
"[",
"'value'",
"]",
")",
"==",
"str",
"(",
"annotation_value",
")",
":",
"annotation_id",
"=",
"annotation",
"[",
"'id'",
"]",
"break",
"if",
"not",
"annotation_id",
":",
"print",
"(",
"'''WARNING: Annotation you wanted to delete does not exist '''",
")",
"return",
"None",
"url",
"=",
"self",
".",
"base_url",
"+",
"'term/edit-annotation/{annotation_id}'",
".",
"format",
"(",
"annotation_id",
"=",
"annotation_id",
")",
"data",
"=",
"{",
"'tid'",
":",
"' '",
",",
"# for delete",
"'annotation_tid'",
":",
"' '",
",",
"# for delete",
"'value'",
":",
"' '",
",",
"# for delete",
"'term_version'",
":",
"' '",
",",
"'annotation_term_version'",
":",
"' '",
",",
"}",
"output",
"=",
"self",
".",
"post",
"(",
"url",
"=",
"url",
",",
"data",
"=",
"data",
",",
")",
"# check output",
"return",
"output"
] |
Train & Test using cross validation testfile is a file that contains the filenames of all the folds!
|
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
| 2,781
|
https://github.com/proycon/python-timbl/blob/e3c876711fa7f60648cfb1e4066c421a65faf524/timbl.py#L271-L289
|
[
"def",
"promote_owner",
"(",
"self",
",",
"stream_id",
",",
"user_id",
")",
":",
"req_hook",
"=",
"'pod/v1/room/'",
"+",
"stream_id",
"+",
"'/membership/promoteOwner'",
"req_args",
"=",
"'{ \"id\": %s }'",
"%",
"user_id",
"status_code",
",",
"response",
"=",
"self",
".",
"__rest__",
".",
"POST_query",
"(",
"req_hook",
",",
"req_args",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"'%s: %s'",
"%",
"(",
"status_code",
",",
"response",
")",
")",
"return",
"status_code",
",",
"response"
] |
Train & Test using leave one out
|
def leaveoneout ( self ) : traintestfile = self . fileprefix + '.train' options = "-F " + self . format + " " + self . timbloptions + " -t leave_one_out" 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 API : " + options , file = stderr ) if sys . version < '3' : self . api . learn ( b ( traintestfile ) ) self . api . test ( b ( traintestfile ) , b ( self . fileprefix + '.out' ) , b'' ) else : self . api . learn ( u ( traintestfile ) ) self . api . test ( u ( traintestfile ) , u ( self . fileprefix + '.out' ) , '' ) return self . api . getAccuracy ( )
| 2,782
|
https://github.com/proycon/python-timbl/blob/e3c876711fa7f60648cfb1e4066c421a65faf524/timbl.py#L293-L311
|
[
"def",
"wrap_file",
"(",
"file_like_obj",
")",
":",
"if",
"isinstance",
"(",
"file_like_obj",
",",
"AsyncIOBaseWrapper",
")",
":",
"return",
"file_like_obj",
"if",
"isinstance",
"(",
"file_like_obj",
",",
"sync_io",
".",
"FileIO",
")",
":",
"return",
"AsyncFileIOWrapper",
"(",
"file_like_obj",
")",
"if",
"isinstance",
"(",
"file_like_obj",
",",
"sync_io",
".",
"BufferedRandom",
")",
":",
"return",
"AsyncBufferedRandomWrapper",
"(",
"file_like_obj",
")",
"if",
"isinstance",
"(",
"file_like_obj",
",",
"sync_io",
".",
"BufferedReader",
")",
":",
"return",
"AsyncBufferedReaderWrapper",
"(",
"file_like_obj",
")",
"if",
"isinstance",
"(",
"file_like_obj",
",",
"sync_io",
".",
"BufferedWriter",
")",
":",
"return",
"AsyncBufferedWriterWrapper",
"(",
"file_like_obj",
")",
"if",
"isinstance",
"(",
"file_like_obj",
",",
"sync_io",
".",
"TextIOWrapper",
")",
":",
"return",
"AsyncTextIOWrapperWrapper",
"(",
"file_like_obj",
")",
"raise",
"TypeError",
"(",
"'Unrecognized file stream type {}.'",
".",
"format",
"(",
"file_like_obj",
".",
"__class__",
")",
",",
")"
] |
Store action needs and excludes .
|
def set_action_cache ( self , action_key , data ) : if self . cache : self . cache . set ( self . app . config [ 'ACCESS_ACTION_CACHE_PREFIX' ] + action_key , data )
| 2,783
|
https://github.com/inveniosoftware/invenio-access/blob/3b033a4bdc110eb2f7e9f08f0744a780884bfc80/invenio_access/ext.py#L52-L64
|
[
"def",
"update_thumbnail_via_upload",
"(",
"api_key",
",",
"api_secret",
",",
"video_key",
",",
"local_video_image_path",
"=",
"''",
",",
"api_format",
"=",
"'json'",
",",
"*",
"*",
"kwargs",
")",
":",
"jwplatform_client",
"=",
"jwplatform",
".",
"Client",
"(",
"api_key",
",",
"api_secret",
")",
"logging",
".",
"info",
"(",
"\"Updating video thumbnail.\"",
")",
"try",
":",
"response",
"=",
"jwplatform_client",
".",
"videos",
".",
"thumbnails",
".",
"update",
"(",
"video_key",
"=",
"video_key",
",",
"*",
"*",
"kwargs",
")",
"except",
"jwplatform",
".",
"errors",
".",
"JWPlatformError",
"as",
"e",
":",
"logging",
".",
"error",
"(",
"\"Encountered an error updating thumbnail.\\n{}\"",
".",
"format",
"(",
"e",
")",
")",
"sys",
".",
"exit",
"(",
"e",
".",
"message",
")",
"logging",
".",
"info",
"(",
"response",
")",
"# Construct base url for upload",
"upload_url",
"=",
"'{}://{}{}'",
".",
"format",
"(",
"response",
"[",
"'link'",
"]",
"[",
"'protocol'",
"]",
",",
"response",
"[",
"'link'",
"]",
"[",
"'address'",
"]",
",",
"response",
"[",
"'link'",
"]",
"[",
"'path'",
"]",
")",
"# Query parameters for the upload",
"query_parameters",
"=",
"response",
"[",
"'link'",
"]",
"[",
"'query'",
"]",
"query_parameters",
"[",
"'api_format'",
"]",
"=",
"api_format",
"with",
"open",
"(",
"local_video_image_path",
",",
"'rb'",
")",
"as",
"f",
":",
"files",
"=",
"{",
"'file'",
":",
"f",
"}",
"r",
"=",
"requests",
".",
"post",
"(",
"upload_url",
",",
"params",
"=",
"query_parameters",
",",
"files",
"=",
"files",
")",
"logging",
".",
"info",
"(",
"'uploading file {} to url {}'",
".",
"format",
"(",
"local_video_image_path",
",",
"r",
".",
"url",
")",
")",
"logging",
".",
"info",
"(",
"'upload response: {}'",
".",
"format",
"(",
"r",
".",
"text",
")",
")"
] |
Get action needs and excludes from cache .
|
def get_action_cache ( self , action_key ) : data = None if self . cache : data = self . cache . get ( self . app . config [ 'ACCESS_ACTION_CACHE_PREFIX' ] + action_key ) return data
| 2,784
|
https://github.com/inveniosoftware/invenio-access/blob/3b033a4bdc110eb2f7e9f08f0744a780884bfc80/invenio_access/ext.py#L66-L80
|
[
"def",
"libvlc_log_set_file",
"(",
"p_instance",
",",
"stream",
")",
":",
"f",
"=",
"_Cfunctions",
".",
"get",
"(",
"'libvlc_log_set_file'",
",",
"None",
")",
"or",
"_Cfunction",
"(",
"'libvlc_log_set_file'",
",",
"(",
"(",
"1",
",",
")",
",",
"(",
"1",
",",
")",
",",
")",
",",
"None",
",",
"None",
",",
"Instance",
",",
"FILE_ptr",
")",
"return",
"f",
"(",
"p_instance",
",",
"stream",
")"
] |
Delete action needs and excludes from cache .
|
def delete_action_cache ( self , action_key ) : if self . cache : self . cache . delete ( self . app . config [ 'ACCESS_ACTION_CACHE_PREFIX' ] + action_key )
| 2,785
|
https://github.com/inveniosoftware/invenio-access/blob/3b033a4bdc110eb2f7e9f08f0744a780884bfc80/invenio_access/ext.py#L82-L93
|
[
"def",
"libvlc_log_set_file",
"(",
"p_instance",
",",
"stream",
")",
":",
"f",
"=",
"_Cfunctions",
".",
"get",
"(",
"'libvlc_log_set_file'",
",",
"None",
")",
"or",
"_Cfunction",
"(",
"'libvlc_log_set_file'",
",",
"(",
"(",
"1",
",",
")",
",",
"(",
"1",
",",
")",
",",
")",
",",
"None",
",",
"None",
",",
"Instance",
",",
"FILE_ptr",
")",
"return",
"f",
"(",
"p_instance",
",",
"stream",
")"
] |
Register an action to be showed in the actions list .
|
def register_action ( self , action ) : assert action . value not in self . actions self . actions [ action . value ] = action
| 2,786
|
https://github.com/inveniosoftware/invenio-access/blob/3b033a4bdc110eb2f7e9f08f0744a780884bfc80/invenio_access/ext.py#L95-L104
|
[
"def",
"build_vrt",
"(",
"source_file",
",",
"destination_file",
",",
"*",
"*",
"kwargs",
")",
":",
"with",
"rasterio",
".",
"open",
"(",
"source_file",
")",
"as",
"src",
":",
"vrt_doc",
"=",
"boundless_vrt_doc",
"(",
"src",
",",
"*",
"*",
"kwargs",
")",
".",
"tostring",
"(",
")",
"with",
"open",
"(",
"destination_file",
",",
"'wb'",
")",
"as",
"dst",
":",
"dst",
".",
"write",
"(",
"vrt_doc",
")",
"return",
"destination_file"
] |
Register a system role .
|
def register_system_role ( self , system_role ) : assert system_role . value not in self . system_roles self . system_roles [ system_role . value ] = system_role
| 2,787
|
https://github.com/inveniosoftware/invenio-access/blob/3b033a4bdc110eb2f7e9f08f0744a780884bfc80/invenio_access/ext.py#L114-L123
|
[
"def",
"edit_ticket",
"(",
"self",
",",
"ticket_id",
",",
"*",
"*",
"kwargs",
")",
":",
"post_data",
"=",
"''",
"for",
"key",
",",
"value",
"in",
"iteritems",
"(",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"value",
"=",
"\", \"",
".",
"join",
"(",
"value",
")",
"if",
"key",
"[",
":",
"3",
"]",
"!=",
"'CF_'",
":",
"post_data",
"+=",
"\"{}: {}\\n\"",
".",
"format",
"(",
"key",
",",
"value",
")",
"else",
":",
"post_data",
"+=",
"\"CF.{{{}}}: {}\\n\"",
".",
"format",
"(",
"key",
"[",
"3",
":",
"]",
",",
"value",
")",
"msg",
"=",
"self",
".",
"__request",
"(",
"'ticket/{}/edit'",
".",
"format",
"(",
"str",
"(",
"ticket_id",
")",
")",
",",
"post_data",
"=",
"{",
"'content'",
":",
"post_data",
"}",
")",
"state",
"=",
"msg",
".",
"split",
"(",
"'\\n'",
")",
"[",
"2",
"]",
"return",
"self",
".",
"RE_PATTERNS",
"[",
"'update_pattern'",
"]",
".",
"match",
"(",
"state",
")",
"is",
"not",
"None"
] |
Load system roles from an entry point group .
|
def load_entry_point_system_roles ( self , entry_point_group ) : for ep in pkg_resources . iter_entry_points ( group = entry_point_group ) : self . register_system_role ( ep . load ( ) )
| 2,788
|
https://github.com/inveniosoftware/invenio-access/blob/3b033a4bdc110eb2f7e9f08f0744a780884bfc80/invenio_access/ext.py#L125-L131
|
[
"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",
"(",
"in_file",
")",
")",
")",
"if",
"not",
"utils",
".",
"file_uptodate",
"(",
"out_file",
",",
"in_file",
")",
":",
"with",
"file_transaction",
"(",
"somatic_info",
".",
"tumor_data",
",",
"out_file",
")",
"as",
"tx_out_file",
":",
"with",
"open",
"(",
"in_file",
")",
"as",
"in_handle",
":",
"with",
"open",
"(",
"tx_out_file",
",",
"\"w\"",
")",
"as",
"out_handle",
":",
"out_handle",
".",
"write",
"(",
"in_handle",
".",
"readline",
"(",
")",
")",
"# header",
"for",
"line",
"in",
"in_handle",
":",
"parts",
"=",
"line",
".",
"split",
"(",
"\"\\t\"",
")",
"parts",
"[",
"1",
"]",
"=",
"_phylowgs_compatible_chroms",
"(",
"parts",
"[",
"1",
"]",
")",
"out_handle",
".",
"write",
"(",
"\"\\t\"",
".",
"join",
"(",
"parts",
")",
")",
"return",
"out_file"
] |
Parse argument and start main program .
|
def main ( argv = sys . argv [ 1 : ] ) : args = docopt ( __doc__ , argv = argv , version = pkg_resources . require ( 'buienradar' ) [ 0 ] . version ) level = logging . ERROR if args [ '-v' ] : level = logging . INFO if args [ '-v' ] == 2 : level = logging . DEBUG logging . basicConfig ( level = level ) log = logging . getLogger ( __name__ ) log . info ( "Start..." ) latitude = float ( args [ '--latitude' ] ) longitude = float ( args [ '--longitude' ] ) timeframe = int ( args [ '--timeframe' ] ) usexml = False if args [ '--usexml' ] : usexml = True result = get_data ( latitude , longitude , usexml ) if result [ SUCCESS ] : log . debug ( "Retrieved data:\n%s" , result ) result = parse_data ( result [ CONTENT ] , result [ RAINCONTENT ] , latitude , longitude , timeframe , usexml ) log . info ( "result: %s" , result ) print ( result ) else : log . error ( "Retrieving weather data was not successfull (%s)" , result [ MESSAGE ] )
| 2,789
|
https://github.com/mjj4791/python-buienradar/blob/a70436f54e007ce921d5210cb296cf3e4adf9d09/buienradar/__main__.py#L29-L62
|
[
"def",
"list_kadastrale_afdelingen",
"(",
"self",
")",
":",
"def",
"creator",
"(",
")",
":",
"gemeentes",
"=",
"self",
".",
"list_gemeenten",
"(",
")",
"res",
"=",
"[",
"]",
"for",
"g",
"in",
"gemeentes",
":",
"res",
"+=",
"self",
".",
"list_kadastrale_afdelingen_by_gemeente",
"(",
"g",
")",
"return",
"res",
"if",
"self",
".",
"caches",
"[",
"'permanent'",
"]",
".",
"is_configured",
":",
"key",
"=",
"'list_afdelingen_rest'",
"afdelingen",
"=",
"self",
".",
"caches",
"[",
"'permanent'",
"]",
".",
"get_or_create",
"(",
"key",
",",
"creator",
")",
"else",
":",
"afdelingen",
"=",
"creator",
"(",
")",
"return",
"afdelingen"
] |
Global achievement unlock percent .
|
def global_unlock_percent ( self ) : percent = CRef . cfloat ( ) result = self . _iface . get_ach_progress ( self . name , percent ) if not result : return 0.0 return float ( percent )
| 2,790
|
https://github.com/idlesign/steampak/blob/cb3f2c737e272b0360802d947e388df7e34f50f3/steampak/libsteam/resources/stats.py#L56-L67
|
[
"def",
"create_cloudwatch_log_event",
"(",
"app_name",
",",
"env",
",",
"region",
",",
"rules",
")",
":",
"session",
"=",
"boto3",
".",
"Session",
"(",
"profile_name",
"=",
"env",
",",
"region_name",
"=",
"region",
")",
"cloudwatch_client",
"=",
"session",
".",
"client",
"(",
"'logs'",
")",
"log_group",
"=",
"rules",
".",
"get",
"(",
"'log_group'",
")",
"filter_name",
"=",
"rules",
".",
"get",
"(",
"'filter_name'",
")",
"filter_pattern",
"=",
"rules",
".",
"get",
"(",
"'filter_pattern'",
")",
"if",
"not",
"log_group",
":",
"LOG",
".",
"critical",
"(",
"'Log group is required and no \"log_group\" is defined!'",
")",
"raise",
"InvalidEventConfiguration",
"(",
"'Log group is required and no \"log_group\" is defined!'",
")",
"if",
"not",
"filter_name",
":",
"LOG",
".",
"critical",
"(",
"'Filter name is required and no filter_name is defined!'",
")",
"raise",
"InvalidEventConfiguration",
"(",
"'Filter name is required and no filter_name is defined!'",
")",
"if",
"filter_pattern",
"is",
"None",
":",
"LOG",
".",
"critical",
"(",
"'Filter pattern is required and no filter_pattern is defined!'",
")",
"raise",
"InvalidEventConfiguration",
"(",
"'Filter pattern is required and no filter_pattern is defined!'",
")",
"lambda_alias_arn",
"=",
"get_lambda_alias_arn",
"(",
"app",
"=",
"app_name",
",",
"account",
"=",
"env",
",",
"region",
"=",
"region",
")",
"statement_id",
"=",
"'{}_cloudwatchlog_{}'",
".",
"format",
"(",
"app_name",
",",
"filter_name",
".",
"replace",
"(",
"\" \"",
",",
"\"_\"",
")",
")",
"principal",
"=",
"'logs.{}.amazonaws.com'",
".",
"format",
"(",
"region",
")",
"account_id",
"=",
"get_env_credential",
"(",
"env",
"=",
"env",
")",
"[",
"'accountId'",
"]",
"source_arn",
"=",
"\"arn:aws:logs:{0}:{1}:log-group:{2}:*\"",
".",
"format",
"(",
"region",
",",
"account_id",
",",
"log_group",
")",
"add_lambda_permissions",
"(",
"function",
"=",
"lambda_alias_arn",
",",
"statement_id",
"=",
"statement_id",
",",
"action",
"=",
"'lambda:InvokeFunction'",
",",
"principal",
"=",
"principal",
",",
"source_arn",
"=",
"source_arn",
",",
"env",
"=",
"env",
",",
"region",
"=",
"region",
")",
"cloudwatch_client",
".",
"put_subscription_filter",
"(",
"logGroupName",
"=",
"log_group",
",",
"filterName",
"=",
"filter_name",
",",
"filterPattern",
"=",
"filter_pattern",
",",
"destinationArn",
"=",
"lambda_alias_arn",
")",
"LOG",
".",
"info",
"(",
"\"Created Cloudwatch log event with filter: %s\"",
",",
"filter_pattern",
")"
] |
True if achievement is unlocked .
|
def unlocked ( self ) : achieved = CRef . cbool ( ) result = self . _iface . get_ach ( self . name , achieved ) if not result : return False return bool ( achieved )
| 2,791
|
https://github.com/idlesign/steampak/blob/cb3f2c737e272b0360802d947e388df7e34f50f3/steampak/libsteam/resources/stats.py#L78-L89
|
[
"def",
"connect",
"(",
"self",
",",
"db_uri",
",",
"debug",
"=",
"False",
")",
":",
"kwargs",
"=",
"{",
"'echo'",
":",
"debug",
",",
"'convert_unicode'",
":",
"True",
"}",
"# connect to the SQL database",
"if",
"'mysql'",
"in",
"db_uri",
":",
"kwargs",
"[",
"'pool_recycle'",
"]",
"=",
"3600",
"elif",
"'://'",
"not",
"in",
"db_uri",
":",
"logger",
".",
"debug",
"(",
"\"detected sqlite path URI: {}\"",
".",
"format",
"(",
"db_uri",
")",
")",
"db_path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"db_uri",
")",
")",
"db_uri",
"=",
"\"sqlite:///{}\"",
".",
"format",
"(",
"db_path",
")",
"self",
".",
"engine",
"=",
"create_engine",
"(",
"db_uri",
",",
"*",
"*",
"kwargs",
")",
"logger",
".",
"debug",
"(",
"'connection established successfully'",
")",
"# make sure the same engine is propagated to the BASE classes",
"BASE",
".",
"metadata",
".",
"bind",
"=",
"self",
".",
"engine",
"# start a session",
"self",
".",
"session",
"=",
"scoped_session",
"(",
"sessionmaker",
"(",
"bind",
"=",
"self",
".",
"engine",
")",
")",
"# shortcut to query method",
"self",
".",
"query",
"=",
"self",
".",
"session",
".",
"query",
"return",
"self"
] |
Unlocks the achievement .
|
def unlock ( self , store = True ) : result = self . _iface . ach_unlock ( self . name ) result and store and self . _store ( ) return result
| 2,792
|
https://github.com/idlesign/steampak/blob/cb3f2c737e272b0360802d947e388df7e34f50f3/steampak/libsteam/resources/stats.py#L91-L101
|
[
"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 the buienradar xml and rain data .
|
def __parse_ws_data ( content , latitude = 52.091579 , longitude = 5.119734 ) : log . info ( "Parse ws data: latitude: %s, longitude: %s" , latitude , longitude ) result = { SUCCESS : False , MESSAGE : None , DATA : None } # convert the xml data into a dictionary: try : xmldata = xmltodict . parse ( content ) [ __BRROOT ] except ( xmltodict . expat . ExpatError , KeyError ) : result [ MESSAGE ] = "Unable to parse content as xml." log . exception ( result [ MESSAGE ] ) return result # select the nearest weather station loc_data = __select_nearest_ws ( xmldata , latitude , longitude ) # process current weather data from selected weatherstation if not loc_data : result [ MESSAGE ] = 'No location selected.' return result if not __is_valid ( loc_data ) : result [ MESSAGE ] = 'Location data is invalid.' return result # add distance to weatherstation log . debug ( "Raw location data: %s" , loc_data ) result [ DISTANCE ] = __get_ws_distance ( loc_data , latitude , longitude ) result = __parse_loc_data ( loc_data , result ) # extract weather forecast try : fc_data = xmldata [ __BRWEERGEGEVENS ] [ __BRVERWACHTING ] except ( xmltodict . expat . ExpatError , KeyError ) : result [ MESSAGE ] = 'Unable to extract forecast data.' log . exception ( result [ MESSAGE ] ) return result if fc_data : # result = __parse_fc_data(fc_data, result) log . debug ( "Raw forecast data: %s" , fc_data ) # pylint: disable=unsupported-assignment-operation result [ DATA ] [ FORECAST ] = __parse_fc_data ( fc_data ) return result
| 2,793
|
https://github.com/mjj4791/python-buienradar/blob/a70436f54e007ce921d5210cb296cf3e4adf9d09/buienradar/buienradar_xml.py#L253-L296
|
[
"def",
"truncate_schema",
"(",
"self",
")",
":",
"assert",
"self",
".",
"server",
"==",
"'localhost'",
"con",
"=",
"self",
".",
"connection",
"or",
"self",
".",
"_connect",
"(",
")",
"self",
".",
"_initialize",
"(",
"con",
")",
"cur",
"=",
"con",
".",
"cursor",
"(",
")",
"cur",
".",
"execute",
"(",
"'DELETE FROM publication;'",
")",
"cur",
".",
"execute",
"(",
"'TRUNCATE systems CASCADE;'",
")",
"con",
".",
"commit",
"(",
")",
"con",
".",
"close",
"(",
")",
"return"
] |
Parse the xml data from selected weatherstation .
|
def __parse_loc_data ( loc_data , result ) : result [ DATA ] = { ATTRIBUTION : ATTRIBUTION_INFO , FORECAST : [ ] , PRECIPITATION_FORECAST : None } for key , [ value , func ] in SENSOR_TYPES . items ( ) : result [ DATA ] [ key ] = None try : from buienradar . buienradar import condition_from_code sens_data = loc_data [ value ] if key == CONDITION : # update weather symbol & status text code = sens_data [ __BRID ] [ : 1 ] result [ DATA ] [ CONDITION ] = condition_from_code ( code ) result [ DATA ] [ CONDITION ] [ IMAGE ] = sens_data [ __BRTEXT ] else : if key == STATIONNAME : name = sens_data [ __BRTEXT ] . replace ( "Meetstation" , "" ) name = name . strip ( ) name += " (%s)" % loc_data [ __BRSTATIONCODE ] result [ DATA ] [ key ] = name else : # update all other data if func is not None : result [ DATA ] [ key ] = func ( sens_data ) else : result [ DATA ] [ key ] = sens_data except KeyError : if result [ MESSAGE ] is None : result [ MESSAGE ] = "Missing key(s) in br data: " result [ MESSAGE ] += "%s " % value log . warning ( "Data element with key='%s' " "not loaded from br data!" , key ) result [ SUCCESS ] = True return result
| 2,794
|
https://github.com/mjj4791/python-buienradar/blob/a70436f54e007ce921d5210cb296cf3e4adf9d09/buienradar/buienradar_xml.py#L357-L392
|
[
"def",
"start_rest_api",
"(",
"host",
",",
"port",
",",
"connection",
",",
"timeout",
",",
"registry",
",",
"client_max_size",
"=",
"None",
")",
":",
"loop",
"=",
"asyncio",
".",
"get_event_loop",
"(",
")",
"connection",
".",
"open",
"(",
")",
"app",
"=",
"web",
".",
"Application",
"(",
"loop",
"=",
"loop",
",",
"client_max_size",
"=",
"client_max_size",
")",
"app",
".",
"on_cleanup",
".",
"append",
"(",
"lambda",
"app",
":",
"connection",
".",
"close",
"(",
")",
")",
"# Add routes to the web app",
"LOGGER",
".",
"info",
"(",
"'Creating handlers for validator at %s'",
",",
"connection",
".",
"url",
")",
"handler",
"=",
"RouteHandler",
"(",
"loop",
",",
"connection",
",",
"timeout",
",",
"registry",
")",
"app",
".",
"router",
".",
"add_post",
"(",
"'/batches'",
",",
"handler",
".",
"submit_batches",
")",
"app",
".",
"router",
".",
"add_get",
"(",
"'/batch_statuses'",
",",
"handler",
".",
"list_statuses",
")",
"app",
".",
"router",
".",
"add_post",
"(",
"'/batch_statuses'",
",",
"handler",
".",
"list_statuses",
")",
"app",
".",
"router",
".",
"add_get",
"(",
"'/state'",
",",
"handler",
".",
"list_state",
")",
"app",
".",
"router",
".",
"add_get",
"(",
"'/state/{address}'",
",",
"handler",
".",
"fetch_state",
")",
"app",
".",
"router",
".",
"add_get",
"(",
"'/blocks'",
",",
"handler",
".",
"list_blocks",
")",
"app",
".",
"router",
".",
"add_get",
"(",
"'/blocks/{block_id}'",
",",
"handler",
".",
"fetch_block",
")",
"app",
".",
"router",
".",
"add_get",
"(",
"'/batches'",
",",
"handler",
".",
"list_batches",
")",
"app",
".",
"router",
".",
"add_get",
"(",
"'/batches/{batch_id}'",
",",
"handler",
".",
"fetch_batch",
")",
"app",
".",
"router",
".",
"add_get",
"(",
"'/transactions'",
",",
"handler",
".",
"list_transactions",
")",
"app",
".",
"router",
".",
"add_get",
"(",
"'/transactions/{transaction_id}'",
",",
"handler",
".",
"fetch_transaction",
")",
"app",
".",
"router",
".",
"add_get",
"(",
"'/receipts'",
",",
"handler",
".",
"list_receipts",
")",
"app",
".",
"router",
".",
"add_post",
"(",
"'/receipts'",
",",
"handler",
".",
"list_receipts",
")",
"app",
".",
"router",
".",
"add_get",
"(",
"'/peers'",
",",
"handler",
".",
"fetch_peers",
")",
"app",
".",
"router",
".",
"add_get",
"(",
"'/status'",
",",
"handler",
".",
"fetch_status",
")",
"subscriber_handler",
"=",
"StateDeltaSubscriberHandler",
"(",
"connection",
")",
"app",
".",
"router",
".",
"add_get",
"(",
"'/subscriptions'",
",",
"subscriber_handler",
".",
"subscriptions",
")",
"app",
".",
"on_shutdown",
".",
"append",
"(",
"lambda",
"app",
":",
"subscriber_handler",
".",
"on_shutdown",
"(",
")",
")",
"# Start app",
"LOGGER",
".",
"info",
"(",
"'Starting REST API on %s:%s'",
",",
"host",
",",
"port",
")",
"web",
".",
"run_app",
"(",
"app",
",",
"host",
"=",
"host",
",",
"port",
"=",
"port",
",",
"access_log",
"=",
"LOGGER",
",",
"access_log_format",
"=",
"'%r: %s status, %b size, in %Tf s'",
")"
] |
Parse the forecast data from the xml section .
|
def __parse_fc_data ( fc_data ) : from buienradar . buienradar import condition_from_code fc = [ ] for daycnt in range ( 1 , 6 ) : daysection = __BRDAYFC % daycnt if daysection in fc_data : tmpsect = fc_data [ daysection ] fcdatetime = datetime . now ( pytz . timezone ( __TIMEZONE ) ) fcdatetime = fcdatetime . replace ( hour = 12 , minute = 0 , second = 0 , microsecond = 0 ) # add daycnt days fcdatetime = fcdatetime + timedelta ( days = daycnt ) code = tmpsect . get ( __BRICOON , [ ] ) . get ( __BRID ) fcdata = { CONDITION : condition_from_code ( code ) , TEMPERATURE : __get_float ( tmpsect , __BRMAXTEMP ) , MIN_TEMP : __get_float ( tmpsect , __BRMINTEMP ) , MAX_TEMP : __get_float ( tmpsect , __BRMAXTEMP ) , SUN_CHANCE : __get_int ( tmpsect , __BRKANSZON ) , RAIN_CHANCE : __get_int ( tmpsect , __BRKANSREGEN ) , RAIN : __get_float ( tmpsect , __BRMAXMMREGEN ) , SNOW : __get_float ( tmpsect , __BRSNEEUWCMS ) , WINDFORCE : __get_int ( tmpsect , __BRWINDKRACHT ) , DATETIME : fcdatetime , } fcdata [ CONDITION ] [ IMAGE ] = tmpsect . get ( __BRICOON , [ ] ) . get ( __BRTEXT ) fc . append ( fcdata ) return fc
| 2,795
|
https://github.com/mjj4791/python-buienradar/blob/a70436f54e007ce921d5210cb296cf3e4adf9d09/buienradar/buienradar_xml.py#L395-L426
|
[
"def",
"factor_aug",
"(",
"z",
",",
"DPhival",
",",
"G",
",",
"A",
")",
":",
"M",
",",
"N",
"=",
"G",
".",
"shape",
"P",
",",
"N",
"=",
"A",
".",
"shape",
"\"\"\"Multiplier for inequality constraints\"\"\"",
"l",
"=",
"z",
"[",
"N",
"+",
"P",
":",
"N",
"+",
"P",
"+",
"M",
"]",
"\"\"\"Slacks\"\"\"",
"s",
"=",
"z",
"[",
"N",
"+",
"P",
"+",
"M",
":",
"]",
"\"\"\"Sigma matrix\"\"\"",
"SIG",
"=",
"diags",
"(",
"l",
"/",
"s",
",",
"0",
")",
"# SIG = diags(l*s, 0)",
"\"\"\"Convert A\"\"\"",
"if",
"not",
"issparse",
"(",
"A",
")",
":",
"A",
"=",
"csr_matrix",
"(",
"A",
")",
"\"\"\"Convert G\"\"\"",
"if",
"not",
"issparse",
"(",
"G",
")",
":",
"G",
"=",
"csr_matrix",
"(",
"G",
")",
"\"\"\"Since we expect symmetric DPhival, we need to change A\"\"\"",
"sign",
"=",
"np",
".",
"zeros",
"(",
"N",
")",
"sign",
"[",
"0",
":",
"N",
"//",
"2",
"]",
"=",
"1.0",
"sign",
"[",
"N",
"//",
"2",
":",
"]",
"=",
"-",
"1.0",
"T",
"=",
"diags",
"(",
"sign",
",",
"0",
")",
"A_new",
"=",
"A",
".",
"dot",
"(",
"T",
")",
"W",
"=",
"AugmentedSystem",
"(",
"DPhival",
",",
"G",
",",
"SIG",
",",
"A_new",
")",
"return",
"W"
] |
Get the distance to the weatherstation from wstation section of xml .
|
def __get_ws_distance ( wstation , latitude , longitude ) : if wstation : try : wslat = float ( wstation [ __BRLAT ] ) wslon = float ( wstation [ __BRLON ] ) dist = vincenty ( ( latitude , longitude ) , ( wslat , wslon ) ) log . debug ( "calc distance: %s (latitude: %s, longitude: " "%s, wslat: %s, wslon: %s)" , dist , latitude , longitude , wslat , wslon ) return dist except ( ValueError , TypeError , KeyError ) : # value does not exist, or is not a float return None else : return None
| 2,796
|
https://github.com/mjj4791/python-buienradar/blob/a70436f54e007ce921d5210cb296cf3e4adf9d09/buienradar/buienradar_xml.py#L445-L466
|
[
"def",
"retino_colors",
"(",
"vcolorfn",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"0",
":",
"def",
"_retino_color_pass",
"(",
"*",
"args",
",",
"*",
"*",
"new_kwargs",
")",
":",
"return",
"retino_colors",
"(",
"vcolorfn",
",",
"*",
"args",
",",
"*",
"*",
"{",
"k",
":",
"(",
"new_kwargs",
"[",
"k",
"]",
"if",
"k",
"in",
"new_kwargs",
"else",
"kwargs",
"[",
"k",
"]",
")",
"for",
"k",
"in",
"set",
"(",
"kwargs",
".",
"keys",
"(",
")",
"+",
"new_kwargs",
".",
"keys",
"(",
")",
")",
"}",
")",
"return",
"_retino_color_pass",
"elif",
"len",
"(",
"args",
")",
">",
"1",
":",
"raise",
"ValueError",
"(",
"'retinotopy color functions accepts at most one argument'",
")",
"m",
"=",
"args",
"[",
"0",
"]",
"# we need to handle the arguments",
"if",
"isinstance",
"(",
"m",
",",
"(",
"geo",
".",
"VertexSet",
",",
"pimms",
".",
"ITable",
")",
")",
":",
"tbl",
"=",
"m",
".",
"properties",
"if",
"isinstance",
"(",
"m",
",",
"geo",
".",
"VertexSet",
")",
"else",
"m",
"n",
"=",
"tbl",
".",
"row_count",
"# if the weight or property arguments are lists, we need to thread these along",
"if",
"'property'",
"in",
"kwargs",
":",
"props",
"=",
"kwargs",
"[",
"'property'",
"]",
"del",
"kwargs",
"[",
"'property'",
"]",
"if",
"not",
"(",
"pimms",
".",
"is_vector",
"(",
"props",
")",
"or",
"pimms",
".",
"is_matrix",
"(",
"props",
")",
")",
":",
"props",
"=",
"[",
"props",
"for",
"_",
"in",
"range",
"(",
"n",
")",
"]",
"else",
":",
"props",
"=",
"None",
"if",
"'weight'",
"in",
"kwargs",
":",
"ws",
"=",
"kwargs",
"[",
"'weight'",
"]",
"del",
"kwargs",
"[",
"'weight'",
"]",
"if",
"not",
"pimms",
".",
"is_vector",
"(",
"ws",
")",
"and",
"not",
"pimms",
".",
"is_matrix",
"(",
"ws",
")",
":",
"ws",
"=",
"[",
"ws",
"for",
"_",
"in",
"range",
"(",
"n",
")",
"]",
"else",
":",
"ws",
"=",
"None",
"vcolorfn0",
"=",
"vcolorfn",
"(",
"Ellipsis",
",",
"*",
"*",
"kwargs",
")",
"if",
"len",
"(",
"kwargs",
")",
">",
"0",
"else",
"vcolorfn",
"if",
"props",
"is",
"None",
"and",
"ws",
"is",
"None",
":",
"vcfn",
"=",
"lambda",
"m",
",",
"k",
":",
"vcolorfn0",
"(",
"m",
")",
"elif",
"props",
"is",
"None",
":",
"vcfn",
"=",
"lambda",
"m",
",",
"k",
":",
"vcolorfn0",
"(",
"m",
",",
"weight",
"=",
"ws",
"[",
"k",
"]",
")",
"elif",
"ws",
"is",
"None",
":",
"vcfn",
"=",
"lambda",
"m",
",",
"k",
":",
"vcolorfn0",
"(",
"m",
",",
"property",
"=",
"props",
"[",
"k",
"]",
")",
"else",
":",
"vcfn",
"=",
"lambda",
"m",
",",
"k",
":",
"vcolorfn0",
"(",
"m",
",",
"property",
"=",
"props",
"[",
"k",
"]",
",",
"weight",
"=",
"ws",
"[",
"k",
"]",
")",
"return",
"np",
".",
"asarray",
"(",
"[",
"vcfn",
"(",
"r",
",",
"kk",
")",
"for",
"(",
"kk",
",",
"r",
")",
"in",
"enumerate",
"(",
"tbl",
".",
"rows",
")",
"]",
")",
"else",
":",
"return",
"vcolorfn",
"(",
"m",
",",
"*",
"*",
"kwargs",
")"
] |
Predict binding for each peptide in peptfile to allele using the IEDB mhcii binding prediction tool .
|
def predict_mhcii_binding ( job , peptfile , allele , univ_options , mhcii_options ) : work_dir = os . getcwd ( ) input_files = { 'peptfile.faa' : peptfile } input_files = get_files_from_filestore ( job , input_files , work_dir , docker = True ) peptides = read_peptide_file ( os . path . join ( os . getcwd ( ) , 'peptfile.faa' ) ) parameters = [ mhcii_options [ 'pred' ] , allele , input_files [ 'peptfile.faa' ] ] if not peptides : return job . fileStore . writeGlobalFile ( job . fileStore . getLocalTempFile ( ) ) , None with open ( '/' . join ( [ work_dir , 'predictions.tsv' ] ) , 'w' ) as predfile : docker_call ( tool = 'mhcii' , tool_parameters = parameters , work_dir = work_dir , dockerhub = univ_options [ 'dockerhub' ] , outfile = predfile , interactive = True , tool_version = mhcii_options [ 'version' ] ) run_netmhciipan = True predictor = None with open ( predfile . name , 'r' ) as predfile : for line in predfile : if not line . startswith ( 'HLA' ) : continue if line . strip ( ) . split ( '\t' ) [ 5 ] == 'NetMHCIIpan' : break # If the predictor type is sturniolo then it needs to be processed differently elif line . strip ( ) . split ( '\t' ) [ 5 ] == 'Sturniolo' : predictor = 'Sturniolo' else : predictor = 'Consensus' run_netmhciipan = False break if run_netmhciipan : netmhciipan = job . addChildJobFn ( predict_netmhcii_binding , peptfile , allele , univ_options , mhcii_options [ 'netmhciipan' ] , disk = '100M' , memory = '100M' , cores = 1 ) job . fileStore . logToMaster ( 'Ran mhcii on %s:%s successfully' % ( univ_options [ 'patient' ] , allele ) ) return netmhciipan . rv ( ) else : output_file = job . fileStore . writeGlobalFile ( predfile . name ) job . fileStore . logToMaster ( 'Ran mhcii on %s:%s successfully' % ( univ_options [ 'patient' ] , allele ) ) return output_file , predictor
| 2,797
|
https://github.com/BD2KGenomics/protect/blob/06310682c50dcf8917b912c8e551299ff7ee41ce/src/protect/binding_prediction/mhcii.py#L24-L76
|
[
"def",
"gc_velocity_update",
"(",
"particle",
",",
"social",
",",
"state",
")",
":",
"gbest",
"=",
"state",
".",
"swarm",
"[",
"gbest_idx",
"(",
"state",
".",
"swarm",
")",
"]",
".",
"position",
"if",
"not",
"np",
".",
"array_equal",
"(",
"gbest",
",",
"particle",
".",
"position",
")",
":",
"return",
"std_velocity",
"(",
"particle",
",",
"social",
",",
"state",
")",
"rho",
"=",
"state",
".",
"params",
"[",
"'rho'",
"]",
"inertia",
"=",
"state",
".",
"params",
"[",
"'inertia'",
"]",
"v_max",
"=",
"state",
".",
"params",
"[",
"'v_max'",
"]",
"size",
"=",
"particle",
".",
"position",
".",
"size",
"r2",
"=",
"state",
".",
"rng",
".",
"uniform",
"(",
"0.0",
",",
"1.0",
",",
"size",
")",
"velocity",
"=",
"__gc_velocity_equation__",
"(",
"inertia",
",",
"rho",
",",
"r2",
",",
"particle",
",",
"gbest",
")",
"return",
"__clamp__",
"(",
"velocity",
",",
"v_max",
")"
] |
Predict binding for each peptide in peptfile to allele using netMHCIIpan .
|
def predict_netmhcii_binding ( job , peptfile , allele , univ_options , netmhciipan_options ) : work_dir = os . getcwd ( ) input_files = { 'peptfile.faa' : peptfile } input_files = get_files_from_filestore ( job , input_files , work_dir , docker = True ) peptides = read_peptide_file ( os . path . join ( os . getcwd ( ) , 'peptfile.faa' ) ) if not peptides : return job . fileStore . writeGlobalFile ( job . fileStore . getLocalTempFile ( ) ) , None # netMHCIIpan accepts differently formatted alleles so we need to modify the input alleles if allele . startswith ( 'HLA-DQA' ) or allele . startswith ( 'HLA-DPA' ) : allele = re . sub ( r'[*:]' , '' , allele ) allele = re . sub ( r'/' , '-' , allele ) elif allele . startswith ( 'HLA-DRB' ) : allele = re . sub ( r':' , '' , allele ) allele = re . sub ( r'\*' , '_' , allele ) allele = allele . lstrip ( 'HLA-' ) else : raise RuntimeError ( 'Unknown allele seen' ) parameters = [ '-a' , allele , '-xls' , '1' , '-xlsfile' , 'predictions.tsv' , '-f' , input_files [ 'peptfile.faa' ] ] # netMHC writes a lot of useless stuff to sys.stdout so we open /dev/null and dump output there. with open ( os . devnull , 'w' ) as output_catcher : docker_call ( tool = 'netmhciipan' , tool_parameters = parameters , work_dir = work_dir , dockerhub = univ_options [ 'dockerhub' ] , outfile = output_catcher , tool_version = netmhciipan_options [ 'version' ] ) output_file = job . fileStore . writeGlobalFile ( '/' . join ( [ work_dir , 'predictions.tsv' ] ) ) job . fileStore . logToMaster ( 'Ran netmhciipan on %s successfully' % allele ) return output_file , 'netMHCIIpan'
| 2,798
|
https://github.com/BD2KGenomics/protect/blob/06310682c50dcf8917b912c8e551299ff7ee41ce/src/protect/binding_prediction/mhcii.py#L79-L118
|
[
"def",
"remove_obsolete_folders",
"(",
"states",
",",
"path",
")",
":",
"elements_in_folder",
"=",
"os",
".",
"listdir",
"(",
"path",
")",
"# find all state folder elements in system path",
"state_folders_in_file_system",
"=",
"[",
"]",
"for",
"folder_name",
"in",
"elements_in_folder",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"folder_name",
",",
"FILE_NAME_CORE_DATA",
")",
")",
"or",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"folder_name",
",",
"FILE_NAME_CORE_DATA_OLD",
")",
")",
":",
"state_folders_in_file_system",
".",
"append",
"(",
"folder_name",
")",
"# remove elements used by existing states and storage format",
"for",
"state",
"in",
"states",
":",
"storage_folder_for_state",
"=",
"get_storage_id_for_state",
"(",
"state",
")",
"if",
"storage_folder_for_state",
"in",
"state_folders_in_file_system",
":",
"state_folders_in_file_system",
".",
"remove",
"(",
"storage_folder_for_state",
")",
"# remove the remaining state folders",
"for",
"folder_name",
"in",
"state_folders_in_file_system",
":",
"shutil",
".",
"rmtree",
"(",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"folder_name",
")",
")"
] |
In - place update of permissions .
|
def update ( self , permission ) : self . needs . update ( permission . needs ) self . excludes . update ( permission . excludes )
| 2,799
|
https://github.com/inveniosoftware/invenio-access/blob/3b033a4bdc110eb2f7e9f08f0744a780884bfc80/invenio_access/permissions.py#L61-L64
|
[
"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",
")"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.