text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def get_charset(html):
"""
get charset in html page
return : default if not exist `charset`
"""
regex = r'charset=([a-zA-Z0-9-]+)?'
pattern = re.compile(regex, re.IGNORECASE)
if len(pattern.findall(html)) == 0:
return 'UTF-8'
return pattern.findall(html)[0] | [
"def",
"get_charset",
"(",
"html",
")",
":",
"regex",
"=",
"r'charset=([a-zA-Z0-9-]+)?'",
"pattern",
"=",
"re",
".",
"compile",
"(",
"regex",
",",
"re",
".",
"IGNORECASE",
")",
"if",
"len",
"(",
"pattern",
".",
"findall",
"(",
"html",
")",
")",
"==",
"... | 28.8 | 0.003367 |
def update(self, index, iterable, commit=True):
"""
Updates the `index` with any objects in `iterable` by adding/updating
the database as needed.
Required arguments:
`index` -- The `SearchIndex` to process
`iterable` -- An iterable of model instances to index
... | [
"def",
"update",
"(",
"self",
",",
"index",
",",
"iterable",
",",
"commit",
"=",
"True",
")",
":",
"database",
"=",
"self",
".",
"_database",
"(",
"writable",
"=",
"True",
")",
"try",
":",
"term_generator",
"=",
"xapian",
".",
"TermGenerator",
"(",
")"... | 44.354331 | 0.001302 |
def get_displaced_structures(pmg_structure, atom_disp=0.01,
supercell_matrix=None, yaml_fname=None, **kwargs):
"""
Generate a set of symmetrically inequivalent displaced structures for
phonon calculations.
Args:
pmg_structure (Structure): A pymatgen structure object... | [
"def",
"get_displaced_structures",
"(",
"pmg_structure",
",",
"atom_disp",
"=",
"0.01",
",",
"supercell_matrix",
"=",
"None",
",",
"yaml_fname",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"is_plusminus",
"=",
"kwargs",
".",
"get",
"(",
"\"is_plusminus\"",... | 40.622642 | 0.000454 |
def unstack(df, level=-1, reset_index=True):
"""pd.DataFrame.unstack adapter.
Call the `df.unstack` method using the indicated level and afterwards
join the column names using an underscore.
Args:
df (pandas.DataFrame): DataFrame to unstack.
level (str, int or list): Level(s) of index ... | [
"def",
"unstack",
"(",
"df",
",",
"level",
"=",
"-",
"1",
",",
"reset_index",
"=",
"True",
")",
":",
"df",
"=",
"df",
".",
"unstack",
"(",
"level",
"=",
"level",
")",
"if",
"reset_index",
":",
"df",
"=",
"df",
".",
"reset_index",
"(",
")",
"df",
... | 30.95 | 0.003135 |
def status_gps_send(self, csFails, gpsQuality, msgsType, posStatus, magVar, magDir, modeInd, force_mavlink1=False):
'''
This contains the status of the GPS readings
csFails : Number of times checksum has failed (uint16_t)
gpsQuality ... | [
"def",
"status_gps_send",
"(",
"self",
",",
"csFails",
",",
"gpsQuality",
",",
"msgsType",
",",
"posStatus",
",",
"magVar",
",",
"magDir",
",",
"modeInd",
",",
"force_mavlink1",
"=",
"False",
")",
":",
"return",
"self",
".",
"send",
"(",
"self",
".",
"st... | 95 | 0.007446 |
def _set_duplicateWWN(self, v, load=False):
"""
Setter method for duplicateWWN, mapped from YANG variable /rbridge_id/fabric/login_policy/duplicateWWN (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_duplicateWWN is considered as a private
method. Backends... | [
"def",
"_set_duplicateWWN",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"b... | 76.851852 | 0.00476 |
def events(self):
'''
A generator that will return all ansible job events in the order that they were emitted from Ansible
Example:
{
"event":"runner_on_ok",
"uuid":"00a50d9c-161a-4b74-b978-9f60becaf209",
"stdout":"ok: [localhost] => {\\... | [
"def",
"events",
"(",
"self",
")",
":",
"event_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"config",
".",
"artifact_dir",
",",
"'job_events'",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"event_path",
")",
":",
"raise",... | 41.057692 | 0.002287 |
def tofile(self, fileobj):
"""
write a cache object to the fileobj as a lal cache file
"""
for entry in self:
print >>fileobj, str(entry)
fileobj.close() | [
"def",
"tofile",
"(",
"self",
",",
"fileobj",
")",
":",
"for",
"entry",
"in",
"self",
":",
"print",
">>",
"fileobj",
",",
"str",
"(",
"entry",
")",
"fileobj",
".",
"close",
"(",
")"
] | 22.857143 | 0.048193 |
def decimal(self, var, default=NOTSET, force=True):
"""Convenience method for casting to a decimal.Decimal
Note:
Casting
"""
return self._get(var, default=default, cast=Decimal, force=force) | [
"def",
"decimal",
"(",
"self",
",",
"var",
",",
"default",
"=",
"NOTSET",
",",
"force",
"=",
"True",
")",
":",
"return",
"self",
".",
"_get",
"(",
"var",
",",
"default",
"=",
"default",
",",
"cast",
"=",
"Decimal",
",",
"force",
"=",
"force",
")"
] | 32.714286 | 0.008511 |
def home(self):
"""
Home the pipette's plunger axis during a protocol run
Notes
-----
`Pipette.home()` homes the `Robot`
Returns
-------
This instance of :class:`Pipette`.
Examples
--------
..
>>> from opentrons import i... | [
"def",
"home",
"(",
"self",
")",
":",
"def",
"_home",
"(",
"mount",
")",
":",
"self",
".",
"current_volume",
"=",
"0",
"self",
".",
"instrument_actuator",
".",
"set_active_current",
"(",
"self",
".",
"_plunger_current",
")",
"self",
".",
"robot",
".",
"p... | 33.5 | 0.001706 |
def setCurrency( self, currency ):
"""
Sets the currency for this widget.
:param currency | <str>
"""
self._currency = currency
self.setValue(self.value()) | [
"def",
"setCurrency",
"(",
"self",
",",
"currency",
")",
":",
"self",
".",
"_currency",
"=",
"currency",
"self",
".",
"setValue",
"(",
"self",
".",
"value",
"(",
")",
")"
] | 27.125 | 0.022321 |
def list(cls, params=None, custom_headers=None):
"""
Get a collection of all available users.
:type params: dict[str, str]|None
:type custom_headers: dict[str, str]|None
:rtype: BunqResponseUserList
"""
if params is None:
params = {}
if cus... | [
"def",
"list",
"(",
"cls",
",",
"params",
"=",
"None",
",",
"custom_headers",
"=",
"None",
")",
":",
"if",
"params",
"is",
"None",
":",
"params",
"=",
"{",
"}",
"if",
"custom_headers",
"is",
"None",
":",
"custom_headers",
"=",
"{",
"}",
"api_client",
... | 28.521739 | 0.00295 |
def revoke_cert(
ca_name,
CN,
cacert_path=None,
ca_filename=None,
cert_path=None,
cert_filename=None,
crl_file=None,
digest='sha256',
):
'''
Revoke a certificate.
.. versionadded:: 2015.8.0
ca_name
Name of the CA.
CN
... | [
"def",
"revoke_cert",
"(",
"ca_name",
",",
"CN",
",",
"cacert_path",
"=",
"None",
",",
"ca_filename",
"=",
"None",
",",
"cert_path",
"=",
"None",
",",
"cert_filename",
"=",
"None",
",",
"crl_file",
"=",
"None",
",",
"digest",
"=",
"'sha256'",
",",
")",
... | 30.424581 | 0.000178 |
def get(self, context, **kwargs):
"""Grab the stored value, and resolve object(s) from UID catalog.
:param context: context is the object who's schema contains this field.
:type context: BaseContent
:param kwargs: kwargs are passed directly to the underlying get.
:type kwargs: d... | [
"def",
"get",
"(",
"self",
",",
"context",
",",
"*",
"*",
"kwargs",
")",
":",
"value",
"=",
"StringField",
".",
"get",
"(",
"self",
",",
"context",
",",
"*",
"*",
"kwargs",
")",
"if",
"not",
"value",
":",
"return",
"[",
"]",
"if",
"self",
".",
... | 45.090909 | 0.001974 |
def map_as_series(self, func, value_size=None, dtype=None, chunk_size='auto'):
"""
Efficiently apply a function to images as series data.
For images data that represent image sequences, this method
applies a function to each pixel's series, and then returns to
the images format,... | [
"def",
"map_as_series",
"(",
"self",
",",
"func",
",",
"value_size",
"=",
"None",
",",
"dtype",
"=",
"None",
",",
"chunk_size",
"=",
"'auto'",
")",
":",
"blocks",
"=",
"self",
".",
"toblocks",
"(",
"chunk_size",
"=",
"chunk_size",
")",
"if",
"value_size"... | 43.333333 | 0.003761 |
def compute_group_count(self, pattern):
"""Compute the number of regexp match groups when the pattern is provided
to the :func:`Cardinality.make_pattern()` method.
:param pattern: Item regexp pattern (as string).
:return: Number of regexp match groups in the cardinality pattern.
... | [
"def",
"compute_group_count",
"(",
"self",
",",
"pattern",
")",
":",
"group_count",
"=",
"self",
".",
"group_count",
"pattern_repeated",
"=",
"1",
"if",
"self",
".",
"is_many",
"(",
")",
":",
"pattern_repeated",
"=",
"2",
"return",
"group_count",
"+",
"patte... | 43.166667 | 0.005671 |
def _exit(self, obj, type, value, traceback):
"""
Teardown a Resource or Middleware.
"""
if type is None:
# No in-context exception occurred
try:
obj.next()
except StopIteration:
# Resource closed as expected
... | [
"def",
"_exit",
"(",
"self",
",",
"obj",
",",
"type",
",",
"value",
",",
"traceback",
")",
":",
"if",
"type",
"is",
"None",
":",
"# No in-context exception occurred",
"try",
":",
"obj",
".",
"next",
"(",
")",
"except",
"StopIteration",
":",
"# Resource clo... | 47.972973 | 0.00497 |
def dqdv(voltage, capacity, voltage_resolution=None, capacity_resolution=None,
voltage_fwhm=0.01, pre_smoothing=True, diff_smoothing=False,
post_smoothing=True, post_normalization=True,
interpolation_method=None, gaussian_order=None, gaussian_mode=None, gaussian_cval=None,
gaussian_t... | [
"def",
"dqdv",
"(",
"voltage",
",",
"capacity",
",",
"voltage_resolution",
"=",
"None",
",",
"capacity_resolution",
"=",
"None",
",",
"voltage_fwhm",
"=",
"0.01",
",",
"pre_smoothing",
"=",
"True",
",",
"diff_smoothing",
"=",
"False",
",",
"post_smoothing",
"=... | 39.317308 | 0.001193 |
def save_vocabulary(self, vocab_path):
"""Save the tokenizer vocabulary to a directory or file."""
index = 0
if os.path.isdir(vocab_path):
vocab_file = os.path.join(vocab_path, VOCAB_NAME)
with open(vocab_file, "w", encoding="utf-8") as writer:
for token, token_in... | [
"def",
"save_vocabulary",
"(",
"self",
",",
"vocab_path",
")",
":",
"index",
"=",
"0",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"vocab_path",
")",
":",
"vocab_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"vocab_path",
",",
"VOCAB_NAME",
")",
"... | 53.714286 | 0.006536 |
def meta_wrapped(f):
"""
Add a field label, errors, and a description (if it exists) to
a field.
"""
@wraps(f)
def wrapped(self, field, *args, **kwargs):
html = "{label}{errors}{original}<small>{description}</small>".format(
label=field.label(class_='control-label'),
... | [
"def",
"meta_wrapped",
"(",
"f",
")",
":",
"@",
"wraps",
"(",
"f",
")",
"def",
"wrapped",
"(",
"self",
",",
"field",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"html",
"=",
"\"{label}{errors}{original}<small>{description}</small>\"",
".",
"format... | 34.866667 | 0.005587 |
def replace(self, to_replace=None, value=None, inplace=False,
limit=None, regex=False, method='pad', axis=None):
"""Replace values given in 'to_replace' with 'value'.
Wrapper around the :meth:`pandas.DataFrame.replace` method.
"""
if inplace:
self._frame.repl... | [
"def",
"replace",
"(",
"self",
",",
"to_replace",
"=",
"None",
",",
"value",
"=",
"None",
",",
"inplace",
"=",
"False",
",",
"limit",
"=",
"None",
",",
"regex",
"=",
"False",
",",
"method",
"=",
"'pad'",
",",
"axis",
"=",
"None",
")",
":",
"if",
... | 47.705882 | 0.003628 |
def __parse_loc_data(loc_data, result):
"""Parse the xml data from selected weatherstation."""
result[DATA] = {ATTRIBUTION: ATTRIBUTION_INFO,
FORECAST: [],
PRECIPITATION_FORECAST: None}
for key, [value, func] in SENSOR_TYPES.items():
result[DATA][key] = None
... | [
"def",
"__parse_loc_data",
"(",
"loc_data",
",",
"result",
")",
":",
"result",
"[",
"DATA",
"]",
"=",
"{",
"ATTRIBUTION",
":",
"ATTRIBUTION_INFO",
",",
"FORECAST",
":",
"[",
"]",
",",
"PRECIPITATION_FORECAST",
":",
"None",
"}",
"for",
"key",
",",
"[",
"v... | 42.472222 | 0.000639 |
def get_media_detail_input_interface_type(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_media_detail = ET.Element("get_media_detail")
config = get_media_detail
input = ET.SubElement(get_media_detail, "input")
interface_type = ET.Sub... | [
"def",
"get_media_detail_input_interface_type",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_media_detail",
"=",
"ET",
".",
"Element",
"(",
"\"get_media_detail\"",
")",
"config",
"=",
"get_me... | 40.916667 | 0.003984 |
def validate_meta_object(meta: Dict[str, Any], allow_extra_meta_fields: bool) -> None:
"""
Validates that every key is one of `META_FIELDS` and has a value of the expected type.
"""
for key, value in meta.items():
if key in META_FIELDS:
if type(value) is not META_FIELDS[key]:
... | [
"def",
"validate_meta_object",
"(",
"meta",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
",",
"allow_extra_meta_fields",
":",
"bool",
")",
"->",
"None",
":",
"for",
"key",
",",
"value",
"in",
"meta",
".",
"items",
"(",
")",
":",
"if",
"key",
"in",
"META... | 43.454545 | 0.005118 |
def get_otp_modehex_interpretation(self, otp):
"""
Return modhex interpretation of the provided OTP.
If there are multiple interpretations available, first one is used,
because if the OTP uses all 16 characters in its alphabet there is only
one possible interpretation of that OT... | [
"def",
"get_otp_modehex_interpretation",
"(",
"self",
",",
"otp",
")",
":",
"try",
":",
"interpretations",
"=",
"translate",
"(",
"u",
"(",
"otp",
")",
")",
"except",
"Exception",
":",
"return",
"otp",
"if",
"len",
"(",
"interpretations",
")",
"==",
"0",
... | 34.423077 | 0.002174 |
def get_store(self, name, workspace=None):
'''
Returns a single store object.
Will return None if no store is found.
Will raise an error if more than one store with the same name is found.
'''
stores = self.get_stores(workspaces=workspace, names=name)
retur... | [
"def",
"get_store",
"(",
"self",
",",
"name",
",",
"workspace",
"=",
"None",
")",
":",
"stores",
"=",
"self",
".",
"get_stores",
"(",
"workspaces",
"=",
"workspace",
",",
"names",
"=",
"name",
")",
"return",
"self",
".",
"_return_first_item",
"(",
"store... | 38.333333 | 0.008499 |
def copy_children(self, foreign_id, existing_node):
'''
Initiates copying of tree, with existing_node acting as root
'''
url = "{}/api/v2/pages/{}/".format(self.base_url, foreign_id)
self.log(
ACTION,
"Copying Children",
{"existing node type": ... | [
"def",
"copy_children",
"(",
"self",
",",
"foreign_id",
",",
"existing_node",
")",
":",
"url",
"=",
"\"{}/api/v2/pages/{}/\"",
".",
"format",
"(",
"self",
".",
"base_url",
",",
"foreign_id",
")",
"self",
".",
"log",
"(",
"ACTION",
",",
"\"Copying Children\"",
... | 43.407407 | 0.001669 |
def failover_to_replicant(self, volume_id, replicant_id, immediate=False):
"""Failover to a volume replicant.
:param integer volume_id: The id of the volume
:param integer replicant_id: ID of replicant to failover to
:param boolean immediate: Flag indicating if failover is immediate
... | [
"def",
"failover_to_replicant",
"(",
"self",
",",
"volume_id",
",",
"replicant_id",
",",
"immediate",
"=",
"False",
")",
":",
"return",
"self",
".",
"client",
".",
"call",
"(",
"'Network_Storage'",
",",
"'failoverToReplicant'",
",",
"replicant_id",
",",
"immedia... | 48 | 0.003717 |
def load_keysym_group(group):
'''Load all the keysyms in group.
Given a group name such as 'latin1' or 'katakana' load the keysyms
defined in module 'Xlib.keysymdef.group-name' into this XK module.'''
if '.' in group:
raise ValueError('invalid keysym group name: %s' % group)
G = globals() ... | [
"def",
"load_keysym_group",
"(",
"group",
")",
":",
"if",
"'.'",
"in",
"group",
":",
"raise",
"ValueError",
"(",
"'invalid keysym group name: %s'",
"%",
"group",
")",
"G",
"=",
"globals",
"(",
")",
"#Get a reference to XK.__dict__ a.k.a. globals",
"#Import just the ke... | 34.608696 | 0.00978 |
def maybe_show_progress(it, show_progress, **kwargs):
"""Optionally show a progress bar for the given iterator.
Parameters
----------
it : iterable
The underlying iterator.
show_progress : bool
Should progress be shown.
**kwargs
Forwarded to the click progress bar.
... | [
"def",
"maybe_show_progress",
"(",
"it",
",",
"show_progress",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"show_progress",
":",
"return",
"click",
".",
"progressbar",
"(",
"it",
",",
"*",
"*",
"kwargs",
")",
"# context manager that just return `it` when we enter it"... | 25.1 | 0.001279 |
def syncScrollbars(self):
"""
Synchronizes the various scrollbars within this chart.
"""
chart_hbar = self.uiChartVIEW.horizontalScrollBar()
chart_vbar = self.uiChartVIEW.verticalScrollBar()
x_hbar = self.uiXAxisVIEW.horizontalScrollBar()
x_vbar =... | [
"def",
"syncScrollbars",
"(",
"self",
")",
":",
"chart_hbar",
"=",
"self",
".",
"uiChartVIEW",
".",
"horizontalScrollBar",
"(",
")",
"chart_vbar",
"=",
"self",
".",
"uiChartVIEW",
".",
"verticalScrollBar",
"(",
")",
"x_hbar",
"=",
"self",
".",
"uiXAxisVIEW",
... | 36.619048 | 0.008872 |
def upload_check(self, filename=None, folder_key=None, filedrop_key=None,
size=None, hash_=None, path=None, resumable=None):
"""upload/check
http://www.mediafire.com/developers/core_api/1.3/upload/#check
"""
return self.request('upload/check', QueryParams({
... | [
"def",
"upload_check",
"(",
"self",
",",
"filename",
"=",
"None",
",",
"folder_key",
"=",
"None",
",",
"filedrop_key",
"=",
"None",
",",
"size",
"=",
"None",
",",
"hash_",
"=",
"None",
",",
"path",
"=",
"None",
",",
"resumable",
"=",
"None",
")",
":"... | 35.8 | 0.005445 |
def main(uport):
"""Instantiate connection to the InfluxDB."""
# NOTE: structure of the UDP packet is different than that of information
# sent via HTTP
json_body = {
"tags": {
"host": "server01",
"region": "us-west"
},
"time": "2009-11-10T23:00:00Z"... | [
"def",
"main",
"(",
"uport",
")",
":",
"# NOTE: structure of the UDP packet is different than that of information",
"# sent via HTTP",
"json_body",
"=",
"{",
"\"tags\"",
":",
"{",
"\"host\"",
":",
"\"server01\"",
",",
"\"region\"",
":",
"\"us-west\"",
"}",
",",
"\... | 29.8 | 0.001083 |
def format(self, record, *args, **kwargs):
"""
Format a message in the log
Act like the normal format, but indent anything that is a
newline within the message.
"""
return logging.Formatter.format(
self, record, *args, **kwargs).replace('\n', '\n' + ' ' * 8) | [
"def",
"format",
"(",
"self",
",",
"record",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"logging",
".",
"Formatter",
".",
"format",
"(",
"self",
",",
"record",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
".",
"replace",
"(... | 31.1 | 0.00625 |
def _normalizeParseActionArgs( f ):
"""Internal method used to decorate parse actions that take fewer than 3 arguments,
so that all parse actions can be called as f(s,l,t)."""
STAR_ARGS = 4
try:
restore = None
if isinstance(f,type):
restore = f... | [
"def",
"_normalizeParseActionArgs",
"(",
"f",
")",
":",
"STAR_ARGS",
"=",
"4",
"try",
":",
"restore",
"=",
"None",
"if",
"isinstance",
"(",
"f",
",",
"type",
")",
":",
"restore",
"=",
"f",
"f",
"=",
"f",
".",
"__init__",
"if",
"not",
"_PY3K",
":",
... | 35.836957 | 0.010035 |
def web(ticker, field=None, start=None, end=None,
mrefresh=False, source='yahoo'):
"""
Data provider wrapper around pandas.io.data provider. Provides
memoization.
"""
if source == 'yahoo' and field is None:
field = 'Adj Close'
tmp = _download_web(ticker, data_source=source,
... | [
"def",
"web",
"(",
"ticker",
",",
"field",
"=",
"None",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
",",
"mrefresh",
"=",
"False",
",",
"source",
"=",
"'yahoo'",
")",
":",
"if",
"source",
"==",
"'yahoo'",
"and",
"field",
"is",
"None",
":",
... | 27.052632 | 0.00188 |
def create_onvif_service(self, name, from_template=True, portType=None):
'''Create ONVIF service client'''
name = name.lower()
xaddr, wsdl_file = self.get_definition(name)
with self.services_lock:
svt = self.services_template.get(name)
# Has a template, clone fr... | [
"def",
"create_onvif_service",
"(",
"self",
",",
"name",
",",
"from_template",
"=",
"True",
",",
"portType",
"=",
"None",
")",
":",
"name",
"=",
"name",
".",
"lower",
"(",
")",
"xaddr",
",",
"wsdl_file",
"=",
"self",
".",
"get_definition",
"(",
"name",
... | 48.40625 | 0.002532 |
def parse_message(self):
"""results in an OmapiMessage"""
parser = parse_chain(self.parse_net32int, # authid
lambda *_: self.parse_net32int(), # authlen
lambda *_: self.parse_net32int(), # opcode
lambda *_: self.parse_net32int(), # handle
lambda *_: self.parse_net32int(), # tid
... | [
"def",
"parse_message",
"(",
"self",
")",
":",
"parser",
"=",
"parse_chain",
"(",
"self",
".",
"parse_net32int",
",",
"# authid",
"lambda",
"*",
"_",
":",
"self",
".",
"parse_net32int",
"(",
")",
",",
"# authlen",
"lambda",
"*",
"_",
":",
"self",
".",
... | 48.230769 | 0.035994 |
def merge(self, other):
'''
Returns a *copy* of this phoneme, with the features of other merged into this feature bundle.
Other can be a list of phonemes, in which case the list is returned (for technical reasons).
Other may also be a single feature value or a list of feature values.
'''
phoneme = dee... | [
"def",
"merge",
"(",
"self",
",",
"other",
")",
":",
"phoneme",
"=",
"deepcopy",
"(",
"self",
")",
"# special case for list of phonemes\r",
"if",
"isinstance",
"(",
"other",
",",
"list",
")",
"and",
"len",
"(",
"other",
")",
">",
"0",
"and",
"isinstance",
... | 31.15625 | 0.030156 |
def check_lat(self, dataset):
'''
float lat(time) ;//....................................... Depending on the precision used for the variable, the data type could be int or double instead of float.
lat:long_name = "" ; //...................................... RECOMMENDED - Provide a desc... | [
"def",
"check_lat",
"(",
"self",
",",
"dataset",
")",
":",
"results",
"=",
"[",
"]",
"lat",
"=",
"util",
".",
"get_lat_variable",
"(",
"dataset",
")",
"if",
"not",
"lat",
":",
"return",
"Result",
"(",
"BaseCheck",
".",
"HIGH",
",",
"False",
",",
"'la... | 79.805556 | 0.007565 |
def _factor_rhs(self, in_port):
"""With::
n := self.cdim
in_im := self.permutation[in_port]
m_{k->l} := map_signals_circuit({k:l}, n)
solve the equation (I) containing ``self``::
self << m_{(n-1) -> in_port}
== m_{(n-1... | [
"def",
"_factor_rhs",
"(",
"self",
",",
"in_port",
")",
":",
"n",
"=",
"self",
".",
"cdim",
"if",
"not",
"(",
"0",
"<=",
"in_port",
"<",
"n",
")",
":",
"raise",
"Exception",
"in_im",
"=",
"self",
".",
"permutation",
"[",
"in_port",
"]",
"# (I) is equ... | 37.978723 | 0.002185 |
def to_netjson(self, remove_block=True):
"""
Converts the intermediate data structure (``self.intermediate_datra``)
to a NetJSON configuration dictionary (``self.config``)
"""
result = OrderedDict()
# copy list
intermediate_data = list(self.intermediate_data[self.... | [
"def",
"to_netjson",
"(",
"self",
",",
"remove_block",
"=",
"True",
")",
":",
"result",
"=",
"OrderedDict",
"(",
")",
"# copy list",
"intermediate_data",
"=",
"list",
"(",
"self",
".",
"intermediate_data",
"[",
"self",
".",
"intermediate_key",
"]",
")",
"# i... | 45.227273 | 0.001969 |
def cli(ctx):
"""\b
Welcome to the Wio Command line utility!
https://github.com/Seeed-Studio/wio-cli
For more information Run: wio <command_name> --help
"""
ctx.obj = Wio()
cur_dir = os.path.abspath(os.path.expanduser("~/.wio"))
if not os.path.exists(cur_dir):
text = {"email":""... | [
"def",
"cli",
"(",
"ctx",
")",
":",
"ctx",
".",
"obj",
"=",
"Wio",
"(",
")",
"cur_dir",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"\"~/.wio\"",
")",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists... | 31.809524 | 0.007267 |
def itransform_define(transform):
"""
This function links the user's choice of transformation with its inverse
"""
if transform == 'tanh':
return np.arctanh
elif transform == 'exp':
return np.log
elif transform == 'logit':
return Family... | [
"def",
"itransform_define",
"(",
"transform",
")",
":",
"if",
"transform",
"==",
"'tanh'",
":",
"return",
"np",
".",
"arctanh",
"elif",
"transform",
"==",
"'exp'",
":",
"return",
"np",
".",
"log",
"elif",
"transform",
"==",
"'logit'",
":",
"return",
"Famil... | 29.357143 | 0.007075 |
def sync(self):
"""Retrieve lights from ElkM1"""
for i in range(4):
self.elk.send(ps_encode(i))
self.get_descriptions(TextDescriptions.LIGHT.value) | [
"def",
"sync",
"(",
"self",
")",
":",
"for",
"i",
"in",
"range",
"(",
"4",
")",
":",
"self",
".",
"elk",
".",
"send",
"(",
"ps_encode",
"(",
"i",
")",
")",
"self",
".",
"get_descriptions",
"(",
"TextDescriptions",
".",
"LIGHT",
".",
"value",
")"
] | 35.8 | 0.010929 |
def get_unique_sentence_indices( text ):
''' Returns a list of sentence indices for the whole text. For each token in text,
the list contains index of the sentence the word belongs to, and the indices
are unique over the whole text. '''
# Add sentence annotation (if missing)
if not text.is_... | [
"def",
"get_unique_sentence_indices",
"(",
"text",
")",
":",
"# Add sentence annotation (if missing)",
"if",
"not",
"text",
".",
"is_tagged",
"(",
"SENTENCES",
")",
":",
"text",
".",
"tokenize_sentences",
"(",
")",
"# Collect (unique) sent indices over the whole text",
"s... | 45.5625 | 0.017473 |
def get_rec_column_descr(self, colnum, vstorage):
"""
Get a descriptor entry for the specified column.
parameters
----------
colnum: integer
The column number, 0 offset
vstorage: string
See docs in read_columns
"""
npy_type, isvar,... | [
"def",
"get_rec_column_descr",
"(",
"self",
",",
"colnum",
",",
"vstorage",
")",
":",
"npy_type",
",",
"isvar",
",",
"istbit",
"=",
"self",
".",
"_get_tbl_numpy_dtype",
"(",
"colnum",
")",
"name",
"=",
"self",
".",
"_info",
"[",
"'colinfo'",
"]",
"[",
"c... | 39.431034 | 0.000853 |
def options(self):
'''
Yields `(raw_value, label)` pairs for all acceptable choices.
'''
conv = self.conv
for python_value, label in self.choices:
yield conv.from_python(python_value), label | [
"def",
"options",
"(",
"self",
")",
":",
"conv",
"=",
"self",
".",
"conv",
"for",
"python_value",
",",
"label",
"in",
"self",
".",
"choices",
":",
"yield",
"conv",
".",
"from_python",
"(",
"python_value",
")",
",",
"label"
] | 33.714286 | 0.008264 |
def project_geometry(geometry, crs=None, to_crs=None, to_latlong=False):
"""
Project a shapely Polygon or MultiPolygon from lat-long to UTM, or
vice-versa
Parameters
----------
geometry : shapely Polygon or MultiPolygon
the geometry to project
crs : dict
the starting coordin... | [
"def",
"project_geometry",
"(",
"geometry",
",",
"crs",
"=",
"None",
",",
"to_crs",
"=",
"None",
",",
"to_latlong",
"=",
"False",
")",
":",
"if",
"crs",
"is",
"None",
":",
"crs",
"=",
"settings",
".",
"default_crs",
"gdf",
"=",
"gpd",
".",
"GeoDataFram... | 31.222222 | 0.000863 |
def show_raslog_input_rbridge_id(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
show_raslog = ET.Element("show_raslog")
config = show_raslog
input = ET.SubElement(show_raslog, "input")
rbridge_id = ET.SubElement(input, "rbridge-id")
... | [
"def",
"show_raslog_input_rbridge_id",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"show_raslog",
"=",
"ET",
".",
"Element",
"(",
"\"show_raslog\"",
")",
"config",
"=",
"show_raslog",
"input",
... | 37.166667 | 0.004376 |
def Dummy(self):
"Obtener el estado de los servidores de la AFIP"
results = self.client.dummy()['response']
self.AppServerStatus = str(results['appserver'])
self.DbServerStatus = str(results['dbserver'])
self.AuthServerStatus = str(results['authserver']) | [
"def",
"Dummy",
"(",
"self",
")",
":",
"results",
"=",
"self",
".",
"client",
".",
"dummy",
"(",
")",
"[",
"'response'",
"]",
"self",
".",
"AppServerStatus",
"=",
"str",
"(",
"results",
"[",
"'appserver'",
"]",
")",
"self",
".",
"DbServerStatus",
"=",
... | 48.166667 | 0.006803 |
def connections(self):
"""
Gets the Connections API client.
Returns:
Connections:
"""
if not self.__connections:
self.__connections = Connections(
self.__connection)
return self.__connections | [
"def",
"connections",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"__connections",
":",
"self",
".",
"__connections",
"=",
"Connections",
"(",
"self",
".",
"__connection",
")",
"return",
"self",
".",
"__connections"
] | 24.545455 | 0.007143 |
def add_values_to_run_set_xml(self, runSet, cputime, walltime, energy):
"""
This function adds the result values to the XML representation of a runSet.
"""
self.add_column_to_xml(runSet.xml, 'cputime', cputime)
self.add_column_to_xml(runSet.xml, 'walltime', walltime)
ener... | [
"def",
"add_values_to_run_set_xml",
"(",
"self",
",",
"runSet",
",",
"cputime",
",",
"walltime",
",",
"energy",
")",
":",
"self",
".",
"add_column_to_xml",
"(",
"runSet",
".",
"xml",
",",
"'cputime'",
",",
"cputime",
")",
"self",
".",
"add_column_to_xml",
"(... | 54.666667 | 0.006 |
def get_from_thread_name_or_id(self, name_or_id, report_error=True):
'''See if *name_or_id* is either a thread name or a thread id.
The frame of that id/name is returned, or None if name_or_id is
invalid.'''
thread_id = self.proc.get_int_noerr(name_or_id)
if thread_id is None:
... | [
"def",
"get_from_thread_name_or_id",
"(",
"self",
",",
"name_or_id",
",",
"report_error",
"=",
"True",
")",
":",
"thread_id",
"=",
"self",
".",
"proc",
".",
"get_int_noerr",
"(",
"name_or_id",
")",
"if",
"thread_id",
"is",
"None",
":",
"# Must be a \"frame\" com... | 44.071429 | 0.003172 |
def assign_proficiency_to_objective_bank(self, proficiency_id, objective_bank_id):
"""Adds an existing ``Proficiency`` to a ``ObjectiveBank``.
arg: proficiency_id (osid.id.Id): the ``Id`` of the
``Proficiency``
arg: objective_bank_id (osid.id.Id): the ``Id`` of the
... | [
"def",
"assign_proficiency_to_objective_bank",
"(",
"self",
",",
"proficiency_id",
",",
"objective_bank_id",
")",
":",
"# Implemented from template for",
"# osid.resource.ResourceBinAssignmentSession.assign_resource_to_bin",
"mgr",
"=",
"self",
".",
"_get_provider_manager",
"(",
... | 52.125 | 0.003925 |
def syncdb(settings_module,
bin_env=None,
migrate=False,
database=None,
pythonpath=None,
env=None,
noinput=True,
runas=None):
'''
Run syncdb
Execute the Django-Admin syncdb command, if South is available on the
minion the ``mi... | [
"def",
"syncdb",
"(",
"settings_module",
",",
"bin_env",
"=",
"None",
",",
"migrate",
"=",
"False",
",",
"database",
"=",
"None",
",",
"pythonpath",
"=",
"None",
",",
"env",
"=",
"None",
",",
"noinput",
"=",
"True",
",",
"runas",
"=",
"None",
")",
":... | 25.8 | 0.002801 |
def _band8(ins):
""" Pops top 2 operands out of the stack, and does
1st AND (bitwise) 2nd operand (top of the stack),
pushes the result.
8 bit un/signed version
"""
op1, op2 = tuple(ins.quad[2:])
if _int_ops(op1, op2) is not None:
op1, op2 = _int_ops(op1, op2)
o... | [
"def",
"_band8",
"(",
"ins",
")",
":",
"op1",
",",
"op2",
"=",
"tuple",
"(",
"ins",
".",
"quad",
"[",
"2",
":",
"]",
")",
"if",
"_int_ops",
"(",
"op1",
",",
"op2",
")",
"is",
"not",
"None",
":",
"op1",
",",
"op2",
"=",
"_int_ops",
"(",
"op1",... | 25.142857 | 0.001368 |
def start_session(self, capabilities, browser_profile=None):
"""
Creates a new session with the desired capabilities.
:Args:
- browser_name - The name of the browser to request.
- version - Which browser version to request.
- platform - Which platform to request the b... | [
"def",
"start_session",
"(",
"self",
",",
"capabilities",
",",
"browser_profile",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"capabilities",
",",
"dict",
")",
":",
"raise",
"InvalidArgumentException",
"(",
"\"Capabilities must be a dictionary\"",
")",
... | 47.6 | 0.003529 |
def tie_weights(self):
""" Run this to be sure output and input (adaptive) softmax weights are tied """
# sampled softmax
if self.sample_softmax > 0:
if self.config.tie_weight:
self.out_layer.weight = self.transformer.word_emb.weight
# adaptive softmax (includ... | [
"def",
"tie_weights",
"(",
"self",
")",
":",
"# sampled softmax",
"if",
"self",
".",
"sample_softmax",
">",
"0",
":",
"if",
"self",
".",
"config",
".",
"tie_weight",
":",
"self",
".",
"out_layer",
".",
"weight",
"=",
"self",
".",
"transformer",
".",
"wor... | 58.411765 | 0.006938 |
async def update_firmware(module, firmware_file_path, loop):
"""
Run avrdude firmware upload command. Switch back to normal module port
Note: For modules with old bootloader, the kernel could assign the module
a new port after the update (since the board is automatically reset).
Scan for such a por... | [
"async",
"def",
"update_firmware",
"(",
"module",
",",
"firmware_file_path",
",",
"loop",
")",
":",
"# TODO: Make sure the module isn't in the middle of operation",
"ports_before_update",
"=",
"await",
"_discover_ports",
"(",
")",
"config_file_path",
"=",
"os",
".",
"path... | 40.290323 | 0.000782 |
def get_schema_path(self, schemas_folder):
"""
Return a file protocol URI e.g. file:///D:/mappyfile/mappyfile/schemas/ on Windows
and file:////home/user/mappyfile/mappyfile/schemas/ on Linux
"""
# replace any Windows path back slashes with forward slashes
schemas_folder ... | [
"def",
"get_schema_path",
"(",
"self",
",",
"schemas_folder",
")",
":",
"# replace any Windows path back slashes with forward slashes",
"schemas_folder",
"=",
"schemas_folder",
".",
"replace",
"(",
"\"\\\\\"",
",",
"\"/\"",
")",
"# HACK Python 2.7 on Linux seems to remove the r... | 36.5 | 0.004451 |
def run(data, samples, force, ipyclient):
"""
Check all samples requested have been clustered (state=6), make output
directory, then create the requested outfiles. Excluded samples are already
removed from samples.
"""
## prepare dirs
data.dirs.outfiles = os.path.join(data.dirs.project, dat... | [
"def",
"run",
"(",
"data",
",",
"samples",
",",
"force",
",",
"ipyclient",
")",
":",
"## prepare dirs",
"data",
".",
"dirs",
".",
"outfiles",
"=",
"os",
".",
"path",
".",
"join",
"(",
"data",
".",
"dirs",
".",
"project",
",",
"data",
".",
"name",
"... | 43.183673 | 0.007856 |
def feature_TIC_correlation(self):
r"""Instantaneous correlation matrix between mean-free input features and TICs
Denoting the input features as :math:`X_i` and the TICs as :math:`\theta_j`, the instantaneous, linear correlation
between them can be written as
.. math::
\ma... | [
"def",
"feature_TIC_correlation",
"(",
"self",
")",
":",
"feature_sigma",
"=",
"np",
".",
"sqrt",
"(",
"np",
".",
"diag",
"(",
"self",
".",
"cov",
")",
")",
"return",
"np",
".",
"dot",
"(",
"self",
".",
"cov",
",",
"self",
".",
"eigenvectors",
"[",
... | 46.142857 | 0.008089 |
def stop_transmit(self, fd):
"""
Stop yielding writeability events for `fd`.
Redundant calls to :meth:`stop_transmit` are silently ignored, this may
change in future.
"""
self._wfds.pop(fd, None)
self._update(fd) | [
"def",
"stop_transmit",
"(",
"self",
",",
"fd",
")",
":",
"self",
".",
"_wfds",
".",
"pop",
"(",
"fd",
",",
"None",
")",
"self",
".",
"_update",
"(",
"fd",
")"
] | 29 | 0.007435 |
def formatPoint(point, affine):
"""
Retrieves a string representation of @point
"""
# Affine coordinates: (x,y)
if affine:
fmt = "\tx:{}\n\ty:{}"
coords = [point.x, point.y]
# Projected coordinates: (x,y,z)
else:
fmt = "\tx:{}\n\ty:{}\n\tz:{}"
coords ... | [
"def",
"formatPoint",
"(",
"point",
",",
"affine",
")",
":",
"# Affine coordinates: (x,y) ",
"if",
"affine",
":",
"fmt",
"=",
"\"\\tx:{}\\n\\ty:{}\"",
"coords",
"=",
"[",
"point",
".",
"x",
",",
"point",
".",
"y",
"]",
"# Projected coordinates: (x,y,z)",
... | 25.5 | 0.004728 |
def parse_osm_relations(relations, osm_way_df):
"""
Parses the osm relations (multipolygons) from osm
ways and nodes. See more information about relations
from OSM documentation: http://wiki.openstreetmap.org/wiki/Relation
Parameters
----------
relations : list
OSM 'rela... | [
"def",
"parse_osm_relations",
"(",
"relations",
",",
"osm_way_df",
")",
":",
"gdf_relations",
"=",
"gpd",
".",
"GeoDataFrame",
"(",
")",
"# Iterate over relations and extract the items",
"for",
"relation",
"in",
"relations",
":",
"if",
"relation",
"[",
"'tags'",
"]"... | 47.131148 | 0.005792 |
def truncate_to_issuer(self, cert):
"""
Remove all certificates in the path after the issuer of the cert
specified, as defined by this path
:param cert:
An asn1crypto.x509.Certificate object to find the issuer of
:raises:
LookupError - when the issuer of... | [
"def",
"truncate_to_issuer",
"(",
"self",
",",
"cert",
")",
":",
"issuer_index",
"=",
"None",
"for",
"index",
",",
"entry",
"in",
"enumerate",
"(",
"self",
")",
":",
"if",
"entry",
".",
"subject",
"==",
"cert",
".",
"issuer",
":",
"if",
"entry",
".",
... | 32.121212 | 0.002747 |
def read_data(self, **kwargs):
"""
get the data from the service
as the pocket service does not have any date
in its API linked to the note,
add the triggered date to the dict data
thus the service will be triggered when data will be found
... | [
"def",
"read_data",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"trigger_id",
"=",
"kwargs",
".",
"get",
"(",
"'trigger_id'",
")",
"trigger",
"=",
"Reddit",
".",
"objects",
".",
"get",
"(",
"trigger_id",
"=",
"trigger_id",
")",
"date_triggered",
"=",... | 45.034483 | 0.002999 |
def version_gt(version, gt):
"""
Code for parsing simple, numeric versions. Letters will be stripped prior to
comparison. Simple appendages such as 1-rc1 are supported. Test cases for
function are present on dscan/tests/fingerprint_tests.py
"""
version_split = strip_letters(version).split('.')
... | [
"def",
"version_gt",
"(",
"version",
",",
"gt",
")",
":",
"version_split",
"=",
"strip_letters",
"(",
"version",
")",
".",
"split",
"(",
"'.'",
")",
"gt_split",
"=",
"strip_letters",
"(",
"gt",
")",
".",
"split",
"(",
"'.'",
")",
"v_len",
"=",
"len",
... | 25.93 | 0.001486 |
def currentStore(self, store_view=None):
"""
Set/Get current store view
:param store_view: Store view ID or Code
:return: int
"""
args = [store_view] if store_view else []
return int(self.call('catalog_category_attribute.currentStore', args)) | [
"def",
"currentStore",
"(",
"self",
",",
"store_view",
"=",
"None",
")",
":",
"args",
"=",
"[",
"store_view",
"]",
"if",
"store_view",
"else",
"[",
"]",
"return",
"int",
"(",
"self",
".",
"call",
"(",
"'catalog_category_attribute.currentStore'",
",",
"args",... | 32.333333 | 0.006689 |
def numberify_file(self, filename):
'''Prepend each line of a file with the line number
Argument:
filename - name of the file to be numberified
'''
try:
fd = open(filename, 'r+')
lines = fd.readlines()
for i in range(len(lines)):
... | [
"def",
"numberify_file",
"(",
"self",
",",
"filename",
")",
":",
"try",
":",
"fd",
"=",
"open",
"(",
"filename",
",",
"'r+'",
")",
"lines",
"=",
"fd",
".",
"readlines",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"lines",
")",
")",
":",... | 34.347826 | 0.003695 |
def phasicTonic(self,m1=None,m2=None,chunkMs=50,quietPercentile=10,
histResolution=.5,plotToo=False):
"""
let's keep the chunkMs as high as we reasonably can. 50ms is good.
Things get flakey at lower numbers like 10ms.
IMPORTANT! for this to work, prevent 0s... | [
"def",
"phasicTonic",
"(",
"self",
",",
"m1",
"=",
"None",
",",
"m2",
"=",
"None",
",",
"chunkMs",
"=",
"50",
",",
"quietPercentile",
"=",
"10",
",",
"histResolution",
"=",
".5",
",",
"plotToo",
"=",
"False",
")",
":",
"# prepare sectioning values to be us... | 41.234568 | 0.030117 |
def init_realms(self, realms):
"""
:type realms: tuple
"""
# this eliminates the need for an authorizing_realms attribute:
self.realms = tuple(realm for realm in realms
if isinstance(realm, realm_abcs.AuthorizingRealm))
self.register_cache_clea... | [
"def",
"init_realms",
"(",
"self",
",",
"realms",
")",
":",
"# this eliminates the need for an authorizing_realms attribute:",
"self",
".",
"realms",
"=",
"tuple",
"(",
"realm",
"for",
"realm",
"in",
"realms",
"if",
"isinstance",
"(",
"realm",
",",
"realm_abcs",
"... | 40.625 | 0.006024 |
def add_boundary_pores(network, pores, offset, apply_label='boundary'):
r"""
This method uses ``clone_pores`` to clone the input pores, then shifts
them the specified amount and direction, then applies the given label.
Parameters
----------
pores : array_like
List of pores to offset. I... | [
"def",
"add_boundary_pores",
"(",
"network",
",",
"pores",
",",
"offset",
",",
"apply_label",
"=",
"'boundary'",
")",
":",
"# Parse the input pores",
"Ps",
"=",
"sp",
".",
"array",
"(",
"pores",
",",
"ndmin",
"=",
"1",
")",
"if",
"Ps",
".",
"dtype",
"is"... | 32.811321 | 0.000558 |
def GetView(self, viewname):
"""Get Info on View Name
"""
# Build Request
soap_request = soap('GetView')
soap_request.add_parameter('listName', self.listName)
if viewname == None:
views = self.GetViewCollection()
for view in views:
... | [
"def",
"GetView",
"(",
"self",
",",
"viewname",
")",
":",
"# Build Request",
"soap_request",
"=",
"soap",
"(",
"'GetView'",
")",
"soap_request",
".",
"add_parameter",
"(",
"'listName'",
",",
"self",
".",
"listName",
")",
"if",
"viewname",
"==",
"None",
":",
... | 39.820513 | 0.003143 |
def save_to(self, file):
"""Save data to file.
Will copy by either writing out the data or using
:func:`shutil.copyfileobj`.
:param file: A file-like object (with a ``write`` method) or a
filename."""
dest = file
if hasattr(dest, 'write'):
... | [
"def",
"save_to",
"(",
"self",
",",
"file",
")",
":",
"dest",
"=",
"file",
"if",
"hasattr",
"(",
"dest",
",",
"'write'",
")",
":",
"# writing to a file-like",
"# only works when no unicode conversion is done",
"if",
"self",
".",
"file",
"is",
"not",
"None",
"a... | 35.862069 | 0.001873 |
def beta_code(self, text):
"""Replace method. Note: regex.subn() returns a tuple (new_string,
number_of_subs_made).
"""
text = text.upper().replace('-', '')
for (pattern, repl) in self.pattern1:
text = pattern.subn(repl, text)[0]
for (pattern, repl) in self.pa... | [
"def",
"beta_code",
"(",
"self",
",",
"text",
")",
":",
"text",
"=",
"text",
".",
"upper",
"(",
")",
".",
"replace",
"(",
"'-'",
",",
"''",
")",
"for",
"(",
"pattern",
",",
"repl",
")",
"in",
"self",
".",
"pattern1",
":",
"text",
"=",
"pattern",
... | 40.461538 | 0.003717 |
def get(self, request, *args, **kwargs):
""" return profile of current user if authenticated otherwise 401 """
serializer = self.serializer_reader_class
if request.user.is_authenticated():
return Response(serializer(request.user, context=self.get_serializer_context()).data)
e... | [
"def",
"get",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"serializer",
"=",
"self",
".",
"serializer_reader_class",
"if",
"request",
".",
"user",
".",
"is_authenticated",
"(",
")",
":",
"return",
"Response",
"(",
... | 60.142857 | 0.009368 |
def contains_all(self, other):
"""Return ``True`` if ``other`` is a sequence of integers."""
dtype = getattr(other, 'dtype', None)
if dtype is None:
dtype = np.result_type(*other)
return is_int_dtype(dtype) | [
"def",
"contains_all",
"(",
"self",
",",
"other",
")",
":",
"dtype",
"=",
"getattr",
"(",
"other",
",",
"'dtype'",
",",
"None",
")",
"if",
"dtype",
"is",
"None",
":",
"dtype",
"=",
"np",
".",
"result_type",
"(",
"*",
"other",
")",
"return",
"is_int_d... | 40.833333 | 0.008 |
def deploy(self, iid):
'''
Links an item from the vault to the original path
'''
for index in iid:
target = Target.getTarget(index)
if target:
verbose('Deploying id {} from {} to {} with the name {}'
.format(index, targ... | [
"def",
"deploy",
"(",
"self",
",",
"iid",
")",
":",
"for",
"index",
"in",
"iid",
":",
"target",
"=",
"Target",
".",
"getTarget",
"(",
"index",
")",
"if",
"target",
":",
"verbose",
"(",
"'Deploying id {} from {} to {} with the name {}'",
".",
"format",
"(",
... | 32.076923 | 0.006993 |
def plot_chain(sampler, p=None, **kwargs):
"""Generate a diagnostic plot of the sampler chains.
Parameters
----------
sampler : `emcee.EnsembleSampler`
Sampler containing the chains to be plotted.
p : int (optional)
Index of the parameter to plot. If omitted, all chains are plotted.... | [
"def",
"plot_chain",
"(",
"sampler",
",",
"p",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"p",
"is",
"None",
":",
"npars",
"=",
"sampler",
".",
"chain",
".",
"shape",
"[",
"-",
"1",
"]",
"for",
"pp",
"in",
"six",
".",
"moves",
".",
... | 28 | 0.001279 |
def members_to_ask(self, name_id):
"""Find the member of the Virtual Organization that I haven't already
spoken too
"""
vo_members = self._affiliation_members()
for member in self.member:
if member not in vo_members:
vo_members.append(member)
... | [
"def",
"members_to_ask",
"(",
"self",
",",
"name_id",
")",
":",
"vo_members",
"=",
"self",
".",
"_affiliation_members",
"(",
")",
"for",
"member",
"in",
"self",
".",
"member",
":",
"if",
"member",
"not",
"in",
"vo_members",
":",
"vo_members",
".",
"append"... | 37.333333 | 0.003484 |
def find(self, path, all=False):
"""
Looks for files in PIPELINE.STYLESHEETS and PIPELINE.JAVASCRIPT
"""
matches = []
for elem in chain(settings.STYLESHEETS.values(), settings.JAVASCRIPT.values()):
if normpath(elem['output_filename']) == normpath(path):
... | [
"def",
"find",
"(",
"self",
",",
"path",
",",
"all",
"=",
"False",
")",
":",
"matches",
"=",
"[",
"]",
"for",
"elem",
"in",
"chain",
"(",
"settings",
".",
"STYLESHEETS",
".",
"values",
"(",
")",
",",
"settings",
".",
"JAVASCRIPT",
".",
"values",
"(... | 40 | 0.00611 |
def get_file(self, file, **kwargs):
"""
Return the standard attachment json object for a file.
:calls: `GET /api/v1/files/:id \
<https://canvas.instructure.com/doc/api/files.html#method.files.api_show>`_
:param file: The object or ID of the file to retrieve.
:type file:... | [
"def",
"get_file",
"(",
"self",
",",
"file",
",",
"*",
"*",
"kwargs",
")",
":",
"file_id",
"=",
"obj_or_id",
"(",
"file",
",",
"\"file\"",
",",
"(",
"File",
",",
")",
")",
"response",
"=",
"self",
".",
"__requester",
".",
"request",
"(",
"'GET'",
"... | 33.05 | 0.002941 |
def find_by_filename(filename=None, engines=None):
"""
Find a list of template engine classes to render template `filename`.
:param filename: Template file name (may be a absolute/relative path)
:param engines: Template engines
:return: A list of engines support given template file
"""
if ... | [
"def",
"find_by_filename",
"(",
"filename",
"=",
"None",
",",
"engines",
"=",
"None",
")",
":",
"if",
"engines",
"is",
"None",
":",
"engines",
"=",
"ENGINES",
"if",
"filename",
"is",
"None",
":",
"return",
"list_engines_by_priority",
"(",
"engines",
")",
"... | 31.941176 | 0.001789 |
def _find_parent_directory(directory, filename):
"""Find a directory in parent tree with a specific filename
:param directory: directory name to find
:param filename: filename to find
:returns: absolute directory path
"""
parent_directory = directory
absolute_dir... | [
"def",
"_find_parent_directory",
"(",
"directory",
",",
"filename",
")",
":",
"parent_directory",
"=",
"directory",
"absolute_directory",
"=",
"'.'",
"while",
"absolute_directory",
"!=",
"os",
".",
"path",
".",
"abspath",
"(",
"parent_directory",
")",
":",
"absolu... | 48.526316 | 0.004255 |
def mousePressEvent(self, event):
"""Reimplement Qt method"""
if event.button() == Qt.LeftButton:
self.__drag_start_pos = QPoint(event.pos())
QTabBar.mousePressEvent(self, event) | [
"def",
"mousePressEvent",
"(",
"self",
",",
"event",
")",
":",
"if",
"event",
".",
"button",
"(",
")",
"==",
"Qt",
".",
"LeftButton",
":",
"self",
".",
"__drag_start_pos",
"=",
"QPoint",
"(",
"event",
".",
"pos",
"(",
")",
")",
"QTabBar",
".",
"mouse... | 42.8 | 0.009174 |
def execute(self, input_data):
''' Process the input bytes with pefile '''
raw_bytes = input_data['sample']['raw_bytes']
# Have the PE File module process the file
pefile_handle, error_str = self.open_using_pefile('unknown', raw_bytes)
if not pefile_handle:
return {... | [
"def",
"execute",
"(",
"self",
",",
"input_data",
")",
":",
"raw_bytes",
"=",
"input_data",
"[",
"'sample'",
"]",
"[",
"'raw_bytes'",
"]",
"# Have the PE File module process the file",
"pefile_handle",
",",
"error_str",
"=",
"self",
".",
"open_using_pefile",
"(",
... | 44.866667 | 0.007278 |
def BIC(self,data=None):
'''
BIC on the passed data. If passed data is None (default), calculates BIC
on the model's assigned data
'''
# NOTE: in principle this method computes the BIC only after finding the
# maximum likelihood parameters (or, of course, an EM fixed-poin... | [
"def",
"BIC",
"(",
"self",
",",
"data",
"=",
"None",
")",
":",
"# NOTE: in principle this method computes the BIC only after finding the",
"# maximum likelihood parameters (or, of course, an EM fixed-point as an",
"# approximation!)",
"assert",
"data",
"is",
"None",
"and",
"len",... | 52.533333 | 0.009975 |
def place_new_order(self, stock, price, qty, direction, order_type):
"""Place an order for a stock.
https://starfighter.readme.io/docs/place-new-order
"""
url_fragment = 'venues/{venue}/stocks/{stock}/orders'.format(
venue=self.venue,
stock=stock,
)
... | [
"def",
"place_new_order",
"(",
"self",
",",
"stock",
",",
"price",
",",
"qty",
",",
"direction",
",",
"order_type",
")",
":",
"url_fragment",
"=",
"'venues/{venue}/stocks/{stock}/orders'",
".",
"format",
"(",
"venue",
"=",
"self",
".",
"venue",
",",
"stock",
... | 31.285714 | 0.002954 |
def recommend(self, userid, user_items,
N=10, filter_already_liked_items=True, filter_items=None, recalculate_user=False):
""" returns the best N recommendations for a user given its id"""
if userid >= user_items.shape[0]:
raise ValueError("userid is out of bounds of the us... | [
"def",
"recommend",
"(",
"self",
",",
"userid",
",",
"user_items",
",",
"N",
"=",
"10",
",",
"filter_already_liked_items",
"=",
"True",
",",
"filter_items",
"=",
"None",
",",
"recalculate_user",
"=",
"False",
")",
":",
"if",
"userid",
">=",
"user_items",
"... | 46.571429 | 0.009018 |
def array(self, name, data, **kwargs):
"""Create an array. Keyword arguments as per
:func:`zarr.creation.array`."""
return self._write_op(self._array_nosync, name, data, **kwargs) | [
"def",
"array",
"(",
"self",
",",
"name",
",",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_write_op",
"(",
"self",
".",
"_array_nosync",
",",
"name",
",",
"data",
",",
"*",
"*",
"kwargs",
")"
] | 50 | 0.009852 |
def p_qualifier(p):
"""qualifier : qualifierName
| qualifierName ':' flavorList
| qualifierName qualifierParameter
| qualifierName qualifierParameter ':' flavorList
"""
# pylint: disable=too-many-branches
qname = p[1]
ns = p.parser.han... | [
"def",
"p_qualifier",
"(",
"p",
")",
":",
"# pylint: disable=too-many-branches",
"qname",
"=",
"p",
"[",
"1",
"]",
"ns",
"=",
"p",
".",
"parser",
".",
"handle",
".",
"default_namespace",
"qval",
"=",
"None",
"flavorlist",
"=",
"[",
"]",
"if",
"len",
"(",... | 32.066667 | 0.000504 |
def get_edge_init_data(self, fn, save_path=None):
"""
Creates the initialization data from the edge structure
"""
edge_init_data = {key: self.edges[fn][key].get('data') for key in
self.edges[fn].keys()}
edge_init_done = {key: self.edges[fn][key].get('do... | [
"def",
"get_edge_init_data",
"(",
"self",
",",
"fn",
",",
"save_path",
"=",
"None",
")",
":",
"edge_init_data",
"=",
"{",
"key",
":",
"self",
".",
"edges",
"[",
"fn",
"]",
"[",
"key",
"]",
".",
"get",
"(",
"'data'",
")",
"for",
"key",
"in",
"self",... | 46.5 | 0.003515 |
def get_layers(self):
"""
Returns a set of layers in this cell.
Returns
-------
out : set
Set of the layers used in this cell.
"""
layers = set()
for element in self.elements:
if isinstance(element, PolygonSet):
lay... | [
"def",
"get_layers",
"(",
"self",
")",
":",
"layers",
"=",
"set",
"(",
")",
"for",
"element",
"in",
"self",
".",
"elements",
":",
"if",
"isinstance",
"(",
"element",
",",
"PolygonSet",
")",
":",
"layers",
".",
"update",
"(",
"element",
".",
"layers",
... | 31 | 0.003295 |
def get_device_status(self, t):
'''get device status at a given time t (within self.monitor_period)'''
data = {}
for name, (func, _, _) in self.addons.iteritems():
data[name] = func(t)
return data | [
"def",
"get_device_status",
"(",
"self",
",",
"t",
")",
":",
"data",
"=",
"{",
"}",
"for",
"name",
",",
"(",
"func",
",",
"_",
",",
"_",
")",
"in",
"self",
".",
"addons",
".",
"iteritems",
"(",
")",
":",
"data",
"[",
"name",
"]",
"=",
"func",
... | 40 | 0.008163 |
def from_dict(cls, content):
"""Create an instance from a dict.
An alternative constructor. Equivalent to ``DidlObject(**content)``.
Args:
content (dict): a dict containing metadata information. Required.
Valid keys are the same as the parameters for `DidlObject`.
... | [
"def",
"from_dict",
"(",
"cls",
",",
"content",
")",
":",
"# Do we really need this constructor? Could use DidlObject(**content)",
"# instead. -- We do now",
"if",
"'resources'",
"in",
"content",
":",
"content",
"[",
"'resources'",
"]",
"=",
"[",
"DidlResource",
".",
"... | 38.8125 | 0.003145 |
def ensure_packages(packages):
"""Install but do not upgrade required plugin packages."""
required = filter_installed_packages(packages)
if required:
apt_install(required, fatal=True) | [
"def",
"ensure_packages",
"(",
"packages",
")",
":",
"required",
"=",
"filter_installed_packages",
"(",
"packages",
")",
"if",
"required",
":",
"apt_install",
"(",
"required",
",",
"fatal",
"=",
"True",
")"
] | 39.8 | 0.004926 |
def display_images_widgets(self, fnames:list) -> None:
"Display a few preview images in the notebook"
imgs = [widgets.Image(value=open(f, 'rb').read(), width='200px') for f in fnames]
self._img_pane.children = tuple(imgs) | [
"def",
"display_images_widgets",
"(",
"self",
",",
"fnames",
":",
"list",
")",
"->",
"None",
":",
"imgs",
"=",
"[",
"widgets",
".",
"Image",
"(",
"value",
"=",
"open",
"(",
"f",
",",
"'rb'",
")",
".",
"read",
"(",
")",
",",
"width",
"=",
"'200px'",... | 60.5 | 0.016327 |
def _get_running_apps(self, instance, requests_config):
"""
Determine what mode was specified
"""
tags = instance.get('tags', [])
if tags is None:
tags = []
master_address = self._get_master_address(instance)
# Get the cluster name from the instance co... | [
"def",
"_get_running_apps",
"(",
"self",
",",
"instance",
",",
"requests_config",
")",
":",
"tags",
"=",
"instance",
".",
"get",
"(",
"'tags'",
",",
"[",
"]",
")",
"if",
"tags",
"is",
"None",
":",
"tags",
"=",
"[",
"]",
"master_address",
"=",
"self",
... | 45 | 0.004579 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.