text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def prepare_to_run(self, clock, period_count):
"""
Prepare the entity for execution.
:param clock: The clock containing the execution start time and
execution period information.
:param period_count: The total amount of periods this activity will be
requested to be r... | [
"def",
"prepare_to_run",
"(",
"self",
",",
"clock",
",",
"period_count",
")",
":",
"self",
".",
"period_count",
"=",
"period_count",
"self",
".",
"_exec_year_end_datetime",
"=",
"clock",
".",
"get_datetime_at_period_ix",
"(",
"period_count",
")",
"self",
".",
"_... | 32.72 | 18.8 |
def concat_multiple_inputs(data, sample):
"""
If multiple fastq files were appended into the list of fastqs for samples
then we merge them here before proceeding.
"""
## if more than one tuple in fastq list
if len(sample.files.fastqs) > 1:
## create a cat command to append them all (d... | [
"def",
"concat_multiple_inputs",
"(",
"data",
",",
"sample",
")",
":",
"## if more than one tuple in fastq list",
"if",
"len",
"(",
"sample",
".",
"files",
".",
"fastqs",
")",
">",
"1",
":",
"## create a cat command to append them all (doesn't matter if they ",
"## are gz... | 44.564103 | 21.769231 |
def deps(ctx):
'''Install or update development dependencies'''
header(deps.__doc__)
with ctx.cd(ROOT):
ctx.run('pip install -r requirements/develop.pip -r requirements/doc.pip', pty=True) | [
"def",
"deps",
"(",
"ctx",
")",
":",
"header",
"(",
"deps",
".",
"__doc__",
")",
"with",
"ctx",
".",
"cd",
"(",
"ROOT",
")",
":",
"ctx",
".",
"run",
"(",
"'pip install -r requirements/develop.pip -r requirements/doc.pip'",
",",
"pty",
"=",
"True",
")"
] | 40.8 | 24.8 |
def check(self):
"""
Run the setting checker against the setting raw value.
Raises:
AttributeError: if the setting is missing and required.
ValueError: (or other Exception) if the raw value is invalid.
"""
super(NestedSetting, self).check()
errors... | [
"def",
"check",
"(",
"self",
")",
":",
"super",
"(",
"NestedSetting",
",",
"self",
")",
".",
"check",
"(",
")",
"errors",
"=",
"[",
"]",
"for",
"subsetting",
"in",
"self",
".",
"settings",
".",
"values",
"(",
")",
":",
"try",
":",
"subsetting",
"."... | 33.117647 | 15.588235 |
def quit(self):
'''Quit fetcher'''
self._running = False
self._quit = True
self.ioloop.add_callback(self.ioloop.stop)
if hasattr(self, 'xmlrpc_server'):
self.xmlrpc_ioloop.add_callback(self.xmlrpc_server.stop)
self.xmlrpc_ioloop.add_callback(self.xmlrpc_io... | [
"def",
"quit",
"(",
"self",
")",
":",
"self",
".",
"_running",
"=",
"False",
"self",
".",
"_quit",
"=",
"True",
"self",
".",
"ioloop",
".",
"add_callback",
"(",
"self",
".",
"ioloop",
".",
"stop",
")",
"if",
"hasattr",
"(",
"self",
",",
"'xmlrpc_serv... | 40.375 | 16.625 |
def insert(self, rectangle):
"""
Insert a rectangle into the bin.
Parameters
-------------
rectangle: (2,) float, size of rectangle to insert
"""
rectangle = np.asanyarray(rectangle, dtype=np.float64)
for child in self.child:
if child is not ... | [
"def",
"insert",
"(",
"self",
",",
"rectangle",
")",
":",
"rectangle",
"=",
"np",
".",
"asanyarray",
"(",
"rectangle",
",",
"dtype",
"=",
"np",
".",
"float64",
")",
"for",
"child",
"in",
"self",
".",
"child",
":",
"if",
"child",
"is",
"not",
"None",
... | 34.659574 | 18.914894 |
def add_result(self, job):
"""Adds a job run result to the history table.
:param dict job: The job dictionary
:returns: True
"""
self.cur.execute(
"INSERT INTO history VALUES(?,?,?,?)",
(job["id"], job["description"], job["last-run"], job["last-run-result"... | [
"def",
"add_result",
"(",
"self",
",",
"job",
")",
":",
"self",
".",
"cur",
".",
"execute",
"(",
"\"INSERT INTO history VALUES(?,?,?,?)\"",
",",
"(",
"job",
"[",
"\"id\"",
"]",
",",
"job",
"[",
"\"description\"",
"]",
",",
"job",
"[",
"\"last-run\"",
"]",
... | 33.5 | 16.6 |
def use_args(
self,
argmap,
req=None,
locations=None,
as_kwargs=False,
validate=None,
error_status_code=None,
error_headers=None,
):
"""Decorator that injects parsed arguments into a view function or method.
Example usage with Flask: :... | [
"def",
"use_args",
"(",
"self",
",",
"argmap",
",",
"req",
"=",
"None",
",",
"locations",
"=",
"None",
",",
"as_kwargs",
"=",
"False",
",",
"validate",
"=",
"None",
",",
"error_status_code",
"=",
"None",
",",
"error_headers",
"=",
"None",
",",
")",
":"... | 38.565217 | 19.275362 |
def cleanup(self):
"""
Release resources used by supporting classes
"""
try:
self.unload_lime()
except AttributeError as ex:
pass
self.tunnel.cleanup()
self.shell.cleanup() | [
"def",
"cleanup",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"unload_lime",
"(",
")",
"except",
"AttributeError",
"as",
"ex",
":",
"pass",
"self",
".",
"tunnel",
".",
"cleanup",
"(",
")",
"self",
".",
"shell",
".",
"cleanup",
"(",
")"
] | 24.3 | 12.3 |
def symlink(source, destination):
"""Create a symbolic link"""
log("Symlinking {} as {}".format(source, destination))
cmd = [
'ln',
'-sf',
source,
destination,
]
subprocess.check_call(cmd) | [
"def",
"symlink",
"(",
"source",
",",
"destination",
")",
":",
"log",
"(",
"\"Symlinking {} as {}\"",
".",
"format",
"(",
"source",
",",
"destination",
")",
")",
"cmd",
"=",
"[",
"'ln'",
",",
"'-sf'",
",",
"source",
",",
"destination",
",",
"]",
"subproc... | 23.1 | 19.7 |
def rldecode(data):
"""
RunLength decoder (Adobe version) implementation based on PDF Reference
version 1.4 section 3.3.4:
The RunLengthDecode filter decodes data that has been encoded in a
simple byte-oriented format based on run length. The encoded data
is a sequence of runs, where... | [
"def",
"rldecode",
"(",
"data",
")",
":",
"decoded",
"=",
"[",
"]",
"i",
"=",
"0",
"while",
"i",
"<",
"len",
"(",
"data",
")",
":",
"#print 'data[%d]=:%d:' % (i,ord(data[i]))",
"length",
"=",
"ord",
"(",
"data",
"[",
"i",
"]",
")",
"if",
"length",
"=... | 39.971429 | 17.571429 |
def set_level(self, level=1):
"""Set the logging level
Parameters
----------
level : `int` or `bool` (optional, default: 1)
If False or 0, prints WARNING and higher messages.
If True or 1, prints INFO and higher messages.
If 2 or higher, prints all me... | [
"def",
"set_level",
"(",
"self",
",",
"level",
"=",
"1",
")",
":",
"if",
"level",
"is",
"True",
"or",
"level",
"==",
"1",
":",
"level",
"=",
"logging",
".",
"INFO",
"level_name",
"=",
"\"INFO\"",
"elif",
"level",
"is",
"False",
"or",
"level",
"<=",
... | 35.393939 | 11.848485 |
def get_all_files(root, followlinks=False):
"""
Get all files within the given root directory.
Note that this list is not ordered.
Parameters
----------
root : str
Path to a directory
followlinks : bool, optional (default: False)
Returns
-------
filepaths : list
... | [
"def",
"get_all_files",
"(",
"root",
",",
"followlinks",
"=",
"False",
")",
":",
"filepaths",
"=",
"[",
"]",
"for",
"path",
",",
"_",
",",
"files",
"in",
"os",
".",
"walk",
"(",
"root",
",",
"followlinks",
"=",
"followlinks",
")",
":",
"for",
"name",... | 24.772727 | 19.318182 |
def delete(self):
'''
Deletes link from vault and removes database information
'''
if not self._id:
verbose('This target does not have an id')
return False
# Removes link from vault directory
verbose('Removing link from vault directory')
... | [
"def",
"delete",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_id",
":",
"verbose",
"(",
"'This target does not have an id'",
")",
"return",
"False",
"# Removes link from vault directory",
"verbose",
"(",
"'Removing link from vault directory'",
")",
"os",
".",
... | 28.611111 | 19.722222 |
def path(self, var, default=NOTSET, **kwargs):
"""
:rtype: Path
"""
return Path(self.get_value(var, default=default), **kwargs) | [
"def",
"path",
"(",
"self",
",",
"var",
",",
"default",
"=",
"NOTSET",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"Path",
"(",
"self",
".",
"get_value",
"(",
"var",
",",
"default",
"=",
"default",
")",
",",
"*",
"*",
"kwargs",
")"
] | 31 | 10.6 |
def zoom_out(self):
"""Zoom the view out one zoom step.
"""
viewer = self.getfocus_viewer()
if hasattr(viewer, 'zoom_out'):
viewer.zoom_out()
return True | [
"def",
"zoom_out",
"(",
"self",
")",
":",
"viewer",
"=",
"self",
".",
"getfocus_viewer",
"(",
")",
"if",
"hasattr",
"(",
"viewer",
",",
"'zoom_out'",
")",
":",
"viewer",
".",
"zoom_out",
"(",
")",
"return",
"True"
] | 28.428571 | 7.857143 |
def training_job_summaries(self, force_refresh=False):
"""A (paginated) list of everything from ``ListTrainingJobsForTuningJob``.
Args:
force_refresh (bool): Set to True to fetch the latest data from SageMaker API.
Returns:
dict: The Amazon SageMaker response for ``List... | [
"def",
"training_job_summaries",
"(",
"self",
",",
"force_refresh",
"=",
"False",
")",
":",
"if",
"force_refresh",
":",
"self",
".",
"clear_cache",
"(",
")",
"if",
"self",
".",
"_training_job_summaries",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_tra... | 44.827586 | 24.655172 |
def combine_counts(
fns,
define_sample_name=None,
):
"""
Combine featureCounts output files for multiple samples.
Parameters
----------
fns : list of strings
Filenames of featureCounts output files to combine.
define_sample_name : function
A function mapping the featur... | [
"def",
"combine_counts",
"(",
"fns",
",",
"define_sample_name",
"=",
"None",
",",
")",
":",
"counts",
"=",
"[",
"]",
"for",
"fn",
"in",
"fns",
":",
"df",
"=",
"pd",
".",
"read_table",
"(",
"fn",
",",
"skiprows",
"=",
"1",
",",
"index_col",
"=",
"0"... | 28.424242 | 19.212121 |
def create_header(self, service_id, version_number, name, destination, source, _type=FastlyHeaderType.RESPONSE, action=FastlyHeaderAction.SET, regex=None, substitution=None, ignore_if_set=None, priority=10, response_condition=None, cache_condition=None, request_condition=None):
body = self._formdata({
"name": name... | [
"def",
"create_header",
"(",
"self",
",",
"service_id",
",",
"version_number",
",",
"name",
",",
"destination",
",",
"source",
",",
"_type",
"=",
"FastlyHeaderType",
".",
"RESPONSE",
",",
"action",
"=",
"FastlyHeaderAction",
".",
"SET",
",",
"regex",
"=",
"N... | 46.5 | 28.5 |
async def arun_process(path: Union[Path, str], target: Callable, *,
args: Tuple[Any]=(),
kwargs: Dict[str, Any]=None,
callback: Callable[[Set[Tuple[Change, str]]], Awaitable]=None,
watcher_cls: Type[AllWatcher]=PythonWatcher,
... | [
"async",
"def",
"arun_process",
"(",
"path",
":",
"Union",
"[",
"Path",
",",
"str",
"]",
",",
"target",
":",
"Callable",
",",
"*",
",",
"args",
":",
"Tuple",
"[",
"Any",
"]",
"=",
"(",
")",
",",
"kwargs",
":",
"Dict",
"[",
"str",
",",
"Any",
"]... | 47.333333 | 21.904762 |
def do_diff(self, params):
"""
\x1b[1mNAME\x1b[0m
diff - Display the differences between two paths
\x1b[1mSYNOPSIS\x1b[0m
diff <src> <dst>
\x1b[1mDESCRIPTION\x1b[0m
The output is interpreted as:
-- means the znode is missing in /new-configs
++ means the znode is new... | [
"def",
"do_diff",
"(",
"self",
",",
"params",
")",
":",
"count",
"=",
"0",
"for",
"count",
",",
"(",
"diff",
",",
"path",
")",
"in",
"enumerate",
"(",
"self",
".",
"_zk",
".",
"diff",
"(",
"params",
".",
"path_a",
",",
"params",
".",
"path_b",
")... | 30.03125 | 18.53125 |
def create_from_assocs(self, assocs, **args):
"""
Creates from a list of association objects
"""
amap = defaultdict(list)
subject_label_map = {}
for a in assocs:
subj = a['subject']
subj_id = subj['id']
subj_label = subj['label']
... | [
"def",
"create_from_assocs",
"(",
"self",
",",
"assocs",
",",
"*",
"*",
"args",
")",
":",
"amap",
"=",
"defaultdict",
"(",
"list",
")",
"subject_label_map",
"=",
"{",
"}",
"for",
"a",
"in",
"assocs",
":",
"subj",
"=",
"a",
"[",
"'subject'",
"]",
"sub... | 37.125 | 14.625 |
def SGg(self):
r'''Specific gravity of the gas phase of the chemical, [dimensionless].
The reference condition is air at 15.6 °C (60 °F) and 1 atm
(rho=1.223 kg/m^3). The definition for gases uses the compressibility
factor of the reference gas and the chemical both at the reference
... | [
"def",
"SGg",
"(",
"self",
")",
":",
"Vmg",
"=",
"self",
".",
"VolumeGas",
"(",
"T",
"=",
"288.70555555555552",
",",
"P",
"=",
"101325",
")",
"if",
"Vmg",
":",
"rho",
"=",
"Vm_to_rho",
"(",
"Vmg",
",",
"self",
".",
"MW",
")",
"return",
"SG",
"(",... | 40.941176 | 24.235294 |
def from_sas_token(cls, address, sas_token, eventhub=None, **kwargs):
"""Create an EventHubClient from an existing auth token or token generator.
:param address: The Event Hub address URL
:type address: str
:param sas_token: A SAS token or function that returns a SAS token. If a functio... | [
"def",
"from_sas_token",
"(",
"cls",
",",
"address",
",",
"sas_token",
",",
"eventhub",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"address",
"=",
"_build_uri",
"(",
"address",
",",
"eventhub",
")",
"return",
"cls",
"(",
"address",
",",
"sas_token",... | 57.625 | 27.375 |
def macros_update_many(self, data, **kwargs):
"https://developer.zendesk.com/rest_api/docs/core/macros#update-many-macros"
api_path = "/api/v2/macros/update_many.json"
return self.call(api_path, method="PUT", data=data, **kwargs) | [
"def",
"macros_update_many",
"(",
"self",
",",
"data",
",",
"*",
"*",
"kwargs",
")",
":",
"api_path",
"=",
"\"/api/v2/macros/update_many.json\"",
"return",
"self",
".",
"call",
"(",
"api_path",
",",
"method",
"=",
"\"PUT\"",
",",
"data",
"=",
"data",
",",
... | 62.5 | 22.5 |
def create(self, domain_name, friendly_name=values.unset,
voice_url=values.unset, voice_method=values.unset,
voice_fallback_url=values.unset, voice_fallback_method=values.unset,
voice_status_callback_url=values.unset,
voice_status_callback_method=values.unset,... | [
"def",
"create",
"(",
"self",
",",
"domain_name",
",",
"friendly_name",
"=",
"values",
".",
"unset",
",",
"voice_url",
"=",
"values",
".",
"unset",
",",
"voice_method",
"=",
"values",
".",
"unset",
",",
"voice_fallback_url",
"=",
"values",
".",
"unset",
",... | 49.292683 | 25.634146 |
def query_trial(request):
"""Rest API to query the trial info, with the given trial_id.
The url pattern should be like this:
curl http://<server>:<port>/query_trial?trial_id=<trial_id>
The response may be:
{
"app_url": "None",
"trial_status": "TERMINATED",
"params": {'a':... | [
"def",
"query_trial",
"(",
"request",
")",
":",
"trial_id",
"=",
"request",
".",
"GET",
".",
"get",
"(",
"\"trial_id\"",
")",
"trials",
"=",
"TrialRecord",
".",
"objects",
".",
"filter",
"(",
"trial_id",
"=",
"trial_id",
")",
".",
"order_by",
"(",
"\"-st... | 30.054054 | 14.324324 |
def padded_sequence_accuracy(logits, labels):
"""Percentage of times that predictions matches labels everywhere (non-0)."""
with tf.variable_scope("padded_sequence_accuracy", values=[logits, labels]):
logits, labels = _pad_tensors_to_same_length(logits, labels)
weights = tf.to_float(tf.not_equal(labels, 0))... | [
"def",
"padded_sequence_accuracy",
"(",
"logits",
",",
"labels",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"\"padded_sequence_accuracy\"",
",",
"values",
"=",
"[",
"logits",
",",
"labels",
"]",
")",
":",
"logits",
",",
"labels",
"=",
"_pad_tensors_to... | 59.454545 | 16.090909 |
def make_reply(self):
"""
Creates a copy of the message, exchanging sender and receiver
Returns:
spade.message.Message: a new message with exchanged sender and receiver
"""
return Message(
to=str(self.sender),
sender=str(self.to),
b... | [
"def",
"make_reply",
"(",
"self",
")",
":",
"return",
"Message",
"(",
"to",
"=",
"str",
"(",
"self",
".",
"sender",
")",
",",
"sender",
"=",
"str",
"(",
"self",
".",
"to",
")",
",",
"body",
"=",
"self",
".",
"body",
",",
"thread",
"=",
"self",
... | 26.466667 | 19 |
def p_sens_level(self, p):
'senslist : AT levelsig'
p[0] = SensList((p[2],), lineno=p.lineno(1))
p.set_lineno(0, p.lineno(1)) | [
"def",
"p_sens_level",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"SensList",
"(",
"(",
"p",
"[",
"2",
"]",
",",
")",
",",
"lineno",
"=",
"p",
".",
"lineno",
"(",
"1",
")",
")",
"p",
".",
"set_lineno",
"(",
"0",
",",
"p",
"... | 36.5 | 9.5 |
def inverted(self):
'''
Return a version of this instance with inputs replaced by outputs and vice versa.
'''
return Instance(input=self.output, output=self.input,
annotated_input=self.annotated_output,
annotated_output=self.annotated_input... | [
"def",
"inverted",
"(",
"self",
")",
":",
"return",
"Instance",
"(",
"input",
"=",
"self",
".",
"output",
",",
"output",
"=",
"self",
".",
"input",
",",
"annotated_input",
"=",
"self",
".",
"annotated_output",
",",
"annotated_output",
"=",
"self",
".",
"... | 46.2 | 22 |
def validateObjectPath(p):
"""
Ensures that the provided object path conforms to the DBus standard.
Throws a L{error.MarshallingError} if non-conformant
@type p: C{string}
@param p: A DBus object path
"""
if not p.startswith('/'):
raise MarshallingError('Object paths must begin with... | [
"def",
"validateObjectPath",
"(",
"p",
")",
":",
"if",
"not",
"p",
".",
"startswith",
"(",
"'/'",
")",
":",
"raise",
"MarshallingError",
"(",
"'Object paths must begin with a \"/\"'",
")",
"if",
"len",
"(",
"p",
")",
">",
"1",
"and",
"p",
"[",
"-",
"1",
... | 38.875 | 18.25 |
def __gen_rel_anno_file(self, top_level_layer):
"""
A rel annotation file contains edge (rel)
attributes. It is e.g. used to annotate the type of a dependency
relation (subj, obj etc.).
See also: __gen_hierarchy_file()
"""
paula_id = '{0}.{1}.{2}_{3}_rel'.format(... | [
"def",
"__gen_rel_anno_file",
"(",
"self",
",",
"top_level_layer",
")",
":",
"paula_id",
"=",
"'{0}.{1}.{2}_{3}_rel'",
".",
"format",
"(",
"top_level_layer",
",",
"self",
".",
"corpus_name",
",",
"self",
".",
"name",
",",
"top_level_layer",
")",
"E",
",",
"tre... | 46.695652 | 18.913043 |
def plot_heatmap(
self,
rank="auto",
normalize="auto",
top_n="auto",
threshold="auto",
title=None,
xlabel=None,
ylabel=None,
tooltip=None,
return_chart=False,
linkage="average",
haxis=None,
metric="euclidean",
... | [
"def",
"plot_heatmap",
"(",
"self",
",",
"rank",
"=",
"\"auto\"",
",",
"normalize",
"=",
"\"auto\"",
",",
"top_n",
"=",
"\"auto\"",
",",
"threshold",
"=",
"\"auto\"",
",",
"title",
"=",
"None",
",",
"xlabel",
"=",
"None",
",",
"ylabel",
"=",
"None",
",... | 39.130282 | 24.59507 |
def clized_default_shorts(p1, p2,
first_option='default_value',
second_option=5,
third_option=[4, 3],
last_option=False):
"""Help docstring
"""
print('%s %s %s %s %s %s' % (p1, p2, first_option, second_op... | [
"def",
"clized_default_shorts",
"(",
"p1",
",",
"p2",
",",
"first_option",
"=",
"'default_value'",
",",
"second_option",
"=",
"5",
",",
"third_option",
"=",
"[",
"4",
",",
"3",
"]",
",",
"last_option",
"=",
"False",
")",
":",
"print",
"(",
"'%s %s %s %s %s... | 43.25 | 11.5 |
def generate_random(self, bits_len=None):
"""Generates a random value.
:param int bits_len:
:rtype: int
"""
bits_len = bits_len or self._bits_random
return random().getrandbits(bits_len) | [
"def",
"generate_random",
"(",
"self",
",",
"bits_len",
"=",
"None",
")",
":",
"bits_len",
"=",
"bits_len",
"or",
"self",
".",
"_bits_random",
"return",
"random",
"(",
")",
".",
"getrandbits",
"(",
"bits_len",
")"
] | 28.5 | 10.875 |
def print_big_dir_and_big_file(self, top_n=5):
"""Print ``top_n`` big dir and ``top_n`` big file in each dir.
"""
self.assert_is_dir_and_exists()
size_table1 = sorted(
[(p, p.dirsize) for p in self.select_dir(recursive=False)],
key=lambda x: x[1],
rev... | [
"def",
"print_big_dir_and_big_file",
"(",
"self",
",",
"top_n",
"=",
"5",
")",
":",
"self",
".",
"assert_is_dir_and_exists",
"(",
")",
"size_table1",
"=",
"sorted",
"(",
"[",
"(",
"p",
",",
"p",
".",
"dirsize",
")",
"for",
"p",
"in",
"self",
".",
"sele... | 39.35 | 15 |
def _get_all_resourcescenarios(network_id, user_id):
"""
Get all the resource scenarios in a network, across all scenarios
returns a dictionary of dict objects, keyed on scenario_id
"""
rs_qry = db.DBSession.query(
Dataset.type,
Dataset.unit_id,
... | [
"def",
"_get_all_resourcescenarios",
"(",
"network_id",
",",
"user_id",
")",
":",
"rs_qry",
"=",
"db",
".",
"DBSession",
".",
"query",
"(",
"Dataset",
".",
"type",
",",
"Dataset",
".",
"unit_id",
",",
"Dataset",
".",
"name",
",",
"Dataset",
".",
"hash",
... | 34.892308 | 18.092308 |
def _cellMask(self, index):
""" Returns the data mask of the cell at the index (without any string conversion)
"""
row = index.row()
col = index.column()
if (row < 0 or row >= self.rowCount() or col < 0 or col >= self.columnCount()):
return None
# The check a... | [
"def",
"_cellMask",
"(",
"self",
",",
"index",
")",
":",
"row",
"=",
"index",
".",
"row",
"(",
")",
"col",
"=",
"index",
".",
"column",
"(",
")",
"if",
"(",
"row",
"<",
"0",
"or",
"row",
">=",
"self",
".",
"rowCount",
"(",
")",
"or",
"col",
"... | 40.088235 | 21.352941 |
def load_user_options(self):
"""Load user options from self.user_options dict
This can be set via POST to the API or via options_from_form
Only supported argument by default is 'profile'.
Override in subclasses to support other options.
"""
if self._profile_list is None... | [
"def",
"load_user_options",
"(",
"self",
")",
":",
"if",
"self",
".",
"_profile_list",
"is",
"None",
":",
"if",
"callable",
"(",
"self",
".",
"profile_list",
")",
":",
"self",
".",
"_profile_list",
"=",
"yield",
"gen",
".",
"maybe_future",
"(",
"self",
"... | 41.133333 | 18.933333 |
def is_stats_query(query):
"""
check if the query is a normal search or select query
:param query:
:return:
"""
if not query:
return False
# remove all " enclosed strings
nq = re.sub(r'"[^"]*"', '', query)
# check if there's | .... select
if re.findall(r'\|... | [
"def",
"is_stats_query",
"(",
"query",
")",
":",
"if",
"not",
"query",
":",
"return",
"False",
"# remove all \" enclosed strings\r",
"nq",
"=",
"re",
".",
"sub",
"(",
"r'\"[^\"]*\"'",
",",
"''",
",",
"query",
")",
"# check if there's | .... select\r",
"if",
"re"... | 22.352941 | 18.117647 |
def repr_data_size(size_in_bytes, precision=2): # pragma: no cover
"""Return human readable string represent of a file size. Doesn"t support
size greater than 1EB.
For example:
- 100 bytes => 100 B
- 100,000 bytes => 97.66 KB
- 100,000,000 bytes => 95.37 MB
- 100,000,000,000 bytes => 93.1... | [
"def",
"repr_data_size",
"(",
"size_in_bytes",
",",
"precision",
"=",
"2",
")",
":",
"# pragma: no cover",
"if",
"size_in_bytes",
"<",
"1024",
":",
"return",
"\"%s B\"",
"%",
"size_in_bytes",
"magnitude_of_data",
"=",
"[",
"\"B\"",
",",
"\"KB\"",
",",
"\"MB\"",
... | 30.131579 | 16.815789 |
def fetch(self):
"""
Fetch the recent refs from the remotes.
Unless git-up.fetch.all is set to true, all remotes with
locally existent branches will be fetched.
"""
fetch_kwargs = {'multiple': True}
fetch_args = []
if self.is_prune():
... | [
"def",
"fetch",
"(",
"self",
")",
":",
"fetch_kwargs",
"=",
"{",
"'multiple'",
":",
"True",
"}",
"fetch_args",
"=",
"[",
"]",
"if",
"self",
".",
"is_prune",
"(",
")",
":",
"fetch_kwargs",
"[",
"'prune'",
"]",
"=",
"True",
"if",
"self",
".",
"settings... | 29.129032 | 15.645161 |
def delete_vlan(self, nexus_host, vlanid):
"""Delete a VLAN on Nexus Switch given the VLAN ID."""
starttime = time.time()
path_snip = snipp.PATH_VLAN % vlanid
self.client.rest_delete(path_snip, nexus_host)
self.capture_and_print_timeshot(
starttime, "del_vlan",
... | [
"def",
"delete_vlan",
"(",
"self",
",",
"nexus_host",
",",
"vlanid",
")",
":",
"starttime",
"=",
"time",
".",
"time",
"(",
")",
"path_snip",
"=",
"snipp",
".",
"PATH_VLAN",
"%",
"vlanid",
"self",
".",
"client",
".",
"rest_delete",
"(",
"path_snip",
",",
... | 33.7 | 12.5 |
def new_game(self, mode=None):
"""
new_game() creates a new game. Docs TBC.
:return: JSON String containing the game object.
"""
# Create a placeholder Game object
self._g = GameObject()
# Validate game mode
_mode = mode or "normal"
logging.deb... | [
"def",
"new_game",
"(",
"self",
",",
"mode",
"=",
"None",
")",
":",
"# Create a placeholder Game object",
"self",
".",
"_g",
"=",
"GameObject",
"(",
")",
"# Validate game mode",
"_mode",
"=",
"mode",
"or",
"\"normal\"",
"logging",
".",
"debug",
"(",
"\"new_gam... | 31.658537 | 21.560976 |
def write_table(self):
"""
|write_table| with Markdown table format.
:raises pytablewriter.EmptyHeaderError: If the |headers| is empty.
:Example:
:ref:`example-markdown-table-writer`
.. note::
- |None| values are written as an empty string
- ... | [
"def",
"write_table",
"(",
"self",
")",
":",
"with",
"self",
".",
"_logger",
":",
"self",
".",
"_verify_property",
"(",
")",
"self",
".",
"__write_chapter",
"(",
")",
"self",
".",
"_write_table",
"(",
")",
"if",
"self",
".",
"is_write_null_line_after_table",... | 31.368421 | 17.578947 |
def _init(self, run_conf, run_number=None):
'''Initialization before a new run.
'''
self.stop_run.clear()
self.abort_run.clear()
self._run_status = run_status.running
self._write_run_number(run_number)
self._init_run_conf(run_conf) | [
"def",
"_init",
"(",
"self",
",",
"run_conf",
",",
"run_number",
"=",
"None",
")",
":",
"self",
".",
"stop_run",
".",
"clear",
"(",
")",
"self",
".",
"abort_run",
".",
"clear",
"(",
")",
"self",
".",
"_run_status",
"=",
"run_status",
".",
"running",
... | 35 | 8.25 |
def auth_optional(validator):
"""Decorate a RequestHandler or method to accept optional authentication token
If decorating a coroutine make sure coroutine decorator is first.
eg.::
class Handler(tornado.web.RequestHandler):
@auth_required(validator)
@coroutine
... | [
"def",
"auth_optional",
"(",
"validator",
")",
":",
"def",
"_auth_optional_decorator",
"(",
"handler",
")",
":",
"if",
"inspect",
".",
"isclass",
"(",
"handler",
")",
":",
"return",
"_wrap_class",
"(",
"handler",
",",
"validator",
")",
"return",
"_auth_optiona... | 30.809524 | 19.52381 |
def evaluate_rule(self, rule, value, target):
"""Calculate the value."""
def evaluate(expr):
if expr in LOGICAL_OPERATORS.values():
return expr
rvalue = self.get_value_for_expr(expr, target)
if rvalue is None:
return False # ignore thi... | [
"def",
"evaluate_rule",
"(",
"self",
",",
"rule",
",",
"value",
",",
"target",
")",
":",
"def",
"evaluate",
"(",
"expr",
")",
":",
"if",
"expr",
"in",
"LOGICAL_OPERATORS",
".",
"values",
"(",
")",
":",
"return",
"expr",
"rvalue",
"=",
"self",
".",
"g... | 38.1875 | 15.5625 |
def _start_element (self, tag, attrs, end):
"""
Print HTML element with end string.
@param tag: tag name
@type tag: string
@param attrs: tag attributes
@type attrs: dict
@param end: either > or />
@type end: string
@return: None
"""
... | [
"def",
"_start_element",
"(",
"self",
",",
"tag",
",",
"attrs",
",",
"end",
")",
":",
"tag",
"=",
"tag",
".",
"encode",
"(",
"self",
".",
"encoding",
",",
"\"ignore\"",
")",
"self",
".",
"fd",
".",
"write",
"(",
"\"<%s\"",
"%",
"tag",
".",
"replace... | 33.227273 | 12.045455 |
def transfer(self, from_acct: Account, b58_to_address: str, value: int, payer_acct: Account, gas_limit: int,
gas_price: int) -> str:
"""
This interface is used to call the Transfer method in ope4
that transfer an amount of tokens from one account to another account.
:pa... | [
"def",
"transfer",
"(",
"self",
",",
"from_acct",
":",
"Account",
",",
"b58_to_address",
":",
"str",
",",
"value",
":",
"int",
",",
"payer_acct",
":",
"Account",
",",
"gas_limit",
":",
"int",
",",
"gas_price",
":",
"int",
")",
"->",
"str",
":",
"func",... | 62.857143 | 30.571429 |
def _discover(**kwargs):
"""Yields info about station servers announcing themselves via multicast."""
query = station_server.MULTICAST_QUERY
for host, response in multicast.send(query, **kwargs):
try:
result = json.loads(response)
except ValueError:
_LOG.warn('Received bad JSON over multicast ... | [
"def",
"_discover",
"(",
"*",
"*",
"kwargs",
")",
":",
"query",
"=",
"station_server",
".",
"MULTICAST_QUERY",
"for",
"host",
",",
"response",
"in",
"multicast",
".",
"send",
"(",
"query",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"result",
"=",
... | 44.555556 | 19.333333 |
def stop(name=None):
'''
Kills syslog-ng. This function is intended to be used from the state module.
Users shouldn't use this function, if the service module is available on
their system. If :mod:`syslog_ng.set_config_file
<salt.modules.syslog_ng.set_binary_path>` is called before, this function
... | [
"def",
"stop",
"(",
"name",
"=",
"None",
")",
":",
"pids",
"=",
"__salt__",
"[",
"'ps.pgrep'",
"]",
"(",
"pattern",
"=",
"'syslog-ng'",
")",
"if",
"not",
"pids",
":",
"return",
"_format_state_result",
"(",
"name",
",",
"result",
"=",
"False",
",",
"com... | 31.571429 | 24.942857 |
def _append_path(new_path): # type: (str) -> None
""" Given a path string, append it to sys.path """
for path in sys.path:
path = os.path.abspath(path)
if new_path == path:
return
sys.path.append(new_path) | [
"def",
"_append_path",
"(",
"new_path",
")",
":",
"# type: (str) -> None",
"for",
"path",
"in",
"sys",
".",
"path",
":",
"path",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"path",
")",
"if",
"new_path",
"==",
"path",
":",
"return",
"sys",
".",
"path"... | 34.285714 | 10.571429 |
def _attempt_connect(host, port, timeout, verify, **kwargs):
"""
Internal function to attempt
:param host: <str> "localhost" or IPAddress
:param port: <int>
:param timeout: <int>
:param verify: <bool>
:param kwargs: <**dict> rethinkdb keyword args
:return: <connection> or <NoneType>
... | [
"def",
"_attempt_connect",
"(",
"host",
",",
"port",
",",
"timeout",
",",
"verify",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"connection",
"=",
"rethinkdb",
".",
"connect",
"(",
"host",
",",
"port",
",",
"timeout",
"=",
"timeout",
",",
"*",
"*"... | 33.227273 | 11.045455 |
def convert_ensembl_to_entrez(self, ensembl):
"""Convert Ensembl Id to Entrez Gene Id"""
if 'ENST' in ensembl:
pass
else:
raise (IndexError)
# Submit resquest to NCBI eutils/Gene database
server = "http://eutils.ncbi.nlm.nih.gov/entrez/eutils/esearch.fcgi?... | [
"def",
"convert_ensembl_to_entrez",
"(",
"self",
",",
"ensembl",
")",
":",
"if",
"'ENST'",
"in",
"ensembl",
":",
"pass",
"else",
":",
"raise",
"(",
"IndexError",
")",
"# Submit resquest to NCBI eutils/Gene database",
"server",
"=",
"\"http://eutils.ncbi.nlm.nih.gov/entr... | 36.095238 | 18.571429 |
def load(self, config):
"""Load the password from the configuration file."""
password_dict = {}
if config is None:
logger.warning("No configuration file available. Cannot load password list.")
elif not config.has_section(self._section):
logger.warning("No [%s] se... | [
"def",
"load",
"(",
"self",
",",
"config",
")",
":",
"password_dict",
"=",
"{",
"}",
"if",
"config",
"is",
"None",
":",
"logger",
".",
"warning",
"(",
"\"No configuration file available. Cannot load password list.\"",
")",
"elif",
"not",
"config",
".",
"has_sect... | 43.833333 | 30.5 |
def parse_changes():
""" grab version from CHANGES and validate entry """
with open('CHANGES') as changes:
for match in re.finditer(RE_CHANGES, changes.read(1024), re.M):
if len(match.group(1)) != len(match.group(3)):
error('incorrect underline in CHANGES')
date... | [
"def",
"parse_changes",
"(",
")",
":",
"with",
"open",
"(",
"'CHANGES'",
")",
"as",
"changes",
":",
"for",
"match",
"in",
"re",
".",
"finditer",
"(",
"RE_CHANGES",
",",
"changes",
".",
"read",
"(",
"1024",
")",
",",
"re",
".",
"M",
")",
":",
"if",
... | 34.941176 | 21.176471 |
def create_connection_model(service):
""" Create an SQL Alchemy table that connects the provides services """
# the services connected
services = service._services
# the mixins / base for the model
bases = (BaseModel,)
# the fields of the derived
attributes = {model_service_name(service): f... | [
"def",
"create_connection_model",
"(",
"service",
")",
":",
"# the services connected",
"services",
"=",
"service",
".",
"_services",
"# the mixins / base for the model",
"bases",
"=",
"(",
"BaseModel",
",",
")",
"# the fields of the derived",
"attributes",
"=",
"{",
"m... | 41.416667 | 20.333333 |
def metamodel_from_str(lang_desc, metamodel=None, **kwargs):
"""
Creates a new metamodel from the textX description given as a string.
Args:
lang_desc(str): A textX language description.
metamodel(TextXMetaModel): A metamodel that should be used.
other params: See TextXMetaModel.
... | [
"def",
"metamodel_from_str",
"(",
"lang_desc",
",",
"metamodel",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"metamodel",
":",
"metamodel",
"=",
"TextXMetaModel",
"(",
"*",
"*",
"kwargs",
")",
"language_from_str",
"(",
"lang_desc",
",",
"m... | 26.176471 | 21.823529 |
def get_paths(scheme=_get_default_scheme(), vars=None, expand=True):
"""Return a mapping containing an install scheme.
``scheme`` is the install scheme name. If not provided, it will
return the default scheme for the current platform.
"""
_ensure_cfg_read()
if expand:
return _expand_var... | [
"def",
"get_paths",
"(",
"scheme",
"=",
"_get_default_scheme",
"(",
")",
",",
"vars",
"=",
"None",
",",
"expand",
"=",
"True",
")",
":",
"_ensure_cfg_read",
"(",
")",
"if",
"expand",
":",
"return",
"_expand_vars",
"(",
"scheme",
",",
"vars",
")",
"else",... | 34.454545 | 17.181818 |
def plotly(
data: typing.Union[dict, list] = None,
layout: dict = None,
scale: float = 0.5,
figure: dict = None,
static: bool = False
):
"""
Creates a Plotly plot in the display with the specified data and
layout.
:param data:
The Plotly trace data to be ... | [
"def",
"plotly",
"(",
"data",
":",
"typing",
".",
"Union",
"[",
"dict",
",",
"list",
"]",
"=",
"None",
",",
"layout",
":",
"dict",
"=",
"None",
",",
"scale",
":",
"float",
"=",
"0.5",
",",
"figure",
":",
"dict",
"=",
"None",
",",
"static",
":",
... | 32.659091 | 21.25 |
def recv(self, socket, mode=zmq.NOBLOCK, content=True, copy=True):
"""Receive and unpack a message.
Parameters
----------
socket : ZMQStream or Socket
The socket or stream to use in receiving.
Returns
-------
[idents], msg
[idents] is a l... | [
"def",
"recv",
"(",
"self",
",",
"socket",
",",
"mode",
"=",
"zmq",
".",
"NOBLOCK",
",",
"content",
"=",
"True",
",",
"copy",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"socket",
",",
"ZMQStream",
")",
":",
"socket",
"=",
"socket",
".",
"socke... | 36.424242 | 19.181818 |
def process_item(self, item, spider):
"""
Store item data in DB.
First determine if a version of the article already exists,
if so then 'migrate' the older version to the archive table.
Second store the new article in the current version table
"""
# Set default... | [
"def",
"process_item",
"(",
"self",
",",
"item",
",",
"spider",
")",
":",
"# Set defaults",
"version",
"=",
"1",
"ancestor",
"=",
"0",
"# Search the CurrentVersion table for an old version of the article",
"try",
":",
"self",
".",
"cursor",
".",
"execute",
"(",
"s... | 45.11236 | 22.685393 |
def sign(self, url, endpoint, endpoint_path, method_verb, *args, **kwargs):
"""
Dummy Signature creation method. Override this in child.
URL is required to be returned, as some Signatures use the url for
sig generation, and api calls made must match the address exactly.
param url... | [
"def",
"sign",
"(",
"self",
",",
"url",
",",
"endpoint",
",",
"endpoint_path",
",",
"method_verb",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"url",
"=",
"self",
".",
"uri",
"return",
"url",
",",
"{",
"'params'",
":",
"{",
"'test_param'",
... | 50.5 | 25.642857 |
def _exclude_ss_bonded_cysteines(self):
"""
Pre-compute ss bonds to discard cystines for H-adding.
"""
ss_bonds = self.nh_structure.search_ss_bonds()
for cys_pair in ss_bonds:
cys1, cys2 = cys_pair
cys1.resname = 'CYX'
c... | [
"def",
"_exclude_ss_bonded_cysteines",
"(",
"self",
")",
":",
"ss_bonds",
"=",
"self",
".",
"nh_structure",
".",
"search_ss_bonds",
"(",
")",
"for",
"cys_pair",
"in",
"ss_bonds",
":",
"cys1",
",",
"cys2",
"=",
"cys_pair",
"cys1",
".",
"resname",
"=",
"'CYX'"... | 29.909091 | 11.545455 |
def max_variance_genes(data, nbins=5, frac=0.2):
"""
This function identifies the genes that have the max variance
across a number of bins sorted by mean.
Args:
data (array): genes x cells
nbins (int): number of bins to sort genes by mean expression level. Default: 10.
frac (flo... | [
"def",
"max_variance_genes",
"(",
"data",
",",
"nbins",
"=",
"5",
",",
"frac",
"=",
"0.2",
")",
":",
"# TODO: profile, make more efficient for large matrices",
"# 8000 cells: 0.325 seconds",
"# top time: sparse.csc_tocsr, csc_matvec, astype, copy, mul_scalar",
"# 73233 cells: 5.347... | 35.930233 | 16.674419 |
def get_ttf(self):
""" Given a search path, find file with requested extension """
font_dict = {}
families = []
rootdirlist = string.split(self.search_path, os.pathsep)
#for rootdir in rootdirlist:
# rootdir = os.path.expanduser(rootdir)
for dirName, subdirLis... | [
"def",
"get_ttf",
"(",
"self",
")",
":",
"font_dict",
"=",
"{",
"}",
"families",
"=",
"[",
"]",
"rootdirlist",
"=",
"string",
".",
"split",
"(",
"self",
".",
"search_path",
",",
"os",
".",
"pathsep",
")",
"#for rootdir in rootdirlist:",
"# rootdir = os.pa... | 49.179487 | 16.435897 |
def lev(self):
"""Pressure levels at grid centers (hPa or mb)
:getter: Returns the points of axis ``'lev'`` if availible in the
process's domains.
:type: array
:raises: :exc:`ValueError`
if no ``'lev'`` axis can be found.
"""
... | [
"def",
"lev",
"(",
"self",
")",
":",
"try",
":",
"for",
"domname",
",",
"dom",
"in",
"self",
".",
"domains",
".",
"items",
"(",
")",
":",
"try",
":",
"thislev",
"=",
"dom",
".",
"axes",
"[",
"'lev'",
"]",
".",
"points",
"except",
":",
"pass",
"... | 31 | 18 |
def write(self, outname, dtype='default', format='ENVI', nodata='default', compress_tif=False, overwrite=False):
"""
write the raster object to a file.
Parameters
----------
outname: str
the file to be written
dtype: str
the data type of the writt... | [
"def",
"write",
"(",
"self",
",",
"outname",
",",
"dtype",
"=",
"'default'",
",",
"format",
"=",
"'ENVI'",
",",
"nodata",
"=",
"'default'",
",",
"compress_tif",
"=",
"False",
",",
"overwrite",
"=",
"False",
")",
":",
"if",
"os",
".",
"path",
".",
"is... | 39.712121 | 20.19697 |
def _writeCloseFrame(self, reason=DISCONNECT.GO_AWAY):
'''Write a close frame with the given reason and schedule this
connection close.
'''
self.transport.writeClose(reason)
self.transport.loseConnection()
self.transport = None | [
"def",
"_writeCloseFrame",
"(",
"self",
",",
"reason",
"=",
"DISCONNECT",
".",
"GO_AWAY",
")",
":",
"self",
".",
"transport",
".",
"writeClose",
"(",
"reason",
")",
"self",
".",
"transport",
".",
"loseConnection",
"(",
")",
"self",
".",
"transport",
"=",
... | 33.625 | 17.625 |
def urlAt(self, index):
"""
Returns the url at the inputed index wihtin the stack. If the index \
is invalid, then a blank string is returned.
:return <str>
"""
if 0 <= index and index < len(self._stack):
return self._stack[index][0]
retu... | [
"def",
"urlAt",
"(",
"self",
",",
"index",
")",
":",
"if",
"0",
"<=",
"index",
"and",
"index",
"<",
"len",
"(",
"self",
".",
"_stack",
")",
":",
"return",
"self",
".",
"_stack",
"[",
"index",
"]",
"[",
"0",
"]",
"return",
"''"
] | 31.6 | 14.8 |
def _check_equal_shape(name,
static_shape,
dynamic_shape,
static_target_shape,
dynamic_target_shape=None):
"""Check that source and target shape match, statically if possible."""
static_target_shape = tf.TensorShape(static_... | [
"def",
"_check_equal_shape",
"(",
"name",
",",
"static_shape",
",",
"dynamic_shape",
",",
"static_target_shape",
",",
"dynamic_target_shape",
"=",
"None",
")",
":",
"static_target_shape",
"=",
"tf",
".",
"TensorShape",
"(",
"static_target_shape",
")",
"if",
"tensors... | 46.230769 | 19.115385 |
def query_download_tasks(self, task_ids, operate_type=1, **kwargs):
"""根据任务ID号,查询离线下载任务信息及进度信息。
:param task_ids: 要查询的任务 ID字符串 列表
:type task_ids: list or tuple
:param operate_type:
* 0:查任务信息
* 1:查进度信息,默认为1
:return: requests... | [
"def",
"query_download_tasks",
"(",
"self",
",",
"task_ids",
",",
"operate_type",
"=",
"1",
",",
"*",
"*",
"kwargs",
")",
":",
"params",
"=",
"{",
"'task_ids'",
":",
"','",
".",
"join",
"(",
"map",
"(",
"str",
",",
"task_ids",
")",
")",
",",
"'op_typ... | 28.833333 | 23.530303 |
def get_next_step(self):
"""Find the proper step when user clicks the Next button.
:returns: The step to be switched to.
:rtype: WizardStep instance or None
"""
if self.validate_extent():
new_step = self.parent.step_fc_summary
else:
new_step = sel... | [
"def",
"get_next_step",
"(",
"self",
")",
":",
"if",
"self",
".",
"validate_extent",
"(",
")",
":",
"new_step",
"=",
"self",
".",
"parent",
".",
"step_fc_summary",
"else",
":",
"new_step",
"=",
"self",
".",
"parent",
".",
"step_fc_extent_disjoint",
"return",... | 33.272727 | 12.909091 |
def check_sp_certs(self):
"""
Checks if the x509 certs of the SP exists and are valid.
:returns: If the x509 certs of the SP exists and are valid
:rtype: boolean
"""
key = self.get_sp_key()
cert = self.get_sp_cert()
return key is not None and cert is not N... | [
"def",
"check_sp_certs",
"(",
"self",
")",
":",
"key",
"=",
"self",
".",
"get_sp_key",
"(",
")",
"cert",
"=",
"self",
".",
"get_sp_cert",
"(",
")",
"return",
"key",
"is",
"not",
"None",
"and",
"cert",
"is",
"not",
"None"
] | 35 | 12.111111 |
def header(self):
''' :class:`HeaderDict` filled with request headers.
HeaderDict keys are case insensitive str.title()d
'''
if self._header is None:
self._header = HeaderDict()
for key, value in self.environ.iteritems():
if key.startswith('HT... | [
"def",
"header",
"(",
"self",
")",
":",
"if",
"self",
".",
"_header",
"is",
"None",
":",
"self",
".",
"_header",
"=",
"HeaderDict",
"(",
")",
"for",
"key",
",",
"value",
"in",
"self",
".",
"environ",
".",
"iteritems",
"(",
")",
":",
"if",
"key",
... | 37.333333 | 16.333333 |
def standalone_from_launchable(cls, launch):
"""
Given a launchable resource, create a definition of a standalone
instance, which doesn't depend on or contain references to other
elements.
"""
attrs = copy.copy(launch.el_attrs)
# Remove attributes we overwrite / d... | [
"def",
"standalone_from_launchable",
"(",
"cls",
",",
"launch",
")",
":",
"attrs",
"=",
"copy",
".",
"copy",
"(",
"launch",
".",
"el_attrs",
")",
"# Remove attributes we overwrite / don't need",
"del",
"attrs",
"[",
"\"Type\"",
"]",
"if",
"attrs",
".",
"has_key"... | 44.086957 | 14.608696 |
def redirect(pattern, to, permanent=True, locale_prefix=True, anchor=None, name=None,
query=None, vary=None, cache_timeout=12, decorators=None, re_flags=None,
to_args=None, to_kwargs=None, prepend_locale=True, merge_query=False):
"""
Return a url matcher suited for urlpatterns.
pa... | [
"def",
"redirect",
"(",
"pattern",
",",
"to",
",",
"permanent",
"=",
"True",
",",
"locale_prefix",
"=",
"True",
",",
"anchor",
"=",
"None",
",",
"name",
"=",
"None",
",",
"query",
"=",
"None",
",",
"vary",
"=",
"None",
",",
"cache_timeout",
"=",
"12"... | 40.923077 | 24.569231 |
def add_text_memo(self, memo_text):
"""Set the memo for the transaction to a new :class:`TextMemo
<stellar_base.memo.TextMemo>`.
:param memo_text: The text for the memo to add.
:type memo_text: str, bytes
:return: This builder instance.
"""
memo_text = memo.Text... | [
"def",
"add_text_memo",
"(",
"self",
",",
"memo_text",
")",
":",
"memo_text",
"=",
"memo",
".",
"TextMemo",
"(",
"memo_text",
")",
"return",
"self",
".",
"add_memo",
"(",
"memo_text",
")"
] | 33.181818 | 10.272727 |
def save(self, saveLocation, outName):
"""
Saves a featureset object to a feature class
Input:
saveLocation - output location of the data
outName - name of the table the data will be saved to
Types:
*.csv - CSV file returned
... | [
"def",
"save",
"(",
"self",
",",
"saveLocation",
",",
"outName",
")",
":",
"filename",
",",
"file_extension",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"outName",
")",
"if",
"(",
"file_extension",
"==",
"\".csv\"",
")",
":",
"res",
"=",
"os",
".",
... | 37.629032 | 14.854839 |
def _generate_ascii(self, matrix, foreground, background):
"""
Generates an identicon "image" in the ASCII format. The image will just
output the matrix used to generate the identicon.
Arguments:
matrix - Matrix describing which blocks in the identicon should be
pai... | [
"def",
"_generate_ascii",
"(",
"self",
",",
"matrix",
",",
"foreground",
",",
"background",
")",
":",
"return",
"\"\\n\"",
".",
"join",
"(",
"[",
"\"\"",
".",
"join",
"(",
"[",
"foreground",
"if",
"cell",
"else",
"background",
"for",
"cell",
"in",
"row",... | 33.782609 | 29.695652 |
def findFile(self, fname, numtype):
"""
Function that finds the associated file for fname when Fname is
time or NDump.
Parameters
----------
fname : string
The name of the file we are looking for.
numType : string
Designates how this funct... | [
"def",
"findFile",
"(",
"self",
",",
"fname",
",",
"numtype",
")",
":",
"numType",
"=",
"numtype",
".",
"upper",
"(",
")",
"if",
"numType",
"==",
"'FILE'",
":",
"#do nothing",
"return",
"fname",
"elif",
"numType",
"==",
"'CYCNUM'",
":",
"try",
":",
"fn... | 39.275 | 18.275 |
def _load_config(self):
""" Loads the configuration from YAML, if no override config was passed in initially. """
if (
self.config
): # any config being pre-set at init will short circuit out, but not a plain {}
return
# Verify that we're in a project
r... | [
"def",
"_load_config",
"(",
"self",
")",
":",
"if",
"(",
"self",
".",
"config",
")",
":",
"# any config being pre-set at init will short circuit out, but not a plain {}",
"return",
"# Verify that we're in a project",
"repo_root",
"=",
"self",
".",
"repo_root",
"if",
"not"... | 40.148148 | 23.981481 |
def database_names(self, session=None):
"""**DEPRECATED**: Get a list of the names of all databases on the
connected server.
:Parameters:
- `session` (optional): a
:class:`~pymongo.client_session.ClientSession`.
.. versionchanged:: 3.7
Deprecated. Use :... | [
"def",
"database_names",
"(",
"self",
",",
"session",
"=",
"None",
")",
":",
"warnings",
".",
"warn",
"(",
"\"database_names is deprecated. Use list_database_names \"",
"\"instead.\"",
",",
"DeprecationWarning",
",",
"stacklevel",
"=",
"2",
")",
"return",
"self",
".... | 36.470588 | 17.352941 |
def make_stream(
name, # type: Text
bin_file, # type: RawIOBase
mode="r", # type: Text
buffering=-1, # type: int
encoding=None, # type: Optional[Text]
errors=None, # type: Optional[Text]
newline="", # type: Optional[Text]
line_buffering=False, # type: bool
**kwargs # type: A... | [
"def",
"make_stream",
"(",
"name",
",",
"# type: Text",
"bin_file",
",",
"# type: RawIOBase",
"mode",
"=",
"\"r\"",
",",
"# type: Text",
"buffering",
"=",
"-",
"1",
",",
"# type: int",
"encoding",
"=",
"None",
",",
"# type: Optional[Text]",
"errors",
"=",
"None"... | 29.288462 | 15.788462 |
def get_note(self, note_id):
"""
Get a loan note that you've invested in by ID
Parameters
----------
note_id : int
The note ID
Returns
-------
dict
A dictionary representing the matching note or False
Examples
---... | [
"def",
"get_note",
"(",
"self",
",",
"note_id",
")",
":",
"index",
"=",
"0",
"while",
"True",
":",
"notes",
"=",
"self",
".",
"my_notes",
"(",
"start_index",
"=",
"index",
",",
"sort_by",
"=",
"'noteId'",
")",
"if",
"notes",
"[",
"'result'",
"]",
"!=... | 31.056604 | 24.113208 |
def effective_rules(self, context=None):
"""
Get effective rules for this rebulk object and its children.
:param context:
:type context:
:return:
:rtype:
"""
rules = Rules()
rules.extend(self._rules)
for rebulk in self._rebulks:
... | [
"def",
"effective_rules",
"(",
"self",
",",
"context",
"=",
"None",
")",
":",
"rules",
"=",
"Rules",
"(",
")",
"rules",
".",
"extend",
"(",
"self",
".",
"_rules",
")",
"for",
"rebulk",
"in",
"self",
".",
"_rebulks",
":",
"if",
"not",
"rebulk",
".",
... | 29.357143 | 12.357143 |
def verify(self, data, signature):
"""Verify the signature of a sequence of bytes.
Verify the signature of a sequence of bytes using the verifying
(public) key and the data that was originally signed, otherwise throws
an exception.
:param bytes data: A sequence of bytes that we... | [
"def",
"verify",
"(",
"self",
",",
"data",
",",
"signature",
")",
":",
"try",
":",
"return",
"self",
".",
"verifying_key",
".",
"verify",
"(",
"signature",
",",
"data",
")",
"except",
"ed25519",
".",
"BadSignatureError",
":",
"raise",
"BadSignatureError",
... | 44.5 | 22 |
def order_error(subtag, got, expected):
"""
Output an error indicating that tags were out of order.
"""
options = SUBTAG_TYPES[expected:]
if len(options) == 1:
expect_str = options[0]
elif len(options) == 2:
expect_str = '%s or %s' % (options[0], options[1])
else:
exp... | [
"def",
"order_error",
"(",
"subtag",
",",
"got",
",",
"expected",
")",
":",
"options",
"=",
"SUBTAG_TYPES",
"[",
"expected",
":",
"]",
"if",
"len",
"(",
"options",
")",
"==",
"1",
":",
"expect_str",
"=",
"options",
"[",
"0",
"]",
"elif",
"len",
"(",
... | 38.785714 | 15.071429 |
def _get_list_key(self, obj, key, vc, obj_nex_id=None):
"""Either:
* Returns a list, or
* Generates a MissingExpectedListWarning and returns None (if
the value is not a dict or list)
"""
k = obj.get(key)
if k is None:
return None
... | [
"def",
"_get_list_key",
"(",
"self",
",",
"obj",
",",
"key",
",",
"vc",
",",
"obj_nex_id",
"=",
"None",
")",
":",
"k",
"=",
"obj",
".",
"get",
"(",
"key",
")",
"if",
"k",
"is",
"None",
":",
"return",
"None",
"if",
"isinstance",
"(",
"k",
",",
"... | 36.7 | 13.05 |
def check_infile(filename):
"""Check text file exisitense.
Argument:
filename: text file of bulk updating
"""
if os.path.isfile(filename):
domain = os.path.basename(filename).split('.txt')[0]
return domain
else:
sys.stderr.write("ERROR: %s : No such file\n" % filena... | [
"def",
"check_infile",
"(",
"filename",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"filename",
")",
":",
"domain",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"filename",
")",
".",
"split",
"(",
"'.txt'",
")",
"[",
"0",
"]",
"return",... | 25.461538 | 19.076923 |
def set_properties(obj, values):
"""
Sets values of some (all) object properties.
If some properties do not exist or introspection fails
they are just silently skipped and no errors thrown.
:param obj: an object to write properties to.
:param values: a map, containing ... | [
"def",
"set_properties",
"(",
"obj",
",",
"values",
")",
":",
"if",
"values",
"==",
"None",
"or",
"len",
"(",
"values",
")",
"==",
"0",
":",
"return",
"for",
"(",
"name",
",",
"value",
")",
"in",
"values",
":",
"PropertyReflector",
".",
"set_property",... | 32.125 | 20 |
def rr_history(self, ips):
"""Get the domains related to input ips.
Args:
ips: an enumerable of strings as ips
Returns:
An enumerable of resource records and features
"""
api_name = 'opendns-rr_history'
fmt_url_path = u'dnsdb/ip/a/{0}.json'
... | [
"def",
"rr_history",
"(",
"self",
",",
"ips",
")",
":",
"api_name",
"=",
"'opendns-rr_history'",
"fmt_url_path",
"=",
"u'dnsdb/ip/a/{0}.json'",
"return",
"self",
".",
"_multi_get",
"(",
"api_name",
",",
"fmt_url_path",
",",
"ips",
")"
] | 33 | 14.181818 |
def fql(self, query, args=None, post_args=None):
"""FQL query.
Example query: "SELECT affiliations FROM user WHERE uid = me()"
"""
args = args or {}
if self.access_token:
if post_args is not None:
post_args["access_token"] = self.access_token
... | [
"def",
"fql",
"(",
"self",
",",
"query",
",",
"args",
"=",
"None",
",",
"post_args",
"=",
"None",
")",
":",
"args",
"=",
"args",
"or",
"{",
"}",
"if",
"self",
".",
"access_token",
":",
"if",
"post_args",
"is",
"not",
"None",
":",
"post_args",
"[",
... | 34.470588 | 18.509804 |
def get_customer_group_by_id(cls, customer_group_id, **kwargs):
"""Find CustomerGroup
Return single instance of CustomerGroup by its ID.
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async=True
>>> thread = api.get_cus... | [
"def",
"get_customer_group_by_id",
"(",
"cls",
",",
"customer_group_id",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async'",
")",
":",
"return",
"cls",
".",
"_get_custome... | 44.714286 | 22.333333 |
def loop(self):
"""
Run the demo suite in a loop.
"""
logging.info("Running %s in loop mode." % self.service_name)
res = None
while True:
try:
res = self.run()
time.sleep(self.loop_duration)
except KeyboardInterrupt... | [
"def",
"loop",
"(",
"self",
")",
":",
"logging",
".",
"info",
"(",
"\"Running %s in loop mode.\"",
"%",
"self",
".",
"service_name",
")",
"res",
"=",
"None",
"while",
"True",
":",
"try",
":",
"res",
"=",
"self",
".",
"run",
"(",
")",
"time",
".",
"sl... | 33.777778 | 20.333333 |
def iterSourceCode(paths):
"""
Iterate over all Python source files in C{paths}.
@param paths: A list of paths. Directories will be recursed into and
any .py files found will be yielded. Any non-directories will be
yielded as-is.
"""
for path in paths:
if os.path.isdir(pat... | [
"def",
"iterSourceCode",
"(",
"paths",
")",
":",
"for",
"path",
"in",
"paths",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"for",
"dirpath",
",",
"dirnames",
",",
"filenames",
"in",
"os",
".",
"walk",
"(",
"path",
")",
":",
... | 35.411765 | 16.352941 |
def shortname(inputid): # type: (Text) -> Text
"""Returns the last segment of the provided fragment or path."""
parsed_id = urllib.parse.urlparse(inputid)
if parsed_id.fragment:
return parsed_id.fragment.split(u"/")[-1]
return parsed_id.path.split(u"/")[-1] | [
"def",
"shortname",
"(",
"inputid",
")",
":",
"# type: (Text) -> Text",
"parsed_id",
"=",
"urllib",
".",
"parse",
".",
"urlparse",
"(",
"inputid",
")",
"if",
"parsed_id",
".",
"fragment",
":",
"return",
"parsed_id",
".",
"fragment",
".",
"split",
"(",
"u\"/\... | 46.166667 | 6.166667 |
def dbf_asdict(fn, usecols=None, keystyle='ints'):
"""Return data from dbf file fn as a dict.
fn: str
The filename string.
usecols: seqence
The columns to use, 0-based.
keystyle: str
'ints' or 'names' accepted. Should be 'ints' (default) when this
function is given to ... | [
"def",
"dbf_asdict",
"(",
"fn",
",",
"usecols",
"=",
"None",
",",
"keystyle",
"=",
"'ints'",
")",
":",
"if",
"keystyle",
"not",
"in",
"[",
"'ints'",
",",
"'names'",
"]",
":",
"raise",
"ValueError",
"(",
"'Unknown keyword: '",
"+",
"str",
"(",
"keystyle",... | 26.216216 | 20.783784 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.