text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def all_inspections(obj):
"""
Generator to iterate all current Jishaku inspections.
"""
for name, callback in INSPECTIONS:
result = callback(obj)
if result:
yield name, result | [
"def",
"all_inspections",
"(",
"obj",
")",
":",
"for",
"name",
",",
"callback",
"in",
"INSPECTIONS",
":",
"result",
"=",
"callback",
"(",
"obj",
")",
"if",
"result",
":",
"yield",
"name",
",",
"result"
] | 23.555556 | 12.888889 |
def contians_attribute(self, attribute):
"""
Returns how many cards in the deck have the specified attribute.
This method requires a library to be stored in the deck instance and
will return `None` if there is no library.
"""
if self.library is None:
return 0... | [
"def",
"contians_attribute",
"(",
"self",
",",
"attribute",
")",
":",
"if",
"self",
".",
"library",
"is",
"None",
":",
"return",
"0",
"load",
"=",
"self",
".",
"library",
".",
"load_card",
"matches",
"=",
"0",
"for",
"code",
"in",
"self",
".",
"cards",... | 30.764706 | 15.588235 |
def duration(self):
"""
Returns the current value of the counter and then multiplies it by
:attr:`factor`
:rtype: float
"""
d = self.for_attempt(self.cur_attempt)
self.cur_attempt += 1
return d | [
"def",
"duration",
"(",
"self",
")",
":",
"d",
"=",
"self",
".",
"for_attempt",
"(",
"self",
".",
"cur_attempt",
")",
"self",
".",
"cur_attempt",
"+=",
"1",
"return",
"d"
] | 24.9 | 17.3 |
def domain(self, expparams):
"""
Returns a list of ``Domain``s, one for each input expparam.
:param numpy.ndarray expparams: Array of experimental parameters. This
array must be of dtype agreeing with the ``expparams_dtype``
property, or, in the case where ``n_outcomes_... | [
"def",
"domain",
"(",
"self",
",",
"expparams",
")",
":",
"return",
"[",
"IntegerDomain",
"(",
"min",
"=",
"0",
",",
"max",
"=",
"n_o",
"-",
"1",
")",
"for",
"n_o",
"in",
"self",
".",
"n_outcomes",
"(",
"expparams",
")",
"]"
] | 42.666667 | 23.833333 |
def __experimental_range(start, stop, var, cond, loc={}):
'''Utility function made to reproduce range() with unit integer step
but with the added possibility of specifying a condition
on the looping variable (e.g. var % 2 == 0)
'''
locals().update(loc)
if start < stop:
for __ in ... | [
"def",
"__experimental_range",
"(",
"start",
",",
"stop",
",",
"var",
",",
"cond",
",",
"loc",
"=",
"{",
"}",
")",
":",
"locals",
"(",
")",
".",
"update",
"(",
"loc",
")",
"if",
"start",
"<",
"stop",
":",
"for",
"__",
"in",
"range",
"(",
"start",... | 36.5 | 15.875 |
def get_transactions(cls, address):
"""Gets the ID of all transactions related to an address.
:param address: The address in question.
:type address: ``str``
:raises ConnectionError: If all API services fail.
:rtype: ``list`` of ``str``
"""
for api_call in cls.G... | [
"def",
"get_transactions",
"(",
"cls",
",",
"address",
")",
":",
"for",
"api_call",
"in",
"cls",
".",
"GET_TRANSACTIONS_MAIN",
":",
"try",
":",
"return",
"api_call",
"(",
"address",
")",
"except",
"cls",
".",
"IGNORED_ERRORS",
":",
"pass",
"raise",
"Connecti... | 31.5 | 15 |
def getattr(self, c, attr, default=None, match_only=None):
"""
Get the attribute of a component.
Args:
c (component): The component to look up.
attr (str): The attribute to get.
default (str): What to return in the event of no match.
match_only (list ... | [
"def",
"getattr",
"(",
"self",
",",
"c",
",",
"attr",
",",
"default",
"=",
"None",
",",
"match_only",
"=",
"None",
")",
":",
"matching_decor",
"=",
"self",
".",
"get_decor",
"(",
"c",
",",
"match_only",
"=",
"match_only",
")",
"try",
":",
"return",
"... | 34.75 | 19.95 |
def html_to_text(html, base_url='', bodywidth=CONFIG_DEFAULT):
"""
Convert a HTML mesasge to plain text.
"""
def _patched_handle_charref(c):
self = h
charref = self.charref(c)
if self.code or self.pre:
charref = cgi.escape(charref)
self.o(charref, 1)
def ... | [
"def",
"html_to_text",
"(",
"html",
",",
"base_url",
"=",
"''",
",",
"bodywidth",
"=",
"CONFIG_DEFAULT",
")",
":",
"def",
"_patched_handle_charref",
"(",
"c",
")",
":",
"self",
"=",
"h",
"charref",
"=",
"self",
".",
"charref",
"(",
"c",
")",
"if",
"sel... | 35 | 14.818182 |
def strip_tx_flags(self, idx):
"""strip(1 byte) tx_flags
:idx: int
:return: int
idx
:return: int
"""
idx = Radiotap.align(idx, 2)
tx_flags, = struct.unpack_from('<B', self._rtap, idx)
return idx + 1, tx_flags | [
"def",
"strip_tx_flags",
"(",
"self",
",",
"idx",
")",
":",
"idx",
"=",
"Radiotap",
".",
"align",
"(",
"idx",
",",
"2",
")",
"tx_flags",
",",
"=",
"struct",
".",
"unpack_from",
"(",
"'<B'",
",",
"self",
".",
"_rtap",
",",
"idx",
")",
"return",
"idx... | 27.5 | 13.1 |
def cfg(self):
"""Load the application configuration.
This method loads configuration from python module.
"""
config = LStruct(self.defaults)
module = config['CONFIG'] = os.environ.get(
CONFIGURATION_ENVIRON_VARIABLE, config['CONFIG'])
if module:
... | [
"def",
"cfg",
"(",
"self",
")",
":",
"config",
"=",
"LStruct",
"(",
"self",
".",
"defaults",
")",
"module",
"=",
"config",
"[",
"'CONFIG'",
"]",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"CONFIGURATION_ENVIRON_VARIABLE",
",",
"config",
"[",
"'CONFIG'",... | 32.903226 | 20.354839 |
def _set_factory_context(factory_class, bundle_context):
# type: (type, Optional[BundleContext]) -> Optional[FactoryContext]
"""
Transforms the context data dictionary into its FactoryContext object form.
:param factory_class: A manipulated class
:param bundle_context: The class bundle context
... | [
"def",
"_set_factory_context",
"(",
"factory_class",
",",
"bundle_context",
")",
":",
"# type: (type, Optional[BundleContext]) -> Optional[FactoryContext]",
"try",
":",
"# Try to get the factory context (built using decorators)",
"context",
"=",
"getattr",
"(",
"factory_class",
","... | 35.73913 | 19.565217 |
def create_subscription(self, subscription):
"""CreateSubscription.
Create a subscription.
:param :class:`<Subscription> <azure.devops.v5_0.service_hooks.models.Subscription>` subscription: Subscription to be created.
:rtype: :class:`<Subscription> <azure.devops.v5_0.service_hooks.models... | [
"def",
"create_subscription",
"(",
"self",
",",
"subscription",
")",
":",
"content",
"=",
"self",
".",
"_serialize",
".",
"body",
"(",
"subscription",
",",
"'Subscription'",
")",
"response",
"=",
"self",
".",
"_send",
"(",
"http_method",
"=",
"'POST'",
",",
... | 57.333333 | 22.25 |
def instruction_INC_register(self, opcode, register):
"""
Adds to the register. The carry bit is not affected, thus allowing this
instruction to be used as a loop counter in multiple-precision
computations. When operating on unsigned values, only the BEQ and BNE
branches can be e... | [
"def",
"instruction_INC_register",
"(",
"self",
",",
"opcode",
",",
"register",
")",
":",
"a",
"=",
"register",
".",
"value",
"r",
"=",
"self",
".",
"INC",
"(",
"a",
")",
"r",
"=",
"register",
".",
"set",
"(",
"r",
")"
] | 40.066667 | 21.8 |
def get(value):
"Query to get the value."
if not isinstance(value, Token):
raise TypeError('value must be a token')
if not hasattr(value, 'identifier'):
raise TypeError('value must support an identifier')
if not value.identifier:
value = value.__class__(**value.__dict__)
... | [
"def",
"get",
"(",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"Token",
")",
":",
"raise",
"TypeError",
"(",
"'value must be a token'",
")",
"if",
"not",
"hasattr",
"(",
"value",
",",
"'identifier'",
")",
":",
"raise",
"TypeError",
"... | 24.444444 | 19.555556 |
def receives(self, *args, **kwargs):
"""Pop the next `Request` and assert it matches.
Returns None if the server is stopped.
Pass a `Request` or request pattern to specify what client request to
expect. See the tutorial for examples. Pass ``timeout`` as a keyword
argument to ov... | [
"def",
"receives",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"timeout",
"=",
"kwargs",
".",
"pop",
"(",
"'timeout'",
",",
"self",
".",
"_request_timeout",
")",
"end",
"=",
"time",
".",
"time",
"(",
")",
"+",
"timeout",
"matc... | 43.961538 | 18.846154 |
def make_folium_polyline(edge, edge_color, edge_width, edge_opacity, popup_attribute=None):
"""
Turn a row from the gdf_edges GeoDataFrame into a folium PolyLine with
attributes.
Parameters
----------
edge : GeoSeries
a row from the gdf_edges GeoDataFrame
edge_color : string
... | [
"def",
"make_folium_polyline",
"(",
"edge",
",",
"edge_color",
",",
"edge_width",
",",
"edge_opacity",
",",
"popup_attribute",
"=",
"None",
")",
":",
"# check if we were able to import folium successfully",
"if",
"not",
"folium",
":",
"raise",
"ImportError",
"(",
"'Th... | 33.234043 | 23.276596 |
def callback(self, filename, lines, **kwargs):
"""Sends log lines to redis servers"""
self._logger.debug('Redis transport called')
timestamp = self.get_timestamp(**kwargs)
if kwargs.get('timestamp', False):
del kwargs['timestamp']
namespaces = self._beaver_config.g... | [
"def",
"callback",
"(",
"self",
",",
"filename",
",",
"lines",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_logger",
".",
"debug",
"(",
"'Redis transport called'",
")",
"timestamp",
"=",
"self",
".",
"get_timestamp",
"(",
"*",
"*",
"kwargs",
")",
... | 33.52381 | 19.857143 |
def getZernike(self, index):
"""getZernike
Retrieve a map representing the index-th Zernike polynomial
Args:
index (int): The index of Zernike map to be generated,
following Noll 1976 ordering.
Returns:
np.array: A map representing the index-th ... | [
"def",
"getZernike",
"(",
"self",
",",
"index",
")",
":",
"if",
"index",
"not",
"in",
"list",
"(",
"self",
".",
"_dictCache",
".",
"keys",
"(",
")",
")",
":",
"self",
".",
"_dictCache",
"[",
"index",
"]",
"=",
"self",
".",
"_polar",
"(",
"index",
... | 32.941176 | 22.352941 |
def base(self, du):
"""Return the base CLB for a given DU"""
parameter = 'base'
if parameter not in self._by:
self._by[parameter] = {}
for clb in self.upi.values():
if clb.floor == 0:
self._by[parameter][clb.du] = clb
return sel... | [
"def",
"base",
"(",
"self",
",",
"du",
")",
":",
"parameter",
"=",
"'base'",
"if",
"parameter",
"not",
"in",
"self",
".",
"_by",
":",
"self",
".",
"_by",
"[",
"parameter",
"]",
"=",
"{",
"}",
"for",
"clb",
"in",
"self",
".",
"upi",
".",
"values",... | 36.888889 | 7.111111 |
def gram_schmidt(matrix, return_opt='orthonormal'):
r"""Gram-Schmit
This method orthonormalizes the row vectors of the input matrix.
Parameters
----------
matrix : np.ndarray
Input matrix array
return_opt : str {orthonormal, orthogonal, both}
Option to return u, e or both.
... | [
"def",
"gram_schmidt",
"(",
"matrix",
",",
"return_opt",
"=",
"'orthonormal'",
")",
":",
"if",
"return_opt",
"not",
"in",
"(",
"'orthonormal'",
",",
"'orthogonal'",
",",
"'both'",
")",
":",
"raise",
"ValueError",
"(",
"'Invalid return_opt, options are: \"orthonormal... | 24.482759 | 23.206897 |
def get_code(self, code, card_id=None, check_consume=True):
"""
查询 code 信息
"""
card_data = {
'code': code
}
if card_id:
card_data['card_id'] = card_id
if not check_consume:
card_data['check_consume'] = check_consume
retu... | [
"def",
"get_code",
"(",
"self",
",",
"code",
",",
"card_id",
"=",
"None",
",",
"check_consume",
"=",
"True",
")",
":",
"card_data",
"=",
"{",
"'code'",
":",
"code",
"}",
"if",
"card_id",
":",
"card_data",
"[",
"'card_id'",
"]",
"=",
"card_id",
"if",
... | 25.733333 | 15.066667 |
def getSet(self, setID):
'''
Gets the information of one specific build using its Brickset set ID.
:param str setID: The ID of the build from Brickset.
:returns: A single Build object.
:rtype: :class:`brickfront.build.Build`
:raises brickfront.errors.InvalidSetID: If no ... | [
"def",
"getSet",
"(",
"self",
",",
"setID",
")",
":",
"params",
"=",
"{",
"'apiKey'",
":",
"self",
".",
"apiKey",
",",
"'userHash'",
":",
"self",
".",
"userHash",
",",
"'setID'",
":",
"setID",
"}",
"url",
"=",
"Client",
".",
"ENDPOINT",
".",
"format"... | 31.571429 | 19.642857 |
def _bound_waveform(wave, indep_min, indep_max):
"""Add independent variable vector bounds if they are not in vector."""
indep_min, indep_max = _validate_min_max(wave, indep_min, indep_max)
indep_vector = copy.copy(wave._indep_vector)
if (
isinstance(indep_min, float) or isinstance(indep_max, fl... | [
"def",
"_bound_waveform",
"(",
"wave",
",",
"indep_min",
",",
"indep_max",
")",
":",
"indep_min",
",",
"indep_max",
"=",
"_validate_min_max",
"(",
"wave",
",",
"indep_min",
",",
"indep_max",
")",
"indep_vector",
"=",
"copy",
".",
"copy",
"(",
"wave",
".",
... | 57.588235 | 19.294118 |
def update_flags(self, idlist, flags):
"""
A thin back compat wrapper around build_update(flags=X)
"""
return self.update_bugs(idlist, self.build_update(flags=flags)) | [
"def",
"update_flags",
"(",
"self",
",",
"idlist",
",",
"flags",
")",
":",
"return",
"self",
".",
"update_bugs",
"(",
"idlist",
",",
"self",
".",
"build_update",
"(",
"flags",
"=",
"flags",
")",
")"
] | 38.8 | 11.2 |
def message_convert_rx(message_rx):
"""convert the message from the CANAL type to pythoncan type"""
is_extended_id = bool(message_rx.flags & IS_ID_TYPE)
is_remote_frame = bool(message_rx.flags & IS_REMOTE_FRAME)
is_error_frame = bool(message_rx.flags & IS_ERROR_FRAME)
return Message(timestamp=messa... | [
"def",
"message_convert_rx",
"(",
"message_rx",
")",
":",
"is_extended_id",
"=",
"bool",
"(",
"message_rx",
".",
"flags",
"&",
"IS_ID_TYPE",
")",
"is_remote_frame",
"=",
"bool",
"(",
"message_rx",
".",
"flags",
"&",
"IS_REMOTE_FRAME",
")",
"is_error_frame",
"=",... | 48.615385 | 13.461538 |
def _connect(self):
"""
Connects the bot to the server and identifies itself.
"""
self.conn = self._create_connection()
spawn(self.conn.connect)
self.set_nick(self.nick)
self.cmd(u'USER', u'{0} 3 * {1}'.format(self.nick, self.realname)) | [
"def",
"_connect",
"(",
"self",
")",
":",
"self",
".",
"conn",
"=",
"self",
".",
"_create_connection",
"(",
")",
"spawn",
"(",
"self",
".",
"conn",
".",
"connect",
")",
"self",
".",
"set_nick",
"(",
"self",
".",
"nick",
")",
"self",
".",
"cmd",
"("... | 35.625 | 12.125 |
def commits(self, drop_collections=True):
"""
Returns a table of git log data, with "commits" as rows/observations.
:param bool drop_collections: Defaults to True. Indicates whether columns with lists/dicts/sets will be dropped.
:return: pandas.DataFrame
"""
base_df = s... | [
"def",
"commits",
"(",
"self",
",",
"drop_collections",
"=",
"True",
")",
":",
"base_df",
"=",
"self",
".",
"_data",
"if",
"drop_collections",
"is",
"True",
":",
"out_df",
"=",
"self",
".",
"_drop_collections",
"(",
"base_df",
")",
"else",
":",
"out_df",
... | 33.642857 | 20.785714 |
def compose(*validators):
"""
Implement composition of validators. For instance
>>> utf8_not_empty = compose(utf8, not_empty)
"""
def composed_validator(value):
out = value
for validator in reversed(validators):
out = validator(out)
return out
composed_valida... | [
"def",
"compose",
"(",
"*",
"validators",
")",
":",
"def",
"composed_validator",
"(",
"value",
")",
":",
"out",
"=",
"value",
"for",
"validator",
"in",
"reversed",
"(",
"validators",
")",
":",
"out",
"=",
"validator",
"(",
"out",
")",
"return",
"out",
... | 30.071429 | 12.357143 |
def get(self):
"""
Constructs a EngagementContextContext
:returns: twilio.rest.studio.v1.flow.engagement.engagement_context.EngagementContextContext
:rtype: twilio.rest.studio.v1.flow.engagement.engagement_context.EngagementContextContext
"""
return EngagementContextCont... | [
"def",
"get",
"(",
"self",
")",
":",
"return",
"EngagementContextContext",
"(",
"self",
".",
"_version",
",",
"flow_sid",
"=",
"self",
".",
"_solution",
"[",
"'flow_sid'",
"]",
",",
"engagement_sid",
"=",
"self",
".",
"_solution",
"[",
"'engagement_sid'",
"]... | 38.333333 | 21.666667 |
def foreground(color):
"""Set the foreground color."""
if color not in foreground_colors:
return
if is_win32:
last_fg = foreground_colors[color][1]
set_color_win32(last_fg | last_bg)
else:
set_color_ansi(foreground_colors[color][0]) | [
"def",
"foreground",
"(",
"color",
")",
":",
"if",
"color",
"not",
"in",
"foreground_colors",
":",
"return",
"if",
"is_win32",
":",
"last_fg",
"=",
"foreground_colors",
"[",
"color",
"]",
"[",
"1",
"]",
"set_color_win32",
"(",
"last_fg",
"|",
"last_bg",
")... | 23.6 | 16.6 |
def crc32(filename):
'''
Calculates the CRC checksum for a file.
Using CRC32 because security isn't the issue and don't need perfect noncollisions.
We just need to know if a file has changed.
On my machine, crc32 was 20 times faster than any hashlib algorithm,
including blake and md5 algorithms... | [
"def",
"crc32",
"(",
"filename",
")",
":",
"result",
"=",
"0",
"with",
"open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"fin",
":",
"while",
"True",
":",
"chunk",
"=",
"fin",
".",
"read",
"(",
"48",
")",
"if",
"len",
"(",
"chunk",
")",
"==",
"0... | 31.647059 | 19.411765 |
def on_result(self, task, result):
'''Called every result'''
if not result:
return
if 'taskid' in task and 'project' in task and 'url' in task:
logger.info('result %s:%s %s -> %.30r' % (
task['project'], task['taskid'], task['url'], result))
re... | [
"def",
"on_result",
"(",
"self",
",",
"task",
",",
"result",
")",
":",
"if",
"not",
"result",
":",
"return",
"if",
"'taskid'",
"in",
"task",
"and",
"'project'",
"in",
"task",
"and",
"'url'",
"in",
"task",
":",
"logger",
".",
"info",
"(",
"'result %s:%s... | 36.3125 | 15.3125 |
def strip_label(mapper, connection, target):
"""Strip labels at ORM level so the unique=True means something."""
if target.label is not None:
target.label = target.label.strip() | [
"def",
"strip_label",
"(",
"mapper",
",",
"connection",
",",
"target",
")",
":",
"if",
"target",
".",
"label",
"is",
"not",
"None",
":",
"target",
".",
"label",
"=",
"target",
".",
"label",
".",
"strip",
"(",
")"
] | 47.5 | 3.75 |
def _check_for_life_signs(self):
"""Check Connection for life signs.
First check if any data has been sent, if not send a heartbeat
to the remote server.
If we have not received any data what so ever within two
intervals, we need to raise an exception so that we... | [
"def",
"_check_for_life_signs",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_running",
".",
"is_set",
"(",
")",
":",
"return",
"False",
"if",
"self",
".",
"_writes_since_check",
"==",
"0",
":",
"self",
".",
"send_heartbeat_impl",
"(",
")",
"self",
... | 32.03125 | 13.90625 |
def _insert_vars(self, path: str, data: dict) -> str:
"""Inserts variables into the ESI URL path.
Args:
path: raw ESI URL path
data: data to insert into the URL
Returns:
path with variables filled
"""
data = data.copy()
while True:
... | [
"def",
"_insert_vars",
"(",
"self",
",",
"path",
":",
"str",
",",
"data",
":",
"dict",
")",
"->",
"str",
":",
"data",
"=",
"data",
".",
"copy",
"(",
")",
"while",
"True",
":",
"match",
"=",
"re",
".",
"search",
"(",
"self",
".",
"VAR_REPLACE_REGEX"... | 31.833333 | 15.277778 |
def do_dump(self, arg):
''' Output all bytes waiting in output queue. '''
if not self.arm.is_connected():
print(self.style.error('Error: ', 'Arm is not connected.'))
return
print(self.arm.dump()) | [
"def",
"do_dump",
"(",
"self",
",",
"arg",
")",
":",
"if",
"not",
"self",
".",
"arm",
".",
"is_connected",
"(",
")",
":",
"print",
"(",
"self",
".",
"style",
".",
"error",
"(",
"'Error: '",
",",
"'Arm is not connected.'",
")",
")",
"return",
"print",
... | 39.666667 | 16.333333 |
def flash_progress_callback(action, progress_string, percentage):
"""Callback that can be used with ``JLink.flash()``.
This callback generates a progress bar in the console to show the progress
of each of the steps of the flash.
Args:
action (str): the current action being invoked
progress... | [
"def",
"flash_progress_callback",
"(",
"action",
",",
"progress_string",
",",
"percentage",
")",
":",
"if",
"action",
".",
"lower",
"(",
")",
"!=",
"'compare'",
":",
"return",
"progress_bar",
"(",
"min",
"(",
"100",
",",
"percentage",
")",
",",
"100",
",",... | 30.571429 | 24.52381 |
def init(self, dict_or_str, val=None, warn=True):
"""initialize one or several options.
Arguments
---------
`dict_or_str`
a dictionary if ``val is None``, otherwise a key.
If `val` is provided `dict_or_str` must be a valid key.
`val`
... | [
"def",
"init",
"(",
"self",
",",
"dict_or_str",
",",
"val",
"=",
"None",
",",
"warn",
"=",
"True",
")",
":",
"# dic = dict_or_key if val is None else {dict_or_key:val}",
"self",
".",
"check",
"(",
"dict_or_str",
")",
"dic",
"=",
"dict_or_str",
"if",
"val",
"is... | 30.757576 | 19.363636 |
def wrap(self, wrapper):
"""
Allows the underlying socket to be wrapped, as by an SSL
connection.
:param wrapper: A callable taking, as its first argument, a
socket.socket object. The callable must
return a valid proxy for the socket.sock... | [
"def",
"wrap",
"(",
"self",
",",
"wrapper",
")",
":",
"if",
"self",
".",
"_recv_thread",
"and",
"self",
".",
"_send_thread",
":",
"# Have to suspend the send/recv threads",
"self",
".",
"_recv_lock",
".",
"acquire",
"(",
")",
"self",
".",
"_send_lock",
".",
... | 39.0625 | 18.9375 |
def parse_elem(element):
"""Parse a OSM node XML element.
Args:
element (etree.Element): XML Element to parse
Returns:
Node: Object representing parsed element
"""
ident = int(element.get('id'))
latitude = element.get('lat')
longitude = e... | [
"def",
"parse_elem",
"(",
"element",
")",
":",
"ident",
"=",
"int",
"(",
"element",
".",
"get",
"(",
"'id'",
")",
")",
"latitude",
"=",
"element",
".",
"get",
"(",
"'lat'",
")",
"longitude",
"=",
"element",
".",
"get",
"(",
"'lon'",
")",
"flags",
"... | 26.125 | 17.5625 |
def clear_cache_delete_selected(modeladmin, request, queryset):
"""
A delete action that will invalidate cache after being called.
"""
result = delete_selected(modeladmin, request, queryset)
# A result of None means that the delete happened.
if not result and hasattr(modeladmin, 'invalidate_cac... | [
"def",
"clear_cache_delete_selected",
"(",
"modeladmin",
",",
"request",
",",
"queryset",
")",
":",
"result",
"=",
"delete_selected",
"(",
"modeladmin",
",",
"request",
",",
"queryset",
")",
"# A result of None means that the delete happened.",
"if",
"not",
"result",
... | 35.363636 | 20.090909 |
def service_remove(path, service_name):
'''
Remove the definition of a docker-compose service
This does not rm the container
This wil re-write your yaml file. Comments will be lost. Indentation is set to 2 spaces
path
Path where the docker-compose file is stored on the server
service_na... | [
"def",
"service_remove",
"(",
"path",
",",
"service_name",
")",
":",
"compose_result",
",",
"err",
"=",
"__load_docker_compose",
"(",
"path",
")",
"if",
"err",
":",
"return",
"err",
"services",
"=",
"compose_result",
"[",
"'compose_content'",
"]",
"[",
"'servi... | 37.034483 | 24.413793 |
def _generate_limit_items(lower, upper):
"""Yield key, value pairs for limits dictionary.
Yield pairs of key, value where key is ``lower``, ``upper`` or ``fixed``.
A key, value pair is emitted if the bounds are not None.
"""
# Use value + 0 to convert any -0.0 to 0.0 which looks better.
if lowe... | [
"def",
"_generate_limit_items",
"(",
"lower",
",",
"upper",
")",
":",
"# Use value + 0 to convert any -0.0 to 0.0 which looks better.",
"if",
"lower",
"is",
"not",
"None",
"and",
"upper",
"is",
"not",
"None",
"and",
"lower",
"==",
"upper",
":",
"yield",
"'fixed'",
... | 38.5 | 15.571429 |
def schedules(self):
'''
Returns details of the posting schedules associated with a social media
profile.
'''
url = PATHS['GET_SCHEDULES'] % self.id
self.__schedules = self.api.get(url=url)
return self.__schedules | [
"def",
"schedules",
"(",
"self",
")",
":",
"url",
"=",
"PATHS",
"[",
"'GET_SCHEDULES'",
"]",
"%",
"self",
".",
"id",
"self",
".",
"__schedules",
"=",
"self",
".",
"api",
".",
"get",
"(",
"url",
"=",
"url",
")",
"return",
"self",
".",
"__schedules"
] | 21.636364 | 26.181818 |
def close_spider(self, _spider):
"""
Write out to file
"""
self.df['date_download'] = pd.to_datetime(
self.df['date_download'], errors='coerce', infer_datetime_format=True
)
self.df['date_modify'] = pd.to_datetime(
self.df['date_modify'], errors='c... | [
"def",
"close_spider",
"(",
"self",
",",
"_spider",
")",
":",
"self",
".",
"df",
"[",
"'date_download'",
"]",
"=",
"pd",
".",
"to_datetime",
"(",
"self",
".",
"df",
"[",
"'date_download'",
"]",
",",
"errors",
"=",
"'coerce'",
",",
"infer_datetime_format",
... | 39.733333 | 19.066667 |
def get_values(self, context_type):
"""
Get the values valid on this line.
:param context_type: "ENV" or "LABEL"
:return: values of given type valid on this line
"""
if context_type.upper() == "ENV":
return self.envs
elif context_type.upper() == "LABE... | [
"def",
"get_values",
"(",
"self",
",",
"context_type",
")",
":",
"if",
"context_type",
".",
"upper",
"(",
")",
"==",
"\"ENV\"",
":",
"return",
"self",
".",
"envs",
"elif",
"context_type",
".",
"upper",
"(",
")",
"==",
"\"LABEL\"",
":",
"return",
"self",
... | 31.272727 | 8.727273 |
def _GetStat(self):
"""Retrieves information about the file entry.
Returns:
VFSStat: a stat object.
"""
stat_object = super(FakeFileEntry, self)._GetStat()
location = getattr(self.path_spec, 'location', None)
if location:
file_data = self._file_system.GetDataByPath(location)
... | [
"def",
"_GetStat",
"(",
"self",
")",
":",
"stat_object",
"=",
"super",
"(",
"FakeFileEntry",
",",
"self",
")",
".",
"_GetStat",
"(",
")",
"location",
"=",
"getattr",
"(",
"self",
".",
"path_spec",
",",
"'location'",
",",
"None",
")",
"if",
"location",
... | 24.8125 | 20.125 |
def __parse_enabled_plugins(self):
"""
:returns: [(plugin_name, plugin_package, plugin_config), ...]
:rtype: list of tuple
"""
return [
(
plugin_name,
plugin['package'],
plugin) for plugin_name,
plugin in sel... | [
"def",
"__parse_enabled_plugins",
"(",
"self",
")",
":",
"return",
"[",
"(",
"plugin_name",
",",
"plugin",
"[",
"'package'",
"]",
",",
"plugin",
")",
"for",
"plugin_name",
",",
"plugin",
"in",
"self",
".",
"raw_config_dict",
".",
"items",
"(",
")",
"if",
... | 34.714286 | 13.571429 |
def cmd_link_ports(self):
'''show available ports'''
ports = mavutil.auto_detect_serial(preferred_list=['*FTDI*',"*Arduino_Mega_2560*", "*3D_Robotics*", "*USB_to_UART*", '*PX4*', '*FMU*'])
for p in ports:
print("%s : %s : %s" % (p.device, p.description, p.hwid)) | [
"def",
"cmd_link_ports",
"(",
"self",
")",
":",
"ports",
"=",
"mavutil",
".",
"auto_detect_serial",
"(",
"preferred_list",
"=",
"[",
"'*FTDI*'",
",",
"\"*Arduino_Mega_2560*\"",
",",
"\"*3D_Robotics*\"",
",",
"\"*USB_to_UART*\"",
",",
"'*PX4*'",
",",
"'*FMU*'",
"]"... | 58.8 | 34 |
def sync_time(self):
"""Sets the time on the pyboard to match the time on the host."""
now = time.localtime(time.time())
self.remote(set_time, (now.tm_year, now.tm_mon, now.tm_mday, now.tm_wday + 1,
now.tm_hour, now.tm_min, now.tm_sec, 0))
return now | [
"def",
"sync_time",
"(",
"self",
")",
":",
"now",
"=",
"time",
".",
"localtime",
"(",
"time",
".",
"time",
"(",
")",
")",
"self",
".",
"remote",
"(",
"set_time",
",",
"(",
"now",
".",
"tm_year",
",",
"now",
".",
"tm_mon",
",",
"now",
".",
"tm_mda... | 51.333333 | 19.833333 |
def all_subclasses(cls):
""" Recursively generate of all the subclasses of class cls. """
for subclass in cls.__subclasses__():
yield subclass
for subc in all_subclasses(subclass):
yield subc | [
"def",
"all_subclasses",
"(",
"cls",
")",
":",
"for",
"subclass",
"in",
"cls",
".",
"__subclasses__",
"(",
")",
":",
"yield",
"subclass",
"for",
"subc",
"in",
"all_subclasses",
"(",
"subclass",
")",
":",
"yield",
"subc"
] | 37 | 9.666667 |
def dragMoveEvent( self, event ):
"""
Handles the drag move event.
:param event | <QDragEvent>
"""
tags = nativestring(event.mimeData().text())
if ( event.source() == self ):
event.acceptProposedAction()
elif ( tags ):
... | [
"def",
"dragMoveEvent",
"(",
"self",
",",
"event",
")",
":",
"tags",
"=",
"nativestring",
"(",
"event",
".",
"mimeData",
"(",
")",
".",
"text",
"(",
")",
")",
"if",
"(",
"event",
".",
"source",
"(",
")",
"==",
"self",
")",
":",
"event",
".",
"acc... | 29.857143 | 10.714286 |
def remove(self, item):
"""
Transactional implementation of :func:`List.remove(item) <hazelcast.proxy.list.List.remove>`
:param item: (object), the specified item to be removed.
:return: (bool), ``true`` if the item is removed successfully, ``false`` otherwise.
"""
check... | [
"def",
"remove",
"(",
"self",
",",
"item",
")",
":",
"check_not_none",
"(",
"item",
",",
"\"item can't be none\"",
")",
"return",
"self",
".",
"_encode_invoke",
"(",
"transactional_list_remove_codec",
",",
"item",
"=",
"self",
".",
"_to_data",
"(",
"item",
")"... | 49.222222 | 28.333333 |
def run(self, stat_name, criticity, commands, repeat, mustache_dict=None):
"""Run the commands (in background).
- stats_name: plugin_name (+ header)
- criticity: criticity of the trigger
- commands: a list of command line with optional {{mustache}}
- If True, then repeat the act... | [
"def",
"run",
"(",
"self",
",",
"stat_name",
",",
"criticity",
",",
"commands",
",",
"repeat",
",",
"mustache_dict",
"=",
"None",
")",
":",
"if",
"(",
"self",
".",
"get",
"(",
"stat_name",
")",
"==",
"criticity",
"and",
"not",
"repeat",
")",
"or",
"n... | 40 | 19.439024 |
def color_key(tkey):
"""
Function which returns a colorized TKey name given its type
"""
name = tkey.GetName()
classname = tkey.GetClassName()
for class_regex, color in _COLOR_MATCHER:
if class_regex.match(classname):
return colored(name, color=color)
return name | [
"def",
"color_key",
"(",
"tkey",
")",
":",
"name",
"=",
"tkey",
".",
"GetName",
"(",
")",
"classname",
"=",
"tkey",
".",
"GetClassName",
"(",
")",
"for",
"class_regex",
",",
"color",
"in",
"_COLOR_MATCHER",
":",
"if",
"class_regex",
".",
"match",
"(",
... | 30.2 | 9.8 |
def _GetStat(self):
"""Retrieves information about the file entry.
Returns:
VFSStat: a stat object.
"""
stat_object = super(FVDEFileEntry, self)._GetStat()
stat_object.size = self._fvde_volume.get_size()
return stat_object | [
"def",
"_GetStat",
"(",
"self",
")",
":",
"stat_object",
"=",
"super",
"(",
"FVDEFileEntry",
",",
"self",
")",
".",
"_GetStat",
"(",
")",
"stat_object",
".",
"size",
"=",
"self",
".",
"_fvde_volume",
".",
"get_size",
"(",
")",
"return",
"stat_object"
] | 22.272727 | 20.363636 |
def get_status(self, json_status=None):
""" Returns status of for json """
if json_status:
self.json_status = json_status
if self.json_status not in AjaxResponseStatus.choices:
raise ValueError(
"Invalid status selected: '{}'".format(self.json_status))
... | [
"def",
"get_status",
"(",
"self",
",",
"json_status",
"=",
"None",
")",
":",
"if",
"json_status",
":",
"self",
".",
"json_status",
"=",
"json_status",
"if",
"self",
".",
"json_status",
"not",
"in",
"AjaxResponseStatus",
".",
"choices",
":",
"raise",
"ValueEr... | 34.1 | 17.5 |
def get_pip_requirement_set(self, arguments, use_remote_index, use_wheels=False):
"""
Get the unpacked requirement(s) specified by the caller by running pip.
:param arguments: The command line arguments to ``pip install ...`` (a
list of strings).
:param use_rem... | [
"def",
"get_pip_requirement_set",
"(",
"self",
",",
"arguments",
",",
"use_remote_index",
",",
"use_wheels",
"=",
"False",
")",
":",
"# Compose the pip command line arguments. This is where a lot of the",
"# core logic of pip-accel is hidden and it uses some esoteric features",
"# of... | 61.537634 | 25.666667 |
def format_timestamp(t):
"""Cast given object to a Timestamp and return a nicely formatted string"""
# Timestamp is only valid for 1678 to 2262
try:
datetime_str = str(pd.Timestamp(t))
except OutOfBoundsDatetime:
datetime_str = str(t)
try:
date_str, time_str = datetime_str.s... | [
"def",
"format_timestamp",
"(",
"t",
")",
":",
"# Timestamp is only valid for 1678 to 2262",
"try",
":",
"datetime_str",
"=",
"str",
"(",
"pd",
".",
"Timestamp",
"(",
"t",
")",
")",
"except",
"OutOfBoundsDatetime",
":",
"datetime_str",
"=",
"str",
"(",
"t",
")... | 30.888889 | 16.277778 |
def add(self, name, graph):
"""
Index and add a :ref:`networkx.Graph <networkx:graph>` to the
:class:`.GraphCollection`.
Parameters
----------
name : hashable
Unique name used to identify the `graph`.
graph : :ref:`networkx.Graph <networkx:graph>`
... | [
"def",
"add",
"(",
"self",
",",
"name",
",",
"graph",
")",
":",
"if",
"name",
"in",
"self",
":",
"raise",
"ValueError",
"(",
"\"{0} exists in this GraphCollection\"",
".",
"format",
"(",
"name",
")",
")",
"elif",
"hasattr",
"(",
"self",
",",
"unicode",
"... | 35.277778 | 19.666667 |
def _get_model_param_names(cls):
r"""Get parameter names for the model"""
# fetch model parameters
if hasattr(cls, 'set_model_params'):
# introspect the constructor arguments to find the model parameters
# to represent
args, varargs, kw, default = getargspec_n... | [
"def",
"_get_model_param_names",
"(",
"cls",
")",
":",
"# fetch model parameters",
"if",
"hasattr",
"(",
"cls",
",",
"'set_model_params'",
")",
":",
"# introspect the constructor arguments to find the model parameters",
"# to represent",
"args",
",",
"varargs",
",",
"kw",
... | 48.6 | 22.066667 |
def until_synced(self, timeout=None):
"""Return a tornado Future; resolves when all subordinate clients are synced"""
futures = [r.until_synced(timeout) for r in dict.values(self.children)]
yield tornado.gen.multi(futures, quiet_exceptions=tornado.gen.TimeoutError) | [
"def",
"until_synced",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"futures",
"=",
"[",
"r",
".",
"until_synced",
"(",
"timeout",
")",
"for",
"r",
"in",
"dict",
".",
"values",
"(",
"self",
".",
"children",
")",
"]",
"yield",
"tornado",
".",
... | 71.5 | 21.25 |
def get_batch(self, batch_id):
"""
Check to see if the requested batch_id is in the current chain. If so,
find the batch with the batch_id and return it. This is done by
finding the block and searching for the batch.
:param batch_id (string): The id of the batch requested.
... | [
"def",
"get_batch",
"(",
"self",
",",
"batch_id",
")",
":",
"payload",
"=",
"self",
".",
"_get_data_by_id",
"(",
"batch_id",
",",
"'commit_store_get_batch'",
")",
"batch",
"=",
"Batch",
"(",
")",
"batch",
".",
"ParseFromString",
"(",
"payload",
")",
"return"... | 30.941176 | 22.235294 |
def set_or_clear_breakpoint(self):
"""Set/clear breakpoint"""
if self.data:
editor = self.get_current_editor()
editor.debugger.toogle_breakpoint() | [
"def",
"set_or_clear_breakpoint",
"(",
"self",
")",
":",
"if",
"self",
".",
"data",
":",
"editor",
"=",
"self",
".",
"get_current_editor",
"(",
")",
"editor",
".",
"debugger",
".",
"toogle_breakpoint",
"(",
")"
] | 37.2 | 7.4 |
def update_repository(self, new_repository_info, repository_id, project=None):
"""UpdateRepository.
[Preview API] Updates the Git repository with either a new repo name or a new default branch.
:param :class:`<GitRepository> <azure.devops.v5_1.git.models.GitRepository>` new_repository_info: Spec... | [
"def",
"update_repository",
"(",
"self",
",",
"new_repository_info",
",",
"repository_id",
",",
"project",
"=",
"None",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"project",
"is",
"not",
"None",
":",
"route_values",
"[",
"'project'",
"]",
"=",
"self",
... | 64.75 | 29.5 |
def crypto_sign(message, sk):
"""
Signs the message ``message`` using the secret key ``sk`` and returns the
signed message.
:param message: bytes
:param sk: bytes
:rtype: bytes
"""
signed = ffi.new("unsigned char[]", len(message) + crypto_sign_BYTES)
signed_len = ffi.new("unsigned l... | [
"def",
"crypto_sign",
"(",
"message",
",",
"sk",
")",
":",
"signed",
"=",
"ffi",
".",
"new",
"(",
"\"unsigned char[]\"",
",",
"len",
"(",
"message",
")",
"+",
"crypto_sign_BYTES",
")",
"signed_len",
"=",
"ffi",
".",
"new",
"(",
"\"unsigned long long *\"",
... | 29.611111 | 19.611111 |
def h_boiling_Huang_Sheer(rhol, rhog, mul, kl, Hvap, sigma, Cpl, q, Tsat,
angle=35.):
r'''Calculates the two-phase boiling heat transfer coefficient of a
liquid and gas flowing inside a plate and frame heat exchanger, as
developed in [1]_ and again in the thesis [2]_. Depends on ... | [
"def",
"h_boiling_Huang_Sheer",
"(",
"rhol",
",",
"rhog",
",",
"mul",
",",
"kl",
",",
"Hvap",
",",
"sigma",
",",
"Cpl",
",",
"q",
",",
"Tsat",
",",
"angle",
"=",
"35.",
")",
":",
"do",
"=",
"0.0146",
"*",
"angle",
"*",
"(",
"2.",
"*",
"sigma",
... | 43.711538 | 26.673077 |
def handle_has_members(self, _, __, tokens: ParseResults) -> ParseResults:
"""Handle list relations like ``p(X) hasMembers list(p(Y), p(Z), ...)``."""
return self._handle_list_helper(tokens, HAS_MEMBER) | [
"def",
"handle_has_members",
"(",
"self",
",",
"_",
",",
"__",
",",
"tokens",
":",
"ParseResults",
")",
"->",
"ParseResults",
":",
"return",
"self",
".",
"_handle_list_helper",
"(",
"tokens",
",",
"HAS_MEMBER",
")"
] | 72 | 17.666667 |
def urljoin(base, url, allow_fragments=True):
"""Join a base URL and a possibly relative URL to form an absolute
interpretation of the latter."""
if not base:
return url
if not url:
return base
bscheme, bnetloc, bpath, bparams, bquery, bfragment = \
urlparse(base, '', all... | [
"def",
"urljoin",
"(",
"base",
",",
"url",
",",
"allow_fragments",
"=",
"True",
")",
":",
"if",
"not",
"base",
":",
"return",
"url",
"if",
"not",
"url",
":",
"return",
"base",
"bscheme",
",",
"bnetloc",
",",
"bpath",
",",
"bparams",
",",
"bquery",
",... | 34.333333 | 14.72549 |
def is_valid_combination(row):
"""
This is a filtering function. Filtering functions should return True
if combination is valid and False otherwise.
Test row that is passed here can be incomplete.
To prevent search for unnecessary items filtering function
is executed with found subset of data t... | [
"def",
"is_valid_combination",
"(",
"row",
")",
":",
"n",
"=",
"len",
"(",
"row",
")",
"if",
"n",
">",
"1",
":",
"# Brand Y does not support Windows 98",
"if",
"\"98\"",
"==",
"row",
"[",
"1",
"]",
"and",
"\"Brand Y\"",
"==",
"row",
"[",
"0",
"]",
":",... | 27.62963 | 19.851852 |
def worker():
""" Initialize the distributed environment. """
import torch
import torch.distributed as dist
from torch.multiprocessing import Process
import numpy as np
print("Initializing distributed pytorch")
os.environ['MASTER_ADDR'] = str(args.master_addr)
os.environ['MASTER_PORT'] = str(args.mast... | [
"def",
"worker",
"(",
")",
":",
"import",
"torch",
"import",
"torch",
".",
"distributed",
"as",
"dist",
"from",
"torch",
".",
"multiprocessing",
"import",
"Process",
"import",
"numpy",
"as",
"np",
"print",
"(",
"\"Initializing distributed pytorch\"",
")",
"os",
... | 36.975 | 20.85 |
def _call_retry(self, force_retry):
"""Call request and retry up to max_attempts times (or none if self.max_attempts=1)"""
last_exception = None
for i in range(self.max_attempts):
try:
log.info("Calling %s %s" % (self.method, self.url))
response = self... | [
"def",
"_call_retry",
"(",
"self",
",",
"force_retry",
")",
":",
"last_exception",
"=",
"None",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"max_attempts",
")",
":",
"try",
":",
"log",
".",
"info",
"(",
"\"Calling %s %s\"",
"%",
"(",
"self",
".",
"met... | 42.84375 | 21.125 |
def get_group_details(self, group_url='', group_id=0):
''' a method to retrieve details about a meetup group
:param group_url: string with meetup urlname of group
:param group_id: int with meetup id for group
:return: dictionary with group details inside [json] key
gro... | [
"def",
"get_group_details",
"(",
"self",
",",
"group_url",
"=",
"''",
",",
"group_id",
"=",
"0",
")",
":",
"# https://www.meetup.com/meetup_api/docs/:urlname/#get\r",
"title",
"=",
"'%s.get_group_details'",
"%",
"self",
".",
"__class__",
".",
"__name__",
"# validate i... | 37.777778 | 26.755556 |
def match(self, situation):
"""Accept a situation (input) and return a MatchSet containing the
classifier rules whose conditions match the situation. If
appropriate per the algorithm managing this classifier set, create
new rules to ensure sufficient coverage of the possible actions.
... | [
"def",
"match",
"(",
"self",
",",
"situation",
")",
":",
"# Find the conditions that match against the current situation, and",
"# group them according to which action(s) they recommend.",
"by_action",
"=",
"{",
"}",
"for",
"condition",
",",
"actions",
"in",
"self",
".",
"_... | 42.243243 | 21.662162 |
def get_requested_form(self, request):
"""Returns an instance of a form requested."""
flow_name = self.get_flow_name()
flow_key = '%s_flow' % self.flow_type
flow_enabled = self.enabled
form_data = None
if (flow_enabled and
request.method == 'POST' and
... | [
"def",
"get_requested_form",
"(",
"self",
",",
"request",
")",
":",
"flow_name",
"=",
"self",
".",
"get_flow_name",
"(",
")",
"flow_key",
"=",
"'%s_flow'",
"%",
"self",
".",
"flow_type",
"flow_enabled",
"=",
"self",
".",
"enabled",
"form_data",
"=",
"None",
... | 38 | 19.76 |
def img(self):
'''return a cv image for the icon'''
SlipThumbnail.img(self)
if self.rotation:
# rotate the image
mat = cv2.getRotationMatrix2D((self.height//2, self.width//2), -self.rotation, 1.0)
self._rotated = cv2.warpAffine(self._img, mat, (self.height, s... | [
"def",
"img",
"(",
"self",
")",
":",
"SlipThumbnail",
".",
"img",
"(",
"self",
")",
"if",
"self",
".",
"rotation",
":",
"# rotate the image",
"mat",
"=",
"cv2",
".",
"getRotationMatrix2D",
"(",
"(",
"self",
".",
"height",
"//",
"2",
",",
"self",
".",
... | 36.545455 | 22.363636 |
def clear(self, *args):
"""
Clears the LED matrix with a single colour, default is black / off
e.g. ap.clear()
or
ap.clear(r, g, b)
or
colour = (r, g, b)
ap.clear(colour)
"""
black = (0, 0, 0) # default
if len(args) == 0:
... | [
"def",
"clear",
"(",
"self",
",",
"*",
"args",
")",
":",
"black",
"=",
"(",
"0",
",",
"0",
",",
"0",
")",
"# default",
"if",
"len",
"(",
"args",
")",
"==",
"0",
":",
"colour",
"=",
"black",
"elif",
"len",
"(",
"args",
")",
"==",
"1",
":",
"... | 23.75 | 20.416667 |
def annotate_event(ev, key, ts=None, namespace=None, **kwargs):
"""Add an annotation to an event."""
ann = {}
if ts is None:
ts = time.time()
ann["ts"] = ts
ann["key"] = key
if namespace is None and "HUMILIS_ENVIRONMENT" in os.environ:
namespace = "{}:{}:{}".format(
o... | [
"def",
"annotate_event",
"(",
"ev",
",",
"key",
",",
"ts",
"=",
"None",
",",
"namespace",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"ann",
"=",
"{",
"}",
"if",
"ts",
"is",
"None",
":",
"ts",
"=",
"time",
".",
"time",
"(",
")",
"ann",
"[... | 32.961538 | 16.730769 |
def _initialize_distance_grid(self):
"""Initialize the distance grid by calls to _grid_dist."""
p = [self._grid_distance(i) for i in range(self.num_neurons)]
return np.array(p) | [
"def",
"_initialize_distance_grid",
"(",
"self",
")",
":",
"p",
"=",
"[",
"self",
".",
"_grid_distance",
"(",
"i",
")",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"num_neurons",
")",
"]",
"return",
"np",
".",
"array",
"(",
"p",
")"
] | 49.25 | 11.75 |
def _count_counters(self, counter):
"""Return all elements count from Counter
"""
if getattr(self, 'as_set', False):
return len(set(counter))
else:
return sum(counter.values()) | [
"def",
"_count_counters",
"(",
"self",
",",
"counter",
")",
":",
"if",
"getattr",
"(",
"self",
",",
"'as_set'",
",",
"False",
")",
":",
"return",
"len",
"(",
"set",
"(",
"counter",
")",
")",
"else",
":",
"return",
"sum",
"(",
"counter",
".",
"values"... | 32.285714 | 5.428571 |
def snow_dual(im,
voxel_size=1,
boundary_faces=['top', 'bottom', 'left', 'right', 'front', 'back'],
marching_cubes_area=False):
r"""
Analyzes an image that has been partitioned into void and solid regions
and extracts the void and solid phase geometry as well as ne... | [
"def",
"snow_dual",
"(",
"im",
",",
"voxel_size",
"=",
"1",
",",
"boundary_faces",
"=",
"[",
"'top'",
",",
"'bottom'",
",",
"'left'",
",",
"'right'",
",",
"'front'",
",",
"'back'",
"]",
",",
"marching_cubes_area",
"=",
"False",
")",
":",
"# ---------------... | 49.521739 | 22.770186 |
def connect_to_ec2(region='us-east-1', access_key=None, secret_key=None):
""" Connect to AWS ec2
:type region: str
:param region: AWS region to connect to
:type access_key: str
:param access_key: AWS access key id
:type secret_key: str
:param secret_key: AWS secret access key
:returns: ... | [
"def",
"connect_to_ec2",
"(",
"region",
"=",
"'us-east-1'",
",",
"access_key",
"=",
"None",
",",
"secret_key",
"=",
"None",
")",
":",
"if",
"access_key",
":",
"# Connect using supplied credentials",
"logger",
".",
"info",
"(",
"'Connecting to AWS EC2 in {}'",
".",
... | 32.459459 | 18.810811 |
def import_string(dotted_path):
"""
Import a dotted module path and return the attribute/class designated by the
last name in the path. Raise ImportError if the import failed.
Args:
dotted_path: The path to attempt importing
Returns:
Imported class/attribute
"""
... | [
"def",
"import_string",
"(",
"dotted_path",
")",
":",
"try",
":",
"module_path",
",",
"class_name",
"=",
"dotted_path",
".",
"rsplit",
"(",
"'.'",
",",
"1",
")",
"except",
"ValueError",
"as",
"err",
":",
"raise",
"ImportError",
"(",
"\"%s doesn't look like a m... | 32.73913 | 21.782609 |
def get_user_roles(user):
"""Get a list of a users's roles."""
if user:
groups = user.groups.all() # Important! all() query may be cached on User with prefetch_related.
roles = (RolesManager.retrieve_role(group.name) for group in groups if group.name in RolesManager.get_roles_names())
... | [
"def",
"get_user_roles",
"(",
"user",
")",
":",
"if",
"user",
":",
"groups",
"=",
"user",
".",
"groups",
".",
"all",
"(",
")",
"# Important! all() query may be cached on User with prefetch_related.",
"roles",
"=",
"(",
"RolesManager",
".",
"retrieve_role",
"(",
"g... | 48.75 | 33 |
def find_one_and_update(self, filter, update, **kwargs):
"""
See http://api.mongodb.com/python/current/api/pymongo/collection.html#pymongo.collection.Collection.find_one_and_update
"""
self._arctic_lib.check_quota()
return self._collection.find_one_and_update(filter, update, **kw... | [
"def",
"find_one_and_update",
"(",
"self",
",",
"filter",
",",
"update",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_arctic_lib",
".",
"check_quota",
"(",
")",
"return",
"self",
".",
"_collection",
".",
"find_one_and_update",
"(",
"filter",
",",
"upd... | 53.333333 | 23.666667 |
def load(s, **kwargs):
"""Load yaml file"""
try:
return loads(s, **kwargs)
except TypeError:
return loads(s.read(), **kwargs) | [
"def",
"load",
"(",
"s",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"loads",
"(",
"s",
",",
"*",
"*",
"kwargs",
")",
"except",
"TypeError",
":",
"return",
"loads",
"(",
"s",
".",
"read",
"(",
")",
",",
"*",
"*",
"kwargs",
")"
] | 24.666667 | 12.666667 |
def print_spelling_errors(filename, encoding='utf8'):
"""
Print misspelled words returned by sphinxcontrib-spelling
"""
filesize = os.stat(filename).st_size
if filesize:
sys.stdout.write('Misspelled Words:\n')
with io.open(filename, encoding=encoding) as wordlist:
for li... | [
"def",
"print_spelling_errors",
"(",
"filename",
",",
"encoding",
"=",
"'utf8'",
")",
":",
"filesize",
"=",
"os",
".",
"stat",
"(",
"filename",
")",
".",
"st_size",
"if",
"filesize",
":",
"sys",
".",
"stdout",
".",
"write",
"(",
"'Misspelled Words:\\n'",
"... | 31.076923 | 14.615385 |
def is_gzipped_fastq(file_name):
"""
Determine whether indicated file appears to be a gzipped FASTQ.
:param str file_name: Name/path of file to check as gzipped FASTQ.
:return bool: Whether indicated file appears to be in gzipped FASTQ format.
"""
_, ext = os.path.splitext(file_name)
return... | [
"def",
"is_gzipped_fastq",
"(",
"file_name",
")",
":",
"_",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"file_name",
")",
"return",
"file_name",
".",
"endswith",
"(",
"\".fastq.gz\"",
")",
"or",
"file_name",
".",
"endswith",
"(",
"\".fq.gz\""... | 41.777778 | 19.777778 |
def extern_equals(self, context_handle, val1, val2):
"""Return true if the given Handles are __eq__."""
return self._ffi.from_handle(val1[0]) == self._ffi.from_handle(val2[0]) | [
"def",
"extern_equals",
"(",
"self",
",",
"context_handle",
",",
"val1",
",",
"val2",
")",
":",
"return",
"self",
".",
"_ffi",
".",
"from_handle",
"(",
"val1",
"[",
"0",
"]",
")",
"==",
"self",
".",
"_ffi",
".",
"from_handle",
"(",
"val2",
"[",
"0",
... | 60.333333 | 15.666667 |
def getSamplingWorkflowEnabled(self):
"""Returns True if the sample of this Analysis Request has to be
collected by the laboratory personnel
"""
template = self.getTemplate()
if template:
return template.getSamplingRequired()
return self.bika_setup.getSampling... | [
"def",
"getSamplingWorkflowEnabled",
"(",
"self",
")",
":",
"template",
"=",
"self",
".",
"getTemplate",
"(",
")",
"if",
"template",
":",
"return",
"template",
".",
"getSamplingRequired",
"(",
")",
"return",
"self",
".",
"bika_setup",
".",
"getSamplingWorkflowEn... | 41.25 | 7.375 |
def create_bool(help_string=NO_HELP, default=NO_DEFAULT):
# type: (str, Union[bool, NO_DEFAULT_TYPE]) -> bool
"""
Create a bool parameter
:param help_string:
:param default:
:return:
"""
# noinspection PyTypeChecker
return ParamFunctions(
... | [
"def",
"create_bool",
"(",
"help_string",
"=",
"NO_HELP",
",",
"default",
"=",
"NO_DEFAULT",
")",
":",
"# type: (str, Union[bool, NO_DEFAULT_TYPE]) -> bool",
"# noinspection PyTypeChecker",
"return",
"ParamFunctions",
"(",
"help_string",
"=",
"help_string",
",",
"default",
... | 31.1875 | 11.6875 |
def build_select_fields(self):
"""
Generates the sql for the SELECT portion of the query
:return: the SELECT portion of the query
:rtype: str
"""
field_sql = []
# get the field sql for each table
for table in self.tables:
field_sql += table.g... | [
"def",
"build_select_fields",
"(",
"self",
")",
":",
"field_sql",
"=",
"[",
"]",
"# get the field sql for each table",
"for",
"table",
"in",
"self",
".",
"tables",
":",
"field_sql",
"+=",
"table",
".",
"get_field_sql",
"(",
")",
"# get the field sql for each join ta... | 31.1 | 18.2 |
def clean_cell_meta(self, meta):
"""Remove cell metadata that matches the default cell metadata."""
for k, v in DEFAULT_CELL_METADATA.items():
if meta.get(k, None) == v:
meta.pop(k, None)
return meta | [
"def",
"clean_cell_meta",
"(",
"self",
",",
"meta",
")",
":",
"for",
"k",
",",
"v",
"in",
"DEFAULT_CELL_METADATA",
".",
"items",
"(",
")",
":",
"if",
"meta",
".",
"get",
"(",
"k",
",",
"None",
")",
"==",
"v",
":",
"meta",
".",
"pop",
"(",
"k",
... | 41 | 8 |
def asdatetime(self, naive=True):
"""Return this datetime_tz as a datetime object.
Args:
naive: Return *without* any tz info.
Returns:
This datetime_tz as a datetime object.
"""
args = list(self.timetuple()[0:6])+[self.microsecond]
if not naive:
args.append(self.tzinfo)
r... | [
"def",
"asdatetime",
"(",
"self",
",",
"naive",
"=",
"True",
")",
":",
"args",
"=",
"list",
"(",
"self",
".",
"timetuple",
"(",
")",
"[",
"0",
":",
"6",
"]",
")",
"+",
"[",
"self",
".",
"microsecond",
"]",
"if",
"not",
"naive",
":",
"args",
"."... | 26 | 15.923077 |
def normalizeBoolean(value):
"""
Normalizes a boolean.
* **value** must be an ``int`` with value of 0 or 1, or a ``bool``.
* Returned value will be a boolean.
"""
if isinstance(value, int) and value in (0, 1):
value = bool(value)
if not isinstance(value, bool):
raise ValueEr... | [
"def",
"normalizeBoolean",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"int",
")",
"and",
"value",
"in",
"(",
"0",
",",
"1",
")",
":",
"value",
"=",
"bool",
"(",
"value",
")",
"if",
"not",
"isinstance",
"(",
"value",
",",
"bool",... | 31.692308 | 14.769231 |
def _verify_field_spec(self, spec, path):
"""Verifies a given field specification is valid, recursing into nested schemas if required."""
# Required should be a boolean
if 'required' in spec and not isinstance(spec['required'], bool):
raise SchemaFormatException("{} required declara... | [
"def",
"_verify_field_spec",
"(",
"self",
",",
"spec",
",",
"path",
")",
":",
"# Required should be a boolean",
"if",
"'required'",
"in",
"spec",
"and",
"not",
"isinstance",
"(",
"spec",
"[",
"'required'",
"]",
",",
"bool",
")",
":",
"raise",
"SchemaFormatExce... | 45.785714 | 26.464286 |
def add_composition(self, composition):
"""Add a composition to the suite.
Raise an UnexpectedObjectError when the supplied argument is not a
Composition object.
"""
if not hasattr(composition, 'tracks'):
raise UnexpectedObjectError("Object '%s' not expected. Expecti... | [
"def",
"add_composition",
"(",
"self",
",",
"composition",
")",
":",
"if",
"not",
"hasattr",
"(",
"composition",
",",
"'tracks'",
")",
":",
"raise",
"UnexpectedObjectError",
"(",
"\"Object '%s' not expected. Expecting \"",
"\"a mingus.containers.Composition object.\"",
"%... | 41.545455 | 17.636364 |
def nworker(data, smpchunk, tests):
""" The workhorse function. Not numba. """
## tell engines to limit threads
#numba.config.NUMBA_DEFAULT_NUM_THREADS = 1
## open the seqarray view, the modified array is in bootsarr
with h5py.File(data.database.input, 'r') as io5:
seqview = io5["b... | [
"def",
"nworker",
"(",
"data",
",",
"smpchunk",
",",
"tests",
")",
":",
"## tell engines to limit threads",
"#numba.config.NUMBA_DEFAULT_NUM_THREADS = 1",
"## open the seqarray view, the modified array is in bootsarr",
"with",
"h5py",
".",
"File",
"(",
"data",
".",
"database"... | 38.2 | 20.022222 |
def raise_for_status(self):
'''
Raise BadStatus if one occurred.
'''
if 400 <= self.status_code < 500:
raise BadStatus('{} Client Error: {} for url: {}'.format(self.status_code, self.reason_phrase, self.url), self.status_code)
elif 500 <= self.status_code < 600:
... | [
"def",
"raise_for_status",
"(",
"self",
")",
":",
"if",
"400",
"<=",
"self",
".",
"status_code",
"<",
"500",
":",
"raise",
"BadStatus",
"(",
"'{} Client Error: {} for url: {}'",
".",
"format",
"(",
"self",
".",
"status_code",
",",
"self",
".",
"reason_phrase",... | 55.375 | 33.125 |
def _update_access_key_pair(self, access_key_id, key, val):
"""
Helper for updating access keys in a DRY fashion.
"""
# Get current state via HTTPS.
current_access_key = self.get_access_key(access_key_id)
# Copy and only change the single parameter.
payload_dict ... | [
"def",
"_update_access_key_pair",
"(",
"self",
",",
"access_key_id",
",",
"key",
",",
"val",
")",
":",
"# Get current state via HTTPS.",
"current_access_key",
"=",
"self",
".",
"get_access_key",
"(",
"access_key_id",
")",
"# Copy and only change the single parameter.",
"p... | 39.615385 | 18.076923 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.