text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def stop_gracefully(self):
'''Refuse to start more processes.
This runs in response to SIGINT or SIGTERM; if this isn't a
background process, control-C and a normal ``kill`` command
cause this.
'''
if self.shutting_down:
self.log(logging.INFO,
... | [
"def",
"stop_gracefully",
"(",
"self",
")",
":",
"if",
"self",
".",
"shutting_down",
":",
"self",
".",
"log",
"(",
"logging",
".",
"INFO",
",",
"'second shutdown request, shutting down now'",
")",
"self",
".",
"scram",
"(",
")",
"else",
":",
"self",
".",
"... | 34.2 | 21.666667 |
def post_request(self, endpoint, body=None, timeout=-1):
"""
Perform a POST request to a given endpoint in UpCloud's API.
"""
return self.request('POST', endpoint, body, timeout) | [
"def",
"post_request",
"(",
"self",
",",
"endpoint",
",",
"body",
"=",
"None",
",",
"timeout",
"=",
"-",
"1",
")",
":",
"return",
"self",
".",
"request",
"(",
"'POST'",
",",
"endpoint",
",",
"body",
",",
"timeout",
")"
] | 41.2 | 12.8 |
def update_activity(self, activity_form):
"""Updates an existing activity,.
arg: activity_form (osid.learning.ActivityForm): the form
containing the elements to be updated
raise: IllegalState - ``activity_form`` already used in an
update transaction
r... | [
"def",
"update_activity",
"(",
"self",
",",
"activity_form",
")",
":",
"# Implemented from template for",
"# osid.resource.ResourceAdminSession.update_resource_template",
"collection",
"=",
"JSONClientValidated",
"(",
"'learning'",
",",
"collection",
"=",
"'Activity'",
",",
"... | 50.756098 | 22.902439 |
def create_option(cls, option, **kwargs):
"""Create Option
Create a new Option
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.create_option(option, async=True)
>>> result = thread.get... | [
"def",
"create_option",
"(",
"cls",
",",
"option",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
"return",
"cls",
".",
"_create_option_with_http_info",
... | 38.142857 | 17.904762 |
def plot_fit_individuals_lens_plane_only(
fit, should_plot_mask=True, extract_array_from_mask=False, zoom_around_mask=False, positions=None,
should_plot_image_plane_pix=False,
should_plot_image=False,
should_plot_noise_map=False,
should_plot_signal_to_noise_map=False,
sho... | [
"def",
"plot_fit_individuals_lens_plane_only",
"(",
"fit",
",",
"should_plot_mask",
"=",
"True",
",",
"extract_array_from_mask",
"=",
"False",
",",
"zoom_around_mask",
"=",
"False",
",",
"positions",
"=",
"None",
",",
"should_plot_image_plane_pix",
"=",
"False",
",",
... | 44.851351 | 27.851351 |
def _get_lr_tensor(self):
"""Get lr minimizing the surrogate.
Returns:
The lr_t.
"""
lr = tf.squared_difference(1.0, tf.sqrt(self._mu)) / self._h_min
return lr | [
"def",
"_get_lr_tensor",
"(",
"self",
")",
":",
"lr",
"=",
"tf",
".",
"squared_difference",
"(",
"1.0",
",",
"tf",
".",
"sqrt",
"(",
"self",
".",
"_mu",
")",
")",
"/",
"self",
".",
"_h_min",
"return",
"lr"
] | 22.375 | 20.375 |
def rectmode(self, mode=None):
'''
Set the current rectmode.
:param mode: CORNER, CENTER, CORNERS
:return: rectmode if mode is None or valid.
'''
if mode in (self.CORNER, self.CENTER, self.CORNERS):
self.rectmode = mode
return self.rectmode
... | [
"def",
"rectmode",
"(",
"self",
",",
"mode",
"=",
"None",
")",
":",
"if",
"mode",
"in",
"(",
"self",
".",
"CORNER",
",",
"self",
".",
"CENTER",
",",
"self",
".",
"CORNERS",
")",
":",
"self",
".",
"rectmode",
"=",
"mode",
"return",
"self",
".",
"r... | 31.071429 | 16.785714 |
def generate(env):
"""Add Builders and construction variables for javac to an Environment."""
java_file = SCons.Tool.CreateJavaFileBuilder(env)
java_class = SCons.Tool.CreateJavaClassFileBuilder(env)
java_class_dir = SCons.Tool.CreateJavaClassDirBuilder(env)
java_class.add_emitter(None, emit_java_cl... | [
"def",
"generate",
"(",
"env",
")",
":",
"java_file",
"=",
"SCons",
".",
"Tool",
".",
"CreateJavaFileBuilder",
"(",
"env",
")",
"java_class",
"=",
"SCons",
".",
"Tool",
".",
"CreateJavaClassFileBuilder",
"(",
"env",
")",
"java_class_dir",
"=",
"SCons",
".",
... | 57.2 | 25.2 |
def operation(self, other, function, **kwargs):
"""Calculate "elementwise" operation either between this TimeSeries
and another one, i.e.
operation(t) = function(self(t), other(t))
or between this timeseries and a constant:
operation(t) = function(self(t), other)
If i... | [
"def",
"operation",
"(",
"self",
",",
"other",
",",
"function",
",",
"*",
"*",
"kwargs",
")",
":",
"result",
"=",
"TimeSeries",
"(",
"*",
"*",
"kwargs",
")",
"if",
"isinstance",
"(",
"other",
",",
"TimeSeries",
")",
":",
"for",
"time",
",",
"value",
... | 36.269231 | 16.884615 |
def to_networkx(self, names_only=False):
"""Create a NetworkX graph representing the hierarchy of a Compound.
Parameters
----------
names_only : bool, optional, default=False Store only the names of the
compounds in the graph. When set to False, the default behavior,
... | [
"def",
"to_networkx",
"(",
"self",
",",
"names_only",
"=",
"False",
")",
":",
"nx",
"=",
"import_",
"(",
"'networkx'",
")",
"nodes",
"=",
"list",
"(",
")",
"edges",
"=",
"list",
"(",
")",
"if",
"names_only",
":",
"nodes",
".",
"append",
"(",
"self",
... | 29.703704 | 19.962963 |
def down(removekeys=False, tgt='*', tgt_type='glob', timeout=None, gather_job_timeout=None):
'''
.. versionchanged:: 2017.7.0
The ``expr_form`` argument has been renamed to ``tgt_type``, earlier
releases must use ``expr_form``.
Print a list of all the down or unresponsive salt minions
O... | [
"def",
"down",
"(",
"removekeys",
"=",
"False",
",",
"tgt",
"=",
"'*'",
",",
"tgt_type",
"=",
"'glob'",
",",
"timeout",
"=",
"None",
",",
"gather_job_timeout",
"=",
"None",
")",
":",
"ret",
"=",
"status",
"(",
"output",
"=",
"False",
",",
"tgt",
"=",... | 30.758621 | 21.37931 |
def trigger(self, event):
"""AlertManager event handler for incoming events
:param event with incoming AlertManager message
"""
topic = event.data.get('topic', None)
if topic is None:
self.log('No alert topic to trigger', lvl=warn)
return
alert ... | [
"def",
"trigger",
"(",
"self",
",",
"event",
")",
":",
"topic",
"=",
"event",
".",
"data",
".",
"get",
"(",
"'topic'",
",",
"None",
")",
"if",
"topic",
"is",
"None",
":",
"self",
".",
"log",
"(",
"'No alert topic to trigger'",
",",
"lvl",
"=",
"warn"... | 28.055556 | 20.277778 |
def set_element(self, row, col, value):
"""
Sets the float value at the specified location.
:param row: the 0-based index of the row
:type row: int
:param col: the 0-based index of the column
:type col: int
:param value: the float value for that cell
:typ... | [
"def",
"set_element",
"(",
"self",
",",
"row",
",",
"col",
",",
"value",
")",
":",
"javabridge",
".",
"call",
"(",
"self",
".",
"jobject",
",",
"\"setElement\"",
",",
"\"(IID)V\"",
",",
"row",
",",
"col",
",",
"value",
")"
] | 32.769231 | 13.692308 |
def rmon_alarm_entry_snmp_oid(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
rmon = ET.SubElement(config, "rmon", xmlns="urn:brocade.com:mgmt:brocade-rmon")
alarm_entry = ET.SubElement(rmon, "alarm-entry")
alarm_index_key = ET.SubElement(alarm_e... | [
"def",
"rmon_alarm_entry_snmp_oid",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"rmon",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"rmon\"",
",",
"xmlns",
"=",
"\"urn:brocade.com:mgm... | 44.692308 | 15.692308 |
def _read_configuration_file(self, path):
"""Try to read and parse `path` as a configuration file.
If the configurations were illegal (checked with
`self._validate_options`), raises `IllegalConfiguration`.
Returns (options, should_inherit).
"""
parser = RawConfigParser... | [
"def",
"_read_configuration_file",
"(",
"self",
",",
"path",
")",
":",
"parser",
"=",
"RawConfigParser",
"(",
"inline_comment_prefixes",
"=",
"(",
"'#'",
",",
"';'",
")",
")",
"options",
"=",
"None",
"should_inherit",
"=",
"True",
"if",
"parser",
".",
"read"... | 38.851852 | 19.944444 |
def get(tree, name):
""" Return a float value attribute NAME from TREE.
"""
if name in tree:
value = tree[name]
else:
return float("nan")
try:
a = float(value)
except ValueError:
a = float("nan")
return a | [
"def",
"get",
"(",
"tree",
",",
"name",
")",
":",
"if",
"name",
"in",
"tree",
":",
"value",
"=",
"tree",
"[",
"name",
"]",
"else",
":",
"return",
"float",
"(",
"\"nan\"",
")",
"try",
":",
"a",
"=",
"float",
"(",
"value",
")",
"except",
"ValueErro... | 21.083333 | 17.333333 |
def download_as_pem(
base_url=d1_common.const.URL_DATAONE_ROOT,
timeout_sec=d1_common.const.DEFAULT_HTTP_TIMEOUT,
):
"""Download public certificate from a TLS/SSL web server as PEM encoded string.
Also see download_as_der().
Args:
base_url : str
A full URL to a DataONE service en... | [
"def",
"download_as_pem",
"(",
"base_url",
"=",
"d1_common",
".",
"const",
".",
"URL_DATAONE_ROOT",
",",
"timeout_sec",
"=",
"d1_common",
".",
"const",
".",
"DEFAULT_HTTP_TIMEOUT",
",",
")",
":",
"return",
"ssl",
".",
"DER_cert_to_PEM_cert",
"(",
"download_as_der"... | 29.631579 | 21.736842 |
def _convert_to(maybe_device, convert_to):
'''
Convert a device name, UUID or LABEL to a device name, UUID or
LABEL.
Return the fs_spec required for fstab.
'''
# Fast path. If we already have the information required, we can
# save one blkid call
if not convert_to or \
(convert... | [
"def",
"_convert_to",
"(",
"maybe_device",
",",
"convert_to",
")",
":",
"# Fast path. If we already have the information required, we can",
"# save one blkid call",
"if",
"not",
"convert_to",
"or",
"(",
"convert_to",
"==",
"'device'",
"and",
"maybe_device",
".",
"startswith... | 28.806452 | 22.419355 |
def princomp(x):
"""Determine the principal components of a vector of measurements
Determine the principal components of a vector of measurements
x should be a M x N numpy array composed of M observations of n variables
The output is:
coeffs - the NxN correlation matrix that can be used to tran... | [
"def",
"princomp",
"(",
"x",
")",
":",
"(",
"M",
",",
"N",
")",
"=",
"x",
".",
"shape",
"Mean",
"=",
"x",
".",
"mean",
"(",
"0",
")",
"y",
"=",
"x",
"-",
"Mean",
"cov",
"=",
"numpy",
".",
"dot",
"(",
"y",
".",
"transpose",
"(",
")",
",",
... | 35.142857 | 23.238095 |
def TryAction(self, action, text = None, extension = ""):
"""Tries to execute the given action with optional source file
contents <text> and optional source file extension <extension>,
Returns the status (0 : failed, 1 : ok) and the contents of the
output file.
"""
builde... | [
"def",
"TryAction",
"(",
"self",
",",
"action",
",",
"text",
"=",
"None",
",",
"extension",
"=",
"\"\"",
")",
":",
"builder",
"=",
"SCons",
".",
"Builder",
".",
"Builder",
"(",
"action",
"=",
"action",
")",
"self",
".",
"env",
".",
"Append",
"(",
"... | 48.714286 | 18.785714 |
def join(self):
"""Note that the Executor must be close()'d elsewhere,
or join() will never return.
"""
self.inputfeeder_thread.join()
self.pool.join()
self.resulttracker_thread.join()
self.failuretracker_thread.join() | [
"def",
"join",
"(",
"self",
")",
":",
"self",
".",
"inputfeeder_thread",
".",
"join",
"(",
")",
"self",
".",
"pool",
".",
"join",
"(",
")",
"self",
".",
"resulttracker_thread",
".",
"join",
"(",
")",
"self",
".",
"failuretracker_thread",
".",
"join",
"... | 28.125 | 9.5 |
def rename(self, from_path, to_path):
"""
Rename file.
:type from_path: str
:param from_path: the path of the source file
:type to_path: str
:param to_path: the path of the destination file
:raises: :exc:`~exceptions.IOError`
"""
_complain_ifclose... | [
"def",
"rename",
"(",
"self",
",",
"from_path",
",",
"to_path",
")",
":",
"_complain_ifclosed",
"(",
"self",
".",
"closed",
")",
"return",
"self",
".",
"fs",
".",
"rename",
"(",
"from_path",
",",
"to_path",
")"
] | 31.083333 | 10.916667 |
def _get_format_callable(term, color, back_color):
"""Get string-coloring callable
Get callable for string output using ``color`` on ``back_color``
on ``term``
:param term: blessings.Terminal instance
:param color: Color that callable will color the string it's passed
... | [
"def",
"_get_format_callable",
"(",
"term",
",",
"color",
",",
"back_color",
")",
":",
"if",
"isinstance",
"(",
"color",
",",
"str",
")",
":",
"ensure",
"(",
"any",
"(",
"isinstance",
"(",
"back_color",
",",
"t",
")",
"for",
"t",
"in",
"[",
"str",
",... | 35.758621 | 15.827586 |
def maximum(left, right):
"""Returns element-wise maximum of the input elements.
Both inputs can be Symbol or scalar number. Broadcasting is not supported.
Parameters
---------
left : Symbol or scalar
First symbol to be compared.
right : Symbol or scalar
Second symbol to be com... | [
"def",
"maximum",
"(",
"left",
",",
"right",
")",
":",
"if",
"isinstance",
"(",
"left",
",",
"Symbol",
")",
"and",
"isinstance",
"(",
"right",
",",
"Symbol",
")",
":",
"return",
"_internal",
".",
"_Maximum",
"(",
"left",
",",
"right",
")",
"if",
"isi... | 34.55 | 20.025 |
def dedent(text):
"""Equivalent of textwrap.dedent that ignores unindented first line.
This means it will still dedent strings like:
'''foo
is a bar
'''
For use in wrap_paragraphs.
"""
if text.startswith('\n'):
# text starts with blank line, don't ignore the first line
... | [
"def",
"dedent",
"(",
"text",
")",
":",
"if",
"text",
".",
"startswith",
"(",
"'\\n'",
")",
":",
"# text starts with blank line, don't ignore the first line",
"return",
"textwrap",
".",
"dedent",
"(",
"text",
")",
"# split first line",
"splits",
"=",
"text",
".",
... | 24.2 | 18.72 |
def sandbox(cls, path):
'''Ensures path exists before yielding, cleans up after'''
# Ensure the path exists and is clean
try:
os.makedirs(path)
logger.debug('Making %s' % path)
except OSError:
if not os.path.isdir(path):
raise
f... | [
"def",
"sandbox",
"(",
"cls",
",",
"path",
")",
":",
"# Ensure the path exists and is clean",
"try",
":",
"os",
".",
"makedirs",
"(",
"path",
")",
"logger",
".",
"debug",
"(",
"'Making %s'",
"%",
"path",
")",
"except",
"OSError",
":",
"if",
"not",
"os",
... | 30.5625 | 17.8125 |
def named_entity_labels(self):
"""The named entity labels without BIO prefixes."""
if not self.is_tagged(NAMED_ENTITIES):
self.tag_named_entities()
return [ne[LABEL] for ne in self[NAMED_ENTITIES]] | [
"def",
"named_entity_labels",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_tagged",
"(",
"NAMED_ENTITIES",
")",
":",
"self",
".",
"tag_named_entities",
"(",
")",
"return",
"[",
"ne",
"[",
"LABEL",
"]",
"for",
"ne",
"in",
"self",
"[",
"NAMED_ENTIT... | 45.8 | 7.2 |
def definition(
self,
text,
definition):
"""*genarate a MMD definition*
**Key Arguments:**
- ``text`` -- the text to define
- ``definition`` -- the definition
**Return:**
- ``definition`` -- the MMD style definition
... | [
"def",
"definition",
"(",
"self",
",",
"text",
",",
"definition",
")",
":",
"text",
"=",
"text",
".",
"strip",
"(",
")",
"definition",
"=",
"definition",
".",
"strip",
"(",
")",
"regex",
"=",
"re",
".",
"compile",
"(",
"r'\\n(\\S)'",
")",
"definition",... | 29.513514 | 22.243243 |
def save_image(self, image_file):
"""
Saves the image file to disk.
"""
self.ensure_pyplot()
command = 'plt.gcf().savefig("%s")'%image_file
#print 'SAVEFIG', command # dbg
self.process_input_line('bookmark ipy_thisdir', store_history=False)
self.process_i... | [
"def",
"save_image",
"(",
"self",
",",
"image_file",
")",
":",
"self",
".",
"ensure_pyplot",
"(",
")",
"command",
"=",
"'plt.gcf().savefig(\"%s\")'",
"%",
"image_file",
"#print 'SAVEFIG', command # dbg",
"self",
".",
"process_input_line",
"(",
"'bookmark ipy_thisdir'",... | 46.230769 | 16.384615 |
def ensure_object_is_ndarray(item, title):
"""
Ensures that a given mapping matrix is a dense numpy array. Raises a
helpful TypeError if otherwise.
"""
assert isinstance(title, str)
if not isinstance(item, np.ndarray):
msg = "{} must be a np.ndarray. {} passed instead."
raise Ty... | [
"def",
"ensure_object_is_ndarray",
"(",
"item",
",",
"title",
")",
":",
"assert",
"isinstance",
"(",
"title",
",",
"str",
")",
"if",
"not",
"isinstance",
"(",
"item",
",",
"np",
".",
"ndarray",
")",
":",
"msg",
"=",
"\"{} must be a np.ndarray. {} passed instea... | 30.333333 | 15.333333 |
def executions(self) -> List[Execution]:
"""
List of all executions from this session.
"""
return list(fill.execution for fill in self.wrapper.fills.values()) | [
"def",
"executions",
"(",
"self",
")",
"->",
"List",
"[",
"Execution",
"]",
":",
"return",
"list",
"(",
"fill",
".",
"execution",
"for",
"fill",
"in",
"self",
".",
"wrapper",
".",
"fills",
".",
"values",
"(",
")",
")"
] | 37.2 | 8.8 |
def render_output_json(self, graph_data, output_file=None):
"""Write model data to file or stdout in JSON format."""
if output_file:
with open(output_file, 'wt') as json_output_f:
json.dump(graph_data, json_output_f)
else:
self.stdout.write(json.dumps(grap... | [
"def",
"render_output_json",
"(",
"self",
",",
"graph_data",
",",
"output_file",
"=",
"None",
")",
":",
"if",
"output_file",
":",
"with",
"open",
"(",
"output_file",
",",
"'wt'",
")",
"as",
"json_output_f",
":",
"json",
".",
"dump",
"(",
"graph_data",
",",... | 46 | 15.142857 |
def start_daemon_thread(*args, **kwargs):
"""Starts a thread and marks it as a daemon thread."""
thread = threading.Thread(*args, **kwargs)
thread.daemon = True
thread.start()
return thread | [
"def",
"start_daemon_thread",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"thread",
"=",
"threading",
".",
"Thread",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"thread",
".",
"daemon",
"=",
"True",
"thread",
".",
"start",
"(",
")",
"r... | 34 | 11.333333 |
def validate_version(err, value, source):
'Tests a manifest version number'
field_name = '<em:version>' if source == 'install.rdf' else 'version'
err.metadata['version'] = value
# May not be longer than 32 characters
if len(value) > 32:
err.error(
('metadata_helpers', '_test_... | [
"def",
"validate_version",
"(",
"err",
",",
"value",
",",
"source",
")",
":",
"field_name",
"=",
"'<em:version>'",
"if",
"source",
"==",
"'install.rdf'",
"else",
"'version'",
"err",
".",
"metadata",
"[",
"'version'",
"]",
"=",
"value",
"# May not be longer than ... | 40.115385 | 24.269231 |
def _findlinestarts(code):
"""Find the offsets in a byte code which are start of lines in the source.
Generate pairs (offset, lineno) as described in Python/compile.c.
Arguments:
code: code object.
Yields:
Address and line number pairs.
"""
byte_increments = [ord(c) for c in code.co_lnotab[0::2]]... | [
"def",
"_findlinestarts",
"(",
"code",
")",
":",
"byte_increments",
"=",
"[",
"ord",
"(",
"c",
")",
"for",
"c",
"in",
"code",
".",
"co_lnotab",
"[",
"0",
":",
":",
"2",
"]",
"]",
"line_increments",
"=",
"[",
"ord",
"(",
"c",
")",
"for",
"c",
"in"... | 26.615385 | 20.423077 |
def calibrate(self,
dataset_id,
pre_launch_coeffs=False,
calib_coeffs=None):
"""Calibrate the data
"""
tic = datetime.now()
if calib_coeffs is None:
calib_coeffs = {}
units = {'reflectance': '%',
... | [
"def",
"calibrate",
"(",
"self",
",",
"dataset_id",
",",
"pre_launch_coeffs",
"=",
"False",
",",
"calib_coeffs",
"=",
"None",
")",
":",
"tic",
"=",
"datetime",
".",
"now",
"(",
")",
"if",
"calib_coeffs",
"is",
"None",
":",
"calib_coeffs",
"=",
"{",
"}",
... | 36.216667 | 17.55 |
def get_extent(array, units, kpc_per_arcsec, xticks_manual, yticks_manual):
"""Get the extent of the dimensions of the array in the units of the figure (e.g. arc-seconds or kpc).
This is used to set the extent of the array and thus the y / x axis limits.
Parameters
-----------
array : data.array.s... | [
"def",
"get_extent",
"(",
"array",
",",
"units",
",",
"kpc_per_arcsec",
",",
"xticks_manual",
",",
"yticks_manual",
")",
":",
"if",
"xticks_manual",
"is",
"not",
"None",
"and",
"yticks_manual",
"is",
"not",
"None",
":",
"return",
"np",
".",
"asarray",
"(",
... | 55.272727 | 31.848485 |
def _get_pwm_values(self, brightness=None, color=None):
"""
Get the pwm values for a specific state of the led.
If a state argument is omitted, current value is used.
:param brightness: The brightness of the state.
:param color: The color of the state.
:return: The pwm ... | [
"def",
"_get_pwm_values",
"(",
"self",
",",
"brightness",
"=",
"None",
",",
"color",
"=",
"None",
")",
":",
"if",
"brightness",
"is",
"None",
":",
"brightness",
"=",
"self",
".",
"brightness",
"if",
"color",
"is",
"None",
":",
"color",
"=",
"self",
"."... | 33 | 17 |
def is_parent_of_repository(self, id_, repository_id):
"""Tests if an ``Id`` is a direct parent of a repository.
arg: id (osid.id.Id): an ``Id``
arg: repository_id (osid.id.Id): the ``Id`` of a repository
return: (boolean) - ``true`` if this ``id`` is a parent of
`... | [
"def",
"is_parent_of_repository",
"(",
"self",
",",
"id_",
",",
"repository_id",
")",
":",
"# Implemented from template for",
"# osid.resource.BinHierarchySession.is_parent_of_bin",
"if",
"self",
".",
"_catalog_session",
"is",
"not",
"None",
":",
"return",
"self",
".",
... | 53.2 | 21.5 |
def add_cookies_to_web_driver(driver, cookies):
"""
Sets cookies in an existing WebDriver session.
"""
for cookie in cookies:
driver.add_cookie(convert_cookie_to_dict(cookie))
return driver | [
"def",
"add_cookies_to_web_driver",
"(",
"driver",
",",
"cookies",
")",
":",
"for",
"cookie",
"in",
"cookies",
":",
"driver",
".",
"add_cookie",
"(",
"convert_cookie_to_dict",
"(",
"cookie",
")",
")",
"return",
"driver"
] | 30.142857 | 10.142857 |
def to_float(b:Collection[Tensor])->Collection[Tensor]:
"Recursively map lists of tensors in `b ` to FP16."
if is_listy(b): return [to_float(o) for o in b]
return b.float() if b.dtype not in [torch.int64, torch.int32, torch.int16] else b | [
"def",
"to_float",
"(",
"b",
":",
"Collection",
"[",
"Tensor",
"]",
")",
"->",
"Collection",
"[",
"Tensor",
"]",
":",
"if",
"is_listy",
"(",
"b",
")",
":",
"return",
"[",
"to_float",
"(",
"o",
")",
"for",
"o",
"in",
"b",
"]",
"return",
"b",
".",
... | 61.5 | 21.5 |
def dispatch_to_series(left, right, func, str_rep=None, axis=None):
"""
Evaluate the frame operation func(left, right) by evaluating
column-by-column, dispatching to the Series implementation.
Parameters
----------
left : DataFrame
right : scalar or DataFrame
func : arithmetic or compar... | [
"def",
"dispatch_to_series",
"(",
"left",
",",
"right",
",",
"func",
",",
"str_rep",
"=",
"None",
",",
"axis",
"=",
"None",
")",
":",
"# Note: we use iloc to access columns for compat with cases",
"# with non-unique columns.",
"import",
"pandas",
".",
"core",
".... | 32.822581 | 20.112903 |
def add_urlhelpers(event):
"""
Add helpers to the template engine.
"""
event['static_url'] = lambda x: static_path(x, event['request'])
event['route_url'] = lambda name, *args, **kwargs: \
route_path(name, event['request'], *args, **kwargs)
event['parse_rest'] = parse_rest
event['has... | [
"def",
"add_urlhelpers",
"(",
"event",
")",
":",
"event",
"[",
"'static_url'",
"]",
"=",
"lambda",
"x",
":",
"static_path",
"(",
"x",
",",
"event",
"[",
"'request'",
"]",
")",
"event",
"[",
"'route_url'",
"]",
"=",
"lambda",
"name",
",",
"*",
"args",
... | 39.888889 | 11.444444 |
def _create_link(self, act_node, name, instance):
"""Creates a link and checks if names are appropriate
"""
act_node._links[name] = instance
act_node._children[name] = instance
full_name = instance.v_full_name
if full_name not in self._root_instance._linked_by:
... | [
"def",
"_create_link",
"(",
"self",
",",
"act_node",
",",
"name",
",",
"instance",
")",
":",
"act_node",
".",
"_links",
"[",
"name",
"]",
"=",
"instance",
"act_node",
".",
"_children",
"[",
"name",
"]",
"=",
"instance",
"full_name",
"=",
"instance",
".",... | 40.782609 | 16.608696 |
def create_token_role(self, role,
allowed_policies=None, disallowed_policies=None,
orphan=None, period=None, renewable=None,
path_suffix=None, explicit_max_ttl=None):
"""POST /auth/token/roles/<role>
:param role:
:typ... | [
"def",
"create_token_role",
"(",
"self",
",",
"role",
",",
"allowed_policies",
"=",
"None",
",",
"disallowed_policies",
"=",
"None",
",",
"orphan",
"=",
"None",
",",
"period",
"=",
"None",
",",
"renewable",
"=",
"None",
",",
"path_suffix",
"=",
"None",
","... | 32.657143 | 16.057143 |
def reload(self):
''' reloads this object so if it was updated in the database it now
contains the new values'''
key = self.key()
redis = type(self).get_redis()
if not redis.exists(key):
raise ModelNotFoundError('This object has been deleted')
data = debyte_... | [
"def",
"reload",
"(",
"self",
")",
":",
"key",
"=",
"self",
".",
"key",
"(",
")",
"redis",
"=",
"type",
"(",
"self",
")",
".",
"get_redis",
"(",
")",
"if",
"not",
"redis",
".",
"exists",
"(",
"key",
")",
":",
"raise",
"ModelNotFoundError",
"(",
"... | 25.904762 | 21.52381 |
def configs_for_reader(reader=None, ppp_config_dir=None):
"""Generator of reader configuration files for one or more readers
Args:
reader (Optional[str]): Yield configs only for this reader
ppp_config_dir (Optional[str]): Additional configuration directory
to search for reader confi... | [
"def",
"configs_for_reader",
"(",
"reader",
"=",
"None",
",",
"ppp_config_dir",
"=",
"None",
")",
":",
"search_paths",
"=",
"(",
"ppp_config_dir",
",",
")",
"if",
"ppp_config_dir",
"else",
"tuple",
"(",
")",
"if",
"reader",
"is",
"not",
"None",
":",
"if",
... | 41.212766 | 22 |
def substitute_variables(cls, configuration, value, ref):
"""
Substitute variables in `value` from `configuration` where any path reference is relative to
`ref`.
Parameters
----------
configuration : dict
configuration (required to resolve intra-document refe... | [
"def",
"substitute_variables",
"(",
"cls",
",",
"configuration",
",",
"value",
",",
"ref",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"# Substitute all intra-document references",
"while",
"True",
":",
"match",
"=",
"cls",
".",
"REF_PATT... | 34.390244 | 18.634146 |
def calc_significand(prefix, dpd_bits, num_bits):
"""
prefix: High bits integer value
dpd_bits: dpd encoded bits
num_bits: bit length of dpd_bits
"""
# https://en.wikipedia.org/wiki/Decimal128_floating-point_format#Densely_packed_decimal_significand_field
num_segments = num_bits // 10
se... | [
"def",
"calc_significand",
"(",
"prefix",
",",
"dpd_bits",
",",
"num_bits",
")",
":",
"# https://en.wikipedia.org/wiki/Decimal128_floating-point_format#Densely_packed_decimal_significand_field",
"num_segments",
"=",
"num_bits",
"//",
"10",
"segments",
"=",
"[",
"]",
"for",
... | 28.263158 | 17.315789 |
def xml(self, xml):
"""
Defines a XML body value to match.
Arguments:
xml (str|regex): body XML to match.
Returns:
self: current Mock instance.
"""
self._request.xml = xml
self.add_matcher(matcher('XMLMatcher', xml)) | [
"def",
"xml",
"(",
"self",
",",
"xml",
")",
":",
"self",
".",
"_request",
".",
"xml",
"=",
"xml",
"self",
".",
"add_matcher",
"(",
"matcher",
"(",
"'XMLMatcher'",
",",
"xml",
")",
")"
] | 23.916667 | 14.75 |
async def _check_for_matching_user(self, **user_filters):
"""
This function checks if there is a user with the same uid in the
remote user service
Args:
**kwds : the filters of the user to check for
Returns:
(bool): wether or not th... | [
"async",
"def",
"_check_for_matching_user",
"(",
"self",
",",
"*",
"*",
"user_filters",
")",
":",
"# there is a matching user if there are no errors and no results from",
"user_data",
"=",
"self",
".",
"_get_matching_user",
"(",
"user_filters",
")",
"# return true if there we... | 44.928571 | 22.214286 |
def get_manifest_from_meta(metaurl, name):
"""
Extact manifest url from metadata url
:param metaurl: Url to metadata
:param name: Name of application to extract
:return:
"""
if 'http' in metaurl:
kit = yaml.safe_load(requests.get(url=metaurl).content)['kit']['applications']
else:... | [
"def",
"get_manifest_from_meta",
"(",
"metaurl",
",",
"name",
")",
":",
"if",
"'http'",
"in",
"metaurl",
":",
"kit",
"=",
"yaml",
".",
"safe_load",
"(",
"requests",
".",
"get",
"(",
"url",
"=",
"metaurl",
")",
".",
"content",
")",
"[",
"'kit'",
"]",
... | 35.642857 | 15.785714 |
def migrate_constituencies(apps, schema_editor):
"""
Re-save constituencies to recompute fingerprints
"""
Constituency = apps.get_model("representatives", "Constituency")
for c in Constituency.objects.all():
c.save() | [
"def",
"migrate_constituencies",
"(",
"apps",
",",
"schema_editor",
")",
":",
"Constituency",
"=",
"apps",
".",
"get_model",
"(",
"\"representatives\"",
",",
"\"Constituency\"",
")",
"for",
"c",
"in",
"Constituency",
".",
"objects",
".",
"all",
"(",
")",
":",
... | 34 | 10.285714 |
def all_control_flow_elements_count(bpmn_graph):
"""
Returns the total count of all control flow elements
in the BPMNDiagramGraph instance.
:param bpmn_graph: an instance of BpmnDiagramGraph representing BPMN model.
:return: total count of the control flow elements in the BPMNDiagramGraph inst... | [
"def",
"all_control_flow_elements_count",
"(",
"bpmn_graph",
")",
":",
"gateway_counts",
"=",
"get_gateway_counts",
"(",
"bpmn_graph",
")",
"events_counts",
"=",
"get_events_counts",
"(",
"bpmn_graph",
")",
"control_flow_elements_counts",
"=",
"gateway_counts",
".",
"copy... | 36.166667 | 22.277778 |
def execute(self, request):
"""Execute a request and return a response"""
url = request.uri
if request.parameters:
url += '?' + urlencode(request.parameters)
if request.headers:
headers = dict(self._headers, **request.headers)
else:
headers = ... | [
"def",
"execute",
"(",
"self",
",",
"request",
")",
":",
"url",
"=",
"request",
".",
"uri",
"if",
"request",
".",
"parameters",
":",
"url",
"+=",
"'?'",
"+",
"urlencode",
"(",
"request",
".",
"parameters",
")",
"if",
"request",
".",
"headers",
":",
"... | 42.325581 | 19.232558 |
def docker_environment(env):
"""
Transform dictionary of environment variables into Docker -e parameters.
>>> result = docker_environment({'param1': 'val1', 'param2': 'val2'})
>>> result in ['-e "param1=val1" -e "param2=val2"', '-e "param2=val2" -e "param1=val1"']
True
"""
return ' '.join(
... | [
"def",
"docker_environment",
"(",
"env",
")",
":",
"return",
"' '",
".",
"join",
"(",
"[",
"\"-e \\\"%s=%s\\\"\"",
"%",
"(",
"key",
",",
"value",
".",
"replace",
"(",
"\"$\"",
",",
"\"\\\\$\"",
")",
".",
"replace",
"(",
"\"\\\"\"",
",",
"\"\\\\\\\"\"",
"... | 41 | 25.909091 |
def worker(compute, task_queue, result_queue, log_queue, complete,
*context):
"""A worker process, run by ``multiprocessing.Process``."""
try:
MapReduce._forked = True
log.debug('Worker process starting...')
configure_worker_logging(log_queue)
... | [
"def",
"worker",
"(",
"compute",
",",
"task_queue",
",",
"result_queue",
",",
"log_queue",
",",
"complete",
",",
"*",
"context",
")",
":",
"try",
":",
"MapReduce",
".",
"_forked",
"=",
"True",
"log",
".",
"debug",
"(",
"'Worker process starting...'",
")",
... | 36.869565 | 18.73913 |
def do_b0(self, line):
"""Send the Master a BinaryInput (group 2) value of False at index 6. Command syntax is: b0"""
self.application.apply_update(opendnp3.Binary(False), index=6) | [
"def",
"do_b0",
"(",
"self",
",",
"line",
")",
":",
"self",
".",
"application",
".",
"apply_update",
"(",
"opendnp3",
".",
"Binary",
"(",
"False",
")",
",",
"index",
"=",
"6",
")"
] | 64.666667 | 16 |
def match_value_to_text(self, text):
"""
this is going to be the tricky bit - probably not possible
to get the 'exact' rating for a value. Will need to do sentiment
analysis of the text to see how it matches the rating. Even that
sounds like it wont work - maybe a ML algorithm wo... | [
"def",
"match_value_to_text",
"(",
"self",
",",
"text",
")",
":",
"if",
"self",
".",
"nme",
"in",
"text",
":",
"res",
"=",
"0.8",
"else",
":",
"res",
"=",
"0.2",
"return",
"self",
".",
"nme",
"+",
"' = '",
"+",
"str",
"(",
"res",
")",
"+",
"' mat... | 38.05 | 25.05 |
def pip_installer_url(version=None):
"""Get argument to give to ``pip`` to install HPCBench.
"""
version = version or hpcbench.__version__
version = str(version)
if '.dev' in version:
git_rev = 'master'
if 'TRAVIS_BRANCH' in os.environ:
git_rev = version.split('+', 1)[-1]... | [
"def",
"pip_installer_url",
"(",
"version",
"=",
"None",
")",
":",
"version",
"=",
"version",
"or",
"hpcbench",
".",
"__version__",
"version",
"=",
"str",
"(",
"version",
")",
"if",
"'.dev'",
"in",
"version",
":",
"git_rev",
"=",
"'master'",
"if",
"'TRAVIS... | 40.823529 | 10.823529 |
def cmyk_to_rgb(Class, c, m, y, k):
"""CMYK in % to RGB in 0-255
based on https://www.openprocessing.org/sketch/46231#
"""
c = float(c)/100.0
m = float(m)/100.0
y = float(y)/100.0
k = float(k)/100.0
nc = (c * (1-k)) + k
nm = (m * (1-k)) ... | [
"def",
"cmyk_to_rgb",
"(",
"Class",
",",
"c",
",",
"m",
",",
"y",
",",
"k",
")",
":",
"c",
"=",
"float",
"(",
"c",
")",
"/",
"100.0",
"m",
"=",
"float",
"(",
"m",
")",
"/",
"100.0",
"y",
"=",
"float",
"(",
"y",
")",
"/",
"100.0",
"k",
"="... | 26.055556 | 14.666667 |
def get_tags(self, md5):
"""Get tags for this sample"""
tag_data = self.data_store.get_work_results('tags', md5)
return tag_data['tags'] if tag_data else None | [
"def",
"get_tags",
"(",
"self",
",",
"md5",
")",
":",
"tag_data",
"=",
"self",
".",
"data_store",
".",
"get_work_results",
"(",
"'tags'",
",",
"md5",
")",
"return",
"tag_data",
"[",
"'tags'",
"]",
"if",
"tag_data",
"else",
"None"
] | 44.75 | 13.25 |
def valid(self):
""" Check to see if we are still active. """
if self.finished is not None:
return False
with self._db_conn() as conn:
row = conn.get('''
SELECT (last_contact > %%(now)s - INTERVAL %%(ttl)s SECOND) AS valid
FROM %s
... | [
"def",
"valid",
"(",
"self",
")",
":",
"if",
"self",
".",
"finished",
"is",
"not",
"None",
":",
"return",
"False",
"with",
"self",
".",
"_db_conn",
"(",
")",
"as",
"conn",
":",
"row",
"=",
"conn",
".",
"get",
"(",
"'''\n SELECT (last_conta... | 35.578947 | 13.894737 |
def modify_relationship(self, rel_uri, old_object, new_object):
"""
Modify a relationship from RELS-EXT for this object. As the Fedora API-M does not contain
a native "modifyRelationship", this method purges an existing one, then adds a new one,
pivoting on the predicate.
Calls ... | [
"def",
"modify_relationship",
"(",
"self",
",",
"rel_uri",
",",
"old_object",
",",
"new_object",
")",
":",
"if",
"isinstance",
"(",
"rel_uri",
",",
"URIRef",
")",
":",
"rel_uri",
"=",
"force_text",
"(",
"rel_uri",
")",
"# old_object",
"obj_old_is_literal",
"="... | 45.153846 | 24.230769 |
def plot_result(filt, full, prntres=True):
r"""QC the inversion result.
Parameters
----------
- filt, full as returned from fdesign.design with full_output=True
- If prntres is True, it calls fdesign.print_result as well.
r"""
# Check matplotlib (soft dependency)
if not plt:
pr... | [
"def",
"plot_result",
"(",
"filt",
",",
"full",
",",
"prntres",
"=",
"True",
")",
":",
"# Check matplotlib (soft dependency)",
"if",
"not",
"plt",
":",
"print",
"(",
"plt_msg",
")",
"return",
"if",
"prntres",
":",
"print_result",
"(",
"filt",
",",
"full",
... | 34.368421 | 17.263158 |
def offset_overlays(self, text, offset=0, **kw):
"""
Generate overlays after offset.
:param text: The text to be searched.
:param offset: Match starting that index. If none just search.
:returns: An overlay or None
"""
# This may be a bit slower but overlayedtext... | [
"def",
"offset_overlays",
"(",
"self",
",",
"text",
",",
"offset",
"=",
"0",
",",
"*",
"*",
"kw",
")",
":",
"# This may be a bit slower but overlayedtext takes care of",
"# unicode issues.",
"if",
"not",
"isinstance",
"(",
"text",
",",
"OverlayedText",
")",
":",
... | 39.117647 | 14.529412 |
def print_graphic_information(self, num_curve, information):
"""
This function displays information about curves.
Inputs ; num_curve ; The index of the curve's line that we have to display.
information ; The array which contains the information, of all curves to display.
... | [
"def",
"print_graphic_information",
"(",
"self",
",",
"num_curve",
",",
"information",
")",
":",
"\"\"\"In this function, the best would to create labels each time we need to create one,\n following the number of labels in label_information.\n #self.essai = QtGui.QLabel(self.ui.tab... | 57.121951 | 24.97561 |
def recv_into(self, buffer, nbytes=None, flags=None):
"""
Receive data on the connection and copy it directly into the provided
buffer, rather than creating a new string.
:param buffer: The buffer to copy into.
:param nbytes: (optional) The maximum number of bytes to read into t... | [
"def",
"recv_into",
"(",
"self",
",",
"buffer",
",",
"nbytes",
"=",
"None",
",",
"flags",
"=",
"None",
")",
":",
"if",
"nbytes",
"is",
"None",
":",
"nbytes",
"=",
"len",
"(",
"buffer",
")",
"else",
":",
"nbytes",
"=",
"min",
"(",
"nbytes",
",",
"... | 45.722222 | 23 |
def temp_files(self):
"""Return a list of the temporary files produced by this link.
This returns all files that were explicitly marked for removal.
"""
ret_list = []
for key, val in self.file_dict.items():
# For temp files we only want files that were marked for rem... | [
"def",
"temp_files",
"(",
"self",
")",
":",
"ret_list",
"=",
"[",
"]",
"for",
"key",
",",
"val",
"in",
"self",
".",
"file_dict",
".",
"items",
"(",
")",
":",
"# For temp files we only want files that were marked for removal",
"if",
"val",
"&",
"FileFlags",
"."... | 37.727273 | 15.818182 |
def compare_version(a, b): # Ignore PyDocStyleBear
"""Compare two version strings.
:param a: str
:param b: str
:return: -1 / 0 / 1
"""
def _range(q):
"""Convert a version string to array of integers.
"1.2.3" -> [1, 2, 3]
:param q: str
:return: List[int]
... | [
"def",
"compare_version",
"(",
"a",
",",
"b",
")",
":",
"# Ignore PyDocStyleBear",
"def",
"_range",
"(",
"q",
")",
":",
"\"\"\"Convert a version string to array of integers.\n\n \"1.2.3\" -> [1, 2, 3]\n\n :param q: str\n :return: List[int]\n \"\"\"",
"r",
... | 24.327273 | 17.836364 |
def set_snap_server_variables(host, port, snap_extension='.xml', path=None):
""" Change dynamically port and host variable in xml Snap! project file"""
localdir = os.getcwd()
if path is None:
os.chdir(os.path.dirname(os.path.realpath(__file__)))
else:
os.chdir(path)
xml_files = [f f... | [
"def",
"set_snap_server_variables",
"(",
"host",
",",
"port",
",",
"snap_extension",
"=",
"'.xml'",
",",
"path",
"=",
"None",
")",
":",
"localdir",
"=",
"os",
".",
"getcwd",
"(",
")",
"if",
"path",
"is",
"None",
":",
"os",
".",
"chdir",
"(",
"os",
".... | 47 | 24.76 |
def _mainthread_poll_readable(self):
"""Searches for readable client sockets. These sockets are then put in a subthread
to be handled by _handle_readable
"""
events = self._recv_selector.select(self.block_time)
for key, mask in events:
if mask == selectors.EVENT_READ:... | [
"def",
"_mainthread_poll_readable",
"(",
"self",
")",
":",
"events",
"=",
"self",
".",
"_recv_selector",
".",
"select",
"(",
"self",
".",
"block_time",
")",
"for",
"key",
",",
"mask",
"in",
"events",
":",
"if",
"mask",
"==",
"selectors",
".",
"EVENT_READ",... | 48.545455 | 16.090909 |
def stop(id):
"""
Stop a running job.
"""
try:
experiment = ExperimentClient().get(normalize_job_name(id))
except FloydException:
experiment = ExperimentClient().get(id)
if experiment.state not in ["queued", "queue_scheduled", "running"]:
floyd_logger.info("Job in {} sta... | [
"def",
"stop",
"(",
"id",
")",
":",
"try",
":",
"experiment",
"=",
"ExperimentClient",
"(",
")",
".",
"get",
"(",
"normalize_job_name",
"(",
"id",
")",
")",
"except",
"FloydException",
":",
"experiment",
"=",
"ExperimentClient",
"(",
")",
".",
"get",
"("... | 32.722222 | 24.388889 |
def police_priority_map_exceed_map_pri2_exceed(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
police_priority_map = ET.SubElement(config, "police-priority-map", xmlns="urn:brocade.com:mgmt:brocade-policer")
name_key = ET.SubElement(police_priority_map, ... | [
"def",
"police_priority_map_exceed_map_pri2_exceed",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"police_priority_map",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"police-priority-map\"",
... | 49.153846 | 20.153846 |
def plot(self, axis, title=None, saved=False):
"""
Plots the planar average electrostatic potential against the Long range and short range models from Freysoldt
"""
x = self.metadata['pot_plot_data'][axis]['x']
v_R = self.metadata['pot_plot_data'][axis]['Vr']
dft_diff =... | [
"def",
"plot",
"(",
"self",
",",
"axis",
",",
"title",
"=",
"None",
",",
"saved",
"=",
"False",
")",
":",
"x",
"=",
"self",
".",
"metadata",
"[",
"'pot_plot_data'",
"]",
"[",
"axis",
"]",
"[",
"'x'",
"]",
"v_R",
"=",
"self",
".",
"metadata",
"[",... | 42.628571 | 23.657143 |
def encode_int(n):
"""
Encodes an int as a variable length signed 29-bit integer as defined by
the spec.
@param n: The integer to be encoded
@return: The encoded string
@rtype: C{str}
@raise OverflowError: Out of range.
"""
global ENCODED_INT_CACHE
try:
return ENCODED_I... | [
"def",
"encode_int",
"(",
"n",
")",
":",
"global",
"ENCODED_INT_CACHE",
"try",
":",
"return",
"ENCODED_INT_CACHE",
"[",
"n",
"]",
"except",
"KeyError",
":",
"pass",
"if",
"n",
"<",
"MIN_29B_INT",
"or",
"n",
">",
"MAX_29B_INT",
":",
"raise",
"OverflowError",
... | 19.291667 | 21.833333 |
def flush_stdout(self):
"""
Empties the standard out redirect buffer and renders the
contents to the body as a preformatted text box.
"""
try:
contents = self.stdout_interceptor.flush_all()
except Exception:
return
if len(contents) > 0:
... | [
"def",
"flush_stdout",
"(",
"self",
")",
":",
"try",
":",
"contents",
"=",
"self",
".",
"stdout_interceptor",
".",
"flush_all",
"(",
")",
"except",
"Exception",
":",
"return",
"if",
"len",
"(",
"contents",
")",
">",
"0",
":",
"self",
".",
"body",
".",
... | 29.866667 | 19.066667 |
def lookup(img, **kwargs):
"""Assign values to channels based on a table."""
luts = np.array(kwargs['luts'], dtype=np.float32) / 255.0
def func(band_data, luts=luts, index=-1):
# NaN/null values will become 0
lut = luts[:, index] if len(luts.shape) == 2 else luts
band_data = band_da... | [
"def",
"lookup",
"(",
"img",
",",
"*",
"*",
"kwargs",
")",
":",
"luts",
"=",
"np",
".",
"array",
"(",
"kwargs",
"[",
"'luts'",
"]",
",",
"dtype",
"=",
"np",
".",
"float32",
")",
"/",
"255.0",
"def",
"func",
"(",
"band_data",
",",
"luts",
"=",
"... | 42.466667 | 21.866667 |
def p_arr_decl_initialized(p):
""" var_arr_decl : DIM idlist LP bound_list RP typedef RIGHTARROW const_vector
| DIM idlist LP bound_list RP typedef EQ const_vector
"""
def check_bound(boundlist, remaining):
""" Checks if constant vector bounds matches the array one
"""
... | [
"def",
"p_arr_decl_initialized",
"(",
"p",
")",
":",
"def",
"check_bound",
"(",
"boundlist",
",",
"remaining",
")",
":",
"\"\"\" Checks if constant vector bounds matches the array one\n \"\"\"",
"lineno",
"=",
"p",
".",
"lineno",
"(",
"8",
")",
"if",
"not",
"... | 36.128205 | 23.923077 |
def _make_in_prompt(self, number):
""" Given a prompt number, returns an HTML In prompt.
"""
try:
body = self.in_prompt % number
except TypeError:
# allow in_prompt to leave out number, e.g. '>>> '
body = self.in_prompt
return '<span class="in-... | [
"def",
"_make_in_prompt",
"(",
"self",
",",
"number",
")",
":",
"try",
":",
"body",
"=",
"self",
".",
"in_prompt",
"%",
"number",
"except",
"TypeError",
":",
"# allow in_prompt to leave out number, e.g. '>>> '",
"body",
"=",
"self",
".",
"in_prompt",
"return",
"... | 37.444444 | 10.777778 |
def get_timestamp(str_len=13):
""" get timestamp string, length can only between 0 and 16
"""
if isinstance(str_len, integer_types) and 0 < str_len < 17:
return builtin_str(time.time()).replace(".", "")[:str_len]
raise ParamsError("timestamp length can only between 0 and 16.") | [
"def",
"get_timestamp",
"(",
"str_len",
"=",
"13",
")",
":",
"if",
"isinstance",
"(",
"str_len",
",",
"integer_types",
")",
"and",
"0",
"<",
"str_len",
"<",
"17",
":",
"return",
"builtin_str",
"(",
"time",
".",
"time",
"(",
")",
")",
".",
"replace",
... | 42.285714 | 18.142857 |
def create_info_endpoint(self, name, data):
"""Create an endpoint to serve info GET requests."""
# make sure data is serializable
data = make_serializable(data)
# create generic restful resource to serve static JSON data
class InfoBase(Resource):
@staticmethod
... | [
"def",
"create_info_endpoint",
"(",
"self",
",",
"name",
",",
"data",
")",
":",
"# make sure data is serializable",
"data",
"=",
"make_serializable",
"(",
"data",
")",
"# create generic restful resource to serve static JSON data",
"class",
"InfoBase",
"(",
"Resource",
")"... | 40.090909 | 18.772727 |
def get_resource(self, resource_key, **variables):
"""Get a resource.
Attempts to get and return a cached version of the resource if
available, otherwise a new resource object is created and returned.
Args:
resource_key (`str`): Name of the type of `Resources` to find
... | [
"def",
"get_resource",
"(",
"self",
",",
"resource_key",
",",
"*",
"*",
"variables",
")",
":",
"handle",
"=",
"self",
".",
"make_resource_handle",
"(",
"resource_key",
",",
"*",
"*",
"variables",
")",
"return",
"self",
".",
"get_resource_from_handle",
"(",
"... | 39.133333 | 24.8 |
def set_dead_lock(self, deadLock):
"""
Set the dead lock time.
:Parameters:
#. deadLock (number): The time delay judging if the lock was left out mistakenly
after a system crash or other unexpected reasons. Normally Locker is stable
and takes care of no... | [
"def",
"set_dead_lock",
"(",
"self",
",",
"deadLock",
")",
":",
"try",
":",
"deadLock",
"=",
"float",
"(",
"deadLock",
")",
"assert",
"deadLock",
">=",
"0",
"except",
":",
"raise",
"Exception",
"(",
"'deadLock must be a positive number'",
")",
"self",
".",
"... | 39 | 20.875 |
def as_colr(self, label_args=None, value_args=None):
""" Like __str__, except it returns a colorized Colr instance. """
label_args = label_args or {'fore': 'red'}
value_args = value_args or {'fore': 'blue', 'style': 'bright'}
return Colr(self.default_format.format(
label=Colr... | [
"def",
"as_colr",
"(",
"self",
",",
"label_args",
"=",
"None",
",",
"value_args",
"=",
"None",
")",
":",
"label_args",
"=",
"label_args",
"or",
"{",
"'fore'",
":",
"'red'",
"}",
"value_args",
"=",
"value_args",
"or",
"{",
"'fore'",
":",
"'blue'",
",",
... | 50.875 | 14.125 |
def subject(self, value):
"""The subject of the email(s)
:param value: The subject of the email(s)
:type value: Subject, string
"""
if isinstance(value, Subject):
if value.personalization is not None:
try:
personalization = \
... | [
"def",
"subject",
"(",
"self",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"Subject",
")",
":",
"if",
"value",
".",
"personalization",
"is",
"not",
"None",
":",
"try",
":",
"personalization",
"=",
"self",
".",
"_personalizations",
"[",... | 37.08 | 12.8 |
def clear(self):
"""Clear all work items from the session.
This removes any associated results as well.
"""
with self._conn:
self._conn.execute('DELETE FROM results')
self._conn.execute('DELETE FROM work_items') | [
"def",
"clear",
"(",
"self",
")",
":",
"with",
"self",
".",
"_conn",
":",
"self",
".",
"_conn",
".",
"execute",
"(",
"'DELETE FROM results'",
")",
"self",
".",
"_conn",
".",
"execute",
"(",
"'DELETE FROM work_items'",
")"
] | 32.625 | 15.125 |
def witnesses(ctx):
""" List witnesses and relevant information
"""
t = [
[
"weight",
"account",
"signing_key",
"vote_id",
"url",
"total_missed",
"last_confirmed_block_num",
]
]
for witness in sorted(... | [
"def",
"witnesses",
"(",
"ctx",
")",
":",
"t",
"=",
"[",
"[",
"\"weight\"",
",",
"\"account\"",
",",
"\"signing_key\"",
",",
"\"vote_id\"",
",",
"\"url\"",
",",
"\"total_missed\"",
",",
"\"last_confirmed_block_num\"",
",",
"]",
"]",
"for",
"witness",
"in",
"... | 26.571429 | 17.071429 |
def pilcoords(self, (x,y)):
"""
Converts the coordinates (x,y) of the original array or FITS file to the current coordinates of the PIL image,
respecting cropping, rebinning, and upsampling.
This is only used once the PIL image is available, for drawing.
Note that we also have to... | [
"def",
"pilcoords",
"(",
"self",
",",
"(",
"x",
",",
"y",
")",
")",
":",
"pilx",
"=",
"int",
"(",
"(",
"x",
"-",
"1",
"-",
"self",
".",
"xa",
")",
"*",
"float",
"(",
"self",
".",
"upsamplefactor",
")",
"/",
"float",
"(",
"self",
".",
"binfact... | 51.692308 | 30 |
def process_stdin(line):
'''handle commands from user'''
if line is None:
sys.exit(0)
line = line.strip()
if not line:
return
args = shlex.split(line)
cmd = args[0]
if cmd == 'help':
k = command_map.keys()
k.sort()
for cmd in k:
(fn, help... | [
"def",
"process_stdin",
"(",
"line",
")",
":",
"if",
"line",
"is",
"None",
":",
"sys",
".",
"exit",
"(",
"0",
")",
"line",
"=",
"line",
".",
"strip",
"(",
")",
"if",
"not",
"line",
":",
"return",
"args",
"=",
"shlex",
".",
"split",
"(",
"line",
... | 22.733333 | 19.333333 |
def inject_func_as_property(self, func, method_name=None, class_=None):
"""
WARNING:
properties are more safely injected using metaclasses
References:
http://stackoverflow.com/questions/13850114/dynamically-adding-methods-with-or-without-metaclass-in-python
"""
if method_name is Non... | [
"def",
"inject_func_as_property",
"(",
"self",
",",
"func",
",",
"method_name",
"=",
"None",
",",
"class_",
"=",
"None",
")",
":",
"if",
"method_name",
"is",
"None",
":",
"method_name",
"=",
"get_funcname",
"(",
"func",
")",
"#new_method = func.__get__(self, sel... | 37.923077 | 20.384615 |
def get_name(obj, setting_name='LONG_NAME_FORMAT'):
"""
Returns the correct order of the name according to the current language.
"""
nickname = obj.get_nickname()
romanized_first_name = obj.get_romanized_first_name()
romanized_last_name = obj.get_romanized_last_name()
non_romanized_first_na... | [
"def",
"get_name",
"(",
"obj",
",",
"setting_name",
"=",
"'LONG_NAME_FORMAT'",
")",
":",
"nickname",
"=",
"obj",
".",
"get_nickname",
"(",
")",
"romanized_first_name",
"=",
"obj",
".",
"get_romanized_first_name",
"(",
")",
"romanized_last_name",
"=",
"obj",
".",... | 40.054545 | 14.927273 |
def get_configs(cls):
"""Get rate limiters configuration
specified at application level
:rtype: dict of configurations
"""
import docido_sdk.config
http_config = docido_sdk.config.get('http') or {}
session_config = http_config.get('session') or {}
rate_li... | [
"def",
"get_configs",
"(",
"cls",
")",
":",
"import",
"docido_sdk",
".",
"config",
"http_config",
"=",
"docido_sdk",
".",
"config",
".",
"get",
"(",
"'http'",
")",
"or",
"{",
"}",
"session_config",
"=",
"http_config",
".",
"get",
"(",
"'session'",
")",
"... | 34.727273 | 12.636364 |
def gray2qimage(gray, normalize = False):
"""Convert the 2D numpy array `gray` into a 8-bit, indexed QImage_
with a gray colormap. The first dimension represents the vertical
image axis.
The parameter `normalize` can be used to normalize an image's
value range to 0..255:
`normalize` = (nmin, ... | [
"def",
"gray2qimage",
"(",
"gray",
",",
"normalize",
"=",
"False",
")",
":",
"if",
"_np",
".",
"ndim",
"(",
"gray",
")",
"!=",
"2",
":",
"raise",
"ValueError",
"(",
"\"gray2QImage can only convert 2D arrays\"",
"+",
"\" (try using array2qimage)\"",
"if",
"_np",
... | 37.071429 | 24 |
def at_time(self, time, asof=False, axis=None):
"""
Select values at particular time of day (e.g. 9:30AM).
Parameters
----------
time : datetime.time or str
axis : {0 or 'index', 1 or 'columns'}, default 0
.. versionadded:: 0.24.0
Returns
--... | [
"def",
"at_time",
"(",
"self",
",",
"time",
",",
"asof",
"=",
"False",
",",
"axis",
"=",
"None",
")",
":",
"if",
"axis",
"is",
"None",
":",
"axis",
"=",
"self",
".",
"_stat_axis_number",
"axis",
"=",
"self",
".",
"_get_axis_number",
"(",
"axis",
")",... | 29.454545 | 20.327273 |
def linkify_s_by_sd(self, services):
"""Add dependency in service objects
:return: None
"""
for servicedep in self:
# Only used for debugging purpose when loops are detected
setattr(servicedep, "service_description_string", "undefined")
setattr(servic... | [
"def",
"linkify_s_by_sd",
"(",
"self",
",",
"services",
")",
":",
"for",
"servicedep",
"in",
"self",
":",
"# Only used for debugging purpose when loops are detected",
"setattr",
"(",
"servicedep",
",",
"\"service_description_string\"",
",",
"\"undefined\"",
")",
"setattr"... | 54.129032 | 30.935484 |
def augknt(knots,order):
"""Augment knot sequence such that some boundary conditions
are met."""
a = []
[a.append(knots[0]) for t in range(0,order)]
[a.append(k) for k in knots]
[a.append(knots[-1]) for t in range(0,order)]
return np.array(a) | [
"def",
"augknt",
"(",
"knots",
",",
"order",
")",
":",
"a",
"=",
"[",
"]",
"[",
"a",
".",
"append",
"(",
"knots",
"[",
"0",
"]",
")",
"for",
"t",
"in",
"range",
"(",
"0",
",",
"order",
")",
"]",
"[",
"a",
".",
"append",
"(",
"k",
")",
"fo... | 33 | 11.125 |
def compute_K_numerical(dataframe, settings=None, keep_dir=None):
"""Use a finite-element modeling code to infer geometric factors for meshes
with topography or irregular electrode spacings.
Parameters
----------
dataframe : pandas.DataFrame
the data frame that contains the data
setting... | [
"def",
"compute_K_numerical",
"(",
"dataframe",
",",
"settings",
"=",
"None",
",",
"keep_dir",
"=",
"None",
")",
":",
"inversion_code",
"=",
"reda",
".",
"rcParams",
".",
"get",
"(",
"'geom_factor.inversion_code'",
",",
"'crtomo'",
")",
"if",
"inversion_code",
... | 29.065217 | 21.021739 |
def context_processor(self, func):
""" Decorate a given function to use as a context processor.
::
@app.ps.jinja2.context_processor
def my_context():
return {...}
"""
func = to_coroutine(func)
self.providers.append(func)
return fun... | [
"def",
"context_processor",
"(",
"self",
",",
"func",
")",
":",
"func",
"=",
"to_coroutine",
"(",
"func",
")",
"self",
".",
"providers",
".",
"append",
"(",
"func",
")",
"return",
"func"
] | 28.272727 | 12.363636 |
def sector(self, start_ray, end_ray, start_distance=None, end_distance=None, units='b'):
"""Slices a sector from the selected dataset.
Slice contains the start and end rays. If start and end rays are equal
one ray is returned. If the start_ray is greater than the end_ray
slicin... | [
"def",
"sector",
"(",
"self",
",",
"start_ray",
",",
"end_ray",
",",
"start_distance",
"=",
"None",
",",
"end_distance",
"=",
"None",
",",
"units",
"=",
"'b'",
")",
":",
"if",
"self",
".",
"dataset",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'Dat... | 38.044944 | 21.101124 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.