text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def exit(self):
"""Use carefully to cause the Minecraft service to exit (and hopefully restart).
Likely to throw communication errors so wrap in exception handler.
"""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.connect((self.server2, self.port2))
self._... | [
"def",
"exit",
"(",
"self",
")",
":",
"sock",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_STREAM",
")",
"sock",
".",
"connect",
"(",
"(",
"self",
".",
"server2",
",",
"self",
".",
"port2",
")",
")",
"self"... | 40.923077 | 17.615385 |
def get_tree(ident_hash, baked=False):
"""Return a tree structure of the Collection"""
id, version = get_id_n_version(ident_hash)
stmt = _get_sql('get-tree.sql')
args = dict(id=id, version=version, baked=baked)
with db_connect() as db_conn:
with db_conn.cursor() as cursor:
curs... | [
"def",
"get_tree",
"(",
"ident_hash",
",",
"baked",
"=",
"False",
")",
":",
"id",
",",
"version",
"=",
"get_id_n_version",
"(",
"ident_hash",
")",
"stmt",
"=",
"_get_sql",
"(",
"'get-tree.sql'",
")",
"args",
"=",
"dict",
"(",
"id",
"=",
"id",
",",
"ver... | 29.555556 | 13.611111 |
def get_path(self, path, query=None):
"""Make a GET request, optionally including a query, to a relative path.
The path of the request includes a path on top of the base URL
assigned to the endpoint.
Parameters
----------
path : str
The path to request, rela... | [
"def",
"get_path",
"(",
"self",
",",
"path",
",",
"query",
"=",
"None",
")",
":",
"return",
"self",
".",
"get",
"(",
"self",
".",
"url_path",
"(",
"path",
")",
",",
"query",
")"
] | 27.291667 | 19.75 |
def _computeforceArray(self,dr_dx, dtheta_dx, dphi_dx, R, z, phi):
"""
NAME:
_computeforceArray
PURPOSE:
evaluate the forces in the x direction for a given array of coordinates
INPUT:
dr_dx - the derivative of r with respect to the chosen variable x
... | [
"def",
"_computeforceArray",
"(",
"self",
",",
"dr_dx",
",",
"dtheta_dx",
",",
"dphi_dx",
",",
"R",
",",
"z",
",",
"phi",
")",
":",
"R",
"=",
"nu",
".",
"array",
"(",
"R",
",",
"dtype",
"=",
"float",
")",
"z",
"=",
"nu",
".",
"array",
"(",
"z",... | 41.487179 | 20.538462 |
def get_license_assignment_manager(service_instance):
'''
Returns the license assignment manager.
service_instance
The Service Instance Object from which to obrain the license manager.
'''
log.debug('Retrieving license assignment manager')
try:
lic_assignment_manager = \
... | [
"def",
"get_license_assignment_manager",
"(",
"service_instance",
")",
":",
"log",
".",
"debug",
"(",
"'Retrieving license assignment manager'",
")",
"try",
":",
"lic_assignment_manager",
"=",
"service_instance",
".",
"content",
".",
"licenseManager",
".",
"licenseAssignm... | 37.555556 | 17.185185 |
def datatable_df(self):
""" returns the dataframe representation of the symbol's final data """
data = self._all_datatable_data()
adf = pd.DataFrame(data)
adf.columns = self.dt_all_cols
return self._finish_df(adf, 'ALL') | [
"def",
"datatable_df",
"(",
"self",
")",
":",
"data",
"=",
"self",
".",
"_all_datatable_data",
"(",
")",
"adf",
"=",
"pd",
".",
"DataFrame",
"(",
"data",
")",
"adf",
".",
"columns",
"=",
"self",
".",
"dt_all_cols",
"return",
"self",
".",
"_finish_df",
... | 43.333333 | 4.666667 |
def com_google_fonts_check_metadata_subsets_order(family_metadata):
"""METADATA.pb subsets should be alphabetically ordered."""
expected = list(sorted(family_metadata.subsets))
if list(family_metadata.subsets) != expected:
yield FAIL, ("METADATA.pb subsets are not sorted "
"in alphabetical o... | [
"def",
"com_google_fonts_check_metadata_subsets_order",
"(",
"family_metadata",
")",
":",
"expected",
"=",
"list",
"(",
"sorted",
"(",
"family_metadata",
".",
"subsets",
")",
")",
"if",
"list",
"(",
"family_metadata",
".",
"subsets",
")",
"!=",
"expected",
":",
... | 51.272727 | 22.636364 |
def terrain_data_send(self, lat, lon, grid_spacing, gridbit, data, force_mavlink1=False):
'''
Terrain data sent from GCS. The lat/lon and grid_spacing must be the
same as a lat/lon from a TERRAIN_REQUEST
lat : Latitude of SW corner o... | [
"def",
"terrain_data_send",
"(",
"self",
",",
"lat",
",",
"lon",
",",
"grid_spacing",
",",
"gridbit",
",",
"data",
",",
"force_mavlink1",
"=",
"False",
")",
":",
"return",
"self",
".",
"send",
"(",
"self",
".",
"terrain_data_encode",
"(",
"lat",
",",
"lo... | 65.846154 | 44.615385 |
def register(self, username, password):
"""Register a new user.
Parameters
----------
username: str
The username.
password: str
The password.
Returns
-------
bool
True if the new user is successfully registered, False ... | [
"def",
"register",
"(",
"self",
",",
"username",
",",
"password",
")",
":",
"result",
"=",
"{",
"pytwis_constants",
".",
"ERROR_KEY",
":",
"None",
"}",
"# Check the username.",
"if",
"not",
"Pytwis",
".",
"_check_username",
"(",
"username",
")",
":",
"result... | 39.642857 | 24.02381 |
def InjectionStatistics(campaign=0, clobber=False, model='nPLD', plot=True,
show=True, **kwargs):
'''
Computes and plots the statistics for injection/recovery tests.
:param int campaign: The campaign number. Default 0
:param str model: The :py:obj:`everest` model name
:param... | [
"def",
"InjectionStatistics",
"(",
"campaign",
"=",
"0",
",",
"clobber",
"=",
"False",
",",
"model",
"=",
"'nPLD'",
",",
"plot",
"=",
"True",
",",
"show",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"# Compute the statistics",
"stars",
"=",
"GetK2Cam... | 44.347594 | 22.283422 |
def _init_content_type_params(self):
""" Return the Content-Type request header parameters
Convert all of the semi-colon separated parameters into
a dict of key/vals. If for some stupid reason duplicate
& conflicting params are present then the last one
wins.
If a parti... | [
"def",
"_init_content_type_params",
"(",
"self",
")",
":",
"ret",
"=",
"{",
"}",
"if",
"self",
".",
"content_type",
":",
"params",
"=",
"self",
".",
"content_type",
".",
"split",
"(",
"';'",
")",
"[",
"1",
":",
"]",
"for",
"param",
"in",
"params",
":... | 29.689655 | 20.586207 |
def attributes(attrs):
"""Returns an attribute list, constructed from the
dictionary attrs.
"""
attrs = attrs or {}
ident = attrs.get("id", "")
classes = attrs.get("classes", [])
keyvals = [[x, attrs[x]] for x in attrs if (x != "classes" and x != "id")]
return [ident, classes, keyvals] | [
"def",
"attributes",
"(",
"attrs",
")",
":",
"attrs",
"=",
"attrs",
"or",
"{",
"}",
"ident",
"=",
"attrs",
".",
"get",
"(",
"\"id\"",
",",
"\"\"",
")",
"classes",
"=",
"attrs",
".",
"get",
"(",
"\"classes\"",
",",
"[",
"]",
")",
"keyvals",
"=",
"... | 34.444444 | 11.888889 |
def get(self, id_or_url, default=None):
"""Fetch and return the spreadsheet with the given id or url.
Args:
id_or_url (str): unique alphanumeric id or URL of the spreadsheet
Returns:
New SpreadSheet instance or given default if none is found
Raises:
V... | [
"def",
"get",
"(",
"self",
",",
"id_or_url",
",",
"default",
"=",
"None",
")",
":",
"if",
"'/'",
"in",
"id_or_url",
":",
"id",
"=",
"urls",
".",
"SheetUrl",
".",
"from_string",
"(",
"id_or_url",
")",
".",
"id",
"else",
":",
"id",
"=",
"id_or_url",
... | 33.333333 | 20.111111 |
def changed(self, node=None, allowcache=False):
"""
Returns if the node is up-to-date with respect to the BuildInfo
stored last time it was built.
For File nodes this is basically a wrapper around Node.changed(),
but we allow the return value to get cached after the reference
... | [
"def",
"changed",
"(",
"self",
",",
"node",
"=",
"None",
",",
"allowcache",
"=",
"False",
")",
":",
"if",
"node",
"is",
"None",
":",
"try",
":",
"return",
"self",
".",
"_memo",
"[",
"'changed'",
"]",
"except",
"KeyError",
":",
"pass",
"has_changed",
... | 33.142857 | 18.571429 |
def get_cgi_parameter_str_or_none(form: cgi.FieldStorage,
key: str) -> Optional[str]:
"""
Extracts a string parameter from a CGI form, or ``None`` if the key doesn't
exist or the string is zero-length.
"""
s = get_cgi_parameter_str(form, key)
if s is None or len... | [
"def",
"get_cgi_parameter_str_or_none",
"(",
"form",
":",
"cgi",
".",
"FieldStorage",
",",
"key",
":",
"str",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"s",
"=",
"get_cgi_parameter_str",
"(",
"form",
",",
"key",
")",
"if",
"s",
"is",
"None",
"or",
"... | 35.3 | 13.5 |
def valid_identifiers(self):
"""Get a list of all valid identifiers for the current context.
Returns:
list(str): A list of all of the valid identifiers for this context
"""
funcs = list(utils.find_all(self.contexts[-1])) + list(self.builtins)
return funcs | [
"def",
"valid_identifiers",
"(",
"self",
")",
":",
"funcs",
"=",
"list",
"(",
"utils",
".",
"find_all",
"(",
"self",
".",
"contexts",
"[",
"-",
"1",
"]",
")",
")",
"+",
"list",
"(",
"self",
".",
"builtins",
")",
"return",
"funcs"
] | 33.444444 | 23.444444 |
async def _bind_key_to_queue(self, routing_key: AnyStr, queue_name: AnyStr) -> None:
"""
Bind to queue with specified routing key.
:param routing_key: Routing key to bind with.
:param queue_name: Name of the queue
:return: Does not return anything
"""
logger.info... | [
"async",
"def",
"_bind_key_to_queue",
"(",
"self",
",",
"routing_key",
":",
"AnyStr",
",",
"queue_name",
":",
"AnyStr",
")",
"->",
"None",
":",
"logger",
".",
"info",
"(",
"\"Binding key='%s'\"",
",",
"routing_key",
")",
"result",
"=",
"await",
"self",
".",
... | 33.6875 | 14.8125 |
def _CheckStatusAnalysisProcess(self, pid):
"""Checks the status of an analysis process.
Args:
pid (int): process ID (PID) of a registered analysis process.
Raises:
KeyError: if the process is not registered with the engine.
"""
# TODO: Refactor this method, simplify and separate conce... | [
"def",
"_CheckStatusAnalysisProcess",
"(",
"self",
",",
"pid",
")",
":",
"# TODO: Refactor this method, simplify and separate concerns (monitoring",
"# vs management).",
"self",
".",
"_RaiseIfNotRegistered",
"(",
"pid",
")",
"if",
"pid",
"in",
"self",
".",
"_completed_analy... | 34.61039 | 21.792208 |
def extract_input(pipe_def=None, pipe_generator=None):
"""Extract inputs required by a pipe"""
if pipe_def:
pyinput = gen_input(pipe_def)
elif pipe_generator:
pyinput = pipe_generator(Context(describe_input=True))
else:
raise Exception('Must supply at least one kwarg!')
retu... | [
"def",
"extract_input",
"(",
"pipe_def",
"=",
"None",
",",
"pipe_generator",
"=",
"None",
")",
":",
"if",
"pipe_def",
":",
"pyinput",
"=",
"gen_input",
"(",
"pipe_def",
")",
"elif",
"pipe_generator",
":",
"pyinput",
"=",
"pipe_generator",
"(",
"Context",
"("... | 33.5 | 17.6 |
def _set_seed(self):
""" Set random seed for numpy and tensorflow packages """
if self.flags['SEED'] is not None:
tf.set_random_seed(self.flags['SEED'])
np.random.seed(self.flags['SEED']) | [
"def",
"_set_seed",
"(",
"self",
")",
":",
"if",
"self",
".",
"flags",
"[",
"'SEED'",
"]",
"is",
"not",
"None",
":",
"tf",
".",
"set_random_seed",
"(",
"self",
".",
"flags",
"[",
"'SEED'",
"]",
")",
"np",
".",
"random",
".",
"seed",
"(",
"self",
... | 44.6 | 7.6 |
def _xread(self, streams, timeout=0, count=None, latest_ids=None):
"""Wraps up common functionality between ``xread()``
and ``xread_group()``
You should probably be using ``xread()`` or ``xread_group()`` directly.
"""
if latest_ids is None:
latest_ids = ['$'] * len(s... | [
"def",
"_xread",
"(",
"self",
",",
"streams",
",",
"timeout",
"=",
"0",
",",
"count",
"=",
"None",
",",
"latest_ids",
"=",
"None",
")",
":",
"if",
"latest_ids",
"is",
"None",
":",
"latest_ids",
"=",
"[",
"'$'",
"]",
"*",
"len",
"(",
"streams",
")",... | 38.695652 | 17.782609 |
def fit(self, X, y, random_state=np.random):
"""Create constraints from labels and learn the LSML model.
Parameters
----------
X : (n x d) matrix
Input data, where each row corresponds to a single instance.
y : (n) array-like
Data labels.
random_state : numpy.random.RandomStat... | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"y",
",",
"random_state",
"=",
"np",
".",
"random",
")",
":",
"if",
"self",
".",
"num_labeled",
"!=",
"'deprecated'",
":",
"warnings",
".",
"warn",
"(",
"'\"num_labeled\" parameter is not used.'",
"' It has been deprec... | 37.724138 | 18.62069 |
def retrieve_loadbalancer_stats(self, loadbalancer, **_params):
"""Retrieves stats for a certain load balancer."""
return self.get(self.lbaas_loadbalancer_path_stats % (loadbalancer),
params=_params) | [
"def",
"retrieve_loadbalancer_stats",
"(",
"self",
",",
"loadbalancer",
",",
"*",
"*",
"_params",
")",
":",
"return",
"self",
".",
"get",
"(",
"self",
".",
"lbaas_loadbalancer_path_stats",
"%",
"(",
"loadbalancer",
")",
",",
"params",
"=",
"_params",
")"
] | 59 | 15 |
def infer_issubclass(callnode, context=None):
"""Infer issubclass() calls
:param nodes.Call callnode: an `issubclass` call
:param InferenceContext: the context for the inference
:rtype nodes.Const: Boolean Const value of the `issubclass` call
:raises UseInferenceDefault: If the node cannot be infer... | [
"def",
"infer_issubclass",
"(",
"callnode",
",",
"context",
"=",
"None",
")",
":",
"call",
"=",
"arguments",
".",
"CallSite",
".",
"from_call",
"(",
"callnode",
")",
"if",
"call",
".",
"keyword_arguments",
":",
"# issubclass doesn't support keyword arguments",
"ra... | 40 | 17.534884 |
def _query_postgres(self):
"""
Queries Postgres and returns a cursor to the results.
"""
postgres = PostgresHook(postgres_conn_id=self.postgres_conn_id)
conn = postgres.get_conn()
cursor = conn.cursor()
cursor.execute(self.sql, self.parameters)
return curs... | [
"def",
"_query_postgres",
"(",
"self",
")",
":",
"postgres",
"=",
"PostgresHook",
"(",
"postgres_conn_id",
"=",
"self",
".",
"postgres_conn_id",
")",
"conn",
"=",
"postgres",
".",
"get_conn",
"(",
")",
"cursor",
"=",
"conn",
".",
"cursor",
"(",
")",
"curso... | 34.888889 | 12.222222 |
def install(packages, options=None, fatal=False):
"""Install one or more packages."""
cmd = ['yum', '--assumeyes']
if options is not None:
cmd.extend(options)
cmd.append('install')
if isinstance(packages, six.string_types):
cmd.append(packages)
else:
cmd.extend(packages)
... | [
"def",
"install",
"(",
"packages",
",",
"options",
"=",
"None",
",",
"fatal",
"=",
"False",
")",
":",
"cmd",
"=",
"[",
"'yum'",
",",
"'--assumeyes'",
"]",
"if",
"options",
"is",
"not",
"None",
":",
"cmd",
".",
"extend",
"(",
"options",
")",
"cmd",
... | 35.076923 | 12.384615 |
def list_all_zip_codes_geo_zones(cls, **kwargs):
"""List ZipCodesGeoZones
Return a list of ZipCodesGeoZones
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.list_all_zip_codes_geo_zones(async=T... | [
"def",
"list_all_zip_codes_geo_zones",
"(",
"cls",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
"return",
"cls",
".",
"_list_all_zip_codes_geo_zones_with_htt... | 39.130435 | 15.695652 |
def __validate_path_parameters(self, field, path_parameters):
"""Verifies that all path parameters correspond to an existing subfield.
Args:
field: An instance of a subclass of messages.Field. Should be the root
level property name in each path parameter in path_parameters. For
exampl... | [
"def",
"__validate_path_parameters",
"(",
"self",
",",
"field",
",",
"path_parameters",
")",
":",
"for",
"param",
"in",
"path_parameters",
":",
"segment_list",
"=",
"param",
".",
"split",
"(",
"'.'",
")",
"if",
"segment_list",
"[",
"0",
"]",
"!=",
"field",
... | 45.947368 | 22.947368 |
def __extend_token_object(self, token_object,
is_denormalize=True,
func_denormalizer=denormalize_text):
# type: (TokenizedResult,bool,Callable[[str],str])->Tuple
"""This method creates dict object from token object.
"""
assert i... | [
"def",
"__extend_token_object",
"(",
"self",
",",
"token_object",
",",
"is_denormalize",
"=",
"True",
",",
"func_denormalizer",
"=",
"denormalize_text",
")",
":",
"# type: (TokenizedResult,bool,Callable[[str],str])->Tuple",
"assert",
"isinstance",
"(",
"token_object",
",",
... | 44.40625 | 21.09375 |
def _construct_number_token(self, d: Dict, nlp) -> List[Dict]:
"""
Construct a shape token
Args:
d: Dict
nlp
Returns: List[Dict]
"""
result = []
if not d["numbers"]:
this_token = {attrs.LIKE_NUM: True}
result.appen... | [
"def",
"_construct_number_token",
"(",
"self",
",",
"d",
":",
"Dict",
",",
"nlp",
")",
"->",
"List",
"[",
"Dict",
"]",
":",
"result",
"=",
"[",
"]",
"if",
"not",
"d",
"[",
"\"numbers\"",
"]",
":",
"this_token",
"=",
"{",
"attrs",
".",
"LIKE_NUM",
"... | 30.1875 | 16.625 |
def new_address(self, sender=None, nonce=None):
"""Create a fresh 160bit address"""
if sender is not None and nonce is None:
nonce = self.get_nonce(sender)
new_address = self.calculate_new_address(sender, nonce)
if sender is None and new_address in self:
return s... | [
"def",
"new_address",
"(",
"self",
",",
"sender",
"=",
"None",
",",
"nonce",
"=",
"None",
")",
":",
"if",
"sender",
"is",
"not",
"None",
"and",
"nonce",
"is",
"None",
":",
"nonce",
"=",
"self",
".",
"get_nonce",
"(",
"sender",
")",
"new_address",
"="... | 41 | 12.666667 |
def route(bp, *args, **kwargs):
"""Journey route decorator
Enables simple serialization, deserialization and validation of Flask routes with the help of Marshmallow.
:param bp: :class:`flask.Blueprint` object
:param args: args to pass along to `Blueprint.route`
:param kwargs:
- :strict_sla... | [
"def",
"route",
"(",
"bp",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'strict_slashes'",
"]",
"=",
"kwargs",
".",
"pop",
"(",
"'strict_slashes'",
",",
"False",
")",
"body",
"=",
"_validate_schema",
"(",
"kwargs",
".",
"pop",
... | 38.12069 | 21.724138 |
def getUpperDetectionLimit(self):
"""Returns the Upper Detection Limit for this service as a floatable
"""
udl = self.getField('UpperDetectionLimit').get(self)
try:
return float(udl)
except ValueError:
return 0 | [
"def",
"getUpperDetectionLimit",
"(",
"self",
")",
":",
"udl",
"=",
"self",
".",
"getField",
"(",
"'UpperDetectionLimit'",
")",
".",
"get",
"(",
"self",
")",
"try",
":",
"return",
"float",
"(",
"udl",
")",
"except",
"ValueError",
":",
"return",
"0"
] | 33.375 | 12.5 |
def lock(self):
'''
Try to get locked the file
- the function will wait until the file is unlocked if 'wait' was defined as locktype
- the funciton will raise AlreadyLocked exception if 'lock' was defined as locktype
'''
# Open file
self.__fd = open(self.__lockfi... | [
"def",
"lock",
"(",
"self",
")",
":",
"# Open file",
"self",
".",
"__fd",
"=",
"open",
"(",
"self",
".",
"__lockfile",
",",
"\"w\"",
")",
"# Get it locked",
"if",
"self",
".",
"__locktype",
"==",
"\"wait\"",
":",
"# Try to get it locked until ready",
"fcntl",
... | 38.4 | 23.2 |
def argument_kind(args):
# type: (List[Argument]) -> Optional[str]
"""Return the kind of an argument, based on one or more descriptions of the argument.
Return None if every item does not have the same kind.
"""
kinds = set(arg.kind for arg in args)
if len(kinds) != 1:
return None
r... | [
"def",
"argument_kind",
"(",
"args",
")",
":",
"# type: (List[Argument]) -> Optional[str]",
"kinds",
"=",
"set",
"(",
"arg",
".",
"kind",
"for",
"arg",
"in",
"args",
")",
"if",
"len",
"(",
"kinds",
")",
"!=",
"1",
":",
"return",
"None",
"return",
"kinds",
... | 32.8 | 13.6 |
def order_executed(self, orderDict):
''' call back for executed order '''
for orderId, order in orderDict.items():
if order.security in self.__trakers.keys():
self.__trakers[order.security].orderExecuted(orderId) | [
"def",
"order_executed",
"(",
"self",
",",
"orderDict",
")",
":",
"for",
"orderId",
",",
"order",
"in",
"orderDict",
".",
"items",
"(",
")",
":",
"if",
"order",
".",
"security",
"in",
"self",
".",
"__trakers",
".",
"keys",
"(",
")",
":",
"self",
".",... | 50.4 | 12 |
def _process_changes(self, newRev, branch):
"""
Read changes since last change.
- Read list of commit hashes.
- Extract details from each commit.
- Add changes to database.
"""
# initial run, don't parse all history
if not self.lastRev:
retur... | [
"def",
"_process_changes",
"(",
"self",
",",
"newRev",
",",
"branch",
")",
":",
"# initial run, don't parse all history",
"if",
"not",
"self",
".",
"lastRev",
":",
"return",
"rebuild",
"=",
"False",
"if",
"newRev",
"in",
"self",
".",
"lastRev",
".",
"values",
... | 38.78481 | 18.025316 |
def initialize_approx_dist(self, phi, start_diffuse, gaussian_latents):
""" Initializes the appoximate distibution for the model
Parameters
----------
phi : np.ndarray
Latent variables
start_diffuse: boolean
Whether to start from diffuse values or not
... | [
"def",
"initialize_approx_dist",
"(",
"self",
",",
"phi",
",",
"start_diffuse",
",",
"gaussian_latents",
")",
":",
"# Starting values for approximate distribution",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"self",
".",
"latent_variables",
".",
"z_list",
")",
")... | 37.365854 | 24.146341 |
def get_entities(seq, suffix=False):
"""Gets entities from sequence.
Args:
seq (list): sequence of labels.
Returns:
list: list of (chunk_type, chunk_start, chunk_end).
Example:
>>> from seqeval.metrics.sequence_labeling import get_entities
>>> seq = ['B-PER', 'I-PER', ... | [
"def",
"get_entities",
"(",
"seq",
",",
"suffix",
"=",
"False",
")",
":",
"# for nested list",
"if",
"any",
"(",
"isinstance",
"(",
"s",
",",
"list",
")",
"for",
"s",
"in",
"seq",
")",
":",
"seq",
"=",
"[",
"item",
"for",
"sublist",
"in",
"seq",
"f... | 27.461538 | 19.102564 |
def parse(self, stream, template, predefines=True, orig_filename=None, keep_successful=False, printf=True):
"""Parse the data stream using the template (e.g. parse the 010 template
and interpret the template using the stream as the data source).
:stream: The input data stream
:template:... | [
"def",
"parse",
"(",
"self",
",",
"stream",
",",
"template",
",",
"predefines",
"=",
"True",
",",
"orig_filename",
"=",
"None",
",",
"keep_successful",
"=",
"False",
",",
"printf",
"=",
"True",
")",
":",
"self",
".",
"_dlog",
"(",
"\"parsing\"",
")",
"... | 43.478261 | 23.782609 |
def assertFileSizeAlmostEqual(
self, filename, size, places=None, msg=None, delta=None):
'''Fail if ``filename`` does not have the given ``size`` as
determined by their difference rounded to the given number of
decimal ``places`` (default 7) and comparing to zero, or if
their... | [
"def",
"assertFileSizeAlmostEqual",
"(",
"self",
",",
"filename",
",",
"size",
",",
"places",
"=",
"None",
",",
"msg",
"=",
"None",
",",
"delta",
"=",
"None",
")",
":",
"fsize",
"=",
"self",
".",
"_get_file_size",
"(",
"filename",
")",
"self",
".",
"as... | 35.615385 | 21.538462 |
def add_deploy(state, deploy_func, *args, **kwargs):
'''
Prepare & add an deploy to pyinfra.state by executing it on all hosts.
Args:
state (``pyinfra.api.State`` obj): the deploy state to add the operation
deploy_func (function): the operation function from one of the modules,
ie `... | [
"def",
"add_deploy",
"(",
"state",
",",
"deploy_func",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"frameinfo",
"=",
"get_caller_frameinfo",
"(",
")",
"kwargs",
"[",
"'frameinfo'",
"]",
"=",
"frameinfo",
"for",
"host",
"in",
"state",
".",
"inven... | 33.8125 | 24.5625 |
def get_notifications(self, login=None, **kwargs):
"""Get the current notifications of a user.
:return: JSON
"""
_login = kwargs.get(
'login',
login or self._login
)
_notif_url = NOTIF_URL.format(login=_login)
return self._request_api(url... | [
"def",
"get_notifications",
"(",
"self",
",",
"login",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"_login",
"=",
"kwargs",
".",
"get",
"(",
"'login'",
",",
"login",
"or",
"self",
".",
"_login",
")",
"_notif_url",
"=",
"NOTIF_URL",
".",
"format",
... | 27.333333 | 17.166667 |
def walk_directories_info(self, relativePath="", fullPath=False, recursive=False):
"""
Walk the repository relative path and yield tuple of two items where
first item is directory relative/full path and second item is directory
info. If directory file info is not found on disk, second it... | [
"def",
"walk_directories_info",
"(",
"self",
",",
"relativePath",
"=",
"\"\"",
",",
"fullPath",
"=",
"False",
",",
"recursive",
"=",
"False",
")",
":",
"assert",
"isinstance",
"(",
"fullPath",
",",
"bool",
")",
",",
"\"fullPath must be boolean\"",
"assert",
"i... | 52 | 26.076923 |
def F(self, x):
"""
Classic NFW function in terms of arctanh and arctan
:param x: r/Rs
:return:
"""
if isinstance(x, np.ndarray):
nfwvals = np.ones_like(x)
inds1 = np.where(x < 1)
inds2 = np.where(x > 1)
nfwvals[inds1] = (1 ... | [
"def",
"F",
"(",
"self",
",",
"x",
")",
":",
"if",
"isinstance",
"(",
"x",
",",
"np",
".",
"ndarray",
")",
":",
"nfwvals",
"=",
"np",
".",
"ones_like",
"(",
"x",
")",
"inds1",
"=",
"np",
".",
"where",
"(",
"x",
"<",
"1",
")",
"inds2",
"=",
... | 37.238095 | 20.285714 |
def raise_with_traceback(exc, traceback=Ellipsis):
"""
Raise exception with existing traceback.
If traceback is not passed, uses sys.exc_info() to get traceback.
"""
if traceback == Ellipsis:
_, _, traceback = sys.exc_info()
raise exc.with_traceback(traceback) | [
"def",
"raise_with_traceback",
"(",
"exc",
",",
"traceback",
"=",
"Ellipsis",
")",
":",
"if",
"traceback",
"==",
"Ellipsis",
":",
"_",
",",
"_",
",",
"traceback",
"=",
"sys",
".",
"exc_info",
"(",
")",
"raise",
"exc",
".",
"with_traceback",
"(",
"traceba... | 35.625 | 6.875 |
def run_step(context):
"""Parse input json file and substitute {tokens} from context.
Loads json into memory to do parsing, so be aware of big files.
Args:
context: pypyr.context.Context. Mandatory.
- fileFormatJson
- in. mandatory.
str, pa... | [
"def",
"run_step",
"(",
"context",
")",
":",
"logger",
".",
"debug",
"(",
"\"started\"",
")",
"deprecated",
"(",
"context",
")",
"ObjectRewriterStep",
"(",
"__name__",
",",
"'fileFormatJson'",
",",
"context",
")",
".",
"run_step",
"(",
"JsonRepresenter",
"(",
... | 38.744186 | 24.209302 |
def _thumbnail_resize(self, image, thumb_size, crop=None, bg=None):
"""Performs the actual image cropping operation with PIL."""
if crop == 'fit':
img = ImageOps.fit(image, thumb_size, Image.ANTIALIAS)
else:
img = image.copy()
img.thumbnail(thumb_size, Image.... | [
"def",
"_thumbnail_resize",
"(",
"self",
",",
"image",
",",
"thumb_size",
",",
"crop",
"=",
"None",
",",
"bg",
"=",
"None",
")",
":",
"if",
"crop",
"==",
"'fit'",
":",
"img",
"=",
"ImageOps",
".",
"fit",
"(",
"image",
",",
"thumb_size",
",",
"Image",... | 30.538462 | 22.230769 |
def lyricsmode(song):
"""
Returns the lyrics found in lyricsmode.com for the specified mp3 file or an
empty string if not found.
"""
translate = {
URLESCAPE: '',
' ': '_'
}
artist = song.artist.lower()
artist = normalize(artist, translate)
title = song.title.lower()
... | [
"def",
"lyricsmode",
"(",
"song",
")",
":",
"translate",
"=",
"{",
"URLESCAPE",
":",
"''",
",",
"' '",
":",
"'_'",
"}",
"artist",
"=",
"song",
".",
"artist",
".",
"lower",
"(",
")",
"artist",
"=",
"normalize",
"(",
"artist",
",",
"translate",
")",
... | 25.548387 | 16.580645 |
def _is_memory_usage_qualified(self):
""" return a boolean if we need a qualified .info display """
def f(l):
return 'mixed' in l or 'string' in l or 'unicode' in l
return any(f(l) for l in self._inferred_type_levels) | [
"def",
"_is_memory_usage_qualified",
"(",
"self",
")",
":",
"def",
"f",
"(",
"l",
")",
":",
"return",
"'mixed'",
"in",
"l",
"or",
"'string'",
"in",
"l",
"or",
"'unicode'",
"in",
"l",
"return",
"any",
"(",
"f",
"(",
"l",
")",
"for",
"l",
"in",
"self... | 49.8 | 14.4 |
def process_header(self, headers):
"""Ignore the incomming header and replace it with the destination header"""
return [c.name for c in self.source.dest_table.columns][1:] | [
"def",
"process_header",
"(",
"self",
",",
"headers",
")",
":",
"return",
"[",
"c",
".",
"name",
"for",
"c",
"in",
"self",
".",
"source",
".",
"dest_table",
".",
"columns",
"]",
"[",
"1",
":",
"]"
] | 46.25 | 18.25 |
def _try_disconnect(self, ref):
"""
Called by the weak reference when its target dies.
In other words, we can assert that self.weak_subscribers is not
None at this time.
"""
with self.lock:
weak = [s[0] for s in self.weak_subscribers]
try:
... | [
"def",
"_try_disconnect",
"(",
"self",
",",
"ref",
")",
":",
"with",
"self",
".",
"lock",
":",
"weak",
"=",
"[",
"s",
"[",
"0",
"]",
"for",
"s",
"in",
"self",
".",
"weak_subscribers",
"]",
"try",
":",
"index",
"=",
"weak",
".",
"index",
"(",
"ref... | 35.4 | 15 |
def _create_paths(self, basedir, name=None):
"""Create datadir and subdir paths."""
if name:
datapath = os.path.join(basedir, name)
else:
datapath = basedir
dbpath = os.path.join(datapath, 'db')
if not os.path.exists(dbpath):
os.makedirs(dbpat... | [
"def",
"_create_paths",
"(",
"self",
",",
"basedir",
",",
"name",
"=",
"None",
")",
":",
"if",
"name",
":",
"datapath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"basedir",
",",
"name",
")",
"else",
":",
"datapath",
"=",
"basedir",
"dbpath",
"=",
"... | 30 | 14.857143 |
def _set_v3host(self, v, load=False):
"""
Setter method for v3host, mapped from YANG variable /snmp_server/v3host (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_v3host is considered as a private
method. Backends looking to populate this variable should
do... | [
"def",
"_set_v3host",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"base",
... | 125.045455 | 60.090909 |
def create_vars_from_data(self, dataset, split="train"):
"""
Create vars given a dataset and set test values.
Useful when dataset is already defined.
"""
from deepy.core.neural_var import NeuralVariable
vars = []
if split == "valid":
data_split = datas... | [
"def",
"create_vars_from_data",
"(",
"self",
",",
"dataset",
",",
"split",
"=",
"\"train\"",
")",
":",
"from",
"deepy",
".",
"core",
".",
"neural_var",
"import",
"NeuralVariable",
"vars",
"=",
"[",
"]",
"if",
"split",
"==",
"\"valid\"",
":",
"data_split",
... | 40.777778 | 14.5 |
def f_add_derived_parameter(self, *args, **kwargs):
"""Adds a derived parameter under the current group.
Similar to
:func:`~pypet.naturalnaming.ParameterGroup.f_add_parameter`
Naming prefixes are added as in
:func:`~pypet.naturalnaming.DerivedParameterGroup.f_add_derived_parame... | [
"def",
"f_add_derived_parameter",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_nn_interface",
".",
"_add_generic",
"(",
"self",
",",
"type_name",
"=",
"DERIVED_PARAMETER",
",",
"group_type_name",
"=",
"DERIVED_PARA... | 44.153846 | 26.846154 |
def get_current_version(repo_path):
"""
Given a repo will return the version string, according to semantic
versioning, counting as non-backwards compatible commit any one with a
message header that matches (case insensitive)::
sem-ver: .*break.*
And as features any commit with a header mat... | [
"def",
"get_current_version",
"(",
"repo_path",
")",
":",
"repo",
"=",
"dulwich",
".",
"repo",
".",
"Repo",
"(",
"repo_path",
")",
"tags",
"=",
"get_tags",
"(",
"repo",
")",
"maj_version",
"=",
"0",
"feat_version",
"=",
"0",
"fix_version",
"=",
"0",
"for... | 29.088235 | 18.794118 |
def create_python_bundle(self, dirn, arch):
"""
Create a packaged python bundle in the target directory, by
copying all the modules and standard library to the right
place.
"""
# Todo: find a better way to find the build libs folder
modules_build_dir = join(
... | [
"def",
"create_python_bundle",
"(",
"self",
",",
"dirn",
",",
"arch",
")",
":",
"# Todo: find a better way to find the build libs folder",
"modules_build_dir",
"=",
"join",
"(",
"self",
".",
"get_build_dir",
"(",
"arch",
".",
"arch",
")",
",",
"'android-build'",
","... | 46.314286 | 18.771429 |
def canonic_signame(name_num):
"""Return a signal name for a signal name or signal
number. Return None is name_num is an int but not a valid signal
number and False if name_num is a not number. If name_num is a
signal name or signal number, the canonic if name is returned."""
signum = lookup_signum... | [
"def",
"canonic_signame",
"(",
"name_num",
")",
":",
"signum",
"=",
"lookup_signum",
"(",
"name_num",
")",
"if",
"signum",
"is",
"None",
":",
"# Maybe signame is a number?",
"try",
":",
"num",
"=",
"int",
"(",
"name_num",
")",
"signame",
"=",
"lookup_signame",... | 34.6 | 15 |
def parse_host_port(host_port):
"""
Takes a string argument specifying host or host:port.
Returns a (hostname, port) or (ip_address, port) tuple. If no port is given,
the second (port) element of the returned tuple will be None.
host:port argument, for example, is accepted in the forms of:
-... | [
"def",
"parse_host_port",
"(",
"host_port",
")",
":",
"host",
",",
"port",
"=",
"None",
",",
"None",
"# default",
"_s_",
"=",
"host_port",
"[",
":",
"]",
"if",
"_s_",
"[",
"0",
"]",
"==",
"\"[\"",
":",
"if",
"\"]\"",
"in",
"host_port",
":",
"host",
... | 33.8 | 20.12 |
def user_deleted_from_site_event(event):
""" Remove deleted user from all the workspaces where he
is a member """
userid = event.principal
catalog = api.portal.get_tool('portal_catalog')
query = {'object_provides': WORKSPACE_INTERFACE}
query['workspace_members'] = userid
workspaces = [
... | [
"def",
"user_deleted_from_site_event",
"(",
"event",
")",
":",
"userid",
"=",
"event",
".",
"principal",
"catalog",
"=",
"api",
".",
"portal",
".",
"get_tool",
"(",
"'portal_catalog'",
")",
"query",
"=",
"{",
"'object_provides'",
":",
"WORKSPACE_INTERFACE",
"}",... | 32.866667 | 13.466667 |
def _fetch(self, statement, commit, max_attempts=5):
"""
Execute a SQL query and return a result.
Recursively disconnect and reconnect to the database
if an error occurs.
"""
if self._auto_reconnect:
attempts = 0
while attempts < max_attempts:
... | [
"def",
"_fetch",
"(",
"self",
",",
"statement",
",",
"commit",
",",
"max_attempts",
"=",
"5",
")",
":",
"if",
"self",
".",
"_auto_reconnect",
":",
"attempts",
"=",
"0",
"while",
"attempts",
"<",
"max_attempts",
":",
"try",
":",
"# Execute statement",
"self... | 35.486486 | 12.783784 |
def get_policy(self):
"""
Returns an instance of :attr:`~policy_class`.
:return: An instance of the current policy class.
:rtype: dockermap.map.policy.base.BasePolicy
"""
if not self._policy:
self._policy = self.policy_class(self._maps, self._clients)
... | [
"def",
"get_policy",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_policy",
":",
"self",
".",
"_policy",
"=",
"self",
".",
"policy_class",
"(",
"self",
".",
"_maps",
",",
"self",
".",
"_clients",
")",
"return",
"self",
".",
"_policy"
] | 33.1 | 15.7 |
def _packet_manager(self):
""" Watch packet list for timeouts. """
while True:
if self._packets:
with self._packet_lock:
now = time.time()
self._packets[:] = \
[packet for packet in self._packets
... | [
"def",
"_packet_manager",
"(",
"self",
")",
":",
"while",
"True",
":",
"if",
"self",
".",
"_packets",
":",
"with",
"self",
".",
"_packet_lock",
":",
"now",
"=",
"time",
".",
"time",
"(",
")",
"self",
".",
"_packets",
"[",
":",
"]",
"=",
"[",
"packe... | 32.461538 | 14.384615 |
def register(coordinator):
"""Registers this module as a worker with the given coordinator."""
timer_queue = Queue.Queue()
coordinator.register(TimerItem, timer_queue)
coordinator.worker_threads.append(
TimerThread(timer_queue, coordinator.input_queue)) | [
"def",
"register",
"(",
"coordinator",
")",
":",
"timer_queue",
"=",
"Queue",
".",
"Queue",
"(",
")",
"coordinator",
".",
"register",
"(",
"TimerItem",
",",
"timer_queue",
")",
"coordinator",
".",
"worker_threads",
".",
"append",
"(",
"TimerThread",
"(",
"ti... | 45.333333 | 8.5 |
def update_environment(self, environment):
"""
Updates this channel's remote shell environment.
.. note::
This operation is additive - i.e. the current environment is not
reset before the given environment variables are set.
.. warning::
Servers may ... | [
"def",
"update_environment",
"(",
"self",
",",
"environment",
")",
":",
"for",
"name",
",",
"value",
"in",
"environment",
".",
"items",
"(",
")",
":",
"try",
":",
"self",
".",
"set_environment_variable",
"(",
"name",
",",
"value",
")",
"except",
"SSHExcept... | 40.125 | 21.041667 |
def compose(self, *args, **kwargs):
"""
Generate a file from the current template and given arguments.
Warning:
Make certain to check the formatted editor for correctness!
Args:
args: Positional arguments to update the template
kwargs: Keywo... | [
"def",
"compose",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"linebreak",
"=",
"kwargs",
".",
"pop",
"(",
"\"linebreak\"",
",",
"\"\\n\"",
")",
"# Update the internally stored args/kwargs from which formatting arguments come\r",
"if",
"len",
... | 42.28 | 18.04 |
def fill_subparser(subparser):
"""Sets up a subparser to download audio of YouTube videos.
Adds the compulsory `--youtube-id` flag.
Parameters
----------
subparser : :class:`argparse.ArgumentParser`
Subparser handling the `youtube_audio` command.
"""
subparser.add_argument(
... | [
"def",
"fill_subparser",
"(",
"subparser",
")",
":",
"subparser",
".",
"add_argument",
"(",
"'--youtube-id'",
",",
"type",
"=",
"str",
",",
"required",
"=",
"True",
",",
"help",
"=",
"(",
"\"The YouTube ID of the video from which to extract audio, \"",
"\"usually an 1... | 29.117647 | 19.235294 |
def predict(oracle, context, ab=None, verbose=False):
"""Single symbolic prediction given a context, an oracle and an alphabet.
:param oracle: a learned vmo object from a symbolic sequence.
:param context: the context precedes the predicted symbol
:param ab: alphabet
:param verbose: to show if the ... | [
"def",
"predict",
"(",
"oracle",
",",
"context",
",",
"ab",
"=",
"None",
",",
"verbose",
"=",
"False",
")",
":",
"if",
"verbose",
":",
"print",
"(",
"\"original context: \"",
",",
"context",
")",
"if",
"ab",
"is",
"None",
":",
"ab",
"=",
"oracle",
".... | 35.214286 | 18.309524 |
def add_process(self, command=None, vsplit=False, start_directory=None):
"""
Add a new process to the current window. (vsplit/hsplit).
"""
assert command is None or isinstance(command, six.text_type)
assert start_directory is None or isinstance(start_directory, six.text_type)
... | [
"def",
"add_process",
"(",
"self",
",",
"command",
"=",
"None",
",",
"vsplit",
"=",
"False",
",",
"start_directory",
"=",
"None",
")",
":",
"assert",
"command",
"is",
"None",
"or",
"isinstance",
"(",
"command",
",",
"six",
".",
"text_type",
")",
"assert"... | 41.153846 | 23.307692 |
def _proxy(self):
"""
Generate an instance context for the instance, the context is capable of
performing various actions. All instance actions are proxied to the context
:returns: ParticipantContext for this ParticipantInstance
:rtype: twilio.rest.video.v1.room.room_participan... | [
"def",
"_proxy",
"(",
"self",
")",
":",
"if",
"self",
".",
"_context",
"is",
"None",
":",
"self",
".",
"_context",
"=",
"ParticipantContext",
"(",
"self",
".",
"_version",
",",
"room_sid",
"=",
"self",
".",
"_solution",
"[",
"'room_sid'",
"]",
",",
"si... | 39.333333 | 19.066667 |
def set_dependencies(ctx, archive_name, dependency=None):
'''
Set the dependencies of an archive
'''
_generate_api(ctx)
kwargs = _parse_dependencies(dependency)
var = ctx.obj.api.get_archive(archive_name)
var.set_dependencies(dependencies=kwargs) | [
"def",
"set_dependencies",
"(",
"ctx",
",",
"archive_name",
",",
"dependency",
"=",
"None",
")",
":",
"_generate_api",
"(",
"ctx",
")",
"kwargs",
"=",
"_parse_dependencies",
"(",
"dependency",
")",
"var",
"=",
"ctx",
".",
"obj",
".",
"api",
".",
"get_archi... | 24.272727 | 21.727273 |
def scale_to_vol(self, vol):
"""Scale ball to encompass a target volume."""
f = (vol / self.vol_ball) ** (1.0 / self.n) # linear factor
self.expand *= f
self.radius *= f
self.vol_ball = vol | [
"def",
"scale_to_vol",
"(",
"self",
",",
"vol",
")",
":",
"f",
"=",
"(",
"vol",
"/",
"self",
".",
"vol_ball",
")",
"**",
"(",
"1.0",
"/",
"self",
".",
"n",
")",
"# linear factor",
"self",
".",
"expand",
"*=",
"f",
"self",
".",
"radius",
"*=",
"f"... | 32.142857 | 17.857143 |
def uniqueName(self, name):
"""UIParser.uniqueName(string) -> string
Create a unique name from a string.
>>> p = UIParser(QtCore, QtGui, QtWidgets)
>>> p.uniqueName("foo")
'foo'
>>> p.uniqueName("foo")
'foo1'
"""
try:
suffix = self.nam... | [
"def",
"uniqueName",
"(",
"self",
",",
"name",
")",
":",
"try",
":",
"suffix",
"=",
"self",
".",
"name_suffixes",
"[",
"name",
"]",
"except",
"KeyError",
":",
"self",
".",
"name_suffixes",
"[",
"name",
"]",
"=",
"0",
"return",
"name",
"suffix",
"+=",
... | 25.5 | 15.35 |
def sunionstore(self, destkey, key, *keys):
"""Add multiple sets and store the resulting set in a key."""
return self.execute(b'SUNIONSTORE', destkey, key, *keys) | [
"def",
"sunionstore",
"(",
"self",
",",
"destkey",
",",
"key",
",",
"*",
"keys",
")",
":",
"return",
"self",
".",
"execute",
"(",
"b'SUNIONSTORE'",
",",
"destkey",
",",
"key",
",",
"*",
"keys",
")"
] | 58.666667 | 9 |
def _make_defaults_hazard_table():
"""Build headers for a table related to hazard classes.
:return: A table with headers.
:rtype: m.Table
"""
table = m.Table(style_class='table table-condensed table-striped')
row = m.Row()
# first row is for colour - we dont use a header here as some tables... | [
"def",
"_make_defaults_hazard_table",
"(",
")",
":",
"table",
"=",
"m",
".",
"Table",
"(",
"style_class",
"=",
"'table table-condensed table-striped'",
")",
"row",
"=",
"m",
".",
"Row",
"(",
")",
"# first row is for colour - we dont use a header here as some tables",
"#... | 38.55 | 14.75 |
def get_base_url(config, args):
"""
Get the API base url. Try Terraform state first, then
:py:class:`~.AWSInfo`.
:param config: configuration
:type config: :py:class:`~.Config`
:param args: command line arguments
:type args: :py:class:`argparse.Namespace`
:return: API base URL
:rtyp... | [
"def",
"get_base_url",
"(",
"config",
",",
"args",
")",
":",
"try",
":",
"logger",
".",
"debug",
"(",
"'Trying to get Terraform base_url output'",
")",
"runner",
"=",
"TerraformRunner",
"(",
"config",
",",
"args",
".",
"tf_path",
")",
"outputs",
"=",
"runner",... | 34.555556 | 13.518519 |
def _ParseAttribute(self, file_object):
"""Parses a CUPS IPP attribute from a file-like object.
Args:
file_object (dfvfs.FileIO): file-like object.
Returns:
tuple[str, object]: attribute name and value.
Raises:
ParseError: if the attribute cannot be parsed.
"""
file_offset =... | [
"def",
"_ParseAttribute",
"(",
"self",
",",
"file_object",
")",
":",
"file_offset",
"=",
"file_object",
".",
"tell",
"(",
")",
"attribute_map",
"=",
"self",
".",
"_GetDataTypeMap",
"(",
"'cups_ipp_attribute'",
")",
"try",
":",
"attribute",
",",
"_",
"=",
"se... | 34.340426 | 23.744681 |
def iter_events(self, number=-1, etag=None):
"""Iterate over public events.
:param int number: (optional), number of events to return. Default: -1
returns all available events
:param str etag: (optional), ETag from a previous request to the same
endpoint
:returns... | [
"def",
"iter_events",
"(",
"self",
",",
"number",
"=",
"-",
"1",
",",
"etag",
"=",
"None",
")",
":",
"url",
"=",
"self",
".",
"_build_url",
"(",
"'events'",
")",
"return",
"self",
".",
"_iter",
"(",
"int",
"(",
"number",
")",
",",
"url",
",",
"Ev... | 43.545455 | 17.454545 |
def ExtractCredentialsFromPathSpec(self, path_spec):
"""Extracts credentials from a path specification.
Args:
path_spec (PathSpec): path specification to extract credentials from.
"""
credentials = manager.CredentialsManager.GetCredentials(path_spec)
for identifier in credentials.CREDENTIALS:... | [
"def",
"ExtractCredentialsFromPathSpec",
"(",
"self",
",",
"path_spec",
")",
":",
"credentials",
"=",
"manager",
".",
"CredentialsManager",
".",
"GetCredentials",
"(",
"path_spec",
")",
"for",
"identifier",
"in",
"credentials",
".",
"CREDENTIALS",
":",
"value",
"=... | 35.076923 | 19.923077 |
def reformat_date(date, new_fmt='%Y-%m-%d'):
""" Returns reformated date.
:param date:
The string date with this format %m/%d/%Y
:type date:
String
:param new_fmt:
date format string. Default is '%Y-%m-%d'
:type date:
String
:returns:
int
:example:
... | [
"def",
"reformat_date",
"(",
"date",
",",
"new_fmt",
"=",
"'%Y-%m-%d'",
")",
":",
"try",
":",
"if",
"isinstance",
"(",
"date",
",",
"datetime",
")",
":",
"return",
"date",
".",
"strftime",
"(",
"new_fmt",
")",
"else",
":",
"fmt",
"=",
"'%m/%d/%Y'",
"re... | 22.740741 | 20.037037 |
def as_obj(func):
""" A decorator used to return a JSON response with a dict
representation of the model instance. It expects the decorated function
to return a Model instance. It then converts the instance to dicts
and serializes it into a json response
Examples:
>>> ... | [
"def",
"as_obj",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"response",
"=",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"render_json_obj_with_... | 34.833333 | 17.555556 |
def number_of_bytes_to_modify(buf_len, fuzz_factor):
"""Calculate number of bytes to modify.
:param buf_len: len of data buffer to fuzz.
:param fuzz_factor: degree of fuzzing.
:return: number of bytes to change.
"""
return random.randrange(math.ceil((float(buf_len) / fuzz_factor))) + 1 | [
"def",
"number_of_bytes_to_modify",
"(",
"buf_len",
",",
"fuzz_factor",
")",
":",
"return",
"random",
".",
"randrange",
"(",
"math",
".",
"ceil",
"(",
"(",
"float",
"(",
"buf_len",
")",
"/",
"fuzz_factor",
")",
")",
")",
"+",
"1"
] | 38 | 12 |
def __merge_nearest_successors(self, node):
"""!
@brief Find nearest sucessors and merge them.
@param[in] node (non_leaf_node): Node whose two nearest successors should be merged.
@return (bool): True if merging has been successfully performed, otherwise False.
... | [
"def",
"__merge_nearest_successors",
"(",
"self",
",",
"node",
")",
":",
"merging_result",
"=",
"False",
"if",
"(",
"node",
".",
"successors",
"[",
"0",
"]",
".",
"type",
"==",
"cfnode_type",
".",
"CFNODE_NONLEAF",
")",
":",
"[",
"nearest_child_node1",
",",
... | 42.6 | 27.04 |
def foreach_model(self, fn):
"""Apply the given function to each model replica in each worker.
Returns:
List of results from applying the function.
"""
results = ray.get([w.foreach_model.remote(fn) for w in self.workers])
out = []
for r in results:
... | [
"def",
"foreach_model",
"(",
"self",
",",
"fn",
")",
":",
"results",
"=",
"ray",
".",
"get",
"(",
"[",
"w",
".",
"foreach_model",
".",
"remote",
"(",
"fn",
")",
"for",
"w",
"in",
"self",
".",
"workers",
"]",
")",
"out",
"=",
"[",
"]",
"for",
"r... | 28.666667 | 20.333333 |
def get(img, cache_dir=CACHE_DIR, iterative=False):
"""Validate image input."""
if os.path.isfile(img):
wal_img = img
elif os.path.isdir(img):
if iterative:
wal_img = get_next_image(img)
else:
wal_img = get_random_image(img)
else:
logging.error(... | [
"def",
"get",
"(",
"img",
",",
"cache_dir",
"=",
"CACHE_DIR",
",",
"iterative",
"=",
"False",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"img",
")",
":",
"wal_img",
"=",
"img",
"elif",
"os",
".",
"path",
".",
"isdir",
"(",
"img",
")",... | 25.26087 | 21.652174 |
def copy_resource(self, container, resource, local_filename):
"""
Identical to :meth:`dockermap.client.base.DockerClientWrapper.copy_resource` with additional logging.
"""
self.push_log("Receiving tarball for resource '{0}:{1}' and storing as {2}".format(container, resource, local_filena... | [
"def",
"copy_resource",
"(",
"self",
",",
"container",
",",
"resource",
",",
"local_filename",
")",
":",
"self",
".",
"push_log",
"(",
"\"Receiving tarball for resource '{0}:{1}' and storing as {2}\"",
".",
"format",
"(",
"container",
",",
"resource",
",",
"local_file... | 68.333333 | 38 |
def save(self, *args, **kwargs):
"""
Before saving, if slide is for a publication, use publication info
for slide's title, subtitle, description.
"""
if self.publication:
publication = self.publication
if not self.title:
self.title = publi... | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"publication",
":",
"publication",
"=",
"self",
".",
"publication",
"if",
"not",
"self",
".",
"title",
":",
"self",
".",
"title",
"=",
"publication",
... | 36.027778 | 19.972222 |
def _check_multi_statement_line(self, node, line):
"""Check for lines containing multiple statements."""
# Do not warn about multiple nested context managers
# in with statements.
if isinstance(node, nodes.With):
return
# For try... except... finally..., the two nodes... | [
"def",
"_check_multi_statement_line",
"(",
"self",
",",
"node",
",",
"line",
")",
":",
"# Do not warn about multiple nested context managers",
"# in with statements.",
"if",
"isinstance",
"(",
"node",
",",
"nodes",
".",
"With",
")",
":",
"return",
"# For try... except..... | 36.884615 | 15.307692 |
def _create_model_matrices(self):
""" Creates model matrices/vectors
Returns
----------
None (changes model attributes)
"""
self.model_Y = self.data
self.model_scores = np.zeros((self.X.shape[1], self.model_Y.shape[0]+1)) | [
"def",
"_create_model_matrices",
"(",
"self",
")",
":",
"self",
".",
"model_Y",
"=",
"self",
".",
"data",
"self",
".",
"model_scores",
"=",
"np",
".",
"zeros",
"(",
"(",
"self",
".",
"X",
".",
"shape",
"[",
"1",
"]",
",",
"self",
".",
"model_Y",
".... | 27 | 18.3 |
def status(self):
"""
Check if the daemon is currently running.
Requires procfs, so it will only work on POSIX compliant OS'.
"""
# Get the pid from the pidfile
try:
pf = file(self.pidfile,'r')
pid = int(pf.read().strip())
pf.close()
except IOError:
pid = None
if not pid:
return False
... | [
"def",
"status",
"(",
"self",
")",
":",
"# Get the pid from the pidfile",
"try",
":",
"pf",
"=",
"file",
"(",
"self",
".",
"pidfile",
",",
"'r'",
")",
"pid",
"=",
"int",
"(",
"pf",
".",
"read",
"(",
")",
".",
"strip",
"(",
")",
")",
"pf",
".",
"c... | 19.5 | 20.5 |
def _record_extension(self, key, value):
"""
To structure a record extension property bean
"""
record_bean = {
'value': value,
'displayName': self._text_bean(key),
'description': self._text_bean(key),
'displayLabel': self._text_bean(key),
... | [
"def",
"_record_extension",
"(",
"self",
",",
"key",
",",
"value",
")",
":",
"record_bean",
"=",
"{",
"'value'",
":",
"value",
",",
"'displayName'",
":",
"self",
".",
"_text_bean",
"(",
"key",
")",
",",
"'description'",
":",
"self",
".",
"_text_bean",
"(... | 32.333333 | 9.666667 |
def _make_metadata_request(self, meta_id, metadata_type=None):
"""
Get the Metadata. The Session initializes with 'COMPACT-DECODED' as the format type. If that returns a DTD error
then we change to the 'STANDARD-XML' format and try again.
:param meta_id: The name of the resource, class, ... | [
"def",
"_make_metadata_request",
"(",
"self",
",",
"meta_id",
",",
"metadata_type",
"=",
"None",
")",
":",
"# If this metadata _request has already happened, returned the saved result.",
"key",
"=",
"'{0!s}:{1!s}'",
".",
"format",
"(",
"metadata_type",
",",
"meta_id",
")"... | 44.97619 | 21.97619 |
def get_vertex_string(self, i):
"""Return a string based on the atom number"""
number = self.numbers[i]
if number == 0:
return Graph.get_vertex_string(self, i)
else:
# pad with zeros to make sure that string sort is identical to number sort
return "%03... | [
"def",
"get_vertex_string",
"(",
"self",
",",
"i",
")",
":",
"number",
"=",
"self",
".",
"numbers",
"[",
"i",
"]",
"if",
"number",
"==",
"0",
":",
"return",
"Graph",
".",
"get_vertex_string",
"(",
"self",
",",
"i",
")",
"else",
":",
"# pad with zeros t... | 40.5 | 15.5 |
def _set_LED(self, status):
"""
_set_LED: boolean -> None
Sets the status of the remote LED
"""
# DIO pin 1 (LED), active low
self.hw.remote_at(
dest_addr=self.remote_addr,
command='D1',
parameter='\x04' if status else '\x05') | [
"def",
"_set_LED",
"(",
"self",
",",
"status",
")",
":",
"# DIO pin 1 (LED), active low",
"self",
".",
"hw",
".",
"remote_at",
"(",
"dest_addr",
"=",
"self",
".",
"remote_addr",
",",
"command",
"=",
"'D1'",
",",
"parameter",
"=",
"'\\x04'",
"if",
"status",
... | 27.363636 | 9.545455 |
def union(self, other, recursive=True, overwrite=False):
"""
Recursively compute union of data. For dictionaries, items
for specific keys will be combined into a list, depending on the
status of the overwrite= parameter. For lists, items will be appended
and reduced to unique ite... | [
"def",
"union",
"(",
"self",
",",
"other",
",",
"recursive",
"=",
"True",
",",
"overwrite",
"=",
"False",
")",
":",
"if",
"not",
"isinstance",
"(",
"other",
",",
"composite",
")",
":",
"raise",
"AssertionError",
"(",
"'Cannot union composite and {} types'",
... | 42.2 | 15.52 |
def started(name=None,
user=None,
group=None,
chroot=None,
caps=None,
no_caps=False,
pidfile=None,
enable_core=False,
fd_limit=None,
verbose=False,
debug=False,
trace=False,
yy... | [
"def",
"started",
"(",
"name",
"=",
"None",
",",
"user",
"=",
"None",
",",
"group",
"=",
"None",
",",
"chroot",
"=",
"None",
",",
"caps",
"=",
"None",
",",
"no_caps",
"=",
"False",
",",
"pidfile",
"=",
"None",
",",
"enable_core",
"=",
"False",
",",... | 37.5 | 17.6 |
def where(self, cond, value, other=None, subset=None, **kwargs):
"""
Apply a function elementwise, updating the HTML
representation with a style which is selected in
accordance with the return value of a function.
.. versionadded:: 0.21.0
Parameters
----------
... | [
"def",
"where",
"(",
"self",
",",
"cond",
",",
"value",
",",
"other",
"=",
"None",
",",
"subset",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"other",
"is",
"None",
":",
"other",
"=",
"''",
"return",
"self",
".",
"applymap",
"(",
"lambd... | 28.361111 | 20.861111 |
def _sector_erase_program_double_buffer(self, progress_cb=_stub_progress):
"""! @brief Double-buffered program by performing sector erases."""
actual_sector_erase_count = 0
actual_sector_erase_weight = 0
progress = 0
progress_cb(0.0)
# Fill in same flag for all pages. T... | [
"def",
"_sector_erase_program_double_buffer",
"(",
"self",
",",
"progress_cb",
"=",
"_stub_progress",
")",
":",
"actual_sector_erase_count",
"=",
"0",
"actual_sector_erase_weight",
"=",
"0",
"progress",
"=",
"0",
"progress_cb",
"(",
"0.0",
")",
"# Fill in same flag for ... | 38.736842 | 21.881579 |
def get_account_user(self, account_id, user_id, **kwargs): # noqa: E501
"""Details of the user. # noqa: E501
An endpoint for retrieving details of the user. **Example usage:** `curl https://api.us-east-1.mbedcloud.com/v3/accounts/{accountID}/users/{userID} -H 'Authorization: Bearer API_KEY'` # noq... | [
"def",
"get_account_user",
"(",
"self",
",",
"account_id",
",",
"user_id",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'asynchronous'",
")",
":",
"return",
... | 54.5 | 29.409091 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.