text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def enabled(self):
"""
read or write the child sub-reaper flag of the current process
This property behaves in the following manner:
* If a read is attempted and a prior read or write has determined that
this feature is unavailable (status is equal to ``SR_UNSUPPORTED``)
... | [
"def",
"enabled",
"(",
"self",
")",
":",
"if",
"self",
".",
"_status",
"==",
"self",
".",
"SR_UNSUPPORTED",
":",
"return",
"False",
"status",
"=",
"c_int",
"(",
")",
"try",
":",
"prctl",
"(",
"PR_GET_CHILD_SUBREAPER",
",",
"addressof",
"(",
"status",
")"... | 53.780488 | 0.000891 |
def regs_group(self, regs, regs_aggregates=None):
"""
*Wrapper of* ``GROUP``
Group operation only for region data. For further information check :meth:`~.group`
"""
return self.group(regs=regs, regs_aggregates=regs_aggregates) | [
"def",
"regs_group",
"(",
"self",
",",
"regs",
",",
"regs_aggregates",
"=",
"None",
")",
":",
"return",
"self",
".",
"group",
"(",
"regs",
"=",
"regs",
",",
"regs_aggregates",
"=",
"regs_aggregates",
")"
] | 37.285714 | 0.011236 |
def loop(*, seconds=0, minutes=0, hours=0, count=None, reconnect=True, loop=None):
"""A decorator that schedules a task in the background for you with
optional reconnect logic.
Parameters
------------
seconds: :class:`float`
The number of seconds between every iteration.
minutes: :class... | [
"def",
"loop",
"(",
"*",
",",
"seconds",
"=",
"0",
",",
"minutes",
"=",
"0",
",",
"hours",
"=",
"0",
",",
"count",
"=",
"None",
",",
"reconnect",
"=",
"True",
",",
"loop",
"=",
"None",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"retur... | 34.128205 | 0.002191 |
def slots(self):
"""Get all the slots for this node.
:returns: The names of slots for this class.
If the class doesn't define any slot, through the ``__slots__``
variable, then this function will return a None.
Also, it will return None in the case the slots were not... | [
"def",
"slots",
"(",
"self",
")",
":",
"def",
"grouped_slots",
"(",
")",
":",
"# Not interested in object, since it can't have slots.",
"for",
"cls",
"in",
"self",
".",
"mro",
"(",
")",
"[",
":",
"-",
"1",
"]",
":",
"try",
":",
"cls_slots",
"=",
"cls",
"... | 34.1875 | 0.001778 |
def import_table(self, table):
"""import table by Table object
:param `manager.table_conf.Table` table: Table object
"""
file_path = os.path.join(self.pyctd_data_dir, table.file_name)
log.info('importing %s data into table %s', file_path, table.name)
table_import... | [
"def",
"import_table",
"(",
"self",
",",
"table",
")",
":",
"file_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"pyctd_data_dir",
",",
"table",
".",
"file_name",
")",
"log",
".",
"info",
"(",
"'importing %s data into table %s'",
",",
"file_... | 42.086957 | 0.008081 |
def do_ping(self, line):
"""ping [base-url ...] Check if a server responds to the DataONE ping() API
method ping (no arguments): Ping the CN and MN that is specified in the session
ping <base-url> [base-url ...]: Ping each CN or MN.
If an incomplete base-url is provided, default CN and ... | [
"def",
"do_ping",
"(",
"self",
",",
"line",
")",
":",
"hosts",
"=",
"self",
".",
"_split_args",
"(",
"line",
",",
"0",
",",
"99",
",",
"pad",
"=",
"False",
")",
"self",
".",
"_command_processor",
".",
"ping",
"(",
"hosts",
")"
] | 43 | 0.010352 |
def makePlot(args):
"""
Make the plot with parallax horizons. The plot shows V-band magnitude vs distance for a number of
spectral types and over the range 5.7<G<20. In addition a set of crudely drawn contours show the points
where 0.1, 1, and 10 per cent relative parallax accracy are reached.
Parameters
-... | [
"def",
"makePlot",
"(",
"args",
")",
":",
"distances",
"=",
"10.0",
"**",
"np",
".",
"linspace",
"(",
"1",
",",
"6",
",",
"10001",
")",
"av",
"=",
"args",
"[",
"'extinction'",
"]",
"ai",
"=",
"0.479",
"*",
"av",
"#Cardelli et al R=3.1",
"spts",
"=",
... | 38.431373 | 0.032082 |
def _is_enum_class(node: astroid.ClassDef) -> bool:
"""Check if a class definition defines an Enum class.
:param node: The class node to check.
:type node: astroid.ClassDef
:returns: True if the given node represents an Enum class. False otherwise.
:rtype: bool
"""
for base in node.bases:
... | [
"def",
"_is_enum_class",
"(",
"node",
":",
"astroid",
".",
"ClassDef",
")",
"->",
"bool",
":",
"for",
"base",
"in",
"node",
".",
"bases",
":",
"try",
":",
"inferred_bases",
"=",
"base",
".",
"inferred",
"(",
")",
"except",
"astroid",
".",
"InferenceError... | 28.782609 | 0.001462 |
def import_from_xlsx(
filename_or_fobj,
sheet_name=None,
sheet_index=0,
start_row=None,
start_column=None,
end_row=None,
end_column=None,
workbook_kwargs=None,
*args,
**kwargs
):
"""Return a rows.Table created from imported XLSX file.
workbook_kwargs will be passed to op... | [
"def",
"import_from_xlsx",
"(",
"filename_or_fobj",
",",
"sheet_name",
"=",
"None",
",",
"sheet_index",
"=",
"0",
",",
"start_row",
"=",
"None",
",",
"start_column",
"=",
"None",
",",
"end_row",
"=",
"None",
",",
"end_column",
"=",
"None",
",",
"workbook_kwa... | 37.875 | 0.000919 |
def draw(self, cr, highlight=False, bounding=None):
"""Draw this shape with the given cairo context"""
if bounding is None or self._intersects(bounding):
self._draw(cr, highlight, bounding) | [
"def",
"draw",
"(",
"self",
",",
"cr",
",",
"highlight",
"=",
"False",
",",
"bounding",
"=",
"None",
")",
":",
"if",
"bounding",
"is",
"None",
"or",
"self",
".",
"_intersects",
"(",
"bounding",
")",
":",
"self",
".",
"_draw",
"(",
"cr",
",",
"highl... | 53.5 | 0.009217 |
def addSuccess(self, test, capt=None):
"""Called when a test passes."""
time_taken = self._register_time(test, 'success')
if self.timer_fail is not None and time_taken * 1000.0 > self.threshold:
test.fail('Test was too slow (took {0:0.4f}s, threshold was '
'{1:0... | [
"def",
"addSuccess",
"(",
"self",
",",
"test",
",",
"capt",
"=",
"None",
")",
":",
"time_taken",
"=",
"self",
".",
"_register_time",
"(",
"test",
",",
"'success'",
")",
"if",
"self",
".",
"timer_fail",
"is",
"not",
"None",
"and",
"time_taken",
"*",
"10... | 61.166667 | 0.008065 |
def color( self, name, colorGroup = None ):
"""
Returns the color for the given name at the inputed group. If no \
group is specified, the first group in the list is used.
:param name | <str>
colorGroup | <str> || None
:retu... | [
"def",
"color",
"(",
"self",
",",
"name",
",",
"colorGroup",
"=",
"None",
")",
":",
"if",
"(",
"not",
"colorGroup",
"and",
"self",
".",
"_colorGroups",
")",
":",
"colorGroup",
"=",
"self",
".",
"_colorGroups",
"[",
"0",
"]",
"if",
"(",
"not",
"colorG... | 34.411765 | 0.023295 |
def atFontFace(self, declarations):
"""
Embed fonts
"""
result = self.ruleset([self.selector('*')], declarations)
data = list(result[0].values())[0]
if "src" not in data:
# invalid - source is required, ignore this specification
return {}, {}
... | [
"def",
"atFontFace",
"(",
"self",
",",
"declarations",
")",
":",
"result",
"=",
"self",
".",
"ruleset",
"(",
"[",
"self",
".",
"selector",
"(",
"'*'",
")",
"]",
",",
"declarations",
")",
"data",
"=",
"list",
"(",
"result",
"[",
"0",
"]",
".",
"valu... | 33.394737 | 0.002297 |
async def add_unit(self, count=1, to=None):
"""Add one or more units to this application.
:param int count: Number of units to add
:param str to: Placement directive, e.g.::
'23' - machine 23
'lxc:7' - new lxc container on machine 7
'24/lxc/3' - lxc container... | [
"async",
"def",
"add_unit",
"(",
"self",
",",
"count",
"=",
"1",
",",
"to",
"=",
"None",
")",
":",
"app_facade",
"=",
"client",
".",
"ApplicationFacade",
".",
"from_connection",
"(",
"self",
".",
"connection",
")",
"log",
".",
"debug",
"(",
"'Adding %s u... | 32.642857 | 0.002125 |
def area(self, x=None, y=None, **kwds):
"""
Draw a stacked area plot.
An area plot displays quantitative data visually.
This function wraps the matplotlib area function.
Parameters
----------
x : label or position, optional
Coordinates for the X axis... | [
"def",
"area",
"(",
"self",
",",
"x",
"=",
"None",
",",
"y",
"=",
"None",
",",
"*",
"*",
"kwds",
")",
":",
"return",
"self",
"(",
"kind",
"=",
"'area'",
",",
"x",
"=",
"x",
",",
"y",
"=",
"y",
",",
"*",
"*",
"kwds",
")"
] | 29.444444 | 0.000913 |
def forward(self, x):
"""
Args:
x (:class:`torch.FloatTensor` [batch size, sequence length, rnn hidden size]): Input to
apply dropout too.
"""
if not self.training or not self.p:
return x
x = x.clone()
mask = x.new_empty(1, x.size(1... | [
"def",
"forward",
"(",
"self",
",",
"x",
")",
":",
"if",
"not",
"self",
".",
"training",
"or",
"not",
"self",
".",
"p",
":",
"return",
"x",
"x",
"=",
"x",
".",
"clone",
"(",
")",
"mask",
"=",
"x",
".",
"new_empty",
"(",
"1",
",",
"x",
".",
... | 35.307692 | 0.008493 |
def open(self):
"""init the checkers: reset linesets and statistics information"""
self.linesets = []
self.stats = self.linter.add_stats(
nb_duplicated_lines=0, percent_duplicated_lines=0
) | [
"def",
"open",
"(",
"self",
")",
":",
"self",
".",
"linesets",
"=",
"[",
"]",
"self",
".",
"stats",
"=",
"self",
".",
"linter",
".",
"add_stats",
"(",
"nb_duplicated_lines",
"=",
"0",
",",
"percent_duplicated_lines",
"=",
"0",
")"
] | 38 | 0.008584 |
def run(self, *args, **kwargs):
"""Update the cache of all DNS entries and perform checks
Args:
*args: Optional list of arguments
**kwargs: Optional list of keyword arguments
Returns:
None
"""
try:
zones = list(DNSZone.get_all().v... | [
"def",
"run",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"zones",
"=",
"list",
"(",
"DNSZone",
".",
"get_all",
"(",
")",
".",
"values",
"(",
")",
")",
"buckets",
"=",
"{",
"k",
".",
"lower",
"(",
")",
":",
... | 38.180952 | 0.001945 |
def dist_factory(path_item, entry, only):
"""
Return a dist_factory for a path_item and entry
"""
lower = entry.lower()
is_meta = any(map(lower.endswith, ('.egg-info', '.dist-info')))
return (
distributions_from_metadata
if is_meta else
find_distributions
if not o... | [
"def",
"dist_factory",
"(",
"path_item",
",",
"entry",
",",
"only",
")",
":",
"lower",
"=",
"entry",
".",
"lower",
"(",
")",
"is_meta",
"=",
"any",
"(",
"map",
"(",
"lower",
".",
"endswith",
",",
"(",
"'.egg-info'",
",",
"'.dist-info'",
")",
")",
")"... | 29.6 | 0.002183 |
async def add_key(request: web.Request) -> web.Response:
""" Add a key file (for later use in EAP config) to the system.
```
POST /wifi/keys Content-Type: multipart/form-data,
Body:
file field named 'key'
```
returns
```
201 Created
{
uri: '/wifi/keys/some-hex-digest',
... | [
"async",
"def",
"add_key",
"(",
"request",
":",
"web",
".",
"Request",
")",
"->",
"web",
".",
"Response",
":",
"keys_dir",
"=",
"CONFIG",
"[",
"'wifi_keys_dir'",
"]",
"if",
"not",
"request",
".",
"can_read_body",
":",
"return",
"web",
".",
"json_response",... | 30.80597 | 0.000469 |
def Record(self, value):
"""Records given value."""
self.sum += value
self.count += 1
pos = bisect.bisect(self.bins, value) - 1
if pos < 0:
pos = 0
elif pos == len(self.bins):
pos = len(self.bins) - 1
self.heights[pos] += 1 | [
"def",
"Record",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"sum",
"+=",
"value",
"self",
".",
"count",
"+=",
"1",
"pos",
"=",
"bisect",
".",
"bisect",
"(",
"self",
".",
"bins",
",",
"value",
")",
"-",
"1",
"if",
"pos",
"<",
"0",
":",
... | 21.166667 | 0.011321 |
def static(self, uri, file_or_directory, pattern=r'/?.+',
use_modified_since=True, use_content_range=False):
'''Register a root to serve files from. The input can either be a
file or a directory. See
'''
static_register(self, uri, file_or_directory, pattern,
... | [
"def",
"static",
"(",
"self",
",",
"uri",
",",
"file_or_directory",
",",
"pattern",
"=",
"r'/?.+'",
",",
"use_modified_since",
"=",
"True",
",",
"use_content_range",
"=",
"False",
")",
":",
"static_register",
"(",
"self",
",",
"uri",
",",
"file_or_directory",
... | 51.714286 | 0.008152 |
def _flatten_tree(tree, old_path=None):
"""Flatten dict tree into dictionary where keys are paths of old dict."""
flat_tree = []
for key, value in tree.items():
new_path = "/".join([old_path, key]) if old_path else key
if isinstance(value, dict) and "format" not in value:
flat_tr... | [
"def",
"_flatten_tree",
"(",
"tree",
",",
"old_path",
"=",
"None",
")",
":",
"flat_tree",
"=",
"[",
"]",
"for",
"key",
",",
"value",
"in",
"tree",
".",
"items",
"(",
")",
":",
"new_path",
"=",
"\"/\"",
".",
"join",
"(",
"[",
"old_path",
",",
"key",... | 44.4 | 0.002208 |
def open_las(source, closefd=True):
""" Opens and reads the header of the las content in the source
>>> with open_las('pylastests/simple.las') as f:
... print(f.header.point_format_id)
3
>>> f = open('pylastests/simple.las', mode='rb')
>>> with open_las(f, closefd=Fals... | [
"def",
"open_las",
"(",
"source",
",",
"closefd",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"source",
",",
"str",
")",
":",
"stream",
"=",
"open",
"(",
"source",
",",
"mode",
"=",
"\"rb\"",
")",
"if",
"not",
"closefd",
":",
"raise",
"ValueError... | 28.170213 | 0.00073 |
def _mac(model, obs, h):
"""Forward pass of the multi-agent controller.
Arguments:
model: TorchModel class
obs: Tensor of shape [B, n_agents, obs_size]
h: List of tensors of shape [B, n_agents, h_size]
Returns:
q_vals: Tensor of shape [B, n_agents, n_actions]
h: Ten... | [
"def",
"_mac",
"(",
"model",
",",
"obs",
",",
"h",
")",
":",
"B",
",",
"n_agents",
"=",
"obs",
".",
"size",
"(",
"0",
")",
",",
"obs",
".",
"size",
"(",
"1",
")",
"obs_flat",
"=",
"obs",
".",
"reshape",
"(",
"[",
"B",
"*",
"n_agents",
",",
... | 36.722222 | 0.001475 |
def execute_project_models_sql_scripts(force_update=False):
"""
Used to get project information from MinC database
and convert to this application Project models.
Uses bulk_create if database is clean
"""
# TODO: Remove except and use ignore_conflicts
# on bulk_create when django... | [
"def",
"execute_project_models_sql_scripts",
"(",
"force_update",
"=",
"False",
")",
":",
"# TODO: Remove except and use ignore_conflicts",
"# on bulk_create when django 2.2. is released",
"with",
"open",
"(",
"MODEL_FILE",
",",
"\"r\"",
")",
"as",
"file_content",
":",
"query... | 46.606061 | 0.000637 |
def set_panel_label(label, ax=None, x=0.05, y=0.9):
"""Add a panel label to the figure/axes, by default in the top-left corner
Parameters
----------
label : str
text to be added as panel label
ax : matplotlib.Axes, optional
panel to which to add the panel label
x : number, defau... | [
"def",
"set_panel_label",
"(",
"label",
",",
"ax",
"=",
"None",
",",
"x",
"=",
"0.05",
",",
"y",
"=",
"0.9",
")",
":",
"def",
"_lim_loc",
"(",
"lim",
",",
"loc",
")",
":",
"return",
"lim",
"[",
"0",
"]",
"+",
"(",
"lim",
"[",
"1",
"]",
"-",
... | 33.142857 | 0.001397 |
def log(self, logfile=None):
"""Log the ASCII traceback into a file object."""
if logfile is None:
logfile = sys.stderr
tb = self.plaintext.rstrip() + u"\n"
logfile.write(to_native(tb, "utf-8", "replace")) | [
"def",
"log",
"(",
"self",
",",
"logfile",
"=",
"None",
")",
":",
"if",
"logfile",
"is",
"None",
":",
"logfile",
"=",
"sys",
".",
"stderr",
"tb",
"=",
"self",
".",
"plaintext",
".",
"rstrip",
"(",
")",
"+",
"u\"\\n\"",
"logfile",
".",
"write",
"(",... | 40.666667 | 0.008032 |
def set_connect_args(self, dsn=None, **connect_kwargs):
r"""Set the new connection arguments for this pool.
The new connection arguments will be used for all subsequent
new connection attempts. Existing connections will remain until
they expire. Use :meth:`Pool.expire_connections()
... | [
"def",
"set_connect_args",
"(",
"self",
",",
"dsn",
"=",
"None",
",",
"*",
"*",
"connect_kwargs",
")",
":",
"self",
".",
"_connect_args",
"=",
"[",
"dsn",
"]",
"self",
".",
"_connect_kwargs",
"=",
"connect_kwargs",
"self",
".",
"_working_addr",
"=",
"None"... | 36.461538 | 0.002055 |
def request(self, *args, **kwargs):
""" Partial original request func and run it in a thread. """
func = partial(super().request, *args, **kwargs)
return self.loop.run_in_executor(self.thread_pool, func) | [
"def",
"request",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"func",
"=",
"partial",
"(",
"super",
"(",
")",
".",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"loop",
".",
"run_in_execut... | 56 | 0.008811 |
def delete_asset(self, asset_id=None):
"""Deletes an ``Asset``.
arg: asset_id (osid.id.Id): the ``Id`` of the ``Asset`` to
remove
raise: NotFound - ``asset_id`` not found
raise: NullArgument - ``asset_id`` is ``null``
raise: OperationFailed - unable to comp... | [
"def",
"delete_asset",
"(",
"self",
",",
"asset_id",
"=",
"None",
")",
":",
"# Implemented from awsosid template for -",
"# osid.resource.ResourceAdminSession.delete_resource_template",
"# clean up AWS",
"asset",
"=",
"self",
".",
"_asset_lookup_session",
".",
"get_asset",
"(... | 42.105263 | 0.002445 |
def ReduceOpacity(im, opacity):
"""Reduces Opacity.
Returns an image with reduced opacity.
Taken from http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/362879
"""
assert opacity >= 0 and opacity <= 1
if isalpha(im):
im = im.copy()
else:
im = im.convert('RGBA')
alp... | [
"def",
"ReduceOpacity",
"(",
"im",
",",
"opacity",
")",
":",
"assert",
"opacity",
">=",
"0",
"and",
"opacity",
"<=",
"1",
"if",
"isalpha",
"(",
"im",
")",
":",
"im",
"=",
"im",
".",
"copy",
"(",
")",
"else",
":",
"im",
"=",
"im",
".",
"convert",
... | 26.25 | 0.002299 |
def _determine_colorspace(self, colorspace=None, **kwargs):
"""Determine the colorspace from the supplied inputs.
Parameters
----------
colorspace : str, optional
Either 'rgb' or 'gray'.
"""
if colorspace is None:
# Must infer the colorspace from ... | [
"def",
"_determine_colorspace",
"(",
"self",
",",
"colorspace",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"colorspace",
"is",
"None",
":",
"# Must infer the colorspace from the image dimensions.",
"if",
"len",
"(",
"self",
".",
"shape",
")",
"<",
"... | 43.222222 | 0.001257 |
def _python2_load_cpkl(fpath):
"""
References:
https://stackoverflow.com/questions/41720952/unpickle-sklearn-tree-descisiontreeregressor-in-python-2-from-python3
"""
from lib2to3.fixes.fix_imports import MAPPING
import sys
import pickle
# MAPPING maps Python 2 names to Python 3 name... | [
"def",
"_python2_load_cpkl",
"(",
"fpath",
")",
":",
"from",
"lib2to3",
".",
"fixes",
".",
"fix_imports",
"import",
"MAPPING",
"import",
"sys",
"import",
"pickle",
"# MAPPING maps Python 2 names to Python 3 names. We want this in reverse.",
"REVERSE_MAPPING",
"=",
"{",
"}... | 33.413793 | 0.001003 |
def GetLabelFromFleetspeak(client_id):
"""Returns the primary GRR label to use for a fleetspeak client."""
res = fleetspeak_connector.CONN.outgoing.ListClients(
admin_pb2.ListClientsRequest(client_ids=[GRRIDToFleetspeakID(client_id)]))
if not res.clients or not res.clients[0].labels:
return fleetspeak_c... | [
"def",
"GetLabelFromFleetspeak",
"(",
"client_id",
")",
":",
"res",
"=",
"fleetspeak_connector",
".",
"CONN",
".",
"outgoing",
".",
"ListClients",
"(",
"admin_pb2",
".",
"ListClientsRequest",
"(",
"client_ids",
"=",
"[",
"GRRIDToFleetspeakID",
"(",
"client_id",
")... | 41.285714 | 0.015228 |
def getTypedValueOrException(self, row):
'Returns the properly-typed value for the given row at this column, or an Exception object.'
return wrapply(self.type, wrapply(self.getValue, row)) | [
"def",
"getTypedValueOrException",
"(",
"self",
",",
"row",
")",
":",
"return",
"wrapply",
"(",
"self",
".",
"type",
",",
"wrapply",
"(",
"self",
".",
"getValue",
",",
"row",
")",
")"
] | 67.333333 | 0.014706 |
def _load_plt(self, filename):
"""Initialize Grid from gOpenMol plt file."""
g = gOpenMol.Plt()
g.read(filename)
grid, edges = g.histogramdd()
self.__init__(grid=grid, edges=edges, metadata=self.metadata) | [
"def",
"_load_plt",
"(",
"self",
",",
"filename",
")",
":",
"g",
"=",
"gOpenMol",
".",
"Plt",
"(",
")",
"g",
".",
"read",
"(",
"filename",
")",
"grid",
",",
"edges",
"=",
"g",
".",
"histogramdd",
"(",
")",
"self",
".",
"__init__",
"(",
"grid",
"=... | 39.833333 | 0.008197 |
def image_preprocessing(image_buffer, bbox, train, thread_id=0):
"""Decode and preprocess one image for evaluation or training.
Args:
image_buffer: JPEG encoded string Tensor
bbox: 3-D float Tensor of bounding boxes arranged [1, num_boxes, coords]
where each coordinate is [0, 1) and the coordinates a... | [
"def",
"image_preprocessing",
"(",
"image_buffer",
",",
"bbox",
",",
"train",
",",
"thread_id",
"=",
"0",
")",
":",
"if",
"bbox",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'Please supply a bounding box.'",
")",
"image",
"=",
"decode_jpeg",
"(",
"image_bu... | 29.757576 | 0.011834 |
def show(fig, width=600):
""" Renders a Matplotlib figure in Zeppelin.
:param fig: a Matplotlib figure
:param width: the width in pixel of the rendered figure, defaults to 600
Usage example::
import matplotlib.pyplot as plt
from moztelemetry.zeppelin import show
fig = plt.fig... | [
"def",
"show",
"(",
"fig",
",",
"width",
"=",
"600",
")",
":",
"img",
"=",
"StringIO",
"(",
")",
"fig",
".",
"savefig",
"(",
"img",
",",
"format",
"=",
"'svg'",
")",
"img",
".",
"seek",
"(",
"0",
")",
"print",
"(",
"\"%html <div style='width:{}px'>{}... | 26.736842 | 0.001901 |
def parse(handle, seqtype=None, robust=False):
'''Wrap SeqIO.parse'''
if seqtype is None:
seqtype = _get_seqtype_from_ext(handle)
if seqtype.startswith('gz-'):
handle = _unzip_handle(handle)
seqtype = seqtype[3:]
# False positive from pylint, both handles are fileobj-like
#... | [
"def",
"parse",
"(",
"handle",
",",
"seqtype",
"=",
"None",
",",
"robust",
"=",
"False",
")",
":",
"if",
"seqtype",
"is",
"None",
":",
"seqtype",
"=",
"_get_seqtype_from_ext",
"(",
"handle",
")",
"if",
"seqtype",
".",
"startswith",
"(",
"'gz-'",
")",
"... | 32.571429 | 0.00142 |
def delete_affinity_group(self, affinity_group_name):
'''
Deletes an affinity group in the specified subscription.
affinity_group_name:
The name of the affinity group.
'''
_validate_not_none('affinity_group_name', affinity_group_name)
return self._perform_del... | [
"def",
"delete_affinity_group",
"(",
"self",
",",
"affinity_group_name",
")",
":",
"_validate_not_none",
"(",
"'affinity_group_name'",
",",
"affinity_group_name",
")",
"return",
"self",
".",
"_perform_delete",
"(",
"'/'",
"+",
"self",
".",
"subscription_id",
"+",
"'... | 42.363636 | 0.008403 |
def prior_neighbor(C, alpha=0.001):
r"""Neighbor prior of strength alpha for the given count matrix.
Prior is defined by
b_ij = alpha if Z_ij+Z_ji > 0
b_ij = 0 else
Parameters
----------
C : (M, M) scipy.sparse matrix
Count matrix
alpha : float (optional)
... | [
"def",
"prior_neighbor",
"(",
"C",
",",
"alpha",
"=",
"0.001",
")",
":",
"C_sym",
"=",
"C",
"+",
"C",
".",
"transpose",
"(",
")",
"C_sym",
"=",
"C_sym",
".",
"tocoo",
"(",
")",
"data",
"=",
"C_sym",
".",
"data",
"row",
"=",
"C_sym",
".",
"row",
... | 21.448276 | 0.001538 |
def coerce_to_target_dtype(self, other):
"""
coerce the current block to a dtype compat for other
we will return a block, possibly object, and not raise
we can also safely try to coerce to the same dtype
and will receive the same block
"""
# if we cannot then co... | [
"def",
"coerce_to_target_dtype",
"(",
"self",
",",
"other",
")",
":",
"# if we cannot then coerce to object",
"dtype",
",",
"_",
"=",
"infer_dtype_from",
"(",
"other",
",",
"pandas_dtype",
"=",
"True",
")",
"if",
"is_dtype_equal",
"(",
"self",
".",
"dtype",
",",... | 34.6 | 0.000937 |
def folderExist(self, name, folders):
"""Determines if a folder exists, case insensitively.
Args:
name (str): The name of the folder to check.
folders (list): A list of folder dicts to check against. The dicts must contain
the key:value pair ``title``.
... | [
"def",
"folderExist",
"(",
"self",
",",
"name",
",",
"folders",
")",
":",
"if",
"name",
"is",
"not",
"None",
"and",
"name",
"!=",
"''",
":",
"folderID",
"=",
"None",
"for",
"folder",
"in",
"folders",
":",
"if",
"folder",
"[",
"'title'",
"]",
".",
"... | 28.4 | 0.008174 |
def sendSomeData(self, howMany):
"""
Send some DATA commands to my peer(s) to relay some data.
@param howMany: an int, the number of chunks to send out.
"""
# print 'sending some data', howMany
if self.transport is None:
return
peer = self.transport.g... | [
"def",
"sendSomeData",
"(",
"self",
",",
"howMany",
")",
":",
"# print 'sending some data', howMany",
"if",
"self",
".",
"transport",
"is",
"None",
":",
"return",
"peer",
"=",
"self",
".",
"transport",
".",
"getQ2QPeer",
"(",
")",
"while",
"howMany",
">",
"0... | 36.54717 | 0.001006 |
def setup():
"""
Install handlers for Mitogen loggers to redirect them into the Ansible
display framework. Ansible installs its own logging framework handlers when
C.DEFAULT_LOG_PATH is set, therefore disable propagation for our handlers.
"""
l_mitogen = logging.getLogger('mitogen')
l_mitoge... | [
"def",
"setup",
"(",
")",
":",
"l_mitogen",
"=",
"logging",
".",
"getLogger",
"(",
"'mitogen'",
")",
"l_mitogen_io",
"=",
"logging",
".",
"getLogger",
"(",
"'mitogen.io'",
")",
"l_ansible_mitogen",
"=",
"logging",
".",
"getLogger",
"(",
"'ansible_mitogen'",
")... | 41.444444 | 0.000873 |
def _surpress_formatting_errors(fn):
"""
I know this is dangerous and the wrong way to solve the problem, but when
using both row and columns summaries it's easier to just swallow errors
so users can format their tables how they need.
"""
@wraps(fn)
def inner(*args, **kwargs):
try:
... | [
"def",
"_surpress_formatting_errors",
"(",
"fn",
")",
":",
"@",
"wraps",
"(",
"fn",
")",
"def",
"inner",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"try",
":",
"return",
"fn",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"except",
"V... | 31.615385 | 0.002364 |
def loglike(self, x, y):
"""Evaluate the 2-D log-likelihood in the x/y parameter space.
The dimension of the two input arrays should be the same.
Parameters
----------
x : array_like
Array of coordinates in the `x` parameter.
y : array_like
... | [
"def",
"loglike",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"nuis",
"=",
"self",
".",
"_nuis_pdf",
"(",
"y",
")",
"log_nuis",
"=",
"np",
".",
"where",
"(",
"nuis",
">",
"0.",
",",
"np",
".",
"log",
"(",
"nuis",
")",
",",
"-",
"1e2",
")",
"... | 30.789474 | 0.008292 |
def get_cassandra_connection(alias=None, name=None):
"""
:return: cassandra connection matching alias or name or just first found.
"""
for _alias, connection in get_cassandra_connections():
if alias is not None:
if alias == _alias:
return connection
elif name... | [
"def",
"get_cassandra_connection",
"(",
"alias",
"=",
"None",
",",
"name",
"=",
"None",
")",
":",
"for",
"_alias",
",",
"connection",
"in",
"get_cassandra_connections",
"(",
")",
":",
"if",
"alias",
"is",
"not",
"None",
":",
"if",
"alias",
"==",
"_alias",
... | 32.5 | 0.002137 |
def fitPlaneSVD(XYZ):
"""Fit a plane to input point data using SVD
"""
[rows,cols] = XYZ.shape
# Set up constraint equations of the form AB = 0,
# where B is a column vector of the plane coefficients
# in the form b(1)*X + b(2)*Y +b(3)*Z + b(4) = 0.
p = (np.ones((rows,1)))
AB = np.hstac... | [
"def",
"fitPlaneSVD",
"(",
"XYZ",
")",
":",
"[",
"rows",
",",
"cols",
"]",
"=",
"XYZ",
".",
"shape",
"# Set up constraint equations of the form AB = 0,",
"# where B is a column vector of the plane coefficients",
"# in the form b(1)*X + b(2)*Y +b(3)*Z + b(4) = 0.",
"p",
"=",
... | 33.571429 | 0.014493 |
def status(*args):
"""
Get the current status of the fragments repository, limited to FILENAME(s) if specified.
Limit output to files with status STATUS, if present.
"""
parser = argparse.ArgumentParser(prog="%s %s" % (__package__, status.__name__), description=status.__doc__)
parser.add_argumen... | [
"def",
"status",
"(",
"*",
"args",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"prog",
"=",
"\"%s %s\"",
"%",
"(",
"__package__",
",",
"status",
".",
"__name__",
")",
",",
"description",
"=",
"status",
".",
"__doc__",
")",
"parser",
... | 58.866667 | 0.008919 |
def get_distance_scaling_term(self, C, rhyp):
"""
Returns the distance scaling term (equation 1)
"""
rval = rhyp + C['bh']
return C['b5'] * np.log(rval) + C['b6'] * rval | [
"def",
"get_distance_scaling_term",
"(",
"self",
",",
"C",
",",
"rhyp",
")",
":",
"rval",
"=",
"rhyp",
"+",
"C",
"[",
"'bh'",
"]",
"return",
"C",
"[",
"'b5'",
"]",
"*",
"np",
".",
"log",
"(",
"rval",
")",
"+",
"C",
"[",
"'b6'",
"]",
"*",
"rval"... | 34 | 0.009569 |
def group_systems(self, group_name, systems):
"""
Adds an array of systems to specified group
Args:
group_name: Display name of group
systems: Array of {'machine_id': machine_id}
"""
api_group_id = None
headers = {'Content-Type': 'application/json... | [
"def",
"group_systems",
"(",
"self",
",",
"group_name",
",",
"systems",
")",
":",
"api_group_id",
"=",
"None",
"headers",
"=",
"{",
"'Content-Type'",
":",
"'application/json'",
"}",
"group_path",
"=",
"self",
".",
"api_url",
"+",
"'/v1/groups'",
"group_get_path"... | 44.309524 | 0.001052 |
def getDistances(self, inputPattern):
"""Return the distances between the input pattern and all other
stored patterns.
:param inputPattern: pattern to check distance with
:returns: (distances, categories) numpy arrays of the same length.
- overlaps: an integer overlap amount for each category
... | [
"def",
"getDistances",
"(",
"self",
",",
"inputPattern",
")",
":",
"dist",
"=",
"self",
".",
"_getDistances",
"(",
"inputPattern",
")",
"return",
"(",
"dist",
",",
"self",
".",
"_categoryList",
")"
] | 38.75 | 0.002101 |
def deleteMetadata(self, remote, address, key):
"""Delete metadata of device"""
try:
return self.proxies["%s-%s" % (self._interface_id, remote)].deleteMetadata(address, key)
except Exception as err:
LOG.debug("ServerThread.deleteMetadata: Exception: %s" % str(err)) | [
"def",
"deleteMetadata",
"(",
"self",
",",
"remote",
",",
"address",
",",
"key",
")",
":",
"try",
":",
"return",
"self",
".",
"proxies",
"[",
"\"%s-%s\"",
"%",
"(",
"self",
".",
"_interface_id",
",",
"remote",
")",
"]",
".",
"deleteMetadata",
"(",
"add... | 51.333333 | 0.009585 |
def _cert_array_from_pem(pem_bundle):
"""
Given a bundle of certs in PEM format, turns them into a CFArray of certs
that can be used to validate a cert chain.
"""
# Normalize the PEM bundle's line endings.
pem_bundle = pem_bundle.replace(b"\r\n", b"\n")
der_certs = [
base64.b64decod... | [
"def",
"_cert_array_from_pem",
"(",
"pem_bundle",
")",
":",
"# Normalize the PEM bundle's line endings.",
"pem_bundle",
"=",
"pem_bundle",
".",
"replace",
"(",
"b\"\\r\\n\"",
",",
"b\"\\n\"",
")",
"der_certs",
"=",
"[",
"base64",
".",
"b64decode",
"(",
"match",
".",... | 34.795455 | 0.000635 |
def del_subkey(self,name):
"""Delete the named subkey, and any values or keys it contains."""
self.sam |= KEY_WRITE
subkey = self.get_subkey(name)
subkey.clear()
_winreg.DeleteKey(subkey.parent.hkey,subkey.name) | [
"def",
"del_subkey",
"(",
"self",
",",
"name",
")",
":",
"self",
".",
"sam",
"|=",
"KEY_WRITE",
"subkey",
"=",
"self",
".",
"get_subkey",
"(",
"name",
")",
"subkey",
".",
"clear",
"(",
")",
"_winreg",
".",
"DeleteKey",
"(",
"subkey",
".",
"parent",
"... | 41 | 0.015936 |
def fermi_fourier_trans_2(p, q):
"""The 2-mode fermionic Fourier transformation can be implemented
straightforwardly by the √iSWAP gate. The √iSWAP gate can be readily
implemented with the gmon qubits using the XX + YY Hamiltonian. The matrix
representation of the 2-qubit fermionic Fourier transformatio... | [
"def",
"fermi_fourier_trans_2",
"(",
"p",
",",
"q",
")",
":",
"yield",
"cirq",
".",
"Z",
"(",
"p",
")",
"**",
"1.5",
"yield",
"cirq",
".",
"ISWAP",
"(",
"q",
",",
"p",
")",
"**",
"0.5",
"yield",
"cirq",
".",
"Z",
"(",
"p",
")",
"**",
"1.5"
] | 30.956522 | 0.001362 |
def _ReadCompressedData(self, read_size):
"""Reads compressed data from the file-like object.
Args:
read_size (int): number of bytes of compressed data to read.
Returns:
int: number of bytes of compressed data read.
"""
compressed_data = self._file_object.read(read_size)
read_coun... | [
"def",
"_ReadCompressedData",
"(",
"self",
",",
"read_size",
")",
":",
"compressed_data",
"=",
"self",
".",
"_file_object",
".",
"read",
"(",
"read_size",
")",
"read_count",
"=",
"len",
"(",
"compressed_data",
")",
"self",
".",
"_compressed_data",
"=",
"b''",
... | 29.047619 | 0.001587 |
def _add_arguments(param, parser, used_char_args, add_nos):
'''
Add the argument(s) to an ArgumentParser (using add_argument) for a given
parameter. used_char_args is the set of -short options currently already in
use, and is updated (if necessary) by this function. If add_nos is True,
this will als... | [
"def",
"_add_arguments",
"(",
"param",
",",
"parser",
",",
"used_char_args",
",",
"add_nos",
")",
":",
"# Impl note: This function is kept separate from make_parser because it's",
"# already very long and I wanted to separate out as much as possible into",
"# its own call scope, to preve... | 33.773585 | 0.000271 |
def search_files(source: str, extensions: List[str]) -> List[Path]:
"""Retrieve files located the source directory and its subdirectories,
whose extension match one of the listed extensions.
:raise GuesslangError: when there is not enough files in the directory
:param source: directory name
:param ... | [
"def",
"search_files",
"(",
"source",
":",
"str",
",",
"extensions",
":",
"List",
"[",
"str",
"]",
")",
"->",
"List",
"[",
"Path",
"]",
":",
"files",
"=",
"[",
"path",
"for",
"path",
"in",
"Path",
"(",
"source",
")",
".",
"glob",
"(",
"'**/*'",
"... | 37.26087 | 0.001138 |
def logout(self):
"""Log out of the account."""
self._master_token = None
self._auth_token = None
self._email = None
self._android_id = None | [
"def",
"logout",
"(",
"self",
")",
":",
"self",
".",
"_master_token",
"=",
"None",
"self",
".",
"_auth_token",
"=",
"None",
"self",
".",
"_email",
"=",
"None",
"self",
".",
"_android_id",
"=",
"None"
] | 29.166667 | 0.011111 |
def _build_gadgets(self, gadget_tree_root):
"""Return a gadgets list.
"""
node_list = self._build_gadgets_rec(gadget_tree_root)
return [RawGadget(n) for n in node_list] | [
"def",
"_build_gadgets",
"(",
"self",
",",
"gadget_tree_root",
")",
":",
"node_list",
"=",
"self",
".",
"_build_gadgets_rec",
"(",
"gadget_tree_root",
")",
"return",
"[",
"RawGadget",
"(",
"n",
")",
"for",
"n",
"in",
"node_list",
"]"
] | 32.666667 | 0.00995 |
def get_component_product(self, other):
"""Returns the component product of this vector and the given
other vector."""
return Point(self.x * other.x, self.y * other.y) | [
"def",
"get_component_product",
"(",
"self",
",",
"other",
")",
":",
"return",
"Point",
"(",
"self",
".",
"x",
"*",
"other",
".",
"x",
",",
"self",
".",
"y",
"*",
"other",
".",
"y",
")"
] | 47 | 0.010471 |
def run_app(app: Union[Application, Awaitable[Application]], *,
host: Optional[str]=None,
port: Optional[int]=None,
path: Optional[str]=None,
sock: Optional[socket.socket]=None,
shutdown_timeout: float=60.0,
ssl_context: Optional[SSLContext]=None,
... | [
"def",
"run_app",
"(",
"app",
":",
"Union",
"[",
"Application",
",",
"Awaitable",
"[",
"Application",
"]",
"]",
",",
"*",
",",
"host",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"port",
":",
"Optional",
"[",
"int",
"]",
"=",
"None",
",",
... | 48.625 | 0.01218 |
def get_comments_by_search(self, comment_query, comment_search):
"""Pass through to provider CommentSearchSession.get_comments_by_search"""
# Implemented from azosid template for -
# osid.resource.ResourceSearchSession.get_resources_by_search_template
if not self._can('search'):
... | [
"def",
"get_comments_by_search",
"(",
"self",
",",
"comment_query",
",",
"comment_search",
")",
":",
"# Implemented from azosid template for -",
"# osid.resource.ResourceSearchSession.get_resources_by_search_template",
"if",
"not",
"self",
".",
"_can",
"(",
"'search'",
")",
"... | 62 | 0.009091 |
def parse_tz(tz):
"""Parse a timezone specification in the [+|-]HHMM format.
:return: the timezone offset in seconds.
"""
# from git_repository.py in bzr-git
sign_byte = tz[0:1]
# in python 3 b'+006'[0] would return an integer,
# but b'+006'[0:1] return a new bytes string.
if sign_byte ... | [
"def",
"parse_tz",
"(",
"tz",
")",
":",
"# from git_repository.py in bzr-git",
"sign_byte",
"=",
"tz",
"[",
"0",
":",
"1",
"]",
"# in python 3 b'+006'[0] would return an integer,",
"# but b'+006'[0:1] return a new bytes string.",
"if",
"sign_byte",
"not",
"in",
"(",
"b'+'... | 29.235294 | 0.001949 |
def join(self, ignore_errors=False):
"""Waits until last executed command completed."""
assert self._status_fn, "Asked to join a task which hasn't had any commands executed on it"
check_interval = 0.2
status_fn = self._status_fn
if not self.wait_for_file(status_fn, max_wait_sec=30):
self.log(f... | [
"def",
"join",
"(",
"self",
",",
"ignore_errors",
"=",
"False",
")",
":",
"assert",
"self",
".",
"_status_fn",
",",
"\"Asked to join a task which hasn't had any commands executed on it\"",
"check_interval",
"=",
"0.2",
"status_fn",
"=",
"self",
".",
"_status_fn",
"if"... | 40.354839 | 0.009368 |
def run(command, input=None, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
timeout=None, copy_local_env=False, **kwargs):
"""
Cross platform compatible subprocess with CompletedProcess return.
No formatting or encoding is performed on the output of subprocess, so it's
output will appear the s... | [
"def",
"run",
"(",
"command",
",",
"input",
"=",
"None",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
",",
"timeout",
"=",
"None",
",",
"copy_local_env",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":"... | 42.8375 | 0.00057 |
def project(self, other):
"""Return one vector projected on the vector other"""
n = other.normalized()
return self.dot(n) * n | [
"def",
"project",
"(",
"self",
",",
"other",
")",
":",
"n",
"=",
"other",
".",
"normalized",
"(",
")",
"return",
"self",
".",
"dot",
"(",
"n",
")",
"*",
"n"
] | 36.5 | 0.013423 |
def is_path_python_module(thepath):
"""
Given a path, find out of the path is a python module or is inside
a python module.
"""
thepath = path.normpath(thepath)
if path.isfile(thepath):
base, ext = path.splitext(thepath)
if ext in _py_suffixes:
return True
... | [
"def",
"is_path_python_module",
"(",
"thepath",
")",
":",
"thepath",
"=",
"path",
".",
"normpath",
"(",
"thepath",
")",
"if",
"path",
".",
"isfile",
"(",
"thepath",
")",
":",
"base",
",",
"ext",
"=",
"path",
".",
"splitext",
"(",
"thepath",
")",
"if",
... | 27.888889 | 0.001927 |
def smtp_handler(name, logname, mailhost, fromaddr, toaddrs, subject,
credentials=None):
"""
A Bark logging handler logging output via SMTP. To specify a
non-standard SMTP port, use the "host:port" format. To specify
multiple "To" addresses, separate them with commas. To specify
... | [
"def",
"smtp_handler",
"(",
"name",
",",
"logname",
",",
"mailhost",
",",
"fromaddr",
",",
"toaddrs",
",",
"subject",
",",
"credentials",
"=",
"None",
")",
":",
"return",
"wrap_log_handler",
"(",
"logging",
".",
"handlers",
".",
"SMTPHandler",
"(",
"mailhost... | 42.307692 | 0.001779 |
def do_interact(self, arg):
"""interact
Start an interative interpreter whose global namespace
contains all the (global and local) names found in the current scope.
"""
def readfunc(prompt):
self.stdout.write(prompt)
self.stdout.flush()
line =... | [
"def",
"do_interact",
"(",
"self",
",",
"arg",
")",
":",
"def",
"readfunc",
"(",
"prompt",
")",
":",
"self",
".",
"stdout",
".",
"write",
"(",
"prompt",
")",
"self",
".",
"stdout",
".",
"flush",
"(",
")",
"line",
"=",
"self",
".",
"stdin",
".",
"... | 35.758621 | 0.001878 |
def calc_gamma_from_position_autocorrelation_fit(self, GammaGuess=None, FreqTrapGuess=None, silent=False, MakeFig=True, show_fig=True):
"""
Calculates the total damping, i.e. Gamma, by calculating the autocorrleation
of the position-time trace. The autocorrelation is fitted with an exponential ... | [
"def",
"calc_gamma_from_position_autocorrelation_fit",
"(",
"self",
",",
"GammaGuess",
"=",
"None",
",",
"FreqTrapGuess",
"=",
"None",
",",
"silent",
"=",
"False",
",",
"MakeFig",
"=",
"True",
",",
"show_fig",
"=",
"True",
")",
":",
"autocorrelation",
"=",
"ca... | 43.071429 | 0.008106 |
def register_setting(name=None, label=None, editable=False, description=None,
default=None, choices=None, append=False,
translatable=False):
"""
Registers a setting that can be edited via the admin. This mostly
equates to storing the given args as a dict in the ``re... | [
"def",
"register_setting",
"(",
"name",
"=",
"None",
",",
"label",
"=",
"None",
",",
"editable",
"=",
"False",
",",
"description",
"=",
"None",
",",
"default",
"=",
"None",
",",
"choices",
"=",
"None",
",",
"append",
"=",
"False",
",",
"translatable",
... | 41.826923 | 0.000449 |
def send(sender_instance):
"""Send a transactional email using SendInBlue API.
Site: https://www.sendinblue.com
API: https://apidocs.sendinblue.com/
"""
m = Mailin(
"https://api.sendinblue.com/v2.0",
sender_instance._kwargs.get("api_key")
)
data = {
"to": email_list_... | [
"def",
"send",
"(",
"sender_instance",
")",
":",
"m",
"=",
"Mailin",
"(",
"\"https://api.sendinblue.com/v2.0\"",
",",
"sender_instance",
".",
"_kwargs",
".",
"get",
"(",
"\"api_key\"",
")",
")",
"data",
"=",
"{",
"\"to\"",
":",
"email_list_to_email_dict",
"(",
... | 38.032258 | 0.000827 |
def _rotations_to_disentangle(local_param):
"""
Static internal method to work out Ry and Rz rotation angles used
to disentangle the LSB qubit.
These rotations make up the block diagonal matrix U (i.e. multiplexor)
that disentangles the LSB.
[[Ry(theta_1).Rz(phi_1) 0 ... | [
"def",
"_rotations_to_disentangle",
"(",
"local_param",
")",
":",
"remaining_vector",
"=",
"[",
"]",
"thetas",
"=",
"[",
"]",
"phis",
"=",
"[",
"]",
"param_len",
"=",
"len",
"(",
"local_param",
")",
"for",
"i",
"in",
"range",
"(",
"param_len",
"//",
"2",... | 36.945946 | 0.002138 |
def add_table(self, t):
"""
remember to call pop_element after done with table
"""
self.push_element()
self._page.append(t.node)
self.cur_element = t | [
"def",
"add_table",
"(",
"self",
",",
"t",
")",
":",
"self",
".",
"push_element",
"(",
")",
"self",
".",
"_page",
".",
"append",
"(",
"t",
".",
"node",
")",
"self",
".",
"cur_element",
"=",
"t"
] | 27.285714 | 0.010152 |
def parse(self, arguments):
"""Parses one or more arguments with the installed parser.
Args:
arguments: a single argument or a list of arguments (typically a
list of default values); a single argument is converted
internally into a list containing one item.
"""
if not isinstance(a... | [
"def",
"parse",
"(",
"self",
",",
"arguments",
")",
":",
"if",
"not",
"isinstance",
"(",
"arguments",
",",
"list",
")",
":",
"# Default value may be a list of values. Most other arguments",
"# will not be, so convert them into a single-item list to make",
"# processing simpler... | 35.642857 | 0.011707 |
def main(argv=None):
"""
September 18, 2014: if an arg is passed, we visualize it
Otherwise a simple shell gets opened.
"""
print("Ontospy " + ontospy.VERSION)
ontospy.get_or_create_home_repo()
if argv:
print("Argument passing not implemented yet")
if False:
onto = Model(argv[0])
for x in onto.get_c... | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"print",
"(",
"\"Ontospy \"",
"+",
"ontospy",
".",
"VERSION",
")",
"ontospy",
".",
"get_or_create_home_repo",
"(",
")",
"if",
"argv",
":",
"print",
"(",
"\"Argument passing not implemented yet\"",
")",
"if",
... | 21.188679 | 0.041702 |
def next_interval(self, interval):
"""
Given a value of an interval, this function returns the
next interval value
"""
index = np.where(self.intervals == interval)
if index[0][0] + 1 < len(self.intervals):
return self.intervals[index[0][0] + 1]
else:
... | [
"def",
"next_interval",
"(",
"self",
",",
"interval",
")",
":",
"index",
"=",
"np",
".",
"where",
"(",
"self",
".",
"intervals",
"==",
"interval",
")",
"if",
"index",
"[",
"0",
"]",
"[",
"0",
"]",
"+",
"1",
"<",
"len",
"(",
"self",
".",
"interval... | 36.4 | 0.008043 |
def _correlate(self):
"""
Run correlation algorithm.
"""
a = self.algorithm(**self.algorithm_params)
self.correlation_result = a.run() | [
"def",
"_correlate",
"(",
"self",
")",
":",
"a",
"=",
"self",
".",
"algorithm",
"(",
"*",
"*",
"self",
".",
"algorithm_params",
")",
"self",
".",
"correlation_result",
"=",
"a",
".",
"run",
"(",
")"
] | 28.166667 | 0.011494 |
def _escape_token(token, alphabet):
r"""Replace characters that aren't in the alphabet and append "_" to token.
Apply three transformations to the token:
1. Replace underline character "_" with "\u", and backslash "\" with "\\".
2. Replace characters outside of the alphabet with "\###;", where ### is the
... | [
"def",
"_escape_token",
"(",
"token",
",",
"alphabet",
")",
":",
"token",
"=",
"token",
".",
"replace",
"(",
"u\"\\\\\"",
",",
"u\"\\\\\\\\\"",
")",
".",
"replace",
"(",
"u\"_\"",
",",
"u\"\\\\u\"",
")",
"ret",
"=",
"[",
"c",
"if",
"c",
"in",
"alphabet... | 36.157895 | 0.009929 |
def checkArgs(args):
"""Checks the arguments and options.
:param args: an object containing the options of the program.
:type args: argparse.Namespace
:returns: ``True`` if everything was OK.
If there is a problem with an option, an exception is raised using the
:py:class:`ProgramError` clas... | [
"def",
"checkArgs",
"(",
"args",
")",
":",
"# Check if we have the tped and the tfam files",
"for",
"fileName",
"in",
"[",
"args",
".",
"bfile",
"+",
"i",
"for",
"i",
"in",
"[",
"\".bed\"",
",",
"\".bim\"",
",",
"\".fam\"",
"]",
"]",
":",
"if",
"not",
"os"... | 31.884615 | 0.001171 |
def get_module_config(self, name):
"""
Return module configuration loaded from separate file or None
"""
if self.exists("modules"):
if name in self._json["modules"] and not isinstance(self._json["modules"][name], str):
return self._json["modules"][name]
return None | [
"def",
"get_module_config",
"(",
"self",
",",
"name",
")",
":",
"if",
"self",
".",
"exists",
"(",
"\"modules\"",
")",
":",
"if",
"name",
"in",
"self",
".",
"_json",
"[",
"\"modules\"",
"]",
"and",
"not",
"isinstance",
"(",
"self",
".",
"_json",
"[",
... | 36.625 | 0.01 |
def plot_gaussian_2D(mu, lmbda, color='b', centermarker=True,label='',alpha=1.,ax=None,artists=None):
'''
Plots mean and cov ellipsoid into current axes. Must be 2D. lmbda is a covariance matrix.
'''
assert len(mu) == 2
ax = ax if ax else plt.gca()
# TODO use artists!
t = np.hstack([np.ara... | [
"def",
"plot_gaussian_2D",
"(",
"mu",
",",
"lmbda",
",",
"color",
"=",
"'b'",
",",
"centermarker",
"=",
"True",
",",
"label",
"=",
"''",
",",
"alpha",
"=",
"1.",
",",
"ax",
"=",
"None",
",",
"artists",
"=",
"None",
")",
":",
"assert",
"len",
"(",
... | 35.857143 | 0.027158 |
def ssh_get_mic(self, session_id, gss_kex=False):
"""
Create the MIC token for a SSH2 message.
:param str session_id: The SSH session ID
:param bool gss_kex: Generate the MIC for Key Exchange with SSPI or not
:return: gssapi-with-mic:
Returns the MIC token from ... | [
"def",
"ssh_get_mic",
"(",
"self",
",",
"session_id",
",",
"gss_kex",
"=",
"False",
")",
":",
"self",
".",
"_session_id",
"=",
"session_id",
"if",
"not",
"gss_kex",
":",
"mic_field",
"=",
"self",
".",
"_ssh_build_mic",
"(",
"self",
".",
"_session_id",
",",... | 37.5 | 0.002 |
def create_component(self, module_name):
'''Create a component out of a loaded module.
Turns a previously-loaded shared module into a component in the
manager. This will invalidate any objects that are children of this
node.
The @ref module_name argument can contain options tha... | [
"def",
"create_component",
"(",
"self",
",",
"module_name",
")",
":",
"with",
"self",
".",
"_mutex",
":",
"if",
"not",
"self",
".",
"_obj",
".",
"create_component",
"(",
"module_name",
")",
":",
"raise",
"exceptions",
".",
"FailedToCreateComponentError",
"(",
... | 45.391304 | 0.001876 |
def _discover(self):
"""Find and install all extensions"""
for ep in pkg_resources.iter_entry_points('yamlsettings10'):
ext = ep.load()
if callable(ext):
ext = ext()
self.add(ext) | [
"def",
"_discover",
"(",
"self",
")",
":",
"for",
"ep",
"in",
"pkg_resources",
".",
"iter_entry_points",
"(",
"'yamlsettings10'",
")",
":",
"ext",
"=",
"ep",
".",
"load",
"(",
")",
"if",
"callable",
"(",
"ext",
")",
":",
"ext",
"=",
"ext",
"(",
")",
... | 34.428571 | 0.008097 |
def prune_anomalies(e_seq, smoothed_errors, max_error_below_e, anomaly_indices):
""" Helper method that removes anomalies which don't meet
a minimum separation from next anomaly.
"""
# min accepted perc decrease btwn max errors in anomalous sequences
MIN_PERCENT_DECREASE = 0.05
e_seq_max, sm... | [
"def",
"prune_anomalies",
"(",
"e_seq",
",",
"smoothed_errors",
",",
"max_error_below_e",
",",
"anomaly_indices",
")",
":",
"# min accepted perc decrease btwn max errors in anomalous sequences",
"MIN_PERCENT_DECREASE",
"=",
"0.05",
"e_seq_max",
",",
"smoothed_errors_max",
"=",
... | 36.263158 | 0.001413 |
def Write(self, grr_message):
"""Write the message into the transaction log."""
grr_message = grr_message.SerializeToString()
try:
with io.open(self.logfile, "wb") as fd:
fd.write(grr_message)
except (IOError, OSError):
# Check if we're missing directories and try to create them.
... | [
"def",
"Write",
"(",
"self",
",",
"grr_message",
")",
":",
"grr_message",
"=",
"grr_message",
".",
"SerializeToString",
"(",
")",
"try",
":",
"with",
"io",
".",
"open",
"(",
"self",
".",
"logfile",
",",
"\"wb\"",
")",
"as",
"fd",
":",
"fd",
".",
"wri... | 38.882353 | 0.01034 |
def created_hosted_zone_parser(root, connection):
"""
Parses the API responses for the
:py:meth:`route53.connection.Route53Connection.create_hosted_zone` method.
:param lxml.etree._Element root: The root node of the etree parsed
response from the API.
:param Route53Connection connection: Th... | [
"def",
"created_hosted_zone_parser",
"(",
"root",
",",
"connection",
")",
":",
"zone",
"=",
"root",
".",
"find",
"(",
"'./{*}HostedZone'",
")",
"# This pops out a HostedZone instance.",
"hosted_zone",
"=",
"parse_hosted_zone",
"(",
"zone",
",",
"connection",
")",
"#... | 37.6 | 0.000864 |
def read_text_from_cg3_file( file_name, layer_name=LAYER_VISLCG3, **kwargs ):
''' Reads the output of VISLCG3 syntactic analysis from given file, and
returns as a Text object.
The Text object has been tokenized for paragraphs, sentences, words, and it
contains syntactic analyses a... | [
"def",
"read_text_from_cg3_file",
"(",
"file_name",
",",
"layer_name",
"=",
"LAYER_VISLCG3",
",",
"*",
"*",
"kwargs",
")",
":",
"clean_up",
"=",
"False",
"for",
"argName",
",",
"argVal",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"if",
"argName",
"in",
... | 41.759615 | 0.013495 |
def time_restarts(data_path):
""" When called will create a file and measure its mtime on restarts """
path = os.path.join(data_path, 'last_restarted')
if not os.path.isfile(path):
with open(path, 'a'):
os.utime(path, None)
last_modified = os.stat(path).st_mtime
with open(path,... | [
"def",
"time_restarts",
"(",
"data_path",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"data_path",
",",
"'last_restarted'",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
":",
"with",
"open",
"(",
"path",
",",
... | 36 | 0.001592 |
def add2(self, target, path_settings, method):
"""
add() with reordered paameters
"""
return self.add(method, path_settings, target) | [
"def",
"add2",
"(",
"self",
",",
"target",
",",
"path_settings",
",",
"method",
")",
":",
"return",
"self",
".",
"add",
"(",
"method",
",",
"path_settings",
",",
"target",
")"
] | 32 | 0.012195 |
def get_unique_families(hkls):
"""
Returns unique families of Miller indices. Families must be permutations
of each other.
Args:
hkls ([h, k, l]): List of Miller indices.
Returns:
{hkl: multiplicity}: A dict with unique hkl and multiplicity.
"""
# TODO: Definitely can be sp... | [
"def",
"get_unique_families",
"(",
"hkls",
")",
":",
"# TODO: Definitely can be sped up.",
"def",
"is_perm",
"(",
"hkl1",
",",
"hkl2",
")",
":",
"h1",
"=",
"np",
".",
"abs",
"(",
"hkl1",
")",
"h2",
"=",
"np",
".",
"abs",
"(",
"hkl2",
")",
"return",
"al... | 26.787879 | 0.001092 |
def _ps(osdata):
'''
Return the ps grain
'''
grains = {}
bsd_choices = ('FreeBSD', 'NetBSD', 'OpenBSD', 'MacOS')
if osdata['os'] in bsd_choices:
grains['ps'] = 'ps auxwww'
elif osdata['os_family'] == 'Solaris':
grains['ps'] = '/usr/ucb/ps auxwww'
elif osdata['os'] == 'Win... | [
"def",
"_ps",
"(",
"osdata",
")",
":",
"grains",
"=",
"{",
"}",
"bsd_choices",
"=",
"(",
"'FreeBSD'",
",",
"'NetBSD'",
",",
"'OpenBSD'",
",",
"'MacOS'",
")",
"if",
"osdata",
"[",
"'os'",
"]",
"in",
"bsd_choices",
":",
"grains",
"[",
"'ps'",
"]",
"=",... | 34.36 | 0.001133 |
def publish_scene_config(self, scene_id, config):
"""publish a changed scene configuration"""
self.sequence_number += 1
self.publisher.send_multipart(msgs.MessageBuilder.scene_config(self.sequence_number, scene_id, config))
return self.sequence_number | [
"def",
"publish_scene_config",
"(",
"self",
",",
"scene_id",
",",
"config",
")",
":",
"self",
".",
"sequence_number",
"+=",
"1",
"self",
".",
"publisher",
".",
"send_multipart",
"(",
"msgs",
".",
"MessageBuilder",
".",
"scene_config",
"(",
"self",
".",
"sequ... | 55.8 | 0.010601 |
def highlight(self, x, y, w, h, fg=None, bg=None, blend=100):
"""
Highlight a specified section of the screen.
:param x: The column (x coord) for the start of the highlight.
:param y: The line (y coord) for the start of the highlight.
:param w: The width of the highlight (in cha... | [
"def",
"highlight",
"(",
"self",
",",
"x",
",",
"y",
",",
"w",
",",
"h",
",",
"fg",
"=",
"None",
",",
"bg",
"=",
"None",
",",
"blend",
"=",
"100",
")",
":",
"# Convert to buffer coordinates",
"y",
"-=",
"self",
".",
"_start_line",
"for",
"i",
"in",... | 43.580645 | 0.002172 |
def hyper_parameter_search(
self,
param_distributions,
n_iter=10,
scoring=None,
fit_params={},
n_jobs=1,
iid=True,
refit=True,
cv=None,
verbose=0,
pre_dispatch='2*njobs',
rando... | [
"def",
"hyper_parameter_search",
"(",
"self",
",",
"param_distributions",
",",
"n_iter",
"=",
"10",
",",
"scoring",
"=",
"None",
",",
"fit_params",
"=",
"{",
"}",
",",
"n_jobs",
"=",
"1",
",",
"iid",
"=",
"True",
",",
"refit",
"=",
"True",
",",
"cv",
... | 30.142857 | 0.002295 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.