text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def commitVersion(self, spec):
''' return a GithubComponentVersion object for a specific commit if valid
'''
import re
commit_match = re.match('^[a-f0-9]{7,40}$', spec, re.I)
if commit_match:
return GitCloneVersion('', spec, self)
return None | [
"def",
"commitVersion",
"(",
"self",
",",
"spec",
")",
":",
"import",
"re",
"commit_match",
"=",
"re",
".",
"match",
"(",
"'^[a-f0-9]{7,40}$'",
",",
"spec",
",",
"re",
".",
"I",
")",
"if",
"commit_match",
":",
"return",
"GitCloneVersion",
"(",
"''",
",",... | 29.5 | 0.009868 |
def _extract_buffers(obj, threshold=MAX_BYTES):
"""Extract buffers larger than a certain threshold."""
buffers = []
if isinstance(obj, CannedObject) and obj.buffers:
for i, buf in enumerate(obj.buffers):
nbytes = _nbytes(buf)
if nbytes > threshold:
# buffer la... | [
"def",
"_extract_buffers",
"(",
"obj",
",",
"threshold",
"=",
"MAX_BYTES",
")",
":",
"buffers",
"=",
"[",
"]",
"if",
"isinstance",
"(",
"obj",
",",
"CannedObject",
")",
"and",
"obj",
".",
"buffers",
":",
"for",
"i",
",",
"buf",
"in",
"enumerate",
"(",
... | 44.529412 | 0.001294 |
def timing(self, stat, value, tags=None):
"""Measure a timing for statistical distribution.
Note: timing is a special case of histogram.
"""
self.histogram(stat, value, tags) | [
"def",
"timing",
"(",
"self",
",",
"stat",
",",
"value",
",",
"tags",
"=",
"None",
")",
":",
"self",
".",
"histogram",
"(",
"stat",
",",
"value",
",",
"tags",
")"
] | 28.857143 | 0.009615 |
def mnist_model(image, labels, mesh):
"""The model.
Args:
image: tf.Tensor with shape [batch, 28*28]
labels: a tf.Tensor with shape [batch] and dtype tf.int32
mesh: a mtf.Mesh
Returns:
logits: a mtf.Tensor with shape [batch, 10]
loss: a mtf.Tensor with shape []
"""
batch_dim = mtf.Dimens... | [
"def",
"mnist_model",
"(",
"image",
",",
"labels",
",",
"mesh",
")",
":",
"batch_dim",
"=",
"mtf",
".",
"Dimension",
"(",
"\"batch\"",
",",
"FLAGS",
".",
"batch_size",
")",
"row_blocks_dim",
"=",
"mtf",
".",
"Dimension",
"(",
"\"row_blocks\"",
",",
"4",
... | 36.086957 | 0.011728 |
def acos(x, context=None):
"""
Return the inverse cosine of ``x``.
The mathematically exact result lies in the range [0, π]. However, note
that as a result of rounding to the current context, it's possible for the
actual value returned to be fractionally larger than π::
>>> from bigfloat ... | [
"def",
"acos",
"(",
"x",
",",
"context",
"=",
"None",
")",
":",
"return",
"_apply_function_in_current_context",
"(",
"BigFloat",
",",
"mpfr",
".",
"mpfr_acos",
",",
"(",
"BigFloat",
".",
"_implicit_convert",
"(",
"x",
")",
",",
")",
",",
"context",
",",
... | 26.041667 | 0.001543 |
def rename_file(self, relativePath, newRelativePath,
force=False, raiseError=True, ntrials=3):
"""
Rename a file in the repository. It insures renaming the file in the system.
:Parameters:
#. relativePath (string): The relative to the repository path of
... | [
"def",
"rename_file",
"(",
"self",
",",
"relativePath",
",",
"newRelativePath",
",",
"force",
"=",
"False",
",",
"raiseError",
"=",
"True",
",",
"ntrials",
"=",
"3",
")",
":",
"assert",
"isinstance",
"(",
"raiseError",
",",
"bool",
")",
",",
"\"raiseError ... | 53.55 | 0.011917 |
def get_init_file(dir):
# type: (str) -> Optional[str]
"""Check whether a directory contains a file named __init__.py[i].
If so, return the file's name (with dir prefixed). If not, return
None.
This prefers .pyi over .py (because of the ordering of PY_EXTENSIONS).
"""
for ext in PY_EXTENSIO... | [
"def",
"get_init_file",
"(",
"dir",
")",
":",
"# type: (str) -> Optional[str]",
"for",
"ext",
"in",
"PY_EXTENSIONS",
":",
"f",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dir",
",",
"'__init__'",
"+",
"ext",
")",
"if",
"os",
".",
"path",
".",
"isfile",
... | 35.583333 | 0.002283 |
def generate_dataset(number_items=1000):
"""
Generate a dataset with number_items elements.
"""
data = []
names = get_names()
totalnames = len(names)
#init random seeder
random.seed()
#calculate items
# names = random.sample(names, number_items)
for i in range(number_items):
... | [
"def",
"generate_dataset",
"(",
"number_items",
"=",
"1000",
")",
":",
"data",
"=",
"[",
"]",
"names",
"=",
"get_names",
"(",
")",
"totalnames",
"=",
"len",
"(",
"names",
")",
"#init random seeder",
"random",
".",
"seed",
"(",
")",
"#calculate items",
"# ... | 30.8125 | 0.015748 |
def get_unique_variable(name):
"""Gets the variable uniquely identified by that name.
Args:
name: a name that uniquely identifies the variable.
Returns:
a tensorflow variable.
Raises:
ValueError: if no variable uniquely identified by the name exists.
"""
candidates = tf.get_collection(tf.Grap... | [
"def",
"get_unique_variable",
"(",
"name",
")",
":",
"candidates",
"=",
"tf",
".",
"get_collection",
"(",
"tf",
".",
"GraphKeys",
".",
"GLOBAL_VARIABLES",
",",
"name",
")",
"if",
"not",
"candidates",
":",
"raise",
"ValueError",
"(",
"'Couldnt find variable %s'",... | 28.7 | 0.011804 |
def get_placeholder(self, value=None, compiler=None, connection=None):
"""Tell postgres to encrypt this field using PGP."""
return self.encrypt_sql.format(get_setting(connection, 'PUBLIC_PGP_KEY')) | [
"def",
"get_placeholder",
"(",
"self",
",",
"value",
"=",
"None",
",",
"compiler",
"=",
"None",
",",
"connection",
"=",
"None",
")",
":",
"return",
"self",
".",
"encrypt_sql",
".",
"format",
"(",
"get_setting",
"(",
"connection",
",",
"'PUBLIC_PGP_KEY'",
"... | 70.333333 | 0.014085 |
def restore_layout(self, name, *args):
"""
Restores given layout.
:param name: Layout name.
:type name: unicode
:param \*args: Arguments.
:type \*args: \*
:return: Method success.
:rtype: bool
"""
layout = self.__layouts.get(name)
... | [
"def",
"restore_layout",
"(",
"self",
",",
"name",
",",
"*",
"args",
")",
":",
"layout",
"=",
"self",
".",
"__layouts",
".",
"get",
"(",
"name",
")",
"if",
"not",
"layout",
":",
"raise",
"umbra",
".",
"exceptions",
".",
"LayoutExistError",
"(",
"\"{0} ... | 41.352941 | 0.008339 |
def detect(self, text):
"""Decide which language is used to write the text.
The method tries first to detect the language with high reliability. If
that is not possible, the method switches to best effort strategy.
Args:
text (string): A snippet of text, the longer it is the more reliable we
... | [
"def",
"detect",
"(",
"self",
",",
"text",
")",
":",
"t",
"=",
"text",
".",
"encode",
"(",
"\"utf-8\"",
")",
"reliable",
",",
"index",
",",
"top_3_choices",
"=",
"cld2",
".",
"detect",
"(",
"t",
",",
"bestEffort",
"=",
"False",
")",
"if",
"not",
"r... | 34.62963 | 0.008325 |
def _send_command(self, cmd, expect=None):
"""Send a command to MPlayer.
cmd: the command string
expect: expect the output starts with a certain string
The result, if any, is returned as a string.
"""
if not self.is_alive:
raise NotPlayingError()
logg... | [
"def",
"_send_command",
"(",
"self",
",",
"cmd",
",",
"expect",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"is_alive",
":",
"raise",
"NotPlayingError",
"(",
")",
"logger",
".",
"debug",
"(",
"\"Send command to mplayer: \"",
"+",
"cmd",
")",
"cmd",
... | 40.194444 | 0.00135 |
def init_logging(name, level=logging.INFO):
"""Logging config
Set the level and create a more detailed formatter for debug mode.
"""
logger = logging.getLogger(name)
logger.setLevel(level)
try:
if os.isatty(sys.stdout.fileno()) and \
not sys.platform.startswith('win'):... | [
"def",
"init_logging",
"(",
"name",
",",
"level",
"=",
"logging",
".",
"INFO",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"name",
")",
"logger",
".",
"setLevel",
"(",
"level",
")",
"try",
":",
"if",
"os",
".",
"isatty",
"(",
"sys",
... | 30.916667 | 0.001307 |
def quadratic_2d(data):
"""
Compute the quadratic estimate of the centroid in a 2d-array.
Args:
data (2darray): two dimensional data array
Returns
center (tuple): centroid estimate on the row and column directions,
respectively
"""
arg_data_max = np.argm... | [
"def",
"quadratic_2d",
"(",
"data",
")",
":",
"arg_data_max",
"=",
"np",
".",
"argmax",
"(",
"data",
")",
"i",
",",
"j",
"=",
"np",
".",
"unravel_index",
"(",
"arg_data_max",
",",
"data",
".",
"shape",
")",
"z_",
"=",
"data",
"[",
"i",
"-",
"1",
... | 41.868421 | 0.029484 |
def update(self):
"""Update light objects to their current values."""
bulbs = self._hub.get_lights()
if not bulbs:
_LOGGER.debug("%s is offline, send command failed", self._zid)
self._online = False | [
"def",
"update",
"(",
"self",
")",
":",
"bulbs",
"=",
"self",
".",
"_hub",
".",
"get_lights",
"(",
")",
"if",
"not",
"bulbs",
":",
"_LOGGER",
".",
"debug",
"(",
"\"%s is offline, send command failed\"",
",",
"self",
".",
"_zid",
")",
"self",
".",
"_onlin... | 40.166667 | 0.00813 |
def archive(context, clear_log, items, path, name):
"""
Archive the history log and all results/log files.
After archive is created optionally clear the history log.
"""
history_log = context.obj['history_log']
no_color = context.obj['no_color']
with open(history_log, 'r') as f:
# ... | [
"def",
"archive",
"(",
"context",
",",
"clear_log",
",",
"items",
",",
"path",
",",
"name",
")",
":",
"history_log",
"=",
"context",
".",
"obj",
"[",
"'history_log'",
"]",
"no_color",
"=",
"context",
".",
"obj",
"[",
"'no_color'",
"]",
"with",
"open",
... | 31.607843 | 0.000602 |
def create_existing_file(help_string=NO_HELP, default=NO_DEFAULT, suffixes=None):
# type: (str, Union[str, NO_DEFAULT_TYPE], Union[List[str], None]) -> str
"""
Create a new file parameter
:param help_string:
:param default:
:param suffixes:
:return:
"""
... | [
"def",
"create_existing_file",
"(",
"help_string",
"=",
"NO_HELP",
",",
"default",
"=",
"NO_DEFAULT",
",",
"suffixes",
"=",
"None",
")",
":",
"# type: (str, Union[str, NO_DEFAULT_TYPE], Union[List[str], None]) -> str",
"# noinspection PyTypeChecker",
"return",
"ParamFilename",
... | 32.1875 | 0.009434 |
def refresh_model(self, model, *, overwrite=False):
"""Pulls the model's record from the database. If overwrite is True, the model values are
overwritten and returns the model, otherwise a new model instance with the newer record is
returned.
"""
new_model = self.find_model_by_id(model.__class__, mo... | [
"def",
"refresh_model",
"(",
"self",
",",
"model",
",",
"*",
",",
"overwrite",
"=",
"False",
")",
":",
"new_model",
"=",
"self",
".",
"find_model_by_id",
"(",
"model",
".",
"__class__",
",",
"model",
".",
"primary_key",
")",
"if",
"overwrite",
":",
"mode... | 42 | 0.012712 |
def logger(self):
"""uses "global logger" for logging"""
if self._logger:
return self._logger
else:
log_builder = p_logging.ProsperLogger(
self.PROGNAME,
self.config.get_option('LOGGING', 'log_path'),
config_obj=self.config
... | [
"def",
"logger",
"(",
"self",
")",
":",
"if",
"self",
".",
"_logger",
":",
"return",
"self",
".",
"_logger",
"else",
":",
"log_builder",
"=",
"p_logging",
".",
"ProsperLogger",
"(",
"self",
".",
"PROGNAME",
",",
"self",
".",
"config",
".",
"get_option",
... | 37.787879 | 0.001564 |
def do_connect(self):
"""发起连接"""
assert self.socket is None
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.connect(self._connect_address) | [
"def",
"do_connect",
"(",
"self",
")",
":",
"assert",
"self",
".",
"socket",
"is",
"None",
"self",
".",
"create_socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_STREAM",
")",
"self",
".",
"connect",
"(",
"self",
".",
"_connect_address",
... | 35.6 | 0.010989 |
def write_int(self, number):
""" Writes a integer to the underlying output file as a 4-byte value. """
buf = pack(self.byte_order + "i", number)
self.write(buf) | [
"def",
"write_int",
"(",
"self",
",",
"number",
")",
":",
"buf",
"=",
"pack",
"(",
"self",
".",
"byte_order",
"+",
"\"i\"",
",",
"number",
")",
"self",
".",
"write",
"(",
"buf",
")"
] | 45.25 | 0.016304 |
def _do_element(self, node, initial_other_attrs = [], unused = None):
'''_do_element(self, node, initial_other_attrs = [], unused = {}) -> None
Process an element (and its children).'''
# Get state (from the stack) make local copies.
# ns_parent -- NS declarations in parent
# ... | [
"def",
"_do_element",
"(",
"self",
",",
"node",
",",
"initial_other_attrs",
"=",
"[",
"]",
",",
"unused",
"=",
"None",
")",
":",
"# Get state (from the stack) make local copies.",
"# ns_parent -- NS declarations in parent",
"# ns_rendered -- NS nodes rendered by ancestors",... | 43.606838 | 0.011115 |
def dependency_state(widgets, drop_defaults=True):
"""Get the state of all widgets specified, and their dependencies.
This uses a simple dependency finder, including:
- any widget directly referenced in the state of an included widget
- any widget in a list/tuple attribute in the state of an included... | [
"def",
"dependency_state",
"(",
"widgets",
",",
"drop_defaults",
"=",
"True",
")",
":",
"# collect the state of all relevant widgets",
"if",
"widgets",
"is",
"None",
":",
"# Get state of all widgets, no smart resolution needed.",
"state",
"=",
"Widget",
".",
"get_manager_st... | 39.068182 | 0.001135 |
def read(self, input_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Read the data encoding the Archive response payload and decode it
into its constituent parts.
Args:
input_stream (stream): A data stream containing encoded object
data, supporting a re... | [
"def",
"read",
"(",
"self",
",",
"input_stream",
",",
"kmip_version",
"=",
"enums",
".",
"KMIPVersion",
".",
"KMIP_1_0",
")",
":",
"super",
"(",
"ArchiveResponsePayload",
",",
"self",
")",
".",
"read",
"(",
"input_stream",
",",
"kmip_version",
"=",
"kmip_ver... | 37.424242 | 0.001579 |
def detectors(regex=None, sep='\t', temporary=False):
"""Print the detectors table"""
db = DBManager(temporary=temporary)
dt = db.detectors
if regex is not None:
try:
re.compile(regex)
except re.error:
log.error("Invalid regex!")
return
dt = dt... | [
"def",
"detectors",
"(",
"regex",
"=",
"None",
",",
"sep",
"=",
"'\\t'",
",",
"temporary",
"=",
"False",
")",
":",
"db",
"=",
"DBManager",
"(",
"temporary",
"=",
"temporary",
")",
"dt",
"=",
"db",
".",
"detectors",
"if",
"regex",
"is",
"not",
"None",... | 34 | 0.002387 |
def svd_flip(u, v, u_based_decision=True):
"""Sign correction to ensure deterministic output from SVD.
Adjusts the columns of u and the rows of v such that the loadings in the
columns in u that are largest in absolute value are always positive.
Parameters
----------
u, v : ndarray
u and ... | [
"def",
"svd_flip",
"(",
"u",
",",
"v",
",",
"u_based_decision",
"=",
"True",
")",
":",
"if",
"u_based_decision",
":",
"# columns of u, rows of v",
"max_abs_cols",
"=",
"np",
".",
"argmax",
"(",
"np",
".",
"abs",
"(",
"u",
")",
",",
"axis",
"=",
"0",
")... | 40.612903 | 0.000776 |
def dump(self, f):
"""Dump an XML document to an open FILE. """
ret = libxml2mod.xmlDocDump(f, self._o)
return ret | [
"def",
"dump",
"(",
"self",
",",
"f",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"xmlDocDump",
"(",
"f",
",",
"self",
".",
"_o",
")",
"return",
"ret"
] | 33.75 | 0.014493 |
def determinize(m):
"""Determinizes a finite automaton."""
if not m.is_finite():
raise TypeError("machine must be a finite automaton")
transitions = collections.defaultdict(lambda: collections.defaultdict(set))
alphabet = set()
for transition in m.get_transitions():
[[lstate], read]... | [
"def",
"determinize",
"(",
"m",
")",
":",
"if",
"not",
"m",
".",
"is_finite",
"(",
")",
":",
"raise",
"TypeError",
"(",
"\"machine must be a finite automaton\"",
")",
"transitions",
"=",
"collections",
".",
"defaultdict",
"(",
"lambda",
":",
"collections",
"."... | 33.442623 | 0.001905 |
def setBatchSize(self, size):
"""
Sets the batch size of records to look up for this record box.
:param size | <int>
"""
self._batchSize = size
try:
self._worker.setBatchSize(size)
except AttributeError:
pass | [
"def",
"setBatchSize",
"(",
"self",
",",
"size",
")",
":",
"self",
".",
"_batchSize",
"=",
"size",
"try",
":",
"self",
".",
"_worker",
".",
"setBatchSize",
"(",
"size",
")",
"except",
"AttributeError",
":",
"pass"
] | 27.454545 | 0.009615 |
def pubsub_sub(self, topic, discover=False, **kwargs):
"""Subscribe to mesages on a given topic
Subscribing to a topic in IPFS means anytime
a message is published to a topic, the subscribers
will be notified of the publication.
The connection with the pubsub topic is opened an... | [
"def",
"pubsub_sub",
"(",
"self",
",",
"topic",
",",
"discover",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"(",
"topic",
",",
"discover",
")",
"return",
"SubChannel",
"(",
"self",
".",
"_client",
".",
"request",
"(",
"'/pubsub/sub'"... | 34.77551 | 0.001142 |
def yaml_force_unicode():
"""
Force pyyaml to return unicode values.
"""
#/
## modified from |http://stackoverflow.com/a/2967461|
if sys.version_info[0] == 2:
def construct_func(self, node):
return self.construct_scalar(node)
yaml.L... | [
"def",
"yaml_force_unicode",
"(",
")",
":",
"#/",
"## modified from |http://stackoverflow.com/a/2967461|",
"if",
"sys",
".",
"version_info",
"[",
"0",
"]",
"==",
"2",
":",
"def",
"construct_func",
"(",
"self",
",",
"node",
")",
":",
"return",
"self",
".",
"con... | 42.090909 | 0.012685 |
def mask(array, predicates, new_value, ty):
"""
Returns a new array, with each element in the original array satisfying the
passed-in predicate set to `new_value`
Args:
array (WeldObject / Numpy.ndarray): Input array
predicates (WeldObject / Numpy.ndarray<bool>): Predicate set
n... | [
"def",
"mask",
"(",
"array",
",",
"predicates",
",",
"new_value",
",",
"ty",
")",
":",
"weld_obj",
"=",
"WeldObject",
"(",
"encoder_",
",",
"decoder_",
")",
"array_var",
"=",
"weld_obj",
".",
"update",
"(",
"array",
")",
"if",
"isinstance",
"(",
"array",... | 32.106383 | 0.000643 |
def _is_blacklisted_filename(filepath):
"""Checks if the filename matches filename_blacklist
blacklist is a list of filenames(str) and/or file patterns(dict)
string, specifying an exact filename to ignore
[".DS_Store", "Thumbs.db"]
mapping(dict), where each dict contains:
'match' - (if th... | [
"def",
"_is_blacklisted_filename",
"(",
"filepath",
")",
":",
"if",
"not",
"cfg",
".",
"CONF",
".",
"filename_blacklist",
":",
"return",
"False",
"filename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"filepath",
")",
"fname",
"=",
"os",
".",
"path",
... | 32.267857 | 0.000537 |
def cli(
template_variables, template, output, variables, extensions,
encoding, include_path, no_variable_file, no_extension_file,
no_trim_blocks, no_lstrip_blocks, remove_trailing_newline,
mode, m, md):
"""Reads the given Jinja TEMPLATE and renders its content
into a new file. F... | [
"def",
"cli",
"(",
"template_variables",
",",
"template",
",",
"output",
",",
"variables",
",",
"extensions",
",",
"encoding",
",",
"include_path",
",",
"no_variable_file",
",",
"no_extension_file",
",",
"no_trim_blocks",
",",
"no_lstrip_blocks",
",",
"remove_traili... | 33.657143 | 0.00055 |
def _prefix_from_prefix_string(cls, prefixlen_str):
"""Return prefix length from a numeric string
Args:
prefixlen_str: The string to be converted
Returns:
An integer, the prefix length.
Raises:
NetmaskValueError: If the input is not a valid netmask
... | [
"def",
"_prefix_from_prefix_string",
"(",
"cls",
",",
"prefixlen_str",
")",
":",
"# int allows a leading +/- as well as surrounding whitespace,",
"# so we ensure that isn't the case",
"if",
"not",
"_BaseV4",
".",
"_DECIMAL_DIGITS",
".",
"issuperset",
"(",
"prefixlen_str",
")",
... | 35.478261 | 0.002387 |
def getPrinted(self):
""" returns "0", "1" or "2" to indicate Printed state.
0 -> Never printed.
1 -> Printed after last publish
2 -> Printed but republished afterwards.
"""
workflow = getToolByName(self, 'portal_workflow')
review_state = workflow.getI... | [
"def",
"getPrinted",
"(",
"self",
")",
":",
"workflow",
"=",
"getToolByName",
"(",
"self",
",",
"'portal_workflow'",
")",
"review_state",
"=",
"workflow",
".",
"getInfoFor",
"(",
"self",
",",
"'review_state'",
",",
"''",
")",
"if",
"review_state",
"not",
"in... | 37.954545 | 0.002336 |
def from_schema(cls, schema, handlers={}, **kwargs):
"""
Construct a resolver from a JSON schema object.
"""
return cls(
schema.get('$id', schema.get('id', '')) if isinstance(schema, dict) else '',
schema,
handlers=handlers,
**kwarg... | [
"def",
"from_schema",
"(",
"cls",
",",
"schema",
",",
"handlers",
"=",
"{",
"}",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"cls",
"(",
"schema",
".",
"get",
"(",
"'$id'",
",",
"schema",
".",
"get",
"(",
"'id'",
",",
"''",
")",
")",
"if",
"is... | 32.3 | 0.009036 |
def _instruction_to_gate(self, instruction, layer):
""" Convert an instruction into its corresponding Gate object, and establish
any connections it introduces between qubits"""
current_cons = []
connection_label = None
# add in a gate that operates over multiple qubits
... | [
"def",
"_instruction_to_gate",
"(",
"self",
",",
"instruction",
",",
"layer",
")",
":",
"current_cons",
"=",
"[",
"]",
"connection_label",
"=",
"None",
"# add in a gate that operates over multiple qubits",
"def",
"add_connected_gate",
"(",
"instruction",
",",
"gates",
... | 39.915254 | 0.001657 |
def default_view_method(pid, record, template=None, **kwargs):
r"""Display default view.
Sends record_viewed signal and renders template.
:param pid: PID object.
:param record: Record object.
:param template: Template to render.
:param \*\*kwargs: Additional view arguments based on URL rule.
... | [
"def",
"default_view_method",
"(",
"pid",
",",
"record",
",",
"template",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"record_viewed",
".",
"send",
"(",
"current_app",
".",
"_get_current_object",
"(",
")",
",",
"pid",
"=",
"pid",
",",
"record",
"=",
... | 26.095238 | 0.001761 |
def get_uvw_segment(d, segment=-1):
""" Calculates uvw for each baseline at mid time of a given segment.
d defines pipeline state. assumes segmenttimes defined by RT.set_pipeline.
"""
# define times to read
if segment != -1:
assert 'segmenttimes' in d, 'd must have segmenttimes defined'
... | [
"def",
"get_uvw_segment",
"(",
"d",
",",
"segment",
"=",
"-",
"1",
")",
":",
"# define times to read",
"if",
"segment",
"!=",
"-",
"1",
":",
"assert",
"'segmenttimes'",
"in",
"d",
",",
"'d must have segmenttimes defined'",
"t0",
"=",
"d",
"[",
"'segmenttimes'"... | 37.962963 | 0.000951 |
def get_data(service, cache_data, trigger_id):
"""
get the data from the cache
:param service: the service name
:param cache_data: the data from the cache
:type trigger_id: integer
:return: Return the data from the cache
:rtype: object
... | [
"def",
"get_data",
"(",
"service",
",",
"cache_data",
",",
"trigger_id",
")",
":",
"if",
"service",
".",
"startswith",
"(",
"'th_'",
")",
":",
"cache",
"=",
"caches",
"[",
"'django_th'",
"]",
"limit",
"=",
"settings",
".",
"DJANGO_TH",
".",
"get",
"(",
... | 42.137931 | 0.0016 |
def do_dock6_flexible(self, ligand_path, force_rerun=False):
"""Dock a ligand to the protein.
Args:
ligand_path (str): Path to ligand (mol2 format) to dock to protein
force_rerun (bool): If method should be rerun even if output file exists
"""
log.debug('{}: run... | [
"def",
"do_dock6_flexible",
"(",
"self",
",",
"ligand_path",
",",
"force_rerun",
"=",
"False",
")",
":",
"log",
".",
"debug",
"(",
"'{}: running DOCK6...'",
".",
"format",
"(",
"self",
".",
"id",
")",
")",
"ligand_name",
"=",
"os",
".",
"path",
".",
"bas... | 59.990741 | 0.002126 |
def get_details_letssingit(song_name):
'''
Gets the song details if song details not found through spotify
'''
song_name = improvename.songname(song_name)
url = "http://search.letssingit.com/cgi-exe/am.cgi?a=search&artist_id=&l=archive&s=" + \
quote(song_name.encode('utf-8'))
html = ur... | [
"def",
"get_details_letssingit",
"(",
"song_name",
")",
":",
"song_name",
"=",
"improvename",
".",
"songname",
"(",
"song_name",
")",
"url",
"=",
"\"http://search.letssingit.com/cgi-exe/am.cgi?a=search&artist_id=&l=archive&s=\"",
"+",
"quote",
"(",
"song_name",
".",
"enco... | 31.813559 | 0.001034 |
def clean(mapping, bind, values):
""" Perform several types of string cleaning for titles etc.. """
categories = {'C': ' '}
for value in values:
if isinstance(value, six.string_types):
value = normality.normalize(value, lowercase=False, collapse=True,
... | [
"def",
"clean",
"(",
"mapping",
",",
"bind",
",",
"values",
")",
":",
"categories",
"=",
"{",
"'C'",
":",
"' '",
"}",
"for",
"value",
"in",
"values",
":",
"if",
"isinstance",
"(",
"value",
",",
"six",
".",
"string_types",
")",
":",
"value",
"=",
"n... | 47 | 0.00232 |
def load_rsa_public_key_file(rsakeyfile):
# type: (str, str) ->
# cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKey
"""Load an RSA Public key PEM file
:param str rsakeyfile: RSA public key PEM file to load
:rtype: cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKey
:return... | [
"def",
"load_rsa_public_key_file",
"(",
"rsakeyfile",
")",
":",
"# type: (str, str) ->",
"# cryptography.hazmat.primitives.asymmetric.rsa.RSAPublicKey",
"keypath",
"=",
"os",
".",
"path",
".",
"expandvars",
"(",
"os",
".",
"path",
".",
"expanduser",
"(",
"rsakeyfil... | 43.066667 | 0.001515 |
def create_style_from_font(font):
"""
Convert from font string/tyuple into a Qt style sheet string
:param font: "Arial 10 Bold" or ('Arial', 10, 'Bold)
:return: style string that can be combined with other style strings
"""
if font is None:
return ''
if type(font) is str:
_... | [
"def",
"create_style_from_font",
"(",
"font",
")",
":",
"if",
"font",
"is",
"None",
":",
"return",
"''",
"if",
"type",
"(",
"font",
")",
"is",
"str",
":",
"_font",
"=",
"font",
".",
"split",
"(",
"' '",
")",
"else",
":",
"_font",
"=",
"font",
"styl... | 26.814815 | 0.001333 |
async def start_master(host="", port=48484, *, loop=None):
"""
Starts a new HighFive master at the given host and port, and returns it.
"""
loop = loop if loop is not None else asyncio.get_event_loop()
manager = jobs.JobManager(loop=loop)
workers = set()
server = await loop.create_server(
... | [
"async",
"def",
"start_master",
"(",
"host",
"=",
"\"\"",
",",
"port",
"=",
"48484",
",",
"*",
",",
"loop",
"=",
"None",
")",
":",
"loop",
"=",
"loop",
"if",
"loop",
"is",
"not",
"None",
"else",
"asyncio",
".",
"get_event_loop",
"(",
")",
"manager",
... | 35.75 | 0.002273 |
def robust_outer_product(vec_1, vec_2):
"""
Calculates a 'robust' outer product of two vectors that may or may not
contain very small values.
Parameters
----------
vec_1 : 1D ndarray
vec_2 : 1D ndarray
Returns
-------
outer_prod : 2D ndarray. The outer product of vec_1 and vec_... | [
"def",
"robust_outer_product",
"(",
"vec_1",
",",
"vec_2",
")",
":",
"mantissa_1",
",",
"exponents_1",
"=",
"np",
".",
"frexp",
"(",
"vec_1",
")",
"mantissa_2",
",",
"exponents_2",
"=",
"np",
".",
"frexp",
"(",
"vec_2",
")",
"new_mantissas",
"=",
"mantissa... | 30.473684 | 0.001675 |
def has_settable_hwclock():
'''
Returns True if the system has a hardware clock capable of being
set from software.
CLI Example:
salt '*' system.has_settable_hwclock
'''
if salt.utils.path.which_bin(['hwclock']) is not None:
res = __salt__['cmd.run_all'](
['hwclock', '-... | [
"def",
"has_settable_hwclock",
"(",
")",
":",
"if",
"salt",
".",
"utils",
".",
"path",
".",
"which_bin",
"(",
"[",
"'hwclock'",
"]",
")",
"is",
"not",
"None",
":",
"res",
"=",
"__salt__",
"[",
"'cmd.run_all'",
"]",
"(",
"[",
"'hwclock'",
",",
"'--test'... | 29.0625 | 0.002083 |
def get_slice_info(slice_times):
"""
Extract slice order from slice timing info.
TODO: Be more specific with slice orders.
Currently anything where there's some kind of skipping is interpreted as
interleaved of some kind.
Parameters
----------
slice_times : array-like
A list of... | [
"def",
"get_slice_info",
"(",
"slice_times",
")",
":",
"# Slice order",
"slice_times",
"=",
"remove_duplicates",
"(",
"slice_times",
")",
"slice_order",
"=",
"sorted",
"(",
"range",
"(",
"len",
"(",
"slice_times",
")",
")",
",",
"key",
"=",
"lambda",
"k",
":... | 35.028571 | 0.001587 |
def view_config(
method='get',
template_name='',
predicates=(),
wrappers=(),
base_wrappers_getter=get_base_wrappers,
):
""" Creating Views applied some configurations
and store it to _wrapped attribute on each Views.
* _wrapped expects to be called by Controller
... | [
"def",
"view_config",
"(",
"method",
"=",
"'get'",
",",
"template_name",
"=",
"''",
",",
"predicates",
"=",
"(",
")",
",",
"wrappers",
"=",
"(",
")",
",",
"base_wrappers_getter",
"=",
"get_base_wrappers",
",",
")",
":",
"wrappers",
"=",
"base_wrappers_getter... | 32.730769 | 0.002283 |
def get_dummies(
data,
prefix=None,
prefix_sep="_",
dummy_na=False,
columns=None,
sparse=False,
drop_first=False,
dtype=None,
):
"""Convert categorical variable into indicator variables.
Args:
data (array-like, Series, or DataFrame): data to encode.
prefix (strin... | [
"def",
"get_dummies",
"(",
"data",
",",
"prefix",
"=",
"None",
",",
"prefix_sep",
"=",
"\"_\"",
",",
"dummy_na",
"=",
"False",
",",
"columns",
"=",
"None",
",",
"sparse",
"=",
"False",
",",
"drop_first",
"=",
"False",
",",
"dtype",
"=",
"None",
",",
... | 31.535714 | 0.000549 |
def is_type(value):
"""Determine if value is an instance or subclass of the class Type."""
if isinstance(value, type):
return issubclass(value, Type)
return isinstance(value, Type) | [
"def",
"is_type",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"type",
")",
":",
"return",
"issubclass",
"(",
"value",
",",
"Type",
")",
"return",
"isinstance",
"(",
"value",
",",
"Type",
")"
] | 42.4 | 0.009259 |
def disable_buffering(self):
"""Disable the output buffering."""
self._next = self._gen.next
self.buffered = False | [
"def",
"disable_buffering",
"(",
"self",
")",
":",
"self",
".",
"_next",
"=",
"self",
".",
"_gen",
".",
"next",
"self",
".",
"buffered",
"=",
"False"
] | 33.75 | 0.014493 |
def returner(ret):
'''
Insert minion return data into the sqlite3 database
'''
log.debug('sqlite3 returner <returner> called with data: %s', ret)
conn = _get_conn(ret)
cur = conn.cursor()
sql = '''INSERT INTO salt_returns
(fun, jid, id, fun_args, date, full_ret, success)
... | [
"def",
"returner",
"(",
"ret",
")",
":",
"log",
".",
"debug",
"(",
"'sqlite3 returner <returner> called with data: %s'",
",",
"ret",
")",
"conn",
"=",
"_get_conn",
"(",
"ret",
")",
"cur",
"=",
"conn",
".",
"cursor",
"(",
")",
"sql",
"=",
"'''INSERT INTO salt... | 42.210526 | 0.002439 |
def open_mfdataset(paths, chunks=None, concat_dim=_CONCAT_DIM_DEFAULT,
compat='no_conflicts', preprocess=None, engine=None,
lock=None, data_vars='all', coords='different',
autoclose=None, parallel=False, **kwargs):
"""Open multiple files as a single dataset.
... | [
"def",
"open_mfdataset",
"(",
"paths",
",",
"chunks",
"=",
"None",
",",
"concat_dim",
"=",
"_CONCAT_DIM_DEFAULT",
",",
"compat",
"=",
"'no_conflicts'",
",",
"preprocess",
"=",
"None",
",",
"engine",
"=",
"None",
",",
"lock",
"=",
"None",
",",
"data_vars",
... | 44.55615 | 0.000117 |
def get_type(obj, **kwargs):
"""Return the type of an object. Do some regex to remove the "<class..." bit."""
t = type(obj)
s = extract_type(str(t))
return 'Type: {}'.format(s) | [
"def",
"get_type",
"(",
"obj",
",",
"*",
"*",
"kwargs",
")",
":",
"t",
"=",
"type",
"(",
"obj",
")",
"s",
"=",
"extract_type",
"(",
"str",
"(",
"t",
")",
")",
"return",
"'Type: {}'",
".",
"format",
"(",
"s",
")"
] | 26.857143 | 0.010309 |
def Import(context, request):
""" Read Dimensional-CSV analysis results
"""
form = request.form
# TODO form['file'] sometimes returns a list
infile = form['instrument_results_file'][0] if \
isinstance(form['instrument_results_file'], list) else \
form['instrument_results_file']
a... | [
"def",
"Import",
"(",
"context",
",",
"request",
")",
":",
"form",
"=",
"request",
".",
"form",
"# TODO form['file'] sometimes returns a list",
"infile",
"=",
"form",
"[",
"'instrument_results_file'",
"]",
"[",
"0",
"]",
"if",
"isinstance",
"(",
"form",
"[",
"... | 34.302326 | 0.001318 |
def add(self, session):
""" Add session to the container.
@param session: Session object
"""
self._items[session.session_id] = session
if session.expiry is not None:
self._queue.push(session) | [
"def",
"add",
"(",
"self",
",",
"session",
")",
":",
"self",
".",
"_items",
"[",
"session",
".",
"session_id",
"]",
"=",
"session",
"if",
"session",
".",
"expiry",
"is",
"not",
"None",
":",
"self",
".",
"_queue",
".",
"push",
"(",
"session",
")"
] | 26.333333 | 0.008163 |
def peers(**kwargs): # pylint: disable=unused-argument
'''
Returns a list the NTP peers configured on the network device.
:return: configured NTP peers as list.
CLI Example:
.. code-block:: bash
salt '*' ntp.peers
Example output:
.. code-block:: python
[
... | [
"def",
"peers",
"(",
"*",
"*",
"kwargs",
")",
":",
"# pylint: disable=unused-argument",
"ntp_peers",
"=",
"salt",
".",
"utils",
".",
"napalm",
".",
"call",
"(",
"napalm_device",
",",
"# pylint: disable=undefined-variable",
"'get_ntp_peers'",
",",
"*",
"*",
"{",
... | 18.219512 | 0.001271 |
def remove():
"""
Blow away the current project.
"""
if exists(env.venv_path):
run("rm -rf %s" % env.venv_path)
if exists(env.proj_path):
run("rm -rf %s" % env.proj_path)
for template in get_templates().values():
remote_path = template["remote_path"]
if exists(rem... | [
"def",
"remove",
"(",
")",
":",
"if",
"exists",
"(",
"env",
".",
"venv_path",
")",
":",
"run",
"(",
"\"rm -rf %s\"",
"%",
"env",
".",
"venv_path",
")",
"if",
"exists",
"(",
"env",
".",
"proj_path",
")",
":",
"run",
"(",
"\"rm -rf %s\"",
"%",
"env",
... | 33.294118 | 0.001718 |
def image_get_by_alias(alias,
remote_addr=None,
cert=None,
key=None,
verify_cert=True,
_raw=False):
''' Get an image by an alias
alias :
The alias of the image to retrieve
... | [
"def",
"image_get_by_alias",
"(",
"alias",
",",
"remote_addr",
"=",
"None",
",",
"cert",
"=",
"None",
",",
"key",
"=",
"None",
",",
"verify_cert",
"=",
"True",
",",
"_raw",
"=",
"False",
")",
":",
"client",
"=",
"pylxd_client_get",
"(",
"remote_addr",
",... | 25.966102 | 0.000629 |
def freedman_diaconis_bins(a):
"""
Calculate number of hist bins using Freedman-Diaconis rule.
"""
# From http://stats.stackexchange.com/questions/798/
a = np.asarray(a)
h = 2 * iqr(a) / (len(a) ** (1 / 3))
# fall back to sqrt(a) bins if iqr is 0
if h == 0:
bins = np.ceil(np.sqr... | [
"def",
"freedman_diaconis_bins",
"(",
"a",
")",
":",
"# From http://stats.stackexchange.com/questions/798/",
"a",
"=",
"np",
".",
"asarray",
"(",
"a",
")",
"h",
"=",
"2",
"*",
"iqr",
"(",
"a",
")",
"/",
"(",
"len",
"(",
"a",
")",
"**",
"(",
"1",
"/",
... | 27.266667 | 0.002364 |
def get_statsmodels_summary(self,
title=None,
alpha=.05):
"""
Parameters
----------
title : str, or None, optional.
Will be the title of the returned summary. If None, the default
title is used.
... | [
"def",
"get_statsmodels_summary",
"(",
"self",
",",
"title",
"=",
"None",
",",
"alpha",
"=",
".05",
")",
":",
"try",
":",
"# Get the statsmodels Summary class",
"from",
"statsmodels",
".",
"iolib",
".",
"summary",
"import",
"Summary",
"except",
"ImportError",
":... | 37.073171 | 0.001282 |
def get_peers(self):
"""Get all known nodes and their 'state' """
node = NodeLeader.Instance()
result = {"connected": [], "unconnected": [], "bad": []}
connected_peers = []
for peer in node.Peers:
result['connected'].append({"address": peer.host,
... | [
"def",
"get_peers",
"(",
"self",
")",
":",
"node",
"=",
"NodeLeader",
".",
"Instance",
"(",
")",
"result",
"=",
"{",
"\"connected\"",
":",
"[",
"]",
",",
"\"unconnected\"",
":",
"[",
"]",
",",
"\"bad\"",
":",
"[",
"]",
"}",
"connected_peers",
"=",
"[... | 41.041667 | 0.001984 |
def translate_func(name, block, args):
"""Translates functions and all nested functions to Python code.
name - name of that function (global functions will be available under var while
inline will be available directly under this name )
block - code of the function (*with* brackets {} )
... | [
"def",
"translate_func",
"(",
"name",
",",
"block",
",",
"args",
")",
":",
"inline",
"=",
"name",
".",
"startswith",
"(",
"'PyJsLvalInline'",
")",
"real_name",
"=",
"''",
"if",
"inline",
":",
"name",
",",
"real_name",
"=",
"name",
".",
"split",
"(",
"'... | 48.8 | 0.002232 |
def update(self, z, R=None, H=None):
"""
Add a new measurement (z) to the Kalman filter. If z is None, nothing
is changed.
Parameters
----------
z : np.array
measurement for this update.
R : np.array, scalar, or None
Optionally provide R... | [
"def",
"update",
"(",
"self",
",",
"z",
",",
"R",
"=",
"None",
",",
"H",
"=",
"None",
")",
":",
"if",
"H",
"is",
"None",
":",
"H",
"=",
"self",
".",
"H",
"# new probability is recursively defined as prior * likelihood",
"for",
"i",
",",
"f",
"in",
"enu... | 31.537037 | 0.002278 |
def __generate_actor(self, instance_id, operator, input, output):
"""Generates an actor that will execute a particular instance of
the logical operator
Attributes:
instance_id (UUID): The id of the instance the actor will execute.
operator (Operator): The metadata of the... | [
"def",
"__generate_actor",
"(",
"self",
",",
"instance_id",
",",
"operator",
",",
"input",
",",
"output",
")",
":",
"actor_id",
"=",
"(",
"operator",
".",
"id",
",",
"instance_id",
")",
"# Record the physical dataflow graph (for debugging purposes)",
"self",
".",
... | 51.243243 | 0.000517 |
def update_git_repos(opts=None, clean=False, masterless=False):
'''
Checkout git repos containing Windows Software Package Definitions
opts
Specify an alternate opts dict. Should not be used unless this function
is imported into an execution module.
clean : False
Clean repo cac... | [
"def",
"update_git_repos",
"(",
"opts",
"=",
"None",
",",
"clean",
"=",
"False",
",",
"masterless",
"=",
"False",
")",
":",
"if",
"opts",
"is",
"None",
":",
"opts",
"=",
"__opts__",
"winrepo_dir",
"=",
"opts",
"[",
"'winrepo_dir'",
"]",
"winrepo_remotes",
... | 42.433962 | 0.000652 |
def scaleY(self, y):
'returns plotter y coordinate'
return round(self.plotviewBox.ymin+(y-self.visibleBox.ymin)*self.yScaler) | [
"def",
"scaleY",
"(",
"self",
",",
"y",
")",
":",
"return",
"round",
"(",
"self",
".",
"plotviewBox",
".",
"ymin",
"+",
"(",
"y",
"-",
"self",
".",
"visibleBox",
".",
"ymin",
")",
"*",
"self",
".",
"yScaler",
")"
] | 46.333333 | 0.021277 |
def remove_experiment(self, id):
'''remove an experiment by id'''
if id in self.experiments:
self.experiments.pop(id)
self.write_file() | [
"def",
"remove_experiment",
"(",
"self",
",",
"id",
")",
":",
"if",
"id",
"in",
"self",
".",
"experiments",
":",
"self",
".",
"experiments",
".",
"pop",
"(",
"id",
")",
"self",
".",
"write_file",
"(",
")"
] | 33.4 | 0.011696 |
def _reduce_diff_results(self, matches_path, tokenizer, output_fh):
"""Returns `output_fh` populated with a reduced set of data from
`matches_fh`.
Diff results typically contain a lot of filler results that
serve only to hide real differences. If one text has a single
extra toke... | [
"def",
"_reduce_diff_results",
"(",
"self",
",",
"matches_path",
",",
"tokenizer",
",",
"output_fh",
")",
":",
"self",
".",
"_logger",
".",
"info",
"(",
"'Removing filler results'",
")",
"# For performance, perform the attribute accesses once.",
"tokenize",
"=",
"tokeni... | 49.028169 | 0.000563 |
def normalize_json(template):
"""Normalize our template for diffing.
Args:
template(str): string representing the template
Returns:
list: json representation of the parameters
"""
obj = parse_cloudformation_template(template)
json_str = json.dumps(
obj, sort_keys=True, ... | [
"def",
"normalize_json",
"(",
"template",
")",
":",
"obj",
"=",
"parse_cloudformation_template",
"(",
"template",
")",
"json_str",
"=",
"json",
".",
"dumps",
"(",
"obj",
",",
"sort_keys",
"=",
"True",
",",
"indent",
"=",
"4",
",",
"default",
"=",
"str",
... | 26.666667 | 0.002012 |
def statichttp(container = None):
"wrap a WSGI-style function to a HTTPRequest event handler"
def decorator(func):
@functools.wraps(func)
def handler(event):
return _handler(container, event, func)
if hasattr(func, '__self__'):
handler.__self__ = func.__self__
... | [
"def",
"statichttp",
"(",
"container",
"=",
"None",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"handler",
"(",
"event",
")",
":",
"return",
"_handler",
"(",
"container",
",",
"event",
... | 35.1 | 0.008333 |
def raise_figure_window(f=0):
"""
Raises the supplied figure number or figure window.
"""
if _fun.is_a_number(f): f = _pylab.figure(f)
f.canvas.manager.window.raise_() | [
"def",
"raise_figure_window",
"(",
"f",
"=",
"0",
")",
":",
"if",
"_fun",
".",
"is_a_number",
"(",
"f",
")",
":",
"f",
"=",
"_pylab",
".",
"figure",
"(",
"f",
")",
"f",
".",
"canvas",
".",
"manager",
".",
"window",
".",
"raise_",
"(",
")"
] | 30.333333 | 0.010695 |
def set_datetime_format(self, format):
"""
Set the Accept-Datetime-Format header to an acceptable
value
Args:
format: UNIX or RFC3339
"""
if not format in ["UNIX", "RFC3339"]:
return
self.datetime_format = format
self.set_header(... | [
"def",
"set_datetime_format",
"(",
"self",
",",
"format",
")",
":",
"if",
"not",
"format",
"in",
"[",
"\"UNIX\"",
",",
"\"RFC3339\"",
"]",
":",
"return",
"self",
".",
"datetime_format",
"=",
"format",
"self",
".",
"set_header",
"(",
"\"Accept-Datetime-Format\"... | 25.285714 | 0.008174 |
def read_initializer_configuration(self, name, **kwargs): # noqa: E501
"""read_initializer_configuration # noqa: E501
read the specified InitializerConfiguration # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass as... | [
"def",
"read_initializer_configuration",
"(",
"self",
",",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
"."... | 54.875 | 0.001493 |
def __setIncludes(self, schema):
"""Add dictionary of includes to schema instance.
schema -- XMLSchema instance
"""
for schemaLocation, val in schema.includes.items():
if self._includes.has_key(schemaLocation):
schema.addIncludeSchema(schemaLocation, self.... | [
"def",
"__setIncludes",
"(",
"self",
",",
"schema",
")",
":",
"for",
"schemaLocation",
",",
"val",
"in",
"schema",
".",
"includes",
".",
"items",
"(",
")",
":",
"if",
"self",
".",
"_includes",
".",
"has_key",
"(",
"schemaLocation",
")",
":",
"schema",
... | 48.428571 | 0.014493 |
def find_bind_module(name, verbose=False):
"""Find the bind module matching the given name.
Args:
name (str): Name of package to find bind module for.
verbose (bool): If True, print extra output.
Returns:
str: Filepath to bind module .py file, or None if not found.
"""
bind... | [
"def",
"find_bind_module",
"(",
"name",
",",
"verbose",
"=",
"False",
")",
":",
"bindnames",
"=",
"get_bind_modules",
"(",
"verbose",
"=",
"verbose",
")",
"bindfile",
"=",
"bindnames",
".",
"get",
"(",
"name",
")",
"if",
"bindfile",
":",
"return",
"bindfil... | 25.833333 | 0.001244 |
def set_definition_node(self, node, name):
"""Set definition by name."""
definition = self.get_definition(name)
if definition:
definition.node = node | [
"def",
"set_definition_node",
"(",
"self",
",",
"node",
",",
"name",
")",
":",
"definition",
"=",
"self",
".",
"get_definition",
"(",
"name",
")",
"if",
"definition",
":",
"definition",
".",
"node",
"=",
"node"
] | 36.2 | 0.010811 |
def urlencode(params):
"""Urlencode a multidimensional dict."""
# Not doing duck typing here. Will make debugging easier.
if not isinstance(params, dict):
raise TypeError("Only dicts are supported.")
params = flatten(params)
url_params = OrderedDict()
for param in params:
valu... | [
"def",
"urlencode",
"(",
"params",
")",
":",
"# Not doing duck typing here. Will make debugging easier.",
"if",
"not",
"isinstance",
"(",
"params",
",",
"dict",
")",
":",
"raise",
"TypeError",
"(",
"\"Only dicts are supported.\"",
")",
"params",
"=",
"flatten",
"(",
... | 25.4 | 0.001898 |
def sky_to_image(shape_list, header):
"""Converts a `ShapeList` into shapes with coordinates in image coordinates
Parameters
----------
shape_list : `pyregion.ShapeList`
The ShapeList to convert
header : `~astropy.io.fits.Header`
Specifies what WCS transf... | [
"def",
"sky_to_image",
"(",
"shape_list",
",",
"header",
")",
":",
"for",
"shape",
",",
"comment",
"in",
"shape_list",
":",
"if",
"isinstance",
"(",
"shape",
",",
"Shape",
")",
"and",
"(",
"shape",
".",
"coord_format",
"not",
"in",
"image_like_coordformats",... | 29.479167 | 0.002052 |
def transform_non_affine(self, values):
"""Transform an array of GPS times.
This method is designed to filter out transformations that will
generate text elements that require exact precision, and use
`Decimal` objects to do the transformation, and simple `float`
otherwise.
... | [
"def",
"transform_non_affine",
"(",
"self",
",",
"values",
")",
":",
"scale",
"=",
"self",
".",
"scale",
"or",
"1",
"epoch",
"=",
"self",
".",
"epoch",
"or",
"0",
"values",
"=",
"numpy",
".",
"asarray",
"(",
"values",
")",
"# handle simple or data transfor... | 37.857143 | 0.00184 |
def update_user_info(self, **kwargs):
"""Update user info and settings.
:param \*\*kwargs: settings to be merged with
:func:`User.get_configfile` setings and sent to Filemail.
:rtype: ``bool``
"""
if kwargs:
self.config.update(kwargs)
method, url =... | [
"def",
"update_user_info",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"kwargs",
":",
"self",
".",
"config",
".",
"update",
"(",
"kwargs",
")",
"method",
",",
"url",
"=",
"get_URL",
"(",
"'user_update'",
")",
"res",
"=",
"getattr",
"(",
"se... | 25.263158 | 0.008032 |
def _default_temporary_directory(self, prefix):
"""__init__ helper."""
try:
self.temporary_file = tempfile.NamedTemporaryFile(prefix=prefix)
except OSError as err: # pragma: no cover
logger.critical('Cannot create a system temporary directory: '+repr(err))
raise securesystemslib.exception... | [
"def",
"_default_temporary_directory",
"(",
"self",
",",
"prefix",
")",
":",
"try",
":",
"self",
".",
"temporary_file",
"=",
"tempfile",
".",
"NamedTemporaryFile",
"(",
"prefix",
"=",
"prefix",
")",
"except",
"OSError",
"as",
"err",
":",
"# pragma: no cover",
... | 40.625 | 0.01506 |
def period_end_day(self, value=None):
"""Corresponds to IDD Field `period_end_day`
Args:
value (str): value for IDD Field `period_end_day`
if `value` is None it will not be checked against the
specification and is assumed to be a missing value
Raises... | [
"def",
"period_end_day",
"(",
"self",
",",
"value",
"=",
"None",
")",
":",
"if",
"value",
"is",
"not",
"None",
":",
"try",
":",
"value",
"=",
"str",
"(",
"value",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"'value {} need to be of type s... | 35.869565 | 0.002361 |
def read_tdms(tdms_file):
"""Read tdms file and return channel names and data"""
tdms_file = nptdms.TdmsFile(tdms_file)
ch_names = []
ch_data = []
for o in tdms_file.objects.values():
if o.data is not None and len(o.data):
chn = o.path.split('/')[-1].strip("'")
if "u... | [
"def",
"read_tdms",
"(",
"tdms_file",
")",
":",
"tdms_file",
"=",
"nptdms",
".",
"TdmsFile",
"(",
"tdms_file",
")",
"ch_names",
"=",
"[",
"]",
"ch_data",
"=",
"[",
"]",
"for",
"o",
"in",
"tdms_file",
".",
"objects",
".",
"values",
"(",
")",
":",
"if"... | 31.333333 | 0.001721 |
def Open(self):
"""Connects to the database and creates the required tables.
Raises:
IOError: if the 4n6time tables cannot be created or data not inserted
in the database.
OSError: if the 4n6time tables cannot be created or data not inserted
in the database.
ValueError: if... | [
"def",
"Open",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_dbname",
":",
"raise",
"ValueError",
"(",
"'Missing database name.'",
")",
"try",
":",
"if",
"self",
".",
"_append",
":",
"self",
".",
"_connection",
"=",
"MySQLdb",
".",
"connect",
"(",
... | 38.109589 | 0.00876 |
def calculate(*args, **kwargs):
'''
Calculates and returns a requested quantity from quantities passed in as
keyword arguments.
Parameters
----------
\*args : string
Names of quantities to be calculated.
assumptions : tuple, optional
Strings specifying which assumptions to enable. Overrides the default
... | [
"def",
"calculate",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"0",
":",
"raise",
"ValueError",
"(",
"'must specify quantities to calculate'",
")",
"# initialize a solver to do the work",
"solver",
"=",
"FluidSolver... | 31.356322 | 0.001421 |
def produce_examples(shard_ids, wikis_dir, refs_dir, urls_dir, vocab_path,
out_filepaths):
"""Produce examples from shard_ids to out_filepaths."""
# * Join the Wikipedia articles with their references
# * Run Tf-idf to sort reference paragraphs
# * Encode the Wikipedia and reference text wi... | [
"def",
"produce_examples",
"(",
"shard_ids",
",",
"wikis_dir",
",",
"refs_dir",
",",
"urls_dir",
",",
"vocab_path",
",",
"out_filepaths",
")",
":",
"# * Join the Wikipedia articles with their references",
"# * Run Tf-idf to sort reference paragraphs",
"# * Encode the Wikipedia an... | 41.27 | 0.008045 |
def tag_info(self):
"""Return Unicode string with class, name and unnested value."""
return self.__class__.__name__ + (
'(%r)' % self.name if self.name
else "") + ": " + self.valuestr() | [
"def",
"tag_info",
"(",
"self",
")",
":",
"return",
"self",
".",
"__class__",
".",
"__name__",
"+",
"(",
"'(%r)'",
"%",
"self",
".",
"name",
"if",
"self",
".",
"name",
"else",
"\"\"",
")",
"+",
"\": \"",
"+",
"self",
".",
"valuestr",
"(",
")"
] | 44.2 | 0.008889 |
def get_selection_as_executable_code(self):
"""Return selected text as a processed text,
to be executable in a Python/IPython interpreter"""
ls = self.get_line_separator()
_indent = lambda line: len(line)-len(line.lstrip())
line_from, line_to = self.get_selection_bounds(... | [
"def",
"get_selection_as_executable_code",
"(",
"self",
")",
":",
"ls",
"=",
"self",
".",
"get_line_separator",
"(",
")",
"_indent",
"=",
"lambda",
"line",
":",
"len",
"(",
"line",
")",
"-",
"len",
"(",
"line",
".",
"lstrip",
"(",
")",
")",
"line_from",
... | 38.381818 | 0.001386 |
def contents(self):
"""
A C{PMap}, the message contents without Eliot metadata.
"""
return self._logged_dict.discard(TIMESTAMP_FIELD).discard(
TASK_UUID_FIELD
).discard(TASK_LEVEL_FIELD) | [
"def",
"contents",
"(",
"self",
")",
":",
"return",
"self",
".",
"_logged_dict",
".",
"discard",
"(",
"TIMESTAMP_FIELD",
")",
".",
"discard",
"(",
"TASK_UUID_FIELD",
")",
".",
"discard",
"(",
"TASK_LEVEL_FIELD",
")"
] | 33.142857 | 0.008403 |
def get_git_root(index=3): # type: (int) -> str
"""
Get the path of the git root directory of the caller's file
Raises a RuntimeError if a git repository cannot be found
"""
path = get_current_path(index=index)
while True:
git_path = os.path.join(path, '.git')
if os.path.isdir(g... | [
"def",
"get_git_root",
"(",
"index",
"=",
"3",
")",
":",
"# type: (int) -> str",
"path",
"=",
"get_current_path",
"(",
"index",
"=",
"index",
")",
"while",
"True",
":",
"git_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"'.git'",
")",
"... | 36.615385 | 0.002049 |
def case_name_parts(self):
"""
Convert all the parts of the name to the proper case... carefully!
"""
if not self.is_mixed_case():
self.honorific = self.honorific.title() if self.honorific else None
self.nick = self.nick.title() if self.nick else None
... | [
"def",
"case_name_parts",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"is_mixed_case",
"(",
")",
":",
"self",
".",
"honorific",
"=",
"self",
".",
"honorific",
".",
"title",
"(",
")",
"if",
"self",
".",
"honorific",
"else",
"None",
"self",
".",
"... | 36.538462 | 0.002051 |
def setup(app):
"""Register directives.
When sphinx loads the extension (= imports the extension module) it
also executes the setup() function. Setup is the way extension
informs Sphinx about everything that the extension enables: which
config_values are introduced, which custom nodes/directives/ro... | [
"def",
"setup",
"(",
"app",
")",
":",
"app",
".",
"add_config_value",
"(",
"'autoprocess_process_dir'",
",",
"''",
",",
"'env'",
")",
"app",
".",
"add_config_value",
"(",
"'autoprocess_source_base_url'",
",",
"''",
",",
"'env'",
")",
"app",
".",
"add_config_va... | 43.541667 | 0.000936 |
def grid_search(fn, grd, fmin=True, nproc=None):
"""Perform a grid search for optimal parameters of a specified
function. In the simplest case the function returns a float value,
and a single optimum value and corresponding parameter values are
identified. If the function returns a tuple of values, eac... | [
"def",
"grid_search",
"(",
"fn",
",",
"grd",
",",
"fmin",
"=",
"True",
",",
"nproc",
"=",
"None",
")",
":",
"if",
"fmin",
":",
"slct",
"=",
"np",
".",
"argmin",
"else",
":",
"slct",
"=",
"np",
".",
"argmax",
"fprm",
"=",
"itertools",
".",
"produc... | 40.153846 | 0.000623 |
def resize(self, size):
""" Re-sizes the :class:`Array` by appending new :class:`Array` elements
or removing :class:`Array` elements from the end.
:param int size: new size of the :class:`Array` in number of
:class:`Array` elements.
"""
if isinstance(self._data, Arra... | [
"def",
"resize",
"(",
"self",
",",
"size",
")",
":",
"if",
"isinstance",
"(",
"self",
".",
"_data",
",",
"Array",
")",
":",
"self",
".",
"_data",
".",
"resize",
"(",
"size",
")"
] | 39 | 0.008357 |
def baseimage(self, new_image):
"""
change image of final stage FROM instruction
"""
images = self.parent_images or [None]
images[-1] = new_image
self.parent_images = images | [
"def",
"baseimage",
"(",
"self",
",",
"new_image",
")",
":",
"images",
"=",
"self",
".",
"parent_images",
"or",
"[",
"None",
"]",
"images",
"[",
"-",
"1",
"]",
"=",
"new_image",
"self",
".",
"parent_images",
"=",
"images"
] | 30.714286 | 0.00905 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.