text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def get_client_kwargs(self):
"""Get kwargs for use with the methods in :mod:`nailgun.client`.
This method returns a dict of attributes that can be unpacked and used
as kwargs via the ``**`` operator. For example::
cfg = ServerConfig.get()
client.get(cfg.url + '/api/v2',... | [
"def",
"get_client_kwargs",
"(",
"self",
")",
":",
"config",
"=",
"vars",
"(",
"self",
")",
".",
"copy",
"(",
")",
"config",
".",
"pop",
"(",
"'url'",
")",
"config",
".",
"pop",
"(",
"'version'",
",",
"None",
")",
"return",
"config"
] | 38.76 | 0.002014 |
def catch_exception(exception, message=None):
"""A decorator that gracefully handles exceptions, exiting
with :py:obj:`exit_codes.OTHER_FAILURE`.
"""
def decorator(f):
@click.pass_context
def new_func(ctx, *args, **kwargs):
try:
return ctx.invoke(f, *args, **k... | [
"def",
"catch_exception",
"(",
"exception",
",",
"message",
"=",
"None",
")",
":",
"def",
"decorator",
"(",
"f",
")",
":",
"@",
"click",
".",
"pass_context",
"def",
"new_func",
"(",
"ctx",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
... | 38.8 | 0.001678 |
def find_bounds(model):
"""
Return the median upper and lower bound of the metabolic model.
Bounds can vary from model to model. Cobrapy defaults to (-1000, 1000) but
this may not be the case for merged or autogenerated models. In these
cases, this function is used to iterate over all the bounds of... | [
"def",
"find_bounds",
"(",
"model",
")",
":",
"lower_bounds",
"=",
"np",
".",
"asarray",
"(",
"[",
"rxn",
".",
"lower_bound",
"for",
"rxn",
"in",
"model",
".",
"reactions",
"]",
",",
"dtype",
"=",
"float",
")",
"upper_bounds",
"=",
"np",
".",
"asarray"... | 40.896552 | 0.000824 |
def sample_discrete_from_log(p_log,axis=0,dtype=np.int32):
'samples log probability array along specified axis'
cumvals = np.exp(p_log - np.expand_dims(p_log.max(axis),axis)).cumsum(axis) # cumlogaddexp
thesize = np.array(p_log.shape)
thesize[axis] = 1
randvals = random(size=thesize) * \
... | [
"def",
"sample_discrete_from_log",
"(",
"p_log",
",",
"axis",
"=",
"0",
",",
"dtype",
"=",
"np",
".",
"int32",
")",
":",
"cumvals",
"=",
"np",
".",
"exp",
"(",
"p_log",
"-",
"np",
".",
"expand_dims",
"(",
"p_log",
".",
"max",
"(",
"axis",
")",
",",... | 53.666667 | 0.022403 |
def from_spherical_coords(theta_phi, phi=None):
"""Return the quaternion corresponding to these spherical coordinates
Assumes the spherical coordinates correspond to the quaternion R via
R = exp(phi*z/2) * exp(theta*y/2)
The angles naturally must be in radians for this to make any sense.
Not... | [
"def",
"from_spherical_coords",
"(",
"theta_phi",
",",
"phi",
"=",
"None",
")",
":",
"# Figure out the input angles from either type of input",
"if",
"phi",
"is",
"None",
":",
"theta_phi",
"=",
"np",
".",
"asarray",
"(",
"theta_phi",
",",
"dtype",
"=",
"np",
"."... | 41.056604 | 0.002244 |
def make_safe_filename_from_url(self, url):
'''return a version of url safe for use as a filename'''
r = re.compile("([^a-zA-Z0-9_.-])")
filename = r.sub(lambda m : "%" + str(hex(ord(str(m.group(1))))).upper(), url)
return filename | [
"def",
"make_safe_filename_from_url",
"(",
"self",
",",
"url",
")",
":",
"r",
"=",
"re",
".",
"compile",
"(",
"\"([^a-zA-Z0-9_.-])\"",
")",
"filename",
"=",
"r",
".",
"sub",
"(",
"lambda",
"m",
":",
"\"%\"",
"+",
"str",
"(",
"hex",
"(",
"ord",
"(",
"... | 51.8 | 0.015209 |
def dump(self, f, indent=''):
"""Dump this section and its children to a file-like object"""
print(("%s&%s %s" % (indent, self.__name, self.section_parameters)).rstrip(), file=f)
self.dump_children(f, indent)
print("%s&END %s" % (indent, self.__name), file=f) | [
"def",
"dump",
"(",
"self",
",",
"f",
",",
"indent",
"=",
"''",
")",
":",
"print",
"(",
"(",
"\"%s&%s %s\"",
"%",
"(",
"indent",
",",
"self",
".",
"__name",
",",
"self",
".",
"section_parameters",
")",
")",
".",
"rstrip",
"(",
")",
",",
"file",
"... | 57.4 | 0.010309 |
def get_name_by_preorder( self, preorder_hash ):
"""
Given a name preorder hash, get the associated name record.
(It may be expired or revoked)
"""
cur = self.db.cursor()
return namedb_get_name_by_preorder_hash( cur, preorder_hash ) | [
"def",
"get_name_by_preorder",
"(",
"self",
",",
"preorder_hash",
")",
":",
"cur",
"=",
"self",
".",
"db",
".",
"cursor",
"(",
")",
"return",
"namedb_get_name_by_preorder_hash",
"(",
"cur",
",",
"preorder_hash",
")"
] | 39.142857 | 0.021429 |
def inverse_transform(self, sequences):
"""Transform a list of sequences from internal indexing into
labels
Parameters
----------
sequences : list
List of sequences, each of which is one-dimensional array of
integers in ``0, ..., n_states_ - 1``.
... | [
"def",
"inverse_transform",
"(",
"self",
",",
"sequences",
")",
":",
"sequences",
"=",
"list_of_1d",
"(",
"sequences",
")",
"inverse_mapping",
"=",
"{",
"v",
":",
"k",
"for",
"k",
",",
"v",
"in",
"self",
".",
"mapping_",
".",
"items",
"(",
")",
"}",
... | 31.678571 | 0.002188 |
def load_from_file(cfg_file):
"""Load the configuration from a file
Parameters
----------
cfg_file: str
Path to configuration file
Returns
-------
cfg : CaseInsensitiveDict
Dictionary with configuration parameters
"""
path = pathlib.Path(cfg_file).resolve()
wi... | [
"def",
"load_from_file",
"(",
"cfg_file",
")",
":",
"path",
"=",
"pathlib",
".",
"Path",
"(",
"cfg_file",
")",
".",
"resolve",
"(",
")",
"with",
"path",
".",
"open",
"(",
"'r'",
")",
"as",
"f",
":",
"code",
"=",
"f",
".",
"readlines",
"(",
")",
"... | 32.6 | 0.000662 |
def list(self, **params):
"""
Retrieve all tasks
Returns all tasks available to the user, according to the parameters provided
If you ask for tasks without any parameter provided Base API will return you both **floating** and **related** tasks
Although you can narrow the search ... | [
"def",
"list",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"_",
",",
"_",
",",
"tasks",
"=",
"self",
".",
"http_client",
".",
"get",
"(",
"\"/tasks\"",
",",
"params",
"=",
"params",
")",
"return",
"tasks"
] | 41.8125 | 0.008772 |
def users(self):
"""
Property for accessing :class:`UserManager` instance, which is used to manage users.
:rtype: yagocd.resources.user.UserManager
"""
if self._user_manager is None:
self._user_manager = UserManager(session=self._session)
return self._user_ma... | [
"def",
"users",
"(",
"self",
")",
":",
"if",
"self",
".",
"_user_manager",
"is",
"None",
":",
"self",
".",
"_user_manager",
"=",
"UserManager",
"(",
"session",
"=",
"self",
".",
"_session",
")",
"return",
"self",
".",
"_user_manager"
] | 35.222222 | 0.009231 |
def raw_sensor_count(self):
"""
Returns the raw integer ADC count from the sensor
Note: Must be divided depending on the max. sensor resolution
to get floating point celsius
:returns: the raw value from the sensor ADC
:rtype: int
:raises... | [
"def",
"raw_sensor_count",
"(",
"self",
")",
":",
"# two complement bytes, MSB comes after LSB!",
"bytes",
"=",
"self",
".",
"raw_sensor_strings",
"[",
"1",
"]",
".",
"split",
"(",
")",
"# Convert from 16 bit hex string into int",
"int16",
"=",
"int",
"(",
"bytes",
... | 32.48 | 0.002392 |
def textvalidation(self, warnonly=None):
"""Run text validation on this element. Checks whether any text redundancy is consistent and whether offsets are valid.
Parameters:
warnonly (bool): Warn only (True) or raise exceptions (False). If set to None then this value will be determined based... | [
"def",
"textvalidation",
"(",
"self",
",",
"warnonly",
"=",
"None",
")",
":",
"if",
"warnonly",
"is",
"None",
"and",
"self",
".",
"doc",
"and",
"self",
".",
"doc",
".",
"version",
":",
"warnonly",
"=",
"(",
"checkversion",
"(",
"self",
".",
"doc",
".... | 69.355556 | 0.012954 |
def make_driveritem_deviceitem_devicename(device_name, condition='is', negate=False, preserve_case=False):
"""
Create a node for DriverItem/DeviceItem/DeviceName
:return: A IndicatorItem represented as an Element node
"""
document = 'DriverItem'
search = 'DriverItem/DeviceItem/DeviceName'
... | [
"def",
"make_driveritem_deviceitem_devicename",
"(",
"device_name",
",",
"condition",
"=",
"'is'",
",",
"negate",
"=",
"False",
",",
"preserve_case",
"=",
"False",
")",
":",
"document",
"=",
"'DriverItem'",
"search",
"=",
"'DriverItem/DeviceItem/DeviceName'",
"content... | 43.615385 | 0.008636 |
def duty_cycle(self):
"""16 bit value that dictates how much of one cycle is high (1) versus low (0). 0xffff will
always be high, 0 will always be low and 0x7fff will be half high and then half low."""
pwm = self._pca.pwm_regs[self._index]
if pwm[0] == 0x1000:
return 0xfff... | [
"def",
"duty_cycle",
"(",
"self",
")",
":",
"pwm",
"=",
"self",
".",
"_pca",
".",
"pwm_regs",
"[",
"self",
".",
"_index",
"]",
"if",
"pwm",
"[",
"0",
"]",
"==",
"0x1000",
":",
"return",
"0xffff",
"return",
"pwm",
"[",
"1",
"]",
"<<",
"4"
] | 48.857143 | 0.011494 |
def histograms(self, analytes=None, bins=25, logy=False,
filt=False, colourful=True):
"""
Plot histograms of analytes.
Parameters
----------
analytes : optional, array_like or str
The analyte(s) to plot. Defaults to all analytes.
bins : int... | [
"def",
"histograms",
"(",
"self",
",",
"analytes",
"=",
"None",
",",
"bins",
"=",
"25",
",",
"logy",
"=",
"False",
",",
"filt",
"=",
"False",
",",
"colourful",
"=",
"True",
")",
":",
"if",
"analytes",
"is",
"None",
":",
"analytes",
"=",
"self",
"."... | 33.394737 | 0.002297 |
def from_fault_data(cls, edges, mesh_spacing):
"""
Create and return a fault surface using fault source data.
:param edges:
A list of at least two horizontal edges of the surface
as instances of :class:`openquake.hazardlib.geo.line.Line`. The
list should be i... | [
"def",
"from_fault_data",
"(",
"cls",
",",
"edges",
",",
"mesh_spacing",
")",
":",
"cls",
".",
"check_fault_data",
"(",
"edges",
",",
"mesh_spacing",
")",
"surface_nodes",
"=",
"[",
"complex_fault_node",
"(",
"edges",
")",
"]",
"mean_length",
"=",
"numpy",
"... | 43.291667 | 0.000941 |
def get_interface_detail_output_interface_ifHCOutUcastPkts(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_interface_detail = ET.Element("get_interface_detail")
config = get_interface_detail
output = ET.SubElement(get_interface_detail, "outpu... | [
"def",
"get_interface_detail_output_interface_ifHCOutUcastPkts",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_interface_detail",
"=",
"ET",
".",
"Element",
"(",
"\"get_interface_detail\"",
")",
"... | 50.470588 | 0.002288 |
def suspended_ticket_delete(self, id, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/suspended_tickets#delete-suspended-ticket"
api_path = "/api/v2/suspended_tickets/{id}.json"
api_path = api_path.format(id=id)
return self.call(api_path, method="DELETE", **kwargs) | [
"def",
"suspended_ticket_delete",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/suspended_tickets/{id}.json\"",
"api_path",
"=",
"api_path",
".",
"format",
"(",
"id",
"=",
"id",
")",
"return",
"self",
".",
"call",
"("... | 61.2 | 0.009677 |
def limit(self, r=5):
"""
Limit selection to a range in the main dataframe
"""
try:
self.df = self.df[:r]
except Exception as e:
self.err(e, "Can not limit data") | [
"def",
"limit",
"(",
"self",
",",
"r",
"=",
"5",
")",
":",
"try",
":",
"self",
".",
"df",
"=",
"self",
".",
"df",
"[",
":",
"r",
"]",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"err",
"(",
"e",
",",
"\"Can not limit data\"",
")"
] | 27.375 | 0.00885 |
def mappability(args):
"""
%prog mappability reference.fasta
Generate 50mer mappability for reference genome. Commands are based on gem
mapper. See instructions:
<https://github.com/xuefzhao/Reference.Mappability>
"""
p = OptionParser(mappability.__doc__)
p.add_option("--mer", default=5... | [
"def",
"mappability",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"mappability",
".",
"__doc__",
")",
"p",
".",
"add_option",
"(",
"\"--mer\"",
",",
"default",
"=",
"50",
",",
"type",
"=",
"\"int\"",
",",
"help",
"=",
"\"User mer size\"",
")",
... | 26.833333 | 0.001498 |
def _restore_slim(self, variables):
""" Restore from tf-slim file (usually a ImageNet pre-trained model). """
variables_to_restore = self.get_variables_in_checkpoint_file(self.flags['RESTORE_SLIM_FILE'])
variables_to_restore = {self.name_in_checkpoint(v): v for v in variables if (self.name_in_ch... | [
"def",
"_restore_slim",
"(",
"self",
",",
"variables",
")",
":",
"variables_to_restore",
"=",
"self",
".",
"get_variables_in_checkpoint_file",
"(",
"self",
".",
"flags",
"[",
"'RESTORE_SLIM_FILE'",
"]",
")",
"variables_to_restore",
"=",
"{",
"self",
".",
"name_in_... | 70.9 | 0.008357 |
def _get_backend_router(self, locations, item):
"""Returns valid router options for ordering a dedicated host."""
mask = '''
id,
hostname
'''
cpu_count = item['capacity']
for capacity in item['bundleItems']:
for category in capacity['categorie... | [
"def",
"_get_backend_router",
"(",
"self",
",",
"locations",
",",
"item",
")",
":",
"mask",
"=",
"'''\n id,\n hostname\n '''",
"cpu_count",
"=",
"item",
"[",
"'capacity'",
"]",
"for",
"capacity",
"in",
"item",
"[",
"'bundleItems'",
"]",
... | 43.644068 | 0.001899 |
def __fetch_issue_data(self, issue_id):
"""Get data associated to an issue"""
raw_issue = self.client.issue(issue_id)
issue = json.loads(raw_issue)
return issue | [
"def",
"__fetch_issue_data",
"(",
"self",
",",
"issue_id",
")",
":",
"raw_issue",
"=",
"self",
".",
"client",
".",
"issue",
"(",
"issue_id",
")",
"issue",
"=",
"json",
".",
"loads",
"(",
"raw_issue",
")",
"return",
"issue"
] | 26.857143 | 0.010309 |
def quantize(arr, min_val, max_val, levels, dtype=np.int64):
"""Quantize an array of (-inf, inf) to [0, levels-1].
Args:
arr (ndarray): Input array.
min_val (scalar): Minimum value to be clipped.
max_val (scalar): Maximum value to be clipped.
levels (int): Quantization levels.
... | [
"def",
"quantize",
"(",
"arr",
",",
"min_val",
",",
"max_val",
",",
"levels",
",",
"dtype",
"=",
"np",
".",
"int64",
")",
":",
"if",
"not",
"(",
"isinstance",
"(",
"levels",
",",
"int",
")",
"and",
"levels",
">",
"1",
")",
":",
"raise",
"ValueError... | 34.884615 | 0.001073 |
def solvate(solute, solvent, n_solvent, box, overlap=0.2,
seed=12345, edge=0.2, fix_orientation=False, temp_file=None):
"""Solvate a compound in a box of solvent using packmol.
Parameters
----------
solute : mb.Compound
Compound to be placed in a box and solvated.
solvent : mb.C... | [
"def",
"solvate",
"(",
"solute",
",",
"solvent",
",",
"n_solvent",
",",
"box",
",",
"overlap",
"=",
"0.2",
",",
"seed",
"=",
"12345",
",",
"edge",
"=",
"0.2",
",",
"fix_orientation",
"=",
"False",
",",
"temp_file",
"=",
"None",
")",
":",
"_check_packmo... | 35.354167 | 0.00086 |
def create_listeners(name, listeners, region=None, key=None, keyid=None,
profile=None):
'''
Create listeners on an ELB.
CLI example:
.. code-block:: bash
salt myminion boto_elb.create_listeners myelb '[["HTTPS", "HTTP", 443, 80, "arn:aws:iam::11 11111:server-certificate/... | [
"def",
"create_listeners",
"(",
"name",
",",
"listeners",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=",
... | 36.148148 | 0.001996 |
def url_fix(s, charset='utf-8'):
r"""Sometimes you get an URL by a user that just isn't a real URL because
it contains unsafe characters like ' ' and so on. This function can fix
some of the problems in a similar way browsers handle data entered by the
user:
>>> url_fix(u'http://de.wikipedia.org/wi... | [
"def",
"url_fix",
"(",
"s",
",",
"charset",
"=",
"'utf-8'",
")",
":",
"scheme",
",",
"netloc",
",",
"path",
",",
"qs",
",",
"anchor",
"=",
"url_parse",
"(",
"to_unicode",
"(",
"s",
",",
"charset",
",",
"'replace'",
")",
")",
"path",
"=",
"url_quote",... | 48.941176 | 0.002358 |
def with_filter(self, filter):
'''
Returns a new service which will process requests with the specified
filter. Filtering operations can include logging, automatic retrying,
etc... The filter is a lambda which receives the HTTPRequest and
another lambda. The filter can perform an... | [
"def",
"with_filter",
"(",
"self",
",",
"filter",
")",
":",
"res",
"=",
"copy",
".",
"deepcopy",
"(",
"self",
")",
"old_filter",
"=",
"self",
".",
"_filter",
"def",
"new_filter",
"(",
"request",
")",
":",
"return",
"filter",
"(",
"request",
",",
"old_f... | 39.095238 | 0.002378 |
def refresh(self):
"""刷新 Question object 的属性.
例如回答数增加了, 先调用 ``refresh()``
再访问 answer_num 属性, 可获得更新后的答案数量.
:return: None
"""
super().refresh()
self._html = None
self._title = None
self._details = None
self._answer_num = None
... | [
"def",
"refresh",
"(",
"self",
")",
":",
"super",
"(",
")",
".",
"refresh",
"(",
")",
"self",
".",
"_html",
"=",
"None",
"self",
".",
"_title",
"=",
"None",
"self",
".",
"_details",
"=",
"None",
"self",
".",
"_answer_num",
"=",
"None",
"self",
".",... | 26.4375 | 0.011416 |
def set_account_username(self, account, old_username, new_username):
""" Account's username was changed. """
luser = self._get_account(old_username)
rename(luser, database=self._database, uid=new_username) | [
"def",
"set_account_username",
"(",
"self",
",",
"account",
",",
"old_username",
",",
"new_username",
")",
":",
"luser",
"=",
"self",
".",
"_get_account",
"(",
"old_username",
")",
"rename",
"(",
"luser",
",",
"database",
"=",
"self",
".",
"_database",
",",
... | 56.5 | 0.008734 |
def string(self, writesize=None):
'''
Looks like a file handle
'''
if not self.finished:
self.finished = True
return self.content
return '' | [
"def",
"string",
"(",
"self",
",",
"writesize",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"finished",
":",
"self",
".",
"finished",
"=",
"True",
"return",
"self",
".",
"content",
"return",
"''"
] | 24.5 | 0.009852 |
def air_range(self) -> Union[int, float]:
""" Does not include upgrades """
if self._weapons:
weapon = next(
(weapon for weapon in self._weapons if weapon.type in {TargetType.Air.value, TargetType.Any.value}),
None,
)
if weapon:
... | [
"def",
"air_range",
"(",
"self",
")",
"->",
"Union",
"[",
"int",
",",
"float",
"]",
":",
"if",
"self",
".",
"_weapons",
":",
"weapon",
"=",
"next",
"(",
"(",
"weapon",
"for",
"weapon",
"in",
"self",
".",
"_weapons",
"if",
"weapon",
".",
"type",
"in... | 35.6 | 0.008219 |
def deregister_all(self, *events):
"""
Deregisters all handler functions, or those registered against the given event(s).
"""
if events:
for event in events:
self._handler_dict[event] = []
else:
self._handler_dict = {} | [
"def",
"deregister_all",
"(",
"self",
",",
"*",
"events",
")",
":",
"if",
"events",
":",
"for",
"event",
"in",
"events",
":",
"self",
".",
"_handler_dict",
"[",
"event",
"]",
"=",
"[",
"]",
"else",
":",
"self",
".",
"_handler_dict",
"=",
"{",
"}"
] | 32.222222 | 0.010067 |
def main(
gpu:Param("GPU to run on", str)=None,
lr: Param("Learning rate", float)=1e-3,
size: Param("Size (px: 128,192,224)", int)=128,
debias_mom: Param("Debias statistics", bool)=False,
debias_sqr: Param("Debias statistics", bool)=False,
opt: Param("Optimizer: 'adam','g... | [
"def",
"main",
"(",
"gpu",
":",
"Param",
"(",
"\"GPU to run on\"",
",",
"str",
")",
"=",
"None",
",",
"lr",
":",
"Param",
"(",
"\"Learning rate\"",
",",
"float",
")",
"=",
"1e-3",
",",
"size",
":",
"Param",
"(",
"\"Size (px: 128,192,224)\"",
",",
"int",
... | 47.146341 | 0.024328 |
async def trigger_event(self, event, *args):
"""Dispatch an event to the proper handler method.
In the most common usage, this method is not overloaded by subclasses,
as it performs the routing of events to methods. However, this
method can be overriden if special dispatching rules are ... | [
"async",
"def",
"trigger_event",
"(",
"self",
",",
"event",
",",
"*",
"args",
")",
":",
"handler_name",
"=",
"'on_'",
"+",
"event",
"if",
"hasattr",
"(",
"self",
",",
"handler_name",
")",
":",
"handler",
"=",
"getattr",
"(",
"self",
",",
"handler_name",
... | 41.285714 | 0.002255 |
def return_hdr(self):
"""Return the header for further use.
Returns
-------
subj_id : str
subject identification code
start_time : datetime
start time of the dataset
s_freq : float
sampling frequency
chan_name : list of str
... | [
"def",
"return_hdr",
"(",
"self",
")",
":",
"# information contained in .erd",
"orig",
"=",
"self",
".",
"_hdr",
"[",
"'erd'",
"]",
"if",
"orig",
"[",
"'patient_id'",
"]",
":",
"subj_id",
"=",
"orig",
"[",
"'patient_id'",
"]",
"else",
":",
"subj_id",
"=",
... | 34.560606 | 0.001279 |
def set_keyspace(self, keyspace):
"""
Change the keyspace which will be used for subsequent requests to this
CassandraClusterPool, and return a Deferred that will fire once it can
be verified that connections can successfully use that keyspace.
If something goes wrong trying to ... | [
"def",
"set_keyspace",
"(",
"self",
",",
"keyspace",
")",
":",
"# push a real set_keyspace on some (any) connection; the idea is that",
"# if it succeeds there, it is likely to succeed everywhere, and vice",
"# versa. don't bother waiting for all connections to change- some of",
"# them may b... | 49.344828 | 0.001371 |
def get_environ(self, sock):
"""Create WSGI environ entries to be merged into each request."""
cipher = sock.cipher()
ssl_environ = {
"wsgi.url_scheme": "https",
"HTTPS": "on",
'SSL_PROTOCOL': cipher[1],
'SSL_CIPHER': cipher[0]
## SSL_VE... | [
"def",
"get_environ",
"(",
"self",
",",
"sock",
")",
":",
"cipher",
"=",
"sock",
".",
"cipher",
"(",
")",
"ssl_environ",
"=",
"{",
"\"wsgi.url_scheme\"",
":",
"\"https\"",
",",
"\"HTTPS\"",
":",
"\"on\"",
",",
"'SSL_PROTOCOL'",
":",
"cipher",
"[",
"1",
"... | 39.416667 | 0.012397 |
def __get_arg(cls, kwds, kwd):
"""Internal helper method to parse keywords that may be property names."""
alt_kwd = '_' + kwd
if alt_kwd in kwds:
return kwds.pop(alt_kwd)
if kwd in kwds:
obj = getattr(cls, kwd, None)
if not isinstance(obj, Property) or isinstance(obj, ModelKey):
... | [
"def",
"__get_arg",
"(",
"cls",
",",
"kwds",
",",
"kwd",
")",
":",
"alt_kwd",
"=",
"'_'",
"+",
"kwd",
"if",
"alt_kwd",
"in",
"kwds",
":",
"return",
"kwds",
".",
"pop",
"(",
"alt_kwd",
")",
"if",
"kwd",
"in",
"kwds",
":",
"obj",
"=",
"getattr",
"(... | 34.9 | 0.011173 |
def transpose(label, n_semitones):
'''Transpose a chord label by some number of semitones
Parameters
----------
label : str
A chord string
n_semitones : float
The number of semitones to move `label`
Returns
-------
label_transpose : str
The transposed chord lab... | [
"def",
"transpose",
"(",
"label",
",",
"n_semitones",
")",
":",
"# Otherwise, split off the note from the modifier",
"match",
"=",
"re",
".",
"match",
"(",
"six",
".",
"text_type",
"(",
"'(?P<note>[A-G][b#]*)(?P<mod>.*)'",
")",
",",
"six",
".",
"text_type",
"(",
"... | 23 | 0.001346 |
def insert(self, data, using_name=True):
"""Insert one or many records.
:param data: dict type data or list of dict
:param using_name: if you are using field name in data,
please set using_name = True (it's the default), otherwise, False
**中文文档**
插入... | [
"def",
"insert",
"(",
"self",
",",
"data",
",",
"using_name",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"data",
",",
"list",
")",
":",
"# if iterable, insert one by one",
"for",
"d",
"in",
"data",
":",
"self",
".",
"insert_one",
"(",
"d",
",",
"u... | 36.25 | 0.010084 |
def clean_outcpd(self):
"""Hack to act like clean_outcpd on zeta1.TopLevelNode.
Take the max element in each to column, set it to 1, and set all the
other elements to 0.
Only called by inferRowMaxProd() and only needed if an updateRow()
has been called since the last clean_outcpd().
"""
m = ... | [
"def",
"clean_outcpd",
"(",
"self",
")",
":",
"m",
"=",
"self",
".",
"hist_",
".",
"toDense",
"(",
")",
"for",
"j",
"in",
"xrange",
"(",
"m",
".",
"shape",
"[",
"1",
"]",
")",
":",
"# For each column.",
"cmax",
"=",
"m",
"[",
":",
",",
"j",
"]"... | 39.666667 | 0.014778 |
def Prep(self, size, additionalBytes):
"""
Prep prepares to write an element of `size` after `additional_bytes`
have been written, e.g. if you write a string, you need to align
such the int length field is aligned to SizeInt32, and the string
data follows it directly.
If ... | [
"def",
"Prep",
"(",
"self",
",",
"size",
",",
"additionalBytes",
")",
":",
"# Track the biggest thing we've ever aligned to.",
"if",
"size",
">",
"self",
".",
"minalign",
":",
"self",
".",
"minalign",
"=",
"size",
"# Find the amount of alignment needed such that `size` ... | 42.08 | 0.001859 |
def TargetDirectory(ID, season, relative=False, **kwargs):
'''
Returns the location of the :py:mod:`everest` data on disk
for a given target.
:param ID: The target ID
:param int season: The target season number
:param bool relative: Relative path? Default :py:obj:`False`
'''
if season... | [
"def",
"TargetDirectory",
"(",
"ID",
",",
"season",
",",
"relative",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"season",
"is",
"None",
":",
"return",
"None",
"if",
"relative",
":",
"path",
"=",
"''",
"else",
":",
"path",
"=",
"EVEREST_DA... | 27.6 | 0.001751 |
def crypto_scalarmult_base(n):
"""
Computes and returns the scalar product of a standard group element and an
integer ``n``.
:param n: bytes
:rtype: bytes
"""
q = ffi.new("unsigned char[]", crypto_scalarmult_BYTES)
rc = lib.crypto_scalarmult_base(q, n)
ensure(rc == 0,
'U... | [
"def",
"crypto_scalarmult_base",
"(",
"n",
")",
":",
"q",
"=",
"ffi",
".",
"new",
"(",
"\"unsigned char[]\"",
",",
"crypto_scalarmult_BYTES",
")",
"rc",
"=",
"lib",
".",
"crypto_scalarmult_base",
"(",
"q",
",",
"n",
")",
"ensure",
"(",
"rc",
"==",
"0",
"... | 26.6875 | 0.002262 |
def are_metadata_file_based(layer):
"""Check if metadata should be read/written to file or our metadata db.
Determine which metadata lookup system to use (file base or cache db)
based on the layer's provider type. True indicates we should use the
datasource as a file and look for a meta... | [
"def",
"are_metadata_file_based",
"(",
"layer",
")",
":",
"try",
":",
"provider_type",
"=",
"str",
"(",
"layer",
".",
"providerType",
"(",
")",
")",
"except",
"AttributeError",
":",
"raise",
"UnsupportedProviderError",
"(",
"'Could not determine type for provider: %s'... | 35.864865 | 0.001467 |
def dedent(source, use_tabs=False):
"""
Minimizes indentation to save precious bytes. Optionally, *use_tabs*
may be specified if you want to use tabulators (\t) instead of spaces.
Example::
def foo(bar):
test = "This is a test"
Will become::
def foo(bar):
te... | [
"def",
"dedent",
"(",
"source",
",",
"use_tabs",
"=",
"False",
")",
":",
"if",
"use_tabs",
":",
"indent_char",
"=",
"'\\t'",
"else",
":",
"indent_char",
"=",
"' '",
"io_obj",
"=",
"io",
".",
"StringIO",
"(",
"source",
")",
"out",
"=",
"\"\"",
"last_lin... | 28.075472 | 0.000649 |
def as_iso8601(self):
"""
example: 00:38:05.210Z
"""
if self.__time is None:
return None
return "%s:%s:%s0Z" % (self.__time[:2], self.__time[2:4], self.__time[4:]) | [
"def",
"as_iso8601",
"(",
"self",
")",
":",
"if",
"self",
".",
"__time",
"is",
"None",
":",
"return",
"None",
"return",
"\"%s:%s:%s0Z\"",
"%",
"(",
"self",
".",
"__time",
"[",
":",
"2",
"]",
",",
"self",
".",
"__time",
"[",
"2",
":",
"4",
"]",
",... | 26.125 | 0.013889 |
def find_netmiko_dir():
"""Check environment first, then default dir"""
try:
netmiko_base_dir = os.environ["NETMIKO_DIR"]
except KeyError:
netmiko_base_dir = NETMIKO_BASE_DIR
netmiko_base_dir = os.path.expanduser(netmiko_base_dir)
if netmiko_base_dir == "/":
raise ValueError(... | [
"def",
"find_netmiko_dir",
"(",
")",
":",
"try",
":",
"netmiko_base_dir",
"=",
"os",
".",
"environ",
"[",
"\"NETMIKO_DIR\"",
"]",
"except",
"KeyError",
":",
"netmiko_base_dir",
"=",
"NETMIKO_BASE_DIR",
"netmiko_base_dir",
"=",
"os",
".",
"path",
".",
"expanduser... | 40.545455 | 0.002193 |
def Burr(c, k, tag=None):
"""
A Burr random variate
Parameters
----------
c : scalar
The first shape parameter
k : scalar
The second shape parameter
"""
assert c > 0 and k > 0, 'Burr "c" and "k" parameters must be greater than zero'
return uv(ss.burr(c, k), ... | [
"def",
"Burr",
"(",
"c",
",",
"k",
",",
"tag",
"=",
"None",
")",
":",
"assert",
"c",
">",
"0",
"and",
"k",
">",
"0",
",",
"'Burr \"c\" and \"k\" parameters must be greater than zero'",
"return",
"uv",
"(",
"ss",
".",
"burr",
"(",
"c",
",",
"k",
")",
... | 22.5 | 0.012195 |
def abs_urls(data, target_url, image_url):
"""
Filter for a list of reStructuredText lines that replaces relative
link targets and image sources by absolute URLs given the base
URLs that should be used (``target_url`` for link targets,
``image_url``for image sources). Returns a list of strings.
... | [
"def",
"abs_urls",
"(",
"data",
",",
"target_url",
",",
"image_url",
")",
":",
"def",
"replacer",
"(",
"regex",
",",
"url",
")",
":",
"replacement",
"=",
"r\"\\1 {0}/\\2\"",
".",
"format",
"(",
"url",
".",
"rstrip",
"(",
"\"/\"",
")",
")",
"return",
"l... | 49.285714 | 0.001422 |
def lreshape(data, groups, dropna=True, label=None):
"""
Reshape long-format data to wide. Generalized inverse of DataFrame.pivot
Parameters
----------
data : DataFrame
groups : dict
{new_name : list_of_columns}
dropna : boolean, default True
Examples
--------
>>> data ... | [
"def",
"lreshape",
"(",
"data",
",",
"groups",
",",
"dropna",
"=",
"True",
",",
"label",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"groups",
",",
"dict",
")",
":",
"keys",
"=",
"list",
"(",
"groups",
".",
"keys",
"(",
")",
")",
"values",
"=... | 27.970588 | 0.000508 |
def check_lazy_load_adrespositie(f):
'''
Decorator function to lazy load a :class:`Adrespositie`.
'''
def wrapper(*args):
adrespositie = args[0]
if (
adrespositie._geometrie is None or
adrespositie._aard is None or
adrespositie._metadata is None
... | [
"def",
"check_lazy_load_adrespositie",
"(",
"f",
")",
":",
"def",
"wrapper",
"(",
"*",
"args",
")",
":",
"adrespositie",
"=",
"args",
"[",
"0",
"]",
"if",
"(",
"adrespositie",
".",
"_geometrie",
"is",
"None",
"or",
"adrespositie",
".",
"_aard",
"is",
"No... | 35.947368 | 0.001427 |
def wrap_insecure_channel(insecure_channel_func, tracer=None):
"""Wrap the grpc.insecure_channel."""
def call(*args, **kwargs):
channel = insecure_channel_func(*args, **kwargs)
try:
target = kwargs.get('target')
tracer_interceptor = OpenCensusClientInterceptor(tracer, ta... | [
"def",
"wrap_insecure_channel",
"(",
"insecure_channel_func",
",",
"tracer",
"=",
"None",
")",
":",
"def",
"call",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"channel",
"=",
"insecure_channel_func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")... | 39.411765 | 0.001458 |
def y_fit(self):
"""
Using the result of the linear least squares, the result of :math:`X_{ij}\\beta_i`
"""
if self._y_fit is None:
self._y_fit = _np.dot(self.X_unweighted, self.beta)
return self._y_fit | [
"def",
"y_fit",
"(",
"self",
")",
":",
"if",
"self",
".",
"_y_fit",
"is",
"None",
":",
"self",
".",
"_y_fit",
"=",
"_np",
".",
"dot",
"(",
"self",
".",
"X_unweighted",
",",
"self",
".",
"beta",
")",
"return",
"self",
".",
"_y_fit"
] | 35.428571 | 0.011811 |
def main(argv=None):
'''
Handles command line arguments and gets things started.
:param argv: List of arguments, as if specified on the command-line.
If None, ``sys.argv[1:]`` is used instead.
:type argv: list of str
'''
# Get command line arguments
parser = argparse.Argume... | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"# Get command line arguments",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"\"Takes one or more file paths and reports their detected \\\n encodings\"",
",",
"formatter_class"... | 43.310345 | 0.000779 |
def pkcs_emsa_pkcs1_v1_5_encode(M, emLen, h): # section 9.2 of RFC 3447
"""
Implements EMSA-PKCS1-V1_5-ENCODE() function described in Sect.
9.2 of RFC 3447.
Input:
M : message to be encode, an octet string
emLen: intended length in octets of the encoded message, at least
... | [
"def",
"pkcs_emsa_pkcs1_v1_5_encode",
"(",
"M",
",",
"emLen",
",",
"h",
")",
":",
"# section 9.2 of RFC 3447",
"hLen",
"=",
"_hashFuncParams",
"[",
"h",
"]",
"[",
"0",
"]",
"# 1)",
"hFunc",
"=",
"_hashFuncParams",
"[",
"h",
"]",
"[",
"1",
"]",
"H",
"=",
... | 41.129032 | 0.002299 |
def add_child(self, child):
"""
Adds a branch to the current tree.
"""
self.children.append(child)
child.parent = self
self.udepth = max([child.udepth for child in self.children]) + 1 | [
"def",
"add_child",
"(",
"self",
",",
"child",
")",
":",
"self",
".",
"children",
".",
"append",
"(",
"child",
")",
"child",
".",
"parent",
"=",
"self",
"self",
".",
"udepth",
"=",
"max",
"(",
"[",
"child",
".",
"udepth",
"for",
"child",
"in",
"sel... | 32.142857 | 0.008658 |
def load_template_help(builtin):
"""Loads the help for a given template"""
help_file = "templates/%s-help.yml" % builtin
help_file = resource_filename(__name__, help_file)
help_obj = {}
if os.path.exists(help_file):
help_data = yaml.safe_load(open(help_file))
if 'name' in help_data:... | [
"def",
"load_template_help",
"(",
"builtin",
")",
":",
"help_file",
"=",
"\"templates/%s-help.yml\"",
"%",
"builtin",
"help_file",
"=",
"resource_filename",
"(",
"__name__",
",",
"help_file",
")",
"help_obj",
"=",
"{",
"}",
"if",
"os",
".",
"path",
".",
"exist... | 29.833333 | 0.001805 |
def network_size(value, options=None, version=None):
'''
Get the size of a network.
'''
ipaddr_filter_out = _filter_ipaddr(value, options=options, version=version)
if not ipaddr_filter_out:
return
if not isinstance(value, (list, tuple, types.GeneratorType)):
return _network_size(... | [
"def",
"network_size",
"(",
"value",
",",
"options",
"=",
"None",
",",
"version",
"=",
"None",
")",
":",
"ipaddr_filter_out",
"=",
"_filter_ipaddr",
"(",
"value",
",",
"options",
"=",
"options",
",",
"version",
"=",
"version",
")",
"if",
"not",
"ipaddr_fil... | 31.846154 | 0.002347 |
def keelhaul(rest):
"Inflict great pain and embarassment on some(one|thing)"
keelee = rest
karma.Karma.store.change(keelee, -1)
return (
"/me straps %s to a dirty rope, tosses 'em overboard and pulls "
"with great speed. Yarrr!" % keelee) | [
"def",
"keelhaul",
"(",
"rest",
")",
":",
"keelee",
"=",
"rest",
"karma",
".",
"Karma",
".",
"store",
".",
"change",
"(",
"keelee",
",",
"-",
"1",
")",
"return",
"(",
"\"/me straps %s to a dirty rope, tosses 'em overboard and pulls \"",
"\"with great speed. Yarrr!\"... | 34.285714 | 0.028455 |
def make_valid_polygon(shape):
"""
Make a polygon valid. Polygons can be invalid in many ways, such as
self-intersection, self-touching and degeneracy. This process attempts to
make a polygon valid while retaining as much of its extent or area as
possible.
First, we call pyclipper to robustly u... | [
"def",
"make_valid_polygon",
"(",
"shape",
")",
":",
"assert",
"shape",
".",
"geom_type",
"==",
"'Polygon'",
"shape",
"=",
"make_valid_pyclipper",
"(",
"shape",
")",
"assert",
"shape",
".",
"is_valid",
"return",
"shape"
] | 38.095238 | 0.00122 |
def find(self, requirement, meta_extras=None, prereleases=False):
"""
Find a distribution and all distributions it depends on.
:param requirement: The requirement specifying the distribution to
find, or a Distribution instance.
:param meta_extras: A list of m... | [
"def",
"find",
"(",
"self",
",",
"requirement",
",",
"meta_extras",
"=",
"None",
",",
"prereleases",
"=",
"False",
")",
":",
"self",
".",
"provided",
"=",
"{",
"}",
"self",
".",
"dists",
"=",
"{",
"}",
"self",
".",
"dists_by_name",
"=",
"{",
"}",
"... | 44.733945 | 0.000602 |
def get_adjusted_fermi_level(efermi, cbm, band_structure):
"""
When running a band structure computations the fermi level needs to be
take from the static run that gave the charge density used for the non-self
consistent band structure run. Sometimes this fermi level is however a
little too low beca... | [
"def",
"get_adjusted_fermi_level",
"(",
"efermi",
",",
"cbm",
",",
"band_structure",
")",
":",
"# make a working copy of band_structure",
"bs_working",
"=",
"BandStructureSymmLine",
".",
"from_dict",
"(",
"band_structure",
".",
"as_dict",
"(",
")",
")",
"if",
"bs_work... | 44.290323 | 0.000713 |
def string_to_float_list(string_var):
"""Pull comma separated string values out of a text file and converts them to float list"""
try:
return [float(s) for s in string_var.strip('[').strip(']').split(', ')]
except:
return [float(s) for s in string_var.strip('[').strip(']'... | [
"def",
"string_to_float_list",
"(",
"string_var",
")",
":",
"try",
":",
"return",
"[",
"float",
"(",
"s",
")",
"for",
"s",
"in",
"string_var",
".",
"strip",
"(",
"'['",
")",
".",
"strip",
"(",
"']'",
")",
".",
"split",
"(",
"', '",
")",
"]",
"excep... | 54.666667 | 0.018018 |
def create_rule(self, title, symbolizer=None, MinScaleDenominator=None, MaxScaleDenominator=None):
"""
Create a L{Rule} object on this style. A rule requires a title and
symbolizer. If no symbolizer is specified, a PointSymbolizer will be
assigned to the rule.
@type title:... | [
"def",
"create_rule",
"(",
"self",
",",
"title",
",",
"symbolizer",
"=",
"None",
",",
"MinScaleDenominator",
"=",
"None",
",",
"MaxScaleDenominator",
"=",
"None",
")",
":",
"elem",
"=",
"self",
".",
"_node",
".",
"makeelement",
"(",
"'{%s}Rule'",
"%",
"SLD... | 38.020833 | 0.002137 |
def dock(window):
""" Expecting a window to parent into a Nuke panel, that is dockable. """
# Deleting existing dock
# There is a bug where existing docks are kept in-memory when closed via UI
if self._dock:
print("Deleting existing dock...")
parent = self._dock
dialog = None
... | [
"def",
"dock",
"(",
"window",
")",
":",
"# Deleting existing dock",
"# There is a bug where existing docks are kept in-memory when closed via UI",
"if",
"self",
".",
"_dock",
":",
"print",
"(",
"\"Deleting existing dock...\"",
")",
"parent",
"=",
"self",
".",
"_dock",
"di... | 36.066667 | 0.0006 |
def dict_pick(dictionary, allowed_keys):
"""
Return a dictionary only with keys found in `allowed_keys`
"""
return {key: value for key, value in viewitems(dictionary) if key in allowed_keys} | [
"def",
"dict_pick",
"(",
"dictionary",
",",
"allowed_keys",
")",
":",
"return",
"{",
"key",
":",
"value",
"for",
"key",
",",
"value",
"in",
"viewitems",
"(",
"dictionary",
")",
"if",
"key",
"in",
"allowed_keys",
"}"
] | 40.4 | 0.009709 |
def get_airmass(self, times=None, solar_position=None,
model='kastenyoung1989'):
"""
Calculate the relative and absolute airmass.
Automatically chooses zenith or apparant zenith
depending on the selected model.
Parameters
----------
times : N... | [
"def",
"get_airmass",
"(",
"self",
",",
"times",
"=",
"None",
",",
"solar_position",
"=",
"None",
",",
"model",
"=",
"'kastenyoung1989'",
")",
":",
"if",
"solar_position",
"is",
"None",
":",
"solar_position",
"=",
"self",
".",
"get_solarposition",
"(",
"time... | 35.886364 | 0.00185 |
def record_replace_field(rec, tag, new_field, field_position_global=None,
field_position_local=None):
"""Replace a field with a new field."""
if field_position_global is None and field_position_local is None:
raise InvenioBibRecordFieldError(
"A field position is req... | [
"def",
"record_replace_field",
"(",
"rec",
",",
"tag",
",",
"new_field",
",",
"field_position_global",
"=",
"None",
",",
"field_position_local",
"=",
"None",
")",
":",
"if",
"field_position_global",
"is",
"None",
"and",
"field_position_local",
"is",
"None",
":",
... | 41.944444 | 0.000647 |
def fit(self, X, lengths=None):
"""Estimate model parameters.
An initialization step is performed before entering the
EM algorithm. If you want to avoid this step for a subset of
the parameters, pass proper ``init_params`` keyword argument
to estimator's constructor.
Pa... | [
"def",
"fit",
"(",
"self",
",",
"X",
",",
"lengths",
"=",
"None",
")",
":",
"X",
"=",
"check_array",
"(",
"X",
")",
"self",
".",
"_init",
"(",
"X",
",",
"lengths",
"=",
"lengths",
")",
"self",
".",
"_check",
"(",
")",
"self",
".",
"monitor_",
"... | 36.22449 | 0.001097 |
def ensure_each_wide_obs_chose_an_available_alternative(obs_id_col,
choice_col,
availability_vars,
wide_data):
"""
Checks whether or not each ob... | [
"def",
"ensure_each_wide_obs_chose_an_available_alternative",
"(",
"obs_id_col",
",",
"choice_col",
",",
"availability_vars",
",",
"wide_data",
")",
":",
"# Determine the various availability values for each observation",
"wide_availability_values",
"=",
"wide_data",
"[",
"list",
... | 45.90566 | 0.000402 |
def _exec(self, cmd, url, json_data=None):
"""
execute a command at the device using the RESTful API
:param str cmd: one of the REST commands, e.g. GET or POST
:param str url: URL of the REST API the command should be applied to
:param dict json_data: json data that should be at... | [
"def",
"_exec",
"(",
"self",
",",
"cmd",
",",
"url",
",",
"json_data",
"=",
"None",
")",
":",
"assert",
"(",
"cmd",
"in",
"(",
"\"GET\"",
",",
"\"POST\"",
",",
"\"PUT\"",
",",
"\"DELETE\"",
")",
")",
"assert",
"(",
"self",
".",
"dev",
"is",
"not",
... | 30.148936 | 0.001367 |
def get_node(self, ID):
""" Returns the node with the given ID or None.
"""
for node in self.nodes:
if node.ID == str(ID):
return node
return None | [
"def",
"get_node",
"(",
"self",
",",
"ID",
")",
":",
"for",
"node",
"in",
"self",
".",
"nodes",
":",
"if",
"node",
".",
"ID",
"==",
"str",
"(",
"ID",
")",
":",
"return",
"node",
"return",
"None"
] | 28.571429 | 0.009709 |
def nunique(self, dropna=True):
"""
Return number of unique elements in the group.
"""
ids, _, _ = self.grouper.group_info
val = self.obj.get_values()
try:
sorter = np.lexsort((val, ids))
except TypeError: # catches object dtypes
msg = '... | [
"def",
"nunique",
"(",
"self",
",",
"dropna",
"=",
"True",
")",
":",
"ids",
",",
"_",
",",
"_",
"=",
"self",
".",
"grouper",
".",
"group_info",
"val",
"=",
"self",
".",
"obj",
".",
"get_values",
"(",
")",
"try",
":",
"sorter",
"=",
"np",
".",
"... | 32.017857 | 0.001623 |
def data(self, profile_data):
"""Set data for the widget.
:param profile_data: profile data.
:type profile_data: dict
It will replace the previous data.
"""
default_profile = generate_default_profile()
self.clear()
for hazard in sorted(default_profile.ke... | [
"def",
"data",
"(",
"self",
",",
"profile_data",
")",
":",
"default_profile",
"=",
"generate_default_profile",
"(",
")",
"self",
".",
"clear",
"(",
")",
"for",
"hazard",
"in",
"sorted",
"(",
"default_profile",
".",
"keys",
"(",
")",
")",
":",
"classificati... | 51.439394 | 0.000578 |
def get_final_freq(approx, m1, m2, s1z, s2z):
"""
Returns the LALSimulation function which evaluates the final
(highest) frequency for a given approximant using given template
parameters.
NOTE: TaylorTx and TaylorFx are currently all given an ISCO cutoff !!
Parameters
----------
approx ... | [
"def",
"get_final_freq",
"(",
"approx",
",",
"m1",
",",
"m2",
",",
"s1z",
",",
"s2z",
")",
":",
"lalsim_approx",
"=",
"lalsimulation",
".",
"GetApproximantFromString",
"(",
"approx",
")",
"return",
"_vec_get_final_freq",
"(",
"lalsim_approx",
",",
"m1",
",",
... | 34.074074 | 0.001057 |
def create(self, fail_on_found=False, force_on_exists=False, **kwargs):
"""Create a notification template.
All required configuration-related fields (required according to
notification_type) must be provided.
There are two types of notification template creation: isolatedly
cre... | [
"def",
"create",
"(",
"self",
",",
"fail_on_found",
"=",
"False",
",",
"force_on_exists",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"config_item",
"=",
"self",
".",
"_separate",
"(",
"kwargs",
")",
"jt_id",
"=",
"kwargs",
".",
"pop",
"(",
"'job_... | 49.615385 | 0.002432 |
def set_model_version(model, version):
"""
Sets the version of the ONNX model.
:param model: instance of an ONNX model
:param version: integer containing the version of the model
Example:
::
from onnxmltools.utils import set_model_version
onnx_model = load_model("SqueezeNet.on... | [
"def",
"set_model_version",
"(",
"model",
",",
"version",
")",
":",
"if",
"model",
"is",
"None",
"or",
"not",
"isinstance",
"(",
"model",
",",
"onnx_proto",
".",
"ModelProto",
")",
":",
"raise",
"ValueError",
"(",
"\"Model is not a valid ONNX model.\"",
")",
"... | 33.210526 | 0.001541 |
def tag_dssp_data(assembly, loop_assignments=(' ', 'B', 'S', 'T')):
"""Adds output data from DSSP to an Assembly.
A dictionary will be added to the `tags` dictionary of each
residue called `dssp_data`, which contains the secondary
structure definition, solvent accessibility phi and psi values
from ... | [
"def",
"tag_dssp_data",
"(",
"assembly",
",",
"loop_assignments",
"=",
"(",
"' '",
",",
"'B'",
",",
"'S'",
",",
"'T'",
")",
")",
":",
"dssp_out",
"=",
"run_dssp",
"(",
"assembly",
".",
"pdb",
",",
"path",
"=",
"False",
")",
"dssp_data",
"=",
"extract_a... | 39.390244 | 0.001208 |
def present(name,
skip_translate=None,
ignore_collisions=False,
validate_ip_addrs=True,
containers=None,
reconnect=True,
**kwargs):
'''
.. versionchanged:: 2018.3.0
Support added for network configuration options other than ``driver... | [
"def",
"present",
"(",
"name",
",",
"skip_translate",
"=",
"None",
",",
"ignore_collisions",
"=",
"False",
",",
"validate_ip_addrs",
"=",
"True",
",",
"containers",
"=",
"None",
",",
"reconnect",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"ret",
"="... | 39.893216 | 0.000645 |
def with_rule(self, rule):
"""
Adds validation rule to this schema.
This method returns reference to this exception to implement Builder pattern
to chain additional calls.
:param rule: a validation rule to be added.
:return: this validation schema.
"""
... | [
"def",
"with_rule",
"(",
"self",
",",
"rule",
")",
":",
"self",
".",
"rules",
"=",
"self",
".",
"rules",
"if",
"self",
".",
"rules",
"!=",
"None",
"else",
"[",
"]",
"self",
".",
"rules",
".",
"append",
"(",
"rule",
")",
"return",
"self"
] | 29.428571 | 0.009412 |
def autohelp_directive(dirname, arguments, options, content, lineno,
content_offset, block_text, state, state_machine):
"""produces rst from nose help"""
config = Config(parserClass=OptBucket,
plugins=BuiltinPluginManager())
parser = config.getParser(TestProgram.us... | [
"def",
"autohelp_directive",
"(",
"dirname",
",",
"arguments",
",",
"options",
",",
"content",
",",
"lineno",
",",
"content_offset",
",",
"block_text",
",",
"state",
",",
"state_machine",
")",
":",
"config",
"=",
"Config",
"(",
"parserClass",
"=",
"OptBucket",... | 39.965517 | 0.001685 |
def topsort(graph):
"""
For the given graph, returns a list of nodes in topological order
In py3 the behaviour of this function differs from py2,
the resulting order will change with every execution in py3
while in py2 the order stays the same
:param graph:
:return:
"""
count = defa... | [
"def",
"topsort",
"(",
"graph",
")",
":",
"count",
"=",
"defaultdict",
"(",
"int",
")",
"for",
"feature",
",",
"node",
"in",
"graph",
".",
"items",
"(",
")",
":",
"for",
"target",
"in",
"node",
":",
"count",
"[",
"target",
"]",
"+=",
"1",
"# conver... | 32.961538 | 0.001134 |
def update_parser(parser):
"""Update the parser object for the shell.
Arguments:
parser: An instance of argparse.ArgumentParser.
"""
def __stdin(s):
if s is None:
return None
if s == '-':
return sys.stdin
return open(s, 'r', encoding = 'utf8')
... | [
"def",
"update_parser",
"(",
"parser",
")",
":",
"def",
"__stdin",
"(",
"s",
")",
":",
"if",
"s",
"is",
"None",
":",
"return",
"None",
"if",
"s",
"==",
"'-'",
":",
"return",
"sys",
".",
"stdin",
"return",
"open",
"(",
"s",
",",
"'r'",
",",
"encod... | 32.607143 | 0.041489 |
def delete_alert(self, email, alert_id):
"""
delete user alert
"""
data = {'email': email,
'alert_id': alert_id}
return self.api_delete('alert', data) | [
"def",
"delete_alert",
"(",
"self",
",",
"email",
",",
"alert_id",
")",
":",
"data",
"=",
"{",
"'email'",
":",
"email",
",",
"'alert_id'",
":",
"alert_id",
"}",
"return",
"self",
".",
"api_delete",
"(",
"'alert'",
",",
"data",
")"
] | 28.571429 | 0.009709 |
def network_interface_get(name, resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
Get details about a specific network interface.
:param name: The name of the network interface to query.
:param resource_group: The resource group name assigned to the
network interface.
CLI Exa... | [
"def",
"network_interface_get",
"(",
"name",
",",
"resource_group",
",",
"*",
"*",
"kwargs",
")",
":",
"netconn",
"=",
"__utils__",
"[",
"'azurearm.get_client'",
"]",
"(",
"'network'",
",",
"*",
"*",
"kwargs",
")",
"try",
":",
"nic",
"=",
"netconn",
".",
... | 27.533333 | 0.00117 |
def cmd(command, *args, **kwargs):
'''
run commands from __proxy__
:mod:`salt.proxy.onyx<salt.proxy.onyx>`
command
function from `salt.proxy.onyx` to run
args
positional args to pass to `command` function
kwargs
key word arguments to pass to `command` function
.. ... | [
"def",
"cmd",
"(",
"command",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"proxy_prefix",
"=",
"__opts__",
"[",
"'proxy'",
"]",
"[",
"'proxytype'",
"]",
"proxy_cmd",
"=",
"'.'",
".",
"join",
"(",
"[",
"proxy_prefix",
",",
"command",
"]",
")"... | 27.827586 | 0.001198 |
def resize_image(image, height, width,
channels=None,
resize_mode=None
):
"""
Resizes an image and returns it as a np.array
Arguments:
image -- a PIL.Image or numpy.ndarray
height -- height of new image
width -- width of new image
Keyword Ar... | [
"def",
"resize_image",
"(",
"image",
",",
"height",
",",
"width",
",",
"channels",
"=",
"None",
",",
"resize_mode",
"=",
"None",
")",
":",
"if",
"resize_mode",
"is",
"None",
":",
"resize_mode",
"=",
"'squash'",
"if",
"resize_mode",
"not",
"in",
"[",
"'cr... | 41.878378 | 0.001576 |
def romanize(text: str, engine: str = "royin") -> str:
"""
Rendering Thai words in the Latin alphabet or "romanization",
using the Royal Thai General System of Transcription (RTGS),
which is the official system published by the Royal Institute of Thailand.
ถอดเสียงภาษาไทยเป็นอักษรละติน
:param st... | [
"def",
"romanize",
"(",
"text",
":",
"str",
",",
"engine",
":",
"str",
"=",
"\"royin\"",
")",
"->",
"str",
":",
"if",
"not",
"text",
"or",
"not",
"isinstance",
"(",
"text",
",",
"str",
")",
":",
"return",
"\"\"",
"if",
"engine",
"==",
"\"thai2rom\"",... | 43.25 | 0.002262 |
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 fill(self,*args):
'''Sets a fill color, applying it to new paths.'''
self._fillcolor = self.color(*args)
return self._fillcolor | [
"def",
"fill",
"(",
"self",
",",
"*",
"args",
")",
":",
"self",
".",
"_fillcolor",
"=",
"self",
".",
"color",
"(",
"*",
"args",
")",
"return",
"self",
".",
"_fillcolor"
] | 38 | 0.019355 |
def check_intraday(estimate, returns, positions, transactions):
"""
Logic for checking if a strategy is intraday and processing it.
Parameters
----------
estimate: boolean or str, optional
Approximate returns for intraday strategies.
See description in tears.create_full_tear_sheet.
... | [
"def",
"check_intraday",
"(",
"estimate",
",",
"returns",
",",
"positions",
",",
"transactions",
")",
":",
"if",
"estimate",
"==",
"'infer'",
":",
"if",
"positions",
"is",
"not",
"None",
"and",
"transactions",
"is",
"not",
"None",
":",
"if",
"detect_intraday... | 36.818182 | 0.000601 |
def file_delete(context, id, file_id):
"""file_delete(context, id, path)
Delete a job file
>>> dcictl job-delete-file [OPTIONS]
:param string id: ID of the job to delete file [required]
:param string file_id: ID for the file to delete [required]
"""
dci_file.delete(context, id=file_id)
... | [
"def",
"file_delete",
"(",
"context",
",",
"id",
",",
"file_id",
")",
":",
"dci_file",
".",
"delete",
"(",
"context",
",",
"id",
"=",
"file_id",
")",
"result",
"=",
"dci_file",
".",
"delete",
"(",
"context",
",",
"id",
"=",
"file_id",
")",
"utils",
"... | 31 | 0.00241 |
def get_record_status(recid):
"""
Returns the current status of the record, i.e. current restriction to apply for newly submitted
comments, and current commenting round.
The restriction to apply can be found in the record metadata, in
field(s) defined by config CFG_WEBCOMMENT_RESTRICTION_DATAFIELD.... | [
"def",
"get_record_status",
"(",
"recid",
")",
":",
"collections_with_rounds",
"=",
"CFG_WEBCOMMENT_ROUND_DATAFIELD",
".",
"keys",
"(",
")",
"commenting_round",
"=",
"\"\"",
"for",
"collection",
"in",
"collections_with_rounds",
":",
"# Find the first collection defines roun... | 39.282609 | 0.00216 |
def get_global_config(*args):
'''Get (a subset of) the global configuration.
If no arguments are provided, returns the entire configuration.
Otherwise, start with the entire configuration, and get the item
named by the first parameter; then search that for the second
parameter; and so on.
:par... | [
"def",
"get_global_config",
"(",
"*",
"args",
")",
":",
"global",
"_config_cache",
"c",
"=",
"_config_cache",
"if",
"c",
"is",
"None",
":",
"if",
"len",
"(",
"args",
")",
"==",
"0",
":",
"args",
"=",
"(",
"None",
",",
")",
"raise",
"KeyError",
"(",
... | 29.045455 | 0.001515 |
def request_announcement_view(request):
"""The request announcement page."""
if request.method == "POST":
form = AnnouncementRequestForm(request.POST)
logger.debug(form)
logger.debug(form.data)
if form.is_valid():
teacher_objs = form.cleaned_data["teachers_requested"... | [
"def",
"request_announcement_view",
"(",
"request",
")",
":",
"if",
"request",
".",
"method",
"==",
"\"POST\"",
":",
"form",
"=",
"AnnouncementRequestForm",
"(",
"request",
".",
"POST",
")",
"logger",
".",
"debug",
"(",
"form",
")",
"logger",
".",
"debug",
... | 39.46 | 0.001484 |
def set_computer_desc(desc):
'''
Set PRETTY_HOSTNAME value stored in /etc/machine-info
This will create the file if it does not exist. If
it is unable to create or modify this file returns False.
:param str desc: The computer description
:return: False on failure. True if successful.
CLI E... | [
"def",
"set_computer_desc",
"(",
"desc",
")",
":",
"desc",
"=",
"salt",
".",
"utils",
".",
"stringutils",
".",
"to_unicode",
"(",
"desc",
")",
".",
"replace",
"(",
"'\"'",
",",
"r'\\\"'",
")",
".",
"replace",
"(",
"'\\n'",
",",
"r'\\n'",
")",
".",
"r... | 34.693878 | 0.001144 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.