query
stringlengths 5
1.23k
| positive
stringlengths 53
15.2k
| id_
int64 0
252k
| task_name
stringlengths 87
242
| negative
listlengths 20
553
|
|---|---|---|---|---|
Return method tagged order in the handler .
|
def orders ( self ) : return [ order_cmd for order_cmd in dir ( self . handler ) if getattr ( getattr ( self . handler , order_cmd ) , "bot_order" , False ) ]
| 3,300
|
https://github.com/Azure/azure-python-devtools/blob/2bf87b1f3cedd2b26fb2e4fd47a9baf435dcf936/src/azure_devtools/ci_tools/bot_framework.py#L80-L84
|
[
"def",
"remove",
"(",
"self",
",",
"obj",
")",
":",
"relationship_table",
"=",
"self",
".",
"params",
"[",
"'relationship_table'",
"]",
"with",
"self",
".",
"obj",
".",
"backend",
".",
"transaction",
"(",
"implicit",
"=",
"True",
")",
":",
"condition",
"=",
"and_",
"(",
"relationship_table",
".",
"c",
"[",
"self",
".",
"params",
"[",
"'related_pk_field_name'",
"]",
"]",
"==",
"obj",
".",
"pk",
",",
"relationship_table",
".",
"c",
"[",
"self",
".",
"params",
"[",
"'pk_field_name'",
"]",
"]",
"==",
"self",
".",
"obj",
".",
"pk",
")",
"self",
".",
"obj",
".",
"backend",
".",
"connection",
".",
"execute",
"(",
"delete",
"(",
"relationship_table",
")",
".",
"where",
"(",
"condition",
")",
")",
"self",
".",
"_queryset",
"=",
"None"
] |
Sets the value of the field name to value which is True or False .
|
def set ( self , name , value ) : flag = self . flags [ name ] self . _value = ( self . value | flag ) if value else ( self . value & ~ flag )
| 3,301
|
https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/util/flags.py#L40-L46
|
[
"def",
"export_as_string",
"(",
"self",
")",
":",
"if",
"self",
".",
"_exc_info",
":",
"import",
"traceback",
"ret",
"=",
"\"/*\\nWarning: Table %s.%s is incomplete because of an error processing metadata.\\n\"",
"%",
"(",
"self",
".",
"keyspace_name",
",",
"self",
".",
"name",
")",
"for",
"line",
"in",
"traceback",
".",
"format_exception",
"(",
"*",
"self",
".",
"_exc_info",
")",
":",
"ret",
"+=",
"line",
"ret",
"+=",
"\"\\nApproximate structure, for reference:\\n(this should not be used to reproduce this schema)\\n\\n%s\\n*/\"",
"%",
"self",
".",
"_all_as_cql",
"(",
")",
"elif",
"not",
"self",
".",
"is_cql_compatible",
":",
"# If we can't produce this table with CQL, comment inline",
"ret",
"=",
"\"/*\\nWarning: Table %s.%s omitted because it has constructs not compatible with CQL (was created via legacy API).\\n\"",
"%",
"(",
"self",
".",
"keyspace_name",
",",
"self",
".",
"name",
")",
"ret",
"+=",
"\"\\nApproximate structure, for reference:\\n(this should not be used to reproduce this schema)\\n\\n%s\\n*/\"",
"%",
"self",
".",
"_all_as_cql",
"(",
")",
"elif",
"self",
".",
"virtual",
":",
"ret",
"=",
"(",
"'/*\\nWarning: Table {ks}.{tab} is a virtual table and cannot be recreated with CQL.\\n'",
"'Structure, for reference:\\n'",
"'{cql}\\n*/'",
")",
".",
"format",
"(",
"ks",
"=",
"self",
".",
"keyspace_name",
",",
"tab",
"=",
"self",
".",
"name",
",",
"cql",
"=",
"self",
".",
"_all_as_cql",
"(",
")",
")",
"else",
":",
"ret",
"=",
"self",
".",
"_all_as_cql",
"(",
")",
"return",
"ret"
] |
Returns this Flags object s fields as a dictionary .
|
def to_dict ( self ) : return dict ( ( k , self . get ( k ) ) for k in self . flags . keys ( ) )
| 3,302
|
https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/util/flags.py#L58-L62
|
[
"def",
"temperature_hub",
"(",
"self",
",",
"weather_df",
")",
":",
"if",
"self",
".",
"power_plant",
".",
"hub_height",
"in",
"weather_df",
"[",
"'temperature'",
"]",
":",
"temperature_hub",
"=",
"weather_df",
"[",
"'temperature'",
"]",
"[",
"self",
".",
"power_plant",
".",
"hub_height",
"]",
"elif",
"self",
".",
"temperature_model",
"==",
"'linear_gradient'",
":",
"logging",
".",
"debug",
"(",
"'Calculating temperature using temperature '",
"'gradient.'",
")",
"closest_height",
"=",
"weather_df",
"[",
"'temperature'",
"]",
".",
"columns",
"[",
"min",
"(",
"range",
"(",
"len",
"(",
"weather_df",
"[",
"'temperature'",
"]",
".",
"columns",
")",
")",
",",
"key",
"=",
"lambda",
"i",
":",
"abs",
"(",
"weather_df",
"[",
"'temperature'",
"]",
".",
"columns",
"[",
"i",
"]",
"-",
"self",
".",
"power_plant",
".",
"hub_height",
")",
")",
"]",
"temperature_hub",
"=",
"temperature",
".",
"linear_gradient",
"(",
"weather_df",
"[",
"'temperature'",
"]",
"[",
"closest_height",
"]",
",",
"closest_height",
",",
"self",
".",
"power_plant",
".",
"hub_height",
")",
"elif",
"self",
".",
"temperature_model",
"==",
"'interpolation_extrapolation'",
":",
"logging",
".",
"debug",
"(",
"'Calculating temperature using linear inter- or '",
"'extrapolation.'",
")",
"temperature_hub",
"=",
"tools",
".",
"linear_interpolation_extrapolation",
"(",
"weather_df",
"[",
"'temperature'",
"]",
",",
"self",
".",
"power_plant",
".",
"hub_height",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"'{0}' is an invalid value. \"",
".",
"format",
"(",
"self",
".",
"temperature_model",
")",
"+",
"\"`temperature_model` must be \"",
"\"'linear_gradient' or 'interpolation_extrapolation'.\"",
")",
"return",
"temperature_hub"
] |
Add the given value to the collection .
|
def add ( self , host_value ) : host_obj = self . _host_factory ( host_value ) if self . _get_match ( host_obj ) is not None : return self . _add_new ( host_obj )
| 3,303
|
https://github.com/piotr-rusin/spam-lists/blob/fd616e8761b28f3eaa503fee5e45f7748e8f88f2/spam_lists/host_collections.py#L64-L74
|
[
"def",
"parse",
"(",
"data",
"=",
"None",
",",
"template",
"=",
"None",
",",
"data_file",
"=",
"None",
",",
"template_file",
"=",
"None",
",",
"interp",
"=",
"None",
",",
"debug",
"=",
"False",
",",
"predefines",
"=",
"True",
",",
"int3",
"=",
"True",
",",
"keep_successful",
"=",
"False",
",",
"printf",
"=",
"True",
",",
")",
":",
"if",
"data",
"is",
"None",
"and",
"data_file",
"is",
"None",
":",
"raise",
"Exception",
"(",
"\"No input data was specified\"",
")",
"if",
"data",
"is",
"not",
"None",
"and",
"data_file",
"is",
"not",
"None",
":",
"raise",
"Exception",
"(",
"\"Only one input data may be specified\"",
")",
"if",
"isinstance",
"(",
"data",
",",
"six",
".",
"string_types",
")",
":",
"data",
"=",
"six",
".",
"StringIO",
"(",
"data",
")",
"if",
"data_file",
"is",
"not",
"None",
":",
"data",
"=",
"open",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"data_file",
")",
",",
"\"rb\"",
")",
"if",
"template",
"is",
"None",
"and",
"template_file",
"is",
"None",
":",
"raise",
"Exception",
"(",
"\"No template specified!\"",
")",
"if",
"template",
"is",
"not",
"None",
"and",
"template_file",
"is",
"not",
"None",
":",
"raise",
"Exception",
"(",
"\"Only one template may be specified!\"",
")",
"orig_filename",
"=",
"\"string\"",
"if",
"template_file",
"is",
"not",
"None",
":",
"orig_filename",
"=",
"template_file",
"try",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"template_file",
")",
",",
"\"r\"",
")",
"as",
"f",
":",
"template",
"=",
"f",
".",
"read",
"(",
")",
"except",
"Exception",
"as",
"e",
":",
"raise",
"Exception",
"(",
"\"Could not open template file '{}'\"",
".",
"format",
"(",
"template_file",
")",
")",
"# the user may specify their own instance of PfpInterp to be",
"# used",
"if",
"interp",
"is",
"None",
":",
"interp",
"=",
"pfp",
".",
"interp",
".",
"PfpInterp",
"(",
"debug",
"=",
"debug",
",",
"parser",
"=",
"PARSER",
",",
"int3",
"=",
"int3",
",",
")",
"# so we can consume single bits at a time",
"data",
"=",
"BitwrappedStream",
"(",
"data",
")",
"dom",
"=",
"interp",
".",
"parse",
"(",
"data",
",",
"template",
",",
"predefines",
"=",
"predefines",
",",
"orig_filename",
"=",
"orig_filename",
",",
"keep_successful",
"=",
"keep_successful",
",",
"printf",
"=",
"printf",
",",
")",
"# close the data stream if a data_file was specified",
"if",
"data_file",
"is",
"not",
"None",
":",
"data",
".",
"close",
"(",
")",
"return",
"dom"
] |
Get an item matching the given host object .
|
def _get_match ( self , host_object ) : i = self . _get_insertion_point ( host_object ) potential_match = None try : potential_match = self [ i - 1 ] except IndexError : pass if host_object . is_match ( potential_match ) : return potential_match return None
| 3,304
|
https://github.com/piotr-rusin/spam-lists/blob/fd616e8761b28f3eaa503fee5e45f7748e8f88f2/spam_lists/host_collections.py#L118-L138
|
[
"def",
"_wrap_definition_section",
"(",
"source",
",",
"width",
")",
":",
"# type: (str, int) -> str",
"index",
"=",
"source",
".",
"index",
"(",
"'\\n'",
")",
"+",
"1",
"definitions",
",",
"max_len",
"=",
"_get_definitions",
"(",
"source",
"[",
"index",
":",
"]",
")",
"sep",
"=",
"'\\n'",
"+",
"' '",
"*",
"(",
"max_len",
"+",
"4",
")",
"lines",
"=",
"[",
"source",
"[",
":",
"index",
"]",
".",
"strip",
"(",
")",
"]",
"for",
"arg",
",",
"desc",
"in",
"six",
".",
"iteritems",
"(",
"definitions",
")",
":",
"wrapped_desc",
"=",
"sep",
".",
"join",
"(",
"textwrap",
".",
"wrap",
"(",
"desc",
",",
"width",
"-",
"max_len",
"-",
"4",
")",
")",
"lines",
".",
"append",
"(",
"' {arg:{size}} {desc}'",
".",
"format",
"(",
"arg",
"=",
"arg",
",",
"size",
"=",
"str",
"(",
"max_len",
")",
",",
"desc",
"=",
"wrapped_desc",
")",
")",
"return",
"'\\n'",
".",
"join",
"(",
"lines",
")"
] |
Add a new host to the collection .
|
def _add_new ( self , host_object ) : i = self . _get_insertion_point ( host_object ) for listed in self [ i : ] : if not listed . is_subdomain ( host_object ) : break self . hosts . pop ( i ) self . hosts . insert ( i , host_object . to_unicode ( ) )
| 3,305
|
https://github.com/piotr-rusin/spam-lists/blob/fd616e8761b28f3eaa503fee5e45f7748e8f88f2/spam_lists/host_collections.py#L140-L160
|
[
"def",
"get_revision",
"(",
")",
":",
"git_bin",
"=",
"smoke_zephyr",
".",
"utilities",
".",
"which",
"(",
"'git'",
")",
"if",
"not",
"git_bin",
":",
"return",
"None",
"proc_h",
"=",
"subprocess",
".",
"Popen",
"(",
"(",
"git_bin",
",",
"'rev-parse'",
",",
"'HEAD'",
")",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
",",
"close_fds",
"=",
"True",
",",
"cwd",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"__file__",
")",
")",
")",
"rev",
"=",
"proc_h",
".",
"stdout",
".",
"read",
"(",
")",
".",
"strip",
"(",
")",
"proc_h",
".",
"wait",
"(",
")",
"if",
"not",
"len",
"(",
"rev",
")",
":",
"return",
"None",
"return",
"rev",
".",
"decode",
"(",
"'utf-8'",
")"
] |
Parses a Method descriptor as described in section 4 . 3 . 3 of the JVM specification .
|
def method_descriptor ( descriptor : str ) -> MethodDescriptor : end_para = descriptor . find ( ')' ) returns = descriptor [ end_para + 1 : ] args = descriptor [ 1 : end_para ] return MethodDescriptor ( parse_descriptor ( returns ) [ 0 ] , parse_descriptor ( args ) , returns , args , descriptor )
| 3,306
|
https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/util/descriptor.py#L22-L37
|
[
"def",
"reindex",
"(",
"clear",
":",
"bool",
",",
"progressive",
":",
"bool",
",",
"batch_size",
":",
"int",
")",
":",
"reindexer",
"=",
"Reindexer",
"(",
"clear",
",",
"progressive",
",",
"batch_size",
")",
"reindexer",
".",
"reindex_all",
"(",
")"
] |
create serializer field
|
def make_field ( self , * * kwargs ) : kwargs [ 'required' ] = False kwargs [ 'allow_null' ] = True return self . field_class ( * * kwargs )
| 3,307
|
https://github.com/qwiglydee/drf-mongo-filters/blob/f7e397c329bac6d7b8cbb1df70d96eccdcfbc1ec/drf_mongo_filters/filters.py#L48-L52
|
[
"def",
"restore",
"(",
"archive",
",",
"oqdata",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"oqdata",
")",
":",
"sys",
".",
"exit",
"(",
"'%s exists already'",
"%",
"oqdata",
")",
"if",
"'://'",
"in",
"archive",
":",
"# get the zip archive from an URL",
"resp",
"=",
"requests",
".",
"get",
"(",
"archive",
")",
"_",
",",
"archive",
"=",
"archive",
".",
"rsplit",
"(",
"'/'",
",",
"1",
")",
"with",
"open",
"(",
"archive",
",",
"'wb'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"resp",
".",
"content",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"archive",
")",
":",
"sys",
".",
"exit",
"(",
"'%s does not exist'",
"%",
"archive",
")",
"t0",
"=",
"time",
".",
"time",
"(",
")",
"oqdata",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"oqdata",
")",
"assert",
"archive",
".",
"endswith",
"(",
"'.zip'",
")",
",",
"archive",
"os",
".",
"mkdir",
"(",
"oqdata",
")",
"zipfile",
".",
"ZipFile",
"(",
"archive",
")",
".",
"extractall",
"(",
"oqdata",
")",
"dbpath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"oqdata",
",",
"'db.sqlite3'",
")",
"db",
"=",
"Db",
"(",
"sqlite3",
".",
"connect",
",",
"dbpath",
",",
"isolation_level",
"=",
"None",
",",
"detect_types",
"=",
"sqlite3",
".",
"PARSE_DECLTYPES",
")",
"n",
"=",
"0",
"for",
"fname",
"in",
"os",
".",
"listdir",
"(",
"oqdata",
")",
":",
"mo",
"=",
"re",
".",
"match",
"(",
"'calc_(\\d+)\\.hdf5'",
",",
"fname",
")",
"if",
"mo",
":",
"job_id",
"=",
"int",
"(",
"mo",
".",
"group",
"(",
"1",
")",
")",
"fullname",
"=",
"os",
".",
"path",
".",
"join",
"(",
"oqdata",
",",
"fname",
")",
"[",
":",
"-",
"5",
"]",
"# strip .hdf5",
"db",
"(",
"\"UPDATE job SET user_name=?x, ds_calc_dir=?x WHERE id=?x\"",
",",
"getpass",
".",
"getuser",
"(",
")",
",",
"fullname",
",",
"job_id",
")",
"safeprint",
"(",
"'Restoring '",
"+",
"fname",
")",
"n",
"+=",
"1",
"dt",
"=",
"time",
".",
"time",
"(",
")",
"-",
"t0",
"safeprint",
"(",
"'Extracted %d calculations into %s in %d seconds'",
"%",
"(",
"n",
",",
"oqdata",
",",
"dt",
")",
")"
] |
attach filter to filterset
|
def bind ( self , name , filterset ) : if self . name is not None : name = self . name self . field . bind ( name , self )
| 3,308
|
https://github.com/qwiglydee/drf-mongo-filters/blob/f7e397c329bac6d7b8cbb1df70d96eccdcfbc1ec/drf_mongo_filters/filters.py#L54-L61
|
[
"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"
] |
Return the base directory
|
def get_base_dir ( ) : return os . path . split ( os . path . abspath ( os . path . dirname ( __file__ ) ) ) [ 0 ]
| 3,309
|
https://github.com/mardix/pylot/blob/506a33a56ebdfc0925b94015e8cf98ccb16a143c/pylot/utils.py#L20-L24
|
[
"def",
"parse_wrap_facets",
"(",
"facets",
")",
":",
"valid_forms",
"=",
"[",
"'~ var1'",
",",
"'~ var1 + var2'",
"]",
"error_msg",
"=",
"(",
"\"Valid formula for 'facet_wrap' look like\"",
"\" {}\"",
".",
"format",
"(",
"valid_forms",
")",
")",
"if",
"isinstance",
"(",
"facets",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"return",
"facets",
"if",
"not",
"isinstance",
"(",
"facets",
",",
"str",
")",
":",
"raise",
"PlotnineError",
"(",
"error_msg",
")",
"if",
"'~'",
"in",
"facets",
":",
"variables_pattern",
"=",
"r'(\\w+(?:\\s*\\+\\s*\\w+)*|\\.)'",
"pattern",
"=",
"r'\\s*~\\s*{0}\\s*'",
".",
"format",
"(",
"variables_pattern",
")",
"match",
"=",
"re",
".",
"match",
"(",
"pattern",
",",
"facets",
")",
"if",
"not",
"match",
":",
"raise",
"PlotnineError",
"(",
"error_msg",
")",
"facets",
"=",
"[",
"var",
".",
"strip",
"(",
")",
"for",
"var",
"in",
"match",
".",
"group",
"(",
"1",
")",
".",
"split",
"(",
"'+'",
")",
"]",
"elif",
"re",
".",
"match",
"(",
"r'\\w+'",
",",
"facets",
")",
":",
"# allow plain string as the variable name",
"facets",
"=",
"[",
"facets",
"]",
"else",
":",
"raise",
"PlotnineError",
"(",
"error_msg",
")",
"return",
"facets"
] |
Check if url is valid
|
def is_valid_url ( url ) : regex = re . compile ( r'^(?:http|ftp)s?://' # http:// or https:// r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' #domain... #r'localhost|' #localhost... r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip r'(?::\d+)?' # optional port r'(?:/?|[/?]\S+)$' , re . IGNORECASE ) return bool ( regex . match ( url ) )
| 3,310
|
https://github.com/mardix/pylot/blob/506a33a56ebdfc0925b94015e8cf98ccb16a143c/pylot/utils.py#L43-L54
|
[
"def",
"_AlignDecryptedDataOffset",
"(",
"self",
",",
"decrypted_data_offset",
")",
":",
"self",
".",
"_file_object",
".",
"seek",
"(",
"0",
",",
"os",
".",
"SEEK_SET",
")",
"self",
".",
"_decrypter",
"=",
"self",
".",
"_GetDecrypter",
"(",
")",
"self",
".",
"_decrypted_data",
"=",
"b''",
"encrypted_data_offset",
"=",
"0",
"encrypted_data_size",
"=",
"self",
".",
"_file_object",
".",
"get_size",
"(",
")",
"while",
"encrypted_data_offset",
"<",
"encrypted_data_size",
":",
"read_count",
"=",
"self",
".",
"_ReadEncryptedData",
"(",
"self",
".",
"_ENCRYPTED_DATA_BUFFER_SIZE",
")",
"if",
"read_count",
"==",
"0",
":",
"break",
"encrypted_data_offset",
"+=",
"read_count",
"if",
"decrypted_data_offset",
"<",
"self",
".",
"_decrypted_data_size",
":",
"self",
".",
"_decrypted_data_offset",
"=",
"decrypted_data_offset",
"break",
"decrypted_data_offset",
"-=",
"self",
".",
"_decrypted_data_size"
] |
Generate a random string
|
def generate_random_string ( length = 8 ) : char_set = string . ascii_uppercase + string . digits return '' . join ( random . sample ( char_set * ( length - 1 ) , length ) )
| 3,311
|
https://github.com/mardix/pylot/blob/506a33a56ebdfc0925b94015e8cf98ccb16a143c/pylot/utils.py#L117-L122
|
[
"def",
"_CheckFileEntryType",
"(",
"self",
",",
"file_entry",
")",
":",
"if",
"not",
"self",
".",
"_file_entry_types",
":",
"return",
"None",
"return",
"(",
"self",
".",
"_CheckIsDevice",
"(",
"file_entry",
")",
"or",
"self",
".",
"_CheckIsDirectory",
"(",
"file_entry",
")",
"or",
"self",
".",
"_CheckIsFile",
"(",
"file_entry",
")",
"or",
"self",
".",
"_CheckIsLink",
"(",
"file_entry",
")",
"or",
"self",
".",
"_CheckIsPipe",
"(",
"file_entry",
")",
"or",
"self",
".",
"_CheckIsSocket",
"(",
"file_entry",
")",
")"
] |
Stop word filter returns list
|
def filter_stopwords ( str ) : STOPWORDS = [ 'a' , 'able' , 'about' , 'across' , 'after' , 'all' , 'almost' , 'also' , 'am' , 'among' , 'an' , 'and' , 'any' , 'are' , 'as' , 'at' , 'be' , 'because' , 'been' , 'but' , 'by' , 'can' , 'cannot' , 'could' , 'dear' , 'did' , 'do' , 'does' , 'either' , 'else' , 'ever' , 'every' , 'for' , 'from' , 'get' , 'got' , 'had' , 'has' , 'have' , 'he' , 'her' , 'hers' , 'him' , 'his' , 'how' , 'however' , 'i' , 'if' , 'in' , 'into' , 'is' , 'it' , 'its' , 'just' , 'least' , 'let' , 'like' , 'likely' , 'may' , 'me' , 'might' , 'most' , 'must' , 'my' , 'neither' , 'no' , 'nor' , 'not' , 'of' , 'off' , 'often' , 'on' , 'only' , 'or' , 'other' , 'our' , 'own' , 'rather' , 'said' , 'say' , 'says' , 'she' , 'should' , 'since' , 'so' , 'some' , 'than' , 'that' , 'the' , 'their' , 'them' , 'then' , 'there' , 'these' , 'they' , 'this' , 'tis' , 'to' , 'too' , 'twas' , 'us' , 'wants' , 'was' , 'we' , 'were' , 'what' , 'when' , 'where' , 'which' , 'while' , 'who' , 'whom' , 'why' , 'will' , 'with' , 'would' , 'yet' , 'you' , 'your' ] return [ t for t in str . split ( ) if t . lower ( ) not in STOPWORDS ]
| 3,312
|
https://github.com/mardix/pylot/blob/506a33a56ebdfc0925b94015e8cf98ccb16a143c/pylot/utils.py#L139-L161
|
[
"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"
] |
Convert bytes into human readable
|
def convert_bytes ( bytes ) : bytes = float ( bytes ) if bytes >= 1099511627776 : terabytes = bytes / 1099511627776 size = '%.2fT' % terabytes elif bytes >= 1073741824 : gigabytes = bytes / 1073741824 size = '%.2fG' % gigabytes elif bytes >= 1048576 : megabytes = bytes / 1048576 size = '%.2fM' % megabytes elif bytes >= 1024 : kilobytes = bytes / 1024 size = '%.2fK' % kilobytes else : size = '%.2fb' % bytes return size
| 3,313
|
https://github.com/mardix/pylot/blob/506a33a56ebdfc0925b94015e8cf98ccb16a143c/pylot/utils.py#L192-L211
|
[
"def",
"conclude_course",
"(",
"self",
",",
"id",
",",
"event",
")",
":",
"path",
"=",
"{",
"}",
"data",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"# REQUIRED - PATH - id\r",
"\"\"\"ID\"\"\"",
"path",
"[",
"\"id\"",
"]",
"=",
"id",
"# REQUIRED - event\r",
"\"\"\"The action to take on the course.\"\"\"",
"self",
".",
"_validate_enum",
"(",
"event",
",",
"[",
"\"delete\"",
",",
"\"conclude\"",
"]",
")",
"params",
"[",
"\"event\"",
"]",
"=",
"event",
"self",
".",
"logger",
".",
"debug",
"(",
"\"DELETE /api/v1/courses/{id} with query params: {params} and form data: {data}\"",
".",
"format",
"(",
"params",
"=",
"params",
",",
"data",
"=",
"data",
",",
"*",
"*",
"path",
")",
")",
"return",
"self",
".",
"generic_request",
"(",
"\"DELETE\"",
",",
"\"/api/v1/courses/{id}\"",
".",
"format",
"(",
"*",
"*",
"path",
")",
",",
"data",
"=",
"data",
",",
"params",
"=",
"params",
",",
"no_data",
"=",
"True",
")"
] |
Wrapper for lxml s find .
|
def find ( self , node , path ) : return node . find ( path , namespaces = self . namespaces )
| 3,314
|
https://github.com/TyVik/YaDiskClient/blob/ee60163bac8c5696d81e98c8ee1d8b321e46fae4/YaDiskClient/YaDiskClient.py#L24-L27
|
[
"def",
"relative_humidity_wet_psychrometric",
"(",
"dry_bulb_temperature",
",",
"web_bulb_temperature",
",",
"pressure",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"(",
"psychrometric_vapor_pressure_wet",
"(",
"dry_bulb_temperature",
",",
"web_bulb_temperature",
",",
"pressure",
",",
"*",
"*",
"kwargs",
")",
"/",
"saturation_vapor_pressure",
"(",
"dry_bulb_temperature",
")",
")"
] |
Wrapper for lxml s xpath .
|
def xpath ( self , node , path ) : return node . xpath ( path , namespaces = self . namespaces )
| 3,315
|
https://github.com/TyVik/YaDiskClient/blob/ee60163bac8c5696d81e98c8ee1d8b321e46fae4/YaDiskClient/YaDiskClient.py#L29-L32
|
[
"def",
"set_muted",
"(",
"self",
",",
"status",
")",
":",
"new_volume",
"=",
"self",
".",
"_client",
"[",
"'config'",
"]",
"[",
"'volume'",
"]",
"new_volume",
"[",
"'muted'",
"]",
"=",
"status",
"self",
".",
"_client",
"[",
"'config'",
"]",
"[",
"'volume'",
"]",
"[",
"'muted'",
"]",
"=",
"status",
"yield",
"from",
"self",
".",
"_server",
".",
"client_volume",
"(",
"self",
".",
"identifier",
",",
"new_volume",
")",
"_LOGGER",
".",
"info",
"(",
"'set muted to %s on %s'",
",",
"status",
",",
"self",
".",
"friendly_name",
")"
] |
Create directory . All part of path must be exists . Raise exception when path already exists .
|
def mkdir ( self , path ) : resp = self . _sendRequest ( "MKCOL" , path ) if resp . status_code != 201 : if resp . status_code == 409 : raise YaDiskException ( 409 , "Part of path {} does not exists" . format ( path ) ) elif resp . status_code == 405 : raise YaDiskException ( 405 , "Path {} already exists" . format ( path ) ) else : raise YaDiskException ( resp . status_code , resp . content )
| 3,316
|
https://github.com/TyVik/YaDiskClient/blob/ee60163bac8c5696d81e98c8ee1d8b321e46fae4/YaDiskClient/YaDiskClient.py#L118-L128
|
[
"def",
"user_agent",
"(",
"self",
",",
"text",
",",
"*",
"*",
"kwargs",
")",
":",
"indicator_obj",
"=",
"UserAgent",
"(",
"text",
",",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"_indicator",
"(",
"indicator_obj",
")"
] |
Delete file or directory .
|
def rm ( self , path ) : resp = self . _sendRequest ( "DELETE" , path ) # By documentation server must return 200 "OK", but I get 204 "No Content". # Anyway file or directory have been removed. if not ( resp . status_code in ( 200 , 204 ) ) : raise YaDiskException ( resp . status_code , resp . content )
| 3,317
|
https://github.com/TyVik/YaDiskClient/blob/ee60163bac8c5696d81e98c8ee1d8b321e46fae4/YaDiskClient/YaDiskClient.py#L130-L137
|
[
"def",
"cal_v",
"(",
"self",
",",
"p",
",",
"temp",
",",
"min_strain",
"=",
"0.3",
",",
"max_strain",
"=",
"1.0",
")",
":",
"v0",
"=",
"self",
".",
"params_therm",
"[",
"'v0'",
"]",
".",
"nominal_value",
"self",
".",
"force_norm",
"=",
"True",
"pp",
"=",
"unp",
".",
"nominal_values",
"(",
"p",
")",
"ttemp",
"=",
"unp",
".",
"nominal_values",
"(",
"temp",
")",
"def",
"_cal_v_single",
"(",
"pp",
",",
"ttemp",
")",
":",
"if",
"(",
"pp",
"<=",
"1.e-5",
")",
"and",
"(",
"ttemp",
"==",
"300.",
")",
":",
"return",
"v0",
"def",
"f_diff",
"(",
"v",
",",
"ttemp",
",",
"pp",
")",
":",
"return",
"self",
".",
"cal_p",
"(",
"v",
",",
"ttemp",
")",
"-",
"pp",
"# print(f_diff(v0 * 0.3, temp, p))",
"v",
"=",
"brenth",
"(",
"f_diff",
",",
"v0",
"*",
"max_strain",
",",
"v0",
"*",
"min_strain",
",",
"args",
"=",
"(",
"ttemp",
",",
"pp",
")",
")",
"return",
"v",
"f_vu",
"=",
"np",
".",
"vectorize",
"(",
"_cal_v_single",
")",
"v",
"=",
"f_vu",
"(",
"pp",
",",
"ttemp",
")",
"self",
".",
"force_norm",
"=",
"False",
"return",
"v"
] |
Upload file .
|
def upload ( self , file , path ) : with open ( file , "rb" ) as f : resp = self . _sendRequest ( "PUT" , path , data = f ) if resp . status_code != 201 : raise YaDiskException ( resp . status_code , resp . content )
| 3,318
|
https://github.com/TyVik/YaDiskClient/blob/ee60163bac8c5696d81e98c8ee1d8b321e46fae4/YaDiskClient/YaDiskClient.py#L155-L161
|
[
"def",
"_add_dependency",
"(",
"self",
",",
"dependency",
",",
"var_name",
"=",
"None",
")",
":",
"if",
"var_name",
"is",
"None",
":",
"var_name",
"=",
"next",
"(",
"self",
".",
"temp_var_names",
")",
"# Don't add duplicate dependencies",
"if",
"(",
"dependency",
",",
"var_name",
")",
"not",
"in",
"self",
".",
"dependencies",
":",
"self",
".",
"dependencies",
".",
"append",
"(",
"(",
"dependency",
",",
"var_name",
")",
")",
"return",
"var_name"
] |
Download remote file to disk .
|
def download ( self , path , file ) : resp = self . _sendRequest ( "GET" , path ) if resp . status_code == 200 : with open ( file , "wb" ) as f : f . write ( resp . content ) else : raise YaDiskException ( resp . status_code , resp . content )
| 3,319
|
https://github.com/TyVik/YaDiskClient/blob/ee60163bac8c5696d81e98c8ee1d8b321e46fae4/YaDiskClient/YaDiskClient.py#L163-L171
|
[
"def",
"_parse_ISBN_EAN",
"(",
"details",
")",
":",
"isbn_ean",
"=",
"_get_td_or_none",
"(",
"details",
",",
"\"ctl00_ContentPlaceHolder1_tblRowIsbnEan\"",
")",
"if",
"not",
"isbn_ean",
":",
"return",
"None",
",",
"None",
"ean",
"=",
"None",
"isbn",
"=",
"None",
"if",
"\"/\"",
"in",
"isbn_ean",
":",
"# ISBN and EAN are stored in same string",
"isbn",
",",
"ean",
"=",
"isbn_ean",
".",
"split",
"(",
"\"/\"",
")",
"isbn",
"=",
"isbn",
".",
"strip",
"(",
")",
"ean",
"=",
"ean",
".",
"strip",
"(",
")",
"else",
":",
"isbn",
"=",
"isbn_ean",
".",
"strip",
"(",
")",
"if",
"not",
"isbn",
":",
"isbn",
"=",
"None",
"return",
"isbn",
",",
"ean"
] |
Publish file or folder and return public url
|
def publish ( self , path ) : def parseContent ( content ) : root = ET . fromstring ( content ) prop = root . find ( ".//d:prop" , namespaces = self . namespaces ) return prop . find ( "{urn:yandex:disk:meta}public_url" ) . text . strip ( ) data = """
<propertyupdate xmlns="DAV:">
<set>
<prop>
<public_url xmlns="urn:yandex:disk:meta">true</public_url>
</prop>
</set>
</propertyupdate>
""" _check_dst_absolute ( path ) resp = self . _sendRequest ( "PROPPATCH" , addUrl = path , data = data ) if resp . status_code == 207 : return parseContent ( resp . content ) else : raise YaDiskException ( resp . status_code , resp . content )
| 3,320
|
https://github.com/TyVik/YaDiskClient/blob/ee60163bac8c5696d81e98c8ee1d8b321e46fae4/YaDiskClient/YaDiskClient.py#L173-L196
|
[
"def",
"required_event_fields",
"(",
"next_value_columns",
",",
"previous_value_columns",
")",
":",
"# These metadata columns are used to align event indexers.",
"return",
"{",
"TS_FIELD_NAME",
",",
"SID_FIELD_NAME",
",",
"EVENT_DATE_FIELD_NAME",
",",
"}",
".",
"union",
"(",
"# We also expect any of the field names that our loadable columns",
"# are mapped to.",
"viewvalues",
"(",
"next_value_columns",
")",
",",
"viewvalues",
"(",
"previous_value_columns",
")",
",",
")"
] |
Writes a single instruction of opcode with operands to fout .
|
def write_instruction ( fout , start_pos , ins ) : opcode , operands = ins . opcode , ins . operands fmt_operands = opcode_table [ opcode ] [ 'operands' ] if ins . wide : # The "WIDE" prefix fout . write ( pack ( '>B' , 0xC4 ) ) # The real opcode. fout . write ( pack ( '>B' , opcode ) ) fout . write ( pack ( '>H' , operands [ 0 ] . value ) ) if opcode == 0x84 : fout . write ( pack ( '>h' , operands [ 1 ] . value ) ) elif fmt_operands : # A normal simple opcode with simple operands. fout . write ( pack ( '>B' , opcode ) ) for i , ( fmt , _ ) in enumerate ( fmt_operands ) : fout . write ( fmt . value . pack ( operands [ i ] . value ) ) elif opcode == 0xAB : # Special case for lookupswitch. fout . write ( pack ( '>B' , opcode ) ) # assemble([ # ('lookupswitch', { # 2: -3, # 4: 5 # }, <default>) # ]) padding = 4 - ( start_pos + 1 ) % 4 padding = padding if padding != 4 else 0 fout . write ( pack ( f'{padding}x' ) ) fout . write ( pack ( '>ii' , operands [ 1 ] . value , len ( operands [ 0 ] ) ) ) for key in sorted ( operands [ 0 ] . keys ( ) ) : fout . write ( pack ( '>ii' , key , operands [ 0 ] [ key ] ) ) elif opcode == 0xAA : # Special case for table switch. fout . write ( pack ( '>B' , opcode ) ) padding = 4 - ( start_pos + 1 ) % 4 padding = padding if padding != 4 else 0 fout . write ( pack ( f'{padding}x' ) ) fout . write ( pack ( f'>iii{len(operands) - 3}i' , # Default branch offset operands [ 0 ] . value , operands [ 1 ] . value , operands [ 2 ] . value , * ( o . value for o in operands [ 3 : ] ) ) ) else : # opcode with no operands. fout . write ( pack ( '>B' , opcode ) )
| 3,321
|
https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/util/bytecode.py#L123-L178
|
[
"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",
")"
] |
Reads a single instruction from fio and returns it or None if the stream is empty .
|
def read_instruction ( fio , start_pos ) : op = fio . read ( 1 ) if not op : return None op = ord ( op ) ins = opcode_table [ op ] operands = ins [ 'operands' ] name = ins [ 'mnemonic' ] final_operands = [ ] # Most opcodes have simple operands. if operands : for fmt , type_ in operands : final_operands . append ( Operand ( type_ , fmt . value . unpack ( fio . read ( fmt . value . size ) ) [ 0 ] ) ) # Special case for lookupswitch. elif op == 0xAB : # Get rid of the alignment padding. padding = 4 - ( start_pos + 1 ) % 4 padding = padding if padding != 4 else 0 fio . read ( padding ) # Default branch address and branch count. default , npairs = unpack ( '>ii' , fio . read ( 8 ) ) pairs = { } for _ in repeat ( None , npairs ) : match , offset = unpack ( '>ii' , fio . read ( 8 ) ) pairs [ match ] = offset final_operands . append ( pairs ) final_operands . append ( Operand ( OperandTypes . BRANCH , default ) ) # Special case for tableswitch elif op == 0xAA : # Get rid of the alignment padding. padding = 4 - ( start_pos + 1 ) % 4 padding = padding if padding != 4 else 0 fio . read ( padding ) default , low , high = unpack ( '>iii' , fio . read ( 12 ) ) final_operands . append ( Operand ( OperandTypes . BRANCH , default ) ) final_operands . append ( Operand ( OperandTypes . LITERAL , low ) ) final_operands . append ( Operand ( OperandTypes . LITERAL , high ) ) for _ in repeat ( None , high - low + 1 ) : offset = unpack ( '>i' , fio . read ( 4 ) ) [ 0 ] final_operands . append ( Operand ( OperandTypes . BRANCH , offset ) ) # Special case for the wide prefix elif op == 0xC4 : real_op = unpack ( '>B' , fio . read ( 1 ) ) [ 0 ] ins = opcode_table [ real_op ] name = ins [ 'mnemonic' ] final_operands . append ( Operand ( OperandTypes . LOCAL_INDEX , unpack ( '>H' , fio . read ( 2 ) ) [ 0 ] ) ) # Further special case for iinc. if real_op == 0x84 : final_operands . append ( Operand ( OperandTypes . LITERAL , unpack ( '>H' , fio . read ( 2 ) ) [ 0 ] ) ) return Instruction ( name , op , final_operands , start_pos )
| 3,322
|
https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/util/bytecode.py#L181-L259
|
[
"def",
"add_uppercase",
"(",
"table",
")",
":",
"orig",
"=",
"table",
".",
"copy",
"(",
")",
"orig",
".",
"update",
"(",
"dict",
"(",
"(",
"k",
".",
"capitalize",
"(",
")",
",",
"v",
".",
"capitalize",
"(",
")",
")",
"for",
"k",
",",
"v",
"in",
"table",
".",
"items",
"(",
")",
")",
")",
"return",
"orig"
] |
Load bytecode definitions from JSON file .
|
def load_bytecode_definitions ( * , path = None ) -> dict : if path is not None : with open ( path , 'rb' ) as file_in : j = json . load ( file_in ) else : try : j = json . loads ( pkgutil . get_data ( 'jawa.util' , 'bytecode.json' ) ) except json . JSONDecodeError : # Unfortunately our best way to handle missing/malformed/empty # bytecode.json files since it may not actually be backed by a # "real" file. return { } for definition in j . values ( ) : # If the entry has any operands take the text labels and convert # them into pre-cached struct objects and operand types. operands = definition [ 'operands' ] if operands : definition [ 'operands' ] = [ [ getattr ( OperandFmts , oo [ 0 ] ) , OperandTypes [ oo [ 1 ] ] ] for oo in operands ] # Return one dict that contains both mnemonic keys and opcode keys. return { * * j , * * { v [ 'op' ] : v for v in j . values ( ) } }
| 3,323
|
https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/util/bytecode.py#L262-L293
|
[
"def",
"deletecols",
"(",
"X",
",",
"cols",
")",
":",
"if",
"isinstance",
"(",
"cols",
",",
"str",
")",
":",
"cols",
"=",
"cols",
".",
"split",
"(",
"','",
")",
"retain",
"=",
"[",
"n",
"for",
"n",
"in",
"X",
".",
"dtype",
".",
"names",
"if",
"n",
"not",
"in",
"cols",
"]",
"if",
"len",
"(",
"retain",
")",
">",
"0",
":",
"return",
"X",
"[",
"retain",
"]",
"else",
":",
"return",
"None"
] |
Returns the size of this instruction and its operands when packed . start_pos is required for the tableswitch and lookupswitch instruction as the padding depends on alignment .
|
def size_on_disk ( self , start_pos = 0 ) : # All instructions are at least 1 byte (the opcode itself) size = 1 fmts = opcode_table [ self . opcode ] [ 'operands' ] if self . wide : size += 2 # Special case for iinc which has a 2nd extended operand. if self . opcode == 0x84 : size += 2 elif fmts : # A simple opcode with simple operands. for fmt , _ in fmts : size += fmt . value . size elif self . opcode == 0xAB : # lookupswitch padding = 4 - ( start_pos + 1 ) % 4 padding = padding if padding != 4 else 0 size += padding # default & npairs size += 8 size += len ( self . operands [ 0 ] ) * 8 elif self . opcode == 0xAA : # tableswitch raise NotImplementedError ( ) return size
| 3,324
|
https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/util/bytecode.py#L27-L58
|
[
"def",
"get_owned_filters",
"(",
"self",
",",
"server_id",
")",
":",
"# Validate server_id",
"self",
".",
"_get_server",
"(",
"server_id",
")",
"return",
"list",
"(",
"self",
".",
"_owned_filters",
"[",
"server_id",
"]",
")"
] |
True if this instruction needs to be prefixed by the WIDE opcode .
|
def wide ( self ) : if not opcode_table [ self . opcode ] . get ( 'can_be_wide' ) : return False if self . operands [ 0 ] . value >= 255 : return True if self . opcode == 0x84 : if self . operands [ 1 ] . value >= 255 : return True return False
| 3,325
|
https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/util/bytecode.py#L61-L76
|
[
"def",
"delete_group",
"(",
"self",
",",
"name",
")",
":",
"group",
"=",
"self",
".",
"get_group",
"(",
"name",
")",
"method",
",",
"url",
"=",
"get_URL",
"(",
"'group_delete'",
")",
"payload",
"=",
"{",
"'apikey'",
":",
"self",
".",
"config",
".",
"get",
"(",
"'apikey'",
")",
",",
"'logintoken'",
":",
"self",
".",
"session",
".",
"cookies",
".",
"get",
"(",
"'logintoken'",
")",
",",
"'contactgroupid'",
":",
"group",
"[",
"'contactgroupid'",
"]",
"}",
"res",
"=",
"getattr",
"(",
"self",
".",
"session",
",",
"method",
")",
"(",
"url",
",",
"params",
"=",
"payload",
")",
"if",
"res",
".",
"status_code",
"==",
"200",
":",
"return",
"True",
"hellraiser",
"(",
"res",
")"
] |
Get file as MIMEBase message
|
def get_attachment ( self , file_path ) : try : file_ = open ( file_path , 'rb' ) attachment = MIMEBase ( 'application' , 'octet-stream' ) attachment . set_payload ( file_ . read ( ) ) file_ . close ( ) encoders . encode_base64 ( attachment ) attachment . add_header ( 'Content-Disposition' , 'attachment' , filename = os . path . basename ( file_path ) ) return attachment except IOError : traceback . print_exc ( ) message = ( 'The requested file could not be read. Maybe wrong ' 'permissions?' ) print >> sys . stderr , message sys . exit ( 6 )
| 3,326
|
https://github.com/thespacedoctor/polyglot/blob/98038d746aa67e343b73b3ccee1e02d31dab81ec/polyglot/kindle.py#L148-L166
|
[
"def",
"plugin_counts",
"(",
"self",
")",
":",
"ret",
"=",
"{",
"'total'",
":",
"0",
",",
"}",
"# As ususal, we need data before we can actually do anything ;)",
"data",
"=",
"self",
".",
"raw_query",
"(",
"'plugin'",
",",
"'init'",
")",
"# For backwards compatability purposes, we will be handling this a bit",
"# differently than I would like. We are going to check to see if each",
"# value exists and override the default value of 0. The only value that",
"# I know existed in bost 4.2 and 4.4 is pluginCount, the rest aren't",
"# listed in the API docs, however return back from my experimentation.",
"ret",
"[",
"'total'",
"]",
"=",
"data",
"[",
"'pluginCount'",
"]",
"if",
"'lastUpdates'",
"in",
"data",
":",
"for",
"item",
"in",
"[",
"'active'",
",",
"'passive'",
",",
"'compliance'",
",",
"'custom'",
",",
"'event'",
"]",
":",
"itemdata",
"=",
"{",
"}",
"if",
"item",
"in",
"data",
"[",
"'lastUpdates'",
"]",
":",
"itemdata",
"=",
"data",
"[",
"'lastUpdates'",
"]",
"[",
"item",
"]",
"if",
"item",
"in",
"data",
":",
"itemdata",
"[",
"'count'",
"]",
"=",
"data",
"[",
"item",
"]",
"else",
":",
"itemdata",
"[",
"'count'",
"]",
"=",
"0",
"ret",
"[",
"item",
"]",
"=",
"itemdata",
"return",
"ret"
] |
Get a host value matching the given value .
|
def lookup ( self , host_value ) : try : host_object = self . _host_factory ( host_value ) except InvalidHostError : return None result = self . _get_match_and_classification ( host_object ) host_item , classification = result if host_item is not None : return AddressListItem ( host_item . to_unicode ( ) , self , classification ) return None
| 3,327
|
https://github.com/piotr-rusin/spam-lists/blob/fd616e8761b28f3eaa503fee5e45f7748e8f88f2/spam_lists/host_list.py#L66-L90
|
[
"def",
"upload",
"(",
"self",
",",
"params",
"=",
"{",
"}",
")",
":",
"if",
"self",
".",
"upload_token",
"is",
"not",
"None",
":",
"# resume upload",
"status",
"=",
"self",
".",
"check",
"(",
")",
"if",
"status",
"[",
"'status'",
"]",
"!=",
"4",
":",
"return",
"self",
".",
"commit",
"(",
")",
"else",
":",
"self",
".",
"new_slice",
"(",
")",
"while",
"self",
".",
"slice_task_id",
"!=",
"0",
":",
"self",
".",
"upload_slice",
"(",
")",
"return",
"self",
".",
"commit",
"(",
")",
"else",
":",
"# new upload",
"self",
".",
"create",
"(",
"self",
".",
"prepare_video_params",
"(",
"*",
"*",
"params",
")",
")",
"self",
".",
"create_file",
"(",
")",
"self",
".",
"new_slice",
"(",
")",
"while",
"self",
".",
"slice_task_id",
"!=",
"0",
":",
"self",
".",
"upload_slice",
"(",
")",
"return",
"self",
".",
"commit",
"(",
")"
] |
Check if any of the given URLs has a matching host .
|
def any_match ( self , urls ) : return any ( urlparse ( u ) . hostname in self for u in urls )
| 3,328
|
https://github.com/piotr-rusin/spam-lists/blob/fd616e8761b28f3eaa503fee5e45f7748e8f88f2/spam_lists/host_list.py#L93-L101
|
[
"def",
"leave_room",
"(",
"self",
",",
"room_id",
",",
"timeout",
"=",
"None",
")",
":",
"self",
".",
"_post",
"(",
"'/v2/bot/room/{room_id}/leave'",
".",
"format",
"(",
"room_id",
"=",
"room_id",
")",
",",
"timeout",
"=",
"timeout",
")"
] |
Get matching hosts for the given URLs .
|
def lookup_matching ( self , urls ) : hosts = ( urlparse ( u ) . hostname for u in urls ) for val in hosts : item = self . lookup ( val ) if item is not None : yield item
| 3,329
|
https://github.com/piotr-rusin/spam-lists/blob/fd616e8761b28f3eaa503fee5e45f7748e8f88f2/spam_lists/host_list.py#L104-L117
|
[
"def",
"ttl",
"(",
"self",
",",
"value",
")",
":",
"# get timer",
"timer",
"=",
"getattr",
"(",
"self",
",",
"Annotation",
".",
"__TIMER",
",",
"None",
")",
"# if timer is running, stop the timer",
"if",
"timer",
"is",
"not",
"None",
":",
"timer",
".",
"cancel",
"(",
")",
"# initialize timestamp",
"timestamp",
"=",
"None",
"# if value is None",
"if",
"value",
"is",
"None",
":",
"# nonify timer",
"timer",
"=",
"None",
"else",
":",
"# else, renew a timer",
"# get timestamp",
"timestamp",
"=",
"time",
"(",
")",
"+",
"value",
"# start a new timer",
"timer",
"=",
"Timer",
"(",
"value",
",",
"self",
".",
"__del__",
")",
"timer",
".",
"start",
"(",
")",
"# set/update attributes",
"setattr",
"(",
"self",
",",
"Annotation",
".",
"__TIMER",
",",
"timer",
")",
"setattr",
"(",
"self",
",",
"Annotation",
".",
"__TS",
",",
"timestamp",
")"
] |
Get URLs with hosts matching any listed ones .
|
def filter_matching ( self , urls ) : for url in urls : if urlparse ( url ) . hostname in self : yield url
| 3,330
|
https://github.com/piotr-rusin/spam-lists/blob/fd616e8761b28f3eaa503fee5e45f7748e8f88f2/spam_lists/host_list.py#L120-L130
|
[
"def",
"_read_body_by_chunk",
"(",
"self",
",",
"response",
",",
"file",
",",
"raw",
"=",
"False",
")",
":",
"reader",
"=",
"ChunkedTransferReader",
"(",
"self",
".",
"_connection",
")",
"file_is_async",
"=",
"hasattr",
"(",
"file",
",",
"'drain'",
")",
"while",
"True",
":",
"chunk_size",
",",
"data",
"=",
"yield",
"from",
"reader",
".",
"read_chunk_header",
"(",
")",
"self",
".",
"_data_event_dispatcher",
".",
"notify_read",
"(",
"data",
")",
"if",
"raw",
":",
"file",
".",
"write",
"(",
"data",
")",
"if",
"not",
"chunk_size",
":",
"break",
"while",
"True",
":",
"content",
",",
"data",
"=",
"yield",
"from",
"reader",
".",
"read_chunk_body",
"(",
")",
"self",
".",
"_data_event_dispatcher",
".",
"notify_read",
"(",
"data",
")",
"if",
"not",
"content",
":",
"if",
"raw",
":",
"file",
".",
"write",
"(",
"data",
")",
"break",
"content",
"=",
"self",
".",
"_decompress_data",
"(",
"content",
")",
"if",
"file",
":",
"file",
".",
"write",
"(",
"content",
")",
"if",
"file_is_async",
":",
"yield",
"from",
"file",
".",
"drain",
"(",
")",
"content",
"=",
"self",
".",
"_flush_decompressor",
"(",
")",
"if",
"file",
":",
"file",
".",
"write",
"(",
"content",
")",
"if",
"file_is_async",
":",
"yield",
"from",
"file",
".",
"drain",
"(",
")",
"trailer_data",
"=",
"yield",
"from",
"reader",
".",
"read_trailer",
"(",
")",
"self",
".",
"_data_event_dispatcher",
".",
"notify_read",
"(",
"trailer_data",
")",
"if",
"file",
"and",
"raw",
":",
"file",
".",
"write",
"(",
"trailer_data",
")",
"if",
"file_is_async",
":",
"yield",
"from",
"file",
".",
"drain",
"(",
")",
"response",
".",
"fields",
".",
"parse",
"(",
"trailer_data",
")"
] |
Decodes a bytestring containing modified UTF - 8 as defined in section 4 . 4 . 7 of the JVM specification .
|
def decode_modified_utf8 ( s : bytes ) -> str : s = bytearray ( s ) buff = [ ] buffer_append = buff . append ix = 0 while ix < len ( s ) : x = s [ ix ] ix += 1 if x >> 7 == 0 : # Just an ASCII character, nothing else to do. pass elif x >> 6 == 6 : y = s [ ix ] ix += 1 x = ( ( x & 0x1F ) << 6 ) + ( y & 0x3F ) elif x >> 4 == 14 : y , z = s [ ix : ix + 2 ] ix += 2 x = ( ( x & 0xF ) << 12 ) + ( ( y & 0x3F ) << 6 ) + ( z & 0x3F ) elif x == 0xED : v , w , x , y , z = s [ ix : ix + 6 ] ix += 5 x = 0x10000 + ( ( ( v & 0x0F ) << 16 ) + ( ( w & 0x3F ) << 10 ) + ( ( y & 0x0F ) << 6 ) + ( z & 0x3F ) ) elif x == 0xC0 and s [ ix ] == 0x80 : ix += 1 x = 0 buffer_append ( x ) return u'' . join ( chr ( b ) for b in buff )
| 3,331
|
https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/util/utf.py#L12-L52
|
[
"def",
"warp_object",
"(",
"self",
",",
"tileMapObj",
")",
":",
"print",
"\"Collision\"",
"if",
"tileMapObj",
".",
"can_warp",
":",
"#Check to see if we need to load a different tile map",
"if",
"self",
".",
"map_association",
"!=",
"self",
".",
"exitWarp",
".",
"map_association",
":",
"#Load the new tile map.",
"TileMapManager",
".",
"load",
"(",
"exitWarp",
".",
"map_association",
")",
"tileMapObj",
".",
"parent",
".",
"coords",
"=",
"self",
".",
"exitWarp",
".",
"coords"
] |
Encodes a unicode string as modified UTF - 8 as defined in section 4 . 4 . 7 of the JVM specification .
|
def encode_modified_utf8 ( u : str ) -> bytearray : final_string = bytearray ( ) for c in [ ord ( char ) for char in u ] : if c == 0x00 or ( 0x80 < c < 0x7FF ) : final_string . extend ( [ ( 0xC0 | ( 0x1F & ( c >> 6 ) ) ) , ( 0x80 | ( 0x3F & c ) ) ] ) elif c < 0x7F : final_string . append ( c ) elif 0x800 < c < 0xFFFF : final_string . extend ( [ ( 0xE0 | ( 0x0F & ( c >> 12 ) ) ) , ( 0x80 | ( 0x3F & ( c >> 6 ) ) ) , ( 0x80 | ( 0x3F & c ) ) ] ) return final_string
| 3,332
|
https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/util/utf.py#L55-L80
|
[
"def",
"delete_persistent_data",
"(",
"role",
",",
"zk_node",
")",
":",
"if",
"role",
":",
"destroy_volumes",
"(",
"role",
")",
"unreserve_resources",
"(",
"role",
")",
"if",
"zk_node",
":",
"delete_zk_node",
"(",
"zk_node",
")"
] |
Remove a previously registered callback
|
def unregister ( self , name , func ) : try : templatehook = self . _registry [ name ] except KeyError : return templatehook . unregister ( func )
| 3,333
|
https://github.com/nitely/django-hooks/blob/26ea2150c9be110e90b9ee60fbfd1065ac30ab1d/hooks/templatehook.py#L117-L130
|
[
"def",
"save",
"(",
"self",
",",
"create_multiple_renditions",
"=",
"True",
",",
"preserve_source_rendition",
"=",
"True",
",",
"encode_to",
"=",
"enums",
".",
"EncodeToEnum",
".",
"FLV",
")",
":",
"if",
"is_ftp_connection",
"(",
"self",
".",
"connection",
")",
"and",
"len",
"(",
"self",
".",
"assets",
")",
">",
"0",
":",
"self",
".",
"connection",
".",
"post",
"(",
"xml",
"=",
"self",
".",
"to_xml",
"(",
")",
",",
"assets",
"=",
"self",
".",
"assets",
")",
"elif",
"not",
"self",
".",
"id",
"and",
"self",
".",
"_filename",
":",
"self",
".",
"id",
"=",
"self",
".",
"connection",
".",
"post",
"(",
"'create_video'",
",",
"self",
".",
"_filename",
",",
"create_multiple_renditions",
"=",
"create_multiple_renditions",
",",
"preserve_source_rendition",
"=",
"preserve_source_rendition",
",",
"encode_to",
"=",
"encode_to",
",",
"video",
"=",
"self",
".",
"_to_dict",
"(",
")",
")",
"elif",
"not",
"self",
".",
"id",
"and",
"len",
"(",
"self",
".",
"renditions",
")",
">",
"0",
":",
"self",
".",
"id",
"=",
"self",
".",
"connection",
".",
"post",
"(",
"'create_video'",
",",
"video",
"=",
"self",
".",
"_to_dict",
"(",
")",
")",
"elif",
"self",
".",
"id",
":",
"data",
"=",
"self",
".",
"connection",
".",
"post",
"(",
"'update_video'",
",",
"video",
"=",
"self",
".",
"_to_dict",
"(",
")",
")",
"if",
"data",
":",
"self",
".",
"_load",
"(",
"data",
")"
] |
Remove all callbacks
|
def unregister_all ( self , name ) : try : templatehook = self . _registry [ name ] except KeyError : return templatehook . unregister_all ( )
| 3,334
|
https://github.com/nitely/django-hooks/blob/26ea2150c9be110e90b9ee60fbfd1065ac30ab1d/hooks/templatehook.py#L132-L143
|
[
"def",
"BuildChecks",
"(",
"self",
",",
"request",
")",
":",
"result",
"=",
"[",
"]",
"if",
"request",
".",
"HasField",
"(",
"\"start_time\"",
")",
"or",
"request",
".",
"HasField",
"(",
"\"end_time\"",
")",
":",
"def",
"FilterTimestamp",
"(",
"file_stat",
",",
"request",
"=",
"request",
")",
":",
"return",
"file_stat",
".",
"HasField",
"(",
"\"st_mtime\"",
")",
"and",
"(",
"file_stat",
".",
"st_mtime",
"<",
"request",
".",
"start_time",
"or",
"file_stat",
".",
"st_mtime",
">",
"request",
".",
"end_time",
")",
"result",
".",
"append",
"(",
"FilterTimestamp",
")",
"if",
"request",
".",
"HasField",
"(",
"\"min_file_size\"",
")",
"or",
"request",
".",
"HasField",
"(",
"\"max_file_size\"",
")",
":",
"def",
"FilterSize",
"(",
"file_stat",
",",
"request",
"=",
"request",
")",
":",
"return",
"file_stat",
".",
"HasField",
"(",
"\"st_size\"",
")",
"and",
"(",
"file_stat",
".",
"st_size",
"<",
"request",
".",
"min_file_size",
"or",
"file_stat",
".",
"st_size",
">",
"request",
".",
"max_file_size",
")",
"result",
".",
"append",
"(",
"FilterSize",
")",
"if",
"request",
".",
"HasField",
"(",
"\"perm_mode\"",
")",
":",
"def",
"FilterPerms",
"(",
"file_stat",
",",
"request",
"=",
"request",
")",
":",
"return",
"(",
"file_stat",
".",
"st_mode",
"&",
"request",
".",
"perm_mask",
")",
"!=",
"request",
".",
"perm_mode",
"result",
".",
"append",
"(",
"FilterPerms",
")",
"if",
"request",
".",
"HasField",
"(",
"\"uid\"",
")",
":",
"def",
"FilterUID",
"(",
"file_stat",
",",
"request",
"=",
"request",
")",
":",
"return",
"file_stat",
".",
"st_uid",
"!=",
"request",
".",
"uid",
"result",
".",
"append",
"(",
"FilterUID",
")",
"if",
"request",
".",
"HasField",
"(",
"\"gid\"",
")",
":",
"def",
"FilterGID",
"(",
"file_stat",
",",
"request",
"=",
"request",
")",
":",
"return",
"file_stat",
".",
"st_gid",
"!=",
"request",
".",
"gid",
"result",
".",
"append",
"(",
"FilterGID",
")",
"if",
"request",
".",
"HasField",
"(",
"\"path_regex\"",
")",
":",
"regex",
"=",
"request",
".",
"path_regex",
"def",
"FilterPath",
"(",
"file_stat",
",",
"regex",
"=",
"regex",
")",
":",
"\"\"\"Suppress any filename not matching the regular expression.\"\"\"",
"return",
"not",
"regex",
".",
"Search",
"(",
"file_stat",
".",
"pathspec",
".",
"Basename",
"(",
")",
")",
"result",
".",
"append",
"(",
"FilterPath",
")",
"if",
"request",
".",
"HasField",
"(",
"\"data_regex\"",
")",
":",
"def",
"FilterData",
"(",
"file_stat",
",",
"*",
"*",
"_",
")",
":",
"\"\"\"Suppress files that do not match the content.\"\"\"",
"return",
"not",
"self",
".",
"TestFileContent",
"(",
"file_stat",
")",
"result",
".",
"append",
"(",
"FilterData",
")",
"return",
"result"
] |
Allow old method names for backwards compatability .
|
def deprecated_name ( name ) : def decorator ( func ) : """Decorator function.""" def func_wrapper ( self ) : """Wrapper for original function.""" if hasattr ( self , name ) : # Return the old property return getattr ( self , name ) else : return func ( self ) return func_wrapper return decorator
| 3,335
|
https://github.com/mezz64/pyEmby/blob/6bb621e4e25bf1b9b0aba2c38b588e68f8816226/pyemby/helpers.py#L10-L22
|
[
"def",
"find_covalent_bonds",
"(",
"ampal",
",",
"max_range",
"=",
"2.2",
",",
"threshold",
"=",
"1.1",
",",
"tag",
"=",
"True",
")",
":",
"sectors",
"=",
"gen_sectors",
"(",
"ampal",
".",
"get_atoms",
"(",
")",
",",
"max_range",
"*",
"1.1",
")",
"bonds",
"=",
"[",
"]",
"for",
"sector",
"in",
"sectors",
".",
"values",
"(",
")",
":",
"atoms",
"=",
"itertools",
".",
"combinations",
"(",
"sector",
",",
"2",
")",
"bonds",
".",
"extend",
"(",
"covalent_bonds",
"(",
"atoms",
",",
"threshold",
"=",
"threshold",
")",
")",
"bond_set",
"=",
"list",
"(",
"set",
"(",
"bonds",
")",
")",
"if",
"tag",
":",
"for",
"bond",
"in",
"bond_set",
":",
"a",
",",
"b",
"=",
"bond",
".",
"a",
",",
"bond",
".",
"b",
"if",
"'covalent_bonds'",
"not",
"in",
"a",
".",
"tags",
":",
"a",
".",
"tags",
"[",
"'covalent_bonds'",
"]",
"=",
"[",
"b",
"]",
"else",
":",
"a",
".",
"tags",
"[",
"'covalent_bonds'",
"]",
".",
"append",
"(",
"b",
")",
"if",
"'covalent_bonds'",
"not",
"in",
"b",
".",
"tags",
":",
"b",
".",
"tags",
"[",
"'covalent_bonds'",
"]",
"=",
"[",
"a",
"]",
"else",
":",
"b",
".",
"tags",
"[",
"'covalent_bonds'",
"]",
".",
"append",
"(",
"a",
")",
"return",
"bond_set"
] |
Return an object that corresponds to the given EPSG code .
|
def get ( code ) : instance = _cache . get ( code ) if instance is None : url = '{prefix}{code}.gml?download' . format ( prefix = EPSG_IO_URL , code = code ) xml = requests . get ( url ) . content root = ET . fromstring ( xml ) class_for_tag = { GML_NS + 'CartesianCS' : CartesianCS , GML_NS + 'GeodeticCRS' : GeodeticCRS , GML_NS + 'ProjectedCRS' : ProjectedCRS , GML_NS + 'CompoundCRS' : CompoundCRS , GML_NS + 'BaseUnit' : UOM , } if root . tag in class_for_tag : instance = class_for_tag [ root . tag ] ( root ) else : raise ValueError ( 'Unsupported code type: {}' . format ( root . tag ) ) _cache [ code ] = instance return instance
| 3,336
|
https://github.com/rhattersley/pyepsg/blob/0ddd79287f8d42483c8f70ce50aba1cc6b5d780a/pyepsg.py#L263-L301
|
[
"def",
"_sendBuffers",
"(",
"self",
")",
":",
"msg",
"=",
"{",
"}",
"msg_size",
"=",
"0",
"lastlog",
"=",
"None",
"logdata",
"=",
"[",
"]",
"while",
"self",
".",
"buffered",
":",
"# Grab the next bits from the buffer",
"logname",
",",
"data",
"=",
"self",
".",
"buffered",
".",
"popleft",
"(",
")",
"# If this log is different than the last one, then we have to send",
"# out the message so far. This is because the message is",
"# transferred as a dictionary, which makes the ordering of keys",
"# unspecified, and makes it impossible to interleave data from",
"# different logs. A future enhancement could be to change the",
"# master to support a list of (logname, data) tuples instead of a",
"# dictionary.",
"# On our first pass through this loop lastlog is None",
"if",
"lastlog",
"is",
"None",
":",
"lastlog",
"=",
"logname",
"elif",
"logname",
"!=",
"lastlog",
":",
"self",
".",
"_sendMessage",
"(",
"msg",
")",
"msg",
"=",
"{",
"}",
"msg_size",
"=",
"0",
"lastlog",
"=",
"logname",
"logdata",
"=",
"msg",
".",
"setdefault",
"(",
"logname",
",",
"[",
"]",
")",
"# Chunkify the log data to make sure we're not sending more than",
"# CHUNK_LIMIT at a time",
"for",
"chunk",
"in",
"self",
".",
"_chunkForSend",
"(",
"data",
")",
":",
"if",
"not",
"chunk",
":",
"continue",
"logdata",
".",
"append",
"(",
"chunk",
")",
"msg_size",
"+=",
"len",
"(",
"chunk",
")",
"if",
"msg_size",
">=",
"self",
".",
"CHUNK_LIMIT",
":",
"# We've gone beyond the chunk limit, so send out our",
"# message. At worst this results in a message slightly",
"# larger than (2*CHUNK_LIMIT)-1",
"self",
".",
"_sendMessage",
"(",
"msg",
")",
"msg",
"=",
"{",
"}",
"logdata",
"=",
"msg",
".",
"setdefault",
"(",
"logname",
",",
"[",
"]",
")",
"msg_size",
"=",
"0",
"self",
".",
"buflen",
"=",
"0",
"if",
"logdata",
":",
"self",
".",
"_sendMessage",
"(",
"msg",
")",
"if",
"self",
".",
"sendBuffersTimer",
":",
"if",
"self",
".",
"sendBuffersTimer",
".",
"active",
"(",
")",
":",
"self",
".",
"sendBuffersTimer",
".",
"cancel",
"(",
")",
"self",
".",
"sendBuffersTimer",
"=",
"None"
] |
The EPSG code for this CRS .
|
def id ( self ) : id = self . element . attrib [ GML_NS + 'id' ] code = id . split ( '-' ) [ - 1 ] return code
| 3,337
|
https://github.com/rhattersley/pyepsg/blob/0ddd79287f8d42483c8f70ce50aba1cc6b5d780a/pyepsg.py#L112-L116
|
[
"def",
"consume_socket_output",
"(",
"frames",
",",
"demux",
"=",
"False",
")",
":",
"if",
"demux",
"is",
"False",
":",
"# If the streams are multiplexed, the generator returns strings, that",
"# we just need to concatenate.",
"return",
"six",
".",
"binary_type",
"(",
")",
".",
"join",
"(",
"frames",
")",
"# If the streams are demultiplexed, the generator yields tuples",
"# (stdout, stderr)",
"out",
"=",
"[",
"None",
",",
"None",
"]",
"for",
"frame",
"in",
"frames",
":",
"# It is guaranteed that for each frame, one and only one stream",
"# is not None.",
"assert",
"frame",
"!=",
"(",
"None",
",",
"None",
")",
"if",
"frame",
"[",
"0",
"]",
"is",
"not",
"None",
":",
"if",
"out",
"[",
"0",
"]",
"is",
"None",
":",
"out",
"[",
"0",
"]",
"=",
"frame",
"[",
"0",
"]",
"else",
":",
"out",
"[",
"0",
"]",
"+=",
"frame",
"[",
"0",
"]",
"else",
":",
"if",
"out",
"[",
"1",
"]",
"is",
"None",
":",
"out",
"[",
"1",
"]",
"=",
"frame",
"[",
"1",
"]",
"else",
":",
"out",
"[",
"1",
"]",
"+=",
"frame",
"[",
"1",
"]",
"return",
"tuple",
"(",
"out",
")"
] |
Return the OGC WKT which corresponds to the CRS as HTML .
|
def as_html ( self ) : url = '{prefix}{code}.html?download' . format ( prefix = EPSG_IO_URL , code = self . id ) return requests . get ( url ) . text
| 3,338
|
https://github.com/rhattersley/pyepsg/blob/0ddd79287f8d42483c8f70ce50aba1cc6b5d780a/pyepsg.py#L142-L154
|
[
"def",
"sorted_fancy_indexing",
"(",
"indexable",
",",
"request",
")",
":",
"if",
"len",
"(",
"request",
")",
">",
"1",
":",
"indices",
"=",
"numpy",
".",
"argsort",
"(",
"request",
")",
"data",
"=",
"numpy",
".",
"empty",
"(",
"shape",
"=",
"(",
"len",
"(",
"request",
")",
",",
")",
"+",
"indexable",
".",
"shape",
"[",
"1",
":",
"]",
",",
"dtype",
"=",
"indexable",
".",
"dtype",
")",
"data",
"[",
"indices",
"]",
"=",
"indexable",
"[",
"numpy",
".",
"array",
"(",
"request",
")",
"[",
"indices",
"]",
",",
"...",
"]",
"else",
":",
"data",
"=",
"indexable",
"[",
"request",
"]",
"return",
"data"
] |
Return the PROJ . 4 string which corresponds to the CRS .
|
def as_proj4 ( self ) : url = '{prefix}{code}.proj4?download' . format ( prefix = EPSG_IO_URL , code = self . id ) return requests . get ( url ) . text . strip ( )
| 3,339
|
https://github.com/rhattersley/pyepsg/blob/0ddd79287f8d42483c8f70ce50aba1cc6b5d780a/pyepsg.py#L156-L170
|
[
"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.\"",
")"
] |
Removes a method from the table by identity .
|
def remove ( self , method : Method ) : self . _table = [ fld for fld in self . _table if fld is not method ]
| 3,340
|
https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/methods.py#L122-L126
|
[
"def",
"step",
"(",
"self",
",",
"state",
",",
"clamping",
")",
":",
"ns",
"=",
"state",
".",
"copy",
"(",
")",
"for",
"var",
"in",
"state",
":",
"if",
"clamping",
".",
"has_variable",
"(",
"var",
")",
":",
"ns",
"[",
"var",
"]",
"=",
"int",
"(",
"clamping",
".",
"bool",
"(",
"var",
")",
")",
"else",
":",
"or_value",
"=",
"0",
"for",
"clause",
",",
"_",
"in",
"self",
".",
"in_edges_iter",
"(",
"var",
")",
":",
"or_value",
"=",
"or_value",
"or",
"clause",
".",
"bool",
"(",
"state",
")",
"if",
"or_value",
":",
"break",
"ns",
"[",
"var",
"]",
"=",
"int",
"(",
"or_value",
")",
"return",
"ns"
] |
Creates a new method from name and descriptor . If code is not None add a Code attribute to this method .
|
def create ( self , name : str , descriptor : str , code : CodeAttribute = None ) -> Method : method = Method ( self . _cf ) name = self . _cf . constants . create_utf8 ( name ) descriptor = self . _cf . constants . create_utf8 ( descriptor ) method . _name_index = name . index method . _descriptor_index = descriptor . index method . access_flags . acc_public = True if code is not None : method . attributes . create ( CodeAttribute ) self . append ( method ) return method
| 3,341
|
https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/methods.py#L128-L145
|
[
"def",
"retract",
"(",
"self",
")",
":",
"if",
"lib",
".",
"EnvRetract",
"(",
"self",
".",
"_env",
",",
"self",
".",
"_fact",
")",
"!=",
"1",
":",
"raise",
"CLIPSError",
"(",
"self",
".",
"_env",
")"
] |
Read the MethodTable from the file - like object source .
|
def unpack ( self , source : IO ) : method_count = unpack ( '>H' , source . read ( 2 ) ) [ 0 ] for _ in repeat ( None , method_count ) : method = Method ( self . _cf ) method . unpack ( source ) self . append ( method )
| 3,342
|
https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/methods.py#L151-L166
|
[
"def",
"set_nodelay",
"(",
"self",
",",
"value",
":",
"bool",
")",
"->",
"None",
":",
"assert",
"self",
".",
"ws_connection",
"is",
"not",
"None",
"self",
".",
"ws_connection",
".",
"set_nodelay",
"(",
"value",
")"
] |
Write the MethodTable to the file - like object out .
|
def pack ( self , out : IO ) : out . write ( pack ( '>H' , len ( self ) ) ) for method in self . _table : method . pack ( out )
| 3,343
|
https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/methods.py#L168-L181
|
[
"def",
"node_inclusion_predicate_builder",
"(",
"nodes",
":",
"Iterable",
"[",
"BaseEntity",
"]",
")",
"->",
"NodePredicate",
":",
"nodes",
"=",
"set",
"(",
"nodes",
")",
"@",
"node_predicate",
"def",
"node_inclusion_predicate",
"(",
"node",
":",
"BaseEntity",
")",
"->",
"bool",
":",
"\"\"\"Return true if the node is in the given set of nodes.\"\"\"",
"return",
"node",
"in",
"nodes",
"return",
"node_inclusion_predicate"
] |
Read the CodeAttribute from the byte string info .
|
def unpack ( self , info ) : self . max_stack , self . max_locals , c_len = info . unpack ( '>HHI' ) self . _code = info . read ( c_len ) # The exception table ex_table_len = info . u2 ( ) for _ in repeat ( None , ex_table_len ) : self . exception_table . append ( CodeException ( * info . unpack ( '>HHHH' ) ) ) self . attributes = AttributeTable ( self . cf , parent = self ) self . attributes . unpack ( info )
| 3,344
|
https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/attributes/code.py#L70-L91
|
[
"def",
"exclude_types",
"(",
"self",
",",
"*",
"objs",
")",
":",
"for",
"o",
"in",
"objs",
":",
"for",
"t",
"in",
"_keytuple",
"(",
"o",
")",
":",
"if",
"t",
"and",
"t",
"not",
"in",
"self",
".",
"_excl_d",
":",
"self",
".",
"_excl_d",
"[",
"t",
"]",
"=",
"0"
] |
The CodeAttribute in packed byte string form .
|
def pack ( self ) : with io . BytesIO ( ) as file_out : file_out . write ( pack ( '>HHI' , self . max_stack , self . max_locals , len ( self . _code ) ) ) file_out . write ( self . _code ) file_out . write ( pack ( '>H' , len ( self . exception_table ) ) ) for exception in self . exception_table : file_out . write ( pack ( '>HHHH' , * exception ) ) self . attributes . pack ( file_out ) return file_out . getvalue ( )
| 3,345
|
https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/attributes/code.py#L93-L111
|
[
"def",
"libvlc_video_set_subtitle_file",
"(",
"p_mi",
",",
"psz_subtitle",
")",
":",
"f",
"=",
"_Cfunctions",
".",
"get",
"(",
"'libvlc_video_set_subtitle_file'",
",",
"None",
")",
"or",
"_Cfunction",
"(",
"'libvlc_video_set_subtitle_file'",
",",
"(",
"(",
"1",
",",
")",
",",
"(",
"1",
",",
")",
",",
")",
",",
"None",
",",
"ctypes",
".",
"c_int",
",",
"MediaPlayer",
",",
"ctypes",
".",
"c_char_p",
")",
"return",
"f",
"(",
"p_mi",
",",
"psz_subtitle",
")"
] |
Set the value if a volume level is provided else print the current volume level .
|
def _volume_command ( ramp , volume ) : if volume is not None : ramp . set_volume ( float ( volume ) ) else : print ramp . volume
| 3,346
|
https://github.com/jaapz/cast/blob/1c451b11b7c9ce1c65d53ae1f4d2e44969676a1b/cast.py#L39-L45
|
[
"def",
"jing",
"(",
"rng_filepath",
",",
"*",
"xml_filepaths",
")",
":",
"cmd",
"=",
"[",
"'java'",
",",
"'-jar'",
"]",
"cmd",
".",
"extend",
"(",
"[",
"str",
"(",
"JING_JAR",
")",
",",
"str",
"(",
"rng_filepath",
")",
"]",
")",
"for",
"xml_filepath",
"in",
"xml_filepaths",
":",
"cmd",
".",
"append",
"(",
"str",
"(",
"xml_filepath",
")",
")",
"proc",
"=",
"subprocess",
".",
"Popen",
"(",
"cmd",
",",
"stdin",
"=",
"subprocess",
".",
"PIPE",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
",",
"close_fds",
"=",
"True",
")",
"out",
",",
"err",
"=",
"proc",
".",
"communicate",
"(",
")",
"return",
"_parse_jing_output",
"(",
"out",
".",
"decode",
"(",
"'utf-8'",
")",
")"
] |
Build a nice status message and print it to stdout .
|
def _status_command ( cast , ramp ) : if ramp . is_playing : play_symbol = u'\u25B6' else : play_symbol = u'\u2759\u2759' print u' %s %s by %s from %s via %s, %s of %s' % ( play_symbol , ramp . title , ramp . artist , ramp . album , cast . app . app_id , _to_minutes ( ramp . current_time ) , _to_minutes ( ramp . duration ) )
| 3,347
|
https://github.com/jaapz/cast/blob/1c451b11b7c9ce1c65d53ae1f4d2e44969676a1b/cast.py#L48-L63
|
[
"def",
"unbind",
"(",
"self",
",",
"devices_to_unbind",
")",
":",
"if",
"self",
".",
"entity_api_key",
"==",
"\"\"",
":",
"return",
"{",
"'status'",
":",
"'failure'",
",",
"'response'",
":",
"'No API key found in request'",
"}",
"url",
"=",
"self",
".",
"base_url",
"+",
"\"api/0.1.0/subscribe/unbind\"",
"headers",
"=",
"{",
"\"apikey\"",
":",
"self",
".",
"entity_api_key",
"}",
"data",
"=",
"{",
"\"exchange\"",
":",
"\"amq.topic\"",
",",
"\"keys\"",
":",
"devices_to_unbind",
",",
"\"queue\"",
":",
"self",
".",
"entity_id",
"}",
"with",
"self",
".",
"no_ssl_verification",
"(",
")",
":",
"r",
"=",
"requests",
".",
"delete",
"(",
"url",
",",
"json",
"=",
"data",
",",
"headers",
"=",
"headers",
")",
"print",
"(",
"r",
")",
"response",
"=",
"dict",
"(",
")",
"if",
"\"No API key\"",
"in",
"str",
"(",
"r",
".",
"content",
".",
"decode",
"(",
"\"utf-8\"",
")",
")",
":",
"response",
"[",
"\"status\"",
"]",
"=",
"\"failure\"",
"r",
"=",
"json",
".",
"loads",
"(",
"r",
".",
"content",
".",
"decode",
"(",
"\"utf-8\"",
")",
")",
"[",
"'message'",
"]",
"elif",
"'unbind'",
"in",
"str",
"(",
"r",
".",
"content",
".",
"decode",
"(",
"\"utf-8\"",
")",
")",
":",
"response",
"[",
"\"status\"",
"]",
"=",
"\"success\"",
"r",
"=",
"r",
".",
"content",
".",
"decode",
"(",
"\"utf-8\"",
")",
"else",
":",
"response",
"[",
"\"status\"",
"]",
"=",
"\"failure\"",
"r",
"=",
"r",
".",
"content",
".",
"decode",
"(",
"\"utf-8\"",
")",
"response",
"[",
"\"response\"",
"]",
"=",
"str",
"(",
"r",
")",
"return",
"response"
] |
Read the options given on the command line and do the required actions .
|
def main ( ) : opts = docopt ( __doc__ , version = "cast 0.1" ) cast = pychromecast . PyChromecast ( CHROMECAST_HOST ) ramp = cast . get_protocol ( pychromecast . PROTOCOL_RAMP ) # Wait for ramp connection to be initted. time . sleep ( SLEEP_TIME ) if ramp is None : print 'Chromecast is not up or current app does not handle RAMP.' return 1 if opts [ 'next' ] : ramp . next ( ) elif opts [ 'pause' ] : ramp . pause ( ) elif opts [ 'play' ] : ramp . play ( ) elif opts [ 'toggle' ] : ramp . playpause ( ) elif opts [ 'seek' ] : ramp . seek ( opts [ '<second>' ] ) elif opts [ 'rewind' ] : ramp . rewind ( ) elif opts [ 'status' ] : _status_command ( cast , ramp ) elif opts [ 'volume' ] : _volume_command ( ramp , opts [ '<value>' ] ) # Wait for command to be sent. time . sleep ( SLEEP_TIME )
| 3,348
|
https://github.com/jaapz/cast/blob/1c451b11b7c9ce1c65d53ae1f4d2e44969676a1b/cast.py#L66-L101
|
[
"def",
"shared_volume_containers",
"(",
"self",
")",
":",
"for",
"container",
"in",
"self",
".",
"volumes",
".",
"share_with",
":",
"if",
"not",
"isinstance",
"(",
"container",
",",
"six",
".",
"string_types",
")",
":",
"yield",
"container",
".",
"name"
] |
Transform tokens back into Python source code . It returns a bytes object encoded using the ENCODING token which is the first token sequence output by tokenize .
|
def untokenize ( iterable ) : ut = Untokenizer ( ) out = ut . untokenize ( iterable ) if ut . encoding is not None : out = out . encode ( ut . encoding ) return out
| 3,349
|
https://github.com/JarryShaw/f2format/blob/a144250268247ce0a98d734a26d53faadff7a6f8/src/lib/tokenize.py#L312-L336
|
[
"def",
"set_intersection",
"(",
"self",
",",
"division",
",",
"intersection",
")",
":",
"IntersectRelationship",
".",
"objects",
".",
"filter",
"(",
"from_division",
"=",
"self",
",",
"to_division",
"=",
"division",
")",
".",
"update",
"(",
"intersection",
"=",
"intersection",
")"
] |
Get powers of 2 that sum up to the given number .
|
def get_powers_of_2 ( _sum ) : return [ 2 ** y for y , x in enumerate ( bin ( _sum ) [ : 1 : - 1 ] ) if int ( x ) ]
| 3,350
|
https://github.com/piotr-rusin/spam-lists/blob/fd616e8761b28f3eaa503fee5e45f7748e8f88f2/spam_lists/clients.py#L101-L115
|
[
"def",
"disconnect_controller",
"(",
"self",
",",
"vid",
",",
"pid",
",",
"serial",
")",
":",
"self",
".",
"lib",
".",
"tdDisconnectTellStickController",
"(",
"vid",
",",
"pid",
",",
"serial",
")"
] |
Query the DNSBL service for given value .
|
def _query ( self , host_object ) : host_to_query = host_object . relative_domain query_name = host_to_query . derelativize ( self . _query_suffix ) try : return query ( query_name ) except NXDOMAIN : return None
| 3,351
|
https://github.com/piotr-rusin/spam-lists/blob/fd616e8761b28f3eaa503fee5e45f7748e8f88f2/spam_lists/clients.py#L59-L72
|
[
"def",
"_process_data",
"(",
"self",
",",
"obj",
")",
":",
"assert",
"len",
"(",
"self",
".",
"_waiters",
")",
">",
"0",
",",
"(",
"type",
"(",
"obj",
")",
",",
"obj",
")",
"waiter",
",",
"encoding",
",",
"cb",
"=",
"self",
".",
"_waiters",
".",
"popleft",
"(",
")",
"if",
"isinstance",
"(",
"obj",
",",
"RedisError",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"ReplyError",
")",
":",
"if",
"obj",
".",
"args",
"[",
"0",
"]",
".",
"startswith",
"(",
"'READONLY'",
")",
":",
"obj",
"=",
"ReadOnlyError",
"(",
"obj",
".",
"args",
"[",
"0",
"]",
")",
"_set_exception",
"(",
"waiter",
",",
"obj",
")",
"if",
"self",
".",
"_in_transaction",
"is",
"not",
"None",
":",
"self",
".",
"_transaction_error",
"=",
"obj",
"else",
":",
"if",
"encoding",
"is",
"not",
"None",
":",
"try",
":",
"obj",
"=",
"decode",
"(",
"obj",
",",
"encoding",
")",
"except",
"Exception",
"as",
"exc",
":",
"_set_exception",
"(",
"waiter",
",",
"exc",
")",
"return",
"if",
"cb",
"is",
"not",
"None",
":",
"try",
":",
"obj",
"=",
"cb",
"(",
"obj",
")",
"except",
"Exception",
"as",
"exc",
":",
"_set_exception",
"(",
"waiter",
",",
"exc",
")",
"return",
"_set_result",
"(",
"waiter",
",",
"obj",
")",
"if",
"self",
".",
"_in_transaction",
"is",
"not",
"None",
":",
"self",
".",
"_in_transaction",
".",
"append",
"(",
"(",
"encoding",
",",
"cb",
")",
")"
] |
Query the client for data of given host .
|
def _query ( self , host_object , classification = False ) : template = 'http://verify.hosts-file.net/?v={}&s={}' url = template . format ( self . app_id , host_object . to_unicode ( ) ) url = url + '&class=true' if classification else url return get ( url ) . text
| 3,352
|
https://github.com/piotr-rusin/spam-lists/blob/fd616e8761b28f3eaa503fee5e45f7748e8f88f2/spam_lists/clients.py#L146-L158
|
[
"def",
"_slug_strip",
"(",
"self",
",",
"value",
")",
":",
"re_sep",
"=",
"'(?:-|%s)'",
"%",
"re",
".",
"escape",
"(",
"self",
".",
"separator",
")",
"value",
"=",
"re",
".",
"sub",
"(",
"'%s+'",
"%",
"re_sep",
",",
"self",
".",
"separator",
",",
"value",
")",
"return",
"re",
".",
"sub",
"(",
"r'^%s+|%s+$'",
"%",
"(",
"re_sep",
",",
"re_sep",
")",
",",
"''",
",",
"value",
")"
] |
Get address of a POST request to the service .
|
def _request_address ( self ) : if not self . _request_address_val : template = ( 'https://sb-ssl.google.com/safebrowsing/api/lookup' '?client={0}&key={1}&appver={2}&pver={3}' ) self . _request_address_val = template . format ( self . client_name , self . api_key , self . app_version , self . protocol_version ) return self . _request_address_val
| 3,353
|
https://github.com/piotr-rusin/spam-lists/blob/fd616e8761b28f3eaa503fee5e45f7748e8f88f2/spam_lists/clients.py#L192-L205
|
[
"def",
"prepare_blobs",
"(",
"self",
")",
":",
"self",
".",
"raw_header",
"=",
"self",
".",
"extract_header",
"(",
")",
"if",
"self",
".",
"cache_enabled",
":",
"self",
".",
"_cache_offsets",
"(",
")"
] |
Perform a single POST request using lookup API .
|
def _query_once ( self , urls ) : request_body = '{}\n{}' . format ( len ( urls ) , '\n' . join ( urls ) ) response = post ( self . _request_address , request_body ) try : response . raise_for_status ( ) except HTTPError as error : if response . status_code == 401 : msg = 'The API key is not authorized' raise_from ( UnathorizedAPIKeyError ( msg ) , error ) else : raise return response
| 3,354
|
https://github.com/piotr-rusin/spam-lists/blob/fd616e8761b28f3eaa503fee5e45f7748e8f88f2/spam_lists/clients.py#L207-L227
|
[
"def",
"sql_column_like_drug",
"(",
"self",
",",
"column_name",
":",
"str",
")",
"->",
"str",
":",
"clauses",
"=",
"[",
"\"{col} LIKE {fragment}\"",
".",
"format",
"(",
"col",
"=",
"column_name",
",",
"fragment",
"=",
"sql_string_literal",
"(",
"f",
")",
")",
"for",
"f",
"in",
"self",
".",
"sql_like_fragments",
"]",
"return",
"\"({})\"",
".",
"format",
"(",
"\" OR \"",
".",
"join",
"(",
"clauses",
")",
")"
] |
Test URLs for being listed by the service .
|
def _query ( self , urls ) : urls = list ( set ( urls ) ) for i in range ( 0 , len ( urls ) , self . max_urls_per_request ) : chunk = urls [ i : i + self . max_urls_per_request ] response = self . _query_once ( chunk ) if response . status_code == 200 : yield chunk , response
| 3,355
|
https://github.com/piotr-rusin/spam-lists/blob/fd616e8761b28f3eaa503fee5e45f7748e8f88f2/spam_lists/clients.py#L229-L243
|
[
"def",
"snappy_encode",
"(",
"payload",
",",
"xerial_compatible",
"=",
"False",
",",
"xerial_blocksize",
"=",
"32",
"*",
"1024",
")",
":",
"if",
"not",
"has_snappy",
"(",
")",
":",
"raise",
"NotImplementedError",
"(",
"\"Snappy codec is not available\"",
")",
"if",
"xerial_compatible",
":",
"def",
"_chunker",
"(",
")",
":",
"for",
"i",
"in",
"xrange",
"(",
"0",
",",
"len",
"(",
"payload",
")",
",",
"xerial_blocksize",
")",
":",
"yield",
"payload",
"[",
"i",
":",
"i",
"+",
"xerial_blocksize",
"]",
"out",
"=",
"BytesIO",
"(",
")",
"header",
"=",
"b''",
".",
"join",
"(",
"[",
"struct",
".",
"pack",
"(",
"'!'",
"+",
"fmt",
",",
"dat",
")",
"for",
"fmt",
",",
"dat",
"in",
"zip",
"(",
"_XERIAL_V1_FORMAT",
",",
"_XERIAL_V1_HEADER",
")",
"]",
")",
"out",
".",
"write",
"(",
"header",
")",
"for",
"chunk",
"in",
"_chunker",
"(",
")",
":",
"block",
"=",
"snappy",
".",
"compress",
"(",
"chunk",
")",
"block_size",
"=",
"len",
"(",
"block",
")",
"out",
".",
"write",
"(",
"struct",
".",
"pack",
"(",
"'!i'",
",",
"block_size",
")",
")",
"out",
".",
"write",
"(",
"block",
")",
"out",
".",
"seek",
"(",
"0",
")",
"return",
"out",
".",
"read",
"(",
")",
"else",
":",
"return",
"snappy",
".",
"compress",
"(",
"payload",
")"
] |
Get classification for all matching URLs .
|
def _get_match_and_classification ( self , urls ) : for url_list , response in self . _query ( urls ) : classification_set = response . text . splitlines ( ) for url , _class in zip ( url_list , classification_set ) : if _class != 'ok' : yield url , _class
| 3,356
|
https://github.com/piotr-rusin/spam-lists/blob/fd616e8761b28f3eaa503fee5e45f7748e8f88f2/spam_lists/clients.py#L256-L267
|
[
"def",
"fetch_extra_data",
"(",
"resource",
")",
":",
"person_id",
"=",
"resource",
".",
"get",
"(",
"'PersonID'",
",",
"[",
"None",
"]",
")",
"[",
"0",
"]",
"identity_class",
"=",
"resource",
".",
"get",
"(",
"'IdentityClass'",
",",
"[",
"None",
"]",
")",
"[",
"0",
"]",
"department",
"=",
"resource",
".",
"get",
"(",
"'Department'",
",",
"[",
"None",
"]",
")",
"[",
"0",
"]",
"return",
"dict",
"(",
"person_id",
"=",
"person_id",
",",
"identity_class",
"=",
"identity_class",
",",
"department",
"=",
"department",
")"
] |
Get items for all listed URLs .
|
def lookup_matching ( self , urls ) : for url , _class in self . _get_match_and_classification ( urls ) : classification = set ( _class . split ( ',' ) ) yield AddressListItem ( url , self , classification )
| 3,357
|
https://github.com/piotr-rusin/spam-lists/blob/fd616e8761b28f3eaa503fee5e45f7748e8f88f2/spam_lists/clients.py#L270-L280
|
[
"def",
"merge_cts_records",
"(",
"file_name",
",",
"crypto_idfp",
",",
"crypto_idfps",
")",
":",
"db",
"=",
"XonoticDB",
".",
"load_path",
"(",
"file_name",
")",
"db",
".",
"merge_cts_records",
"(",
"crypto_idfp",
",",
"crypto_idfps",
")",
"db",
".",
"save",
"(",
"file_name",
")"
] |
A view decorator to extend another view class or function to itself It will inherit all its methods and propeties and use them on itself
|
def extends_ ( cls , kls ) : if inspect . isclass ( kls ) : for _name , _val in kls . __dict__ . items ( ) : if not _name . startswith ( "__" ) : setattr ( cls , _name , _val ) elif inspect . isfunction ( kls ) : setattr ( cls , kls . __name__ , kls ) return cls
| 3,358
|
https://github.com/mardix/pylot/blob/506a33a56ebdfc0925b94015e8cf98ccb16a143c/pylot/__init__.py#L115-L150
|
[
"def",
"set_trial_config",
"(",
"experiment_config",
",",
"port",
",",
"config_file_name",
")",
":",
"request_data",
"=",
"dict",
"(",
")",
"request_data",
"[",
"'trial_config'",
"]",
"=",
"experiment_config",
"[",
"'trial'",
"]",
"response",
"=",
"rest_put",
"(",
"cluster_metadata_url",
"(",
"port",
")",
",",
"json",
".",
"dumps",
"(",
"request_data",
")",
",",
"REST_TIME_OUT",
")",
"if",
"check_response",
"(",
"response",
")",
":",
"return",
"True",
"else",
":",
"print",
"(",
"'Error message is {}'",
".",
"format",
"(",
"response",
".",
"text",
")",
")",
"_",
",",
"stderr_full_path",
"=",
"get_log_path",
"(",
"config_file_name",
")",
"if",
"response",
":",
"with",
"open",
"(",
"stderr_full_path",
",",
"'a+'",
")",
"as",
"fout",
":",
"fout",
".",
"write",
"(",
"json",
".",
"dumps",
"(",
"json",
".",
"loads",
"(",
"response",
".",
"text",
")",
",",
"indent",
"=",
"4",
",",
"sort_keys",
"=",
"True",
",",
"separators",
"=",
"(",
"','",
",",
"':'",
")",
")",
")",
"return",
"False"
] |
Send simple message
|
def send ( self , to , subject , body , reply_to = None , * * kwargs ) : if self . provider == "SES" : self . mail . send ( to = to , subject = subject , body = body , reply_to = reply_to , * * kwargs ) elif self . provider == "FLASK-MAIL" : msg = flask_mail . Message ( recipients = to , subject = subject , body = body , reply_to = reply_to , sender = self . app . config . get ( "MAIL_DEFAULT_SENDER" ) ) self . mail . send ( msg )
| 3,359
|
https://github.com/mardix/pylot/blob/506a33a56ebdfc0925b94015e8cf98ccb16a143c/pylot/__init__.py#L275-L288
|
[
"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"
] |
Send Template message
|
def send_template ( self , template , to , reply_to = None , * * context ) : if self . provider == "SES" : self . mail . send_template ( template = template , to = to , reply_to = reply_to , * * context ) elif self . provider == "FLASK-MAIL" : ses_mail = ses_mailer . Mail ( app = self . app ) data = ses_mail . parse_template ( template = template , * * context ) msg = flask_mail . Message ( recipients = to , subject = data [ "subject" ] , body = data [ "body" ] , reply_to = reply_to , sender = self . app . config . get ( "MAIL_DEFAULT_SENDER" ) ) self . mail . send ( msg )
| 3,360
|
https://github.com/mardix/pylot/blob/506a33a56ebdfc0925b94015e8cf98ccb16a143c/pylot/__init__.py#L290-L306
|
[
"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"
] |
Displays pylint data to the console .
|
def dump_to_console ( pylint_data ) : for key , value in list ( pylint_data . items ( ) ) : if key not in ( 'errors' , 'total' , 'scores' , 'average' ) and len ( value ) > 0 : print ( "\n*********** {}" . format ( key ) ) for line in value : print ( line . strip ( '\n' ) ) f_score = [ score [ 1 ] for score in pylint_data [ 'scores' ] if score [ 0 ] == key ] [ 0 ] print ( "Score: {}" . format ( f_score ) )
| 3,361
|
https://github.com/astraw38/lint/blob/162ceefcb812f07d18544aaa887b9ec4f102cfb1/lint/utils/general.py#L26-L39
|
[
"def",
"_get_optional_attrs",
"(",
"kws",
")",
":",
"vals",
"=",
"OboOptionalAttrs",
".",
"attributes",
".",
"intersection",
"(",
"kws",
".",
"keys",
"(",
")",
")",
"if",
"'sections'",
"in",
"kws",
":",
"vals",
".",
"add",
"(",
"'relationship'",
")",
"if",
"'norel'",
"in",
"kws",
":",
"vals",
".",
"discard",
"(",
"'relationship'",
")",
"return",
"vals"
] |
Post the data to gerrit . This right now is a stub as I ll need to write the code to post up to gerrit .
|
def post_to_gerrit ( commit , score = 0 , message = '' , user = 'lunatest' , gerrit = None ) : # ssh -p 29418 review.example.com gerrit review --code-review +1 <commit_id> if score > 0 : score = "+{}" . format ( score ) else : url = "{}job/{}/{}/consoleText" . format ( os . environ . get ( 'JENKINS_URL' ) , os . environ . get ( 'JOB_NAME' ) , os . environ . get ( 'BUILD_NUMBER' ) ) message = ( "{}\r\n\r\n" "Check output here: {}" ) . format ( message , url ) score = str ( score ) # Format the message in a way that is readable both by shell command #as well as Gerrit (need to double quote, once for shell, once for gerrit). message = "'\"{}\"'" . format ( message ) subprocess . check_output ( [ "ssh" , "-p" , str ( os . environ . get ( "GERRIT_PORT" , "29418" ) ) , "{}@{}" . format ( user , gerrit ) , "gerrit" , "review" , "--code-review " + score , "-m" , message , commit ] )
| 3,362
|
https://github.com/astraw38/lint/blob/162ceefcb812f07d18544aaa887b9ec4f102cfb1/lint/utils/general.py#L42-L72
|
[
"def",
"add_affiliation",
"(",
"self",
",",
"value",
",",
"curated_relation",
"=",
"None",
",",
"record",
"=",
"None",
")",
":",
"if",
"value",
":",
"affiliation",
"=",
"{",
"'value'",
":",
"value",
"}",
"if",
"record",
":",
"affiliation",
"[",
"'record'",
"]",
"=",
"record",
"if",
"curated_relation",
"is",
"not",
"None",
":",
"affiliation",
"[",
"'curated_relation'",
"]",
"=",
"curated_relation",
"self",
".",
"_ensure_list_field",
"(",
"'affiliations'",
",",
"affiliation",
")"
] |
Sorts a list of files into types .
|
def sort_by_type ( file_list ) : ret_dict = defaultdict ( list ) for filepath in file_list : _ , ext = os . path . splitext ( filepath ) ret_dict [ ext . replace ( '.' , '' ) ] . append ( filepath ) return ret_dict
| 3,363
|
https://github.com/astraw38/lint/blob/162ceefcb812f07d18544aaa887b9ec4f102cfb1/lint/utils/general.py#L75-L87
|
[
"def",
"aggregations",
"(",
"self",
")",
":",
"prev_month_start",
"=",
"get_prev_month",
"(",
"self",
".",
"end",
",",
"self",
".",
"query",
".",
"interval_",
")",
"self",
".",
"query",
".",
"since",
"(",
"prev_month_start",
")",
"agg",
"=",
"super",
"(",
")",
".",
"aggregations",
"(",
")",
"if",
"agg",
"is",
"None",
":",
"agg",
"=",
"0",
"# None is because NaN in ES. Let's convert to 0",
"return",
"agg"
] |
Check out target into the current directory . Target can be a branch review Id or commit .
|
def checkout ( repository , target ) : # git fetch <remote> refs/changes/<review_id> #git checkout FETCH_HEAD repository . git . fetch ( [ next ( iter ( repository . remotes ) ) , target ] ) repository . git . checkout ( "FETCH_HEAD" ) return repository . git . rev_parse ( [ "--short" , "HEAD" ] ) . encode ( 'ascii' , 'ignore' )
| 3,364
|
https://github.com/astraw38/lint/blob/162ceefcb812f07d18544aaa887b9ec4f102cfb1/lint/utils/git_utils.py#L6-L19
|
[
"def",
"get_cluster_port_names",
"(",
"self",
",",
"cluster_name",
")",
":",
"port_names",
"=",
"list",
"(",
")",
"for",
"host_name",
"in",
"self",
".",
"get_hosts_by_clusters",
"(",
")",
"[",
"cluster_name",
"]",
":",
"port_names",
".",
"extend",
"(",
"self",
".",
"get_hosts_by_name",
"(",
"host_name",
")",
")",
"return",
"port_names"
] |
Get a list of files changed compared to the given review . Compares against current directory .
|
def get_files_changed ( repository , review_id ) : repository . git . fetch ( [ next ( iter ( repository . remotes ) ) , review_id ] ) files_changed = repository . git . diff_tree ( [ "--no-commit-id" , "--name-only" , "-r" , "FETCH_HEAD" ] ) . splitlines ( ) print ( "Found {} files changed" . format ( len ( files_changed ) ) ) return files_changed
| 3,365
|
https://github.com/astraw38/lint/blob/162ceefcb812f07d18544aaa887b9ec4f102cfb1/lint/utils/git_utils.py#L22-L38
|
[
"def",
"shape_type",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_placeholder",
":",
"return",
"MSO_SHAPE_TYPE",
".",
"PLACEHOLDER",
"if",
"self",
".",
"_sp",
".",
"has_custom_geometry",
":",
"return",
"MSO_SHAPE_TYPE",
".",
"FREEFORM",
"if",
"self",
".",
"_sp",
".",
"is_autoshape",
":",
"return",
"MSO_SHAPE_TYPE",
".",
"AUTO_SHAPE",
"if",
"self",
".",
"_sp",
".",
"is_textbox",
":",
"return",
"MSO_SHAPE_TYPE",
".",
"TEXT_BOX",
"msg",
"=",
"'Shape instance of unrecognized shape type'",
"raise",
"NotImplementedError",
"(",
"msg",
")"
] |
Start the component running .
|
def start ( self ) : for name , child in self . _compound_children . items ( ) : self . logger . debug ( 'start %s (%s)' , name , child . __class__ . __name__ ) child . start ( )
| 3,366
|
https://github.com/jim-easterbrook/pyctools/blob/2a958665326892f45f249bebe62c2c23f306732b/src/pyctools/core/compound.py#L209-L213
|
[
"def",
"add_bookmark",
"(",
"request",
")",
":",
"if",
"request",
".",
"method",
"==",
"\"POST\"",
":",
"form",
"=",
"BookmarkForm",
"(",
"user",
"=",
"request",
".",
"user",
",",
"data",
"=",
"request",
".",
"POST",
")",
"if",
"form",
".",
"is_valid",
"(",
")",
":",
"bookmark",
"=",
"form",
".",
"save",
"(",
")",
"if",
"not",
"request",
".",
"is_ajax",
"(",
")",
":",
"messages",
".",
"success",
"(",
"request",
",",
"'Bookmark added'",
")",
"if",
"request",
".",
"POST",
".",
"get",
"(",
"'next'",
")",
":",
"return",
"HttpResponseRedirect",
"(",
"request",
".",
"POST",
".",
"get",
"(",
"'next'",
")",
")",
"return",
"HttpResponse",
"(",
"'Added'",
")",
"return",
"render_to_response",
"(",
"'admin_tools/menu/remove_bookmark_form.html'",
",",
"{",
"'bookmark'",
":",
"bookmark",
",",
"'url'",
":",
"bookmark",
".",
"url",
"}",
")",
"else",
":",
"form",
"=",
"BookmarkForm",
"(",
"user",
"=",
"request",
".",
"user",
")",
"return",
"render_to_response",
"(",
"'admin_tools/menu/form.html'",
",",
"{",
"'form'",
":",
"form",
",",
"'title'",
":",
"'Add Bookmark'",
"}",
")"
] |
Wait for the compound component s children to stop running .
|
def join ( self , end_comps = False ) : for name , child in self . _compound_children . items ( ) : if end_comps and not child . is_pipe_end ( ) : continue self . logger . debug ( 'join %s (%s)' , name , child . __class__ . __name__ ) child . join ( )
| 3,367
|
https://github.com/jim-easterbrook/pyctools/blob/2a958665326892f45f249bebe62c2c23f306732b/src/pyctools/core/compound.py#L221-L233
|
[
"def",
"cublasGetVersion",
"(",
"handle",
")",
":",
"version",
"=",
"ctypes",
".",
"c_int",
"(",
")",
"status",
"=",
"_libcublas",
".",
"cublasGetVersion_v2",
"(",
"handle",
",",
"ctypes",
".",
"byref",
"(",
"version",
")",
")",
"cublasCheckStatus",
"(",
"status",
")",
"return",
"version",
".",
"value"
] |
Do the bulk of the work
|
def main ( review_id , repository , branch = "development" , user = 'admin' , gerrit = None ) : checkout ( repository , branch ) raw_file_list = get_files_changed ( repository = repository , review_id = review_id ) checkout ( repository = repository , target = branch ) files = sort_by_type ( raw_file_list ) old_data = run_linters ( files ) commit_id = checkout ( repository = repository , target = review_id ) new_data = run_linters ( files ) dump_to_console ( new_data [ 'py' ] ) validations = run_validators ( new_data , old_data ) # Get the lowest score from all validators. final_score = min ( list ( validations . values ( ) ) , key = lambda x : x [ 0 ] ) [ 0 ] comment = "" for name , validation in list ( validations . items ( ) ) : score , message = validation # Each validator should return it's own specialized comment # Ex: 'Passed <name> Validation!\n', or 'Failed <name> Validation!\n<reasons/data>\n' if message [ - 1 : ] != "\n" : message += "\n" comment += message exit_code = 1 if final_score < 0 else 0 post_to_gerrit ( commit_id , score = final_score , message = comment , user = user , gerrit = gerrit ) exit ( exit_code )
| 3,368
|
https://github.com/astraw38/lint/blob/162ceefcb812f07d18544aaa887b9ec4f102cfb1/bin/gpylinter.py#L14-L55
|
[
"def",
"servertoken",
"(",
"self",
",",
"serverURL",
",",
"referer",
")",
":",
"if",
"self",
".",
"_server_token",
"is",
"None",
"or",
"self",
".",
"_server_token_expires_on",
"is",
"None",
"or",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
">=",
"self",
".",
"_server_token_expires_on",
"or",
"self",
".",
"_server_url",
"!=",
"serverURL",
":",
"self",
".",
"_server_url",
"=",
"serverURL",
"result",
"=",
"self",
".",
"_generateForServerTokenSecurity",
"(",
"serverURL",
"=",
"serverURL",
",",
"token",
"=",
"self",
".",
"token",
",",
"tokenUrl",
"=",
"self",
".",
"_token_url",
",",
"referer",
"=",
"referer",
")",
"if",
"'error'",
"in",
"result",
":",
"self",
".",
"_valid",
"=",
"False",
"self",
".",
"_message",
"=",
"result",
"else",
":",
"self",
".",
"_valid",
"=",
"True",
"self",
".",
"_message",
"=",
"\"Server Token Generated\"",
"return",
"self",
".",
"_server_token"
] |
Allows foreign keys to work in sqlite .
|
def set_sqlite_pragma ( dbapi_connection , connection_record ) : import sqlite3 if dbapi_connection . __class__ is sqlite3 . Connection : cursor = dbapi_connection . cursor ( ) cursor . execute ( "PRAGMA foreign_keys=ON" ) cursor . close ( )
| 3,369
|
https://github.com/nicfit/MishMash/blob/8f988936340bf0ffb83ea90ea124efb3c36a1174/mishmash/orm.py#L539-L545
|
[
"def",
"_read_header_lines",
"(",
"base_record_name",
",",
"dir_name",
",",
"pb_dir",
")",
":",
"file_name",
"=",
"base_record_name",
"+",
"'.hea'",
"# Read local file",
"if",
"pb_dir",
"is",
"None",
":",
"with",
"open",
"(",
"os",
".",
"path",
".",
"join",
"(",
"dir_name",
",",
"file_name",
")",
",",
"'r'",
")",
"as",
"fp",
":",
"# Record line followed by signal/segment lines if any",
"header_lines",
"=",
"[",
"]",
"# Comment lines",
"comment_lines",
"=",
"[",
"]",
"for",
"line",
"in",
"fp",
":",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"# Comment line",
"if",
"line",
".",
"startswith",
"(",
"'#'",
")",
":",
"comment_lines",
".",
"append",
"(",
"line",
")",
"# Non-empty non-comment line = header line.",
"elif",
"line",
":",
"# Look for a comment in the line",
"ci",
"=",
"line",
".",
"find",
"(",
"'#'",
")",
"if",
"ci",
">",
"0",
":",
"header_lines",
".",
"append",
"(",
"line",
"[",
":",
"ci",
"]",
")",
"# comment on same line as header line",
"comment_lines",
".",
"append",
"(",
"line",
"[",
"ci",
":",
"]",
")",
"else",
":",
"header_lines",
".",
"append",
"(",
"line",
")",
"# Read online header file",
"else",
":",
"header_lines",
",",
"comment_lines",
"=",
"download",
".",
"_stream_header",
"(",
"file_name",
",",
"pb_dir",
")",
"return",
"header_lines",
",",
"comment_lines"
] |
Iterate over all triples in the graph and validate each one appropriately
|
def validate ( self ) : log . info ( "{}\nValidating against {}" . format ( "-" * 100 , self . schema_def . __class__ . __name__ ) ) if not self . schema_def : raise ValueError ( "No schema definition supplied." ) self . checked_attributes = [ ] # TODO - this should maybe choose the actually used namespace, not just # the first one in the list result = ValidationResult ( self . allowed_namespaces [ 0 ] , self . schema_def . __class__ . __name__ ) for subject , predicate , object_ in self . graph : log . info ( "\nsubj: {subj}\npred: {pred}\n obj: {obj}" . format ( subj = subject , pred = predicate , obj = object_ . encode ( 'utf-8' ) ) ) result . add_error ( self . _check_triple ( ( subject , predicate , object_ ) ) ) return result
| 3,370
|
https://github.com/Parsely/schemato/blob/7002316fbcd52f2e669f8372bf1338c572e3df4b/schemato/validator.py#L34-L55
|
[
"def",
"_adapt_WSDateTime",
"(",
"dt",
")",
":",
"try",
":",
"ts",
"=",
"int",
"(",
"(",
"dt",
".",
"replace",
"(",
"tzinfo",
"=",
"pytz",
".",
"utc",
")",
"-",
"datetime",
"(",
"1970",
",",
"1",
",",
"1",
",",
"tzinfo",
"=",
"pytz",
".",
"utc",
")",
")",
".",
"total_seconds",
"(",
")",
")",
"except",
"(",
"OverflowError",
",",
"OSError",
")",
":",
"if",
"dt",
"<",
"datetime",
".",
"now",
"(",
")",
":",
"ts",
"=",
"0",
"else",
":",
"ts",
"=",
"2",
"**",
"63",
"-",
"1",
"return",
"ts"
] |
compare triple to ontology return error or None
|
def _check_triple ( self , triple ) : subj , pred , obj = triple if self . _should_ignore_predicate ( pred ) : log . info ( "Ignoring triple with predicate '{}'" . format ( self . _field_name_from_uri ( pred ) ) ) return classes = [ ] log . warning ( "Possible member %s found" % pred ) pred = self . _expand_qname ( pred ) if self . _namespace_from_uri ( pred ) not in self . allowed_namespaces : log . info ( "Member %s does not use an allowed namespace" , pred ) return instanceof = self . _is_instance ( ( subj , pred , obj ) ) if type ( instanceof ) == rt . URIRef : instanceof = self . _expand_qname ( instanceof ) if hasattr ( self . schema_def , "attributes_by_class" ) and not self . schema_def . attributes_by_class : log . info ( "Parsed ontology not found. Parsing..." ) self . schema_def . parse_ontology ( ) class_invalid = self . _validate_class ( instanceof ) if class_invalid : log . warning ( "Invalid class %s" % instanceof ) return class_invalid # TODO - the above sometimes fails when a single object has more than # one rdfa type (eg <span property="schema:creator rnews:creator" # typeof="schema:Person rnews:Person"> # Graph chooses the type in an arbitrary order, so it's unreliable # eg: http://semanticweb.com/the-impact-of-rdfa_b35003 classes = self . _superclasses_for_subject ( self . graph , instanceof ) classes . append ( instanceof ) member_invalid = self . _validate_member ( pred , classes , instanceof ) if member_invalid : log . warning ( "Invalid member of class" ) return member_invalid dupe_invalid = self . _validate_duplication ( ( subj , pred ) , instanceof ) if dupe_invalid : log . warning ( "Duplication found" ) return dupe_invalid # collect a list of checked attributes self . checked_attributes . append ( ( subj , pred ) ) log . warning ( "successfully validated triple, no errors" ) return
| 3,371
|
https://github.com/Parsely/schemato/blob/7002316fbcd52f2e669f8372bf1338c572e3df4b/schemato/validator.py#L61-L114
|
[
"def",
"secure",
"(",
"self",
")",
":",
"log",
".",
"debug",
"(",
"'ConCache securing sockets'",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"cache_sock",
")",
":",
"os",
".",
"chmod",
"(",
"self",
".",
"cache_sock",
",",
"0o600",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"update_sock",
")",
":",
"os",
".",
"chmod",
"(",
"self",
".",
"update_sock",
",",
"0o600",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"upd_t_sock",
")",
":",
"os",
".",
"chmod",
"(",
"self",
".",
"upd_t_sock",
",",
"0o600",
")"
] |
return error if class cl is not found in the ontology
|
def _validate_class ( self , cl ) : if cl not in self . schema_def . attributes_by_class : search_string = self . _build_search_string ( cl ) err = self . err ( "{0} - invalid class" , self . _field_name_from_uri ( cl ) , search_string = search_string ) return ValidationWarning ( ValidationResult . ERROR , err [ 'err' ] , err [ 'line' ] , err [ 'num' ] )
| 3,372
|
https://github.com/Parsely/schemato/blob/7002316fbcd52f2e669f8372bf1338c572e3df4b/schemato/validator.py#L116-L124
|
[
"def",
"run",
"(",
"self",
",",
"handler",
")",
":",
"import",
"eventlet",
".",
"patcher",
"if",
"not",
"eventlet",
".",
"patcher",
".",
"is_monkey_patched",
"(",
"os",
")",
":",
"msg",
"=",
"(",
"\"%s requires eventlet.monkey_patch() (before \"",
"\"import)\"",
"%",
"self",
".",
"__class__",
".",
"__name__",
")",
"raise",
"RuntimeError",
"(",
"msg",
")",
"# Separate out wsgi.server arguments",
"wsgi_args",
"=",
"{",
"}",
"for",
"arg",
"in",
"(",
"'log'",
",",
"'environ'",
",",
"'max_size'",
",",
"'max_http_version'",
",",
"'protocol'",
",",
"'server_event'",
",",
"'minimum_chunk_size'",
",",
"'log_x_forwarded_for'",
",",
"'custom_pool'",
",",
"'keepalive'",
",",
"'log_output'",
",",
"'log_format'",
",",
"'url_length_limit'",
",",
"'debug'",
",",
"'socket_timeout'",
",",
"'capitalize_response_headers'",
")",
":",
"try",
":",
"wsgi_args",
"[",
"arg",
"]",
"=",
"self",
".",
"options",
".",
"pop",
"(",
"arg",
")",
"except",
"KeyError",
":",
"pass",
"if",
"'log_output'",
"not",
"in",
"wsgi_args",
":",
"wsgi_args",
"[",
"'log_output'",
"]",
"=",
"not",
"self",
".",
"quiet",
"import",
"eventlet",
".",
"wsgi",
"sock",
"=",
"self",
".",
"options",
".",
"pop",
"(",
"'shared_socket'",
",",
"None",
")",
"or",
"self",
".",
"get_socket",
"(",
")",
"eventlet",
".",
"wsgi",
".",
"server",
"(",
"sock",
",",
"handler",
",",
"*",
"*",
"wsgi_args",
")"
] |
return error if member is not a member of any class in classes
|
def _validate_member ( self , member , classes , instanceof ) : log . info ( "Validating member %s" % member ) stripped = self . _get_stripped_attributes ( member , classes ) if self . _field_name_from_uri ( member ) in stripped : all_class_members = sum ( [ self . schema_def . attributes_by_class [ cl ] for cl in classes ] , [ ] ) if member in all_class_members : return if self . _namespace_from_uri ( member ) in self . allowed_namespaces : err = self . err ( "Unoficially allowed namespace {0}" , self . _namespace_from_uri ( member ) ) return ValidationWarning ( ValidationResult . WARNING , err [ 'err' ] , err [ 'line' ] , err [ 'num' ] ) else : err = self . err ( "{0} - invalid member of {1}" , self . _field_name_from_uri ( member ) , self . _field_name_from_uri ( instanceof ) ) return ValidationWarning ( ValidationResult . ERROR , err [ 'err' ] , err [ 'line' ] , err [ 'num' ] )
| 3,373
|
https://github.com/Parsely/schemato/blob/7002316fbcd52f2e669f8372bf1338c572e3df4b/schemato/validator.py#L138-L160
|
[
"def",
"save_scatter_table",
"(",
"self",
",",
"fn",
",",
"description",
"=",
"\"\"",
")",
":",
"data",
"=",
"{",
"\"description\"",
":",
"description",
",",
"\"time\"",
":",
"datetime",
".",
"now",
"(",
")",
",",
"\"psd_scatter\"",
":",
"(",
"self",
".",
"num_points",
",",
"self",
".",
"D_max",
",",
"self",
".",
"_psd_D",
",",
"self",
".",
"_S_table",
",",
"self",
".",
"_Z_table",
",",
"self",
".",
"_angular_table",
",",
"self",
".",
"_m_table",
",",
"self",
".",
"geometries",
")",
",",
"\"version\"",
":",
"tmatrix_aux",
".",
"VERSION",
"}",
"pickle",
".",
"dump",
"(",
"data",
",",
"file",
"(",
"fn",
",",
"'w'",
")",
",",
"pickle",
".",
"HIGHEST_PROTOCOL",
")"
] |
returns error if we ve already seen the member pred on subj
|
def _validate_duplication ( self , subj_and_pred , cl ) : subj , pred = subj_and_pred log . info ( "Validating duplication of member %s" % pred ) if ( subj , pred ) in self . checked_attributes : err = self . err ( "{0} - duplicated member of {1}" , self . _field_name_from_uri ( pred ) , self . _field_name_from_uri ( cl ) ) return ValidationWarning ( ValidationResult . WARNING , err [ 'err' ] , err [ 'line' ] , err [ 'num' ] )
| 3,374
|
https://github.com/Parsely/schemato/blob/7002316fbcd52f2e669f8372bf1338c572e3df4b/schemato/validator.py#L162-L172
|
[
"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.\"",
")"
] |
helper returns a list of all superclasses of a given class
|
def _superclasses_for_subject ( self , graph , typeof ) : # TODO - this might be replacing a fairly simple graph API query where # it doesn't need to classes = [ ] superclass = typeof while True : found = False for p , o in self . schema_def . ontology [ superclass ] : if self . schema_def . lexicon [ 'subclass' ] == str ( p ) : found = True classes . append ( o ) superclass = o if not found : break return classes
| 3,375
|
https://github.com/Parsely/schemato/blob/7002316fbcd52f2e669f8372bf1338c572e3df4b/schemato/validator.py#L174-L189
|
[
"def",
"render",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"available",
"(",
")",
":",
"return",
"\"\"",
"mtool",
"=",
"api",
".",
"get_tool",
"(",
"\"portal_membership\"",
")",
"member",
"=",
"mtool",
".",
"getAuthenticatedMember",
"(",
")",
"roles",
"=",
"member",
".",
"getRoles",
"(",
")",
"allowed",
"=",
"\"LabManager\"",
"in",
"roles",
"or",
"\"Manager\"",
"in",
"roles",
"self",
".",
"get_failed_instruments",
"(",
")",
"if",
"allowed",
"and",
"self",
".",
"nr_failed",
":",
"return",
"self",
".",
"index",
"(",
")",
"else",
":",
"return",
"\"\""
] |
helper returns the class type of subj
|
def _is_instance ( self , triple ) : subj , pred , obj = triple input_pred_ns = self . _namespace_from_uri ( self . _expand_qname ( pred ) ) triples = self . graph . triples ( ( subj , rt . URIRef ( self . schema_def . lexicon [ 'type' ] ) , None ) ) if triples : for tr in triples : triple_obj_ns = self . _namespace_from_uri ( self . _expand_qname ( tr [ 2 ] ) ) if input_pred_ns == triple_obj_ns : # match namespaces return tr [ 2 ]
| 3,376
|
https://github.com/Parsely/schemato/blob/7002316fbcd52f2e669f8372bf1338c572e3df4b/schemato/validator.py#L191-L203
|
[
"def",
"db_create",
"(",
"cls",
",",
"impl",
",",
"working_dir",
")",
":",
"global",
"VIRTUALCHAIN_DB_SCRIPT",
"log",
".",
"debug",
"(",
"\"Setup chain state in {}\"",
".",
"format",
"(",
"working_dir",
")",
")",
"path",
"=",
"config",
".",
"get_snapshots_filename",
"(",
"impl",
",",
"working_dir",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"raise",
"Exception",
"(",
"\"Database {} already exists\"",
")",
"lines",
"=",
"[",
"l",
"+",
"\";\"",
"for",
"l",
"in",
"VIRTUALCHAIN_DB_SCRIPT",
".",
"split",
"(",
"\";\"",
")",
"]",
"con",
"=",
"sqlite3",
".",
"connect",
"(",
"path",
",",
"isolation_level",
"=",
"None",
",",
"timeout",
"=",
"2",
"**",
"30",
")",
"for",
"line",
"in",
"lines",
":",
"con",
".",
"execute",
"(",
"line",
")",
"con",
".",
"row_factory",
"=",
"StateEngine",
".",
"db_row_factory",
"return",
"con"
] |
returns the expanded namespace prefix of a uri
|
def _namespace_from_uri ( self , uri ) : # TODO - this could be helped a bunch with proper use of the graph API # it seems a bit fragile to treat these as simple string-splits uri = str ( uri ) parts = uri . split ( '#' ) if len ( parts ) == 1 : return "%s/" % '/' . join ( uri . split ( '/' ) [ : - 1 ] ) return "%s#" % '#' . join ( parts [ : - 1 ] )
| 3,377
|
https://github.com/Parsely/schemato/blob/7002316fbcd52f2e669f8372bf1338c572e3df4b/schemato/validator.py#L215-L223
|
[
"def",
"verify_manifest_main_checksum",
"(",
"self",
",",
"manifest",
")",
":",
"# NOTE: JAR spec does not state whether there can be >1 digest used,",
"# and should the validator require any or all digests to match.",
"# We allow mismatching digests and require just one to be correct.",
"# We see no security risk: it is the signer of the .SF file",
"# who shall check, what is being signed.",
"for",
"java_digest",
"in",
"self",
".",
"keys_with_suffix",
"(",
"\"-Digest-Manifest\"",
")",
":",
"whole_mf_digest",
"=",
"b64_encoded_digest",
"(",
"manifest",
".",
"get_data",
"(",
")",
",",
"_get_digest",
"(",
"java_digest",
")",
")",
"# It is enough for at least one digest to be correct",
"if",
"whole_mf_digest",
"==",
"self",
".",
"get",
"(",
"java_digest",
"+",
"\"-Digest-Manifest\"",
")",
":",
"return",
"True",
"return",
"False"
] |
expand a qualified name s namespace prefix to include the resolved namespace root url
|
def _expand_qname ( self , qname ) : if type ( qname ) is not rt . URIRef : raise TypeError ( "Cannot expand qname of type {}, must be URIRef" . format ( type ( qname ) ) ) for ns in self . graph . namespaces ( ) : if ns [ 0 ] == qname . split ( ':' ) [ 0 ] : return rt . URIRef ( "%s%s" % ( ns [ 1 ] , qname . split ( ':' ) [ - 1 ] ) ) return qname
| 3,378
|
https://github.com/Parsely/schemato/blob/7002316fbcd52f2e669f8372bf1338c572e3df4b/schemato/validator.py#L225-L234
|
[
"def",
"load_contents",
"(",
"self",
")",
":",
"with",
"open",
"(",
"METADATA_FILE",
")",
"as",
"f",
":",
"lines",
"=",
"f",
".",
"readlines",
"(",
")",
"lines",
"=",
"map",
"(",
"lambda",
"x",
":",
"x",
".",
"strip",
"(",
")",
",",
"lines",
")",
"exclude_strings",
"=",
"[",
"'<begin_table>'",
",",
"'<end_table>'",
"]",
"list_of_databases_and_columns",
"=",
"filter",
"(",
"lambda",
"x",
":",
"not",
"x",
"[",
"0",
"]",
"in",
"exclude_strings",
",",
"[",
"list",
"(",
"value",
")",
"for",
"key",
",",
"value",
"in",
"itertools",
".",
"groupby",
"(",
"lines",
",",
"lambda",
"x",
":",
"x",
"in",
"exclude_strings",
")",
"]",
")",
"for",
"iterator",
"in",
"list_of_databases_and_columns",
":",
"self",
".",
"create_table_raw",
"(",
"tablename",
"=",
"iterator",
"[",
"0",
"]",
",",
"columns",
"=",
"iterator",
"[",
"1",
":",
"]",
"[",
":",
"]",
",",
")",
"for",
"i",
"in",
"self",
".",
"tables",
":",
"i",
".",
"load_contents",
"(",
")"
] |
Downloads ports data from IANA & Wikipedia and converts it to a python module . This function is used to generate _ranges . py .
|
def _write_unassigned_ranges ( out_filename ) : with open ( out_filename , 'wt' ) as f : f . write ( '# auto-generated by port_for._download_ranges (%s)\n' % datetime . date . today ( ) ) f . write ( 'UNASSIGNED_RANGES = [\n' ) for range in to_ranges ( sorted ( list ( _unassigned_ports ( ) ) ) ) : f . write ( " (%d, %d),\n" % range ) f . write ( ']\n' )
| 3,379
|
https://github.com/kmike/port-for/blob/f61ebf3c2caf54eabe8233b40ef67b973176a6f5/port_for/_download_ranges.py#L24-L34
|
[
"def",
"_node_has_namespace_helper",
"(",
"node",
":",
"BaseEntity",
",",
"namespace",
":",
"str",
")",
"->",
"bool",
":",
"return",
"namespace",
"==",
"node",
".",
"get",
"(",
"NAMESPACE",
")"
] |
Returns used port ranges according to Wikipedia page . This page contains unofficial well - known ports .
|
def _wikipedia_known_port_ranges ( ) : req = urllib2 . Request ( WIKIPEDIA_PAGE , headers = { 'User-Agent' : "Magic Browser" } ) page = urllib2 . urlopen ( req ) . read ( ) . decode ( 'utf8' ) # just find all numbers in table cells ports = re . findall ( '<td>((\d+)(\W(\d+))?)</td>' , page , re . U ) return ( ( int ( p [ 1 ] ) , int ( p [ 3 ] if p [ 3 ] else p [ 1 ] ) ) for p in ports )
| 3,380
|
https://github.com/kmike/port-for/blob/f61ebf3c2caf54eabe8233b40ef67b973176a6f5/port_for/_download_ranges.py#L44-L54
|
[
"def",
"get_epoch_namespace_lifetime_multiplier",
"(",
"block_height",
",",
"namespace_id",
")",
":",
"epoch_config",
"=",
"get_epoch_config",
"(",
"block_height",
")",
"if",
"epoch_config",
"[",
"'namespaces'",
"]",
".",
"has_key",
"(",
"namespace_id",
")",
":",
"return",
"epoch_config",
"[",
"'namespaces'",
"]",
"[",
"namespace_id",
"]",
"[",
"'NAMESPACE_LIFETIME_MULTIPLIER'",
"]",
"else",
":",
"return",
"epoch_config",
"[",
"'namespaces'",
"]",
"[",
"'*'",
"]",
"[",
"'NAMESPACE_LIFETIME_MULTIPLIER'",
"]"
] |
Returns unassigned port ranges according to IANA .
|
def _iana_unassigned_port_ranges ( ) : page = urllib2 . urlopen ( IANA_DOWNLOAD_URL ) . read ( ) xml = ElementTree . fromstring ( page ) records = xml . findall ( '{%s}record' % IANA_NS ) for record in records : description = record . find ( '{%s}description' % IANA_NS ) . text if description == 'Unassigned' : numbers = record . find ( '{%s}number' % IANA_NS ) . text yield numbers
| 3,381
|
https://github.com/kmike/port-for/blob/f61ebf3c2caf54eabe8233b40ef67b973176a6f5/port_for/_download_ranges.py#L57-L68
|
[
"def",
"load",
"(",
"self",
",",
"cachedir",
"=",
"None",
",",
"cfgstr",
"=",
"None",
",",
"fpath",
"=",
"None",
",",
"verbose",
"=",
"None",
",",
"quiet",
"=",
"QUIET",
",",
"ignore_keys",
"=",
"None",
")",
":",
"if",
"verbose",
"is",
"None",
":",
"verbose",
"=",
"getattr",
"(",
"self",
",",
"'verbose'",
",",
"VERBOSE",
")",
"if",
"fpath",
"is",
"None",
":",
"fpath",
"=",
"self",
".",
"get_fpath",
"(",
"cachedir",
",",
"cfgstr",
"=",
"cfgstr",
")",
"if",
"verbose",
":",
"print",
"(",
"'[Cachable] cache tryload: %r'",
"%",
"(",
"basename",
"(",
"fpath",
")",
",",
")",
")",
"try",
":",
"self",
".",
"_unsafe_load",
"(",
"fpath",
",",
"ignore_keys",
")",
"if",
"verbose",
":",
"print",
"(",
"'... self cache hit: %r'",
"%",
"(",
"basename",
"(",
"fpath",
")",
",",
")",
")",
"except",
"ValueError",
"as",
"ex",
":",
"import",
"utool",
"as",
"ut",
"msg",
"=",
"'[!Cachable] Cachable(%s) is likely corrupt'",
"%",
"(",
"self",
".",
"get_cfgstr",
"(",
")",
")",
"print",
"(",
"'CORRUPT fpath = %s'",
"%",
"(",
"fpath",
",",
")",
")",
"ut",
".",
"printex",
"(",
"ex",
",",
"msg",
",",
"iswarning",
"=",
"True",
")",
"raise",
"#except BadZipFile as ex:",
"except",
"zipfile",
".",
"error",
"as",
"ex",
":",
"import",
"utool",
"as",
"ut",
"msg",
"=",
"'[!Cachable] Cachable(%s) has bad zipfile'",
"%",
"(",
"self",
".",
"get_cfgstr",
"(",
")",
")",
"print",
"(",
"'CORRUPT fpath = %s'",
"%",
"(",
"fpath",
",",
")",
")",
"ut",
".",
"printex",
"(",
"ex",
",",
"msg",
",",
"iswarning",
"=",
"True",
")",
"raise",
"#if exists(fpath):",
"# #print('[Cachable] Removing corrupted file: %r' % fpath)",
"# #os.remove(fpath)",
"# raise hsexcept.HotsNeedsRecomputeError(msg)",
"#else:",
"# raise Exception(msg)",
"except",
"IOError",
"as",
"ex",
":",
"import",
"utool",
"as",
"ut",
"if",
"not",
"exists",
"(",
"fpath",
")",
":",
"msg",
"=",
"'... self cache miss: %r'",
"%",
"(",
"basename",
"(",
"fpath",
")",
",",
")",
"if",
"verbose",
":",
"print",
"(",
"msg",
")",
"raise",
"print",
"(",
"'CORRUPT fpath = %s'",
"%",
"(",
"fpath",
",",
")",
")",
"msg",
"=",
"'[!Cachable] Cachable(%s) is corrupt'",
"%",
"(",
"self",
".",
"get_cfgstr",
"(",
")",
")",
"ut",
".",
"printex",
"(",
"ex",
",",
"msg",
",",
"iswarning",
"=",
"True",
")",
"raise",
"except",
"Exception",
"as",
"ex",
":",
"import",
"utool",
"as",
"ut",
"ut",
".",
"printex",
"(",
"ex",
",",
"'unknown exception while loading query result'",
")",
"raise"
] |
Run through file list and try to find a linter that matches the given file type .
|
def run_linters ( files ) : data = { } for file_type , file_list in list ( files . items ( ) ) : linter = LintFactory . get_linter ( file_type ) if linter is not None : data [ file_type ] = linter . run ( file_list ) return data
| 3,382
|
https://github.com/astraw38/lint/blob/162ceefcb812f07d18544aaa887b9ec4f102cfb1/lint/main.py#L12-L28
|
[
"def",
"prox_unity",
"(",
"X",
",",
"step",
",",
"axis",
"=",
"0",
")",
":",
"return",
"X",
"/",
"np",
".",
"sum",
"(",
"X",
",",
"axis",
"=",
"axis",
",",
"keepdims",
"=",
"True",
")"
] |
Run through all matching validators .
|
def run_validators ( new_data , old_data ) : #{'validator_name': (success, score, message)} validation_data = { } for file_type , lint_data in list ( new_data . items ( ) ) : #TODO: What to do if old data doesn't have this filetype? old_lint_data = old_data . get ( file_type , { } ) validator = ValidatorFactory . get_validator ( file_type ) if validator is not None : validation_data [ validator . name ] = validator . run ( lint_data , old_lint_data ) return validation_data
| 3,383
|
https://github.com/astraw38/lint/blob/162ceefcb812f07d18544aaa887b9ec4f102cfb1/lint/main.py#L31-L47
|
[
"def",
"make_measurement",
"(",
"name",
",",
"channels",
",",
"lumi",
"=",
"1.0",
",",
"lumi_rel_error",
"=",
"0.1",
",",
"output_prefix",
"=",
"'./histfactory'",
",",
"POI",
"=",
"None",
",",
"const_params",
"=",
"None",
",",
"verbose",
"=",
"False",
")",
":",
"if",
"verbose",
":",
"llog",
"=",
"log",
"[",
"'make_measurement'",
"]",
"llog",
".",
"info",
"(",
"\"creating measurement {0}\"",
".",
"format",
"(",
"name",
")",
")",
"if",
"not",
"isinstance",
"(",
"channels",
",",
"(",
"list",
",",
"tuple",
")",
")",
":",
"channels",
"=",
"[",
"channels",
"]",
"# Create the measurement",
"meas",
"=",
"Measurement",
"(",
"'measurement_{0}'",
".",
"format",
"(",
"name",
")",
",",
"''",
")",
"meas",
".",
"SetOutputFilePrefix",
"(",
"output_prefix",
")",
"if",
"POI",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"POI",
",",
"string_types",
")",
":",
"if",
"verbose",
":",
"llog",
".",
"info",
"(",
"\"setting POI {0}\"",
".",
"format",
"(",
"POI",
")",
")",
"meas",
".",
"SetPOI",
"(",
"POI",
")",
"else",
":",
"if",
"verbose",
":",
"llog",
".",
"info",
"(",
"\"adding POIs {0}\"",
".",
"format",
"(",
"', '",
".",
"join",
"(",
"POI",
")",
")",
")",
"for",
"p",
"in",
"POI",
":",
"meas",
".",
"AddPOI",
"(",
"p",
")",
"if",
"verbose",
":",
"llog",
".",
"info",
"(",
"\"setting lumi={0:f} +/- {1:f}\"",
".",
"format",
"(",
"lumi",
",",
"lumi_rel_error",
")",
")",
"meas",
".",
"lumi",
"=",
"lumi",
"meas",
".",
"lumi_rel_error",
"=",
"lumi_rel_error",
"for",
"channel",
"in",
"channels",
":",
"if",
"verbose",
":",
"llog",
".",
"info",
"(",
"\"adding channel {0}\"",
".",
"format",
"(",
"channel",
".",
"GetName",
"(",
")",
")",
")",
"meas",
".",
"AddChannel",
"(",
"channel",
")",
"if",
"const_params",
"is",
"not",
"None",
":",
"if",
"verbose",
":",
"llog",
".",
"info",
"(",
"\"adding constant parameters {0}\"",
".",
"format",
"(",
"', '",
".",
"join",
"(",
"const_params",
")",
")",
")",
"for",
"param",
"in",
"const_params",
":",
"meas",
".",
"AddConstantParam",
"(",
"param",
")",
"return",
"meas"
] |
Since we need to use this sometimes
|
def original_unescape ( self , s ) : if isinstance ( s , basestring ) : return unicode ( HTMLParser . unescape ( self , s ) ) elif isinstance ( s , list ) : return [ unicode ( HTMLParser . unescape ( self , item ) ) for item in s ] else : return s
| 3,384
|
https://github.com/Parsely/schemato/blob/7002316fbcd52f2e669f8372bf1338c572e3df4b/schemato/schemas/parselypage.py#L35-L42
|
[
"def",
"read_struct",
"(",
"fstream",
")",
":",
"line",
"=",
"fstream",
".",
"readline",
"(",
")",
".",
"strip",
"(",
")",
"fragments",
"=",
"line",
".",
"split",
"(",
"\",\"",
")",
"fragments",
"=",
"[",
"x",
"for",
"x",
"in",
"fragments",
"if",
"x",
"is",
"not",
"None",
"]",
"partition",
"=",
"dict",
"(",
")",
"if",
"not",
"len",
"(",
"fragments",
")",
">=",
"3",
":",
"return",
"None",
"partition",
"[",
"\"struct\"",
"]",
"=",
"fragments",
"[",
"0",
"]",
"partition",
"[",
"\"info\"",
"]",
"=",
"fragments",
"[",
"1",
"]",
"partition",
"[",
"\"num_lines\"",
"]",
"=",
"fragments",
"[",
"2",
"]",
"struct",
"=",
"None",
"if",
"partition",
"is",
"not",
"None",
"and",
"partition",
"[",
"\"struct\"",
"]",
"==",
"\"STRUCT\"",
":",
"num_lines",
"=",
"int",
"(",
"partition",
"[",
"\"num_lines\"",
"]",
".",
"strip",
"(",
")",
")",
"struct",
"=",
"{",
"}",
"for",
"_",
"in",
"range",
"(",
"num_lines",
")",
":",
"cols",
"=",
"fetch_cols",
"(",
"fstream",
")",
"struct",
".",
"update",
"(",
"{",
"cols",
"[",
"0",
"]",
":",
"cols",
"[",
"1",
":",
"]",
"}",
")",
"return",
"struct"
] |
get list of allowed parameters
|
def get_standard ( self ) : try : res = urlopen ( PARSELY_PAGE_SCHEMA ) except : return [ ] text = res . read ( ) if isinstance ( text , bytes ) : text = text . decode ( 'utf-8' ) tree = etree . parse ( StringIO ( text ) ) stdref = tree . xpath ( "//div/@about" ) return [ a . split ( ':' ) [ 1 ] for a in stdref ]
| 3,385
|
https://github.com/Parsely/schemato/blob/7002316fbcd52f2e669f8372bf1338c572e3df4b/schemato/schemas/parselypage.py#L56-L67
|
[
"def",
"parse_tophat_log",
"(",
"self",
",",
"raw_data",
")",
":",
"if",
"'Aligned pairs'",
"in",
"raw_data",
":",
"# Paired end data",
"regexes",
"=",
"{",
"'overall_aligned_percent'",
":",
"r\"([\\d\\.]+)% overall read mapping rate.\"",
",",
"'concordant_aligned_percent'",
":",
"r\"([\\d\\.]+)% concordant pair alignment rate.\"",
",",
"'aligned_total'",
":",
"r\"Aligned pairs:\\s+(\\d+)\"",
",",
"'aligned_multimap'",
":",
"r\"Aligned pairs:\\s+\\d+\\n\\s+of these:\\s+(\\d+)\"",
",",
"'aligned_discordant'",
":",
"r\"(\\d+) \\([\\s\\d\\.]+%\\) are discordant alignments\"",
",",
"'total_reads'",
":",
"r\"[Rr]eads:\\n\\s+Input\\s*:\\s+(\\d+)\"",
",",
"}",
"else",
":",
"# Single end data",
"regexes",
"=",
"{",
"'total_reads'",
":",
"r\"[Rr]eads:\\n\\s+Input\\s*:\\s+(\\d+)\"",
",",
"'aligned_total'",
":",
"r\"Mapped\\s*:\\s+(\\d+)\"",
",",
"'aligned_multimap'",
":",
"r\"of these\\s*:\\s+(\\d+)\"",
",",
"'overall_aligned_percent'",
":",
"r\"([\\d\\.]+)% overall read mapping rate.\"",
",",
"}",
"parsed_data",
"=",
"{",
"}",
"for",
"k",
",",
"r",
"in",
"regexes",
".",
"items",
"(",
")",
":",
"r_search",
"=",
"re",
".",
"search",
"(",
"r",
",",
"raw_data",
",",
"re",
".",
"MULTILINE",
")",
"if",
"r_search",
":",
"parsed_data",
"[",
"k",
"]",
"=",
"float",
"(",
"r_search",
".",
"group",
"(",
"1",
")",
")",
"if",
"len",
"(",
"parsed_data",
")",
"==",
"0",
":",
"return",
"None",
"parsed_data",
"[",
"'concordant_aligned_percent'",
"]",
"=",
"parsed_data",
".",
"get",
"(",
"'concordant_aligned_percent'",
",",
"0",
")",
"parsed_data",
"[",
"'aligned_total'",
"]",
"=",
"parsed_data",
".",
"get",
"(",
"'aligned_total'",
",",
"0",
")",
"parsed_data",
"[",
"'aligned_multimap'",
"]",
"=",
"parsed_data",
".",
"get",
"(",
"'aligned_multimap'",
",",
"0",
")",
"parsed_data",
"[",
"'aligned_discordant'",
"]",
"=",
"parsed_data",
".",
"get",
"(",
"'aligned_discordant'",
",",
"0",
")",
"parsed_data",
"[",
"'unaligned_total'",
"]",
"=",
"parsed_data",
"[",
"'total_reads'",
"]",
"-",
"parsed_data",
"[",
"'aligned_total'",
"]",
"parsed_data",
"[",
"'aligned_not_multimapped_discordant'",
"]",
"=",
"parsed_data",
"[",
"'aligned_total'",
"]",
"-",
"parsed_data",
"[",
"'aligned_multimap'",
"]",
"-",
"parsed_data",
"[",
"'aligned_discordant'",
"]",
"return",
"parsed_data"
] |
extract the parsely - page meta content from a page
|
def _get_parselypage ( self , body ) : parser = ParselyPageParser ( ) ret = None try : parser . feed ( body ) except HTMLParseError : pass # ignore and hope we got ppage if parser . ppage is None : return ret = parser . ppage if ret : ret = { parser . original_unescape ( k ) : parser . original_unescape ( v ) for k , v in iteritems ( ret ) } return ret
| 3,386
|
https://github.com/Parsely/schemato/blob/7002316fbcd52f2e669f8372bf1338c572e3df4b/schemato/schemas/parselypage.py#L69-L84
|
[
"def",
"members",
"(",
"name",
",",
"members_list",
",",
"*",
"*",
"kwargs",
")",
":",
"members_list",
"=",
"[",
"salt",
".",
"utils",
".",
"win_functions",
".",
"get_sam_name",
"(",
"m",
")",
"for",
"m",
"in",
"members_list",
".",
"split",
"(",
"\",\"",
")",
"]",
"if",
"not",
"isinstance",
"(",
"members_list",
",",
"list",
")",
":",
"log",
".",
"debug",
"(",
"'member_list is not a list'",
")",
"return",
"False",
"try",
":",
"obj_group",
"=",
"_get_group_object",
"(",
"name",
")",
"except",
"pywintypes",
".",
"com_error",
"as",
"exc",
":",
"# Group probably doesn't exist, but we'll log the error",
"msg",
"=",
"'Failed to access group {0}. {1}'",
".",
"format",
"(",
"name",
",",
"win32api",
".",
"FormatMessage",
"(",
"exc",
".",
"excepinfo",
"[",
"5",
"]",
")",
")",
"log",
".",
"error",
"(",
"msg",
")",
"return",
"False",
"existing_members",
"=",
"[",
"_get_username",
"(",
"x",
")",
"for",
"x",
"in",
"obj_group",
".",
"members",
"(",
")",
"]",
"existing_members",
".",
"sort",
"(",
")",
"members_list",
".",
"sort",
"(",
")",
"if",
"existing_members",
"==",
"members_list",
":",
"log",
".",
"info",
"(",
"'%s membership is correct'",
",",
"name",
")",
"return",
"True",
"# add users",
"success",
"=",
"True",
"for",
"member",
"in",
"members_list",
":",
"if",
"member",
"not",
"in",
"existing_members",
":",
"try",
":",
"obj_group",
".",
"Add",
"(",
"'WinNT://'",
"+",
"member",
".",
"replace",
"(",
"'\\\\'",
",",
"'/'",
")",
")",
"log",
".",
"info",
"(",
"'User added: %s'",
",",
"member",
")",
"except",
"pywintypes",
".",
"com_error",
"as",
"exc",
":",
"msg",
"=",
"'Failed to add {0} to {1}. {2}'",
".",
"format",
"(",
"member",
",",
"name",
",",
"win32api",
".",
"FormatMessage",
"(",
"exc",
".",
"excepinfo",
"[",
"5",
"]",
")",
")",
"log",
".",
"error",
"(",
"msg",
")",
"success",
"=",
"False",
"# remove users not in members_list",
"for",
"member",
"in",
"existing_members",
":",
"if",
"member",
"not",
"in",
"members_list",
":",
"try",
":",
"obj_group",
".",
"Remove",
"(",
"'WinNT://'",
"+",
"member",
".",
"replace",
"(",
"'\\\\'",
",",
"'/'",
")",
")",
"log",
".",
"info",
"(",
"'User removed: %s'",
",",
"member",
")",
"except",
"pywintypes",
".",
"com_error",
"as",
"exc",
":",
"msg",
"=",
"'Failed to remove {0} from {1}. {2}'",
".",
"format",
"(",
"member",
",",
"name",
",",
"win32api",
".",
"FormatMessage",
"(",
"exc",
".",
"excepinfo",
"[",
"5",
"]",
")",
")",
"log",
".",
"error",
"(",
"msg",
")",
"success",
"=",
"False",
"return",
"success"
] |
return the local filename of the definition file for this schema if not present or older than expiry pull the latest version from the web at self . _ontology_file
|
def _read_schema ( self ) : cache_filename = os . path . join ( CACHE_ROOT , "%s.smt" % self . _representation ) log . info ( "Attempting to read local schema at %s" % cache_filename ) try : if time . time ( ) - os . stat ( cache_filename ) . st_mtime > CACHE_EXPIRY : log . warning ( "Cache expired, re-pulling" ) self . _pull_schema_definition ( cache_filename ) except OSError : log . warning ( "Local schema not found. Pulling from web." ) self . _pull_schema_definition ( cache_filename ) else : log . info ( "Success" ) return cache_filename
| 3,387
|
https://github.com/Parsely/schemato/blob/7002316fbcd52f2e669f8372bf1338c572e3df4b/schemato/schemadef.py#L38-L55
|
[
"def",
"driverDebugRequest",
"(",
"self",
",",
"unDeviceIndex",
",",
"pchRequest",
",",
"pchResponseBuffer",
",",
"unResponseBufferSize",
")",
":",
"fn",
"=",
"self",
".",
"function_table",
".",
"driverDebugRequest",
"result",
"=",
"fn",
"(",
"unDeviceIndex",
",",
"pchRequest",
",",
"pchResponseBuffer",
",",
"unResponseBufferSize",
")",
"return",
"result"
] |
download an ontology definition from the web
|
def _pull_schema_definition ( self , fname ) : std_url = urlopen ( self . _ontology_file ) cached_std = open ( fname , "w+" ) cached_std . write ( std_url . read ( ) ) cached_std . close ( )
| 3,388
|
https://github.com/Parsely/schemato/blob/7002316fbcd52f2e669f8372bf1338c572e3df4b/schemato/schemadef.py#L57-L62
|
[
"def",
"_update_tasks_redundancy",
"(",
"config",
",",
"task_id",
",",
"redundancy",
",",
"limit",
"=",
"300",
",",
"offset",
"=",
"0",
")",
":",
"try",
":",
"project",
"=",
"find_project_by_short_name",
"(",
"config",
".",
"project",
"[",
"'short_name'",
"]",
",",
"config",
".",
"pbclient",
",",
"config",
".",
"all",
")",
"if",
"task_id",
":",
"response",
"=",
"config",
".",
"pbclient",
".",
"find_tasks",
"(",
"project",
".",
"id",
",",
"id",
"=",
"task_id",
")",
"check_api_error",
"(",
"response",
")",
"task",
"=",
"response",
"[",
"0",
"]",
"task",
".",
"n_answers",
"=",
"redundancy",
"response",
"=",
"config",
".",
"pbclient",
".",
"update_task",
"(",
"task",
")",
"check_api_error",
"(",
"response",
")",
"msg",
"=",
"\"Task.id = %s redundancy has been updated to %s\"",
"%",
"(",
"task_id",
",",
"redundancy",
")",
"return",
"msg",
"else",
":",
"limit",
"=",
"limit",
"offset",
"=",
"offset",
"tasks",
"=",
"config",
".",
"pbclient",
".",
"get_tasks",
"(",
"project",
".",
"id",
",",
"limit",
",",
"offset",
")",
"with",
"click",
".",
"progressbar",
"(",
"tasks",
",",
"label",
"=",
"\"Updating Tasks\"",
")",
"as",
"pgbar",
":",
"while",
"len",
"(",
"tasks",
")",
">",
"0",
":",
"for",
"t",
"in",
"pgbar",
":",
"t",
".",
"n_answers",
"=",
"redundancy",
"response",
"=",
"config",
".",
"pbclient",
".",
"update_task",
"(",
"t",
")",
"check_api_error",
"(",
"response",
")",
"# Check if for the data we have to auto-throttle task update",
"sleep",
",",
"msg",
"=",
"enable_auto_throttling",
"(",
"config",
",",
"tasks",
")",
"# If auto-throttling enabled, sleep for sleep seconds",
"if",
"sleep",
":",
"# pragma: no cover",
"time",
".",
"sleep",
"(",
"sleep",
")",
"offset",
"+=",
"limit",
"tasks",
"=",
"config",
".",
"pbclient",
".",
"get_tasks",
"(",
"project",
".",
"id",
",",
"limit",
",",
"offset",
")",
"return",
"\"All tasks redundancy have been updated\"",
"except",
"exceptions",
".",
"ConnectionError",
":",
"return",
"(",
"\"Connection Error! The server %s is not responding\"",
"%",
"config",
".",
"server",
")",
"except",
"(",
"ProjectNotFound",
",",
"TaskNotFound",
")",
":",
"raise"
] |
place the ontology graph into a set of custom data structures for use by the validator
|
def parse_ontology ( self ) : start = time . clock ( ) log . info ( "Parsing ontology file for %s" % self . __class__ . __name__ ) for subj , pred , obj in self . _schema_nodes ( ) : if subj not in self . attributes_by_class : if obj == rt . URIRef ( self . lexicon [ 'class' ] ) and pred == rt . URIRef ( self . lexicon [ 'type' ] ) : self . attributes_by_class [ subj ] = [ ] leaves = [ ( subj , pred , obj ) ] if type ( obj ) == rt . BNode : leaves = deepest_node ( ( subj , pred , obj ) , self . graph ) for s , p , o in leaves : if o not in self . attributes_by_class : self . attributes_by_class [ o ] = [ ] if pred == rt . URIRef ( self . lexicon [ 'domain' ] ) : self . attributes_by_class [ o ] . append ( subj ) if not self . attributes_by_class : log . info ( "No nodes found in ontology" ) log . info ( "Ontology parsing complete in {}" . format ( ( time . clock ( ) - start ) * 1000 ) )
| 3,389
|
https://github.com/Parsely/schemato/blob/7002316fbcd52f2e669f8372bf1338c572e3df4b/schemato/schemadef.py#L64-L87
|
[
"def",
"write",
"(",
"self",
",",
"text",
")",
":",
"escape_parts",
"=",
"re",
".",
"compile",
"(",
"'\\x01?\\x1b\\\\[([0-9;]*)m\\x02?'",
")",
"chunks",
"=",
"escape_parts",
".",
"split",
"(",
"text",
")",
"i",
"=",
"0",
"for",
"chunk",
"in",
"chunks",
":",
"if",
"chunk",
"!=",
"''",
":",
"if",
"i",
"%",
"2",
"==",
"0",
":",
"self",
".",
"stream",
".",
"write",
"(",
"chunk",
")",
"else",
":",
"c",
"=",
"chunk",
".",
"split",
"(",
"';'",
")",
"r",
"=",
"Magic",
".",
"rdisplay",
"(",
"c",
")",
"self",
".",
"display",
"(",
"*",
"*",
"r",
")",
"#see caveat 0",
"self",
".",
"flush",
"(",
")",
"i",
"+=",
"1"
] |
parse self . _ontology_file into a graph
|
def _schema_nodes ( self ) : name , ext = os . path . splitext ( self . _ontology_file ) if ext in [ '.ttl' ] : self . _ontology_parser_function = lambda s : rdflib . Graph ( ) . parse ( s , format = 'n3' ) else : self . _ontology_parser_function = lambda s : pyRdfa ( ) . graph_from_source ( s ) if not self . _ontology_parser_function : raise ValueError ( "No function found to parse ontology. %s" % self . errorstring_base ) if not self . _ontology_file : raise ValueError ( "No ontology file specified. %s" % self . errorstring_base ) if not self . lexicon : raise ValueError ( "No lexicon object assigned. %s" % self . errorstring_base ) latest_file = self . _read_schema ( ) try : self . graph = self . _ontology_parser_function ( latest_file ) except : raise IOError ( "Error parsing ontology at %s" % latest_file ) for subj , pred , obj in self . graph : self . ontology [ subj ] . append ( ( pred , obj ) ) yield ( subj , pred , obj )
| 3,390
|
https://github.com/Parsely/schemato/blob/7002316fbcd52f2e669f8372bf1338c572e3df4b/schemato/schemadef.py#L89-L118
|
[
"def",
"get_stats_display_width",
"(",
"self",
",",
"curse_msg",
",",
"without_option",
"=",
"False",
")",
":",
"try",
":",
"if",
"without_option",
":",
"# Size without options",
"c",
"=",
"len",
"(",
"max",
"(",
"''",
".",
"join",
"(",
"[",
"(",
"u",
"(",
"u",
"(",
"nativestr",
"(",
"i",
"[",
"'msg'",
"]",
")",
")",
".",
"encode",
"(",
"'ascii'",
",",
"'replace'",
")",
")",
"if",
"not",
"i",
"[",
"'optional'",
"]",
"else",
"\"\"",
")",
"for",
"i",
"in",
"curse_msg",
"[",
"'msgdict'",
"]",
"]",
")",
".",
"split",
"(",
"'\\n'",
")",
",",
"key",
"=",
"len",
")",
")",
"else",
":",
"# Size with all options",
"c",
"=",
"len",
"(",
"max",
"(",
"''",
".",
"join",
"(",
"[",
"u",
"(",
"u",
"(",
"nativestr",
"(",
"i",
"[",
"'msg'",
"]",
")",
")",
".",
"encode",
"(",
"'ascii'",
",",
"'replace'",
")",
")",
"for",
"i",
"in",
"curse_msg",
"[",
"'msgdict'",
"]",
"]",
")",
".",
"split",
"(",
"'\\n'",
")",
",",
"key",
"=",
"len",
")",
")",
"except",
"Exception",
"as",
"e",
":",
"logger",
".",
"debug",
"(",
"'ERROR: Can not compute plugin width ({})'",
".",
"format",
"(",
"e",
")",
")",
"return",
"0",
"else",
":",
"return",
"c"
] |
Return only the network location portion of the given domain unless includeScheme is True
|
def baseDomain ( domain , includeScheme = True ) : result = '' url = urlparse ( domain ) if includeScheme : result = '%s://' % url . scheme if len ( url . netloc ) == 0 : result += url . path else : result += url . netloc return result
| 3,391
|
https://github.com/bear/bearlib/blob/30f9b8ba4b7a8db4cd2f4c6e07966ae51d0a00dd/bearlib/tools.py#L22-L34
|
[
"def",
"extract_secrets_from_android_rooted",
"(",
"adb_path",
"=",
"'adb'",
")",
":",
"data",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"adb_path",
",",
"'shell'",
",",
"'su'",
",",
"'-c'",
",",
"\"'cat /data/data/com.valvesoftware.android.steam.community/files/Steamguard*'\"",
"]",
")",
"# When adb daemon is not running, `adb` will print a couple of lines before our data.",
"# The data doesn't have new lines and its always on the last line.",
"data",
"=",
"data",
".",
"decode",
"(",
"'utf-8'",
")",
".",
"split",
"(",
"'\\n'",
")",
"[",
"-",
"1",
"]",
"if",
"data",
"[",
"0",
"]",
"!=",
"\"{\"",
":",
"raise",
"RuntimeError",
"(",
"\"Got invalid data: %s\"",
"%",
"repr",
"(",
"data",
")",
")",
"return",
"{",
"int",
"(",
"x",
"[",
"'steamid'",
"]",
")",
":",
"x",
"for",
"x",
"in",
"map",
"(",
"json",
".",
"loads",
",",
"data",
".",
"replace",
"(",
"\"}{\"",
",",
"'}|||||{'",
")",
".",
"split",
"(",
"'|||||'",
")",
")",
"}"
] |
Naive search of the database for query .
|
def search ( session , query ) : flat_query = "" . join ( query . split ( ) ) artists = session . query ( Artist ) . filter ( or_ ( Artist . name . ilike ( f"%%{query}%%" ) , Artist . name . ilike ( f"%%{flat_query}%%" ) ) ) . all ( ) albums = session . query ( Album ) . filter ( Album . title . ilike ( f"%%{query}%%" ) ) . all ( ) tracks = session . query ( Track ) . filter ( Track . title . ilike ( f"%%{query}%%" ) ) . all ( ) return dict ( artists = artists , albums = albums , tracks = tracks )
| 3,392
|
https://github.com/nicfit/MishMash/blob/8f988936340bf0ffb83ea90ea124efb3c36a1174/mishmash/database.py#L86-L105
|
[
"def",
"private_messenger",
"(",
")",
":",
"while",
"__websocket_server_running__",
":",
"pipein",
"=",
"open",
"(",
"PRIVATE_PIPE",
",",
"'r'",
")",
"line",
"=",
"pipein",
".",
"readline",
"(",
")",
".",
"replace",
"(",
"'\\n'",
",",
"''",
")",
".",
"replace",
"(",
"'\\r'",
",",
"''",
")",
"if",
"line",
"!=",
"''",
":",
"message",
"=",
"json",
".",
"loads",
"(",
"line",
")",
"WebSocketHandler",
".",
"send_private_message",
"(",
"user_id",
"=",
"message",
"[",
"'user_id'",
"]",
",",
"message",
"=",
"message",
")",
"print",
"line",
"remaining_lines",
"=",
"pipein",
".",
"read",
"(",
")",
"pipein",
".",
"close",
"(",
")",
"pipeout",
"=",
"open",
"(",
"PRIVATE_PIPE",
",",
"'w'",
")",
"pipeout",
".",
"write",
"(",
"remaining_lines",
")",
"pipeout",
".",
"close",
"(",
")",
"else",
":",
"pipein",
".",
"close",
"(",
")",
"time",
".",
"sleep",
"(",
"0.05",
")"
] |
Print a message and prompt user for input . Return user input .
|
def prompt ( message , default = None , strip = True , suffix = ' ' ) : if default is not None : prompt_text = "{0} [{1}]{2}" . format ( message , default , suffix ) else : prompt_text = "{0}{1}" . format ( message , suffix ) input_value = get_input ( prompt_text ) if input_value and strip : input_value = input_value . strip ( ) if not input_value : input_value = default return input_value
| 3,393
|
https://github.com/tylerdave/prompter/blob/b6a72f4d02cd68c6d9a2bbe00bfc5bf62b25feda/prompter/__init__.py#L66-L81
|
[
"def",
"update",
"(",
"self",
",",
"other",
")",
":",
"self",
".",
"update_ttl",
"(",
"other",
".",
"ttl",
")",
"super",
"(",
"Rdataset",
",",
"self",
")",
".",
"update",
"(",
"other",
")"
] |
Prompt user to answer yes or no . Return True if the default is chosen otherwise False .
|
def yesno ( message , default = 'yes' , suffix = ' ' ) : if default == 'yes' : yesno_prompt = '[Y/n]' elif default == 'no' : yesno_prompt = '[y/N]' else : raise ValueError ( "default must be 'yes' or 'no'." ) if message != '' : prompt_text = "{0} {1}{2}" . format ( message , yesno_prompt , suffix ) else : prompt_text = "{0}{1}" . format ( yesno_prompt , suffix ) while True : response = get_input ( prompt_text ) . strip ( ) if response == '' : return True else : if re . match ( '^(y)(es)?$' , response , re . IGNORECASE ) : if default == 'yes' : return True else : return False elif re . match ( '^(n)(o)?$' , response , re . IGNORECASE ) : if default == 'no' : return True else : return False
| 3,394
|
https://github.com/tylerdave/prompter/blob/b6a72f4d02cd68c6d9a2bbe00bfc5bf62b25feda/prompter/__init__.py#L83-L112
|
[
"def",
"load",
"(",
"dbname",
")",
":",
"db",
"=",
"Database",
"(",
"dbname",
")",
"# Get the name of the objects",
"tables",
"=",
"get_table_list",
"(",
"db",
".",
"cur",
")",
"# Create a Trace instance for each object",
"chains",
"=",
"0",
"for",
"name",
"in",
"tables",
":",
"db",
".",
"_traces",
"[",
"name",
"]",
"=",
"Trace",
"(",
"name",
"=",
"name",
",",
"db",
"=",
"db",
")",
"db",
".",
"_traces",
"[",
"name",
"]",
".",
"_shape",
"=",
"get_shape",
"(",
"db",
".",
"cur",
",",
"name",
")",
"setattr",
"(",
"db",
",",
"name",
",",
"db",
".",
"_traces",
"[",
"name",
"]",
")",
"db",
".",
"cur",
".",
"execute",
"(",
"'SELECT MAX(trace) FROM [%s]'",
"%",
"name",
")",
"chains",
"=",
"max",
"(",
"chains",
",",
"db",
".",
"cur",
".",
"fetchall",
"(",
")",
"[",
"0",
"]",
"[",
"0",
"]",
"+",
"1",
")",
"db",
".",
"chains",
"=",
"chains",
"db",
".",
"trace_names",
"=",
"chains",
"*",
"[",
"tables",
",",
"]",
"db",
".",
"_state_",
"=",
"{",
"}",
"return",
"db"
] |
Register a Validator class for file verification .
|
def register_validator ( validator ) : if hasattr ( validator , "EXTS" ) and hasattr ( validator , "run" ) : ValidatorFactory . PLUGINS . append ( validator ) else : raise ValidatorException ( "Validator does not have 'run' method or EXTS variable!" )
| 3,395
|
https://github.com/astraw38/lint/blob/162ceefcb812f07d18544aaa887b9ec4f102cfb1/lint/validators/validation_factory.py#L32-L42
|
[
"def",
"get_organisations",
"(",
"self",
",",
"service_desk_id",
"=",
"None",
",",
"start",
"=",
"0",
",",
"limit",
"=",
"50",
")",
":",
"url_without_sd_id",
"=",
"'rest/servicedeskapi/organization'",
"url_with_sd_id",
"=",
"'rest/servicedeskapi/servicedesk/{}/organization'",
".",
"format",
"(",
"service_desk_id",
")",
"params",
"=",
"{",
"}",
"if",
"start",
"is",
"not",
"None",
":",
"params",
"[",
"'start'",
"]",
"=",
"int",
"(",
"start",
")",
"if",
"limit",
"is",
"not",
"None",
":",
"params",
"[",
"'limit'",
"]",
"=",
"int",
"(",
"limit",
")",
"if",
"service_desk_id",
"is",
"None",
":",
"return",
"self",
".",
"get",
"(",
"url_without_sd_id",
",",
"headers",
"=",
"self",
".",
"experimental_headers",
",",
"params",
"=",
"params",
")",
"else",
":",
"return",
"self",
".",
"get",
"(",
"url_with_sd_id",
",",
"headers",
"=",
"self",
".",
"experimental_headers",
",",
"params",
"=",
"params",
")"
] |
Generator process to write file
|
def file_writer ( self , in_frame ) : self . update_config ( ) path = self . config [ 'path' ] encoder = self . config [ 'encoder' ] fps = self . config [ 'fps' ] bit16 = self . config [ '16bit' ] numpy_image = in_frame . as_numpy ( ) ylen , xlen , bpc = numpy_image . shape if bpc == 3 : if in_frame . type != 'RGB' : self . logger . warning ( 'Expected RGB input, got %s' , in_frame . type ) pix_fmt = ( 'rgb24' , 'rgb48le' ) [ bit16 ] elif bpc == 1 : if in_frame . type != 'Y' : self . logger . warning ( 'Expected Y input, got %s' , in_frame . type ) pix_fmt = ( 'gray' , 'gray16le' ) [ bit16 ] else : self . logger . critical ( 'Cannot write %s frame with %d components' , in_frame . type , bpc ) return md = Metadata ( ) . copy ( in_frame . metadata ) audit = md . get ( 'audit' ) audit += '%s = data\n' % path audit += ' encoder: "%s"\n' % ( encoder ) audit += ' 16bit: %s\n' % ( self . config [ '16bit' ] ) md . set ( 'audit' , audit ) md . to_file ( path ) with self . subprocess ( [ 'ffmpeg' , '-v' , 'warning' , '-y' , '-an' , '-s' , '%dx%d' % ( xlen , ylen ) , '-f' , 'rawvideo' , '-c:v' , 'rawvideo' , '-r' , '%d' % fps , '-pix_fmt' , pix_fmt , '-i' , '-' , '-r' , '%d' % fps ] + encoder . split ( ) + [ path ] , stdin = subprocess . PIPE ) as sp : while True : in_frame = yield True if not in_frame : break if bit16 : numpy_image = in_frame . as_numpy ( dtype = pt_float ) numpy_image = numpy_image * pt_float ( 256.0 ) numpy_image = numpy_image . clip ( pt_float ( 0 ) , pt_float ( 2 ** 16 - 1 ) ) . astype ( numpy . uint16 ) else : numpy_image = in_frame . as_numpy ( dtype = numpy . uint8 ) sp . stdin . write ( numpy_image . tostring ( ) ) del in_frame
| 3,396
|
https://github.com/jim-easterbrook/pyctools/blob/2a958665326892f45f249bebe62c2c23f306732b/src/pyctools/components/io/videofilewriter.py#L85-L132
|
[
"def",
"get_cash_balance",
"(",
"self",
")",
":",
"cash",
"=",
"False",
"try",
":",
"response",
"=",
"self",
".",
"session",
".",
"get",
"(",
"'/browse/cashBalanceAj.action'",
")",
"json_response",
"=",
"response",
".",
"json",
"(",
")",
"if",
"self",
".",
"session",
".",
"json_success",
"(",
"json_response",
")",
":",
"self",
".",
"__log",
"(",
"'Cash available: {0}'",
".",
"format",
"(",
"json_response",
"[",
"'cashBalance'",
"]",
")",
")",
"cash_value",
"=",
"json_response",
"[",
"'cashBalance'",
"]",
"# Convert currency to float value",
"# Match values like $1,000.12 or 1,0000$",
"cash_match",
"=",
"re",
".",
"search",
"(",
"'^[^0-9]?([0-9\\.,]+)[^0-9]?'",
",",
"cash_value",
")",
"if",
"cash_match",
":",
"cash_str",
"=",
"cash_match",
".",
"group",
"(",
"1",
")",
"cash_str",
"=",
"cash_str",
".",
"replace",
"(",
"','",
",",
"''",
")",
"cash",
"=",
"float",
"(",
"cash_str",
")",
"else",
":",
"self",
".",
"__log",
"(",
"'Could not get cash balance: {0}'",
".",
"format",
"(",
"response",
".",
"text",
")",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"__log",
"(",
"'Could not get the cash balance on the account: Error: {0}\\nJSON: {1}'",
".",
"format",
"(",
"str",
"(",
"e",
")",
",",
"response",
".",
"text",
")",
")",
"raise",
"e",
"return",
"cash"
] |
HHI pre - interlace filter .
|
def HHIPreFilter ( config = { } ) : fil = numpy . array ( [ - 4 , 8 , 25 , - 123 , 230 , 728 , 230 , - 123 , 25 , 8 , - 4 ] , dtype = numpy . float32 ) . reshape ( ( - 1 , 1 , 1 ) ) / numpy . float32 ( 1000 ) resize = Resize ( config = config ) out_frame = Frame ( ) out_frame . data = fil out_frame . type = 'fil' audit = out_frame . metadata . get ( 'audit' ) audit += 'data = HHI pre-interlace filter\n' out_frame . metadata . set ( 'audit' , audit ) resize . filter ( out_frame ) return resize
| 3,397
|
https://github.com/jim-easterbrook/pyctools/blob/2a958665326892f45f249bebe62c2c23f306732b/src/pyctools/components/deinterlace/hhiprefilter.py#L27-L51
|
[
"def",
"deserialize",
"(",
"obj",
")",
":",
"# Be careful of shallow copy here",
"target",
"=",
"dict",
"(",
"obj",
")",
"class_name",
"=",
"None",
"if",
"'__class__'",
"in",
"target",
":",
"class_name",
"=",
"target",
".",
"pop",
"(",
"'__class__'",
")",
"if",
"'__module__'",
"in",
"obj",
":",
"obj",
".",
"pop",
"(",
"'__module__'",
")",
"# Use getattr(module, class_name) for custom types if needed",
"if",
"class_name",
"==",
"'datetime'",
":",
"return",
"datetime",
".",
"datetime",
"(",
"tzinfo",
"=",
"utc",
",",
"*",
"*",
"target",
")",
"if",
"class_name",
"==",
"'StreamingBody'",
":",
"return",
"StringIO",
"(",
"target",
"[",
"'body'",
"]",
")",
"# Return unrecognized structures as-is",
"return",
"obj"
] |
Returns a list of ephemeral port ranges for current machine .
|
def port_ranges ( ) : try : return _linux_ranges ( ) except ( OSError , IOError ) : # not linux, try BSD try : ranges = _bsd_ranges ( ) if ranges : return ranges except ( OSError , IOError ) : pass # fallback return [ DEFAULT_EPHEMERAL_PORT_RANGE ]
| 3,398
|
https://github.com/kmike/port-for/blob/f61ebf3c2caf54eabe8233b40ef67b973176a6f5/port_for/ephemeral.py#L15-L30
|
[
"def",
"title",
"(",
"msg",
")",
":",
"if",
"sys",
".",
"platform",
".",
"startswith",
"(",
"\"win\"",
")",
":",
"ctypes",
".",
"windll",
".",
"kernel32",
".",
"SetConsoleTitleW",
"(",
"tounicode",
"(",
"msg",
")",
")"
] |
The actual event loop .
|
def run ( self ) : try : self . owner . start_event ( ) while True : while not self . incoming : time . sleep ( 0.01 ) while self . incoming : command = self . incoming . popleft ( ) if command is None : raise StopIteration ( ) command ( ) except StopIteration : pass self . owner . stop_event ( )
| 3,399
|
https://github.com/jim-easterbrook/pyctools/blob/2a958665326892f45f249bebe62c2c23f306732b/src/pyctools/core/base.py#L131-L154
|
[
"def",
"join",
"(",
"rasters",
")",
":",
"raster",
"=",
"rasters",
"[",
"0",
"]",
"# using the first raster to understand what is the type of data we have",
"mask_band",
"=",
"None",
"nodata",
"=",
"None",
"with",
"raster",
".",
"_raster_opener",
"(",
"raster",
".",
"source_file",
")",
"as",
"r",
":",
"nodata",
"=",
"r",
".",
"nodata",
"mask_flags",
"=",
"r",
".",
"mask_flag_enums",
"per_dataset_mask",
"=",
"all",
"(",
"[",
"rasterio",
".",
"enums",
".",
"MaskFlags",
".",
"per_dataset",
"in",
"flags",
"for",
"flags",
"in",
"mask_flags",
"]",
")",
"if",
"per_dataset_mask",
"and",
"nodata",
"is",
"None",
":",
"mask_band",
"=",
"0",
"return",
"GeoRaster2",
".",
"from_rasters",
"(",
"rasters",
",",
"relative_to_vrt",
"=",
"False",
",",
"nodata",
"=",
"nodata",
",",
"mask_band",
"=",
"mask_band",
")"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.