text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def participate(self):
"""Finish reading and send text"""
try:
while True:
left = WebDriverWait(self.driver, 10).until(
EC.element_to_be_clickable((By.ID, "left_button"))
)
right = WebDriverWait(self.driver, 10).until(
... | [
"def",
"participate",
"(",
"self",
")",
":",
"try",
":",
"while",
"True",
":",
"left",
"=",
"WebDriverWait",
"(",
"self",
".",
"driver",
",",
"10",
")",
".",
"until",
"(",
"EC",
".",
"element_to_be_clickable",
"(",
"(",
"By",
".",
"ID",
",",
"\"left_... | 35.6 | 19.733333 |
def esxcli(host, user, pwd, cmd, protocol=None, port=None, esxi_host=None, credstore=None):
'''
Shell out and call the specified esxcli commmand, parse the result
and return something sane.
:param host: ESXi or vCenter host to connect to
:param user: User to connect as, usually root
:param pwd:... | [
"def",
"esxcli",
"(",
"host",
",",
"user",
",",
"pwd",
",",
"cmd",
",",
"protocol",
"=",
"None",
",",
"port",
"=",
"None",
",",
"esxi_host",
"=",
"None",
",",
"credstore",
"=",
"None",
")",
":",
"esx_cmd",
"=",
"salt",
".",
"utils",
".",
"path",
... | 42.618182 | 25.890909 |
def _file_path(self, uid):
"""Create and return full file path for DayOne entry"""
file_name = '%s.doentry' % (uid)
return os.path.join(self.dayone_journal_path, file_name) | [
"def",
"_file_path",
"(",
"self",
",",
"uid",
")",
":",
"file_name",
"=",
"'%s.doentry'",
"%",
"(",
"uid",
")",
"return",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"dayone_journal_path",
",",
"file_name",
")"
] | 48.25 | 9.5 |
def main(argv=None):
"""Entry point for Rewind.
Parses input and calls run() for the real work.
Parameters:
argv -- sys.argv arguments. Can be set for testing purposes.
returns -- the proposed exit code for the program.
"""
parser = argparse.ArgumentParser(
description='Event ... | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"'Event storage and event proxy.'",
",",
"usage",
"=",
"'%(prog)s <configfile>'",
")",
"parser",
".",
"add_argument",
"(",
"'--exit-codewo... | 30.965517 | 21.137931 |
def rc_channels_scaled_send(self, time_boot_ms, port, chan1_scaled, chan2_scaled, chan3_scaled, chan4_scaled, chan5_scaled, chan6_scaled, chan7_scaled, chan8_scaled, rssi, force_mavlink1=False):
'''
The scaled values of the RC channels received. (-100%) -10000, (0%) 0,
(1... | [
"def",
"rc_channels_scaled_send",
"(",
"self",
",",
"time_boot_ms",
",",
"port",
",",
"chan1_scaled",
",",
"chan2_scaled",
",",
"chan3_scaled",
",",
"chan4_scaled",
",",
"chan5_scaled",
",",
"chan6_scaled",
",",
"chan7_scaled",
",",
"chan8_scaled",
",",
"rssi",
",... | 107.85 | 81.05 |
def is_group_name_exists(self, group_name):
""" check if group with given name is already exists """
groups = self.m["groups"]
for g in groups:
if (g["group_name"] == group_name):
return True
return False | [
"def",
"is_group_name_exists",
"(",
"self",
",",
"group_name",
")",
":",
"groups",
"=",
"self",
".",
"m",
"[",
"\"groups\"",
"]",
"for",
"g",
"in",
"groups",
":",
"if",
"(",
"g",
"[",
"\"group_name\"",
"]",
"==",
"group_name",
")",
":",
"return",
"True... | 36.857143 | 9.428571 |
def sample_stats_prior_to_xarray(self):
"""Extract sample_stats from fit."""
dtypes = {"divergent__": bool, "n_leapfrog__": np.int64, "treedepth__": np.int64}
# copy dims and coords
dims = deepcopy(self.dims) if self.dims is not None else {}
coords = deepcopy(self.coords) if sel... | [
"def",
"sample_stats_prior_to_xarray",
"(",
"self",
")",
":",
"dtypes",
"=",
"{",
"\"divergent__\"",
":",
"bool",
",",
"\"n_leapfrog__\"",
":",
"np",
".",
"int64",
",",
"\"treedepth__\"",
":",
"np",
".",
"int64",
"}",
"# copy dims and coords",
"dims",
"=",
"de... | 49.1 | 20 |
def move_partition(self, partition, broker_destination):
"""Move partition to destination broker and adjust replicas."""
self.remove_partition(partition)
broker_destination.add_partition(partition) | [
"def",
"move_partition",
"(",
"self",
",",
"partition",
",",
"broker_destination",
")",
":",
"self",
".",
"remove_partition",
"(",
"partition",
")",
"broker_destination",
".",
"add_partition",
"(",
"partition",
")"
] | 54.5 | 6.75 |
def refine_pi_cation_laro(self, all_picat, stacks):
"""Just important for constellations with histidine involved. If the histidine ring is positioned in stacking
position to an aromatic ring in the ligand, there is in most cases stacking and pi-cation interaction reported
as histidine also carri... | [
"def",
"refine_pi_cation_laro",
"(",
"self",
",",
"all_picat",
",",
"stacks",
")",
":",
"i_set",
"=",
"[",
"]",
"for",
"picat",
"in",
"all_picat",
":",
"exclude",
"=",
"False",
"for",
"stack",
"in",
"stacks",
":",
"if",
"whichrestype",
"(",
"stack",
".",... | 52.5 | 22.785714 |
def patch_python_logging_handlers():
'''
Patch the python logging handlers with out mixed-in classes
'''
logging.StreamHandler = StreamHandler
logging.FileHandler = FileHandler
logging.handlers.SysLogHandler = SysLogHandler
logging.handlers.WatchedFileHandler = WatchedFileHandler
logging... | [
"def",
"patch_python_logging_handlers",
"(",
")",
":",
"logging",
".",
"StreamHandler",
"=",
"StreamHandler",
"logging",
".",
"FileHandler",
"=",
"FileHandler",
"logging",
".",
"handlers",
".",
"SysLogHandler",
"=",
"SysLogHandler",
"logging",
".",
"handlers",
".",
... | 40.818182 | 15.181818 |
def _find_node_by_indices(self, point):
""""Find the GSNode that is refered to by the given indices.
See GSNode::_indices()
"""
path_index, node_index = point
path = self.paths[int(path_index)]
node = path.nodes[int(node_index)]
return node | [
"def",
"_find_node_by_indices",
"(",
"self",
",",
"point",
")",
":",
"path_index",
",",
"node_index",
"=",
"point",
"path",
"=",
"self",
".",
"paths",
"[",
"int",
"(",
"path_index",
")",
"]",
"node",
"=",
"path",
".",
"nodes",
"[",
"int",
"(",
"node_in... | 32.111111 | 8.666667 |
def scramble_string(self, length):
"""Return random string"""
return fake.text(length) if length > 5 else ''.join([fake.random_letter() for n in range(0, length)]) | [
"def",
"scramble_string",
"(",
"self",
",",
"length",
")",
":",
"return",
"fake",
".",
"text",
"(",
"length",
")",
"if",
"length",
">",
"5",
"else",
"''",
".",
"join",
"(",
"[",
"fake",
".",
"random_letter",
"(",
")",
"for",
"n",
"in",
"range",
"("... | 59 | 25 |
def add_header_callback(self, cb, port, channel, port_mask=0xFF,
channel_mask=0xFF):
"""
Add a callback for a specific port/header callback with the
possibility to add a mask for channel and port for multiple
hits for same callback.
"""
self.cb... | [
"def",
"add_header_callback",
"(",
"self",
",",
"cb",
",",
"port",
",",
"channel",
",",
"port_mask",
"=",
"0xFF",
",",
"channel_mask",
"=",
"0xFF",
")",
":",
"self",
".",
"cb",
".",
"append",
"(",
"_CallbackContainer",
"(",
"port",
",",
"port_mask",
",",... | 47.222222 | 15.666667 |
def eval(self, data, data_store, *, exclude=None):
""" Return a new object in which callable parameters have been evaluated.
Native types are not touched and simply returned, while callable methods are
executed and their return value is returned.
Args:
data (MultiTaskData):... | [
"def",
"eval",
"(",
"self",
",",
"data",
",",
"data_store",
",",
"*",
",",
"exclude",
"=",
"None",
")",
":",
"exclude",
"=",
"[",
"]",
"if",
"exclude",
"is",
"None",
"else",
"exclude",
"result",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"s... | 41.419355 | 22.322581 |
def setup(
hosts,
default_keyspace,
consistency=ConsistencyLevel.ONE,
lazy_connect=False,
retry_connect=False,
**kwargs):
"""
Records the hosts and connects to one of them
:param hosts: list of hosts, see http://datastax.github.io/python-driver/api/cassandra/... | [
"def",
"setup",
"(",
"hosts",
",",
"default_keyspace",
",",
"consistency",
"=",
"ConsistencyLevel",
".",
"ONE",
",",
"lazy_connect",
"=",
"False",
",",
"retry_connect",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"global",
"cluster",
",",
"session",
"... | 35.188679 | 18.54717 |
def sphergal_to_rectgal(l,b,d,vr,pmll,pmbb,degree=False):
"""
NAME:
sphergal_to_rectgal
PURPOSE:
transform phase-space coordinates in spherical Galactic coordinates to rectangular Galactic coordinates (can take vector inputs)
INPUT:
l - Galactic longitude (rad)
b - Gala... | [
"def",
"sphergal_to_rectgal",
"(",
"l",
",",
"b",
",",
"d",
",",
"vr",
",",
"pmll",
",",
"pmbb",
",",
"degree",
"=",
"False",
")",
":",
"XYZ",
"=",
"lbd_to_XYZ",
"(",
"l",
",",
"b",
",",
"d",
",",
"degree",
"=",
"degree",
")",
"vxvyvz",
"=",
"v... | 23.909091 | 27.5 |
def generate_thumbnail(source, outname, box, delay, fit=True, options=None,
converter='ffmpeg'):
"""Create a thumbnail image for the video source, based on ffmpeg."""
logger = logging.getLogger(__name__)
tmpfile = outname + ".tmp.jpg"
# dump an image of the video
cmd = [conv... | [
"def",
"generate_thumbnail",
"(",
"source",
",",
"outname",
",",
"box",
",",
"delay",
",",
"fit",
"=",
"True",
",",
"options",
"=",
"None",
",",
"converter",
"=",
"'ffmpeg'",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"... | 40.705882 | 18.764706 |
def setColor(self, vehID, color):
"""setColor(string, (integer, integer, integer, integer))
sets color for vehicle with the given ID.
i.e. (255,0,0,0) for the color red.
The fourth integer (alpha) is only used when drawing vehicles with raster images
"""
self._connection.... | [
"def",
"setColor",
"(",
"self",
",",
"vehID",
",",
"color",
")",
":",
"self",
".",
"_connection",
".",
"_beginMessage",
"(",
"tc",
".",
"CMD_SET_VEHICLE_VARIABLE",
",",
"tc",
".",
"VAR_COLOR",
",",
"vehID",
",",
"1",
"+",
"1",
"+",
"1",
"+",
"1",
"+"... | 53.545455 | 15.909091 |
def register_backend(name, backend, allow_overwrite=False):
"""Register new backend.
Args:
name (str): The name of backend.
gateclass (type): The type object of backend
allow_overwrite (bool, optional): If True, allow to overwrite the existing backend.
... | [
"def",
"register_backend",
"(",
"name",
",",
"backend",
",",
"allow_overwrite",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"Circuit",
",",
"\"run_with_\"",
"+",
"name",
")",
":",
"if",
"allow_overwrite",
":",
"warnings",
".",
"warn",
"(",
"f\"Circuit has ... | 42.772727 | 21.636364 |
def let_variable(self, frame_id, var_name, expression_value):
""" Let a frame's var with a value by building then eval a let
expression with breakoints disabled.
"""
breakpoints_backup = IKBreakpoint.backup_breakpoints_state()
IKBreakpoint.disable_all_breakpoints()
let_... | [
"def",
"let_variable",
"(",
"self",
",",
"frame_id",
",",
"var_name",
",",
"expression_value",
")",
":",
"breakpoints_backup",
"=",
"IKBreakpoint",
".",
"backup_breakpoints_state",
"(",
")",
"IKBreakpoint",
".",
"disable_all_breakpoints",
"(",
")",
"let_expression",
... | 38.137931 | 15.931034 |
def fromhdf5sorted(source, where=None, name=None, sortby=None, checkCSI=False,
start=None, stop=None, step=None):
"""
Provides access to an HDF5 table, sorted by an indexed column, e.g.::
>>> import petl as etl
>>> import tables
>>> # set up a new hdf5 table to demons... | [
"def",
"fromhdf5sorted",
"(",
"source",
",",
"where",
"=",
"None",
",",
"name",
"=",
"None",
",",
"sortby",
"=",
"None",
",",
"checkCSI",
"=",
"False",
",",
"start",
"=",
"None",
",",
"stop",
"=",
"None",
",",
"step",
"=",
"None",
")",
":",
"assert... | 37.980769 | 17.211538 |
def boolean_input(self, question, default=None):
'''
Method for yes/no boolean inputs
'''
result = input("%s: " % question)
if not result and default is not None:
return default
while len(result) < 1 or result[0].lower() not in "yn":
result... | [
"def",
"boolean_input",
"(",
"self",
",",
"question",
",",
"default",
"=",
"None",
")",
":",
"result",
"=",
"input",
"(",
"\"%s: \"",
"%",
"question",
")",
"if",
"not",
"result",
"and",
"default",
"is",
"not",
"None",
":",
"return",
"default",
"while",
... | 38.9 | 12.9 |
def nt_db_search(self, files, base, unpack, euk_check,
search_method, maximum_range, threads, evalue):
'''
Nucleotide database search pipeline - pipeline where reads are searched
as nucleotides, and hits are identified using nhmmer searches
Parameters
------... | [
"def",
"nt_db_search",
"(",
"self",
",",
"files",
",",
"base",
",",
"unpack",
",",
"euk_check",
",",
"search_method",
",",
"maximum_range",
",",
"threads",
",",
"evalue",
")",
":",
"# Define outputs",
"hmmsearch_output_table",
"=",
"files",
".",
"hmmsearch_outpu... | 46 | 23.92 |
def create_from_textgrid(self,word_list):
""" Fills the ParsedResponse object with a list of TextGrid.Word objects originally from a .TextGrid file.
:param list word_list: List of TextGrid.Word objects corresponding to words/tokens in the subject response.
Modifies:
- self.timing_i... | [
"def",
"create_from_textgrid",
"(",
"self",
",",
"word_list",
")",
":",
"self",
".",
"timing_included",
"=",
"True",
"for",
"i",
",",
"entry",
"in",
"enumerate",
"(",
"word_list",
")",
":",
"self",
".",
"unit_list",
".",
"append",
"(",
"Unit",
"(",
"entr... | 49.571429 | 24.380952 |
def iter_records_for(self, package_name):
"""
Iterate records for a specific package.
"""
entry_points = self.packages.get(package_name, NotImplemented)
if entry_points is NotImplemented:
logger.debug(
"package '%s' has not declared any entry points f... | [
"def",
"iter_records_for",
"(",
"self",
",",
"package_name",
")",
":",
"entry_points",
"=",
"self",
".",
"packages",
".",
"get",
"(",
"package_name",
",",
"NotImplemented",
")",
"if",
"entry_points",
"is",
"NotImplemented",
":",
"logger",
".",
"debug",
"(",
... | 36.05 | 17.45 |
def start_external_instances(self, late_start=False):
"""Launch external instances that are load correctly
:param late_start: If late_start, don't look for last_init_try
:type late_start: bool
:return: None
"""
for instance in [i for i in self.instances if i.is_external]... | [
"def",
"start_external_instances",
"(",
"self",
",",
"late_start",
"=",
"False",
")",
":",
"for",
"instance",
"in",
"[",
"i",
"for",
"i",
"in",
"self",
".",
"instances",
"if",
"i",
".",
"is_external",
"]",
":",
"# But maybe the init failed a bit, so bypass this ... | 44.5 | 21.333333 |
def set_log_level(self, level):
"""Set the logging level.
Parameters
----------
level : logging level constant
The value to set the logging level to.
"""
self._log_level = level
if self._python_logger:
try:
level = self.PY... | [
"def",
"set_log_level",
"(",
"self",
",",
"level",
")",
":",
"self",
".",
"_log_level",
"=",
"level",
"if",
"self",
".",
"_python_logger",
":",
"try",
":",
"level",
"=",
"self",
".",
"PYTHON_LEVEL",
".",
"get",
"(",
"level",
")",
"except",
"ValueError",
... | 30.25 | 15 |
def post_helper(form_tag=True, edit_mode=False):
"""
Post's form layout helper
"""
helper = FormHelper()
helper.form_action = '.'
helper.attrs = {'data_abide': ''}
helper.form_tag = form_tag
fieldsets = [
Row(
Column(
'text',
css_c... | [
"def",
"post_helper",
"(",
"form_tag",
"=",
"True",
",",
"edit_mode",
"=",
"False",
")",
":",
"helper",
"=",
"FormHelper",
"(",
")",
"helper",
".",
"form_action",
"=",
"'.'",
"helper",
".",
"attrs",
"=",
"{",
"'data_abide'",
":",
"''",
"}",
"helper",
"... | 20.794872 | 18.230769 |
def get_mysql_connection(host, user, port, password, database, ssl={}):
""" MySQL connection """
return pymysql.connect(host=host,
user=user,
port=port,
password=password,
db=database,
... | [
"def",
"get_mysql_connection",
"(",
"host",
",",
"user",
",",
"port",
",",
"password",
",",
"database",
",",
"ssl",
"=",
"{",
"}",
")",
":",
"return",
"pymysql",
".",
"connect",
"(",
"host",
"=",
"host",
",",
"user",
"=",
"user",
",",
"port",
"=",
... | 42.153846 | 13.538462 |
def execute(self, command, blocking=True, exec_create_kwargs=None, exec_start_kwargs=None):
"""
Execute a command in this container -- the container needs to be running.
If the command fails, a ConuException is thrown.
This is a blocking call by default and writes output of the command... | [
"def",
"execute",
"(",
"self",
",",
"command",
",",
"blocking",
"=",
"True",
",",
"exec_create_kwargs",
"=",
"None",
",",
"exec_start_kwargs",
"=",
"None",
")",
":",
"logger",
".",
"info",
"(",
"\"running command %s\"",
",",
"command",
")",
"exec_create_kwargs... | 44.979167 | 25.604167 |
def _parse_vertex_tuple(s):
"""Parse vertex indices in '/' separated form (like 'i/j/k', 'i//k' ...)."""
vt = [0, 0, 0]
for i, c in enumerate(s.split('/')):
if c:
vt[i] = int(c)
return tuple(vt) | [
"def",
"_parse_vertex_tuple",
"(",
"s",
")",
":",
"vt",
"=",
"[",
"0",
",",
"0",
",",
"0",
"]",
"for",
"i",
",",
"c",
"in",
"enumerate",
"(",
"s",
".",
"split",
"(",
"'/'",
")",
")",
":",
"if",
"c",
":",
"vt",
"[",
"i",
"]",
"=",
"int",
"... | 29.428571 | 16 |
def clear_request(name=None):
'''
.. versionadded:: 2017.7.3
Clear out the state execution request without executing it
CLI Example:
.. code-block:: bash
salt '*' state.clear_request
'''
notify_path = os.path.join(__opts__['cachedir'], 'req_state.p')
serial = salt.payload.Ser... | [
"def",
"clear_request",
"(",
"name",
"=",
"None",
")",
":",
"notify_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"__opts__",
"[",
"'cachedir'",
"]",
",",
"'req_state.p'",
")",
"serial",
"=",
"salt",
".",
"payload",
".",
"Serial",
"(",
"__opts__",
"... | 29.55 | 20.3 |
def scramble(expnums, ccd, version='p', dry_run=False):
"""run the plant script on this combination of exposures"""
mjds = []
fobjs = []
for expnum in expnums:
filename = storage.get_image(expnum, ccd=ccd, version=version)
fobjs.append(fits.open(filename))
# Pull out values to r... | [
"def",
"scramble",
"(",
"expnums",
",",
"ccd",
",",
"version",
"=",
"'p'",
",",
"dry_run",
"=",
"False",
")",
":",
"mjds",
"=",
"[",
"]",
"fobjs",
"=",
"[",
"]",
"for",
"expnum",
"in",
"expnums",
":",
"filename",
"=",
"storage",
".",
"get_image",
"... | 36.677419 | 16.516129 |
def peek_string(self, lpBaseAddress, fUnicode = False, dwMaxSize = 0x1000):
"""
Tries to read an ASCII or Unicode string
from the address space of the process.
@see: L{read_string}
@type lpBaseAddress: int
@param lpBaseAddress: Memory address to begin reading.
... | [
"def",
"peek_string",
"(",
"self",
",",
"lpBaseAddress",
",",
"fUnicode",
"=",
"False",
",",
"dwMaxSize",
"=",
"0x1000",
")",
":",
"# Validate the parameters.",
"if",
"not",
"lpBaseAddress",
"or",
"dwMaxSize",
"==",
"0",
":",
"if",
"fUnicode",
":",
"return",
... | 32.894737 | 20.789474 |
def _set_zoning(self, v, load=False):
"""
Setter method for zoning, mapped from YANG variable /zoning (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_zoning is considered as a private
method. Backends looking to populate this variable should
do so via... | [
"def",
"_set_zoning",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"base",
... | 74.909091 | 34.409091 |
def plantloopfieldlists(data):
"""return the plantloopfield list"""
objkey = 'plantloop'.upper()
numobjects = len(data.dt[objkey])
return [[
'Name',
'Plant Side Inlet Node Name',
'Plant Side Outlet Node Name',
'Plant Side Branch List Name',
'Demand Side Inlet Node... | [
"def",
"plantloopfieldlists",
"(",
"data",
")",
":",
"objkey",
"=",
"'plantloop'",
".",
"upper",
"(",
")",
"numobjects",
"=",
"len",
"(",
"data",
".",
"dt",
"[",
"objkey",
"]",
")",
"return",
"[",
"[",
"'Name'",
",",
"'Plant Side Inlet Node Name'",
",",
... | 34.166667 | 8 |
def _extend_spikes(spike_ids, spike_clusters):
"""Return all spikes belonging to the clusters containing the specified
spikes."""
# We find the spikes belonging to modified clusters.
# What are the old clusters that are modified by the assignment?
old_spike_clusters = spike_clusters[spike_ids]
u... | [
"def",
"_extend_spikes",
"(",
"spike_ids",
",",
"spike_clusters",
")",
":",
"# We find the spikes belonging to modified clusters.",
"# What are the old clusters that are modified by the assignment?",
"old_spike_clusters",
"=",
"spike_clusters",
"[",
"spike_ids",
"]",
"unique_clusters... | 53.384615 | 14.384615 |
def find_profile(self, bitarray, eep_rorg, rorg_func, rorg_type, direction=None, command=None):
''' Find profile and data description, matching RORG, FUNC and TYPE '''
if not self.init_ok:
self.logger.warn('EEP.xml not loaded!')
return None
if eep_rorg not in self.telegr... | [
"def",
"find_profile",
"(",
"self",
",",
"bitarray",
",",
"eep_rorg",
",",
"rorg_func",
",",
"rorg_type",
",",
"direction",
"=",
"None",
",",
"command",
"=",
"None",
")",
":",
"if",
"not",
"self",
".",
"init_ok",
":",
"self",
".",
"logger",
".",
"warn"... | 42.972222 | 25.638889 |
def assert_instance_deleted(self, model_class, **kwargs):
"""
Checks if the model instance was deleted from the database.
For example::
>>> with self.assert_instance_deleted(Article, slug='lorem-ipsum'):
... Article.objects.get(slug='lorem-ipsum').delete()
"""
... | [
"def",
"assert_instance_deleted",
"(",
"self",
",",
"model_class",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_InstanceContext",
"(",
"self",
".",
"assert_instance_exists",
",",
"self",
".",
"assert_instance_does_not_exist",
",",
"model_class",
",",
"*",
"*",
... | 31.933333 | 19 |
def destroy(self, force=False):
"""UnmanagedLXC Destructor.
It requires force to be true in order to work. Otherwise it throws an
error.
"""
if force:
super(UnmanagedLXC, self).destroy()
else:
raise UnmanagedLXCError('Destroying an unmanaged LXC m... | [
"def",
"destroy",
"(",
"self",
",",
"force",
"=",
"False",
")",
":",
"if",
"force",
":",
"super",
"(",
"UnmanagedLXC",
",",
"self",
")",
".",
"destroy",
"(",
")",
"else",
":",
"raise",
"UnmanagedLXCError",
"(",
"'Destroying an unmanaged LXC might not '",
"'w... | 36.090909 | 21.909091 |
def pad(data_to_pad, block_size, style='pkcs7'):
"""Apply standard padding.
:Parameters:
data_to_pad : byte string
The data that needs to be padded.
block_size : integer
The block boundary to use for padding. The output length is guaranteed
to be a multiple of ``block_size``... | [
"def",
"pad",
"(",
"data_to_pad",
",",
"block_size",
",",
"style",
"=",
"'pkcs7'",
")",
":",
"padding_len",
"=",
"block_size",
"-",
"len",
"(",
"data_to_pad",
")",
"%",
"block_size",
"if",
"style",
"==",
"'pkcs7'",
":",
"padding",
"=",
"bchr",
"(",
"padd... | 35.52 | 17.8 |
def _getApplication(self):
"""Get the base application UIElement.
If the UIElement is a child of the application, it will try
to get the AXParent until it reaches the top application level
element.
"""
app = self
while True:
try:
app =... | [
"def",
"_getApplication",
"(",
"self",
")",
":",
"app",
"=",
"self",
"while",
"True",
":",
"try",
":",
"app",
"=",
"app",
".",
"AXParent",
"except",
"_a11y",
".",
"ErrorUnsupported",
":",
"break",
"return",
"app"
] | 28.857143 | 17.928571 |
def list_pools(self, retrieve_all=True, **_params):
"""Fetches a list of all load balancer pools for a project."""
# Pass filters in "params" argument to do_request
return self.list('pools', self.pools_path, retrieve_all,
**_params) | [
"def",
"list_pools",
"(",
"self",
",",
"retrieve_all",
"=",
"True",
",",
"*",
"*",
"_params",
")",
":",
"# Pass filters in \"params\" argument to do_request",
"return",
"self",
".",
"list",
"(",
"'pools'",
",",
"self",
".",
"pools_path",
",",
"retrieve_all",
","... | 55.4 | 11.4 |
def read_label_list(path):
"""
Reads labels from an Audacity label file
and returns them wrapped in a :py:class:`audiomate.annotations.LabelList`.
Args:
path (str): Path to the Audacity label file
Returns:
audiomate.annotations.LabelList: Label list containing the labels
"""
... | [
"def",
"read_label_list",
"(",
"path",
")",
":",
"ll",
"=",
"annotations",
".",
"LabelList",
"(",
")",
"for",
"record",
"in",
"read_label_file",
"(",
"path",
")",
":",
"ll",
".",
"add",
"(",
"annotations",
".",
"Label",
"(",
"record",
"[",
"2",
"]",
... | 27.529412 | 22.941176 |
def get_contig_names(fasta_file):
"""
Gets contig names from a fasta file using SeqIO.
:param fasta_file: Full path to uncompressed, fasta-formatted file
:return: List of contig names.
"""
contig_names = list()
for contig in SeqIO.parse(fasta_file, 'fasta'):
contig_names.append(conti... | [
"def",
"get_contig_names",
"(",
"fasta_file",
")",
":",
"contig_names",
"=",
"list",
"(",
")",
"for",
"contig",
"in",
"SeqIO",
".",
"parse",
"(",
"fasta_file",
",",
"'fasta'",
")",
":",
"contig_names",
".",
"append",
"(",
"contig",
".",
"id",
")",
"retur... | 34 | 10 |
def list_drama_series(self, sort=META.SORT_ALPHA, limit=META.MAX_SERIES, offset=0):
"""Get a list of drama series
@param str sort pick how results should be sorted, should be one
of META.SORT_*
@param int limit limit number of series to return, there doesn... | [
"def",
"list_drama_series",
"(",
"self",
",",
"sort",
"=",
"META",
".",
"SORT_ALPHA",
",",
"limit",
"=",
"META",
".",
"MAX_SERIES",
",",
"offset",
"=",
"0",
")",
":",
"result",
"=",
"self",
".",
"_android_api",
".",
"list_series",
"(",
"media_type",
"=",... | 43.9375 | 19.0625 |
def user_has_super_roles():
"""Return whether the current belongs to superuser roles
"""
member = api.get_current_user()
super_roles = ["LabManager", "Manager"]
diff = filter(lambda role: role in super_roles, member.getRoles())
return len(diff) > 0 | [
"def",
"user_has_super_roles",
"(",
")",
":",
"member",
"=",
"api",
".",
"get_current_user",
"(",
")",
"super_roles",
"=",
"[",
"\"LabManager\"",
",",
"\"Manager\"",
"]",
"diff",
"=",
"filter",
"(",
"lambda",
"role",
":",
"role",
"in",
"super_roles",
",",
... | 38 | 9.571429 |
def dispatch_line(self, frame):
"""Handle line action and return the next line callback."""
callback = TerminalPdb.dispatch_line(self, frame)
# If the ipdb session ended, don't return a callback for the next line
if self.stoplineno == -1:
return None
return callback | [
"def",
"dispatch_line",
"(",
"self",
",",
"frame",
")",
":",
"callback",
"=",
"TerminalPdb",
".",
"dispatch_line",
"(",
"self",
",",
"frame",
")",
"# If the ipdb session ended, don't return a callback for the next line",
"if",
"self",
".",
"stoplineno",
"==",
"-",
"... | 34.666667 | 20.555556 |
def ensure_valid_environment_config(module_name, config):
"""Exit if config is invalid."""
if not config.get('namespace'):
LOGGER.fatal("staticsite: module %s's environment configuration is "
"missing a namespace definition!",
module_name)
sys.exit(1) | [
"def",
"ensure_valid_environment_config",
"(",
"module_name",
",",
"config",
")",
":",
"if",
"not",
"config",
".",
"get",
"(",
"'namespace'",
")",
":",
"LOGGER",
".",
"fatal",
"(",
"\"staticsite: module %s's environment configuration is \"",
"\"missing a namespace definit... | 44.428571 | 14.428571 |
def add_data_point(self, x, y):
"""Adds a data point to the series.
:param x: The numerical x value to be added.
:param y: The numerical y value to be added."""
if not is_numeric(x):
raise TypeError("x value must be numeric, not '%s'" % str(x))
if not is_numeric(y):... | [
"def",
"add_data_point",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"if",
"not",
"is_numeric",
"(",
"x",
")",
":",
"raise",
"TypeError",
"(",
"\"x value must be numeric, not '%s'\"",
"%",
"str",
"(",
"x",
")",
")",
"if",
"not",
"is_numeric",
"(",
"y",
... | 39.5 | 16.5 |
def parse_uploaded_image(field):
'''Parse an uploaded image and save into a db.ImageField()'''
args = image_parser.parse_args()
image = args['file']
if image.mimetype not in IMAGES_MIMETYPES:
api.abort(400, 'Unsupported image format')
bbox = args.get('bbox', None)
if bbox:
bbox ... | [
"def",
"parse_uploaded_image",
"(",
"field",
")",
":",
"args",
"=",
"image_parser",
".",
"parse_args",
"(",
")",
"image",
"=",
"args",
"[",
"'file'",
"]",
"if",
"image",
".",
"mimetype",
"not",
"in",
"IMAGES_MIMETYPES",
":",
"api",
".",
"abort",
"(",
"40... | 35 | 15.181818 |
def write_property(fh, key, value):
"""
Write a single property to the file in Java properties format.
:param fh: a writable file-like object
:param key: the key to write
:param value: the value to write
"""
if key is COMMENT:
write_comment(fh, value)
return
_require_string(key, 'keys'... | [
"def",
"write_property",
"(",
"fh",
",",
"key",
",",
"value",
")",
":",
"if",
"key",
"is",
"COMMENT",
":",
"write_comment",
"(",
"fh",
",",
"value",
")",
"return",
"_require_string",
"(",
"key",
",",
"'keys'",
")",
"_require_string",
"(",
"value",
",",
... | 22.947368 | 16.315789 |
def determine_device(kal_out):
"""Extract and return device from scan results."""
device = ""
while device == "":
for line in kal_out.splitlines():
if "Using device " in line:
device = str(line.split(' ', 2)[-1])
if device == "":
device = None
retu... | [
"def",
"determine_device",
"(",
"kal_out",
")",
":",
"device",
"=",
"\"\"",
"while",
"device",
"==",
"\"\"",
":",
"for",
"line",
"in",
"kal_out",
".",
"splitlines",
"(",
")",
":",
"if",
"\"Using device \"",
"in",
"line",
":",
"device",
"=",
"str",
"(",
... | 32 | 12 |
def repair(source, validate_archive=False):
"""Use auditwheel (https://github.com/pypa/auditwheel)
to attempt and repair all wheels in a wagon.
The repair process will:
1. Extract the wagon and its metadata
2. Repair all wheels
3. Update the metadata with the new wheel names and platform
4... | [
"def",
"repair",
"(",
"source",
",",
"validate_archive",
"=",
"False",
")",
":",
"_assert_auditwheel_exists",
"(",
")",
"logger",
".",
"info",
"(",
"'Repairing: %s'",
",",
"source",
")",
"processed_source",
"=",
"get_source",
"(",
"source",
")",
"metadata",
"=... | 33.380952 | 13.452381 |
def getSpktSpkid(cellGids=[], timeRange=None, allCells=False):
'''return spike ids and times; with allCells=True just need to identify slice of time so can omit cellGids'''
from .. import sim
import pandas as pd
try: # Pandas 0.24 and later
from pandas import _lib as pandaslib
except: #... | [
"def",
"getSpktSpkid",
"(",
"cellGids",
"=",
"[",
"]",
",",
"timeRange",
"=",
"None",
",",
"allCells",
"=",
"False",
")",
":",
"from",
".",
".",
"import",
"sim",
"import",
"pandas",
"as",
"pd",
"try",
":",
"# Pandas 0.24 and later",
"from",
"pandas",
"im... | 54.095238 | 32.952381 |
def old(self):
"""
The old value from the event.
"""
ori = self.original.action
if isinstance(ori, (
types.ChannelAdminLogEventActionChangeAbout,
types.ChannelAdminLogEventActionChangeTitle,
types.ChannelAdminLogEventActionChangeUse... | [
"def",
"old",
"(",
"self",
")",
":",
"ori",
"=",
"self",
".",
"original",
".",
"action",
"if",
"isinstance",
"(",
"ori",
",",
"(",
"types",
".",
"ChannelAdminLogEventActionChangeAbout",
",",
"types",
".",
"ChannelAdminLogEventActionChangeTitle",
",",
"types",
... | 44.25 | 17.9375 |
def get_views(self, app_id, include_standard_views=False):
"""
Get all of the views for the specified app
:param app_id: the app containing the views
:param include_standard_views: defaults to false. Set to true if you wish to include standard views.
"""
include_standard... | [
"def",
"get_views",
"(",
"self",
",",
"app_id",
",",
"include_standard_views",
"=",
"False",
")",
":",
"include_standard",
"=",
"\"true\"",
"if",
"include_standard_views",
"is",
"True",
"else",
"\"false\"",
"return",
"self",
".",
"transport",
".",
"GET",
"(",
... | 53.555556 | 28.888889 |
def fw_int_to_hex(*args):
"""Pack integers into hex string.
Use little-endian and unsigned int format.
"""
return binascii.hexlify(
struct.pack('<{}H'.format(len(args)), *args)).decode('utf-8') | [
"def",
"fw_int_to_hex",
"(",
"*",
"args",
")",
":",
"return",
"binascii",
".",
"hexlify",
"(",
"struct",
".",
"pack",
"(",
"'<{}H'",
".",
"format",
"(",
"len",
"(",
"args",
")",
")",
",",
"*",
"args",
")",
")",
".",
"decode",
"(",
"'utf-8'",
")"
] | 30.285714 | 14.571429 |
def prt_goids(self, goids=None, prtfmt=None, sortby=True, prt=sys.stdout):
"""Given GO IDs, print decriptive info about each GO Term."""
if goids is None:
goids = self.go_sources
nts = self.get_nts(goids, sortby)
if prtfmt is None:
prtfmt = self.prt_attr['fmta']
... | [
"def",
"prt_goids",
"(",
"self",
",",
"goids",
"=",
"None",
",",
"prtfmt",
"=",
"None",
",",
"sortby",
"=",
"True",
",",
"prt",
"=",
"sys",
".",
"stdout",
")",
":",
"if",
"goids",
"is",
"None",
":",
"goids",
"=",
"self",
".",
"go_sources",
"nts",
... | 41.545455 | 12.727273 |
def get_stream(self, channel):
"""Return the stream of the given channel
:param channel: the channel that is broadcasting.
Either name or models.Channel instance
:type channel: :class:`str` | :class:`models.Channel`
:returns: the stream or None, if the channel is... | [
"def",
"get_stream",
"(",
"self",
",",
"channel",
")",
":",
"if",
"isinstance",
"(",
"channel",
",",
"models",
".",
"Channel",
")",
":",
"channel",
"=",
"channel",
".",
"name",
"r",
"=",
"self",
".",
"kraken_request",
"(",
"'GET'",
",",
"'streams/'",
"... | 39.133333 | 15.8 |
def generate_single_kcorrection_listing(
log,
pathToOutputDirectory,
pathToSpectralDatabase,
model,
restFrameFilter,
redshift,
temporalResolution=4.0):
"""
*Given a redshift generate a dictionary of k-correction polynomials for the MCS.*
**Key Argumen... | [
"def",
"generate_single_kcorrection_listing",
"(",
"log",
",",
"pathToOutputDirectory",
",",
"pathToSpectralDatabase",
",",
"model",
",",
"restFrameFilter",
",",
"redshift",
",",
"temporalResolution",
"=",
"4.0",
")",
":",
"################ > IMPORTS ################",
"## ... | 42.463054 | 22.817734 |
def _upload_part(api, session, url, upload, part_number, part, retry_count,
timeout):
"""
Used by the worker to upload a part to the storage service.
:param api: Api instance.
:param session: Storage service session.
:param url: Part url.
:param upload: Upload identifier.
:p... | [
"def",
"_upload_part",
"(",
"api",
",",
"session",
",",
"url",
",",
"upload",
",",
"part_number",
",",
"part",
",",
"retry_count",
",",
"timeout",
")",
":",
"part_url",
"=",
"retry",
"(",
"retry_count",
")",
"(",
"_get_part_url",
")",
"(",
"api",
",",
... | 33.090909 | 15.454545 |
def main():
"""Function to remove temperature effect from field data
"""
options = handle_options()
# read in observed and synthetic data
elecs, d_obs = readin_volt(options.d_obs)
elecs, d_est = readin_volt(options.d_est)
elecs, d_estTC = readin_volt(options.d_estTC)
# calculate correct... | [
"def",
"main",
"(",
")",
":",
"options",
"=",
"handle_options",
"(",
")",
"# read in observed and synthetic data",
"elecs",
",",
"d_obs",
"=",
"readin_volt",
"(",
"options",
".",
"d_obs",
")",
"elecs",
",",
"d_est",
"=",
"readin_volt",
"(",
"options",
".",
"... | 30 | 11.421053 |
def revoke_group_permission(
self, group_name, source_group_name, source_group_owner_id):
"""
This is a convenience function that wraps the "authorize group"
functionality of the C{authorize_security_group} method.
For an explanation of the parameters, see C{revoke_security_grou... | [
"def",
"revoke_group_permission",
"(",
"self",
",",
"group_name",
",",
"source_group_name",
",",
"source_group_owner_id",
")",
":",
"d",
"=",
"self",
".",
"revoke_security_group",
"(",
"group_name",
",",
"source_group_name",
"=",
"source_group_name",
",",
"source_grou... | 39.230769 | 18.153846 |
def sha1(self):
"""
:return:
The SHA1 hash of the DER-encoded bytes of this public key info
"""
if self._sha1 is None:
self._sha1 = hashlib.sha1(byte_cls(self['public_key'])).digest()
return self._sha1 | [
"def",
"sha1",
"(",
"self",
")",
":",
"if",
"self",
".",
"_sha1",
"is",
"None",
":",
"self",
".",
"_sha1",
"=",
"hashlib",
".",
"sha1",
"(",
"byte_cls",
"(",
"self",
"[",
"'public_key'",
"]",
")",
")",
".",
"digest",
"(",
")",
"return",
"self",
"... | 28.666667 | 20.444444 |
def use_plenary_sequence_rule_enabler_rule_view(self):
"""Pass through to provider SequenceRuleEnablerRuleLookupSession.use_plenary_sequence_rule_enabler_rule_view"""
self._object_views['sequence_rule_enabler_rule'] = PLENARY
# self._get_provider_session('sequence_rule_enabler_rule_lookup_sessio... | [
"def",
"use_plenary_sequence_rule_enabler_rule_view",
"(",
"self",
")",
":",
"self",
".",
"_object_views",
"[",
"'sequence_rule_enabler_rule'",
"]",
"=",
"PLENARY",
"# self._get_provider_session('sequence_rule_enabler_rule_lookup_session') # To make sure the session is tracked",
"for",... | 61.111111 | 23.444444 |
def _check_array_parms(is_array, array_size, value, element_kind,
element_name):
# pylint: disable=unused-argument
# The array_size argument is unused.
"""
Check whether array-related parameters are ok.
"""
# The following case has been disabled because it cannot happen g... | [
"def",
"_check_array_parms",
"(",
"is_array",
",",
"array_size",
",",
"value",
",",
"element_kind",
",",
"element_name",
")",
":",
"# pylint: disable=unused-argument",
"# The array_size argument is unused.",
"# The following case has been disabled because it cannot happen given",
"... | 43.428571 | 15.642857 |
def create(handler, item_document):
"""Create a new item from a JSON document"""
data = {'operation': 'create',
'item': json.load(item_document)}
handler.invoke(data) | [
"def",
"create",
"(",
"handler",
",",
"item_document",
")",
":",
"data",
"=",
"{",
"'operation'",
":",
"'create'",
",",
"'item'",
":",
"json",
".",
"load",
"(",
"item_document",
")",
"}",
"handler",
".",
"invoke",
"(",
"data",
")"
] | 37.2 | 6.4 |
def Operation(self, x, y):
"""Whether x is fully contained in y."""
if x in y:
return True
# x might be an iterable
# first we need to skip strings or we'll do silly things
# pylint: disable=consider-merging-isinstance
if isinstance(x, py2to3.STRING_TYPES) or isinstance(x, bytes):
r... | [
"def",
"Operation",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"if",
"x",
"in",
"y",
":",
"return",
"True",
"# x might be an iterable",
"# first we need to skip strings or we'll do silly things",
"# pylint: disable=consider-merging-isinstance",
"if",
"isinstance",
"(",
... | 25.277778 | 21.055556 |
def from_xdr(cls, xdr):
"""Create an :class:`Asset` object from its base64 encoded XDR
representation.
:param bytes xdr: The base64 encoded XDR Asset object.
:return: A new :class:`Asset` object from its encoded XDR
representation.
"""
xdr_decoded = base64.... | [
"def",
"from_xdr",
"(",
"cls",
",",
"xdr",
")",
":",
"xdr_decoded",
"=",
"base64",
".",
"b64decode",
"(",
"xdr",
")",
"asset",
"=",
"Xdr",
".",
"StellarXDRUnpacker",
"(",
"xdr_decoded",
")",
"asset_xdr_object",
"=",
"asset",
".",
"unpack_Asset",
"(",
")",
... | 33.133333 | 18 |
def dice_hard_coe(output, target, threshold=0.5, axis=(1, 2, 3), smooth=1e-5):
"""Non-differentiable Sørensen–Dice coefficient for comparing the similarity
of two batch of data, usually be used for binary image segmentation i.e. labels are binary.
The coefficient between 0 to 1, 1 if totally match.
Par... | [
"def",
"dice_hard_coe",
"(",
"output",
",",
"target",
",",
"threshold",
"=",
"0.5",
",",
"axis",
"=",
"(",
"1",
",",
"2",
",",
"3",
")",
",",
"smooth",
"=",
"1e-5",
")",
":",
"output",
"=",
"tf",
".",
"cast",
"(",
"output",
">",
"threshold",
",",... | 38.756757 | 22.027027 |
def _parse_endofnames(client, command, actor, args):
"""Parse an ENDOFNAMES and dispatch a NAMES event for the channel."""
args = args.split(" :", 1)[0] # Strip off human-readable message
_, _, channel = args.rpartition(' ')
channel = client.server.get_channel(channel) or channel.lower()
client.disp... | [
"def",
"_parse_endofnames",
"(",
"client",
",",
"command",
",",
"actor",
",",
"args",
")",
":",
"args",
"=",
"args",
".",
"split",
"(",
"\" :\"",
",",
"1",
")",
"[",
"0",
"]",
"# Strip off human-readable message",
"_",
",",
"_",
",",
"channel",
"=",
"a... | 57.5 | 12 |
def GetReportDownloadHeaders(self, **kwargs):
"""Returns a dictionary of headers for a report download request.
Note that the given keyword arguments will override any settings configured
from the googleads.yaml file.
Args:
**kwargs: Optional keyword arguments.
Keyword Arguments:
clie... | [
"def",
"GetReportDownloadHeaders",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"headers",
"=",
"self",
".",
"_adwords_client",
".",
"oauth2_client",
".",
"CreateHttpHeader",
"(",
")",
"headers",
".",
"update",
"(",
"{",
"'Content-type'",
":",
"self",
"."... | 41.948276 | 24.155172 |
def get_current_word_and_position(self, completion=False):
"""Return current word, i.e. word at cursor position,
and the start position"""
cursor = self.textCursor()
if cursor.hasSelection():
# Removes the selection and moves the cursor to the left side
... | [
"def",
"get_current_word_and_position",
"(",
"self",
",",
"completion",
"=",
"False",
")",
":",
"cursor",
"=",
"self",
".",
"textCursor",
"(",
")",
"if",
"cursor",
".",
"hasSelection",
"(",
")",
":",
"# Removes the selection and moves the cursor to the left side\r",
... | 52.304348 | 20.869565 |
def get_access_token(self, code, state=None):
'''
In callback url: http://host/callback?code=123&state=xyz
use code and state to get an access token.
'''
kw = dict(client_id=self._client_id, client_secret=self._client_secret, code=code)
if self._redirect_uri:
... | [
"def",
"get_access_token",
"(",
"self",
",",
"code",
",",
"state",
"=",
"None",
")",
":",
"kw",
"=",
"dict",
"(",
"client_id",
"=",
"self",
".",
"_client_id",
",",
"client_secret",
"=",
"self",
".",
"_client_secret",
",",
"code",
"=",
"code",
")",
"if"... | 42.130435 | 18.826087 |
def check_signature(signature, key, data):
"""Compute the HMAC signature and test against a given hash."""
if isinstance(key, type(u'')):
key = key.encode()
digest = 'sha1=' + hmac.new(key, data, hashlib.sha1).hexdigest()
# Covert everything to byte sequences
if isinstance(digest, type(u''... | [
"def",
"check_signature",
"(",
"signature",
",",
"key",
",",
"data",
")",
":",
"if",
"isinstance",
"(",
"key",
",",
"type",
"(",
"u''",
")",
")",
":",
"key",
"=",
"key",
".",
"encode",
"(",
")",
"digest",
"=",
"'sha1='",
"+",
"hmac",
".",
"new",
... | 34.642857 | 14.571429 |
def findparent(self, inputtemplates):
"""Find the most suitable parent, that is: the first matching unique/multi inputtemplate"""
for inputtemplate in inputtemplates:
if self.unique == inputtemplate.unique:
return inputtemplate.id
return None | [
"def",
"findparent",
"(",
"self",
",",
"inputtemplates",
")",
":",
"for",
"inputtemplate",
"in",
"inputtemplates",
":",
"if",
"self",
".",
"unique",
"==",
"inputtemplate",
".",
"unique",
":",
"return",
"inputtemplate",
".",
"id",
"return",
"None"
] | 48.166667 | 6.666667 |
def write_pkg_file(self, file):
"""Write the PKG-INFO format data to a file object.
"""
version = self.get_metadata_version()
if six.PY2:
def write_field(key, value):
file.write("%s: %s\n" % (key, self._encode_field(value)))
else:
def write_field(key, value):
... | [
"def",
"write_pkg_file",
"(",
"self",
",",
"file",
")",
":",
"version",
"=",
"self",
".",
"get_metadata_version",
"(",
")",
"if",
"six",
".",
"PY2",
":",
"def",
"write_field",
"(",
"key",
",",
"value",
")",
":",
"file",
".",
"write",
"(",
"\"%s: %s\\n\... | 32.72973 | 16.567568 |
def dry_lapse(pressure, temperature, ref_pressure=None):
r"""Calculate the temperature at a level assuming only dry processes.
This function lifts a parcel starting at `temperature`, conserving
potential temperature. The starting pressure can be given by `ref_pressure`.
Parameters
----------
p... | [
"def",
"dry_lapse",
"(",
"pressure",
",",
"temperature",
",",
"ref_pressure",
"=",
"None",
")",
":",
"if",
"ref_pressure",
"is",
"None",
":",
"ref_pressure",
"=",
"pressure",
"[",
"0",
"]",
"return",
"temperature",
"*",
"(",
"pressure",
"/",
"ref_pressure",
... | 32.96875 | 22.65625 |
def require_auth(request: Request, exceptions: bool=True) -> User:
"""
Returns authenticated User.
:param request: HttpRequest
:param exceptions: Raise (NotAuthenticated) exception. Default is True.
:return: User
"""
if not request.user or not request.user.is_authenticated:
if except... | [
"def",
"require_auth",
"(",
"request",
":",
"Request",
",",
"exceptions",
":",
"bool",
"=",
"True",
")",
"->",
"User",
":",
"if",
"not",
"request",
".",
"user",
"or",
"not",
"request",
".",
"user",
".",
"is_authenticated",
":",
"if",
"exceptions",
":",
... | 32.916667 | 15.25 |
def write_output(output_report, sample_name, multi_positions, genus, percent_contam, contam_stddev, total_gene_length,
database_download_date, snp_cutoff=3, cgmlst=None):
"""
Function that writes the output generated by ConFindr to a report file. Appends to a file that already exists,
or cr... | [
"def",
"write_output",
"(",
"output_report",
",",
"sample_name",
",",
"multi_positions",
",",
"genus",
",",
"percent_contam",
",",
"contam_stddev",
",",
"total_gene_length",
",",
"database_download_date",
",",
"snp_cutoff",
"=",
"3",
",",
"cgmlst",
"=",
"None",
")... | 70.583333 | 37.75 |
def _at_function(self, calculator, rule, scope, block):
"""
Implements @mixin and @function
"""
if not block.argument:
raise SyntaxError("%s requires a function name (%s)" % (block.directive, rule.file_and_line))
funct, argspec_node = self._get_funct_def(rule, calcul... | [
"def",
"_at_function",
"(",
"self",
",",
"calculator",
",",
"rule",
",",
"scope",
",",
"block",
")",
":",
"if",
"not",
"block",
".",
"argument",
":",
"raise",
"SyntaxError",
"(",
"\"%s requires a function name (%s)\"",
"%",
"(",
"block",
".",
"directive",
",... | 41.188235 | 17.023529 |
def _ls_sites(path):
"""
List only sites in the domain_sites() to ensure we co-exist with other projects
"""
with cd(path):
sites = run('ls').split('\n')
doms = [d.name for d in domain_sites()]
dom_sites = []
for s in sites:
ds = s.split('-')[0]
d... | [
"def",
"_ls_sites",
"(",
"path",
")",
":",
"with",
"cd",
"(",
"path",
")",
":",
"sites",
"=",
"run",
"(",
"'ls'",
")",
".",
"split",
"(",
"'\\n'",
")",
"doms",
"=",
"[",
"d",
".",
"name",
"for",
"d",
"in",
"domain_sites",
"(",
")",
"]",
"dom_si... | 31.214286 | 12.642857 |
def CreateSession(
cls, artifact_filter_names=None, command_line_arguments=None,
debug_mode=False, filter_file_path=None, preferred_encoding='utf-8',
preferred_time_zone=None, preferred_year=None):
"""Creates a session attribute container.
Args:
artifact_filter_names (Optional[list[str]... | [
"def",
"CreateSession",
"(",
"cls",
",",
"artifact_filter_names",
"=",
"None",
",",
"command_line_arguments",
"=",
"None",
",",
"debug_mode",
"=",
"False",
",",
"filter_file_path",
"=",
"None",
",",
"preferred_encoding",
"=",
"'utf-8'",
",",
"preferred_time_zone",
... | 40.935484 | 20.935484 |
def add_mapping(self, data, name=None):
"""
Add a new mapping
"""
from .mappings import DocumentObjectField
from .mappings import NestedObject
from .mappings import ObjectField
if isinstance(data, (DocumentObjectField, ObjectField, NestedObject)):
sel... | [
"def",
"add_mapping",
"(",
"self",
",",
"data",
",",
"name",
"=",
"None",
")",
":",
"from",
".",
"mappings",
"import",
"DocumentObjectField",
"from",
".",
"mappings",
"import",
"NestedObject",
"from",
".",
"mappings",
"import",
"ObjectField",
"if",
"isinstance... | 35.115385 | 12.346154 |
def query_pre_approvals(self, initial_date, final_date, page=None,
max_results=None):
""" query pre-approvals by date range """
last_page = False
results = []
while last_page is False:
search_result = self._consume_query_pre_approvals(
... | [
"def",
"query_pre_approvals",
"(",
"self",
",",
"initial_date",
",",
"final_date",
",",
"page",
"=",
"None",
",",
"max_results",
"=",
"None",
")",
":",
"last_page",
"=",
"False",
"results",
"=",
"[",
"]",
"while",
"last_page",
"is",
"False",
":",
"search_r... | 42.235294 | 17.117647 |
def master_open():
"""master_open() -> (master_fd, slave_name)
Open a pty master and return the fd, and the filename of the slave end.
Deprecated, use openpty() instead."""
try:
master_fd, slave_fd = os.openpty()
except (AttributeError, OSError):
pass
else:
slave_name = ... | [
"def",
"master_open",
"(",
")",
":",
"try",
":",
"master_fd",
",",
"slave_fd",
"=",
"os",
".",
"openpty",
"(",
")",
"except",
"(",
"AttributeError",
",",
"OSError",
")",
":",
"pass",
"else",
":",
"slave_name",
"=",
"os",
".",
"ttyname",
"(",
"slave_fd"... | 27.933333 | 17.666667 |
def post(self, request, bot_id, format=None):
"""
Add a new chat state
---
serializer: KikChatStateSerializer
responseMessages:
- code: 401
message: Not authenticated
- code: 400
message: Not valid request
"""
re... | [
"def",
"post",
"(",
"self",
",",
"request",
",",
"bot_id",
",",
"format",
"=",
"None",
")",
":",
"return",
"super",
"(",
"KikChatStateList",
",",
"self",
")",
".",
"post",
"(",
"request",
",",
"bot_id",
",",
"format",
")"
] | 31.083333 | 10.916667 |
def destroy(name, call=None):
'''
Destroy a machine by name
CLI Example:
.. code-block:: bash
salt-cloud -d vm_name
'''
if call == 'function':
raise SaltCloudSystemExit(
'The destroy action must be called with -d, --destroy, '
'-a or --action.'
... | [
"def",
"destroy",
"(",
"name",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The destroy action must be called with -d, --destroy, '",
"'-a or --action.'",
")",
"__utils__",
"[",
"'cloud.fire_event'",
... | 25.7 | 21.85 |
def list_cluster_custom_object(self, group, version, plural, **kwargs): # noqa: E501
"""list_cluster_custom_object # noqa: E501
list or watch cluster scoped custom objects # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, plea... | [
"def",
"list_cluster_custom_object",
"(",
"self",
",",
"group",
",",
"version",
",",
"plural",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")"... | 77.5 | 49.857143 |
def load(*fps, missing=Missing.silent):
"""
Read a `.Configuration` instance from file-like objects.
:param fps: file-like objects (supporting ``.read()``)
:param missing: policy to be used when a configured key is missing, either
as a `.Missing` instance or a default value
:return: a `.Con... | [
"def",
"load",
"(",
"*",
"fps",
",",
"missing",
"=",
"Missing",
".",
"silent",
")",
":",
"return",
"Configuration",
"(",
"*",
"(",
"yaml",
".",
"safe_load",
"(",
"fp",
".",
"read",
"(",
")",
")",
"for",
"fp",
"in",
"fps",
")",
",",
"missing",
"="... | 43.727273 | 19.363636 |
def _to_java_object_rdd(self):
""" Return a JavaRDD of Object by unpickling
It will convert each Python object into Java object by Pyrolite, whenever the
RDD is serialized in batch or not.
"""
rdd = self._pickled()
return self.ctx._jvm.SerDeUtil.pythonToJava(rdd._jrdd, T... | [
"def",
"_to_java_object_rdd",
"(",
"self",
")",
":",
"rdd",
"=",
"self",
".",
"_pickled",
"(",
")",
"return",
"self",
".",
"ctx",
".",
"_jvm",
".",
"SerDeUtil",
".",
"pythonToJava",
"(",
"rdd",
".",
"_jrdd",
",",
"True",
")"
] | 39.625 | 17 |
def classes(self, set_uri_or_id=None, nestedhierarchy=False):
"""Returns a dictionary of classes for the specified (sub)set (if None, default, the main set is selected)"""
if set_uri_or_id and set_uri_or_id.startswith(('http://','https://')):
set_uri = set_uri_or_id
else:
... | [
"def",
"classes",
"(",
"self",
",",
"set_uri_or_id",
"=",
"None",
",",
"nestedhierarchy",
"=",
"False",
")",
":",
"if",
"set_uri_or_id",
"and",
"set_uri_or_id",
".",
"startswith",
"(",
"(",
"'http://'",
",",
"'https://'",
")",
")",
":",
"set_uri",
"=",
"se... | 54.088235 | 29.470588 |
def cake(return_X_y=True):
"""cake dataset
Parameters
----------
return_X_y : bool,
if True, returns a model-ready tuple of data (X, y)
otherwise, returns a Pandas DataFrame
Returns
-------
model-ready tuple of data (X, y)
OR
Pandas DataFrame
Notes
----... | [
"def",
"cake",
"(",
"return_X_y",
"=",
"True",
")",
":",
"# y is real",
"# recommend LinearGAM",
"cake",
"=",
"pd",
".",
"read_csv",
"(",
"PATH",
"+",
"'/cake.csv'",
",",
"index_col",
"=",
"0",
")",
"if",
"return_X_y",
":",
"X",
"=",
"cake",
"[",
"[",
... | 25.771429 | 22.285714 |
def available(name):
'''
.. versionadded:: 2014.7.0
Returns ``True`` if the specified service is available, otherwise returns
``False``.
CLI Example:
.. code-block:: bash
salt '*' service.available sshd
'''
path = '/etc/rc.d/{0}'.format(name)
return os.path.isfile(path) a... | [
"def",
"available",
"(",
"name",
")",
":",
"path",
"=",
"'/etc/rc.d/{0}'",
".",
"format",
"(",
"name",
")",
"return",
"os",
".",
"path",
".",
"isfile",
"(",
"path",
")",
"and",
"os",
".",
"access",
"(",
"path",
",",
"os",
".",
"X_OK",
")"
] | 22.2 | 25.4 |
def from_yaml(self, node):
'''
Implementes a !from_yaml constructor with the following syntax:
!from_yaml filename key
Arguments:
filename: Filename of external YAML document from which to load,
relative to the current YAML file.
key... | [
"def",
"from_yaml",
"(",
"self",
",",
"node",
")",
":",
"# Load the content from the node, as a scalar",
"content",
"=",
"self",
".",
"construct_scalar",
"(",
"node",
")",
"# Split on unquoted spaces",
"try",
":",
"parts",
"=",
"shlex",
".",
"split",
"(",
"content... | 33.644444 | 21.644444 |
def count(fn, coll):
"""Return the count of True values returned by the predicate function applied to the
collection
:param fn: a predicate function
:param coll: a collection
:returns: an integer
>>> count(lambda x: x % 2 == 0, [11, 22, 31, 24, 15])
2
"""
return len([x for x in co... | [
"def",
"count",
"(",
"fn",
",",
"coll",
")",
":",
"return",
"len",
"(",
"[",
"x",
"for",
"x",
"in",
"coll",
"if",
"fn",
"(",
"x",
")",
"is",
"True",
"]",
")"
] | 25.307692 | 20 |
def github_token(token_path=None, token=None):
"""Return a github oauth token as a string. If `token` is defined, it is
has precendece. If `token` and `token_path` are `None`,
`~/.sq_github_token` looked for as a fallback.
Parameters
----------
token_path : str, optional
Path to the t... | [
"def",
"github_token",
"(",
"token_path",
"=",
"None",
",",
"token",
"=",
"None",
")",
":",
"if",
"token",
"is",
"None",
":",
"if",
"token_path",
"is",
"None",
":",
"# Try the default token",
"token_path",
"=",
"'~/.sq_github_token'",
"token_path",
"=",
"os",
... | 32.941176 | 19.529412 |
def _parse_record(self, record_type):
"""Parse a record."""
if self._next_token() in ['{', '(']:
key = self._next_token()
self.records[key] = {
u'id': key,
u'type': record_type.lower()
}
if self._next_token() == ',':
... | [
"def",
"_parse_record",
"(",
"self",
",",
"record_type",
")",
":",
"if",
"self",
".",
"_next_token",
"(",
")",
"in",
"[",
"'{'",
",",
"'('",
"]",
":",
"key",
"=",
"self",
".",
"_next_token",
"(",
")",
"self",
".",
"records",
"[",
"key",
"]",
"=",
... | 43.703704 | 11.518519 |
def _process_targeting_reagents(self, reagent_type, limit=None):
"""
This method processes the gene targeting knockdown reagents,
such as morpholinos, talens, and crisprs.
We create triples for the reagents and pass the data into a hash map
for use in the pheno_enviro method.
... | [
"def",
"_process_targeting_reagents",
"(",
"self",
",",
"reagent_type",
",",
"limit",
"=",
"None",
")",
":",
"LOG",
".",
"info",
"(",
"\"Processing Gene Targeting Reagents\"",
")",
"if",
"self",
".",
"test_mode",
":",
"graph",
"=",
"self",
".",
"testgraph",
"e... | 40.964286 | 21.892857 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.