text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def float_with_multiplier(string):
"""Convert string with optional k, M, G, T multiplier to float"""
match = re_float_with_multiplier.search(string)
if not match or not match.group('num'):
raise ValueError('String "{}" is not numeric!'.format(string))
num = float(match.group('num'))
multi =... | [
"def",
"float_with_multiplier",
"(",
"string",
")",
":",
"match",
"=",
"re_float_with_multiplier",
".",
"search",
"(",
"string",
")",
"if",
"not",
"match",
"or",
"not",
"match",
".",
"group",
"(",
"'num'",
")",
":",
"raise",
"ValueError",
"(",
"'String \"{}\... | 35.857143 | 0.001942 |
def create_execution_state(self, topologyName, executionState):
""" create execution state """
if not executionState or not executionState.IsInitialized():
raise_(StateException("Execution State protobuf not init properly",
StateException.EX_TYPE_PROTOBUF_ERROR), sys.exc_info()... | [
"def",
"create_execution_state",
"(",
"self",
",",
"topologyName",
",",
"executionState",
")",
":",
"if",
"not",
"executionState",
"or",
"not",
"executionState",
".",
"IsInitialized",
"(",
")",
":",
"raise_",
"(",
"StateException",
"(",
"\"Execution State protobuf n... | 49.72 | 0.01026 |
def convertToSpec(model,
input_names = None,
output_names = None,
image_input_names = None,
input_name_shape_dict = {},
is_bgr = False,
red_bias = 0.0,
green_bias = 0.0,
blue_b... | [
"def",
"convertToSpec",
"(",
"model",
",",
"input_names",
"=",
"None",
",",
"output_names",
"=",
"None",
",",
"image_input_names",
"=",
"None",
",",
"input_name_shape_dict",
"=",
"{",
"}",
",",
"is_bgr",
"=",
"False",
",",
"red_bias",
"=",
"0.0",
",",
"gre... | 44.982759 | 0.00825 |
def make_unique_name(base, existing=[], format="%s_%s"):
""" Return a name, unique within a context, based on the specified name.
@param base: the desired base name of the generated unique name.
@param existing: a sequence of the existing names to avoid returning.
@param format: a formatting specificat... | [
"def",
"make_unique_name",
"(",
"base",
",",
"existing",
"=",
"[",
"]",
",",
"format",
"=",
"\"%s_%s\"",
")",
":",
"count",
"=",
"2",
"name",
"=",
"base",
"while",
"name",
"in",
"existing",
":",
"name",
"=",
"format",
"%",
"(",
"base",
",",
"count",
... | 34.5 | 0.002016 |
def automations_update_many(self, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/automations#update-many-automations"
api_path = "/api/v2/automations/update_many.json"
return self.call(api_path, method="PUT", data=data, **kwargs) | [
"def",
"automations_update_many",
"(",
"self",
",",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/automations/update_many.json\"",
"return",
"self",
".",
"call",
"(",
"api_path",
",",
"method",
"=",
"\"PUT\"",
",",
"data",
"=",
"data",... | 67.5 | 0.010989 |
def adjgraph(args):
"""
%prog adjgraph adjacency.txt subgraph.txt
Construct adjacency graph for graphviz. The file may look like sample below.
The lines with numbers are chromosomes with gene order information.
genome 0
chr 0
-1 -13 -16 3 4 -6126 -5 17 -6 7 18 5357 8 -5358 5359 -9 -10 -11 ... | [
"def",
"adjgraph",
"(",
"args",
")",
":",
"import",
"pygraphviz",
"as",
"pgv",
"from",
"jcvi",
".",
"utils",
".",
"iter",
"import",
"pairwise",
"from",
"jcvi",
".",
"formats",
".",
"base",
"import",
"SetFile",
"p",
"=",
"OptionParser",
"(",
"adjgraph",
"... | 25.355263 | 0.000999 |
def handle_set_row(self):
"""Read incoming row change from server"""
row = self.reader.int()
logger.info(" -> row: %s", row)
self.controller.row = row | [
"def",
"handle_set_row",
"(",
"self",
")",
":",
"row",
"=",
"self",
".",
"reader",
".",
"int",
"(",
")",
"logger",
".",
"info",
"(",
"\" -> row: %s\"",
",",
"row",
")",
"self",
".",
"controller",
".",
"row",
"=",
"row"
] | 35.6 | 0.010989 |
def prepare_attachments(attachment):
"""
Converts incoming attachment into dictionary.
"""
if isinstance(attachment, tuple):
result = {"Name": attachment[0], "Content": attachment[1], "ContentType": attachment[2]}
if len(attachment) == 4:
result["ContentID"] = attachment[3]
... | [
"def",
"prepare_attachments",
"(",
"attachment",
")",
":",
"if",
"isinstance",
"(",
"attachment",
",",
"tuple",
")",
":",
"result",
"=",
"{",
"\"Name\"",
":",
"attachment",
"[",
"0",
"]",
",",
"\"Content\"",
":",
"attachment",
"[",
"1",
"]",
",",
"\"Cont... | 45.351351 | 0.002334 |
def validate(self):
'''Validate required headers and validate notification headers'''
for header in self._requiredHeaders:
if not self.headers.get(header, False):
raise errors.ParseError('Missing Registration Header: ' + header)
for notice in self.notifications:
for header in self._requiredNotificationH... | [
"def",
"validate",
"(",
"self",
")",
":",
"for",
"header",
"in",
"self",
".",
"_requiredHeaders",
":",
"if",
"not",
"self",
".",
"headers",
".",
"get",
"(",
"header",
",",
"False",
")",
":",
"raise",
"errors",
".",
"ParseError",
"(",
"'Missing Registrati... | 47.555556 | 0.022936 |
def _missing_required_parameters(rqset, **kwargs):
"""Helper function to do operation on sets.
Checks for any missing required parameters.
Returns non-empty or empty list. With empty
list being False.
::returns list
"""
key_set = set(list(iterkeys(kwargs)))
required_minus_received = rq... | [
"def",
"_missing_required_parameters",
"(",
"rqset",
",",
"*",
"*",
"kwargs",
")",
":",
"key_set",
"=",
"set",
"(",
"list",
"(",
"iterkeys",
"(",
"kwargs",
")",
")",
")",
"required_minus_received",
"=",
"rqset",
"-",
"key_set",
"if",
"required_minus_received",... | 31.307692 | 0.002387 |
def plot_classifier_errors(predictions, absolute=True, max_relative_size=50, absolute_size=50, title=None,
outfile=None, wait=True):
"""
Plots the classifers for the given list of predictions.
TODO: click events http://matplotlib.org/examples/event_handling/data_browser.html
... | [
"def",
"plot_classifier_errors",
"(",
"predictions",
",",
"absolute",
"=",
"True",
",",
"max_relative_size",
"=",
"50",
",",
"absolute_size",
"=",
"50",
",",
"title",
"=",
"None",
",",
"outfile",
"=",
"None",
",",
"wait",
"=",
"True",
")",
":",
"if",
"no... | 35.884058 | 0.001572 |
def qasm(val: Any,
*,
args: Optional[QasmArgs] = None,
qubits: Optional[Iterable['cirq.Qid']] = None,
default: TDefault = RaiseTypeErrorIfNotProvided
) -> Union[str, TDefault]:
"""Returns QASM code for the given value, if possible.
Different values require different... | [
"def",
"qasm",
"(",
"val",
":",
"Any",
",",
"*",
",",
"args",
":",
"Optional",
"[",
"QasmArgs",
"]",
"=",
"None",
",",
"qubits",
":",
"Optional",
"[",
"Iterable",
"[",
"'cirq.Qid'",
"]",
"]",
"=",
"None",
",",
"default",
":",
"TDefault",
"=",
"Rais... | 43.777778 | 0.001655 |
def getenv(key, value=None):
"""Like `os.getenv` but returns unicode under Windows + Python 2
Args:
key (pathlike): The env var to get
value (object): The value to return if the env var does not exist
Returns:
`fsnative` or `object`:
The env var or the passed value if it... | [
"def",
"getenv",
"(",
"key",
",",
"value",
"=",
"None",
")",
":",
"key",
"=",
"path2fsn",
"(",
"key",
")",
"if",
"is_win",
"and",
"PY2",
":",
"return",
"environ",
".",
"get",
"(",
"key",
",",
"value",
")",
"return",
"os",
".",
"getenv",
"(",
"key... | 29.866667 | 0.002165 |
def filter_python_files(files):
"Get all python files from the list of files."
py_files = []
for f in files:
# If we end in .py, or if we don't have an extension and file says that
# we are a python script, then add us to the list
extension = os.path.splitext(f)[-1]
if exten... | [
"def",
"filter_python_files",
"(",
"files",
")",
":",
"py_files",
"=",
"[",
"]",
"for",
"f",
"in",
"files",
":",
"# If we end in .py, or if we don't have an extension and file says that",
"# we are a python script, then add us to the list",
"extension",
"=",
"os",
".",
"pat... | 34.529412 | 0.001658 |
def save(filename, data, format=None, **kwargs):
'''
save(filename, data) writes the given data to the given filename then yieds that filename.
save(filename, data, format) specifies that the given format should be used; this should be the
name of the exporter (though a file extension that is recogniz... | [
"def",
"save",
"(",
"filename",
",",
"data",
",",
"format",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"os",
".",
"path",
".",
"expandvars",
"(",
"filename",
")",
")",
"if",
"format",... | 46.6875 | 0.009836 |
def window(preceding=None, following=None, group_by=None, order_by=None):
"""Create a window clause for use with window functions.
This ROW window clause aggregates adjacent rows based on differences in row
number.
All window frames / ranges are inclusive.
Parameters
----------
preceding ... | [
"def",
"window",
"(",
"preceding",
"=",
"None",
",",
"following",
"=",
"None",
",",
"group_by",
"=",
"None",
",",
"order_by",
"=",
"None",
")",
":",
"return",
"Window",
"(",
"preceding",
"=",
"preceding",
",",
"following",
"=",
"following",
",",
"group_b... | 30.882353 | 0.000923 |
def header_match(cls, data):
'''
Parse a member namestrs header (1 line, 80 bytes).
'''
mo = cls.header_re.match(data)
return int(mo['n_variables']) | [
"def",
"header_match",
"(",
"cls",
",",
"data",
")",
":",
"mo",
"=",
"cls",
".",
"header_re",
".",
"match",
"(",
"data",
")",
"return",
"int",
"(",
"mo",
"[",
"'n_variables'",
"]",
")"
] | 30.5 | 0.010638 |
def _read_mptcp_add(self, bits, size, kind):
"""Read Add Address option.
Positional arguments:
* bits - str, 4-bit data
* size - int, length of option
* kind - int, 30 (Multipath TCP)
Returns:
* dict -- extracted Add Address (ADD_ADDR) option
... | [
"def",
"_read_mptcp_add",
"(",
"self",
",",
"bits",
",",
"size",
",",
"kind",
")",
":",
"vers",
"=",
"int",
"(",
"bits",
",",
"base",
"=",
"2",
")",
"adid",
"=",
"self",
".",
"_read_unpack",
"(",
"1",
")",
"ipad",
"=",
"self",
".",
"_read_fileng",
... | 40.692308 | 0.000923 |
def get_remote_user(request):
"""Parse basic HTTP_AUTHORIZATION and return user name
"""
if 'HTTP_AUTHORIZATION' not in request.environ:
return
authorization = request.environ['HTTP_AUTHORIZATION']
try:
authmeth, auth = authorization.split(' ', 1)
except ValueError: # not enoug... | [
"def",
"get_remote_user",
"(",
"request",
")",
":",
"if",
"'HTTP_AUTHORIZATION'",
"not",
"in",
"request",
".",
"environ",
":",
"return",
"authorization",
"=",
"request",
".",
"environ",
"[",
"'HTTP_AUTHORIZATION'",
"]",
"try",
":",
"authmeth",
",",
"auth",
"="... | 31.5 | 0.001401 |
def GetMultipleTags(tag_list, start_time, end_time, sampling_rate=None,
fill_limit=99999, verify_time=False, desc_as_label=False,
utc=False):
"""
Retrieves raw data from eDNA history for multiple tags, merging them into
a single DataFrame, and resampling the data... | [
"def",
"GetMultipleTags",
"(",
"tag_list",
",",
"start_time",
",",
"end_time",
",",
"sampling_rate",
"=",
"None",
",",
"fill_limit",
"=",
"99999",
",",
"verify_time",
"=",
"False",
",",
"desc_as_label",
"=",
"False",
",",
"utc",
"=",
"False",
")",
":",
"# ... | 48.77027 | 0.000272 |
def create(vm_):
'''
Create a single VM from a data dict
'''
try:
# Check for required profile parameters before sending any API calls.
if (vm_['profile'] and
config.is_profile_configured(__opts__,
(__active_provider_name__ or
... | [
"def",
"create",
"(",
"vm_",
")",
":",
"try",
":",
"# Check for required profile parameters before sending any API calls.",
"if",
"(",
"vm_",
"[",
"'profile'",
"]",
"and",
"config",
".",
"is_profile_configured",
"(",
"__opts__",
",",
"(",
"__active_provider_name__",
"... | 31.715385 | 0.00047 |
def _is_possible_token(token, token_length=6):
"""Determines if given value is acceptable as a token. Used when validating
tokens.
Currently allows only numeric tokens no longer than 6 chars.
:param token: token value to be checked
:type token: int or str
:param token_length: allowed length of... | [
"def",
"_is_possible_token",
"(",
"token",
",",
"token_length",
"=",
"6",
")",
":",
"if",
"not",
"isinstance",
"(",
"token",
",",
"bytes",
")",
":",
"token",
"=",
"six",
".",
"b",
"(",
"str",
"(",
"token",
")",
")",
"return",
"token",
".",
"isdigit",... | 29.64 | 0.001307 |
def plot(*args, **kwargs):
"""Draw lines in the current context figure.
Signature: `plot(x, y, **kwargs)` or `plot(y, **kwargs)`, depending of the
length of the list of positional arguments. In the case where the `x` array
is not provided.
Parameters
----------
x: numpy.ndarray or list, 1d... | [
"def",
"plot",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"marker_str",
"=",
"None",
"if",
"len",
"(",
"args",
")",
"==",
"1",
":",
"kwargs",
"[",
"'y'",
"]",
"=",
"args",
"[",
"0",
"]",
"if",
"kwargs",
".",
"get",
"(",
"'index_data'"... | 37.830986 | 0.000363 |
def buoy_data_types(cls, buoy):
"""Determine which types of data are available for a given buoy.
Parameters
----------
buoy : str
Buoy name
Returns
-------
dict of valid file extensions and their descriptions
"""
endpoint = cls()... | [
"def",
"buoy_data_types",
"(",
"cls",
",",
"buoy",
")",
":",
"endpoint",
"=",
"cls",
"(",
")",
"file_types",
"=",
"{",
"'txt'",
":",
"'standard meteorological data'",
",",
"'drift'",
":",
"'meteorological data from drifting buoys and limited moored'",
"'buoy data mainly... | 43.567568 | 0.00182 |
def read_bytes(self):
"""
reading bytes; update progress bar after 1 ms
"""
global exit_flag
for self.i in range(0, self.length) :
self.bytes[self.i] = i_max[self.i]
self.maxbytes[self.i] = total_chunks[self.i]
self.progress[self.i]["maximum"] = total_chunks[self.i]
self.progress[self.i]["value"]... | [
"def",
"read_bytes",
"(",
"self",
")",
":",
"global",
"exit_flag",
"for",
"self",
".",
"i",
"in",
"range",
"(",
"0",
",",
"self",
".",
"length",
")",
":",
"self",
".",
"bytes",
"[",
"self",
".",
"i",
"]",
"=",
"i_max",
"[",
"self",
".",
"i",
"]... | 31.157895 | 0.037705 |
def edit_message_caption(self, *args, **kwargs):
"""See :func:`edit_message_caption`"""
return edit_message_caption(*args, **self._merge_overrides(**kwargs)).run() | [
"def",
"edit_message_caption",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"edit_message_caption",
"(",
"*",
"args",
",",
"*",
"*",
"self",
".",
"_merge_overrides",
"(",
"*",
"*",
"kwargs",
")",
")",
".",
"run",
"(",
"... | 59 | 0.01676 |
def _fix_json_agents(ag_obj):
"""Fix the json representation of an agent."""
if isinstance(ag_obj, str):
logger.info("Fixing string agent: %s." % ag_obj)
ret = {'name': ag_obj, 'db_refs': {'TEXT': ag_obj}}
elif isinstance(ag_obj, list):
# Recursive for complexes and similar.
... | [
"def",
"_fix_json_agents",
"(",
"ag_obj",
")",
":",
"if",
"isinstance",
"(",
"ag_obj",
",",
"str",
")",
":",
"logger",
".",
"info",
"(",
"\"Fixing string agent: %s.\"",
"%",
"ag_obj",
")",
"ret",
"=",
"{",
"'name'",
":",
"ag_obj",
",",
"'db_refs'",
":",
... | 37.333333 | 0.001742 |
def autosave_all(self):
"""Autosave all opened files."""
for index in range(self.stack.get_stack_count()):
self.autosave(index) | [
"def",
"autosave_all",
"(",
"self",
")",
":",
"for",
"index",
"in",
"range",
"(",
"self",
".",
"stack",
".",
"get_stack_count",
"(",
")",
")",
":",
"self",
".",
"autosave",
"(",
"index",
")"
] | 38 | 0.012903 |
def storeByteArray(self, context, page, len, data, returnError):
"""please override"""
returnError.contents.value = self.IllegalStateError
raise NotImplementedError("You must override this method.") | [
"def",
"storeByteArray",
"(",
"self",
",",
"context",
",",
"page",
",",
"len",
",",
"data",
",",
"returnError",
")",
":",
"returnError",
".",
"contents",
".",
"value",
"=",
"self",
".",
"IllegalStateError",
"raise",
"NotImplementedError",
"(",
"\"You must over... | 54.75 | 0.009009 |
def _store32(ins):
""" Stores 2nd operand content into address of 1st operand.
store16 a, x => *(&a) = x
"""
op = ins.quad[1]
indirect = op[0] == '*'
if indirect:
op = op[1:]
immediate = op[0] == '#' # Might make no sense here?
if immediate:
op = op[1:]
if is_int... | [
"def",
"_store32",
"(",
"ins",
")",
":",
"op",
"=",
"ins",
".",
"quad",
"[",
"1",
"]",
"indirect",
"=",
"op",
"[",
"0",
"]",
"==",
"'*'",
"if",
"indirect",
":",
"op",
"=",
"op",
"[",
"1",
":",
"]",
"immediate",
"=",
"op",
"[",
"0",
"]",
"==... | 22.6 | 0.000943 |
def clone_with_new_elements(
self,
new_elements,
drop_keywords=set([]),
rename_dict={},
extra_kwargs={}):
"""
Create another Collection of the same class and with same state but
possibly different entries. Extra parameters to control wh... | [
"def",
"clone_with_new_elements",
"(",
"self",
",",
"new_elements",
",",
"drop_keywords",
"=",
"set",
"(",
"[",
"]",
")",
",",
"rename_dict",
"=",
"{",
"}",
",",
"extra_kwargs",
"=",
"{",
"}",
")",
":",
"kwargs",
"=",
"dict",
"(",
"elements",
"=",
"new... | 37.956522 | 0.002235 |
def help_center_user_segment_delete(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/help_center/user_segments#delete-user-segment"
api_path = "/api/v2/help_center/user_segments/{id}.json"
api_path = api_path.format(id=id)
return self.call(api_path, method="DELETE", **kw... | [
"def",
"help_center_user_segment_delete",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/help_center/user_segments/{id}.json\"",
"api_path",
"=",
"api_path",
".",
"format",
"(",
"id",
"=",
"id",
")",
"return",
"self",
".",... | 64.2 | 0.009231 |
def new_img_like(ref_niimg, data, affine=None, copy_header=False):
"""Create a new image of the same class as the reference image
Parameters
----------
ref_niimg: image
Reference image. The new image will be of the same type.
data: numpy array
Data to be stored in the image
af... | [
"def",
"new_img_like",
"(",
"ref_niimg",
",",
"data",
",",
"affine",
"=",
"None",
",",
"copy_header",
"=",
"False",
")",
":",
"# Hand-written loading code to avoid too much memory consumption",
"if",
"not",
"(",
"hasattr",
"(",
"ref_niimg",
",",
"'get_data'",
")",
... | 35.882353 | 0.002128 |
def get_reservations_for_booking_ids(self, booking_ids):
"""Gets booking information for a given list of booking ids.
:param booking_ids: a booking id or a list of room ids (comma separated).
:type booking_ids: string
"""
try:
resp = self._request("GET", "/1.1/space/... | [
"def",
"get_reservations_for_booking_ids",
"(",
"self",
",",
"booking_ids",
")",
":",
"try",
":",
"resp",
"=",
"self",
".",
"_request",
"(",
"\"GET\"",
",",
"\"/1.1/space/booking/{}\"",
".",
"format",
"(",
"booking_ids",
")",
")",
"except",
"resp",
".",
"excep... | 43.727273 | 0.008147 |
def peek(rlp, index, sedes=None):
"""Get a specific element from an rlp encoded nested list.
This function uses :func:`rlp.decode_lazy` and, thus, decodes only the
necessary parts of the string.
Usage example::
>>> import rlp
>>> rlpdata = rlp.encode([1, 2, [3, [4, 5]]])
>>> r... | [
"def",
"peek",
"(",
"rlp",
",",
"index",
",",
"sedes",
"=",
"None",
")",
":",
"ll",
"=",
"decode_lazy",
"(",
"rlp",
")",
"if",
"not",
"isinstance",
"(",
"index",
",",
"Iterable",
")",
":",
"index",
"=",
"[",
"index",
"]",
"for",
"i",
"in",
"index... | 32.235294 | 0.000886 |
def get_authorizations_by_search(self, authorization_query, authorization_search):
"""Pass through to provider AuthorizationSearchSession.get_authorizations_by_search"""
# Implemented from azosid template for -
# osid.resource.ResourceSearchSession.get_resources_by_search_template
if not... | [
"def",
"get_authorizations_by_search",
"(",
"self",
",",
"authorization_query",
",",
"authorization_search",
")",
":",
"# Implemented from azosid template for -",
"# osid.resource.ResourceSearchSession.get_resources_by_search_template",
"if",
"not",
"self",
".",
"_can",
"(",
"'se... | 68.857143 | 0.010246 |
def gunzip(input_gzip_file, block_size=1024):
"""
Gunzips the input file to the same directory
:param input_gzip_file: File to be gunzipped
:return: path to the gunzipped file
:rtype: str
"""
assert os.path.splitext(input_gzip_file)[1] == '.gz'
assert is_gzipfile(input_gzip_file)
wi... | [
"def",
"gunzip",
"(",
"input_gzip_file",
",",
"block_size",
"=",
"1024",
")",
":",
"assert",
"os",
".",
"path",
".",
"splitext",
"(",
"input_gzip_file",
")",
"[",
"1",
"]",
"==",
"'.gz'",
"assert",
"is_gzipfile",
"(",
"input_gzip_file",
")",
"with",
"gzip"... | 33.263158 | 0.001538 |
def youtube(no_controls, no_autoplay, store, store_name, youtube_url):
"""Convert a Youtube URL so that works correctly with Helium.
This command is used for converting the URL for a Youtube video that is
part of a playlist so that Helium recognises it as a playlist and when
the video ends it correctly... | [
"def",
"youtube",
"(",
"no_controls",
",",
"no_autoplay",
",",
"store",
",",
"store_name",
",",
"youtube_url",
")",
":",
"old_url_colour",
"=",
"'blue'",
"new_url_colour",
"=",
"'green'",
"echo",
"(",
"'Format --> {0}: {1}'",
".",
"format",
"(",
"style",
"(",
... | 38.576923 | 0.000973 |
def _bsecurate_cli_make_graph_file(args):
'''Handles the make-graph-file subcommand'''
curate.make_graph_file(args.basis, args.outfile, args.render, args.version, args.data_dir)
return '' | [
"def",
"_bsecurate_cli_make_graph_file",
"(",
"args",
")",
":",
"curate",
".",
"make_graph_file",
"(",
"args",
".",
"basis",
",",
"args",
".",
"outfile",
",",
"args",
".",
"render",
",",
"args",
".",
"version",
",",
"args",
".",
"data_dir",
")",
"return",
... | 39.2 | 0.01 |
def call(method, *args, **kwargs):
'''
Invoke an arbitrary pyeapi method.
method
The name of the pyeapi method to invoke.
args
A list of arguments to send to the method invoked.
kwargs
Key-value dictionary to send to the method invoked.
transport: ``https``
Sp... | [
"def",
"call",
"(",
"method",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"=",
"clean_kwargs",
"(",
"*",
"*",
"kwargs",
")",
"if",
"'pyeapi.call'",
"in",
"__proxy__",
":",
"return",
"__proxy__",
"[",
"'pyeapi.call'",
"]",
"(",
"metho... | 30.723684 | 0.00083 |
def pshp_soundex_last(lname, max_length=4, german=False):
"""Calculate the PSHP Soundex/Viewex Coding of a last name.
This is a wrapper for :py:meth:`PSHPSoundexLast.encode`.
Parameters
----------
lname : str
The last name to encode
max_length : int
The length of the code retur... | [
"def",
"pshp_soundex_last",
"(",
"lname",
",",
"max_length",
"=",
"4",
",",
"german",
"=",
"False",
")",
":",
"return",
"PSHPSoundexLast",
"(",
")",
".",
"encode",
"(",
"lname",
",",
"max_length",
",",
"german",
")"
] | 23.441176 | 0.001205 |
def decode_jwt(encoded_token, secret, algorithm, identity_claim_key,
user_claims_key, csrf_value=None, audience=None,
leeway=0, allow_expired=False):
"""
Decodes an encoded JWT
:param encoded_token: The encoded JWT string to decode
:param secret: Secret key used to encode ... | [
"def",
"decode_jwt",
"(",
"encoded_token",
",",
"secret",
",",
"algorithm",
",",
"identity_claim_key",
",",
"user_claims_key",
",",
"csrf_value",
"=",
"None",
",",
"audience",
"=",
"None",
",",
"leeway",
"=",
"0",
",",
"allow_expired",
"=",
"False",
")",
":"... | 42.533333 | 0.001021 |
def listen_fds(unset_environment=True):
"""Return a list of socket activated descriptors
Example::
(in primary window)
$ systemd-activate -l 2000 python3 -c \\
'from systemd.daemon import listen_fds; print(listen_fds())'
(in another window)
$ telnet localhost 2000
(in p... | [
"def",
"listen_fds",
"(",
"unset_environment",
"=",
"True",
")",
":",
"num",
"=",
"_listen_fds",
"(",
"unset_environment",
")",
"return",
"list",
"(",
"range",
"(",
"LISTEN_FDS_START",
",",
"LISTEN_FDS_START",
"+",
"num",
")",
")"
] | 28.235294 | 0.002016 |
def get_func_kwargs(func, recursive=True):
"""
func = ibeis.run_experiment
SeeAlso:
argparse_funckw
recursive_parse_kwargs
parse_kwarg_keys
parse_func_kwarg_keys
get_func_kwargs
"""
import utool as ut
argspec = ut.get_func_argspec(func)
if argspec.def... | [
"def",
"get_func_kwargs",
"(",
"func",
",",
"recursive",
"=",
"True",
")",
":",
"import",
"utool",
"as",
"ut",
"argspec",
"=",
"ut",
".",
"get_func_argspec",
"(",
"func",
")",
"if",
"argspec",
".",
"defaults",
"is",
"None",
":",
"header_kw",
"=",
"{",
... | 27.2 | 0.001776 |
def load(fnames, tag=None, sat_id=None):
"""Load Kp index files
Parameters
------------
fnames : (pandas.Series)
Series of filenames
tag : (str or NoneType)
tag or None (default=None)
sat_id : (str or NoneType)
satellite id or None (default=None)
Returns
-------... | [
"def",
"load",
"(",
"fnames",
",",
"tag",
"=",
"None",
",",
"sat_id",
"=",
"None",
")",
":",
"# Kp data stored monthly, need to return data daily",
"# the daily date is attached to filename",
"# parse off the last date, load month of data, downselect to desired day",
"data",
"=",... | 34.027397 | 0.018779 |
def getSoundFileDuration(fn):
'''
Returns the duration of a wav file (in seconds)
'''
audiofile = wave.open(fn, "r")
params = audiofile.getparams()
framerate = params[2]
nframes = params[3]
duration = float(nframes) / framerate
return duration | [
"def",
"getSoundFileDuration",
"(",
"fn",
")",
":",
"audiofile",
"=",
"wave",
".",
"open",
"(",
"fn",
",",
"\"r\"",
")",
"params",
"=",
"audiofile",
".",
"getparams",
"(",
")",
"framerate",
"=",
"params",
"[",
"2",
"]",
"nframes",
"=",
"params",
"[",
... | 23.166667 | 0.010381 |
def agents(self):
"""
| Description: IDs of agents involved in the chat
"""
if self.api and self.agent_ids:
return self.api._get_agents(self.agent_ids) | [
"def",
"agents",
"(",
"self",
")",
":",
"if",
"self",
".",
"api",
"and",
"self",
".",
"agent_ids",
":",
"return",
"self",
".",
"api",
".",
"_get_agents",
"(",
"self",
".",
"agent_ids",
")"
] | 31.833333 | 0.010204 |
def send_location(self, peer: Peer, latitude: float, longitude: float, reply: int=None,
on_success: callable=None, reply_markup: botapi.ReplyMarkup=None):
"""
Send location to peer.
:param peer: Peer to send message to.
:param latitude: Latitude of the location.
... | [
"def",
"send_location",
"(",
"self",
",",
"peer",
":",
"Peer",
",",
"latitude",
":",
"float",
",",
"longitude",
":",
"float",
",",
"reply",
":",
"int",
"=",
"None",
",",
"on_success",
":",
"callable",
"=",
"None",
",",
"reply_markup",
":",
"botapi",
".... | 47.166667 | 0.015012 |
def start_standing_subprocess(cmd, shell=False, env=None):
"""Starts a long-running subprocess.
This is not a blocking call and the subprocess started by it should be
explicitly terminated with stop_standing_subprocess.
For short-running commands, you should use subprocess.check_call, which
blocks... | [
"def",
"start_standing_subprocess",
"(",
"cmd",
",",
"shell",
"=",
"False",
",",
"env",
"=",
"None",
")",
":",
"logging",
".",
"debug",
"(",
"'Starting standing subprocess with: %s'",
",",
"cmd",
")",
"proc",
"=",
"subprocess",
".",
"Popen",
"(",
"cmd",
",",... | 38 | 0.000733 |
def get_path(self):
"""
Returns the path to this node top level directory (where config/data is stored)
"""
return os.path.join(self.cluster.get_path(), self.name) | [
"def",
"get_path",
"(",
"self",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"cluster",
".",
"get_path",
"(",
")",
",",
"self",
".",
"name",
")"
] | 38.2 | 0.015385 |
def type(self):
"""Returns type of the data for the given FeatureType."""
if self is FeatureType.TIMESTAMP:
return list
if self is FeatureType.BBOX:
return BBox
return dict | [
"def",
"type",
"(",
"self",
")",
":",
"if",
"self",
"is",
"FeatureType",
".",
"TIMESTAMP",
":",
"return",
"list",
"if",
"self",
"is",
"FeatureType",
".",
"BBOX",
":",
"return",
"BBox",
"return",
"dict"
] | 31.714286 | 0.008772 |
def gen_random_company_name():
"""
随机生成一个公司名称
:returns:
* company_name: (string) 银行名称
举例如下::
print('--- gen_random_company_name demo ---')
print(gen_random_company_name())
print('---')
输出结果::
--- gen_random_company_name demo ---
上海大升旅游质询有限责任公司
... | [
"def",
"gen_random_company_name",
"(",
")",
":",
"region_info",
"=",
"(",
"\"北京,上海,广州,深圳,天津,成都,杭州,苏州,重庆,武汉,南京,大连,沈阳,长沙,郑州,西安,青岛,\"",
"\"无锡,济南,宁波,佛山,南通,哈尔滨,东莞,福州,长春,石家庄,烟台,合肥,唐山,常州,太原,昆明,\"",
"\"潍坊,南昌,泉州,温州,绍兴,嘉兴,厦门,贵阳,淄博,徐州,南宁,扬州,呼和浩特,鄂尔多斯,乌鲁木齐,\"",
"\"金华,台州,镇江,威海,珠海,东营,大庆,中山,盐城,包头,保定,济宁,泰州,廊坊... | 53.23913 | 0.001203 |
def optimize(self, duplicate_manager=None):
"""
Optimizes the acquisition function (uses a flag from the model to use gradients or not).
"""
if not self.analytical_gradient_acq:
out = self.optimizer.optimize(f=self.acquisition_function, duplicate_manager=duplicate_manager)
... | [
"def",
"optimize",
"(",
"self",
",",
"duplicate_manager",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"analytical_gradient_acq",
":",
"out",
"=",
"self",
".",
"optimizer",
".",
"optimize",
"(",
"f",
"=",
"self",
".",
"acquisition_function",
",",
"dupl... | 55.111111 | 0.009921 |
def execute(self, conn, logical_file_name, transaction=False):
"""
simple execute
"""
if not conn:
dbsExceptionHandler("dbsException-db-conn-failed", "Oracle/FileBuffer/DeleteDupicates. Expects db connection from upper layer.")
print(self.sql)
self.dbi.processData(self.sql, logical_fil... | [
"def",
"execute",
"(",
"self",
",",
"conn",
",",
"logical_file_name",
",",
"transaction",
"=",
"False",
")",
":",
"if",
"not",
"conn",
":",
"dbsExceptionHandler",
"(",
"\"dbsException-db-conn-failed\"",
",",
"\"Oracle/FileBuffer/DeleteDupicates. Expects db connection from... | 37.555556 | 0.037572 |
def __add_token_to_document(self, token, token_id, connected):
"""
adds a token to the document graph as a node with the given ID.
Parameters
----------
token : str
the token to be added to the document graph
token_id : int
the node ID of the toke... | [
"def",
"__add_token_to_document",
"(",
"self",
",",
"token",
",",
"token_id",
",",
"connected",
")",
":",
"regex_match",
"=",
"ANNOTATED_ANAPHORA_REGEX",
".",
"search",
"(",
"token",
")",
"if",
"regex_match",
":",
"# token is annotated",
"unannotated_token",
"=",
... | 43.102564 | 0.001163 |
def remove_response_property(xml_root):
"""Removes response properties if exist."""
if xml_root.tag == "testsuites":
properties = xml_root.find("properties")
resp_properties = []
for prop in properties:
prop_name = prop.get("name", "")
if "polarion-response-" in p... | [
"def",
"remove_response_property",
"(",
"xml_root",
")",
":",
"if",
"xml_root",
".",
"tag",
"==",
"\"testsuites\"",
":",
"properties",
"=",
"xml_root",
".",
"find",
"(",
"\"properties\"",
")",
"resp_properties",
"=",
"[",
"]",
"for",
"prop",
"in",
"properties"... | 42.705882 | 0.001348 |
def would_move_be_promotion(self):
"""
Finds if move from current location would be a promotion
"""
return (self._end_loc.rank == 0 and not self.color) or \
(self._end_loc.rank == 7 and self.color) | [
"def",
"would_move_be_promotion",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"_end_loc",
".",
"rank",
"==",
"0",
"and",
"not",
"self",
".",
"color",
")",
"or",
"(",
"self",
".",
"_end_loc",
".",
"rank",
"==",
"7",
"and",
"self",
".",
"color",... | 39.333333 | 0.008299 |
def within_rupture_distance(self, surface, distance, **kwargs):
'''
Select events within a rupture distance from a fault surface
:param surface:
Fault surface as instance of nhlib.geo.surface.base.BaseSurface
:param float distance:
Rupture distance (km)
... | [
"def",
"within_rupture_distance",
"(",
"self",
",",
"surface",
",",
"distance",
",",
"*",
"*",
"kwargs",
")",
":",
"# Check for upper and lower depths",
"upper_depth",
",",
"lower_depth",
"=",
"_check_depth_limits",
"(",
"kwargs",
")",
"rrupt",
"=",
"surface",
"."... | 36.958333 | 0.002198 |
def resize(self, newWidth = 0, newHeight = 0):
"""!
\~english
Resize width and height of rectangles
@param newWidth: new width value
@param newHeight: new height value
\~chinese
重新设定矩形高宽
@param newWidth: 新宽度
@param newHeight: 新高度
"""
... | [
"def",
"resize",
"(",
"self",
",",
"newWidth",
"=",
"0",
",",
"newHeight",
"=",
"0",
")",
":",
"self",
".",
"height",
"=",
"newHeight",
"self",
".",
"width",
"=",
"newWidth"
] | 28.076923 | 0.026525 |
def _execfile(filename, globals, locals=None):
"""
Python 3 implementation of execfile.
"""
mode = 'rb'
# Python 2.6 compile requires LF for newlines, so use deprecated
# Universal newlines support.
if sys.version_info < (2, 7):
mode += 'U'
with open(filename, mode) as stream:
... | [
"def",
"_execfile",
"(",
"filename",
",",
"globals",
",",
"locals",
"=",
"None",
")",
":",
"mode",
"=",
"'rb'",
"# Python 2.6 compile requires LF for newlines, so use deprecated",
"# Universal newlines support.",
"if",
"sys",
".",
"version_info",
"<",
"(",
"2",
",",
... | 30.666667 | 0.00211 |
def to_dict(self):
"""
Recusively exports object values to a dict
:return: `dict`of values
"""
if not hasattr(self, '_fields'):
return self.__dict__
result = dict()
for field_name, field in self._fields.items():
if isinstance(field, xmlmap... | [
"def",
"to_dict",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_fields'",
")",
":",
"return",
"self",
".",
"__dict__",
"result",
"=",
"dict",
"(",
")",
"for",
"field_name",
",",
"field",
"in",
"self",
".",
"_fields",
".",
"items... | 38.103448 | 0.001765 |
def focus_prev(self):
"""move focus to previous position (DFO)"""
w, focuspos = self.get_focus()
prev = self._tree.prev_position(focuspos)
if prev is not None:
self.set_focus(prev) | [
"def",
"focus_prev",
"(",
"self",
")",
":",
"w",
",",
"focuspos",
"=",
"self",
".",
"get_focus",
"(",
")",
"prev",
"=",
"self",
".",
"_tree",
".",
"prev_position",
"(",
"focuspos",
")",
"if",
"prev",
"is",
"not",
"None",
":",
"self",
".",
"set_focus"... | 36.5 | 0.008929 |
def _dict_to_string(dictionary):
'''
converts a dictionary object into a list of strings
'''
ret = ''
for key, val in sorted(dictionary.items()):
if isinstance(val, dict):
for line in _dict_to_string(val):
ret += six.text_type(key) + '-' + line + '\n'
elif... | [
"def",
"_dict_to_string",
"(",
"dictionary",
")",
":",
"ret",
"=",
"''",
"for",
"key",
",",
"val",
"in",
"sorted",
"(",
"dictionary",
".",
"items",
"(",
")",
")",
":",
"if",
"isinstance",
"(",
"val",
",",
"dict",
")",
":",
"for",
"line",
"in",
"_di... | 38 | 0.001712 |
def media_types():
"""Return a list of the IANA Media (MIME) Types, or an empty list if the
IANA website is unreachable.
Store it as a function attribute so that we only build the list once.
"""
if not hasattr(media_types, 'typelist'):
tlist = []
categories = [
'applicati... | [
"def",
"media_types",
"(",
")",
":",
"if",
"not",
"hasattr",
"(",
"media_types",
",",
"'typelist'",
")",
":",
"tlist",
"=",
"[",
"]",
"categories",
"=",
"[",
"'application'",
",",
"'audio'",
",",
"'font'",
",",
"'image'",
",",
"'message'",
",",
"'model'"... | 32.717949 | 0.000761 |
def get_filenames(root, prefix=u'', suffix=u''):
"""Function for listing filenames with given prefix and suffix in the root directory.
Parameters
----------
prefix: str
The prefix of the required files.
suffix: str
The suffix of the required files
Returns
-... | [
"def",
"get_filenames",
"(",
"root",
",",
"prefix",
"=",
"u''",
",",
"suffix",
"=",
"u''",
")",
":",
"return",
"[",
"fnm",
"for",
"fnm",
"in",
"os",
".",
"listdir",
"(",
"root",
")",
"if",
"fnm",
".",
"startswith",
"(",
"prefix",
")",
"and",
"fnm",... | 29.235294 | 0.011696 |
def create_many_to_many_intermediary_model(field, klass):
"""
Copied from django, but uses FKToVersion for the
'from' field. Fields are also always called 'from' and 'to'
to avoid problems between version combined models.
"""
managed = True
if (isinstance(field.remote_field.to, basestring) a... | [
"def",
"create_many_to_many_intermediary_model",
"(",
"field",
",",
"klass",
")",
":",
"managed",
"=",
"True",
"if",
"(",
"isinstance",
"(",
"field",
".",
"remote_field",
".",
"to",
",",
"basestring",
")",
"and",
"field",
".",
"remote_field",
".",
"to",
"!="... | 41.693548 | 0.000378 |
def validate_structure(reference_intervals, reference_labels,
estimated_intervals, estimated_labels):
"""Checks that the input annotations to a structure estimation metric (i.e.
one that takes in both segment boundaries and their labels) look like valid
segment times and labels, and t... | [
"def",
"validate_structure",
"(",
"reference_intervals",
",",
"reference_labels",
",",
"estimated_intervals",
",",
"estimated_labels",
")",
":",
"for",
"(",
"intervals",
",",
"labels",
")",
"in",
"[",
"(",
"reference_intervals",
",",
"reference_labels",
")",
",",
... | 42.8125 | 0.000476 |
def search_for_port(port_glob, req, expected_res):
''' Find the serial port the arm is connected to. '''
# Check that the USB port actually exists, based on the known vendor and
# product ID.
if usb.core.find(idVendor=0x0403, idProduct=0x6001) is None:
return None
# Find ports matching the... | [
"def",
"search_for_port",
"(",
"port_glob",
",",
"req",
",",
"expected_res",
")",
":",
"# Check that the USB port actually exists, based on the known vendor and",
"# product ID.",
"if",
"usb",
".",
"core",
".",
"find",
"(",
"idVendor",
"=",
"0x0403",
",",
"idProduct",
... | 33.314286 | 0.001667 |
def gapfill(
model, core, blocked, exclude, solver, epsilon=0.001, v_max=1000,
weights={}, implicit_sinks=True, allow_bounds_expansion=False):
"""Find a set of reactions to add such that no compounds are blocked.
Returns two iterators: first an iterator of reactions not in
core, that were a... | [
"def",
"gapfill",
"(",
"model",
",",
"core",
",",
"blocked",
",",
"exclude",
",",
"solver",
",",
"epsilon",
"=",
"0.001",
",",
"v_max",
"=",
"1000",
",",
"weights",
"=",
"{",
"}",
",",
"implicit_sinks",
"=",
"True",
",",
"allow_bounds_expansion",
"=",
... | 43.358779 | 0.000172 |
def register_sensor(self, child):
"""Register a sensor required by an aggregate sensor registered with
add_delayed.
Parameters
----------
child : :class:`katcp.Sensor` object
A child sensor required by one or more delayed aggregate sensors.
"""
child... | [
"def",
"register_sensor",
"(",
"self",
",",
"child",
")",
":",
"child_name",
"=",
"self",
".",
"_get_sensor_reference",
"(",
"child",
")",
"if",
"child_name",
"in",
"self",
".",
"_registered_sensors",
":",
"raise",
"ValueError",
"(",
"\"Sensor %r already registere... | 39.714286 | 0.001756 |
def put(cont, path=None, local_file=None, profile=None):
'''
Create a new container, or upload an object to a container.
CLI Example to create a container:
.. code-block:: bash
salt myminion swift.put mycontainer
CLI Example to upload an object to a container:
.. code-block:: bash
... | [
"def",
"put",
"(",
"cont",
",",
"path",
"=",
"None",
",",
"local_file",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"swift_conn",
"=",
"_auth",
"(",
"profile",
")",
"if",
"path",
"is",
"None",
":",
"return",
"swift_conn",
".",
"put_container",
... | 25.375 | 0.001582 |
def keyword_scan(self, query_id=None, query_fc=None, feature_names=None):
'''Keyword scan for feature collections.
This performs a keyword scan using the query given. A keyword
scan searches for FCs with terms in each of the query's indexed
fields.
At least one of ``query_id`` ... | [
"def",
"keyword_scan",
"(",
"self",
",",
"query_id",
"=",
"None",
",",
"query_fc",
"=",
"None",
",",
"feature_names",
"=",
"None",
")",
":",
"it",
"=",
"self",
".",
"_keyword_scan",
"(",
"query_id",
",",
"query_fc",
",",
"feature_names",
"=",
"feature_name... | 44.583333 | 0.00183 |
def _clauses(lexer, varname, nvars):
"""Return a tuple of DIMACS CNF clauses."""
tok = next(lexer)
toktype = type(tok)
if toktype is OP_not or toktype is IntegerToken:
lexer.unpop_token(tok)
first = _clause(lexer, varname, nvars)
rest = _clauses(lexer, varname, nvars)
ret... | [
"def",
"_clauses",
"(",
"lexer",
",",
"varname",
",",
"nvars",
")",
":",
"tok",
"=",
"next",
"(",
"lexer",
")",
"toktype",
"=",
"type",
"(",
"tok",
")",
"if",
"toktype",
"is",
"OP_not",
"or",
"toktype",
"is",
"IntegerToken",
":",
"lexer",
".",
"unpop... | 31 | 0.00241 |
def attrs(self):
"""provide a copy of this player's attributes as a dictionary"""
ret = dict(self.__dict__) # obtain copy of internal __dict__
del ret["_matches"] # match history is specifically distinguished from player information (and stored separately)
if self.type != c.COMPUTER: # d... | [
"def",
"attrs",
"(",
"self",
")",
":",
"ret",
"=",
"dict",
"(",
"self",
".",
"__dict__",
")",
"# obtain copy of internal __dict__",
"del",
"ret",
"[",
"\"_matches\"",
"]",
"# match history is specifically distinguished from player information (and stored separately)",
"if",... | 58.571429 | 0.016827 |
def importaccount(ctx, account, role):
""" Import an account using an account password
"""
from bitsharesbase.account import PasswordKey
password = click.prompt("Account Passphrase", hide_input=True)
account = Account(account, bitshares_instance=ctx.bitshares)
imported = False
if role == "... | [
"def",
"importaccount",
"(",
"ctx",
",",
"account",
",",
"role",
")",
":",
"from",
"bitsharesbase",
".",
"account",
"import",
"PasswordKey",
"password",
"=",
"click",
".",
"prompt",
"(",
"\"Account Passphrase\"",
",",
"hide_input",
"=",
"True",
")",
"account",... | 40.954545 | 0.001626 |
def list_actions(i):
"""
Input: {
(repo_uoa) - repo UOA
(module_uoa) - module_uoa, if =="", use kernel
(data_uoa)
}
Output: {
return - return code = 0, if successful
> 0, if error
... | [
"def",
"list_actions",
"(",
"i",
")",
":",
"o",
"=",
"i",
".",
"get",
"(",
"'out'",
",",
"''",
")",
"ruoa",
"=",
"i",
".",
"get",
"(",
"'repo_uoa'",
",",
"''",
")",
"muoa",
"=",
"i",
".",
"get",
"(",
"'module_uoa'",
",",
"''",
")",
"duoa",
"=... | 21.517857 | 0.043651 |
def localize_fields(cls, localized_fields):
"""
For each field name in localized_fields,
for each language in settings.LANGUAGES,
add fields to cls,
and remove the original field, instead
replace it with a DefaultFieldDescriptor,
which always returns the field in the current language.
""... | [
"def",
"localize_fields",
"(",
"cls",
",",
"localized_fields",
")",
":",
"# never do this twice",
"if",
"hasattr",
"(",
"cls",
",",
"'localized_fields'",
")",
":",
"return",
"cls",
"# MSGID_LANGUAGE is the language that is used for the gettext message id's.",
"# If it is not ... | 42.114943 | 0.000533 |
def get_auth_error_message(self):
''' create an informative error message if there is an issue authenticating'''
errors = ["Authentication error retrieving ec2 inventory."]
if None in [os.environ.get('AWS_ACCESS_KEY_ID'), os.environ.get('AWS_SECRET_ACCESS_KEY')]:
errors.append(' - No... | [
"def",
"get_auth_error_message",
"(",
"self",
")",
":",
"errors",
"=",
"[",
"\"Authentication error retrieving ec2 inventory.\"",
"]",
"if",
"None",
"in",
"[",
"os",
".",
"environ",
".",
"get",
"(",
"'AWS_ACCESS_KEY_ID'",
")",
",",
"os",
".",
"environ",
".",
"... | 63.3125 | 0.008755 |
def resolve_config_spec(config_spec, config_dir=''):
"""
Resolves :attr:`config_spec` to a path to a config file.
:param str config_spec: Valid config specs:
- The basename of a YAML config file *without* the ``.yml`` extension.
The full path to the config file is resolved by appending ... | [
"def",
"resolve_config_spec",
"(",
"config_spec",
",",
"config_dir",
"=",
"''",
")",
":",
"if",
"'/'",
"in",
"config_spec",
"or",
"config_spec",
".",
"endswith",
"(",
"'.yml'",
")",
":",
"return",
"config_spec",
"return",
"os",
".",
"path",
".",
"join",
"(... | 37.84 | 0.001031 |
def loadScopeGroupbyName(self, name, service_group_id, callback=None, errback=None):
"""
Load an existing Scope Group by name and service group id into a high level Scope Group object
:param str name: Name of an existing Scope Group
:param int service_group_id: id of the service group t... | [
"def",
"loadScopeGroupbyName",
"(",
"self",
",",
"name",
",",
"service_group_id",
",",
"callback",
"=",
"None",
",",
"errback",
"=",
"None",
")",
":",
"import",
"ns1",
".",
"ipam",
"scope_group",
"=",
"ns1",
".",
"ipam",
".",
"Scopegroup",
"(",
"self",
"... | 54.9 | 0.010753 |
def list(region=None, key=None, keyid=None, profile=None):
'''
List all buckets owned by the authenticated sender of the request.
Returns list of buckets
CLI Example:
.. code-block:: yaml
Owner: {...}
Buckets:
- {...}
- {...}
'''
try:
conn = _... | [
"def",
"list",
"(",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"try",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=",
"key",
",",
"keyid",
"=",
... | 26.153846 | 0.001418 |
def dataframe(self, sids, head=0, tail=EPOCHS_MAX, datetime=True):
"""
Create data frame
Parameters
----------
sids : list[str]
head : int | pandas.Timestamp, optional
Start of the interval
default earliest available
tail : int | pandas.Ti... | [
"def",
"dataframe",
"(",
"self",
",",
"sids",
",",
"head",
"=",
"0",
",",
"tail",
"=",
"EPOCHS_MAX",
",",
"datetime",
"=",
"True",
")",
":",
"if",
"head",
"is",
"None",
":",
"head",
"=",
"0",
"else",
":",
"head",
"=",
"self",
".",
"_2epochs",
"("... | 26.783784 | 0.001947 |
def list_(name, add, match, stamp=False, prune=0):
'''
Add the specified values to the named list
If ``stamp`` is True, then the timestamp from the event will also be added
if ``prune`` is set to an integer higher than ``0``, then only the last
``prune`` values will be kept in the list.
USAGE:... | [
"def",
"list_",
"(",
"name",
",",
"add",
",",
"match",
",",
"stamp",
"=",
"False",
",",
"prune",
"=",
"0",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'comment'",
":",
"''",
",",
"'result'",
":",
"Tr... | 29.860465 | 0.000754 |
def CMFR(t, C_initial, C_influent):
"""Calculate the effluent concentration of a conversative (non-reacting)
material with continuous input to a completely mixed flow reactor.
Note: time t=0 is the time at which the material starts to flow into the
reactor.
:param C_initial: The concentration in t... | [
"def",
"CMFR",
"(",
"t",
",",
"C_initial",
",",
"C_influent",
")",
":",
"return",
"C_influent",
"*",
"(",
"1",
"-",
"np",
".",
"exp",
"(",
"-",
"t",
")",
")",
"+",
"C_initial",
"*",
"np",
".",
"exp",
"(",
"-",
"t",
")"
] | 40.592593 | 0.001783 |
async def prover_get_credential(wallet_handle: int,
cred_id: str) -> str:
"""
Gets human readable credential by the given id.
:param wallet_handle: wallet handler (created by open_wallet).
:param cred_id: Identifier by which requested credential is stored in the wallet
... | [
"async",
"def",
"prover_get_credential",
"(",
"wallet_handle",
":",
"int",
",",
"cred_id",
":",
"str",
")",
"->",
"str",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"logger",
".",
"debug",
"(",
"\"prover_get_credential: >>> wallet_hand... | 37.289474 | 0.002063 |
def stop(self):
"""Stop the communication with the shield."""
with self.lock:
self._message_received(ConnectionClosed(self._file, self)) | [
"def",
"stop",
"(",
"self",
")",
":",
"with",
"self",
".",
"lock",
":",
"self",
".",
"_message_received",
"(",
"ConnectionClosed",
"(",
"self",
".",
"_file",
",",
"self",
")",
")"
] | 40.25 | 0.012195 |
def mass_2d(self, r, rho0, gamma):
"""
mass enclosed projected 2d sphere of radius r
:param r:
:param rho0:
:param a:
:param s:
:return:
"""
alpha = np.sqrt(np.pi) * special.gamma(1. / 2 * (-1 + gamma)) / special.gamma(gamma / 2.) * r ** (2 - gamma... | [
"def",
"mass_2d",
"(",
"self",
",",
"r",
",",
"rho0",
",",
"gamma",
")",
":",
"alpha",
"=",
"np",
".",
"sqrt",
"(",
"np",
".",
"pi",
")",
"*",
"special",
".",
"gamma",
"(",
"1.",
"/",
"2",
"*",
"(",
"-",
"1",
"+",
"gamma",
")",
")",
"/",
... | 32.416667 | 0.01 |
def _series_generic(self):
"""Return image series in file.
A series is a sequence of TiffPages with the same hash.
"""
pages = self.pages
pages._clear(False)
pages.useframes = False
if pages.cache:
pages._load()
result = []
keys = []... | [
"def",
"_series_generic",
"(",
"self",
")",
":",
"pages",
"=",
"self",
".",
"pages",
"pages",
".",
"_clear",
"(",
"False",
")",
"pages",
".",
"useframes",
"=",
"False",
"if",
"pages",
".",
"cache",
":",
"pages",
".",
"_load",
"(",
")",
"result",
"=",... | 27.763158 | 0.001832 |
def parse_topology(ml_log, log=None, ml_version='1.3.4BETA', print_output=False):
"""Parse the ml_log file generated by the measure_topology function.
Args:
ml_log (str): MeshLab log file to parse
log (str): filename to log output
Returns:
dict: dictionary with the following keys:
... | [
"def",
"parse_topology",
"(",
"ml_log",
",",
"log",
"=",
"None",
",",
"ml_version",
"=",
"'1.3.4BETA'",
",",
"print_output",
"=",
"False",
")",
":",
"topology",
"=",
"{",
"'manifold'",
":",
"True",
",",
"'non_manifold_E'",
":",
"0",
",",
"'non_manifold_V'",
... | 47.380952 | 0.000985 |
def get_root_bins(self):
"""Gets the root bins in the bin hierarchy.
A node with no parents is an orphan. While all bin ``Ids`` are
known to the hierarchy, an orphan does not appear in the
hierarchy unless explicitly added as a root node or child of
another node.
return... | [
"def",
"get_root_bins",
"(",
"self",
")",
":",
"# Implemented from template for",
"# osid.resource.BinHierarchySession.get_root_bins",
"if",
"self",
".",
"_catalog_session",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_catalog_session",
".",
"get_root_catalogs",
"("... | 41.904762 | 0.002222 |
def script_template(state, host, template_filename, chdir=None, **data):
'''
Generate, upload and execute a local script template on the remote host.
+ template_filename: local script template filename
+ chdir: directory to cd into before executing the script
'''
temp_file = state.get_temp_fil... | [
"def",
"script_template",
"(",
"state",
",",
"host",
",",
"template_filename",
",",
"chdir",
"=",
"None",
",",
"*",
"*",
"data",
")",
":",
"temp_file",
"=",
"state",
".",
"get_temp_filename",
"(",
"template_filename",
")",
"yield",
"files",
".",
"template",
... | 31.882353 | 0.001792 |
def serial_load(workflow_file, specification, parameters=None, original=None):
"""Validate and return a expanded REANA Serial workflow specification.
:param workflow_file: A specification file compliant with
REANA Serial workflow specification.
:returns: A dictionary which represents the valid Seri... | [
"def",
"serial_load",
"(",
"workflow_file",
",",
"specification",
",",
"parameters",
"=",
"None",
",",
"original",
"=",
"None",
")",
":",
"parameters",
"=",
"parameters",
"or",
"{",
"}",
"if",
"not",
"specification",
":",
"with",
"open",
"(",
"workflow_file"... | 37.190476 | 0.001248 |
def p_cpf_list(self, p):
'''cpf_list : cpf_list cpf_def
| empty'''
if p[1] is None:
p[0] = []
else:
p[1].append(p[2])
p[0] = p[1] | [
"def",
"p_cpf_list",
"(",
"self",
",",
"p",
")",
":",
"if",
"p",
"[",
"1",
"]",
"is",
"None",
":",
"p",
"[",
"0",
"]",
"=",
"[",
"]",
"else",
":",
"p",
"[",
"1",
"]",
".",
"append",
"(",
"p",
"[",
"2",
"]",
")",
"p",
"[",
"0",
"]",
"=... | 25.25 | 0.009569 |
def process(self, metric, handler):
"""
process a single diamond metric
@type metric: diamond.metric.Metric
@param metric: metric to process
@type handler: diamond.handler.sentry.SentryHandler
@param handler: configured Sentry graphite handler
@rtype None
... | [
"def",
"process",
"(",
"self",
",",
"metric",
",",
"handler",
")",
":",
"match",
"=",
"self",
".",
"regexp",
".",
"match",
"(",
"metric",
".",
"path",
")",
"if",
"match",
":",
"minimum",
"=",
"Minimum",
"(",
"metric",
".",
"value",
",",
"self",
"."... | 45.809524 | 0.001018 |
def representer(dumper, data):
"""
http://stackoverflow.com/a/14001707/4075339
http://stackoverflow.com/a/21912744/4075339
"""
tag = yaml.resolver.BaseResolver.DEFAULT_MAPPING_TAG
return dumper.represent_mapping(tag,list(data.todict().items()),flow_style=True) | [
"def",
"representer",
"(",
"dumper",
",",
"data",
")",
":",
"tag",
"=",
"yaml",
".",
"resolver",
".",
"BaseResolver",
".",
"DEFAULT_MAPPING_TAG",
"return",
"dumper",
".",
"represent_mapping",
"(",
"tag",
",",
"list",
"(",
"data",
".",
"todict",
"(",
")",
... | 43.428571 | 0.022581 |
def filterflags_general_tags(tags_list, has_any=None, has_all=None,
has_none=None, min_num=None, max_num=None,
any_startswith=None, any_endswith=None,
in_any=None, any_match=None, none_match=None,
logic='... | [
"def",
"filterflags_general_tags",
"(",
"tags_list",
",",
"has_any",
"=",
"None",
",",
"has_all",
"=",
"None",
",",
"has_none",
"=",
"None",
",",
"min_num",
"=",
"None",
",",
"max_num",
"=",
"None",
",",
"any_startswith",
"=",
"None",
",",
"any_endswith",
... | 36.85 | 0.000826 |
def _create_archive(self):
'''This will create a tar.gz compressed archive of the scrubbed directory'''
try:
self.archive_path = os.path.join(self.report_dir, "%s.tar.gz" % self.session)
self.logger.con_out('Creating SOSCleaner Archive - %s', self.archive_path)
t = ta... | [
"def",
"_create_archive",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"archive_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"report_dir",
",",
"\"%s.tar.gz\"",
"%",
"self",
".",
"session",
")",
"self",
".",
"logger",
".",
"con_out"... | 52.090909 | 0.009426 |
def _get_ngrams(segment, max_order):
"""Extracts all n-grams up to a given maximum order from an input segment.
Args:
segment: text segment from which n-grams will be extracted.
max_order: maximum length in tokens of the n-grams returned by this
methods.
Returns:
The Counter containing all n... | [
"def",
"_get_ngrams",
"(",
"segment",
",",
"max_order",
")",
":",
"ngram_counts",
"=",
"collections",
".",
"Counter",
"(",
")",
"for",
"order",
"in",
"range",
"(",
"1",
",",
"max_order",
"+",
"1",
")",
":",
"for",
"i",
"in",
"range",
"(",
"0",
",",
... | 34.555556 | 0.010955 |
def suggest_localhost(func):
'''Decorator: prompt user for value of env.host_string with default to
'localhost' when env.host_string is empty.
Modification of decorator function fabric.network.needs_host
'''
from fabric.network import handle_prompt_abort, to_dict
@wraps(func)
def host_prom... | [
"def",
"suggest_localhost",
"(",
"func",
")",
":",
"from",
"fabric",
".",
"network",
"import",
"handle_prompt_abort",
",",
"to_dict",
"@",
"wraps",
"(",
"func",
")",
"def",
"host_prompting_wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"whi... | 38.090909 | 0.001164 |
def bindkw(fun, **kwbind):
"""
kwarg 바인딩된 함수 return.
ex)
def fun(opt1, opt2):
print opt1, opt2
f = bind(fun, opt1=2, opt2=3)
f()
:param function fun:
:param kwbind:
:return: function
"""
@functools.wraps(fun)
def wrapped(*args, **kwargs):
kws = kwbind.co... | [
"def",
"bindkw",
"(",
"fun",
",",
"*",
"*",
"kwbind",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"fun",
")",
"def",
"wrapped",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"kws",
"=",
"kwbind",
".",
"copy",
"(",
")",
"kws",
".",
"... | 18.285714 | 0.002475 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.