text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def build_input_pipeline(train_images, batch_size):
"""Build an iterator over training batches."""
training_dataset = tf.data.Dataset.from_tensor_slices(train_images)
training_batches = training_dataset.shuffle(
50000, reshuffle_each_iteration=True).repeat().batch(batch_size)
training_iterator = tf.compa... | [
"def",
"build_input_pipeline",
"(",
"train_images",
",",
"batch_size",
")",
":",
"training_dataset",
"=",
"tf",
".",
"data",
".",
"Dataset",
".",
"from_tensor_slices",
"(",
"train_images",
")",
"training_batches",
"=",
"training_dataset",
".",
"shuffle",
"(",
"500... | 46.444444 | 0.018779 |
def chugid_and_umask(runas, umask, group=None):
'''
Helper method for for subprocess.Popen to initialise uid/gid and umask
for the new process.
'''
set_runas = False
set_grp = False
current_user = getpass.getuser()
if runas and runas != current_user:
set_runas = True
run... | [
"def",
"chugid_and_umask",
"(",
"runas",
",",
"umask",
",",
"group",
"=",
"None",
")",
":",
"set_runas",
"=",
"False",
"set_grp",
"=",
"False",
"current_user",
"=",
"getpass",
".",
"getuser",
"(",
")",
"if",
"runas",
"and",
"runas",
"!=",
"current_user",
... | 26.230769 | 0.001414 |
def overview(self, limit=None):
"""GETs overview of user's activities. Calls :meth:`narwal.Reddit.user_overview`.
:param limit: max number of items to get
"""
return self._reddit.user_overview(self.name, limit=limit) | [
"def",
"overview",
"(",
"self",
",",
"limit",
"=",
"None",
")",
":",
"return",
"self",
".",
"_reddit",
".",
"user_overview",
"(",
"self",
".",
"name",
",",
"limit",
"=",
"limit",
")"
] | 42.166667 | 0.015504 |
def schedule(self, schedule_time, *messages):
"""Send one or more messages to be enqueued at a specific time.
Returns a list of the sequence numbers of the enqueued messages.
:param schedule_time: The date and time to enqueue the messages.
:type schedule_time: ~datetime.datetime
... | [
"def",
"schedule",
"(",
"self",
",",
"schedule_time",
",",
"*",
"messages",
")",
":",
"for",
"message",
"in",
"messages",
":",
"if",
"not",
"self",
".",
"session_id",
"and",
"not",
"message",
".",
"properties",
".",
"group_id",
":",
"raise",
"ValueError",
... | 42.166667 | 0.001932 |
def decompose_dateint(dateint):
"""Decomposes the given dateint into its year, month and day components.
Arguments
---------
dateint : int
An integer object decipting a specific calendaric day; e.g. 20161225.
Returns
-------
year : int
The year component of the given datein... | [
"def",
"decompose_dateint",
"(",
"dateint",
")",
":",
"year",
"=",
"int",
"(",
"dateint",
"/",
"10000",
")",
"leftover",
"=",
"dateint",
"-",
"year",
"*",
"10000",
"month",
"=",
"int",
"(",
"leftover",
"/",
"100",
")",
"day",
"=",
"leftover",
"-",
"m... | 27.272727 | 0.00161 |
def normalize_getitem_args(args):
'''Turns the arguments to __getitem__ magic methods into a uniform
list of tuples and strings
'''
if not isinstance(args, tuple):
args = (args,)
return_val = []
for arg in args:
if isinstance(arg, six.string_types + (int, )):
return_v... | [
"def",
"normalize_getitem_args",
"(",
"args",
")",
":",
"if",
"not",
"isinstance",
"(",
"args",
",",
"tuple",
")",
":",
"args",
"=",
"(",
"args",
",",
")",
"return_val",
"=",
"[",
"]",
"for",
"arg",
"in",
"args",
":",
"if",
"isinstance",
"(",
"arg",
... | 34.117647 | 0.001678 |
def resample_vinci(
fref,
fflo,
faff,
intrp = 0,
fimout = '',
fcomment = '',
outpath = '',
pickname = 'ref',
vc = '',
con = '',
vincipy_path = '',
atlas_resample = False,
atlas_ref_make = False,
atlas_ref_del... | [
"def",
"resample_vinci",
"(",
"fref",
",",
"fflo",
",",
"faff",
",",
"intrp",
"=",
"0",
",",
"fimout",
"=",
"''",
",",
"fcomment",
"=",
"''",
",",
"outpath",
"=",
"''",
",",
"pickname",
"=",
"'ref'",
",",
"vc",
"=",
"''",
",",
"con",
"=",
"''",
... | 29.616438 | 0.021929 |
def random_adjspecies_pair(maxlen=None, prevent_stutter=True):
"""
Return an ordered 2-tuple containing a species and a describer.
The letter-count of the pair is guarantee to not exceed `maxlen` if
it is given. If `prevent_stutter` is True, the last letter of the
first item of the pair will be diff... | [
"def",
"random_adjspecies_pair",
"(",
"maxlen",
"=",
"None",
",",
"prevent_stutter",
"=",
"True",
")",
":",
"while",
"True",
":",
"pair",
"=",
"_random_adjspecies_pair",
"(",
")",
"if",
"maxlen",
"and",
"len",
"(",
"''",
".",
"join",
"(",
"pair",
")",
")... | 39.533333 | 0.001647 |
def get_profile(self, img_type, coordinate, num_points):
''' Extract a profile from (lat1,lon1) to (lat2,lon2)
Args:
img_type (str): Either lola or wac.
coordinate (float,float,float,flaot): A tupple
``(lon0,lon1,lat0,lat1)`` with:
- lon0: First ... | [
"def",
"get_profile",
"(",
"self",
",",
"img_type",
",",
"coordinate",
",",
"num_points",
")",
":",
"lon0",
",",
"lon1",
",",
"lat0",
",",
"lat1",
"=",
"coordinate",
"X",
",",
"Y",
",",
"Z",
"=",
"self",
".",
"get_arrays",
"(",
"img_type",
")",
"y0",... | 37.233333 | 0.001745 |
def _get_forward_relationships(opts):
"""
Returns an `OrderedDict` of field names to `RelationInfo`.
"""
forward_relations = OrderedDict()
for field in [field for field in opts.fields if field.serialize and field.rel]:
forward_relations[field.name] = RelationInfo(
model_field=fie... | [
"def",
"_get_forward_relationships",
"(",
"opts",
")",
":",
"forward_relations",
"=",
"OrderedDict",
"(",
")",
"for",
"field",
"in",
"[",
"field",
"for",
"field",
"in",
"opts",
".",
"fields",
"if",
"field",
".",
"serialize",
"and",
"field",
".",
"rel",
"]"... | 35.035714 | 0.001984 |
def _FormatSocketInet32Token(self, token_data):
"""Formats an Internet socket token as a dictionary of values.
Args:
token_data (bsm_token_data_sockinet32): AUT_SOCKINET32 token data.
Returns:
dict[str, str]: token values.
"""
protocol = bsmtoken.BSM_PROTOCOLS.get(token_data.socket_fam... | [
"def",
"_FormatSocketInet32Token",
"(",
"self",
",",
"token_data",
")",
":",
"protocol",
"=",
"bsmtoken",
".",
"BSM_PROTOCOLS",
".",
"get",
"(",
"token_data",
".",
"socket_family",
",",
"'UNKNOWN'",
")",
"ip_address",
"=",
"self",
".",
"_FormatPackedIPv4Address",
... | 34.375 | 0.00177 |
def find_matching(root_path,
relative_paths_to_search,
file_pattern):
"""
Given an absolute `root_path`, a list of relative paths to that
absolute root path (`relative_paths_to_search`), and a `file_pattern`
like '*.sql', returns information about the files. For examp... | [
"def",
"find_matching",
"(",
"root_path",
",",
"relative_paths_to_search",
",",
"file_pattern",
")",
":",
"matching",
"=",
"[",
"]",
"root_path",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"root_path",
")",
"for",
"relative_path_to_search",
"in",
"relative_pa... | 40.333333 | 0.000621 |
def domains(self):
"""
Access the domains
:returns: twilio.rest.api.v2010.account.sip.domain.DomainList
:rtype: twilio.rest.api.v2010.account.sip.domain.DomainList
"""
if self._domains is None:
self._domains = DomainList(self._version, account_sid=self._solut... | [
"def",
"domains",
"(",
"self",
")",
":",
"if",
"self",
".",
"_domains",
"is",
"None",
":",
"self",
".",
"_domains",
"=",
"DomainList",
"(",
"self",
".",
"_version",
",",
"account_sid",
"=",
"self",
".",
"_solution",
"[",
"'account_sid'",
"]",
",",
")",... | 36.1 | 0.008108 |
def _extract_calibration(xroot):
"""Extract AHRS calibration information from XML root.
Parameters
----------
xroot: XML root
Returns
-------
Aoff: numpy.array with shape(3,)
Arot: numpy.array with shape(3,3)
Hoff: numpy.array with shape(3,)
Hrot: numpy.array with shape(3,3)
... | [
"def",
"_extract_calibration",
"(",
"xroot",
")",
":",
"names",
"=",
"[",
"c",
".",
"text",
"for",
"c",
"in",
"xroot",
".",
"findall",
"(",
"\".//Name\"",
")",
"]",
"val",
"=",
"[",
"[",
"i",
".",
"text",
"for",
"i",
"in",
"c",
"]",
"for",
"c",
... | 32.38 | 0.0006 |
def skos_transitive(rdf, narrower=True):
"""Perform transitive closure inference (S22, S24)."""
for conc in rdf.subjects(RDF.type, SKOS.Concept):
for bt in rdf.transitive_objects(conc, SKOS.broader):
if bt == conc:
continue
rdf.add((conc, SKOS.broaderTransitive, b... | [
"def",
"skos_transitive",
"(",
"rdf",
",",
"narrower",
"=",
"True",
")",
":",
"for",
"conc",
"in",
"rdf",
".",
"subjects",
"(",
"RDF",
".",
"type",
",",
"SKOS",
".",
"Concept",
")",
":",
"for",
"bt",
"in",
"rdf",
".",
"transitive_objects",
"(",
"conc... | 44.555556 | 0.002445 |
def render(self):
"Re-render Jupyter cell for batch of images."
clear_output()
self.write_csv()
if self.empty() and self._skipped>0:
return display(f'No images to show :). {self._skipped} pairs were '
f'skipped since at least one of the images was deleted ... | [
"def",
"render",
"(",
"self",
")",
":",
"clear_output",
"(",
")",
"self",
".",
"write_csv",
"(",
")",
"if",
"self",
".",
"empty",
"(",
")",
"and",
"self",
".",
"_skipped",
">",
"0",
":",
"return",
"display",
"(",
"f'No images to show :). {self._skipped} pa... | 46.8 | 0.009777 |
def l_sa_check(template, literal, is_standalone):
"""Do a preliminary check to see if a tag could be a standalone"""
# If there is a newline, or the previous tag was a standalone
if literal.find('\n') != -1 or is_standalone:
padding = literal.split('\n')[-1]
# If all the characters since t... | [
"def",
"l_sa_check",
"(",
"template",
",",
"literal",
",",
"is_standalone",
")",
":",
"# If there is a newline, or the previous tag was a standalone",
"if",
"literal",
".",
"find",
"(",
"'\\n'",
")",
"!=",
"-",
"1",
"or",
"is_standalone",
":",
"padding",
"=",
"lit... | 38.071429 | 0.001832 |
def _checkForOrphanedModels (self):
"""If there are any models that haven't been updated in a while, consider
them dead, and mark them as hidden in our resultsDB. We also change the
paramsHash and particleHash of orphaned models so that we can
re-generate that particle and/or model again if we desire.
... | [
"def",
"_checkForOrphanedModels",
"(",
"self",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Checking for orphaned models older than %s\"",
"%",
"(",
"self",
".",
"_modelOrphanIntervalSecs",
")",
")",
"while",
"True",
":",
"orphanedModelId",
"=",
"self",
... | 44.35 | 0.013603 |
def _delete_msg(self, conn, queue_url, receipt_handle):
"""
Delete the message specified by ``receipt_handle`` in the queue
specified by ``queue_url``.
:param conn: SQS API connection
:type conn: :py:class:`botocore:SQS.Client`
:param queue_url: queue URL to delete the m... | [
"def",
"_delete_msg",
"(",
"self",
",",
"conn",
",",
"queue_url",
",",
"receipt_handle",
")",
":",
"resp",
"=",
"conn",
".",
"delete_message",
"(",
"QueueUrl",
"=",
"queue_url",
",",
"ReceiptHandle",
"=",
"receipt_handle",
")",
"if",
"resp",
"[",
"'ResponseM... | 46.772727 | 0.001905 |
def query_kb_mappings(kbid, sortby="to", key="", value="",
match_type="s"):
"""Return a list of all mappings from the given kb, ordered by key.
If key given, give only those with left side (mapFrom) = key.
If value given, give only those with right side (mapTo) = value.
:param kb... | [
"def",
"query_kb_mappings",
"(",
"kbid",
",",
"sortby",
"=",
"\"to\"",
",",
"key",
"=",
"\"\"",
",",
"value",
"=",
"\"\"",
",",
"match_type",
"=",
"\"s\"",
")",
":",
"return",
"models",
".",
"KnwKBRVAL",
".",
"query_kb_mappings",
"(",
"kbid",
",",
"sortb... | 48.466667 | 0.00135 |
def get_by_model(self, model):
"""Gets all object by a specific model."""
content_type = ContentType.objects.get_for_model(model)
return self.filter(content_type=content_type) | [
"def",
"get_by_model",
"(",
"self",
",",
"model",
")",
":",
"content_type",
"=",
"ContentType",
".",
"objects",
".",
"get_for_model",
"(",
"model",
")",
"return",
"self",
".",
"filter",
"(",
"content_type",
"=",
"content_type",
")"
] | 49 | 0.01005 |
def ftr_string_to_instance(config_string):
""" Return a :class:`SiteConfig` built from a ``config_string``.
Simple syntax errors are just plainly ignored, and logged as warnings.
:param config_string: a full site config file, raw-loaded from storage
with something like
``config_string = op... | [
"def",
"ftr_string_to_instance",
"(",
"config_string",
")",
":",
"config",
"=",
"SiteConfig",
"(",
")",
"for",
"line_number",
",",
"line_content",
"in",
"enumerate",
"(",
"config_string",
".",
"strip",
"(",
")",
".",
"split",
"(",
"u'\\n'",
")",
",",
"start"... | 32.817308 | 0.000569 |
def load(self):
"""
Loads the children for this item.
"""
if self._loaded:
return
self.setChildIndicatorPolicy(self.DontShowIndicatorWhenChildless)
self._loaded = True
column = self.schemaColumn()
if not column.isRe... | [
"def",
"load",
"(",
"self",
")",
":",
"if",
"self",
".",
"_loaded",
":",
"return",
"self",
".",
"setChildIndicatorPolicy",
"(",
"self",
".",
"DontShowIndicatorWhenChildless",
")",
"self",
".",
"_loaded",
"=",
"True",
"column",
"=",
"self",
".",
"schemaColumn... | 27.909091 | 0.009449 |
def unpackSeptets(septets, numberOfSeptets=None, prevOctet=None, shift=7):
""" Unpacks the specified septets into octets
:param septets: Iterator or iterable containing the septets packed into octets
:type septets: iter(bytearray), bytearray or str
:param numberOfSeptets: The amount of septets to ... | [
"def",
"unpackSeptets",
"(",
"septets",
",",
"numberOfSeptets",
"=",
"None",
",",
"prevOctet",
"=",
"None",
",",
"shift",
"=",
"7",
")",
":",
"result",
"=",
"bytearray",
"(",
")",
"if",
"type",
"(",
"septets",
")",
"==",
"str",
":",
"septets",
"=",
"... | 34.108696 | 0.012392 |
def qurl(parser, token):
"""
Append, remove or replace query string parameters (preserve order)
{% qurl url [param]* [as <var_name>] %}
{% qurl 'reverse_name' [reverse_params] | [param]* [as <var_name>] %}
param:
name=value: replace all values of name by one value
... | [
"def",
"qurl",
"(",
"parser",
",",
"token",
")",
":",
"bits",
"=",
"token",
".",
"split_contents",
"(",
")",
"if",
"len",
"(",
"bits",
")",
"<",
"2",
":",
"raise",
"TemplateSyntaxError",
"(",
"'\"{0}\" takes at least one argument (url)'",
".",
"format",
"(",... | 31.857143 | 0.000544 |
def _stringify_path(path_or_buffer):
'''Convert path like object to string
Args:
path_or_buffer: object to be converted
Returns:
string_path_or_buffer: maybe string version of path_or_buffer
'''
try:
import pathlib
_PATHLIB_INSTALLED = True
except ImportError:
... | [
"def",
"_stringify_path",
"(",
"path_or_buffer",
")",
":",
"try",
":",
"import",
"pathlib",
"_PATHLIB_INSTALLED",
"=",
"True",
"except",
"ImportError",
":",
"_PATHLIB_INSTALLED",
"=",
"False",
"if",
"hasattr",
"(",
"path_or_buffer",
",",
"'__fspath__'",
")",
":",
... | 24.478261 | 0.001709 |
def calculate_file_distances(dicom_files, field_weights=None,
dist_method_cls=None, **kwargs):
"""
Calculates the DicomFileDistance between all files in dicom_files, using an
weighted Levenshtein measure between all field names in field_weights and
their corresponding weight... | [
"def",
"calculate_file_distances",
"(",
"dicom_files",
",",
"field_weights",
"=",
"None",
",",
"dist_method_cls",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"dist_method_cls",
"is",
"None",
":",
"dist_method",
"=",
"LevenshteinDicomFileDistance",
"(",
... | 35.983051 | 0.001376 |
def generate_mtime_map(opts, path_map):
'''
Generate a dict of filename -> mtime
'''
file_map = {}
for saltenv, path_list in six.iteritems(path_map):
for path in path_list:
for directory, _, filenames in salt.utils.path.os_walk(path):
for item in filenames:
... | [
"def",
"generate_mtime_map",
"(",
"opts",
",",
"path_map",
")",
":",
"file_map",
"=",
"{",
"}",
"for",
"saltenv",
",",
"path_list",
"in",
"six",
".",
"iteritems",
"(",
"path_map",
")",
":",
"for",
"path",
"in",
"path_list",
":",
"for",
"directory",
",",
... | 41.333333 | 0.000985 |
def merge_default_adapters():
"""Merges the default adapters file in the trimmomatic adapters directory
Returns
-------
str
Path with the merged adapters file.
"""
default_adapters = [os.path.join(ADAPTERS_PATH, x) for x in
os.listdir(ADAPTERS_PATH)]
filepat... | [
"def",
"merge_default_adapters",
"(",
")",
":",
"default_adapters",
"=",
"[",
"os",
".",
"path",
".",
"join",
"(",
"ADAPTERS_PATH",
",",
"x",
")",
"for",
"x",
"in",
"os",
".",
"listdir",
"(",
"ADAPTERS_PATH",
")",
"]",
"filepath",
"=",
"os",
".",
"path... | 28.894737 | 0.001764 |
def _det_stat_freq(det_freq, data_freq_sq, data_freq, w, Nc, ulen, mplen):
"""
Compute detection statistic in the frequency domain
:type det_freq: numpy.ndarray
:param det_freq: detector in freq domain
:type data_freq_sq: numpy.ndarray
:param data_freq_sq: squared data in freq domain
:type ... | [
"def",
"_det_stat_freq",
"(",
"det_freq",
",",
"data_freq_sq",
",",
"data_freq",
",",
"w",
",",
"Nc",
",",
"ulen",
",",
"mplen",
")",
":",
"num_cor",
"=",
"np",
".",
"multiply",
"(",
"det_freq",
",",
"data_freq",
")",
"# Numerator convolution",
"den_cor",
... | 38.322581 | 0.000821 |
def get_optics(self):
"""Return optics information."""
optics_table = junos_views.junos_intf_optics_table(self.device)
optics_table.get()
optics_items = optics_table.items()
# optics_items has no lane information, so we need to re-format data
# inserting lane 0 for all o... | [
"def",
"get_optics",
"(",
"self",
")",
":",
"optics_table",
"=",
"junos_views",
".",
"junos_intf_optics_table",
"(",
"self",
".",
"device",
")",
"optics_table",
".",
"get",
"(",
")",
"optics_items",
"=",
"optics_table",
".",
"items",
"(",
")",
"# optics_items ... | 41.97 | 0.002095 |
def data_item_live(self, data_item):
""" Return a context manager to put the data item in a 'live state'. """
class LiveContextManager:
def __init__(self, manager, object):
self.__manager = manager
self.__object = object
def __enter__(self):
... | [
"def",
"data_item_live",
"(",
"self",
",",
"data_item",
")",
":",
"class",
"LiveContextManager",
":",
"def",
"__init__",
"(",
"self",
",",
"manager",
",",
"object",
")",
":",
"self",
".",
"__manager",
"=",
"manager",
"self",
".",
"__object",
"=",
"object",... | 47.416667 | 0.008621 |
def numpy_binning(data, bins=10, range=None, *args, **kwargs) -> NumpyBinning:
"""Construct binning schema compatible with numpy.histogram
Parameters
----------
data: array_like, optional
This is optional if both bins and range are set
bins: int or array_like
range: Optional[tuple]
... | [
"def",
"numpy_binning",
"(",
"data",
",",
"bins",
"=",
"10",
",",
"range",
"=",
"None",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"->",
"NumpyBinning",
":",
"if",
"isinstance",
"(",
"bins",
",",
"int",
")",
":",
"if",
"range",
":",
"bins",
... | 28.133333 | 0.001145 |
def calculate_job_input_hash(job_spec, workflow_json):
"""Calculate md5 hash of job specification and workflow json."""
if 'workflow_workspace' in job_spec:
del job_spec['workflow_workspace']
job_md5_buffer = md5()
job_md5_buffer.update(json.dumps(job_spec).encode('utf-8'))
job_md5_buffer.up... | [
"def",
"calculate_job_input_hash",
"(",
"job_spec",
",",
"workflow_json",
")",
":",
"if",
"'workflow_workspace'",
"in",
"job_spec",
":",
"del",
"job_spec",
"[",
"'workflow_workspace'",
"]",
"job_md5_buffer",
"=",
"md5",
"(",
")",
"job_md5_buffer",
".",
"update",
"... | 49.75 | 0.002469 |
def _substitute(self, str):
"""
Substitute words in the string, according to the specified reflections,
e.g. "I'm" -> "you are"
:type str: str
:param str: The string to be mapped
:rtype: str
"""
if not self.attr.get("substitute",True):return str
r... | [
"def",
"_substitute",
"(",
"self",
",",
"str",
")",
":",
"if",
"not",
"self",
".",
"attr",
".",
"get",
"(",
"\"substitute\"",
",",
"True",
")",
":",
"return",
"str",
"return",
"self",
".",
"_regex",
".",
"sub",
"(",
"lambda",
"mo",
":",
"self",
"."... | 33.846154 | 0.015487 |
def _get_axes(dim, subplots_kwargs=dict()):
"""
Parameters
----------
dim : int
Dimensionality of the orbit.
subplots_kwargs : dict (optional)
Dictionary of kwargs passed to :func:`~matplotlib.pyplot.subplots`.
"""
import matplotlib.pyplot as plt
if dim > 1:
n_p... | [
"def",
"_get_axes",
"(",
"dim",
",",
"subplots_kwargs",
"=",
"dict",
"(",
")",
")",
":",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"if",
"dim",
">",
"1",
":",
"n_panels",
"=",
"int",
"(",
"dim",
"*",
"(",
"dim",
"-",
"1",
")",
"/",
"2",... | 23.111111 | 0.001538 |
def sort_dict(dict_, part='keys', key=None, reverse=False):
"""
sorts a dictionary by its values or its keys
Args:
dict_ (dict_): a dictionary
part (str): specifies to sort by keys or values
key (Optional[func]): a function that takes specified part
and returns a sortab... | [
"def",
"sort_dict",
"(",
"dict_",
",",
"part",
"=",
"'keys'",
",",
"key",
"=",
"None",
",",
"reverse",
"=",
"False",
")",
":",
"if",
"part",
"==",
"'keys'",
":",
"index",
"=",
"0",
"elif",
"part",
"in",
"{",
"'vals'",
",",
"'values'",
"}",
":",
"... | 30.938776 | 0.000639 |
def as4_capability(self, **kwargs):
"""Set Spanning Tree state.
Args:
enabled (bool): Is AS4 Capability enabled? (True, False)
callback (function): A function executed upon completion of the
method. The only parameter passed to `callback` will be the
... | [
"def",
"as4_capability",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"enabled",
"=",
"kwargs",
".",
"pop",
"(",
"'enabled'",
",",
"True",
")",
"callback",
"=",
"kwargs",
".",
"pop",
"(",
"'callback'",
",",
"self",
".",
"_callback",
")",
"if",
"no... | 38.288462 | 0.000979 |
def reformat_pattern(pattern, compile=False):
'''
Apply the filters on user pattern to generate a new regular expression
pattern.
A user provided variable, should start with an alphabet, can be
alphanumeric and can have _.
'''
# User pattern: (w:<name>) --> Changes to (?P<name>\w)
rex_p... | [
"def",
"reformat_pattern",
"(",
"pattern",
",",
"compile",
"=",
"False",
")",
":",
"# User pattern: (w:<name>) --> Changes to (?P<name>\\w)",
"rex_pattern",
"=",
"re",
".",
"sub",
"(",
"r'\\(w:<([\\w\\d_]+)>\\)'",
",",
"'(?P<\\\\1>\\w+)'",
",",
"pattern",
")",
"# User ... | 33.151079 | 0.02402 |
def apply_filter(self, *args, **kwargs):
"""Overridden `apply_filter` to perform tasks for hierarchy child"""
if self.filter is not None:
# make sure self.filter knows about root manual indices
self.filter.retrieve_manual_indices()
# Copy event data from hierarchy parent... | [
"def",
"apply_filter",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"filter",
"is",
"not",
"None",
":",
"# make sure self.filter knows about root manual indices",
"self",
".",
"filter",
".",
"retrieve_manual_indices",
"(",... | 41.533333 | 0.001569 |
def observers(self):
"""the players who are actually observers"""
ret = []
for player in self.players:
try:
if player.observer: ret.append(player)
except: pass # ignore PlayerRecords which don't have an observer attribute
return ret | [
"def",
"observers",
"(",
"self",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"player",
"in",
"self",
".",
"players",
":",
"try",
":",
"if",
"player",
".",
"observer",
":",
"ret",
".",
"append",
"(",
"player",
")",
"except",
":",
"pass",
"# ignore PlayerRe... | 37.125 | 0.023026 |
def transform(self, X):
r"""Maps the input data through the transformer to correspondingly
shaped output data array/list.
Parameters
----------
X : ndarray(T, n) or list of ndarray(T_i, n)
The input data, where T is the number of time steps and n is the
n... | [
"def",
"transform",
"(",
"self",
",",
"X",
")",
":",
"if",
"isinstance",
"(",
"X",
",",
"np",
".",
"ndarray",
")",
":",
"if",
"X",
".",
"ndim",
"==",
"2",
":",
"mapped",
"=",
"self",
".",
"_transform_array",
"(",
"X",
")",
"return",
"mapped",
"el... | 42.5 | 0.001816 |
def authentications_spec(self):
"""Spec for a group of authentication options"""
return container_spec(authentication_objs.Authentication
, dictof(string_spec(), set_options(
reading = optional_spec(authentication_spec())
, writing = optional_spec(authenti... | [
"def",
"authentications_spec",
"(",
"self",
")",
":",
"return",
"container_spec",
"(",
"authentication_objs",
".",
"Authentication",
",",
"dictof",
"(",
"string_spec",
"(",
")",
",",
"set_options",
"(",
"reading",
"=",
"optional_spec",
"(",
"authentication_spec",
... | 41.555556 | 0.026178 |
def options(self):
"""Get the options set on this collection.
Returns a dictionary of options and their values - see
:meth:`~pymongo.database.Database.create_collection` for more
information on the possible options. Returns an empty
dictionary if the collection has not been crea... | [
"def",
"options",
"(",
"self",
")",
":",
"with",
"self",
".",
"_socket_for_primary_reads",
"(",
")",
"as",
"(",
"sock_info",
",",
"slave_ok",
")",
":",
"if",
"sock_info",
".",
"max_wire_version",
">",
"2",
":",
"criteria",
"=",
"{",
"\"name\"",
":",
"sel... | 34.033333 | 0.001905 |
def socket(self):
'''
Lazily create the socket.
'''
if not hasattr(self, '_socket'):
# create a new one
self._socket = self.context.socket(zmq.REQ)
if hasattr(zmq, 'RECONNECT_IVL_MAX'):
self._socket.setsockopt(
zmq.R... | [
"def",
"socket",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_socket'",
")",
":",
"# create a new one",
"self",
".",
"_socket",
"=",
"self",
".",
"context",
".",
"socket",
"(",
"zmq",
".",
"REQ",
")",
"if",
"hasattr",
"(",
"zmq... | 37.708333 | 0.002155 |
def sh(args, **kwargs):
"""
runs the given cmd as shell command
"""
if isinstance(args, str):
args = args.split()
if not args:
return
click.echo('$ {0}'.format(' '.join(args)))
try:
return subprocess.check_call(args, **kwargs)
except subprocess.CalledProcessError ... | [
"def",
"sh",
"(",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"isinstance",
"(",
"args",
",",
"str",
")",
":",
"args",
"=",
"args",
".",
"split",
"(",
")",
"if",
"not",
"args",
":",
"return",
"click",
".",
"echo",
"(",
"'$ {0}'",
".",
"for... | 29.466667 | 0.002193 |
def send(self, data):
"""
Send `data` to the remote end.
"""
_vv and IOLOG.debug('%r.send(%r..)', self, repr(data)[:100])
self.context.send(Message.pickled(data, handle=self.dst_handle)) | [
"def",
"send",
"(",
"self",
",",
"data",
")",
":",
"_vv",
"and",
"IOLOG",
".",
"debug",
"(",
"'%r.send(%r..)'",
",",
"self",
",",
"repr",
"(",
"data",
")",
"[",
":",
"100",
"]",
")",
"self",
".",
"context",
".",
"send",
"(",
"Message",
".",
"pick... | 36.833333 | 0.00885 |
def previousExon(self) :
"""Returns the previous exon of the transcript, or None if there is none"""
if self.number == 0 :
return None
try :
return self.transcript.exons[self.number-1]
except IndexError :
return None | [
"def",
"previousExon",
"(",
"self",
")",
":",
"if",
"self",
".",
"number",
"==",
"0",
":",
"return",
"None",
"try",
":",
"return",
"self",
".",
"transcript",
".",
"exons",
"[",
"self",
".",
"number",
"-",
"1",
"]",
"except",
"IndexError",
":",
"retur... | 23 | 0.07113 |
def derivative(fun, z0, n=1, **kwds):
"""
Calculate n-th derivative of complex analytic function using FFT
Parameters
----------
fun : callable
function to differentiate
z0 : real or complex scalar at which to evaluate the derivatives
n : scalar integer, default 1
Number of ... | [
"def",
"derivative",
"(",
"fun",
",",
"z0",
",",
"n",
"=",
"1",
",",
"*",
"*",
"kwds",
")",
":",
"result",
"=",
"taylor",
"(",
"fun",
",",
"z0",
",",
"n",
"=",
"n",
",",
"*",
"*",
"kwds",
")",
"# convert taylor series --> actual derivatives.",
"m",
... | 41.979381 | 0.00024 |
def get_resource(self, service_name, resource_name, base_class=None):
"""
Returns a ``Resource`` **class** for a given service.
:param service_name: A string that specifies the name of the desired
service. Ex. ``sqs``, ``sns``, ``dynamodb``, etc.
:type service_name: string
... | [
"def",
"get_resource",
"(",
"self",
",",
"service_name",
",",
"resource_name",
",",
"base_class",
"=",
"None",
")",
":",
"try",
":",
"return",
"self",
".",
"cache",
".",
"get_resource",
"(",
"service_name",
",",
"resource_name",
",",
"base_class",
"=",
"base... | 35.142857 | 0.001582 |
def validate(cls, state):
"""Validate state value."""
return state in [cls.ACTIVE, cls.PENDING_ADMIN, cls.PENDING_USER] | [
"def",
"validate",
"(",
"cls",
",",
"state",
")",
":",
"return",
"state",
"in",
"[",
"cls",
".",
"ACTIVE",
",",
"cls",
".",
"PENDING_ADMIN",
",",
"cls",
".",
"PENDING_USER",
"]"
] | 44.333333 | 0.014815 |
def SURFstar_compute_scores(inst, attr, nan_entries, num_attributes, mcmap, NN_near, NN_far, headers, class_type, X, y, labels_std, data_type):
""" Unique scoring procedure for SURFstar algorithm. Scoring based on nearest neighbors within defined radius, as well as
'anti-scoring' of far instances outside of r... | [
"def",
"SURFstar_compute_scores",
"(",
"inst",
",",
"attr",
",",
"nan_entries",
",",
"num_attributes",
",",
"mcmap",
",",
"NN_near",
",",
"NN_far",
",",
"headers",
",",
"class_type",
",",
"X",
",",
"y",
",",
"labels_std",
",",
"data_type",
")",
":",
"score... | 81.461538 | 0.008403 |
def emit(self, op_code, *args):
''' Adds op_code with specified args to tape '''
self.tape.append(OP_CODES[op_code](*args)) | [
"def",
"emit",
"(",
"self",
",",
"op_code",
",",
"*",
"args",
")",
":",
"self",
".",
"tape",
".",
"append",
"(",
"OP_CODES",
"[",
"op_code",
"]",
"(",
"*",
"args",
")",
")"
] | 45.666667 | 0.014388 |
def _get_keys(self, read, input_records):
"""
Generator that yields `KeyPress` objects from the input records.
"""
for i in range(read.value):
ir = input_records[i]
# Get the right EventType from the EVENT_RECORD.
# (For some reason the Windows consol... | [
"def",
"_get_keys",
"(",
"self",
",",
"read",
",",
"input_records",
")",
":",
"for",
"i",
"in",
"range",
"(",
"read",
".",
"value",
")",
":",
"ir",
"=",
"input_records",
"[",
"i",
"]",
"# Get the right EventType from the EVENT_RECORD.",
"# (For some reason the W... | 43.086957 | 0.001974 |
def check_bewit(url, credential_lookup, now=None):
"""
Validates the given bewit.
Returns True if the resource has a valid bewit parameter attached,
or raises a subclass of HawkFail otherwise.
:param credential_lookup:
Callable to look up the credentials dict by sender ID.
The cred... | [
"def",
"check_bewit",
"(",
"url",
",",
"credential_lookup",
",",
"now",
"=",
"None",
")",
":",
"raw_bewit",
",",
"stripped_url",
"=",
"strip_bewit",
"(",
"url",
")",
"bewit",
"=",
"parse_bewit",
"(",
"raw_bewit",
")",
"try",
":",
"credentials",
"=",
"crede... | 36.839286 | 0.000944 |
def with_unit(number, unit=None):
""" Return number with unit
args:
number (mixed): Number
unit (str): Unit
returns:
str
"""
if isinstance(number, tuple):
number, unit = number
if number == 0:
return '0'
if unit:
number = str(number)
if... | [
"def",
"with_unit",
"(",
"number",
",",
"unit",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"number",
",",
"tuple",
")",
":",
"number",
",",
"unit",
"=",
"number",
"if",
"number",
"==",
"0",
":",
"return",
"'0'",
"if",
"unit",
":",
"number",
"=... | 26.166667 | 0.002049 |
def split(pred, iterable, *, trailing=True):
"""Split the iterable.
Arguments
----------
pred : function
A function that accepts an element retrieved from the iterable
and returns a boolean indicating if it is the element on which
to split
iterable :... | [
"def",
"split",
"(",
"pred",
",",
"iterable",
",",
"*",
",",
"trailing",
"=",
"True",
")",
":",
"result",
"=",
"[",
"]",
"result_append",
"=",
"result",
".",
"append",
"if",
"trailing",
":",
"for",
"elem",
"in",
"iterable",
":",
"result_append",
"(",
... | 32.266667 | 0.000668 |
def add_location_reminder(self, service, name, lat, long, trigger, radius):
"""Add a reminder to the task which activates on at a given location.
.. warning:: Requires Todoist premium.
:param service: ```email```, ```sms``` or ```push``` for mobile.
:type service: str
:param na... | [
"def",
"add_location_reminder",
"(",
"self",
",",
"service",
",",
"name",
",",
"lat",
",",
"long",
",",
"trigger",
",",
"radius",
")",
":",
"args",
"=",
"{",
"'item_id'",
":",
"self",
".",
"id",
",",
"'service'",
":",
"service",
",",
"'type'",
":",
"... | 38.189189 | 0.00138 |
def QueryService(svc_name):
"""Query service and get its config."""
hscm = win32service.OpenSCManager(None, None,
win32service.SC_MANAGER_ALL_ACCESS)
result = None
try:
hs = win32serviceutil.SmartOpenService(hscm, svc_name,
win32... | [
"def",
"QueryService",
"(",
"svc_name",
")",
":",
"hscm",
"=",
"win32service",
".",
"OpenSCManager",
"(",
"None",
",",
"None",
",",
"win32service",
".",
"SC_MANAGER_ALL_ACCESS",
")",
"result",
"=",
"None",
"try",
":",
"hs",
"=",
"win32serviceutil",
".",
"Sma... | 35.214286 | 0.013834 |
def from_records(cls, records):
"""Create a table from a sequence of records (dicts with fixed keys)."""
if not records:
return cls()
labels = sorted(list(records[0].keys()))
columns = [[rec[label] for rec in records] for label in labels]
return cls().with_columns(zip... | [
"def",
"from_records",
"(",
"cls",
",",
"records",
")",
":",
"if",
"not",
"records",
":",
"return",
"cls",
"(",
")",
"labels",
"=",
"sorted",
"(",
"list",
"(",
"records",
"[",
"0",
"]",
".",
"keys",
"(",
")",
")",
")",
"columns",
"=",
"[",
"[",
... | 47.428571 | 0.008876 |
def get(self, key):
"""Gets a value by a key.
Args:
key (str): Key to retrieve the value.
Returns: Retrieved value.
"""
self._create_file_if_none_exists()
with open(self.filename, 'rb') as file_object:
cache_pickle = pickle.load(file_object)
val = cache_pickle.get(key, None)
... | [
"def",
"get",
"(",
"self",
",",
"key",
")",
":",
"self",
".",
"_create_file_if_none_exists",
"(",
")",
"with",
"open",
"(",
"self",
".",
"filename",
",",
"'rb'",
")",
"as",
"file_object",
":",
"cache_pickle",
"=",
"pickle",
".",
"load",
"(",
"file_object... | 24.923077 | 0.011905 |
def get(self):
"""
:return: response stats dict
"""
stats = {}
if self.start_date is not None:
stats["start_date"] = self.start_date
if self.end_date is not None:
stats["end_date"] = self.end_date
if self.aggregated_by is not None:
... | [
"def",
"get",
"(",
"self",
")",
":",
"stats",
"=",
"{",
"}",
"if",
"self",
".",
"start_date",
"is",
"not",
"None",
":",
"stats",
"[",
"\"start_date\"",
"]",
"=",
"self",
".",
"start_date",
"if",
"self",
".",
"end_date",
"is",
"not",
"None",
":",
"s... | 38.695652 | 0.002193 |
def atomic(self, func):
"""A decorator that wraps a function in an atomic block.
Example::
db = CustomSQLAlchemy()
@db.atomic
def f():
write_to_db('a message')
return 'OK'
assert f() == 'OK'
This code defines the function `... | [
"def",
"atomic",
"(",
"self",
",",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"session",
"=",
"self",
".",
"session",
"session_info",
"=",
"session",
".",
"info",
"if",
... | 33.052632 | 0.001031 |
def subscribe(self, destination, id, ack='auto', headers=None, **keyword_headers):
"""
:param str destination:
:param str id:
:param str ack:
:param dict headers:
:param keyword_headers:
"""
self.transport.subscriptions[id] = destination | [
"def",
"subscribe",
"(",
"self",
",",
"destination",
",",
"id",
",",
"ack",
"=",
"'auto'",
",",
"headers",
"=",
"None",
",",
"*",
"*",
"keyword_headers",
")",
":",
"self",
".",
"transport",
".",
"subscriptions",
"[",
"id",
"]",
"=",
"destination"
] | 32.555556 | 0.009967 |
def validate(opts):
"""
Client-facing validate method. Checks to see if the passed in opts
argument is either a list or a namespace containing the attribute
'extensions' and runs validations on it accordingly. If opts is neither
of those things, this will raise a ValueError
:param opts: either ... | [
"def",
"validate",
"(",
"opts",
")",
":",
"if",
"hasattr",
"(",
"opts",
",",
"'extensions'",
")",
":",
"return",
"_validate",
"(",
"opts",
".",
"extensions",
")",
"elif",
"isinstance",
"(",
"opts",
",",
"list",
")",
":",
"return",
"_validate",
"(",
"op... | 44.227273 | 0.001006 |
def dnet(dd, dm, zhm, xmm, xm):
'''
/* TURBOPAUSE CORRECTION FOR MSIS MODELS
* Root mean density
* DD - diffusive density
* DM - full mixed density
* ZHM - transition scale length
* XMM - full mixed molecular weight
* XM - species molecular weight
* ... | [
"def",
"dnet",
"(",
"dd",
",",
"dm",
",",
"zhm",
",",
"xmm",
",",
"xm",
")",
":",
"a",
"=",
"zhm",
"/",
"(",
"xmm",
"-",
"xm",
")",
"if",
"(",
"not",
"(",
"(",
"dm",
">",
"0",
")",
"and",
"(",
"dd",
">",
"0",
")",
")",
")",
":",
"# pr... | 25.5 | 0.018893 |
def _get_sub_prop(self, key, default=None):
"""Get a value in the ``self._properties[self._job_type]`` dictionary.
Most job properties are inside the dictionary related to the job type
(e.g. 'copy', 'extract', 'load', 'query'). Use this method to access
those properties::
s... | [
"def",
"_get_sub_prop",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
")",
":",
"return",
"_helpers",
".",
"_get_sub_prop",
"(",
"self",
".",
"_properties",
",",
"[",
"self",
".",
"_job_type",
",",
"key",
"]",
",",
"default",
"=",
"default",
")... | 36.5 | 0.001907 |
def cmd_fw_list(self, args):
'''cmd handler for list'''
stuff = self.filtered_rows_from_args(args)
if stuff is None:
return
(filtered, remainder) = stuff
print("")
print(" seq platform frame major.minor.patch releasetype latest git-sha format")
for ... | [
"def",
"cmd_fw_list",
"(",
"self",
",",
"args",
")",
":",
"stuff",
"=",
"self",
".",
"filtered_rows_from_args",
"(",
"args",
")",
"if",
"stuff",
"is",
"None",
":",
"return",
"(",
"filtered",
",",
"remainder",
")",
"=",
"stuff",
"print",
"(",
"\"\"",
")... | 46 | 0.008529 |
def inventory(self):
"""
Create an inventory structure and returns a dict.
.. code-block:: yaml
ungrouped:
vars:
foo: bar
hosts:
instance-1:
instance-2:
children:
$child_group_n... | [
"def",
"inventory",
"(",
"self",
")",
":",
"dd",
"=",
"self",
".",
"_vivify",
"(",
")",
"for",
"platform",
"in",
"self",
".",
"_config",
".",
"platforms",
".",
"instances",
":",
"for",
"group",
"in",
"platform",
".",
"get",
"(",
"'groups'",
",",
"[",... | 38.466667 | 0.000845 |
def concat(objs, dim=None, data_vars='all', coords='different',
compat='equals', positions=None, indexers=None, mode=None,
concat_over=None):
"""Concatenate xarray objects along a new or existing dimension.
Parameters
----------
objs : sequence of Dataset and DataArray objects
... | [
"def",
"concat",
"(",
"objs",
",",
"dim",
"=",
"None",
",",
"data_vars",
"=",
"'all'",
",",
"coords",
"=",
"'different'",
",",
"compat",
"=",
"'equals'",
",",
"positions",
"=",
"None",
",",
"indexers",
"=",
"None",
",",
"mode",
"=",
"None",
",",
"con... | 48.349057 | 0.000191 |
def render(self, parsed, page=False, minify=False):
"""Render complete markup.
parsed (list): Dependency parses to render.
page (bool): Render parses wrapped as full HTML page.
minify (bool): Minify HTML markup.
RETURNS (unicode): Rendered SVG or HTML markup.
"""
... | [
"def",
"render",
"(",
"self",
",",
"parsed",
",",
"page",
"=",
"False",
",",
"minify",
"=",
"False",
")",
":",
"# Create a random ID prefix to make sure parses don't receive the",
"# same ID, even if they're identical",
"id_prefix",
"=",
"uuid",
".",
"uuid4",
"(",
")"... | 40.5 | 0.002412 |
def get_members(self, show=True, proxy=None, timeout=0):
"""
GET Mediawiki:API (action=query) category members
https://www.mediawiki.org/wiki/API:Categorymembers
Required {params}: title OR pageid
- title: <str> article title
- pageid: <int> Wikipedia database ID
... | [
"def",
"get_members",
"(",
"self",
",",
"show",
"=",
"True",
",",
"proxy",
"=",
"None",
",",
"timeout",
"=",
"0",
")",
":",
"title",
"=",
"self",
".",
"params",
".",
"get",
"(",
"'title'",
")",
"pageid",
"=",
"self",
".",
"params",
".",
"get",
"(... | 32 | 0.002092 |
def native(self, value, context=None):
"""Convert a value from a foriegn type (i.e. web-safe) to Python-native."""
if self.strip and hasattr(value, 'strip'):
value = value.strip()
if self.none and value == '':
return None
if self.encoding and isinstance(value, bytes):
return value.decode(self.... | [
"def",
"native",
"(",
"self",
",",
"value",
",",
"context",
"=",
"None",
")",
":",
"if",
"self",
".",
"strip",
"and",
"hasattr",
"(",
"value",
",",
"'strip'",
")",
":",
"value",
"=",
"value",
".",
"strip",
"(",
")",
"if",
"self",
".",
"none",
"an... | 25.769231 | 0.051873 |
def create_stream(self, stream_id, sandbox=None):
"""
Must be overridden by deriving classes, must create the stream according to the tool and return its unique
identifier stream_id
"""
if stream_id in self.streams:
raise StreamAlreadyExistsError("Stream with id '{}' ... | [
"def",
"create_stream",
"(",
"self",
",",
"stream_id",
",",
"sandbox",
"=",
"None",
")",
":",
"if",
"stream_id",
"in",
"self",
".",
"streams",
":",
"raise",
"StreamAlreadyExistsError",
"(",
"\"Stream with id '{}' already exists\"",
".",
"format",
"(",
"stream_id",... | 42.25 | 0.008683 |
def groupmember_get(self, manager_id, session):
'''taobao.wangwang.eservice.groupmember.get 获取组成员列表
用某个组管理员账号查询,返回该组组名、和该组所有组成员ID(E客服的分流设置)。 用旺旺主帐号查询,返回所有组的组名和该组所有组成员ID。 返回的组成员ID可以是多个,用 "," 隔开。 被查者ID只能传入一个。 组成员中排名最靠前的ID是组管理员ID'''
request = TOPRequest('taobao.wangwang.eservice.groupmembe... | [
"def",
"groupmember_get",
"(",
"self",
",",
"manager_id",
",",
"session",
")",
":",
"request",
"=",
"TOPRequest",
"(",
"'taobao.wangwang.eservice.groupmember.get'",
")",
"request",
"[",
"'manager_id'",
"]",
"=",
"manager_id",
"self",
".",
"create",
"(",
"self",
... | 56.625 | 0.008696 |
def get_uuid_string(low=None, high=None, **x):
"""This method parses a UUID protobuf message type from its component
'high' and 'low' longs into a standard formatted UUID string
Args:
x (dict): containing keys, 'low' and 'high' corresponding to the UUID
protobuf message type
Return... | [
"def",
"get_uuid_string",
"(",
"low",
"=",
"None",
",",
"high",
"=",
"None",
",",
"*",
"*",
"x",
")",
":",
"if",
"low",
"is",
"None",
"or",
"high",
"is",
"None",
":",
"return",
"None",
"x",
"=",
"''",
".",
"join",
"(",
"[",
"parse_part",
"(",
"... | 35.2 | 0.001845 |
def from_secret_type(secret_type, settings):
"""
Note: Only called from audit.py
:type secret_type: str
:param secret_type: unique identifier for plugin type
:type settings: list
:param settings: output of "plugins_used" in baseline. e.g.
>>> [
... {
... 'na... | [
"def",
"from_secret_type",
"(",
"secret_type",
",",
"settings",
")",
":",
"mapping",
"=",
"_get_mapping_from_secret_type_to_class_name",
"(",
")",
"try",
":",
"classname",
"=",
"mapping",
"[",
"secret_type",
"]",
"except",
"KeyError",
":",
"return",
"None",
"for",... | 26.709677 | 0.001166 |
def configuration(parent_package='', top_path=None):
"""Configure all packages that need to be built."""
config = Configuration('', parent_package, top_path)
F95FLAGS = get_compiler_flags()
kwargs = {
'libraries': [],
'include_dirs': [],
'library_dirs': [],
}
kwargs['ex... | [
"def",
"configuration",
"(",
"parent_package",
"=",
"''",
",",
"top_path",
"=",
"None",
")",
":",
"config",
"=",
"Configuration",
"(",
"''",
",",
"parent_package",
",",
"top_path",
")",
"F95FLAGS",
"=",
"get_compiler_flags",
"(",
")",
"kwargs",
"=",
"{",
"... | 33.90625 | 0.000448 |
def set_list_predicates(self):
"""
Reads through the rml mappings and determines all fields that should
map to a list/array with a json output
"""
results = self.rml.query("""
SELECT DISTINCT ?subj_class ?list_field
{
?bn rr:dat... | [
"def",
"set_list_predicates",
"(",
"self",
")",
":",
"results",
"=",
"self",
".",
"rml",
".",
"query",
"(",
"\"\"\"\n SELECT DISTINCT ?subj_class ?list_field\n {\n ?bn rr:datatype rdf:List .\n ?bn rr:predicate ?list_fiel... | 37.565217 | 0.002257 |
def get_namelist():
"""Generate namelist.
Either through set CONF.zvm.namelist, or by generate based on smt userid.
"""
if CONF.zvm.namelist is not None:
# namelist length limit should be 64, but there's bug limit to 8
# will change the limit to 8 once the bug fixed
if len(CONF.... | [
"def",
"get_namelist",
"(",
")",
":",
"if",
"CONF",
".",
"zvm",
".",
"namelist",
"is",
"not",
"None",
":",
"# namelist length limit should be 64, but there's bug limit to 8",
"# will change the limit to 8 once the bug fixed",
"if",
"len",
"(",
"CONF",
".",
"zvm",
".",
... | 35.466667 | 0.001832 |
def refresh(self):
"""
explicitely refresh user interface; useful when changing widgets dynamically
"""
logger.debug("refresh user interface")
try:
with self.refresh_lock:
self.draw_screen()
except AssertionError:
logger.warning("ap... | [
"def",
"refresh",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"\"refresh user interface\"",
")",
"try",
":",
"with",
"self",
".",
"refresh_lock",
":",
"self",
".",
"draw_screen",
"(",
")",
"except",
"AssertionError",
":",
"logger",
".",
"warning",
... | 32.090909 | 0.008264 |
def cpmaximum(image, structure=np.ones((3,3),dtype=bool),offset=None):
"""Find the local maximum at each point in the image, using the given structuring element
image - a 2-d array of doubles
structure - a boolean structuring element indicating which
local elements should be sampled
... | [
"def",
"cpmaximum",
"(",
"image",
",",
"structure",
"=",
"np",
".",
"ones",
"(",
"(",
"3",
",",
"3",
")",
",",
"dtype",
"=",
"bool",
")",
",",
"offset",
"=",
"None",
")",
":",
"center",
"=",
"np",
".",
"array",
"(",
"structure",
".",
"shape",
"... | 46.428571 | 0.00905 |
def union(self, *iterables):
"""
Return a new SortedSet with elements from the set and all *iterables*.
"""
return self.__class__(chain(iter(self), *iterables), key=self._key) | [
"def",
"union",
"(",
"self",
",",
"*",
"iterables",
")",
":",
"return",
"self",
".",
"__class__",
"(",
"chain",
"(",
"iter",
"(",
"self",
")",
",",
"*",
"iterables",
")",
",",
"key",
"=",
"self",
".",
"_key",
")"
] | 40.6 | 0.009662 |
def vm_absent(name, archive=False):
'''
Ensure vm is absent on the computenode
name : string
hostname of vm
archive : boolean
toggle archiving of vm on removal
.. note::
State ID is used as hostname. Hostnames must be unique.
'''
name = name.lower()
ret = {'na... | [
"def",
"vm_absent",
"(",
"name",
",",
"archive",
"=",
"False",
")",
":",
"name",
"=",
"name",
".",
"lower",
"(",
")",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"None",
",",
"'comment'",
":",
"'... | 27.697674 | 0.001622 |
def write(self, *messages):
"""Push a list of messages in the inputs of this graph's inputs, matching the output of special node "BEGIN" in
our graph."""
for i in self.graph.outputs_of(BEGIN):
for message in messages:
self[i].write(message) | [
"def",
"write",
"(",
"self",
",",
"*",
"messages",
")",
":",
"for",
"i",
"in",
"self",
".",
"graph",
".",
"outputs_of",
"(",
"BEGIN",
")",
":",
"for",
"message",
"in",
"messages",
":",
"self",
"[",
"i",
"]",
".",
"write",
"(",
"message",
")"
] | 41 | 0.010239 |
def _update_functions(self):
"""
Uses internal settings to update the functions.
"""
self.f = []
self.bg = []
self._fnames = []
self._bgnames = []
self._odr_models = [] # Like f, but different parameters, for use in ODR... | [
"def",
"_update_functions",
"(",
"self",
")",
":",
"self",
".",
"f",
"=",
"[",
"]",
"self",
".",
"bg",
"=",
"[",
"]",
"self",
".",
"_fnames",
"=",
"[",
"]",
"self",
".",
"_bgnames",
"=",
"[",
"]",
"self",
".",
"_odr_models",
"=",
"[",
"]",
"# L... | 38.90625 | 0.012534 |
def is_native_ion_gate(gate: ops.Gate) -> bool:
"""Check if a gate is a native ion gate.
Args:
gate: Input gate.
Returns:
True if the gate is native to the ion, false otherwise.
"""
return isinstance(gate, (ops.XXPowGate,
ops.MeasurementGate,
... | [
"def",
"is_native_ion_gate",
"(",
"gate",
":",
"ops",
".",
"Gate",
")",
"->",
"bool",
":",
"return",
"isinstance",
"(",
"gate",
",",
"(",
"ops",
".",
"XXPowGate",
",",
"ops",
".",
"MeasurementGate",
",",
"ops",
".",
"XPowGate",
",",
"ops",
".",
"YPowGa... | 30.428571 | 0.002278 |
def calculate(self, scene, xaxis, yaxis):
"""
Calculates the grid data before rendering.
:param scene | <XChartScene>
xaxis | <XChartAxis>
yaxis | <XChartAxis>
"""
# build the grid location
s... | [
"def",
"calculate",
"(",
"self",
",",
"scene",
",",
"xaxis",
",",
"yaxis",
")",
":",
"# build the grid location\r",
"sceneRect",
"=",
"scene",
".",
"sceneRect",
"(",
")",
"# process axis information\r",
"h_lines",
"=",
"[",
"]",
"h_alt",
"=",
"[",
"]",
"h_la... | 34.627119 | 0.011182 |
def _parse_pricing(url, name):
'''
Download and parse an individual pricing file from AWS
.. versionadded:: 2015.8.0
'''
price_js = http.query(url, text=True)
items = []
current_item = ''
price_js = re.sub(JS_COMMENT_RE, '', price_js['text'])
price_js = price_js.strip().rstrip(');... | [
"def",
"_parse_pricing",
"(",
"url",
",",
"name",
")",
":",
"price_js",
"=",
"http",
".",
"query",
"(",
"url",
",",
"text",
"=",
"True",
")",
"items",
"=",
"[",
"]",
"current_item",
"=",
"''",
"price_js",
"=",
"re",
".",
"sub",
"(",
"JS_COMMENT_RE",
... | 27.611111 | 0.001295 |
def calculate(self, T, method):
r'''Method to calculate low-pressure liquid thermal conductivity at
tempearture `T` with a given method.
This method has no exception handling; see `T_dependent_property`
for that.
Parameters
----------
T : float
Tempe... | [
"def",
"calculate",
"(",
"self",
",",
"T",
",",
"method",
")",
":",
"if",
"method",
"==",
"SHEFFY_JOHNSON",
":",
"kl",
"=",
"Sheffy_Johnson",
"(",
"T",
",",
"self",
".",
"MW",
",",
"self",
".",
"Tm",
")",
"elif",
"method",
"==",
"SATO_RIEDEL",
":",
... | 37.333333 | 0.001243 |
def open(self, mode='rb'):
"""Open file.
The caller is responsible for closing the file.
"""
fs, path = self._get_fs()
return fs.open(path, mode=mode) | [
"def",
"open",
"(",
"self",
",",
"mode",
"=",
"'rb'",
")",
":",
"fs",
",",
"path",
"=",
"self",
".",
"_get_fs",
"(",
")",
"return",
"fs",
".",
"open",
"(",
"path",
",",
"mode",
"=",
"mode",
")"
] | 26.428571 | 0.010471 |
def get_statistics(prefix=''):
"""
Get statistics for message codes that start with the prefix.
prefix='' matches all errors and warnings
prefix='E' matches all errors
prefix='W' matches all warnings
prefix='E4' matches all errors that have to do with imports
"""
stats = []
keys = o... | [
"def",
"get_statistics",
"(",
"prefix",
"=",
"''",
")",
":",
"stats",
"=",
"[",
"]",
"keys",
"=",
"options",
".",
"messages",
".",
"keys",
"(",
")",
"keys",
".",
"sort",
"(",
")",
"for",
"key",
"in",
"keys",
":",
"if",
"key",
".",
"startswith",
"... | 31.352941 | 0.001821 |
def translate(self, term=None, phrase=None, strict=False, rating=None):
"""
Retrieve a single image that represents a transalation of a term or
phrase into an animated gif. Punctuation is ignored. By default, this
will perform a `term` translation. If you want to translate by phrase,
... | [
"def",
"translate",
"(",
"self",
",",
"term",
"=",
"None",
",",
"phrase",
"=",
"None",
",",
"strict",
"=",
"False",
",",
"rating",
"=",
"None",
")",
":",
"assert",
"any",
"(",
"(",
"term",
",",
"phrase",
")",
")",
",",
"'You must supply a term or phras... | 40.34375 | 0.002269 |
def webhook_handler(*event_types):
"""
Decorator that registers a function as a webhook handler.
Usage examples:
>>> # Hook a single event
>>> @webhook_handler("payment.sale.completed")
>>> def on_payment_received(event):
>>> payment = event.get_resource()
>>> print("Received payment:", payment)
>>>... | [
"def",
"webhook_handler",
"(",
"*",
"event_types",
")",
":",
"# First expand all wildcards and verify the event types are valid",
"event_types_to_register",
"=",
"set",
"(",
")",
"for",
"event_type",
"in",
"event_types",
":",
"# Always convert to lowercase",
"event_type",
"="... | 30.361702 | 0.027834 |
def overlap(args):
"""
%prog overlap ctgfasta poolfasta
Fish out the sequences in `poolfasta` that overlap with `ctgfasta`.
Mix and combine using `minimus2`.
"""
p = OptionParser(overlap.__doc__)
opts, args = p.parse_args(args)
if len(args) != 2:
sys.exit(not p.print_help())
... | [
"def",
"overlap",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"overlap",
".",
"__doc__",
")",
"opts",
",",
"args",
"=",
"p",
".",
"parse_args",
"(",
"args",
")",
"if",
"len",
"(",
"args",
")",
"!=",
"2",
":",
"sys",
".",
"exit",
"(",
... | 32.793103 | 0.002297 |
def supported(self, tags=None):
# type: (Optional[List[Pep425Tag]]) -> bool
"""Is this wheel supported on this system?"""
if tags is None: # for mock
tags = pep425tags.get_supported()
return bool(set(tags).intersection(self.file_tags)) | [
"def",
"supported",
"(",
"self",
",",
"tags",
"=",
"None",
")",
":",
"# type: (Optional[List[Pep425Tag]]) -> bool",
"if",
"tags",
"is",
"None",
":",
"# for mock",
"tags",
"=",
"pep425tags",
".",
"get_supported",
"(",
")",
"return",
"bool",
"(",
"set",
"(",
"... | 45.833333 | 0.010714 |
def initialize_users(self) -> None:
"""Load device user data and initialize user management."""
users = self.request('get', pwdgrp_url)
self.users = Users(users, self.request) | [
"def",
"initialize_users",
"(",
"self",
")",
"->",
"None",
":",
"users",
"=",
"self",
".",
"request",
"(",
"'get'",
",",
"pwdgrp_url",
")",
"self",
".",
"users",
"=",
"Users",
"(",
"users",
",",
"self",
".",
"request",
")"
] | 49 | 0.01005 |
def b1_noise_id(x, af, rate):
""" B1 ratio for noise identification
ratio of Standard Variace to AVAR
"""
(taus,devs,errs,ns) = at.adev(x,taus=[af*rate],data_type="phase", rate=rate)
oadev_x = devs[0]
y = np.diff(x)
y_cut = np.array( y[:len(y)-(len(y)%af)] ) # cut to length
ass... | [
"def",
"b1_noise_id",
"(",
"x",
",",
"af",
",",
"rate",
")",
":",
"(",
"taus",
",",
"devs",
",",
"errs",
",",
"ns",
")",
"=",
"at",
".",
"adev",
"(",
"x",
",",
"taus",
"=",
"[",
"af",
"*",
"rate",
"]",
",",
"data_type",
"=",
"\"phase\"",
",",... | 34.6 | 0.0394 |
def copy_value(self, orig_name, new_name):
"""Copy value"""
self.shellwidget.copy_value(orig_name, new_name)
self.shellwidget.refresh_namespacebrowser() | [
"def",
"copy_value",
"(",
"self",
",",
"orig_name",
",",
"new_name",
")",
":",
"self",
".",
"shellwidget",
".",
"copy_value",
"(",
"orig_name",
",",
"new_name",
")",
"self",
".",
"shellwidget",
".",
"refresh_namespacebrowser",
"(",
")"
] | 44 | 0.011173 |
def pull(options):
"""
pull all remote programs to a local directory
"""
configuration = config.get_default()
app_url = configuration['app_url']
if options.deployment != None:
deployment_name = options.deployment
else:
deployment_name = configuration['deployment_name']
... | [
"def",
"pull",
"(",
"options",
")",
":",
"configuration",
"=",
"config",
".",
"get_default",
"(",
")",
"app_url",
"=",
"configuration",
"[",
"'app_url'",
"]",
"if",
"options",
".",
"deployment",
"!=",
"None",
":",
"deployment_name",
"=",
"options",
".",
"d... | 37.702703 | 0.001863 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.