text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def request(method, path, params=None, data=None, auto_retry=True):
"""
method - HTTP method. e.g. get, put, post, etc.
path - Path to resource. e.g. /loss_sets/1234
params - Parameter to pass in the query string
data - Dictionary of parameters to pass in the request body
"""
body = None
... | [
"def",
"request",
"(",
"method",
",",
"path",
",",
"params",
"=",
"None",
",",
"data",
"=",
"None",
",",
"auto_retry",
"=",
"True",
")",
":",
"body",
"=",
"None",
"if",
"data",
"is",
"not",
"None",
":",
"body",
"=",
"json",
".",
"dumps",
"(",
"da... | 37.461538 | 0.001001 |
def _lock(self, break_existing=False):
"""Write a special file to the target root folder."""
# write("_lock")
data = {"lock_time": time.time(), "lock_holder": None}
try:
assert self.cur_dir == self.root_dir
self.write_text(DirMetadata.LOCK_FILE_NAME, json.... | [
"def",
"_lock",
"(",
"self",
",",
"break_existing",
"=",
"False",
")",
":",
"# write(\"_lock\")\r",
"data",
"=",
"{",
"\"lock_time\"",
":",
"time",
".",
"time",
"(",
")",
",",
"\"lock_holder\"",
":",
"None",
"}",
"try",
":",
"assert",
"self",
".",
"cur_d... | 41.458333 | 0.001965 |
def _get_choices(self, gandi):
""" Internal method to get choices list """
return [str(item['id'])
for item in gandi.snapshotprofile.list(target=self.target)] | [
"def",
"_get_choices",
"(",
"self",
",",
"gandi",
")",
":",
"return",
"[",
"str",
"(",
"item",
"[",
"'id'",
"]",
")",
"for",
"item",
"in",
"gandi",
".",
"snapshotprofile",
".",
"list",
"(",
"target",
"=",
"self",
".",
"target",
")",
"]"
] | 46.75 | 0.010526 |
def rm_incomplete_des_asc(des_mask, asc_mask):
'''Remove descents-ascents that have no corresponding ascent-descent
Args
----
des_mask: ndarray
Boolean mask of descents in the depth data
asc_mask: ndarray
Boolean mask of ascents in the depth data
Returns
-------
des_mas... | [
"def",
"rm_incomplete_des_asc",
"(",
"des_mask",
",",
"asc_mask",
")",
":",
"from",
".",
"import",
"utils",
"# Get start/stop indices for descents and ascents",
"des_start",
",",
"des_stop",
"=",
"utils",
".",
"contiguous_regions",
"(",
"des_mask",
")",
"asc_start",
"... | 31.111111 | 0.001155 |
def gen_tokens(self):
"""
>>> list(Program("ls").gen_tokens())
['ls']
>>> list(Program("ls -a").gen_tokens())
['ls', '-a']
>>> list(Program("cd /; pwd").gen_tokens())
['cd', '/', None, 'pwd']
>>> list(Program("'cd /; pwd'").gen_tokens())
['cd /; pw... | [
"def",
"gen_tokens",
"(",
"self",
")",
":",
"current_token",
"=",
"[",
"]",
"escape",
"=",
"False",
"quote",
"=",
"None",
"skip",
"=",
"0",
"for",
"char",
",",
"peek",
"in",
"zip",
"(",
"self",
".",
"text",
",",
"self",
".",
"text",
"[",
"1",
":"... | 35.25 | 0.000986 |
def real_dtype(dtype, default=None):
"""Return the real counterpart of ``dtype`` if existing.
Parameters
----------
dtype :
Real or complex floating point data type. It can be given in any
way the `numpy.dtype` constructor understands.
default :
Object to be returned if no r... | [
"def",
"real_dtype",
"(",
"dtype",
",",
"default",
"=",
"None",
")",
":",
"dtype",
",",
"dtype_in",
"=",
"np",
".",
"dtype",
"(",
"dtype",
")",
",",
"dtype",
"if",
"is_real_floating_dtype",
"(",
"dtype",
")",
":",
"return",
"dtype",
"try",
":",
"real_b... | 24.9 | 0.000644 |
def get_new_oids(self):
'''
Returns a list of unique oids that have not been extracted yet.
Essentially, a diff of distinct oids in the source database
compared to cube.
'''
table = self.lconfig.get('table')
_oid = self.lconfig.get('_oid')
if is_array(_oi... | [
"def",
"get_new_oids",
"(",
"self",
")",
":",
"table",
"=",
"self",
".",
"lconfig",
".",
"get",
"(",
"'table'",
")",
"_oid",
"=",
"self",
".",
"lconfig",
".",
"get",
"(",
"'_oid'",
")",
"if",
"is_array",
"(",
"_oid",
")",
":",
"_oid",
"=",
"_oid",
... | 39.142857 | 0.002375 |
def _validate_collection(self):
"""Validates Collection information. Raises errors for required
properties."""
if not self._id:
msg = "No 'id' in Collection for request '{}'"
raise ValidationError(msg.format(self.url))
if not self._title:
msg = "No 't... | [
"def",
"_validate_collection",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_id",
":",
"msg",
"=",
"\"No 'id' in Collection for request '{}'\"",
"raise",
"ValidationError",
"(",
"msg",
".",
"format",
"(",
"self",
".",
"url",
")",
")",
"if",
"not",
"self... | 40.545455 | 0.002191 |
def create_certificate_issuer(self, certificate_issuer_request, **kwargs): # noqa: E501
"""Create certificate issuer. # noqa: E501
Create a certificate issuer. The maximum number of issuers is limited to 20 per account. Multiple certificate issuers of the same issuer type can be created, provided the... | [
"def",
"create_certificate_issuer",
"(",
"self",
",",
"certificate_issuer_request",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'asynchronous'",
")",
":",
"retu... | 230.333333 | 0.000412 |
def fillRGB(self, r, g, b, start=0, end=-1):
"""Fill entire strip by giving individual RGB values instead of tuple"""
self.fill((r, g, b), start, end) | [
"def",
"fillRGB",
"(",
"self",
",",
"r",
",",
"g",
",",
"b",
",",
"start",
"=",
"0",
",",
"end",
"=",
"-",
"1",
")",
":",
"self",
".",
"fill",
"(",
"(",
"r",
",",
"g",
",",
"b",
")",
",",
"start",
",",
"end",
")"
] | 54.666667 | 0.018072 |
def _install_one(
repo_url, branch, destination, commit='', patches=None,
exclude_modules=None, include_modules=None, base=False, work_directory=''
):
""" Install a third party odoo add-on
:param string repo_url: url of the repo that contains the patch.
:param string branch: name of the branch to c... | [
"def",
"_install_one",
"(",
"repo_url",
",",
"branch",
",",
"destination",
",",
"commit",
"=",
"''",
",",
"patches",
"=",
"None",
",",
"exclude_modules",
"=",
"None",
",",
"include_modules",
"=",
"None",
",",
"base",
"=",
"False",
",",
"work_directory",
"=... | 44.625 | 0.001828 |
def get_environ(self):
"""Return a new environ dict targeting the given wsgi.version."""
req = self.req
req_conn = req.conn
env = {
# set a non-standard environ entry so the WSGI app can know what
# the *real* server protocol is (and what features to support).
... | [
"def",
"get_environ",
"(",
"self",
")",
":",
"req",
"=",
"self",
".",
"req",
"req_conn",
"=",
"req",
".",
"conn",
"env",
"=",
"{",
"# set a non-standard environ entry so the WSGI app can know what",
"# the *real* server protocol is (and what features to support).",
"# See h... | 39.171429 | 0.000711 |
def bounding_box(alpha, threshold=0.1):
"""
Returns a bounding box of the support.
Parameters
----------
alpha : ndarray, ndim=2
Any one-channel image where the background has zero or low intensity.
threshold : float
The threshold that divides background from foreground.
Re... | [
"def",
"bounding_box",
"(",
"alpha",
",",
"threshold",
"=",
"0.1",
")",
":",
"assert",
"alpha",
".",
"ndim",
"==",
"2",
"# Take the bounding box of the support, with a certain threshold.",
"supp_axs",
"=",
"[",
"alpha",
".",
"max",
"(",
"axis",
"=",
"1",
"-",
... | 31.884615 | 0.001171 |
def update(self, **kwargs):
"""
Update existing user.
https://www.keycloak.org/docs-api/2.5/rest-api/index.html#_userrepresentation
:param str first_name: first_name for user
:param str last_name: last_name for user
:param str email: Email for user
:param bool e... | [
"def",
"update",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"payload",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"self",
".",
"user",
".",
"items",
"(",
")",
":",
"payload",
"[",
"k",
"]",
"=",
"v",
"for",
"key",
"in",
"USER_KWARGS",
":... | 35.28125 | 0.001724 |
def _parse_timestamp(tokens):
"""Parses each token in the given `_TimestampTokens` and marshals the numeric components into a `Timestamp`."""
def parse():
precision = TimestampPrecision.YEAR
off_hour = tokens[_TimestampState.OFF_HOUR]
off_minutes = tokens[_TimestampState.OFF_MINUTE]
... | [
"def",
"_parse_timestamp",
"(",
"tokens",
")",
":",
"def",
"parse",
"(",
")",
":",
"precision",
"=",
"TimestampPrecision",
".",
"YEAR",
"off_hour",
"=",
"tokens",
"[",
"_TimestampState",
".",
"OFF_HOUR",
"]",
"off_minutes",
"=",
"tokens",
"[",
"_TimestampState... | 36.402597 | 0.001389 |
def sign_in(self, email=None, password=None):
"""Signs in a user, either with the specified email address and password, or a returning user."""
from .pages.sign_in import SignIn
sign_in = SignIn(self.selenium, self.timeout)
sign_in.sign_in(email, password) | [
"def",
"sign_in",
"(",
"self",
",",
"email",
"=",
"None",
",",
"password",
"=",
"None",
")",
":",
"from",
".",
"pages",
".",
"sign_in",
"import",
"SignIn",
"sign_in",
"=",
"SignIn",
"(",
"self",
".",
"selenium",
",",
"self",
".",
"timeout",
")",
"sig... | 56.8 | 0.010417 |
def get_voltage_at_bus_bar(grid, tree):
"""
Determine voltage level at bus bar of MV-LV substation
Parameters
----------
grid : LVGridDing0
Ding0 grid object
tree : :networkx:`NetworkX Graph Obj< >`
Tree of grid topology:
Returns
-------
:any:`list`
Voltage ... | [
"def",
"get_voltage_at_bus_bar",
"(",
"grid",
",",
"tree",
")",
":",
"# voltage at substation bus bar",
"r_mv_grid",
",",
"x_mv_grid",
"=",
"get_mv_impedance",
"(",
"grid",
")",
"r_trafo",
"=",
"sum",
"(",
"[",
"tr",
".",
"r",
"for",
"tr",
"in",
"grid",
".",... | 39.354167 | 0.000517 |
def make_witness_input(outpoint, sequence):
'''
Outpoint, int -> TxIn
'''
if 'decred' in riemann.get_current_network_name():
return tx.DecredTxIn(
outpoint=outpoint,
sequence=utils.i2le_padded(sequence, 4))
return tx.TxIn(outpoint=outpoint,
stack_sc... | [
"def",
"make_witness_input",
"(",
"outpoint",
",",
"sequence",
")",
":",
"if",
"'decred'",
"in",
"riemann",
".",
"get_current_network_name",
"(",
")",
":",
"return",
"tx",
".",
"DecredTxIn",
"(",
"outpoint",
"=",
"outpoint",
",",
"sequence",
"=",
"utils",
".... | 34.666667 | 0.002342 |
def crypto_box_seal(message, pk):
"""
Encrypts and returns a message ``message`` using an ephemeral secret key
and the public key ``pk``.
The ephemeral public key, which is embedded in the sealed box, is also
used, in combination with ``pk``, to derive the nonce needed for the
underlying box con... | [
"def",
"crypto_box_seal",
"(",
"message",
",",
"pk",
")",
":",
"ensure",
"(",
"isinstance",
"(",
"message",
",",
"bytes",
")",
",",
"\"input message must be bytes\"",
",",
"raising",
"=",
"TypeError",
")",
"ensure",
"(",
"isinstance",
"(",
"pk",
",",
"bytes"... | 28.527778 | 0.000942 |
def whois_history(self, query, **kwargs):
"""Pass in a domain name."""
return self._results('whois-history', '/v1/{0}/whois/history'.format(query), items_path=('history', ), **kwargs) | [
"def",
"whois_history",
"(",
"self",
",",
"query",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_results",
"(",
"'whois-history'",
",",
"'/v1/{0}/whois/history'",
".",
"format",
"(",
"query",
")",
",",
"items_path",
"=",
"(",
"'history'",
","... | 65.666667 | 0.015075 |
def execute(path, arguments):
"""
Wrapper around execv():
* fork()s before exec()ing (in order to run the command in a subprocess)
* wait for the subprocess to finish before returning (blocks the parent
process)
This is **hyper** simplistic. This *does not* handle **many** edge cases.
*... | [
"def",
"execute",
"(",
"path",
",",
"arguments",
")",
":",
"pid",
"=",
"os",
".",
"fork",
"(",
")",
"if",
"pid",
"==",
"0",
":",
"try",
":",
"os",
".",
"execv",
"(",
"path",
",",
"arguments",
")",
"finally",
":",
"sys",
".",
"exit",
"(",
"1",
... | 28.961538 | 0.001285 |
async def node(self, node, *, dc=None, watch=None, consistency=None):
"""Returns the health info of a node.
Parameters:
node (ObjectID): Node ID
dc (str): Specify datacenter that will be used.
Defaults to the agent's local datacenter.
watch (Blo... | [
"async",
"def",
"node",
"(",
"self",
",",
"node",
",",
"*",
",",
"dc",
"=",
"None",
",",
"watch",
"=",
"None",
",",
"consistency",
"=",
"None",
")",
":",
"node_id",
"=",
"extract_attr",
"(",
"node",
",",
"keys",
"=",
"[",
"\"Node\"",
",",
"\"ID\"",... | 37.740741 | 0.000956 |
def _split_sympy_quantum_factor(expr):
"""Split a product into sympy and qnet factors
This is a helper routine for applying some sympy transformation on an
arbitrary product-like expression in QNET. The idea is this::
expr -> sympy_factor, quantum_factor
sympy_factor -> sympy_function(symp... | [
"def",
"_split_sympy_quantum_factor",
"(",
"expr",
")",
":",
"from",
"qnet",
".",
"algebra",
".",
"core",
".",
"abstract_quantum_algebra",
"import",
"(",
"QuantumExpression",
",",
"ScalarTimesQuantumExpression",
")",
"from",
"qnet",
".",
"algebra",
".",
"core",
".... | 40.771429 | 0.000684 |
def cleanup(self, ctime=None):
'''
This method is called iteratively by the connection owning it.
Its job is to control the size of cache and remove old entries.
'''
ctime = ctime or time.time()
if self.last_cleanup:
self.average_cleanup_time.add_point(ctime -... | [
"def",
"cleanup",
"(",
"self",
",",
"ctime",
"=",
"None",
")",
":",
"ctime",
"=",
"ctime",
"or",
"time",
".",
"time",
"(",
")",
"if",
"self",
".",
"last_cleanup",
":",
"self",
".",
"average_cleanup_time",
".",
"add_point",
"(",
"ctime",
"-",
"self",
... | 40.492308 | 0.001113 |
def wr_txt(self, fout_txt):
"""Write counts of GO terms at all levels and depths."""
from goatools.wr_tbl import prt_txt
data = self.get_data()
with open(fout_txt, 'w') as prt:
prtfmt = "{Depth_Level:>7} " \
"{BP_D:6,} {MF_D:6,} {CC_D:>6,} " \
... | [
"def",
"wr_txt",
"(",
"self",
",",
"fout_txt",
")",
":",
"from",
"goatools",
".",
"wr_tbl",
"import",
"prt_txt",
"data",
"=",
"self",
".",
"get_data",
"(",
")",
"with",
"open",
"(",
"fout_txt",
",",
"'w'",
")",
"as",
"prt",
":",
"prtfmt",
"=",
"\"{De... | 54.866667 | 0.002389 |
def close(self):
"""
Close the channel by handshaking with the server.
This method is a :ref:`coroutine <coroutine>`.
"""
# If we aren't already closed ask for server to close
if not self.is_closed():
self._closing = True
# Let the ChannelActor do... | [
"def",
"close",
"(",
"self",
")",
":",
"# If we aren't already closed ask for server to close",
"if",
"not",
"self",
".",
"is_closed",
"(",
")",
":",
"self",
".",
"_closing",
"=",
"True",
"# Let the ChannelActor do the actual close operations.",
"# It will do the work on Cl... | 37.636364 | 0.002356 |
def queryBuilderWidget( self ):
"""
Returns the query builder widget instance that this widget is \
associated with.
:return <XQueryBuilderWidget>
"""
from projexui.widgets.xquerybuilderwidget import XQueryBuilderWidget
builder = self.parent(... | [
"def",
"queryBuilderWidget",
"(",
"self",
")",
":",
"from",
"projexui",
".",
"widgets",
".",
"xquerybuilderwidget",
"import",
"XQueryBuilderWidget",
"builder",
"=",
"self",
".",
"parent",
"(",
")",
"while",
"(",
"builder",
"and",
"not",
"isinstance",
"(",
"bui... | 32.5 | 0.019231 |
def calcfluxscale(d, imstd_med, flagfrac_med):
""" Given state dict and noise properties, estimate flux scale at the VLA
imstd and flagfrac are expected to be median (typical) values from sample in merged noise pkl.
"""
# useful functions and VLA parameters
sensitivity = lambda sefd, dt, bw, eta,... | [
"def",
"calcfluxscale",
"(",
"d",
",",
"imstd_med",
",",
"flagfrac_med",
")",
":",
"# useful functions and VLA parameters",
"sensitivity",
"=",
"lambda",
"sefd",
",",
"dt",
",",
"bw",
",",
"eta",
",",
"nbl",
",",
"npol",
":",
"sefd",
"/",
"(",
"eta",
"*",
... | 38.941176 | 0.008106 |
def calc_dewpoint(temp, hum):
'''
calculates the dewpoint via the formula from weatherwise.org
return the dewpoint in degrees F.
'''
c = fahrenheit_to_celsius(temp)
x = 1 - 0.01 * hum;
dewpoint = (14.55 + 0.114 * c) * x;
dewpoint = dewpoint + ((2.5 + 0.007 * c) * x) ** 3;
dewpoint ... | [
"def",
"calc_dewpoint",
"(",
"temp",
",",
"hum",
")",
":",
"c",
"=",
"fahrenheit_to_celsius",
"(",
"temp",
")",
"x",
"=",
"1",
"-",
"0.01",
"*",
"hum",
"dewpoint",
"=",
"(",
"14.55",
"+",
"0.114",
"*",
"c",
")",
"*",
"x",
"dewpoint",
"=",
"dewpoint... | 28.066667 | 0.013793 |
def listen_on_tcp_port():
"""listen_on_tcp_port
Run a simple server for processing messages over ``TCP``.
``LISTEN_ON_HOST`` - listen on this host ip address
``LISTEN_ON_PORT`` - listen on this ``TCP`` port
``LISTEN_SIZE`` - listen on to packets of this size
``LISTEN_SLEEP`` - sleep this nu... | [
"def",
"listen_on_tcp_port",
"(",
")",
":",
"host",
"=",
"os",
".",
"getenv",
"(",
"\"LISTEN_ON_HOST\"",
",",
"\"127.0.0.1\"",
")",
".",
"strip",
"(",
")",
".",
"lstrip",
"(",
")",
"port",
"=",
"int",
"(",
"os",
".",
"getenv",
"(",
"\"LISTEN_ON_PORT\"",
... | 26.631579 | 0.000381 |
def restrict(self,subinterval):
"""
Return a Polyfun that matches self on subinterval.
"""
if (subinterval[0] < self._domain[0]) or (subinterval[1] > self._domain[1]):
raise ValueError("Can only restrict to subinterval")
return self.from_function(self, subinterval) | [
"def",
"restrict",
"(",
"self",
",",
"subinterval",
")",
":",
"if",
"(",
"subinterval",
"[",
"0",
"]",
"<",
"self",
".",
"_domain",
"[",
"0",
"]",
")",
"or",
"(",
"subinterval",
"[",
"1",
"]",
">",
"self",
".",
"_domain",
"[",
"1",
"]",
")",
":... | 44.428571 | 0.012618 |
def GaussianFilterCore(x_sigma=0.0, y_sigma=0.0):
"""Gaussian filter generator core.
Alternative to the :py:class:`GaussianFilter` component that can be
used to make a non-reconfigurable resizer::
resize = Resize()
resize.filter(GaussianFilterCore(x_sigma=1.5))
...
start(..... | [
"def",
"GaussianFilterCore",
"(",
"x_sigma",
"=",
"0.0",
",",
"y_sigma",
"=",
"0.0",
")",
":",
"def",
"filter_1D",
"(",
"sigma",
")",
":",
"alpha",
"=",
"1.0",
"/",
"(",
"2.0",
"*",
"(",
"max",
"(",
"sigma",
",",
"0.0001",
")",
"**",
"2.0",
")",
... | 32.089286 | 0.00054 |
def compute_rows_sum(hdf5_file, path, N_columns, N_processes, method = 'Process'):
"""Parallel computation of the sums across the rows of two-dimensional array
accessible at the node specified by 'path' in the 'hdf5_file'
hierarchical data format.
"""
assert isinstance(me... | [
"def",
"compute_rows_sum",
"(",
"hdf5_file",
",",
"path",
",",
"N_columns",
",",
"N_processes",
",",
"method",
"=",
"'Process'",
")",
":",
"assert",
"isinstance",
"(",
"method",
",",
"str",
")",
",",
"\"parameter 'method' must consist in a string of characters\"",
"... | 40.086957 | 0.019058 |
def block_cat(self, Y0, Y1):
r"""Concatenate components corresponding to :math:`\mathbf{y}_0`
and :math:`\mathbf{y}_1` to form :math:`\mathbf{y}\;\;`.
"""
return np.concatenate((Y0, Y1), axis=self.blkaxis) | [
"def",
"block_cat",
"(",
"self",
",",
"Y0",
",",
"Y1",
")",
":",
"return",
"np",
".",
"concatenate",
"(",
"(",
"Y0",
",",
"Y1",
")",
",",
"axis",
"=",
"self",
".",
"blkaxis",
")"
] | 38.833333 | 0.008403 |
def get_endpoint(brain_or_object, default=DEFAULT_ENDPOINT):
"""Calculate the endpoint for this object
:param brain_or_object: A single catalog brain or content object
:type brain_or_object: ATContentType/DexterityContentType/CatalogBrain
:returns: Endpoint for this object
:rtype: string
"""
... | [
"def",
"get_endpoint",
"(",
"brain_or_object",
",",
"default",
"=",
"DEFAULT_ENDPOINT",
")",
":",
"portal_type",
"=",
"get_portal_type",
"(",
"brain_or_object",
")",
"resource",
"=",
"portal_type_to_resource",
"(",
"portal_type",
")",
"# Try to get the right namespaced en... | 39.095238 | 0.001189 |
def set_room_name(self, room_id, name, timestamp=None):
"""Perform PUT /rooms/$room_id/state/m.room.name
Args:
room_id (str): The room ID
name (str): The new room name
timestamp (int): Set origin_server_ts (For application services only)
"""
body = {
... | [
"def",
"set_room_name",
"(",
"self",
",",
"room_id",
",",
"name",
",",
"timestamp",
"=",
"None",
")",
":",
"body",
"=",
"{",
"\"name\"",
":",
"name",
"}",
"return",
"self",
".",
"send_state_event",
"(",
"room_id",
",",
"\"m.room.name\"",
",",
"body",
","... | 39.181818 | 0.00907 |
def has_waveform_packet(self):
""" Returns True if the point format has waveform packet dimensions
"""
dimensions = set(self.dimension_names)
return all(name in dimensions for name in dims.WAVEFORM_FIELDS_NAMES) | [
"def",
"has_waveform_packet",
"(",
"self",
")",
":",
"dimensions",
"=",
"set",
"(",
"self",
".",
"dimension_names",
")",
"return",
"all",
"(",
"name",
"in",
"dimensions",
"for",
"name",
"in",
"dims",
".",
"WAVEFORM_FIELDS_NAMES",
")"
] | 47.8 | 0.00823 |
def parse(self, handler):
"""
Main method to parse the Sonata files and call the appropriate methods
in the handler
"""
########################################################################
# load the main configuration scripts
main_config_filename =... | [
"def",
"parse",
"(",
"self",
",",
"handler",
")",
":",
"########################################################################",
"# load the main configuration scripts ",
"main_config_filename",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"self",
".",
"parameters",
"... | 50.564756 | 0.016306 |
def vlan_id(self):
"""
VLAN ID for this interface, if any
:return: VLAN identifier
:rtype: str
"""
nicid = self.nicid
if nicid:
v = nicid.split('.')
if len(v) > 1:
return nicid.split('.')[1] | [
"def",
"vlan_id",
"(",
"self",
")",
":",
"nicid",
"=",
"self",
".",
"nicid",
"if",
"nicid",
":",
"v",
"=",
"nicid",
".",
"split",
"(",
"'.'",
")",
"if",
"len",
"(",
"v",
")",
">",
"1",
":",
"return",
"nicid",
".",
"split",
"(",
"'.'",
")",
"[... | 23.666667 | 0.010169 |
def write(self, data):
"""Write ``data`` into the wire.
Returns an empty tuple or a :class:`~asyncio.Future` if this
protocol has paused writing.
"""
if self.closed:
raise ConnectionResetError(
'Transport closed - cannot write on %s' % self
... | [
"def",
"write",
"(",
"self",
",",
"data",
")",
":",
"if",
"self",
".",
"closed",
":",
"raise",
"ConnectionResetError",
"(",
"'Transport closed - cannot write on %s'",
"%",
"self",
")",
"else",
":",
"t",
"=",
"self",
".",
"transport",
"if",
"self",
".",
"_p... | 37.482759 | 0.001794 |
def load_config():
"""
Load settings from default config and optionally
overwrite with config file and commandline parameters
(in that order).
"""
# We start with the default config
config = flatten(default_config.DEFAULT_CONFIG)
# Read commandline arguments
cli_config = flatten(par... | [
"def",
"load_config",
"(",
")",
":",
"# We start with the default config",
"config",
"=",
"flatten",
"(",
"default_config",
".",
"DEFAULT_CONFIG",
")",
"# Read commandline arguments",
"cli_config",
"=",
"flatten",
"(",
"parse_args",
"(",
")",
")",
"if",
"\"configfile\... | 32.928571 | 0.001054 |
def process_cpu_line(self, words):
"""
Process the line starting with "Cpu(s):"
Example log: Cpu(s): 1.3%us, 0.5%sy, 0.0%ni, 98.2%id, 0.0%wa, 0.0%hi, 0.0%si, 0.0%st
"""
values = {}
for word in words[1:]:
val, key = word.split('%')
values['cpu_' + key.strip(',')] = val
sel... | [
"def",
"process_cpu_line",
"(",
"self",
",",
"words",
")",
":",
"values",
"=",
"{",
"}",
"for",
"word",
"in",
"words",
"[",
"1",
":",
"]",
":",
"val",
",",
"key",
"=",
"word",
".",
"split",
"(",
"'%'",
")",
"values",
"[",
"'cpu_'",
"+",
"key",
... | 30.909091 | 0.011429 |
def wait_for_net_service(server, port, timeout=None, poll_interval=0.1):
""" Wait for network service to appear
@param timeout: in seconds, if None or 0 wait forever
@return: True of False, if timeout is None may return only True or
throw unhandled network exception
"""
impo... | [
"def",
"wait_for_net_service",
"(",
"server",
",",
"port",
",",
"timeout",
"=",
"None",
",",
"poll_interval",
"=",
"0.1",
")",
":",
"import",
"socket",
"import",
"errno",
"s",
"=",
"socket",
".",
"socket",
"(",
")",
"if",
"timeout",
":",
"from",
"time",
... | 32.125 | 0.001511 |
def parse_stdout(
stdout,
prediction_method_name,
sequence_key_mapping,
key_index,
offset_index,
peptide_index,
allele_index,
ic50_index,
rank_index,
log_ic50_index,
ignored_value_indices={},
transforms={}):
"""
Gene... | [
"def",
"parse_stdout",
"(",
"stdout",
",",
"prediction_method_name",
",",
"sequence_key_mapping",
",",
"key_index",
",",
"offset_index",
",",
"peptide_index",
",",
"allele_index",
",",
"ic50_index",
",",
"rank_index",
",",
"log_ic50_index",
",",
"ignored_value_indices",... | 31.103448 | 0.001075 |
def kl(Ks, dim, num_q, rhos, nus, clamp=True):
r'''
Estimate the KL divergence between distributions:
\int p(x) \log (p(x) / q(x))
using the kNN-based estimator (5) of
Qing Wang, Sanjeev R Kulkarni, and Sergio Verdu (2009).
Divergence Estimation for Multidimensional Densities Via
... | [
"def",
"kl",
"(",
"Ks",
",",
"dim",
",",
"num_q",
",",
"rhos",
",",
"nus",
",",
"clamp",
"=",
"True",
")",
":",
"est",
"=",
"dim",
"*",
"np",
".",
"mean",
"(",
"np",
".",
"log",
"(",
"nus",
")",
"-",
"np",
".",
"log",
"(",
"rhos",
")",
",... | 35.954545 | 0.001232 |
def _define(self):
"""
gate ccx a,b,c
{
h c; cx b,c; tdg c; cx a,c;
t c; cx b,c; tdg c; cx a,c;
t b; t c; h c; cx a,b;
t a; tdg b; cx a,b;}
"""
definition = []
q = QuantumRegister(3, "q")
rule = [
(HGate(), [q[2]], []),
... | [
"def",
"_define",
"(",
"self",
")",
":",
"definition",
"=",
"[",
"]",
"q",
"=",
"QuantumRegister",
"(",
"3",
",",
"\"q\"",
")",
"rule",
"=",
"[",
"(",
"HGate",
"(",
")",
",",
"[",
"q",
"[",
"2",
"]",
"]",
",",
"[",
"]",
")",
",",
"(",
"Cnot... | 30.548387 | 0.002047 |
def load_params_from_file(self, fname: str, allow_missing_params: bool = False):
"""
Loads parameters from a file and sets the parameters of the underlying module and this model instance.
:param fname: File name to load parameters from.
:param allow_missing_params: If set, the given par... | [
"def",
"load_params_from_file",
"(",
"self",
",",
"fname",
":",
"str",
",",
"allow_missing_params",
":",
"bool",
"=",
"False",
")",
":",
"super",
"(",
")",
".",
"load_params_from_file",
"(",
"fname",
")",
"# sets self.params & self.aux_params",
"self",
".",
"mod... | 58.727273 | 0.009146 |
def _write_weight_histograms(self, iteration:int)->None:
"Writes model weight histograms to Tensorboard."
generator, critic = self.learn.gan_trainer.generator, self.learn.gan_trainer.critic
self.hist_writer.write(model=generator, iteration=iteration, tbwriter=self.tbwriter, name='generator')
... | [
"def",
"_write_weight_histograms",
"(",
"self",
",",
"iteration",
":",
"int",
")",
"->",
"None",
":",
"generator",
",",
"critic",
"=",
"self",
".",
"learn",
".",
"gan_trainer",
".",
"generator",
",",
"self",
".",
"learn",
".",
"gan_trainer",
".",
"critic",... | 84 | 0.016509 |
def _build_flash_regions(self):
"""! @brief Converts ROM memory regions to flash regions.
Each ROM region in the `_regions` attribute is converted to a flash region if a matching
flash algo can be found. If the flash has multiple sector sizes, then separate flash
regions will be... | [
"def",
"_build_flash_regions",
"(",
"self",
")",
":",
"# Must have a default ram.",
"if",
"self",
".",
"_default_ram",
"is",
"None",
":",
"LOG",
".",
"warning",
"(",
"\"CMSIS-Pack device %s has no default RAM defined, cannot program flash\"",
"%",
"self",
".",
"part_numbe... | 47.975 | 0.00817 |
def arcsine(x, null=(-np.inf, np.inf)):
'''
arcsine(x) is equivalent to asin(x) except that it also works on sparse arrays.
The optional argument null (default, (-numpy.inf, numpy.inf)) may be specified to indicate what
value(s) should be assigned when x < -1 or x > 1. If only one number is given, then... | [
"def",
"arcsine",
"(",
"x",
",",
"null",
"=",
"(",
"-",
"np",
".",
"inf",
",",
"np",
".",
"inf",
")",
")",
":",
"if",
"sps",
".",
"issparse",
"(",
"x",
")",
":",
"x",
"=",
"x",
".",
"copy",
"(",
")",
"x",
".",
"data",
"=",
"arcsine",
"(",... | 39.208333 | 0.01556 |
def create_usuario(self):
"""Get an instance of usuario services facade."""
return Usuario(
self.networkapi_url,
self.user,
self.password,
self.user_ldap) | [
"def",
"create_usuario",
"(",
"self",
")",
":",
"return",
"Usuario",
"(",
"self",
".",
"networkapi_url",
",",
"self",
".",
"user",
",",
"self",
".",
"password",
",",
"self",
".",
"user_ldap",
")"
] | 30.285714 | 0.009174 |
def AddAccelerator(self, modifiers, key, action):
"""
Add an accelerator.
Modifiers and key follow the same pattern as the list used to create wx.AcceleratorTable objects.
"""
newId = wx.NewId()
self.Bind(wx.EVT_MENU, action, id = newId)
self.RawAcceleratorTable.append((modifiers, key, newId))
self.SetAcceler... | [
"def",
"AddAccelerator",
"(",
"self",
",",
"modifiers",
",",
"key",
",",
"action",
")",
":",
"newId",
"=",
"wx",
".",
"NewId",
"(",
")",
"self",
".",
"Bind",
"(",
"wx",
".",
"EVT_MENU",
",",
"action",
",",
"id",
"=",
"newId",
")",
"self",
".",
"R... | 34.545455 | 0.028205 |
def _get_path_entry_from_string(self, query_string, first_found=True, full_path=False):
""" Parses a string to form a list of strings that represents a possible config entry header
:param query_string: str, query string we are looking for
:param first_found: bool, return first found entry or en... | [
"def",
"_get_path_entry_from_string",
"(",
"self",
",",
"query_string",
",",
"first_found",
"=",
"True",
",",
"full_path",
"=",
"False",
")",
":",
"iter_matches",
"=",
"gen_dict_key_matches",
"(",
"query_string",
",",
"self",
".",
"config_file_contents",
",",
"ful... | 68.133333 | 0.008687 |
def parse_docword(filename, vocab_filename):
"""
Parse a file that's in "docword" format. This consists of a 3-line header
comprised of the document count, the vocabulary count, and the number of
tokens, i.e. unique (doc_id, word_id) pairs. After the header, each line
contains a space-separated trip... | [
"def",
"parse_docword",
"(",
"filename",
",",
"vocab_filename",
")",
":",
"vocab",
"=",
"_turicreate",
".",
"SFrame",
".",
"read_csv",
"(",
"vocab_filename",
",",
"header",
"=",
"None",
")",
"[",
"'X1'",
"]",
"vocab",
"=",
"list",
"(",
"vocab",
")",
"sf"... | 32.134615 | 0.002323 |
def evaluate(self, values):
"""Evaluate the "OR" expression
Check if the left "or" right expression
evaluate to True.
"""
return self.left.evaluate(values) or self.right.evaluate(values) | [
"def",
"evaluate",
"(",
"self",
",",
"values",
")",
":",
"return",
"self",
".",
"left",
".",
"evaluate",
"(",
"values",
")",
"or",
"self",
".",
"right",
".",
"evaluate",
"(",
"values",
")"
] | 31.571429 | 0.008811 |
def get_agents_by_ids(self, agent_ids):
"""Gets an ``AgentList`` corresponding to the given ``IdList``.
In plenary mode, the returned list contains all of the agents
specified in the ``Id`` list, in the order of the list,
including duplicates, or an error results if an ``Id`` in the
... | [
"def",
"get_agents_by_ids",
"(",
"self",
",",
"agent_ids",
")",
":",
"# Implemented from template for",
"# osid.resource.ResourceLookupSession.get_resources_by_ids",
"# NOTE: This implementation currently ignores plenary view",
"collection",
"=",
"JSONClientValidated",
"(",
"'authentic... | 47.658537 | 0.002006 |
def update_campaign_metrics(self, campaign_id, **kwargs): # noqa: E501
"""Get campaign metrics # noqa: E501
Get detailed statistics of a campaign. # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass asynchronous=True... | [
"def",
"update_campaign_metrics",
"(",
"self",
",",
"campaign_id",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'asynchronous'",
")",
":",
"return",
"self",
... | 46.761905 | 0.001996 |
def is_registered(ext):
''' Returns true when a template exists on an exact match of the provided file extension '''
return Lean.template_mappings.has_key(ext.lower()) and len(Lean.template_mappings[ext]) | [
"def",
"is_registered",
"(",
"ext",
")",
":",
"return",
"Lean",
".",
"template_mappings",
".",
"has_key",
"(",
"ext",
".",
"lower",
"(",
")",
")",
"and",
"len",
"(",
"Lean",
".",
"template_mappings",
"[",
"ext",
"]",
")"
] | 70 | 0.018868 |
def hexbin(self, x, y, size, orientation="pointytop", palette="Viridis256", line_color=None, fill_color=None, aspect_scale=1, **kwargs):
''' Perform a simple equal-weight hexagonal binning.
A :class:`~bokeh.models._glyphs.HexTile` glyph will be added to display
the binning. The :class:`~bokeh.m... | [
"def",
"hexbin",
"(",
"self",
",",
"x",
",",
"y",
",",
"size",
",",
"orientation",
"=",
"\"pointytop\"",
",",
"palette",
"=",
"\"Viridis256\"",
",",
"line_color",
"=",
"None",
",",
"fill_color",
"=",
"None",
",",
"aspect_scale",
"=",
"1",
",",
"*",
"*"... | 42.190909 | 0.001684 |
def get_og_title(self):
"""
return meta_title if exists otherwise fall back to title
"""
if hasattr(self, 'meta_title') and self.meta_title:
return self.meta_title
return self.get_title() | [
"def",
"get_og_title",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
",",
"'meta_title'",
")",
"and",
"self",
".",
"meta_title",
":",
"return",
"self",
".",
"meta_title",
"return",
"self",
".",
"get_title",
"(",
")"
] | 33.285714 | 0.008368 |
def staticMovingAverage2(x, N=3, mode='reflect'):
"""
moving average filter for 1d arrays
supported modes for boundary handling: 'reflect' , 'constant'
"""
assert N > 1
x2 = np.empty(shape=x.shape[0] + N, dtype=x.dtype)
start = N - 2
if N == 2:
start = 1
end = N - start
... | [
"def",
"staticMovingAverage2",
"(",
"x",
",",
"N",
"=",
"3",
",",
"mode",
"=",
"'reflect'",
")",
":",
"assert",
"N",
">",
"1",
"x2",
"=",
"np",
".",
"empty",
"(",
"shape",
"=",
"x",
".",
"shape",
"[",
"0",
"]",
"+",
"N",
",",
"dtype",
"=",
"x... | 25.382353 | 0.001116 |
def lindblad_terms(gamma, rho, Ne, verbose=1):
u"""Return the Lindblad terms for decays gamma in matrix form.
>>> from sympy import pprint
>>> aux = define_frequencies(4, explicitly_antisymmetric=True)
>>> omega_level, omega, gamma = aux
>>> gamma = gamma.subs({gamma[2, 0]:0, gamma[3, 0]:0, gamma[3... | [
"def",
"lindblad_terms",
"(",
"gamma",
",",
"rho",
",",
"Ne",
",",
"verbose",
"=",
"1",
")",
":",
"# We count the necessary Lindblad operators.",
"Nterms",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"Ne",
")",
":",
"for",
"j",
"in",
"range",
"(",
"i",
"... | 44.360656 | 0.000362 |
def set(self, keyword, value):
"""Set the element of the list after the given keyword.
Parameters
----------
keyword : str
The keyword parameter to find in the list.
Putting a colon before the keyword is optional, if no colon is
given, it is added aut... | [
"def",
"set",
"(",
"self",
",",
"keyword",
",",
"value",
")",
":",
"if",
"not",
"keyword",
".",
"startswith",
"(",
"':'",
")",
":",
"keyword",
"=",
"':'",
"+",
"keyword",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"value",
"=",
"KQMLTo... | 35.029412 | 0.001634 |
def projection_matrix(point, normal, direction=None,
perspective=None, pseudo=False):
"""Return matrix to project onto plane defined by point and normal.
Using either perspective point, projection direction, or none of both.
If pseudo is True, perspective projections will preserve re... | [
"def",
"projection_matrix",
"(",
"point",
",",
"normal",
",",
"direction",
"=",
"None",
",",
"perspective",
"=",
"None",
",",
"pseudo",
"=",
"False",
")",
":",
"M",
"=",
"numpy",
".",
"identity",
"(",
"4",
")",
"point",
"=",
"numpy",
".",
"array",
"(... | 41.15 | 0.000396 |
def dropout(input_layer, keep_prob, phase=Phase.train, name=PROVIDED):
"""Aplies dropout if this is in the train phase."""
if phase == Phase.train:
return tf.nn.dropout(input_layer, keep_prob, name=name)
else:
return input_layer | [
"def",
"dropout",
"(",
"input_layer",
",",
"keep_prob",
",",
"phase",
"=",
"Phase",
".",
"train",
",",
"name",
"=",
"PROVIDED",
")",
":",
"if",
"phase",
"==",
"Phase",
".",
"train",
":",
"return",
"tf",
".",
"nn",
".",
"dropout",
"(",
"input_layer",
... | 39.5 | 0.016529 |
def write_newick(rootnode,
features=None,
format=1,
format_root_node=True,
is_leaf_fn=None,
dist_formatter=None,
support_formatter=None,
name_formatter=None):
"""
Iteratively export a tree structure and returns its NHX
representation.
"""
newick = []
leaf = is_leaf_fn if... | [
"def",
"write_newick",
"(",
"rootnode",
",",
"features",
"=",
"None",
",",
"format",
"=",
"1",
",",
"format_root_node",
"=",
"True",
",",
"is_leaf_fn",
"=",
"None",
",",
"dist_formatter",
"=",
"None",
",",
"support_formatter",
"=",
"None",
",",
"name_formatt... | 39.5 | 0.012971 |
def write_k_record(self, *args):
"""
Write a K record::
writer.write_k_record_extensions([
('FXA', 3), ('SIU', 2), ('ENL', 3),
])
writer.write_k_record(datetime.time(2, 3, 4), ['023', 13, 2])
# -> J030810FXA1112SIU1315ENL
# -... | [
"def",
"write_k_record",
"(",
"self",
",",
"*",
"args",
")",
":",
"num_args",
"=",
"len",
"(",
"args",
")",
"if",
"num_args",
"not",
"in",
"(",
"1",
",",
"2",
")",
":",
"raise",
"ValueError",
"(",
"'Invalid number of parameters received'",
")",
"if",
"nu... | 30.563636 | 0.001153 |
def verify_verify(self, id, token):
"""Verify the token of a specific verification."""
return Verify().load(self.request('verify/' + str(id), params={'token': token})) | [
"def",
"verify_verify",
"(",
"self",
",",
"id",
",",
"token",
")",
":",
"return",
"Verify",
"(",
")",
".",
"load",
"(",
"self",
".",
"request",
"(",
"'verify/'",
"+",
"str",
"(",
"id",
")",
",",
"params",
"=",
"{",
"'token'",
":",
"token",
"}",
"... | 60.333333 | 0.016393 |
def is_key(cls, result):
"""Return ``True`` if result is a key object."""
from boto.gs.key import Key
return isinstance(result, Key) | [
"def",
"is_key",
"(",
"cls",
",",
"result",
")",
":",
"from",
"boto",
".",
"gs",
".",
"key",
"import",
"Key",
"return",
"isinstance",
"(",
"result",
",",
"Key",
")"
] | 30.6 | 0.012739 |
def get_rdataset(self, name, rdtype, covers=dns.rdatatype.NONE,
create=False):
"""Look for rdata with the specified name and type in the zone,
and return an rdataset encapsulating it.
The I{name}, I{rdtype}, and I{covers} parameters may be
strings, in which case the... | [
"def",
"get_rdataset",
"(",
"self",
",",
"name",
",",
"rdtype",
",",
"covers",
"=",
"dns",
".",
"rdatatype",
".",
"NONE",
",",
"create",
"=",
"False",
")",
":",
"try",
":",
"rdataset",
"=",
"self",
".",
"find_rdataset",
"(",
"name",
",",
"rdtype",
",... | 36.6875 | 0.00249 |
def assert_is(self, actual_val, expected_type, failure_message='Expected type to be "{1}," but was "{0}"'):
"""
Calls smart_assert, but creates its own assertion closure using
the expected and provided values with the 'is' operator
"""
assertion = lambda: expected_type is actual_... | [
"def",
"assert_is",
"(",
"self",
",",
"actual_val",
",",
"expected_type",
",",
"failure_message",
"=",
"'Expected type to be \"{1},\" but was \"{0}\"'",
")",
":",
"assertion",
"=",
"lambda",
":",
"expected_type",
"is",
"actual_val",
"self",
".",
"webdriver_assert",
"(... | 59.714286 | 0.011792 |
def _needs_git(func):
"""
Small decorator to make sure we have the git repo, or report error
otherwise.
"""
@wraps(func)
def myfunc(*args, **kwargs):
if not WITH_GIT:
raise RuntimeError(
"Dulwich library not available, can't extract info from the "
... | [
"def",
"_needs_git",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"myfunc",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"WITH_GIT",
":",
"raise",
"RuntimeError",
"(",
"\"Dulwich library not available, can't extract info... | 24.5625 | 0.002451 |
def show_member(self, member, **_params):
"""Fetches information of a certain load balancer member."""
return self.get(self.member_path % (member), params=_params) | [
"def",
"show_member",
"(",
"self",
",",
"member",
",",
"*",
"*",
"_params",
")",
":",
"return",
"self",
".",
"get",
"(",
"self",
".",
"member_path",
"%",
"(",
"member",
")",
",",
"params",
"=",
"_params",
")"
] | 59 | 0.011173 |
def uniform_noise(space, low=0, high=1, seed=None):
"""Uniformly distributed noise in ``space``, pointwise ``U(low, high)``.
Parameters
----------
space : `TensorSpace` or `ProductSpace`
The space in which the noise is created.
low : ``space.field`` element or ``space`` `element-like`, opti... | [
"def",
"uniform_noise",
"(",
"space",
",",
"low",
"=",
"0",
",",
"high",
"=",
"1",
",",
"seed",
"=",
"None",
")",
":",
"from",
"odl",
".",
"space",
"import",
"ProductSpace",
"with",
"NumpyRandomSeed",
"(",
"seed",
")",
":",
"if",
"isinstance",
"(",
"... | 37.24 | 0.000523 |
def intensities_from_grid_radii(self, grid_radii):
"""Calculate the intensity of the Gaussian light profile on a grid of radial coordinates.
Parameters
----------
grid_radii : float
The radial distance from the centre of the profile. for each coordinate on the grid.
... | [
"def",
"intensities_from_grid_radii",
"(",
"self",
",",
"grid_radii",
")",
":",
"return",
"np",
".",
"multiply",
"(",
"np",
".",
"divide",
"(",
"self",
".",
"intensity",
",",
"self",
".",
"sigma",
"*",
"np",
".",
"sqrt",
"(",
"2.0",
"*",
"np",
".",
"... | 49.1 | 0.012 |
def dsync_files(self, source, target):
'''Sync directory to directory.'''
src_s3_url = S3URL.is_valid(source)
dst_s3_url = S3URL.is_valid(target)
source_list = self.relative_dir_walk(source)
if len(source_list) == 0 or '.' in source_list:
raise Failure('Sync command need to sync directory to ... | [
"def",
"dsync_files",
"(",
"self",
",",
"source",
",",
"target",
")",
":",
"src_s3_url",
"=",
"S3URL",
".",
"is_valid",
"(",
"source",
")",
"dst_s3_url",
"=",
"S3URL",
".",
"is_valid",
"(",
"target",
")",
"source_list",
"=",
"self",
".",
"relative_dir_walk... | 32.525 | 0.011194 |
def Genra(request):
"""
Generate dict of Dept and its grade.
"""
school = request.GET['school']
c = Course(school=school)
return JsonResponse(c.getGenra(), safe=False) | [
"def",
"Genra",
"(",
"request",
")",
":",
"school",
"=",
"request",
".",
"GET",
"[",
"'school'",
"]",
"c",
"=",
"Course",
"(",
"school",
"=",
"school",
")",
"return",
"JsonResponse",
"(",
"c",
".",
"getGenra",
"(",
")",
",",
"safe",
"=",
"False",
"... | 24 | 0.04023 |
def get_td_qnm(template=None, taper=None, **kwargs):
"""Return a time domain damped sinusoid.
Parameters
----------
template: object
An object that has attached properties. This can be used to substitute
for keyword arguments. A common example would be a row in an xml table.
taper: ... | [
"def",
"get_td_qnm",
"(",
"template",
"=",
"None",
",",
"taper",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"input_params",
"=",
"props",
"(",
"template",
",",
"qnm_required_args",
",",
"*",
"*",
"kwargs",
")",
"f_0",
"=",
"input_params",
".",
"po... | 37.346154 | 0.001254 |
def validate_signature(self, signature, data, encoding='utf8'):
"""Validate the signature for the provided data.
Args:
signature (str or bytes or bytearray): Signature that was provided
for the request.
data (str or bytes or bytearray): Data string to validate ag... | [
"def",
"validate_signature",
"(",
"self",
",",
"signature",
",",
"data",
",",
"encoding",
"=",
"'utf8'",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"string_types",
")",
":",
"data",
"=",
"bytearray",
"(",
"data",
",",
"encoding",
")",
"if",
"isinsta... | 38.92 | 0.002006 |
def draw_bounding_boxes(images, annotations, confidence_threshold=0):
"""
Visualizes bounding boxes (ground truth or predictions) by
returning annotated copies of the images.
Parameters
----------
images: SArray or Image
An `SArray` of type `Image`. A single `Image` instance may also be... | [
"def",
"draw_bounding_boxes",
"(",
"images",
",",
"annotations",
",",
"confidence_threshold",
"=",
"0",
")",
":",
"_numeric_param_check_range",
"(",
"'confidence_threshold'",
",",
"confidence_threshold",
",",
"0.0",
",",
"1.0",
")",
"from",
"PIL",
"import",
"Image",... | 38.155172 | 0.002203 |
def pyoidcMiddleware(func):
"""Common wrapper for the underlying pyoidc library functions.
Reads GET params and POST data before passing it on the library and
converts the response from oic.utils.http_util to wsgi.
:param func: underlying library function
"""
def wrapper(environ, start_response... | [
"def",
"pyoidcMiddleware",
"(",
"func",
")",
":",
"def",
"wrapper",
"(",
"environ",
",",
"start_response",
")",
":",
"data",
"=",
"get_or_post",
"(",
"environ",
")",
"cookies",
"=",
"environ",
".",
"get",
"(",
"\"HTTP_COOKIE\"",
",",
"\"\"",
")",
"resp",
... | 36.357143 | 0.001916 |
def which(program, path=None):
"""
Returns the full path of shell commands.
Replicates the functionality of system which (1) command. Looks
for the named program in the directories indicated in the $PATH
environment variable, and returns the full path if found.
Examples:
>>> system.wh... | [
"def",
"which",
"(",
"program",
",",
"path",
"=",
"None",
")",
":",
"# If path is not given, read the $PATH environment variable.",
"path",
"=",
"path",
"or",
"os",
".",
"environ",
"[",
"\"PATH\"",
"]",
".",
"split",
"(",
"os",
".",
"pathsep",
")",
"abspath",
... | 27.6875 | 0.000727 |
def flash(self, flash):
"""
Turn on or off flashing of the device's LED for physical
identification purposes.
"""
self.m_objPCANBasic.SetValue(self.m_PcanHandle, PCAN_CHANNEL_IDENTIFYING, bool(flash)) | [
"def",
"flash",
"(",
"self",
",",
"flash",
")",
":",
"self",
".",
"m_objPCANBasic",
".",
"SetValue",
"(",
"self",
".",
"m_PcanHandle",
",",
"PCAN_CHANNEL_IDENTIFYING",
",",
"bool",
"(",
"flash",
")",
")"
] | 39.166667 | 0.0125 |
def expand_time(str_time, default_unit='s', multiplier=1):
"""
helper for above functions
"""
parser = re.compile(r'(\d+)([a-zA-Z]*)')
parts = parser.findall(str_time)
result = 0.0
for value, unit in parts:
value = int(value)
unit = unit.lower()
if unit == '':
... | [
"def",
"expand_time",
"(",
"str_time",
",",
"default_unit",
"=",
"'s'",
",",
"multiplier",
"=",
"1",
")",
":",
"parser",
"=",
"re",
".",
"compile",
"(",
"r'(\\d+)([a-zA-Z]*)'",
")",
"parts",
"=",
"parser",
".",
"findall",
"(",
"str_time",
")",
"result",
... | 27.857143 | 0.000991 |
def cached_name_scope(name, top_level=True):
"""
Return a context which either opens and caches a new name scope,
or reenter an existing one.
Args:
top_level(bool): if True, the name scope will always be top-level.
It will not be nested under any existing name scope of the caller.
... | [
"def",
"cached_name_scope",
"(",
"name",
",",
"top_level",
"=",
"True",
")",
":",
"if",
"not",
"top_level",
":",
"current_ns",
"=",
"tf",
".",
"get_default_graph",
"(",
")",
".",
"get_name_scope",
"(",
")",
"if",
"current_ns",
":",
"name",
"=",
"current_ns... | 33.4375 | 0.001818 |
def get_inc(self, native=False):
"""
Get include directories of Windows SDK.
"""
if self.sdk_version == 'v7.0A':
include = os.path.join(self.sdk_dir, 'include')
if os.path.isdir(include):
logging.info(_('using include: %s'), include)
... | [
"def",
"get_inc",
"(",
"self",
",",
"native",
"=",
"False",
")",
":",
"if",
"self",
".",
"sdk_version",
"==",
"'v7.0A'",
":",
"include",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"sdk_dir",
",",
"'include'",
")",
"if",
"os",
".",
"path... | 41.710526 | 0.001233 |
def load_model():
""" Load the model
Parameters
----------
direc: directory with all of the model files
Returns
-------
m: model object
"""
direc = "/home/annaho/TheCannon/code/lamost/mass_age/cn"
m = model.CannonModel(2)
m.coeffs = np.load(direc + "/coeffs.npz")['arr_... | [
"def",
"load_model",
"(",
")",
":",
"direc",
"=",
"\"/home/annaho/TheCannon/code/lamost/mass_age/cn\"",
"m",
"=",
"model",
".",
"CannonModel",
"(",
"2",
")",
"m",
".",
"coeffs",
"=",
"np",
".",
"load",
"(",
"direc",
"+",
"\"/coeffs.npz\"",
")",
"[",
"'arr_0'... | 30.222222 | 0.012478 |
def iter_components(self):
"""Iterate over all defined components yielding IOTile objects."""
names = self.list_components()
for name in names:
yield self.get_component(name) | [
"def",
"iter_components",
"(",
"self",
")",
":",
"names",
"=",
"self",
".",
"list_components",
"(",
")",
"for",
"name",
"in",
"names",
":",
"yield",
"self",
".",
"get_component",
"(",
"name",
")"
] | 29.428571 | 0.009434 |
def to_triple(self, ast_obj=None, fmt="medium"):
"""Convert AST object to BEL triple
Args:
fmt (str): short, medium, long formatted BEL statements
short = short function and short relation format
medium = short function and long relation format
... | [
"def",
"to_triple",
"(",
"self",
",",
"ast_obj",
"=",
"None",
",",
"fmt",
"=",
"\"medium\"",
")",
":",
"if",
"not",
"ast_obj",
":",
"ast_obj",
"=",
"self",
"if",
"self",
".",
"bel_subject",
"and",
"self",
".",
"bel_relation",
"and",
"self",
".",
"bel_o... | 33.586957 | 0.001887 |
def load_ext(self):
"""Read time series data like method |IOSequence.load_ext| of class
|IOSequence|, but with special handling of missing data.
The method's "special handling" is to convert errors to warnings.
We explain the reasons in the documentation on method |Obs.load_ext|
... | [
"def",
"load_ext",
"(",
"self",
")",
":",
"try",
":",
"super",
"(",
")",
".",
"load_ext",
"(",
")",
"except",
"BaseException",
":",
"if",
"hydpy",
".",
"pub",
".",
"options",
".",
"warnmissingsimfile",
":",
"warnings",
".",
"warn",
"(",
"str",
"(",
"... | 38.686567 | 0.000752 |
def rsh(self, num, cin=None):
"""Right shift the farray by *num* places.
The *num* argument must be a non-negative ``int``.
If the *cin* farray is provided, it will be shifted in.
Otherwise, the carry-in is zero.
Returns a two-tuple (farray fs, farray cout),
where *fs*... | [
"def",
"rsh",
"(",
"self",
",",
"num",
",",
"cin",
"=",
"None",
")",
":",
"if",
"num",
"<",
"0",
"or",
"num",
">",
"self",
".",
"size",
":",
"raise",
"ValueError",
"(",
"\"expected 0 <= num <= {0.size}\"",
".",
"format",
"(",
"self",
")",
")",
"if",
... | 38.571429 | 0.001807 |
def interface_endpoints(self):
"""Instance depends on the API version:
* 2018-08-01: :class:`InterfaceEndpointsOperations<azure.mgmt.network.v2018_08_01.operations.InterfaceEndpointsOperations>`
"""
api_version = self._get_api_version('interface_endpoints')
if api_version == ... | [
"def",
"interface_endpoints",
"(",
"self",
")",
":",
"api_version",
"=",
"self",
".",
"_get_api_version",
"(",
"'interface_endpoints'",
")",
"if",
"api_version",
"==",
"'2018-08-01'",
":",
"from",
".",
"v2018_08_01",
".",
"operations",
"import",
"InterfaceEndpointsO... | 61 | 0.008811 |
def on_draw(self):
"""
Run the actual draw calls.
"""
self._update_meshes()
gl.glClear(gl.GL_COLOR_BUFFER_BIT | gl.GL_DEPTH_BUFFER_BIT)
gl.glLoadIdentity()
# pull the new camera transform from the scene
transform_camera = self.scene.graph.get(
... | [
"def",
"on_draw",
"(",
"self",
")",
":",
"self",
".",
"_update_meshes",
"(",
")",
"gl",
".",
"glClear",
"(",
"gl",
".",
"GL_COLOR_BUFFER_BIT",
"|",
"gl",
".",
"GL_DEPTH_BUFFER_BIT",
")",
"gl",
".",
"glLoadIdentity",
"(",
")",
"# pull the new camera transform f... | 39.483516 | 0.000543 |
def _kraus_to_choi(data, input_dim, output_dim):
"""Transform Kraus representation to Choi representation."""
choi = 0
kraus_l, kraus_r = data
if kraus_r is None:
for i in kraus_l:
vec = i.ravel(order='F')
choi += np.outer(vec, vec.conj())
else:
for i, j in zi... | [
"def",
"_kraus_to_choi",
"(",
"data",
",",
"input_dim",
",",
"output_dim",
")",
":",
"choi",
"=",
"0",
"kraus_l",
",",
"kraus_r",
"=",
"data",
"if",
"kraus_r",
"is",
"None",
":",
"for",
"i",
"in",
"kraus_l",
":",
"vec",
"=",
"i",
".",
"ravel",
"(",
... | 35.083333 | 0.002315 |
def mod_repo(repo, basedir=None, **kwargs):
'''
Modify one or more values for a repo. If the repo does not exist, it will
be created, so long as the following values are specified:
repo
name by which the yum refers to the repo
name
a human-readable name for the repo
baseurl
... | [
"def",
"mod_repo",
"(",
"repo",
",",
"basedir",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# Filter out '__pub' arguments, as well as saltenv",
"repo_opts",
"=",
"dict",
"(",
"(",
"x",
",",
"kwargs",
"[",
"x",
"]",
")",
"for",
"x",
"in",
"kwargs",
... | 36.269231 | 0.001548 |
def two_motor_drivetrain(l_motor, r_motor, x_wheelbase=2, speed=5, deadzone=None):
"""
.. deprecated:: 2018.2.0
Use :class:`TwoMotorDrivetrain` instead
"""
return TwoMotorDrivetrain(x_wheelbase, speed, deadzone).get_vector(l_motor, r_motor) | [
"def",
"two_motor_drivetrain",
"(",
"l_motor",
",",
"r_motor",
",",
"x_wheelbase",
"=",
"2",
",",
"speed",
"=",
"5",
",",
"deadzone",
"=",
"None",
")",
":",
"return",
"TwoMotorDrivetrain",
"(",
"x_wheelbase",
",",
"speed",
",",
"deadzone",
")",
".",
"get_v... | 44.333333 | 0.01107 |
def log_event(self, event, payload=None):
"""DEPRECATED"""
if payload is None:
return self.log_kv({logs.EVENT: event})
else:
return self.log_kv({logs.EVENT: event, 'payload': payload}) | [
"def",
"log_event",
"(",
"self",
",",
"event",
",",
"payload",
"=",
"None",
")",
":",
"if",
"payload",
"is",
"None",
":",
"return",
"self",
".",
"log_kv",
"(",
"{",
"logs",
".",
"EVENT",
":",
"event",
"}",
")",
"else",
":",
"return",
"self",
".",
... | 37.833333 | 0.008621 |
def search(self, q, state, labels):
"""Search for issues in Github.
For JSON data returned by Github refer:
https://developer.github.com/v3/search/#search-issues
:param q: query string for search
:param state: the states of the issue
:param labels: labels of the issue
... | [
"def",
"search",
"(",
"self",
",",
"q",
",",
"state",
",",
"labels",
")",
":",
"# TODO: add support for search with labels",
"labels",
"=",
"[",
"'\"{}\"'",
".",
"format",
"(",
"label",
")",
"for",
"label",
"in",
"labels",
"]",
"q",
"=",
"\"'{}'+state:{}+lab... | 36.8 | 0.002119 |
def remove_apppool(name):
# Remove IIS AppPool
'''
Remove an IIS application pool.
:param str name: The name of the IIS application pool.
Usage:
.. code-block:: yaml
defaultapppool-remove:
win_iis.remove_apppool:
- name: DefaultAppPool
'''
ret = {... | [
"def",
"remove_apppool",
"(",
"name",
")",
":",
"# Remove IIS AppPool",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"None",
",",
"'comment'",
":",
"''",
"}",
"current_apppools",
"=",
"__salt__",
"[",
"'w... | 28.111111 | 0.00191 |
def OnSize(self, event):
"""Main window move event"""
# Store window size in config
size = event.GetSize()
config["window_size"] = repr((size.width, size.height)) | [
"def",
"OnSize",
"(",
"self",
",",
"event",
")",
":",
"# Store window size in config",
"size",
"=",
"event",
".",
"GetSize",
"(",
")",
"config",
"[",
"\"window_size\"",
"]",
"=",
"repr",
"(",
"(",
"size",
".",
"width",
",",
"size",
".",
"height",
")",
... | 23.75 | 0.010152 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.