text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def fixup_for_packaged():
''' If we are installing FROM an sdist, then a pre-built BokehJS is
already installed in the python source tree.
The command line options ``--build-js`` or ``--install-js`` are
removed from ``sys.argv``, with a warning.
Also adds ``--existing-js`` to ``sys.argv`` to signa... | [
"def",
"fixup_for_packaged",
"(",
")",
":",
"if",
"exists",
"(",
"join",
"(",
"ROOT",
",",
"'PKG-INFO'",
")",
")",
":",
"if",
"\"--build-js\"",
"in",
"sys",
".",
"argv",
"or",
"\"--install-js\"",
"in",
"sys",
".",
"argv",
":",
"print",
"(",
"SDIST_BUILD_... | 34.130435 | 19.086957 |
def parse(self, lines, root):
"""
Shortcut for #IgnoreList.parse() and #IgnoreListCollection.append().
"""
lst = IgnoreList(root)
lst.parse(lines)
self.append(lst) | [
"def",
"parse",
"(",
"self",
",",
"lines",
",",
"root",
")",
":",
"lst",
"=",
"IgnoreList",
"(",
"root",
")",
"lst",
".",
"parse",
"(",
"lines",
")",
"self",
".",
"append",
"(",
"lst",
")"
] | 22.625 | 17.125 |
def clear(self):
"""Convenience method to reset all the block values to 0
"""
if self._bit_count == 0:
return
block = self._qpart.document().begin()
while block.isValid():
if self.getBlockValue(block):
self.setBlockValue(block, 0)
... | [
"def",
"clear",
"(",
"self",
")",
":",
"if",
"self",
".",
"_bit_count",
"==",
"0",
":",
"return",
"block",
"=",
"self",
".",
"_qpart",
".",
"document",
"(",
")",
".",
"begin",
"(",
")",
"while",
"block",
".",
"isValid",
"(",
")",
":",
"if",
"self... | 30.363636 | 11.181818 |
def _EvaluateNumberOfElements(self, context):
"""Evaluates number of elements.
Args:
context (DataTypeMapContext): data type map context.
Returns:
int: number of elements.
Raises:
MappingError: if the number of elements cannot be determined.
"""
number_of_elements = None
... | [
"def",
"_EvaluateNumberOfElements",
"(",
"self",
",",
"context",
")",
":",
"number_of_elements",
"=",
"None",
"if",
"self",
".",
"_data_type_definition",
".",
"number_of_elements",
":",
"number_of_elements",
"=",
"self",
".",
"_data_type_definition",
".",
"number_of_e... | 34.055556 | 22.25 |
def user_create(name,
passwd,
database=None,
user=None,
password=None,
host=None,
port=None):
'''
Create a cluster admin or a database user.
If a database is specified: it will create database user.
If a dat... | [
"def",
"user_create",
"(",
"name",
",",
"passwd",
",",
"database",
"=",
"None",
",",
"user",
"=",
"None",
",",
"password",
"=",
"None",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
")",
":",
"if",
"user_exists",
"(",
"name",
",",
"database",
... | 25.678571 | 25.178571 |
def wordtokens(self,include_punct=True):
"""Returns a list of this object's Words in order of their appearance.
Set flattenList to False to receive a list of lists of Words."""
ws=self.ents('WordToken')
if not include_punct: return [w for w in ws if not w.is_punct]
return ws | [
"def",
"wordtokens",
"(",
"self",
",",
"include_punct",
"=",
"True",
")",
":",
"ws",
"=",
"self",
".",
"ents",
"(",
"'WordToken'",
")",
"if",
"not",
"include_punct",
":",
"return",
"[",
"w",
"for",
"w",
"in",
"ws",
"if",
"not",
"w",
".",
"is_punct",
... | 46.666667 | 11 |
def emitGeometryChanged( self, point = None ):
"""
Emits the geometryChanged signal, provided the dispatcher's \
signals are not currently blocked. If the point value is not \
provided, the object's current position will be used.
:param point | <QPointF> || No... | [
"def",
"emitGeometryChanged",
"(",
"self",
",",
"point",
"=",
"None",
")",
":",
"# check the signals blocked",
"if",
"(",
"self",
".",
"signalsBlocked",
"(",
")",
")",
":",
"return",
"False",
"# grab the point",
"if",
"(",
"point",
"==",
"None",
")",
":",
... | 31.285714 | 16.047619 |
def num_samples(self, **kwargs):
"""
Get the number of samples in this data source.
Returns
-------
int, `np.inf` or `None`.
An int if the number of samples is known, `np.inf` if it is
infinite or `None` if the number of samples is unknown.
"""
... | [
"def",
"num_samples",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"num_samples_fn",
"is",
"None",
":",
"return",
"None",
"elif",
"callable",
"(",
"self",
".",
"num_samples_fn",
")",
":",
"return",
"self",
".",
"num_samples_fn",
"("... | 32 | 14.75 |
def hil_state_quaternion_encode(self, time_usec, attitude_quaternion, rollspeed, pitchspeed, yawspeed, lat, lon, alt, vx, vy, vz, ind_airspeed, true_airspeed, xacc, yacc, zacc):
'''
Sent from simulation to autopilot, avoids in contrast to HIL_STATE
singularities. This pac... | [
"def",
"hil_state_quaternion_encode",
"(",
"self",
",",
"time_usec",
",",
"attitude_quaternion",
",",
"rollspeed",
",",
"pitchspeed",
",",
"yawspeed",
",",
"lat",
",",
"lon",
",",
"alt",
",",
"vx",
",",
"vy",
",",
"vz",
",",
"ind_airspeed",
",",
"true_airspe... | 85.461538 | 55.769231 |
def command_getkeys(self, command, *args, encoding='utf-8'):
"""Extract keys given a full Redis command."""
return self.execute(b'COMMAND', b'GETKEYS', command, *args,
encoding=encoding) | [
"def",
"command_getkeys",
"(",
"self",
",",
"command",
",",
"*",
"args",
",",
"encoding",
"=",
"'utf-8'",
")",
":",
"return",
"self",
".",
"execute",
"(",
"b'COMMAND'",
",",
"b'GETKEYS'",
",",
"command",
",",
"*",
"args",
",",
"encoding",
"=",
"encoding"... | 56.75 | 13.25 |
def sendToReplica(self, msg, frm):
"""
Send the message to the intended replica.
:param msg: the message to send
:param frm: the name of the node which sent this `msg`
"""
# TODO: discard or stash messages here instead of doing
# this in msgHas* methods!!!
... | [
"def",
"sendToReplica",
"(",
"self",
",",
"msg",
",",
"frm",
")",
":",
"# TODO: discard or stash messages here instead of doing",
"# this in msgHas* methods!!!",
"if",
"self",
".",
"msgHasAcceptableInstId",
"(",
"msg",
",",
"frm",
")",
":",
"self",
".",
"replicas",
... | 37.818182 | 12.363636 |
def truncate_string(text, strip_html=True, chars=255, truncate='…', at_word_boundary=False):
"""Truncate a string to a certain length, removing line breaks and mutliple
spaces, optionally removing HTML, and appending a 'truncate' string.
Keyword arguments:
strip_html -- boolean.
chars -- Number of ... | [
"def",
"truncate_string",
"(",
"text",
",",
"strip_html",
"=",
"True",
",",
"chars",
"=",
"255",
",",
"truncate",
"=",
"'…', ",
"a",
"_word_boundary=F",
"a",
"lse):",
"",
"",
"if",
"strip_html",
":",
"text",
"=",
"strip_tags",
"(",
"text",
")",
"text",
... | 40.52381 | 18.619048 |
def get(self, key, default=None, reraise=False):
"""
Get the given key from the cache, if present.
A default value can be provided in case the requested key is not present,
otherwise, None will be returned.
:param key: the key to query
:type key: str
:param defau... | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
",",
"reraise",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"enabled",
":",
"if",
"reraise",
":",
"raise",
"exceptions",
".",
"DisabledCache",
"(",
")",
"return",
"default",
"t... | 28.897436 | 20.230769 |
def get_brizo_url(config):
"""
Return the Brizo component url.
:param config: Config
:return: Url, str
"""
brizo_url = 'http://localhost:8030'
if config.has_option('resources', 'brizo.url'):
brizo_url = config.get('resources', 'brizo.url') or brizo_ur... | [
"def",
"get_brizo_url",
"(",
"config",
")",
":",
"brizo_url",
"=",
"'http://localhost:8030'",
"if",
"config",
".",
"has_option",
"(",
"'resources'",
",",
"'brizo.url'",
")",
":",
"brizo_url",
"=",
"config",
".",
"get",
"(",
"'resources'",
",",
"'brizo.url'",
"... | 29.923077 | 13.615385 |
def pull(self, source=''):
"""
Downloads and registers a user environment from a git repository
Args:
source: the source where to download the envname (expected 'github.com/user/repo[@branch]')
Note: the user environment will be registered as (username/EnvName-vVersion)
... | [
"def",
"pull",
"(",
"self",
",",
"source",
"=",
"''",
")",
":",
"# Checking syntax",
"branch_parts",
"=",
"source",
".",
"split",
"(",
"'@'",
")",
"if",
"len",
"(",
"branch_parts",
")",
"==",
"2",
":",
"branch",
"=",
"branch_parts",
"[",
"1",
"]",
"s... | 50.166667 | 28.518519 |
def filter_by_slurry(self, slurry, appender="_"):
"""Filters sheet/table by slurry name.
Input is slurry name or list of slurry names, for example 'es030' or
["es012","es033","es031"].
Args:
slurry (str or list of strings): slurry names.
appender (chr): char tha... | [
"def",
"filter_by_slurry",
"(",
"self",
",",
"slurry",
",",
"appender",
"=",
"\"_\"",
")",
":",
"sheet",
"=",
"self",
".",
"table",
"identity",
"=",
"self",
".",
"db_sheet_cols",
".",
"id",
"exists",
"=",
"self",
".",
"db_sheet_cols",
".",
"exists",
"cel... | 28.975 | 17.5 |
def close(self):
'''close the graph'''
self.close_graph.set()
if self.is_alive():
self.child.join(2) | [
"def",
"close",
"(",
"self",
")",
":",
"self",
".",
"close_graph",
".",
"set",
"(",
")",
"if",
"self",
".",
"is_alive",
"(",
")",
":",
"self",
".",
"child",
".",
"join",
"(",
"2",
")"
] | 26.4 | 13.6 |
def set_config(new_config={}):
""" Reset config options to defaults, and then update (optionally)
with the provided dictionary of options. """
# The default base configuration.
flask_app.base_config = dict(working_directory='.',
template='collapse-input',
... | [
"def",
"set_config",
"(",
"new_config",
"=",
"{",
"}",
")",
":",
"# The default base configuration.",
"flask_app",
".",
"base_config",
"=",
"dict",
"(",
"working_directory",
"=",
"'.'",
",",
"template",
"=",
"'collapse-input'",
",",
"debug",
"=",
"False",
",",
... | 46.222222 | 7.333333 |
def _generate_examples(self, images_dir_path, labels_path, setid_path,
split_name):
"""Yields examples."""
with tf.io.gfile.GFile(labels_path, "rb") as f:
labels = tfds.core.lazy_imports.scipy.io.loadmat(f)["labels"][0]
with tf.io.gfile.GFile(setid_path, "rb") as f:
exam... | [
"def",
"_generate_examples",
"(",
"self",
",",
"images_dir_path",
",",
"labels_path",
",",
"setid_path",
",",
"split_name",
")",
":",
"with",
"tf",
".",
"io",
".",
"gfile",
".",
"GFile",
"(",
"labels_path",
",",
"\"rb\"",
")",
"as",
"f",
":",
"labels",
"... | 40.6 | 17.666667 |
def DeleteOldRuns(self, cutoff_timestamp=None):
"""Deletes runs that were started before the timestamp given."""
if cutoff_timestamp is None:
raise ValueError("cutoff_timestamp can't be None")
return data_store.REL_DB.DeleteOldCronJobRuns(
cutoff_timestamp=cutoff_timestamp) | [
"def",
"DeleteOldRuns",
"(",
"self",
",",
"cutoff_timestamp",
"=",
"None",
")",
":",
"if",
"cutoff_timestamp",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"cutoff_timestamp can't be None\"",
")",
"return",
"data_store",
".",
"REL_DB",
".",
"DeleteOldCronJobRuns... | 42.142857 | 11.857143 |
def logout(self):
"""Explicit Skybell logout."""
if self.cache(CONST.ACCESS_TOKEN):
# No explicit logout call as it doesn't seem to matter
# if a logout happens without registering the app which
# we aren't currently doing.
self._session = requests.session... | [
"def",
"logout",
"(",
"self",
")",
":",
"if",
"self",
".",
"cache",
"(",
"CONST",
".",
"ACCESS_TOKEN",
")",
":",
"# No explicit logout call as it doesn't seem to matter",
"# if a logout happens without registering the app which",
"# we aren't currently doing.",
"self",
".",
... | 35.333333 | 17.5 |
def rotate_view(self, axis_ind=0, angle=0):
"""
Rotate the camera view.
Args:
axis_ind: Index of axis to rotate. Defaults to 0, i.e., a-axis.
angle: Angle to rotate by. Defaults to 0.
"""
camera = self.ren.GetActiveCamera()
if axis_ind == 0:
... | [
"def",
"rotate_view",
"(",
"self",
",",
"axis_ind",
"=",
"0",
",",
"angle",
"=",
"0",
")",
":",
"camera",
"=",
"self",
".",
"ren",
".",
"GetActiveCamera",
"(",
")",
"if",
"axis_ind",
"==",
"0",
":",
"camera",
".",
"Roll",
"(",
"angle",
")",
"elif",... | 29.25 | 13.875 |
def _render(self):
"""
Render the text.
Avoid using this fonction too many time as it is slow as it is low to render text and blit it.
"""
self._last_text = self.text
self._surface = self.font.render(self.text, True, self.color, self.bg_color)
rect = self._surf... | [
"def",
"_render",
"(",
"self",
")",
":",
"self",
".",
"_last_text",
"=",
"self",
".",
"text",
"self",
".",
"_surface",
"=",
"self",
".",
"font",
".",
"render",
"(",
"self",
".",
"text",
",",
"True",
",",
"self",
".",
"color",
",",
"self",
".",
"b... | 27.153846 | 24.692308 |
def lists(self, uid=0, **kwargs):
"""
Returns a list of :class:`List` objects (lists which Contact belongs to) and a pager dict.
:Example:
lists, pager = client.contacts.lists(uid=1901010)
:param int uid: The unique id of the Contact to update. Required.
:param int p... | [
"def",
"lists",
"(",
"self",
",",
"uid",
"=",
"0",
",",
"*",
"*",
"kwargs",
")",
":",
"lists",
"=",
"Lists",
"(",
"self",
".",
"base_uri",
",",
"self",
".",
"auth",
")",
"return",
"self",
".",
"get_subresource_instances",
"(",
"uid",
",",
"instance",... | 41.333333 | 25.2 |
def extract_from_urllib3():
"""
Undo monkey-patching by :func:`inject_into_urllib3`.
"""
util.ssl_.SSLContext = orig_util_SSLContext
util.HAS_SNI = orig_util_HAS_SNI
util.ssl_.HAS_SNI = orig_util_HAS_SNI
util.IS_SECURETRANSPORT = False
util.ssl_.IS_SECURETRANSPORT = False | [
"def",
"extract_from_urllib3",
"(",
")",
":",
"util",
".",
"ssl_",
".",
"SSLContext",
"=",
"orig_util_SSLContext",
"util",
".",
"HAS_SNI",
"=",
"orig_util_HAS_SNI",
"util",
".",
"ssl_",
".",
"HAS_SNI",
"=",
"orig_util_HAS_SNI",
"util",
".",
"IS_SECURETRANSPORT",
... | 32.888889 | 5.111111 |
def create_activity(self, activity_form):
"""Creates a new ``Activity``.
arg: activity_form (osid.learning.ActivityForm): the form for
this ``Activity``
return: (osid.learning.Activity) - the new ``Activity``
raise: IllegalState - ``activity_form`` already used in a
... | [
"def",
"create_activity",
"(",
"self",
",",
"activity_form",
")",
":",
"# Implemented from template for",
"# osid.resource.ResourceAdminSession.create_resource_template",
"collection",
"=",
"JSONClientValidated",
"(",
"'learning'",
",",
"collection",
"=",
"'Activity'",
",",
"... | 49.674419 | 23.232558 |
def check_off_chain_batch_roles(self, batch):
""" Check the batch signing key against the allowed off-chain
transactor permissions. The roles being checked are the following,
from first to last:
"transactor.batch_signer"
"transactor"
The first... | [
"def",
"check_off_chain_batch_roles",
"(",
"self",
",",
"batch",
")",
":",
"if",
"self",
".",
"_permissions",
"is",
"None",
":",
"return",
"True",
"header",
"=",
"BatchHeader",
"(",
")",
"header",
".",
"ParseFromString",
"(",
"batch",
".",
"header",
")",
"... | 37.263158 | 21.263158 |
def setvcpus(vm_, vcpus):
'''
Changes the amount of vcpus allocated to VM.
vcpus is an int representing the number to be assigned
CLI Example:
.. code-block:: bash
salt '*' virt.setvcpus myvm 2
'''
with _get_xapi_session() as xapi:
vm_uuid = _get_label_uuid(xapi, 'VM', vm... | [
"def",
"setvcpus",
"(",
"vm_",
",",
"vcpus",
")",
":",
"with",
"_get_xapi_session",
"(",
")",
"as",
"xapi",
":",
"vm_uuid",
"=",
"_get_label_uuid",
"(",
"xapi",
",",
"'VM'",
",",
"vm_",
")",
"if",
"vm_uuid",
"is",
"False",
":",
"return",
"False",
"try"... | 23.904762 | 21.142857 |
def calcTransferResistance(self, gid, seg_coords):
"""Precompute mapping from segment to electrode locations"""
sigma = 0.3 # mS/mm
# Value used in NEURON extracellular recording example ("extracellular_stim_and_rec")
# rho = 35.4 # ohm cm, squid axon cytoplasm = 2.8249e-2 S/cm = 0.0... | [
"def",
"calcTransferResistance",
"(",
"self",
",",
"gid",
",",
"seg_coords",
")",
":",
"sigma",
"=",
"0.3",
"# mS/mm ",
"# Value used in NEURON extracellular recording example (\"extracellular_stim_and_rec\")",
"# rho = 35.4 # ohm cm, squid axon cytoplasm = 2.8249e-2 S/cm = 0.028 S/cm... | 59.179487 | 35.641026 |
def GetRadioButtonSelect(selectList, title="Select", msg=""):
"""
Create radio button window for option selection
title: Window name
mag: Label of the radio button
return (seldctedItem, selectedindex)
"""
root = tkinter.Tk()
root.title(title)
val = tkinter.IntVar()
val.set(0)
... | [
"def",
"GetRadioButtonSelect",
"(",
"selectList",
",",
"title",
"=",
"\"Select\"",
",",
"msg",
"=",
"\"\"",
")",
":",
"root",
"=",
"tkinter",
".",
"Tk",
"(",
")",
"root",
".",
"title",
"(",
"title",
")",
"val",
"=",
"tkinter",
".",
"IntVar",
"(",
")"... | 25.862069 | 20.413793 |
def is_success(self):
''' check all sessions to see if they have completed successfully '''
for _session in self._sessions.values():
if not _session.is_success():
return False
return True | [
"def",
"is_success",
"(",
"self",
")",
":",
"for",
"_session",
"in",
"self",
".",
"_sessions",
".",
"values",
"(",
")",
":",
"if",
"not",
"_session",
".",
"is_success",
"(",
")",
":",
"return",
"False",
"return",
"True"
] | 39.166667 | 16.5 |
def IS(instance, other): # noqa
"""
Support the `future is other` use-case.
Can't override the language so we built a function.
Will work on non-future objects too.
:param instance: future or any python object
:param other: object to compare.
:return:
"""
try:
instance = in... | [
"def",
"IS",
"(",
"instance",
",",
"other",
")",
":",
"# noqa",
"try",
":",
"instance",
"=",
"instance",
".",
"_redpipe_future_result",
"# noqa",
"except",
"AttributeError",
":",
"pass",
"try",
":",
"other",
"=",
"other",
".",
"_redpipe_future_result",
"except... | 23.904762 | 17.52381 |
def imagetransformerpp_sep_channels_8l_8h():
"""separate rgb embeddings."""
hparams = imagetransformer_base()
hparams.likelihood = cia.DistributionType.DMOL
hparams.num_channels = 1
hparams.bottom["targets"] = modalities.image_channel_compress_targets_bottom
hparams.top["targets"] = modalities.identity_top
... | [
"def",
"imagetransformerpp_sep_channels_8l_8h",
"(",
")",
":",
"hparams",
"=",
"imagetransformer_base",
"(",
")",
"hparams",
".",
"likelihood",
"=",
"cia",
".",
"DistributionType",
".",
"DMOL",
"hparams",
".",
"num_channels",
"=",
"1",
"hparams",
".",
"bottom",
... | 37.526316 | 12.052632 |
def samples(self, nsamples, rstate=None):
"""
Draw `nsamples` samples randomly distributed within the unit cube.
Returns
-------
x : `~numpy.ndarray` with shape (nsamples, ndim)
A collection of coordinates within the unit cube.
"""
if rstate is None... | [
"def",
"samples",
"(",
"self",
",",
"nsamples",
",",
"rstate",
"=",
"None",
")",
":",
"if",
"rstate",
"is",
"None",
":",
"rstate",
"=",
"np",
".",
"random",
"xs",
"=",
"np",
".",
"array",
"(",
"[",
"self",
".",
"sample",
"(",
"rstate",
"=",
"rsta... | 25.470588 | 23.823529 |
def nvmlEventSetWait(eventSet, timeoutms):
r"""
/**
* Waits on events and delivers events
*
* For Fermi &tm; or newer fully supported devices.
*
* If some events are ready to be delivered at the time of the call, function returns immediately.
* If there are no events ready to be de... | [
"def",
"nvmlEventSetWait",
"(",
"eventSet",
",",
"timeoutms",
")",
":",
"fn",
"=",
"_nvmlGetFunctionPointer",
"(",
"\"nvmlEventSetWait\"",
")",
"data",
"=",
"c_nvmlEventData_t",
"(",
")",
"ret",
"=",
"fn",
"(",
"eventSet",
",",
"byref",
"(",
"data",
")",
","... | 51.526316 | 32.552632 |
def set_related_method(self, resource, full_resource_url):
"""
Using reflection, generate the related method and return it.
"""
method_name = self.get_method_name(resource, 'get')
def get(self, **kwargs):
return self._call_api_single_related_resource(
... | [
"def",
"set_related_method",
"(",
"self",
",",
"resource",
",",
"full_resource_url",
")",
":",
"method_name",
"=",
"self",
".",
"get_method_name",
"(",
"resource",
",",
"'get'",
")",
"def",
"get",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
... | 32.076923 | 18.769231 |
def get_containing(self, name, depth = 0):
"""Return the n-th (n = ``depth``) context containing attribute named ``name``."""
ctx_dict = object.__getattribute__(self, '__dict__')
if name in ctx_dict:
if depth <= 0:
return self
depth -= 1
parent = c... | [
"def",
"get_containing",
"(",
"self",
",",
"name",
",",
"depth",
"=",
"0",
")",
":",
"ctx_dict",
"=",
"object",
".",
"__getattribute__",
"(",
"self",
",",
"'__dict__'",
")",
"if",
"name",
"in",
"ctx_dict",
":",
"if",
"depth",
"<=",
"0",
":",
"return",
... | 40.090909 | 11.545455 |
def _tot_services_by_state(self, services, state):
"""Get the number of service in the specified state
:param state: state to filter service
:type state:
:return: number of service with s.state_id == state
:rtype: int
"""
return str(sum(1 for s in self.services
... | [
"def",
"_tot_services_by_state",
"(",
"self",
",",
"services",
",",
"state",
")",
":",
"return",
"str",
"(",
"sum",
"(",
"1",
"for",
"s",
"in",
"self",
".",
"services",
"if",
"services",
"[",
"s",
"]",
".",
"state_id",
"==",
"state",
")",
")"
] | 36.7 | 13.9 |
def get_content_charset(self, failobj=None):
"""Return the charset parameter of the Content-Type header.
The returned string is always coerced to lower case. If there is no
Content-Type header, or if that header has no charset parameter,
failobj is returned.
"""
missing... | [
"def",
"get_content_charset",
"(",
"self",
",",
"failobj",
"=",
"None",
")",
":",
"missing",
"=",
"object",
"(",
")",
"charset",
"=",
"self",
".",
"get_param",
"(",
"'charset'",
",",
"missing",
")",
"if",
"charset",
"is",
"missing",
":",
"return",
"failo... | 43.586207 | 16.482759 |
def match_entry_line(str_to_match, regex_obj=MAIN_REGEX_OBJ):
"""Does a regex match of the mount entry string"""
match_obj = regex_obj.match(str_to_match)
if not match_obj:
error_message = ('Line "%s" is unrecognized by overlay4u. '
'This is only meant for use with Ubuntu Linux.')
... | [
"def",
"match_entry_line",
"(",
"str_to_match",
",",
"regex_obj",
"=",
"MAIN_REGEX_OBJ",
")",
":",
"match_obj",
"=",
"regex_obj",
".",
"match",
"(",
"str_to_match",
")",
"if",
"not",
"match_obj",
":",
"error_message",
"=",
"(",
"'Line \"%s\" is unrecognized by overl... | 51.25 | 16.25 |
def _to_dict(self):
"""Return a json dictionary representing this model."""
_dict = {}
if hasattr(self, 'input') and self.input is not None:
_dict['input'] = self.input._to_dict()
return _dict | [
"def",
"_to_dict",
"(",
"self",
")",
":",
"_dict",
"=",
"{",
"}",
"if",
"hasattr",
"(",
"self",
",",
"'input'",
")",
"and",
"self",
".",
"input",
"is",
"not",
"None",
":",
"_dict",
"[",
"'input'",
"]",
"=",
"self",
".",
"input",
".",
"_to_dict",
... | 38.5 | 15.666667 |
def buildErrorResponse(self, request, error=None):
"""
Builds an error response.
@param request: The AMF request
@type request: L{Request<pyamf.remoting.Request>}
@return: The AMF response
@rtype: L{Response<pyamf.remoting.Response>}
"""
if error is not N... | [
"def",
"buildErrorResponse",
"(",
"self",
",",
"request",
",",
"error",
"=",
"None",
")",
":",
"if",
"error",
"is",
"not",
"None",
":",
"cls",
",",
"e",
",",
"tb",
"=",
"error",
"else",
":",
"cls",
",",
"e",
",",
"tb",
"=",
"sys",
".",
"exc_info"... | 32.1875 | 13.8125 |
def _parse_address(self, config):
"""Parses the config block and returns the ip address value
The provided configuration block is scaned and the configured value
for the IP address is returned as a dict object. If the IP address
value is not configured, then None is returned for the va... | [
"def",
"_parse_address",
"(",
"self",
",",
"config",
")",
":",
"match",
"=",
"re",
".",
"search",
"(",
"r'ip address ([^\\s]+)'",
",",
"config",
")",
"value",
"=",
"match",
".",
"group",
"(",
"1",
")",
"if",
"match",
"else",
"None",
"return",
"dict",
"... | 40.0625 | 23.3125 |
def scale(self, vmin=0., vmax=1.):
"""Transforms the colorscale so that the minimal and maximal values
fit the given parameters.
"""
return StepColormap(
self.colors,
index=[vmin + (vmax-vmin)*(x-self.vmin)*1./(self.vmax-self.vmin) for x in self.index], # noqa
... | [
"def",
"scale",
"(",
"self",
",",
"vmin",
"=",
"0.",
",",
"vmax",
"=",
"1.",
")",
":",
"return",
"StepColormap",
"(",
"self",
".",
"colors",
",",
"index",
"=",
"[",
"vmin",
"+",
"(",
"vmax",
"-",
"vmin",
")",
"*",
"(",
"x",
"-",
"self",
".",
... | 36.8 | 17 |
def combined_stop_to_stop_transit_network(gtfs, start_time_ut=None, end_time_ut=None):
"""
Compute stop-to-stop networks for all travel modes and combine them into a single network.
The modes of transport are encoded to a single network.
The network consists of multiple links corresponding to each trave... | [
"def",
"combined_stop_to_stop_transit_network",
"(",
"gtfs",
",",
"start_time_ut",
"=",
"None",
",",
"end_time_ut",
"=",
"None",
")",
":",
"multi_di_graph",
"=",
"networkx",
".",
"MultiDiGraph",
"(",
")",
"for",
"route_type",
"in",
"route_types",
".",
"TRANSIT_ROU... | 42.84 | 25 |
def isFocused(self):
'''
Gets the focused value
@return: the focused value. If the property cannot be found returns C{False}
'''
try:
return True if self.map[self.isFocusedProperty].lower() == 'true' else False
except Exception:
return False | [
"def",
"isFocused",
"(",
"self",
")",
":",
"try",
":",
"return",
"True",
"if",
"self",
".",
"map",
"[",
"self",
".",
"isFocusedProperty",
"]",
".",
"lower",
"(",
")",
"==",
"'true'",
"else",
"False",
"except",
"Exception",
":",
"return",
"False"
] | 27.727273 | 29 |
def normalize_exception(exc):
"""
Given a SyntaxError from a marker evaluation, normalize the error
message:
- Remove indications of filename and line number.
- Replace platform-specific error messages with standard error
messages.
"""
subs = {
... | [
"def",
"normalize_exception",
"(",
"exc",
")",
":",
"subs",
"=",
"{",
"'unexpected EOF while parsing'",
":",
"'invalid syntax'",
",",
"'parenthesis is never closed'",
":",
"'invalid syntax'",
",",
"}",
"exc",
".",
"filename",
"=",
"None",
"exc",
".",
"lineno",
"="... | 34.3125 | 17.9375 |
def get_surface_as_bytes(self, order=None):
"""Returns the surface area as a bytes encoded RGB image buffer.
Subclass should override if there is a more efficient conversion
than from generating a numpy array first.
"""
arr8 = self.get_surface_as_array(order=order)
return... | [
"def",
"get_surface_as_bytes",
"(",
"self",
",",
"order",
"=",
"None",
")",
":",
"arr8",
"=",
"self",
".",
"get_surface_as_array",
"(",
"order",
"=",
"order",
")",
"return",
"arr8",
".",
"tobytes",
"(",
"order",
"=",
"'C'",
")"
] | 48.285714 | 8.428571 |
def build_person(self, doc, entity):
"""Builds an organization object of of a string representation.
Returns built organization. Raises SPDXValueError if failed to extract
name.
"""
match = self.person_re.match(entity)
if match and validations.validate_person_name(match.g... | [
"def",
"build_person",
"(",
"self",
",",
"doc",
",",
"entity",
")",
":",
"match",
"=",
"self",
".",
"person_re",
".",
"match",
"(",
"entity",
")",
"if",
"match",
"and",
"validations",
".",
"validate_person_name",
"(",
"match",
".",
"group",
"(",
"self",
... | 50.2 | 20.866667 |
def unzip_file(i):
"""
Input: {
archive_file - full path to zip file
(path) - path where unzip (current if empty)
(overwrite) - if 'yes', overwrite
(delete_after_unzip) - if 'yes', delete original zip file after unzipping
... | [
"def",
"unzip_file",
"(",
"i",
")",
":",
"import",
"zipfile",
"p",
"=",
"i",
".",
"get",
"(",
"'path'",
",",
"''",
")",
"if",
"p",
"==",
"''",
":",
"p",
"=",
"os",
".",
"getcwd",
"(",
")",
"p3",
"=",
"i",
"[",
"'archive_file'",
"]",
"overwrite"... | 25.965517 | 22.862069 |
def values_list(self, *fields, **kwargs):
"""
Ask the collection to return a list of tuples of given fields (in the
given order) for each instance found in the collection.
If 'flat=True' is passed, the resulting list will be flat, ie without
tuple. It's a valid kwarg only if only... | [
"def",
"values_list",
"(",
"self",
",",
"*",
"fields",
",",
"*",
"*",
"kwargs",
")",
":",
"flat",
"=",
"kwargs",
".",
"pop",
"(",
"'flat'",
",",
"False",
")",
"if",
"kwargs",
":",
"raise",
"ValueError",
"(",
"'Unexpected keyword arguments for the values meth... | 41.125 | 23.041667 |
def html_to_file(html, file_path=None, open_browser=False):
"""Save the html to an html file adapting the paths to the filesystem.
if a file_path is passed, it is used, if not a unique_filename is
generated.
:param html: the html for the output file.
:type html: str
:param file_path: the path... | [
"def",
"html_to_file",
"(",
"html",
",",
"file_path",
"=",
"None",
",",
"open_browser",
"=",
"False",
")",
":",
"if",
"file_path",
"is",
"None",
":",
"file_path",
"=",
"unique_filename",
"(",
"suffix",
"=",
"'.html'",
")",
"# Ensure html is in unicode for codecs... | 30 | 21.96 |
def update(self, incoming_stream, seek=0, size=None, chunk_size=None,
progress_callback=None):
"""Update a file in the file system."""
fp = self.open(mode='r+b')
try:
fp.seek(seek)
bytes_written, checksum = self._write_stream(
incoming_strea... | [
"def",
"update",
"(",
"self",
",",
"incoming_stream",
",",
"seek",
"=",
"0",
",",
"size",
"=",
"None",
",",
"chunk_size",
"=",
"None",
",",
"progress_callback",
"=",
"None",
")",
":",
"fp",
"=",
"self",
".",
"open",
"(",
"mode",
"=",
"'r+b'",
")",
... | 37 | 17.076923 |
def check_firmware_update_component(func):
"""Checks the firmware update component."""
@six.wraps(func)
def wrapper(self, filename, component_type):
"""Wrapper around ``update_firmware`` call.
:param filename: location of the raw firmware file.
:param component_type: Type of compone... | [
"def",
"check_firmware_update_component",
"(",
"func",
")",
":",
"@",
"six",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"self",
",",
"filename",
",",
"component_type",
")",
":",
"\"\"\"Wrapper around ``update_firmware`` call.\n\n :param filename: loca... | 41.85 | 18.6 |
def _init_step(self):
"""Initialize next step of simulation to be run.
"""
self._age += 1
self.env.age = self._age
self._log(logging.INFO, "")
self._log(logging.INFO, "\t***** Step {:0>4} *****". format(self.age))
self._log(logging.INFO, "")
self._agents_t... | [
"def",
"_init_step",
"(",
"self",
")",
":",
"self",
".",
"_age",
"+=",
"1",
"self",
".",
"env",
".",
"age",
"=",
"self",
".",
"_age",
"self",
".",
"_log",
"(",
"logging",
".",
"INFO",
",",
"\"\"",
")",
"self",
".",
"_log",
"(",
"logging",
".",
... | 38.818182 | 10 |
def debug(msg):
'''
Displays debug messages to stderr only if the Python interpreter was invoked with the -O flag.
'''
if DEBUG:
sys.stderr.write("DEBUG: " + msg + "\n")
sys.stderr.flush() | [
"def",
"debug",
"(",
"msg",
")",
":",
"if",
"DEBUG",
":",
"sys",
".",
"stderr",
".",
"write",
"(",
"\"DEBUG: \"",
"+",
"msg",
"+",
"\"\\n\"",
")",
"sys",
".",
"stderr",
".",
"flush",
"(",
")"
] | 30.571429 | 28.285714 |
def delete_pidfile(rundir, process_type=PROCESS_TYPE, name=None, force=False):
"""
Delete the pid file in the run directory, using the given process type
and process name for the filename.
@param force: if errors due to the file not existing should be ignored
@type force: bool
@rtype: str
... | [
"def",
"delete_pidfile",
"(",
"rundir",
",",
"process_type",
"=",
"PROCESS_TYPE",
",",
"name",
"=",
"None",
",",
"force",
"=",
"False",
")",
":",
"from",
"feat",
".",
"common",
".",
"run",
"import",
"get_pidpath",
"log",
".",
"debug",
"(",
"process_type",
... | 30.590909 | 19.863636 |
def get_current_usage_str(self):
"""
Get the a string describing the current usage for this limit.
If no usage has been added for this limit, the result will be
"<unknown>".
If the limit has only one current usage instance, this will be
that instance's :py:meth:`~.AwsLi... | [
"def",
"get_current_usage_str",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"_current_usage",
")",
"==",
"0",
":",
"return",
"'<unknown>'",
"if",
"len",
"(",
"self",
".",
"_current_usage",
")",
"==",
"1",
":",
"return",
"str",
"(",
"self",
".... | 38.366667 | 20.3 |
def containerize(coll):
"""Walk attribute fields passed from an SBP message and convert to
Containers where appropriate. Needed for Construct proper
serialization.
Parameters
----------
coll : dict
"""
if isinstance(coll, Container):
[setattr(coll, k, containerize(v)) for (k, v) in coll.items()]
... | [
"def",
"containerize",
"(",
"coll",
")",
":",
"if",
"isinstance",
"(",
"coll",
",",
"Container",
")",
":",
"[",
"setattr",
"(",
"coll",
",",
"k",
",",
"containerize",
"(",
"v",
")",
")",
"for",
"(",
"k",
",",
"v",
")",
"in",
"coll",
".",
"items",... | 25.818182 | 18.681818 |
def create_signature(public_key, private_key, data, scheme='ecdsa-sha2-nistp256'):
"""
<Purpose>
Return a (signature, scheme) tuple.
>>> requested_scheme = 'ecdsa-sha2-nistp256'
>>> public, private = generate_public_and_private(requested_scheme)
>>> data = b'The quick brown fox jumps over the lazy ... | [
"def",
"create_signature",
"(",
"public_key",
",",
"private_key",
",",
"data",
",",
"scheme",
"=",
"'ecdsa-sha2-nistp256'",
")",
":",
"# Do 'public_key' and 'private_key' have the correct format?",
"# This check will ensure that the arguments conform to",
"# 'securesystemslib.formats... | 35.1125 | 26.6375 |
def listen(bot, receivers=None, token=None, port=10245, status_report=False, status_receiver=None,
status_interval=DEFAULT_REPORT_TIME):
"""
传入 bot 实例并启动 wechat_sender 服务
:param bot: (必填|Bot对象) - wxpy 的 Bot 对象实例
:param receivers: (选填|wxpy.Chat 对象|Chat 对象列表) - 消息接收者,wxpy 的 Chat 对象实例, 或 Chat 对... | [
"def",
"listen",
"(",
"bot",
",",
"receivers",
"=",
"None",
",",
"token",
"=",
"None",
",",
"port",
"=",
"10245",
",",
"status_report",
"=",
"False",
",",
"status_receiver",
"=",
"None",
",",
"status_interval",
"=",
"DEFAULT_REPORT_TIME",
")",
":",
"global... | 49.5 | 30.5 |
def expand_effect_repertoire(self, repertoire, new_purview=None):
"""Alias for |expand_repertoire()| with ``direction`` set to |EFFECT|.
"""
return self.expand_repertoire(Direction.EFFECT, repertoire,
new_purview) | [
"def",
"expand_effect_repertoire",
"(",
"self",
",",
"repertoire",
",",
"new_purview",
"=",
"None",
")",
":",
"return",
"self",
".",
"expand_repertoire",
"(",
"Direction",
".",
"EFFECT",
",",
"repertoire",
",",
"new_purview",
")"
] | 54.2 | 12.4 |
def header_match(cls, data):
'''
Parse a member namestrs header (1 line, 80 bytes).
'''
mo = cls.header_re.match(data)
return int(mo['n_variables']) | [
"def",
"header_match",
"(",
"cls",
",",
"data",
")",
":",
"mo",
"=",
"cls",
".",
"header_re",
".",
"match",
"(",
"data",
")",
"return",
"int",
"(",
"mo",
"[",
"'n_variables'",
"]",
")"
] | 30.5 | 15.5 |
def _create_entry(self, location, element, unique=True, delete_element=False):
"""
Create an entry located at ``location``.
Args:
location: String or :class:`LocationDescriptor` to describe a "separator location" (i.e. dir1/dir2/dir3 for
instance).
... | [
"def",
"_create_entry",
"(",
"self",
",",
"location",
",",
"element",
",",
"unique",
"=",
"True",
",",
"delete_element",
"=",
"False",
")",
":",
"loc_descriptor",
"=",
"self",
".",
"_get_location_descriptor",
"(",
"location",
")",
"# find parent node",
"parent_n... | 43.311111 | 26.688889 |
def set_reprdict_from_attributes(self):
"""
set_reprdict_from_attributes
"""
reprcopy = self.m_reprdict.copy()
for kd, d in reprcopy.items():
for k in d.keys():
if hasattr(self, k):
self.m_reprdict[kd][k] = getattr(self, k) | [
"def",
"set_reprdict_from_attributes",
"(",
"self",
")",
":",
"reprcopy",
"=",
"self",
".",
"m_reprdict",
".",
"copy",
"(",
")",
"for",
"kd",
",",
"d",
"in",
"reprcopy",
".",
"items",
"(",
")",
":",
"for",
"k",
"in",
"d",
".",
"keys",
"(",
")",
":"... | 30.3 | 8.3 |
def _decode_transfer_block_data(self, data):
"""
Take a byte array and extract the data from it
Decode the response returned by a DAP_TransferBlock CMSIS-DAP command
and return it as an array of bytes.
"""
assert self.get_empty() is False
if data[0] != Command.DA... | [
"def",
"_decode_transfer_block_data",
"(",
"self",
",",
"data",
")",
":",
"assert",
"self",
".",
"get_empty",
"(",
")",
"is",
"False",
"if",
"data",
"[",
"0",
"]",
"!=",
"Command",
".",
"DAP_TRANSFER_BLOCK",
":",
"raise",
"ValueError",
"(",
"'DAP_TRANSFER_BL... | 41.615385 | 16.307692 |
def fill_archive(self, stream=None, kind='tgz', prefix=None,
subrepos=False):
"""
Fills up given stream.
:param stream: file like object.
:param kind: one of following: ``zip``, ``tgz`` or ``tbz2``.
Default: ``tgz``.
:param prefix: name of root d... | [
"def",
"fill_archive",
"(",
"self",
",",
"stream",
"=",
"None",
",",
"kind",
"=",
"'tgz'",
",",
"prefix",
"=",
"None",
",",
"subrepos",
"=",
"False",
")",
":",
"allowed_kinds",
"=",
"settings",
".",
"ARCHIVE_SPECS",
".",
"keys",
"(",
")",
"if",
"kind",... | 39.119048 | 19.214286 |
def to_volume(mesh,
file_name=None,
max_element=None,
mesher_id=1):
"""
Convert a surface mesh to a 3D volume mesh generated by gmsh.
An easy way to install the gmsh sdk is through the gmsh-sdk
package on pypi, which downloads and sets up gmsh:
pip inst... | [
"def",
"to_volume",
"(",
"mesh",
",",
"file_name",
"=",
"None",
",",
"max_element",
"=",
"None",
",",
"mesher_id",
"=",
"1",
")",
":",
"# checks mesher selection",
"if",
"mesher_id",
"not",
"in",
"[",
"1",
",",
"4",
",",
"7",
",",
"10",
"]",
":",
"ra... | 33.627273 | 20.990909 |
def _construct(self, context):
"""Constructs this by calling the deferred method.
This assumes that all unbound_vars have been specified in context and if
this layer has already been computed in this context, then the previously
constructed value will be returned.
Args:
context: A dict of Un... | [
"def",
"_construct",
"(",
"self",
",",
"context",
")",
":",
"with",
"self",
".",
"g",
".",
"as_default",
"(",
")",
":",
"if",
"self",
".",
"_pass_through",
":",
"# pylint: disable=protected-access",
"return",
"self",
".",
"_pass_through",
".",
"_construct",
... | 39.571429 | 19.464286 |
def _default_call_in_place(op, x, out, **kwargs):
"""Default in-place evaluation using ``Operator._call()``.
Parameters
----------
op : `Operator`
Operator to call
x : ``op.domain`` element
Point in which to call the operator.
out : ``op.range`` element
An object in the ... | [
"def",
"_default_call_in_place",
"(",
"op",
",",
"x",
",",
"out",
",",
"*",
"*",
"kwargs",
")",
":",
"out",
".",
"assign",
"(",
"op",
".",
"range",
".",
"element",
"(",
"op",
".",
"_call_out_of_place",
"(",
"x",
",",
"*",
"*",
"kwargs",
")",
")",
... | 32.1875 | 15.875 |
def evo_blanket(self, beta, alpha):
""" Creates Markov blanket for the variance latent variables
Parameters
----------
beta : np.array
Contains untransformed starting values for latent variables
alpha : np.array
A vector of states
Returns
... | [
"def",
"evo_blanket",
"(",
"self",
",",
"beta",
",",
"alpha",
")",
":",
"# Markov blanket for each state",
"evo_blanket",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"state_no",
")",
"for",
"i",
"in",
"range",
"(",
"evo_blanket",
".",
"shape",
"[",
"0",
"... | 33.153846 | 23.461538 |
def tostring(self: 'ErrorValue', extra_digits: int = 0, plusminus: str = ' +/- ', fmt: str = None) -> str:
"""Make a string representation of the value and its uncertainty.
Inputs:
-------
``extra_digits``: integer
how many extra digits should be shown (plus or minus... | [
"def",
"tostring",
"(",
"self",
":",
"'ErrorValue'",
",",
"extra_digits",
":",
"int",
"=",
"0",
",",
"plusminus",
":",
"str",
"=",
"' +/- '",
",",
"fmt",
":",
"str",
"=",
"None",
")",
"->",
"str",
":",
"if",
"isinstance",
"(",
"fmt",
",",
"str",
")... | 52.970588 | 27.5 |
def tags(self, task, params={}, **options):
"""Returns a compact representation of all of the tags the task has.
Parameters
----------
task : {Id} The task to get tags on.
[params] : {Object} Parameters for the request
"""
path = "/tasks/%s/tags" % (task)
... | [
"def",
"tags",
"(",
"self",
",",
"task",
",",
"params",
"=",
"{",
"}",
",",
"*",
"*",
"options",
")",
":",
"path",
"=",
"\"/tasks/%s/tags\"",
"%",
"(",
"task",
")",
"return",
"self",
".",
"client",
".",
"get_collection",
"(",
"path",
",",
"params",
... | 37.1 | 13.2 |
def _kraus_to_stinespring(data, input_dim, output_dim):
"""Transform Kraus representation to Stinespring representation."""
stine_pair = [None, None]
for i, kraus in enumerate(data):
if kraus is not None:
num_kraus = len(kraus)
stine = np.zeros((output_dim * num_kraus, input_... | [
"def",
"_kraus_to_stinespring",
"(",
"data",
",",
"input_dim",
",",
"output_dim",
")",
":",
"stine_pair",
"=",
"[",
"None",
",",
"None",
"]",
"for",
"i",
",",
"kraus",
"in",
"enumerate",
"(",
"data",
")",
":",
"if",
"kraus",
"is",
"not",
"None",
":",
... | 41.714286 | 8.785714 |
def merge_resolve(branch, fast_forward=False, commit=True, options=None):
"""Merge that branch into current branch
If git raises an error, and the error is for conflicts
then read the error message looking for any resolved conflicts
Remove the resolved conflicts from the error message
If al... | [
"def",
"merge_resolve",
"(",
"branch",
",",
"fast_forward",
"=",
"False",
",",
"commit",
"=",
"True",
",",
"options",
"=",
"None",
")",
":",
"def",
"get_resolution",
"(",
"resolved",
"=",
"None",
")",
":",
"return",
"resolved",
"with",
"git_continuer",
"("... | 42.588235 | 18.058824 |
def resource_urls(request):
"""Global values to pass to templates"""
url_parsed = urlparse(settings.SEARCH_URL)
defaults = dict(
APP_NAME=__description__,
APP_VERSION=__version__,
SITE_URL=settings.SITE_URL.rstrip('/'),
SEARCH_TYPE=settings.SEARCH_TYPE,
SEARCH_URL=se... | [
"def",
"resource_urls",
"(",
"request",
")",
":",
"url_parsed",
"=",
"urlparse",
"(",
"settings",
".",
"SEARCH_URL",
")",
"defaults",
"=",
"dict",
"(",
"APP_NAME",
"=",
"__description__",
",",
"APP_VERSION",
"=",
"__version__",
",",
"SITE_URL",
"=",
"settings"... | 34.076923 | 16.076923 |
def delete_if_error(path):
'''If any exception is raised inside the context, delete the file at the
given path, and allow the exception to continue.'''
try:
yield
except Exception:
if os.path.exists(path):
os.remove(path)
raise | [
"def",
"delete_if_error",
"(",
"path",
")",
":",
"try",
":",
"yield",
"except",
"Exception",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"os",
".",
"remove",
"(",
"path",
")",
"raise"
] | 30.111111 | 21.222222 |
def set_parent(self, parent) -> object:
"""
When we add a parent (from Symbol), don't forget to resolve.
"""
ret = self
if parent is not None:
ret = self._sig.set_parent(parent)
self.resolve()
elif not hasattr(self, 'parent'):
# only if... | [
"def",
"set_parent",
"(",
"self",
",",
"parent",
")",
"->",
"object",
":",
"ret",
"=",
"self",
"if",
"parent",
"is",
"not",
"None",
":",
"ret",
"=",
"self",
".",
"_sig",
".",
"set_parent",
"(",
"parent",
")",
"self",
".",
"resolve",
"(",
")",
"elif... | 31.916667 | 9.916667 |
def send_message(self, message):
"""Sends a message (REQID is zero)"""
Log.debug("In send_message() of %s" % self._get_classname())
outgoing_pkt = OutgoingPacket.create_packet(REQID.generate_zero(), message)
self._send_packet(outgoing_pkt) | [
"def",
"send_message",
"(",
"self",
",",
"message",
")",
":",
"Log",
".",
"debug",
"(",
"\"In send_message() of %s\"",
"%",
"self",
".",
"_get_classname",
"(",
")",
")",
"outgoing_pkt",
"=",
"OutgoingPacket",
".",
"create_packet",
"(",
"REQID",
".",
"generate_... | 50.2 | 15.2 |
def get_session(self, sid, namespace=None):
"""Return the user session for a client.
The only difference with the :func:`socketio.Server.get_session`
method is that when the ``namespace`` argument is not given the
namespace associated with the class is used.
"""
return s... | [
"def",
"get_session",
"(",
"self",
",",
"sid",
",",
"namespace",
"=",
"None",
")",
":",
"return",
"self",
".",
"server",
".",
"get_session",
"(",
"sid",
",",
"namespace",
"=",
"namespace",
"or",
"self",
".",
"namespace",
")"
] | 43.444444 | 14.888889 |
def update_attrs(self, old, new):
""" Update any `attr` members.
Parameters
-----------
old: Declarative
The existing view instance that needs to be updated
new: Declarative
The new view instance that should be used for updating
... | [
"def",
"update_attrs",
"(",
"self",
",",
"old",
",",
"new",
")",
":",
"#: Copy in storage from new node",
"if",
"new",
".",
"_d_storage",
":",
"old",
".",
"_d_storage",
"=",
"new",
".",
"_d_storage"
] | 30.642857 | 15.714286 |
def get_broadcast_date(pid):
"""Take BBC pid (string); extract and return broadcast date as string."""
print("Extracting first broadcast date...")
broadcast_etree = open_listing_page(pid + '/broadcasts.inc')
original_broadcast_date, = broadcast_etree.xpath(
'(//div[@class="grid__inner"]//div'
... | [
"def",
"get_broadcast_date",
"(",
"pid",
")",
":",
"print",
"(",
"\"Extracting first broadcast date...\"",
")",
"broadcast_etree",
"=",
"open_listing_page",
"(",
"pid",
"+",
"'/broadcasts.inc'",
")",
"original_broadcast_date",
",",
"=",
"broadcast_etree",
".",
"xpath",
... | 50.625 | 10.5 |
def keyboard(self, default=None, heading=None, hidden=False):
'''Displays the keyboard input window to the user. If the user does not
cancel the modal, the value entered by the user will be returned.
:param default: The placeholder text used to prepopulate the input field.
:param headin... | [
"def",
"keyboard",
"(",
"self",
",",
"default",
"=",
"None",
",",
"heading",
"=",
"None",
",",
"hidden",
"=",
"False",
")",
":",
"if",
"heading",
"is",
"None",
":",
"heading",
"=",
"self",
".",
"addon",
".",
"getAddonInfo",
"(",
"'name'",
")",
"if",
... | 47.736842 | 22.157895 |
def load_data_and_build(self, filename, delimiter=","):
""" Convenience function for directly working with a data file.
This opens a file and reads the data into an array, sets the
data as an nparray and list of dimnames
@ In, filename, string representing the data file
... | [
"def",
"load_data_and_build",
"(",
"self",
",",
"filename",
",",
"delimiter",
"=",
"\",\"",
")",
":",
"data",
"=",
"np",
".",
"genfromtxt",
"(",
"filename",
",",
"dtype",
"=",
"float",
",",
"delimiter",
"=",
"delimiter",
",",
"names",
"=",
"True",
")",
... | 37.666667 | 19.666667 |
def execute_function(self, func, *nargs, **kwargs):
"""
Execute a function object within the execution context.
@returns The result of the function call.
"""
# makes a copy of the func
import types
fn = types.FunctionType(func.func_code,
... | [
"def",
"execute_function",
"(",
"self",
",",
"func",
",",
"*",
"nargs",
",",
"*",
"*",
"kwargs",
")",
":",
"# makes a copy of the func",
"import",
"types",
"fn",
"=",
"types",
".",
"FunctionType",
"(",
"func",
".",
"func_code",
",",
"func",
".",
"func_glob... | 34.777778 | 16.703704 |
def pop_density(data: CityInfo) -> str:
"""Calculate the population density from the data entry"""
if not isinstance(data, CityInfo):
raise AttributeError("Argument to pop_density() must be an instance of CityInfo")
return no_dec(data.get_population() / data.get_area()) | [
"def",
"pop_density",
"(",
"data",
":",
"CityInfo",
")",
"->",
"str",
":",
"if",
"not",
"isinstance",
"(",
"data",
",",
"CityInfo",
")",
":",
"raise",
"AttributeError",
"(",
"\"Argument to pop_density() must be an instance of CityInfo\"",
")",
"return",
"no_dec",
... | 57.2 | 14 |
def _storeLog(self, nick, time, uid):
"""Adds the nick & uid to the log for a given time/order. No return."""
query = dict(uid=uid)
update = {'$set': dict(nick=nick, time=time)}
self.db.pastes.update(query, update) | [
"def",
"_storeLog",
"(",
"self",
",",
"nick",
",",
"time",
",",
"uid",
")",
":",
"query",
"=",
"dict",
"(",
"uid",
"=",
"uid",
")",
"update",
"=",
"{",
"'$set'",
":",
"dict",
"(",
"nick",
"=",
"nick",
",",
"time",
"=",
"time",
")",
"}",
"self",... | 48.4 | 6.2 |
def serve_file(load, fnd):
'''
Return a chunk from a file based on the data received
'''
ret = {'data': '',
'dest': ''}
required_load_keys = ('path', 'loc', 'saltenv')
if not all(x in load for x in required_load_keys):
log.debug(
'Not all of the required keys prese... | [
"def",
"serve_file",
"(",
"load",
",",
"fnd",
")",
":",
"ret",
"=",
"{",
"'data'",
":",
"''",
",",
"'dest'",
":",
"''",
"}",
"required_load_keys",
"=",
"(",
"'path'",
",",
"'loc'",
",",
"'saltenv'",
")",
"if",
"not",
"all",
"(",
"x",
"in",
"load",
... | 35.071429 | 18.285714 |
def directive_DCB(self, label, params):
"""
label DCB value[, value ...]
Allocate a byte space in read only memory for the value or list of values
"""
# TODO make this read only
# TODO check for byte size
self.labels[label] = self.space_pointer
if param... | [
"def",
"directive_DCB",
"(",
"self",
",",
"label",
",",
"params",
")",
":",
"# TODO make this read only",
"# TODO check for byte size",
"self",
".",
"labels",
"[",
"label",
"]",
"=",
"self",
".",
"space_pointer",
"if",
"params",
"in",
"self",
".",
"equates",
"... | 37 | 12.230769 |
def filter_lines(config=None,
config_path=None,
parent_regex=None,
child_regex=None,
saltenv='base'):
'''
Return a list of detailed matches, for the configuration blocks (parent-child
relationship) whose parent respects the regular expressi... | [
"def",
"filter_lines",
"(",
"config",
"=",
"None",
",",
"config_path",
"=",
"None",
",",
"parent_regex",
"=",
"None",
",",
"child_regex",
"=",
"None",
",",
"saltenv",
"=",
"'base'",
")",
":",
"ret",
"=",
"[",
"]",
"ccp",
"=",
"_get_ccp",
"(",
"config",... | 34.142857 | 23.171429 |
def proto_avgRange(theABF,m1=None,m2=None):
"""experiment: generic VC time course experiment."""
abf=ABF(theABF)
abf.log.info("analyzing as a fast IV")
if m1 is None:
m1=abf.sweepLength
if m2 is None:
m2=abf.sweepLength
I1=int(abf.pointsPerSec*m1)
I2=int(abf.pointsPerSec*m2... | [
"def",
"proto_avgRange",
"(",
"theABF",
",",
"m1",
"=",
"None",
",",
"m2",
"=",
"None",
")",
":",
"abf",
"=",
"ABF",
"(",
"theABF",
")",
"abf",
".",
"log",
".",
"info",
"(",
"\"analyzing as a fast IV\"",
")",
"if",
"m1",
"is",
"None",
":",
"m1",
"=... | 32.017544 | 18.333333 |
def __return(self, shard_state, tstate, task_directive):
"""Handler should always call this as the last statement."""
task_directive = self._set_state(shard_state, tstate, task_directive)
self._save_state_and_schedule_next(shard_state, tstate, task_directive)
context.Context._set(None) | [
"def",
"__return",
"(",
"self",
",",
"shard_state",
",",
"tstate",
",",
"task_directive",
")",
":",
"task_directive",
"=",
"self",
".",
"_set_state",
"(",
"shard_state",
",",
"tstate",
",",
"task_directive",
")",
"self",
".",
"_save_state_and_schedule_next",
"("... | 59.6 | 18.8 |
def serialize(self):
"""
Serializes the columns into the giraffez archive header
binary format::
0 1 2
+------+------+------+------+------+------+------+------+
| Header | Header Data |
| Length | ... | [
"def",
"serialize",
"(",
"self",
")",
":",
"data",
"=",
"b\"\"",
"for",
"column",
"in",
"self",
":",
"row",
"=",
"struct",
".",
"pack",
"(",
"\"5H\"",
",",
"column",
".",
"type",
",",
"column",
".",
"length",
",",
"column",
".",
"precision",
",",
"... | 33.222222 | 23.063492 |
def create_and_configure_wrapper(context_or_world):
"""Create and configure driver wrapper in behave or lettuce tests
:param context_or_world: behave context or lettuce world
"""
# Create default driver wrapper
context_or_world.driver_wrapper = DriverWrappersPool.get_default_wrapper()
context_o... | [
"def",
"create_and_configure_wrapper",
"(",
"context_or_world",
")",
":",
"# Create default driver wrapper",
"context_or_world",
".",
"driver_wrapper",
"=",
"DriverWrappersPool",
".",
"get_default_wrapper",
"(",
")",
"context_or_world",
".",
"utils",
"=",
"context_or_world",
... | 37.956522 | 25.086957 |
def _find_games(self, date, end_date):
"""
Retrieve all major games played on a given day.
Builds a URL based on the requested date and downloads the HTML
contents before parsing any and all games played during that day. Any
games that are found are added to the boxscores dictio... | [
"def",
"_find_games",
"(",
"self",
",",
"date",
",",
"end_date",
")",
":",
"# Set the end date to the start date if the end date is before the",
"# start date.",
"if",
"not",
"end_date",
"or",
"date",
">",
"end_date",
":",
"end_date",
"=",
"date",
"date_step",
"=",
... | 47.459459 | 20.702703 |
def make_subscriber(self, my_args=None):
"""
not implemented
:return:
"""
LOGGER.debug("zeromq.Driver.make_subscriber")
if my_args is None:
raise exceptions.ArianeConfError('subscriber arguments')
if not self.configuration_OK or self.connection_args is... | [
"def",
"make_subscriber",
"(",
"self",
",",
"my_args",
"=",
"None",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"zeromq.Driver.make_subscriber\"",
")",
"if",
"my_args",
"is",
"None",
":",
"raise",
"exceptions",
".",
"ArianeConfError",
"(",
"'subscriber arguments'",
... | 42 | 17.076923 |
async def on_raw_chghost(self, message):
""" Change user and/or host of user. """
if 'chghost' not in self._capabilities or not self._capabilities['chghost']:
return
nick, _ = self._parse_user(message.source)
if nick not in self.users:
return
# Update us... | [
"async",
"def",
"on_raw_chghost",
"(",
"self",
",",
"message",
")",
":",
"if",
"'chghost'",
"not",
"in",
"self",
".",
"_capabilities",
"or",
"not",
"self",
".",
"_capabilities",
"[",
"'chghost'",
"]",
":",
"return",
"nick",
",",
"_",
"=",
"self",
".",
... | 31.6 | 16.533333 |
def has_sample(self, md5):
"""Checks if data store has this sample.
Args:
md5: The md5 digest of the required sample.
Returns:
True if sample with this md5 is present, else False.
"""
# The easiest thing is to simply get the sample and if that
#... | [
"def",
"has_sample",
"(",
"self",
",",
"md5",
")",
":",
"# The easiest thing is to simply get the sample and if that",
"# succeeds than return True, else return False",
"sample",
"=",
"self",
".",
"get_sample",
"(",
"md5",
")",
"return",
"True",
"if",
"sample",
"else",
... | 30.785714 | 19.142857 |
def flush(self, save_index=False, save_model=False, clear_buffer=False):
"""Commit all changes, clear all caches."""
if save_index:
if self.fresh_index is not None:
self.fresh_index.save(self.location('index_fresh'))
if self.opt_index is not None:
... | [
"def",
"flush",
"(",
"self",
",",
"save_index",
"=",
"False",
",",
"save_model",
"=",
"False",
",",
"clear_buffer",
"=",
"False",
")",
":",
"if",
"save_index",
":",
"if",
"self",
".",
"fresh_index",
"is",
"not",
"None",
":",
"self",
".",
"fresh_index",
... | 46.105263 | 19 |
def reload_scoped_variables_list_store(self):
"""Reloads the scoped variable list store from the data port models"""
if isinstance(self.model, ContainerStateModel):
tmp = self.get_new_list_store()
for sv_model in self.model.scoped_variables:
data_type = sv_model.... | [
"def",
"reload_scoped_variables_list_store",
"(",
"self",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"model",
",",
"ContainerStateModel",
")",
":",
"tmp",
"=",
"self",
".",
"get_new_list_store",
"(",
")",
"for",
"sv_model",
"in",
"self",
".",
"model",
"... | 53.464286 | 19.678571 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.