text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def heatmap(n_x=5,n_y=10):
"""
Returns a DataFrame with the required format for
a heatmap plot
Parameters:
-----------
n_x : int
Number of x categories
n_y : int
Number of y categories
"""
x=['x_'+str(_) for _ in range(n_x)]
y=['y_'+str(_) for _ in range(n_y)]
return pd.DataFrame(surface(n_x-1,n_y... | [
"def",
"heatmap",
"(",
"n_x",
"=",
"5",
",",
"n_y",
"=",
"10",
")",
":",
"x",
"=",
"[",
"'x_'",
"+",
"str",
"(",
"_",
")",
"for",
"_",
"in",
"range",
"(",
"n_x",
")",
"]",
"y",
"=",
"[",
"'y_'",
"+",
"str",
"(",
"_",
")",
"for",
"_",
"i... | 22.333333 | 0.063037 |
def convert_batchnorm(builder, layer, input_names, output_names, keras_layer):
"""
Parameters
keras_layer: layer
A keras layer object.
builder: NeuralNetworkBuilder
A neural network builder object.
"""
# Get input and output names
input_name, output_name = (input_names[0], ... | [
"def",
"convert_batchnorm",
"(",
"builder",
",",
"layer",
",",
"input_names",
",",
"output_names",
",",
"keras_layer",
")",
":",
"# Get input and output names",
"input_name",
",",
"output_name",
"=",
"(",
"input_names",
"[",
"0",
"]",
",",
"output_names",
"[",
"... | 28.422222 | 0.016629 |
def update_offset(self, offset):
# type: (int) -> None
'''
Update the offset for this CE record.
Parameters:
extent - The new offset for this CE record.
Returns:
Nothing.
'''
if not self._initialized:
raise pycdlibexception.PyCdlibIn... | [
"def",
"update_offset",
"(",
"self",
",",
"offset",
")",
":",
"# type: (int) -> None",
"if",
"not",
"self",
".",
"_initialized",
":",
"raise",
"pycdlibexception",
".",
"PyCdlibInternalError",
"(",
"'CE record not yet initialized!'",
")",
"self",
".",
"offset_cont_area... | 28 | 0.009877 |
def get_param(self):
"""Method to get current optimizer's parameter value
"""
lr_list = self.lr_scheduler.get_lr()
if len(lr_list) > 1:
raise ValueError("Optimizer passed to lr_scheduler should have a single param group, "
"but currently there are... | [
"def",
"get_param",
"(",
"self",
")",
":",
"lr_list",
"=",
"self",
".",
"lr_scheduler",
".",
"get_lr",
"(",
")",
"if",
"len",
"(",
"lr_list",
")",
">",
"1",
":",
"raise",
"ValueError",
"(",
"\"Optimizer passed to lr_scheduler should have a single param group, \"",... | 47.25 | 0.01039 |
def get_url(path, dest='', saltenv='base', makedirs=False, source_hash=None):
'''
.. versionchanged:: 2018.3.0
``dest`` can now be a directory
Used to get a single file from a URL.
path
A URL to download a file from. Supported URL schemes are: ``salt://``,
``http://``, ``https:... | [
"def",
"get_url",
"(",
"path",
",",
"dest",
"=",
"''",
",",
"saltenv",
"=",
"'base'",
",",
"makedirs",
"=",
"False",
",",
"source_hash",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"dest",
",",
"six",
".",
"string_types",
")",
":",
"result",
"=",... | 39.559322 | 0.000836 |
def write_aims(filename, atoms):
"""Method to write FHI-aims geometry files in phonopy context."""
lines = ""
lines += "# geometry.in for FHI-aims \n"
lines += "# | generated by phonopy.FHIaims.write_aims() \n"
lattice_vector_line = "lattice_vector " + "%16.16f "*3 + "\n"
for vec in atoms.get_... | [
"def",
"write_aims",
"(",
"filename",
",",
"atoms",
")",
":",
"lines",
"=",
"\"\"",
"lines",
"+=",
"\"# geometry.in for FHI-aims \\n\"",
"lines",
"+=",
"\"# | generated by phonopy.FHIaims.write_aims() \\n\"",
"lattice_vector_line",
"=",
"\"lattice_vector \"",
"+",
"\"%16.16... | 31.518519 | 0.00114 |
def set_client_ca_list(self, certificate_authorities):
"""
Set the list of preferred client certificate signers for this server
context.
This list of certificate authorities will be sent to the client when
the server requests a client certificate.
:param certificate_aut... | [
"def",
"set_client_ca_list",
"(",
"self",
",",
"certificate_authorities",
")",
":",
"name_stack",
"=",
"_lib",
".",
"sk_X509_NAME_new_null",
"(",
")",
"_openssl_assert",
"(",
"name_stack",
"!=",
"_ffi",
".",
"NULL",
")",
"try",
":",
"for",
"ca_name",
"in",
"ce... | 36.472222 | 0.001484 |
def mean_if_greater_than_zero(vals):
""" Calculate mean over numerical values, ignoring values less than zero.
E.g. used for mean time over coincident triggers when timestamps are set
to -1 for ifos not included in the coincidence.
Parameters
----------
vals: iterator of numerical values
... | [
"def",
"mean_if_greater_than_zero",
"(",
"vals",
")",
":",
"vals",
"=",
"numpy",
".",
"array",
"(",
"vals",
")",
"above_zero",
"=",
"vals",
">",
"0",
"return",
"vals",
"[",
"above_zero",
"]",
".",
"mean",
"(",
")",
",",
"above_zero",
".",
"sum",
"(",
... | 31.619048 | 0.001462 |
def normalizeBoolean(value):
"""
Normalizes a boolean.
* **value** must be an ``int`` with value of 0 or 1, or a ``bool``.
* Returned value will be a boolean.
"""
if isinstance(value, int) and value in (0, 1):
value = bool(value)
if not isinstance(value, bool):
raise ValueEr... | [
"def",
"normalizeBoolean",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"int",
")",
"and",
"value",
"in",
"(",
"0",
",",
"1",
")",
":",
"value",
"=",
"bool",
"(",
"value",
")",
"if",
"not",
"isinstance",
"(",
"value",
",",
"bool",... | 31.692308 | 0.002358 |
def which(cmd, safe=False):
"""https://github.com/jc0n/python-which"""
from autopaths.file_path import FilePath
def is_executable(path):
return os.path.exists(path) and os.access(path, os.X_OK) and not os.path.isdir(path)
path, name = os.path.split(cmd)
if path:
if is_executable(cmd)... | [
"def",
"which",
"(",
"cmd",
",",
"safe",
"=",
"False",
")",
":",
"from",
"autopaths",
".",
"file_path",
"import",
"FilePath",
"def",
"is_executable",
"(",
"path",
")",
":",
"return",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
"and",
"os",
".... | 46.615385 | 0.011327 |
def set_power(self, state):
"""Sets the power state of the smart plug."""
packet = bytearray(16)
packet[0] = 2
if self.check_nightlight():
packet[4] = 3 if state else 2
else:
packet[4] = 1 if state else 0
self.send_packet(0x6a, packet) | [
"def",
"set_power",
"(",
"self",
",",
"state",
")",
":",
"packet",
"=",
"bytearray",
"(",
"16",
")",
"packet",
"[",
"0",
"]",
"=",
"2",
"if",
"self",
".",
"check_nightlight",
"(",
")",
":",
"packet",
"[",
"4",
"]",
"=",
"3",
"if",
"state",
"else"... | 29.222222 | 0.01107 |
def compare_schemas(one, two):
"""Compare two structures that represents JSON schemas.
For comparison you can't use normal comparison, because in JSON schema
lists DO NOT keep order (and Python lists do), so this must be taken into
account during comparison.
Note this wont check all configurations... | [
"def",
"compare_schemas",
"(",
"one",
",",
"two",
")",
":",
"one",
"=",
"_normalize_string_type",
"(",
"one",
")",
"two",
"=",
"_normalize_string_type",
"(",
"two",
")",
"_assert_same_types",
"(",
"one",
",",
"two",
")",
"if",
"isinstance",
"(",
"one",
","... | 30.774194 | 0.001016 |
def _handle_timeout(self) -> None:
"""Called by IOLoop when the requested timeout has passed."""
self._timeout = None
while True:
try:
ret, num_handles = self._multi.socket_action(pycurl.SOCKET_TIMEOUT, 0)
except pycurl.error as e:
ret = e.... | [
"def",
"_handle_timeout",
"(",
"self",
")",
"->",
"None",
":",
"self",
".",
"_timeout",
"=",
"None",
"while",
"True",
":",
"try",
":",
"ret",
",",
"num_handles",
"=",
"self",
".",
"_multi",
".",
"socket_action",
"(",
"pycurl",
".",
"SOCKET_TIMEOUT",
",",... | 49.785714 | 0.002111 |
def _get_context(center_idx, sentence_boundaries, window_size,
random_window_size, seed):
"""Compute the context with respect to a center word in a sentence.
Takes an numpy array of sentences boundaries.
"""
random.seed(seed + center_idx)
sentence_index = np.searchsorted(sentence... | [
"def",
"_get_context",
"(",
"center_idx",
",",
"sentence_boundaries",
",",
"window_size",
",",
"random_window_size",
",",
"seed",
")",
":",
"random",
".",
"seed",
"(",
"seed",
"+",
"center_idx",
")",
"sentence_index",
"=",
"np",
".",
"searchsorted",
"(",
"sent... | 36.37931 | 0.000923 |
def character_embedding_network(char_placeholder: tf.Tensor,
n_characters: int = None,
emb_mat: np.array = None,
char_embedding_dim: int = None,
filter_widths=(3, 4, 5, 7),
... | [
"def",
"character_embedding_network",
"(",
"char_placeholder",
":",
"tf",
".",
"Tensor",
",",
"n_characters",
":",
"int",
"=",
"None",
",",
"emb_mat",
":",
"np",
".",
"array",
"=",
"None",
",",
"char_embedding_dim",
":",
"int",
"=",
"None",
",",
"filter_widt... | 51.05 | 0.001922 |
def analyze(self, mode=None, timesteps=None):
"""Analyzes the grid by power flow analysis
Analyze the grid for violations of hosting capacity. Means, perform a
power flow analysis and obtain voltages at nodes (load, generator,
stations/transformers and branch tees) and active/reactive p... | [
"def",
"analyze",
"(",
"self",
",",
"mode",
"=",
"None",
",",
"timesteps",
"=",
"None",
")",
":",
"if",
"timesteps",
"is",
"None",
":",
"timesteps",
"=",
"self",
".",
"network",
".",
"timeseries",
".",
"timeindex",
"# check if timesteps is array-like, otherwis... | 45.1 | 0.000723 |
def set_trace(host=None, port=None, patch_stdstreams=False):
"""
Opens a remote PDB on first available port.
"""
if host is None:
host = os.environ.get('REMOTE_PDB_HOST', '127.0.0.1')
if port is None:
port = int(os.environ.get('REMOTE_PDB_PORT', '0'))
rdb = RemotePdb(host=host, p... | [
"def",
"set_trace",
"(",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"patch_stdstreams",
"=",
"False",
")",
":",
"if",
"host",
"is",
"None",
":",
"host",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'REMOTE_PDB_HOST'",
",",
"'127.0.0.1'",
")",
... | 40.3 | 0.002427 |
def truncate_string(value, max_width=None):
"""Truncate string values."""
if isinstance(value, text_type) and max_width is not None and len(value) > max_width:
return value[:max_width]
return value | [
"def",
"truncate_string",
"(",
"value",
",",
"max_width",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"text_type",
")",
"and",
"max_width",
"is",
"not",
"None",
"and",
"len",
"(",
"value",
")",
">",
"max_width",
":",
"return",
"value",
... | 42.6 | 0.009217 |
def plan_results(self, project_key, plan_key, expand=None, favourite=False, clover_enabled=False, label=None,
issue_key=None, start_index=0, max_results=25):
"""
Get Plan results
:param project_key:
:param plan_key:
:param expand:
:param favourite:
... | [
"def",
"plan_results",
"(",
"self",
",",
"project_key",
",",
"plan_key",
",",
"expand",
"=",
"None",
",",
"favourite",
"=",
"False",
",",
"clover_enabled",
"=",
"False",
",",
"label",
"=",
"None",
",",
"issue_key",
"=",
"None",
",",
"start_index",
"=",
"... | 40.882353 | 0.008439 |
def cylinder(target, throat_length='throat.length',
throat_diameter='throat.diameter'):
r"""
Calculate throat volume assuing a cylindrical shape
Parameters
----------
target : OpenPNM Object
The object which this model is associated with. This controls the
length of the... | [
"def",
"cylinder",
"(",
"target",
",",
"throat_length",
"=",
"'throat.length'",
",",
"throat_diameter",
"=",
"'throat.diameter'",
")",
":",
"leng",
"=",
"target",
"[",
"throat_length",
"]",
"diam",
"=",
"target",
"[",
"throat_diameter",
"]",
"value",
"=",
"_sp... | 32.52 | 0.001195 |
def merge_webhooks_runset(runset):
"""Make some statistics on the run set.
"""
min_started_at = min([w['started_at'] for w in runset])
max_ended_at = max([w['ended_at'] for w in runset])
ellapse = max_ended_at - min_started_at
errors_count = sum(1 for w in runset if 'error' in w)
total_coun... | [
"def",
"merge_webhooks_runset",
"(",
"runset",
")",
":",
"min_started_at",
"=",
"min",
"(",
"[",
"w",
"[",
"'started_at'",
"]",
"for",
"w",
"in",
"runset",
"]",
")",
"max_ended_at",
"=",
"max",
"(",
"[",
"w",
"[",
"'ended_at'",
"]",
"for",
"w",
"in",
... | 26.647059 | 0.002132 |
def _string(self):
""":return: the string from a :class:`io.StringIO`"""
file = StringIO()
self.__dump_to_file(file)
file.seek(0)
return file.read() | [
"def",
"_string",
"(",
"self",
")",
":",
"file",
"=",
"StringIO",
"(",
")",
"self",
".",
"__dump_to_file",
"(",
"file",
")",
"file",
".",
"seek",
"(",
"0",
")",
"return",
"file",
".",
"read",
"(",
")"
] | 30.5 | 0.010638 |
def idaunpack(buf):
"""
Special data packing format, used in struct definitions, and .id2 files
sdk functions: pack_dd etc.
"""
buf = bytearray(buf)
def nextval(o):
val = buf[o] ; o += 1
if val == 0xff: # 32 bit value
val, = struct.unpack_from(">L", buf,... | [
"def",
"idaunpack",
"(",
"buf",
")",
":",
"buf",
"=",
"bytearray",
"(",
"buf",
")",
"def",
"nextval",
"(",
"o",
")",
":",
"val",
"=",
"buf",
"[",
"o",
"]",
"o",
"+=",
"1",
"if",
"val",
"==",
"0xff",
":",
"# 32 bit value\r",
"val",
",",
"=",
"st... | 24.323529 | 0.010465 |
def get_all_requisite_objectives(self, objective_id=None):
"""Gets a list of Objectives that are the requisites for the given
Objective including the requistes of the requisites, and so on.
In plenary mode, the returned list contains all of the immediate
requisites, or an error results ... | [
"def",
"get_all_requisite_objectives",
"(",
"self",
",",
"objective_id",
"=",
"None",
")",
":",
"# This should be re-implemented if and when handcar supports",
"# getting all requisites directly",
"requisites",
"=",
"list",
"(",
")",
"requisite_ids",
"=",
"list",
"(",
")",
... | 49.230769 | 0.002299 |
def _updateParamsFrom(self, *args, **kwargs):
"""
:note: doc in :func:`~hwt.synthesizer.interfaceLevel.propDeclCollector._updateParamsFrom`
"""
for o in self:
o._updateParamsFrom(*args, **kwargs) | [
"def",
"_updateParamsFrom",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"o",
"in",
"self",
":",
"o",
".",
"_updateParamsFrom",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 39 | 0.012552 |
def compute_mem_overhead(self):
"""Returns memory overhead."""
self.mem_overhead = (self._process.memory_info().rss -
builtins.initial_rss_size) | [
"def",
"compute_mem_overhead",
"(",
"self",
")",
":",
"self",
".",
"mem_overhead",
"=",
"(",
"self",
".",
"_process",
".",
"memory_info",
"(",
")",
".",
"rss",
"-",
"builtins",
".",
"initial_rss_size",
")"
] | 46.5 | 0.010582 |
def colour_rgb(self):
"""Return colour as RGB value"""
hexvalue = self.status()[self.DPS][self.DPS_INDEX_COLOUR]
return BulbDevice._hexvalue_to_rgb(hexvalue) | [
"def",
"colour_rgb",
"(",
"self",
")",
":",
"hexvalue",
"=",
"self",
".",
"status",
"(",
")",
"[",
"self",
".",
"DPS",
"]",
"[",
"self",
".",
"DPS_INDEX_COLOUR",
"]",
"return",
"BulbDevice",
".",
"_hexvalue_to_rgb",
"(",
"hexvalue",
")"
] | 44.5 | 0.01105 |
def EQ106(T, Tc, A, B, C=0, D=0, E=0):
r'''DIPPR Equation #106. Often used in calculating liquid surface tension,
and heat of vaporization.
Only parameters A and B parameters are required; many fits include no
further parameters. Critical temperature is also required.
.. math::
Y = A(1-T_r)... | [
"def",
"EQ106",
"(",
"T",
",",
"Tc",
",",
"A",
",",
"B",
",",
"C",
"=",
"0",
",",
"D",
"=",
"0",
",",
"E",
"=",
"0",
")",
":",
"Tr",
"=",
"T",
"/",
"Tc",
"return",
"A",
"*",
"(",
"1.",
"-",
"Tr",
")",
"**",
"(",
"B",
"+",
"Tr",
"*",... | 25.909091 | 0.000845 |
def append_position_to_token_list(token_list):
"""Converts a list of Token into a list of Token, asuming size == 1"""
return [PositionToken(value.content, value.gd, index, index+1) for (index, value) in enumerate(token_list)] | [
"def",
"append_position_to_token_list",
"(",
"token_list",
")",
":",
"return",
"[",
"PositionToken",
"(",
"value",
".",
"content",
",",
"value",
".",
"gd",
",",
"index",
",",
"index",
"+",
"1",
")",
"for",
"(",
"index",
",",
"value",
")",
"in",
"enumerat... | 77 | 0.008584 |
def delete_mappings_in_network(network_id, network_2_id=None, **kwargs):
"""
Delete all the resource attribute mappings in a network. If another network
is specified, only delete the mappings between the two networks.
"""
qry = db.DBSession.query(ResourceAttrMap).filter(or_(ResourceAttrMap.n... | [
"def",
"delete_mappings_in_network",
"(",
"network_id",
",",
"network_2_id",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"qry",
"=",
"db",
".",
"DBSession",
".",
"query",
"(",
"ResourceAttrMap",
")",
".",
"filter",
"(",
"or_",
"(",
"ResourceAttrMap",
"... | 38.235294 | 0.009009 |
def register_new_suffix_tree(case_insensitive=False):
"""Factory method, returns new suffix tree object.
"""
assert isinstance(case_insensitive, bool)
root_node = register_new_node()
suffix_tree_id = uuid4()
event = SuffixTree.Created(
originator_id=suffix_tree_id,
root_node_id=... | [
"def",
"register_new_suffix_tree",
"(",
"case_insensitive",
"=",
"False",
")",
":",
"assert",
"isinstance",
"(",
"case_insensitive",
",",
"bool",
")",
"root_node",
"=",
"register_new_node",
"(",
")",
"suffix_tree_id",
"=",
"uuid4",
"(",
")",
"event",
"=",
"Suffi... | 25.333333 | 0.001812 |
def get_or_create_in_transaction_wrapper(tsession, model, values, missing_columns = [], variable_columns = [], updatable_columns = [], only_use_supplied_columns = False, read_only = False):
'''This function can be used to determine which calling method is spending time in get_or_create_in_transaction when profiling... | [
"def",
"get_or_create_in_transaction_wrapper",
"(",
"tsession",
",",
"model",
",",
"values",
",",
"missing_columns",
"=",
"[",
"]",
",",
"variable_columns",
"=",
"[",
"]",
",",
"updatable_columns",
"=",
"[",
"]",
",",
"only_use_supplied_columns",
"=",
"False",
"... | 187.25 | 0.033245 |
def download_url(url, save_as, iter_size=_default_iter_size, enable_verbose=True):
"""A simple url binary content download function with progress info.
Warning: this function will silently overwrite existing file.
"""
msg = Messenger()
if enable_verbose:
msg.on()
else:
msg.off()... | [
"def",
"download_url",
"(",
"url",
",",
"save_as",
",",
"iter_size",
"=",
"_default_iter_size",
",",
"enable_verbose",
"=",
"True",
")",
":",
"msg",
"=",
"Messenger",
"(",
")",
"if",
"enable_verbose",
":",
"msg",
".",
"on",
"(",
")",
"else",
":",
"msg",
... | 30.363636 | 0.001934 |
def create_dvportgroup(portgroup_dict, portgroup_name, dvs,
service_instance=None):
'''
Creates a distributed virtual portgroup.
Note: The ``portgroup_name`` param will override any name already set
in ``portgroup_dict``.
portgroup_dict
Dictionary with the config val... | [
"def",
"create_dvportgroup",
"(",
"portgroup_dict",
",",
"portgroup_name",
",",
"dvs",
",",
"service_instance",
"=",
"None",
")",
":",
"log",
".",
"trace",
"(",
"'Creating portgroup\\'%s\\' in dvs \\'%s\\' '",
"'with dict = %s'",
",",
"portgroup_name",
",",
"dvs",
","... | 38.326087 | 0.000553 |
def _onLeftButtonDClick(self, evt):
"""Start measuring on an axis."""
x = evt.GetX()
y = self.figure.bbox.height - evt.GetY()
evt.Skip()
self.CaptureMouse()
FigureCanvasBase.button_press_event(self, x, y, 1, dblclick=True, guiEvent=evt) | [
"def",
"_onLeftButtonDClick",
"(",
"self",
",",
"evt",
")",
":",
"x",
"=",
"evt",
".",
"GetX",
"(",
")",
"y",
"=",
"self",
".",
"figure",
".",
"bbox",
".",
"height",
"-",
"evt",
".",
"GetY",
"(",
")",
"evt",
".",
"Skip",
"(",
")",
"self",
".",
... | 39.714286 | 0.010563 |
def _position_in_feature(pos_a, pos_b):
"""return distance to 3' and 5' end of the feature"""
strd = "-"
if pos_a[2] in pos_b[2]:
strd = "+"
if pos_a[2] in "+" and pos_b[2] in "+":
lento5 = pos_a[0] - pos_b[1] + 1
lento3 = pos_a[1] - pos_b[1] + 1
if pos_a[2] in "+" and pos_b[... | [
"def",
"_position_in_feature",
"(",
"pos_a",
",",
"pos_b",
")",
":",
"strd",
"=",
"\"-\"",
"if",
"pos_a",
"[",
"2",
"]",
"in",
"pos_b",
"[",
"2",
"]",
":",
"strd",
"=",
"\"+\"",
"if",
"pos_a",
"[",
"2",
"]",
"in",
"\"+\"",
"and",
"pos_b",
"[",
"2... | 36.571429 | 0.001269 |
def remove_password_from_url(url):
# type: (S) -> S
"""
Given a url, remove the password and insert 4 dashes
:param url: The url to replace the authentication in
:type url: S
:return: The new URL without authentication
:rtype: S
"""
parsed = _get_parsed_url(url)
if parsed.auth:... | [
"def",
"remove_password_from_url",
"(",
"url",
")",
":",
"# type: (S) -> S",
"parsed",
"=",
"_get_parsed_url",
"(",
"url",
")",
"if",
"parsed",
".",
"auth",
":",
"auth",
",",
"_",
",",
"_",
"=",
"parsed",
".",
"auth",
".",
"partition",
"(",
"\":\"",
")",... | 28 | 0.00216 |
def from_zipfile(cls, path, filename, encoding, dialect, fields, converters):
"""Read delimited text from zipfile."""
stream = ZipReader(path, filename).readlines(encoding)
return cls(stream, dialect, fields, converters) | [
"def",
"from_zipfile",
"(",
"cls",
",",
"path",
",",
"filename",
",",
"encoding",
",",
"dialect",
",",
"fields",
",",
"converters",
")",
":",
"stream",
"=",
"ZipReader",
"(",
"path",
",",
"filename",
")",
".",
"readlines",
"(",
"encoding",
")",
"return",... | 48.2 | 0.008163 |
def get_checklist(self, id, name=None):
'''
Get a checklist
Returns:
Checklist: The checklist with the given `id`
'''
return self.create_checklist(dict(id=id, name=name)) | [
"def",
"get_checklist",
"(",
"self",
",",
"id",
",",
"name",
"=",
"None",
")",
":",
"return",
"self",
".",
"create_checklist",
"(",
"dict",
"(",
"id",
"=",
"id",
",",
"name",
"=",
"name",
")",
")"
] | 27 | 0.008969 |
def _get_ssl(self):
"""Get an SMTP session with SSL."""
return smtplib.SMTP_SSL(
self.server, self.port, context=ssl.create_default_context()
) | [
"def",
"_get_ssl",
"(",
"self",
")",
":",
"return",
"smtplib",
".",
"SMTP_SSL",
"(",
"self",
".",
"server",
",",
"self",
".",
"port",
",",
"context",
"=",
"ssl",
".",
"create_default_context",
"(",
")",
")"
] | 35 | 0.011173 |
def get_turnover(positions, transactions, denominator='AGB'):
"""
- Value of purchases and sales divided
by either the actual gross book or the portfolio value
for the time step.
Parameters
----------
positions : pd.DataFrame
Contains daily position values including cash.
-... | [
"def",
"get_turnover",
"(",
"positions",
",",
"transactions",
",",
"denominator",
"=",
"'AGB'",
")",
":",
"txn_vol",
"=",
"get_txn_vol",
"(",
"transactions",
")",
"traded_value",
"=",
"txn_vol",
".",
"txn_volume",
"if",
"denominator",
"==",
"'AGB'",
":",
"# Ac... | 37.448276 | 0.000449 |
def validate_v2_endpoint_data(self, endpoints, admin_port, internal_port,
public_port, expected):
"""Validate endpoint data.
Validate actual endpoint data vs expected endpoint data. The ports
are used to find the matching endpoint.
"""
... | [
"def",
"validate_v2_endpoint_data",
"(",
"self",
",",
"endpoints",
",",
"admin_port",
",",
"internal_port",
",",
"public_port",
",",
"expected",
")",
":",
"self",
".",
"log",
".",
"debug",
"(",
"'Validating endpoint data...'",
")",
"self",
".",
"log",
".",
"de... | 43.428571 | 0.002414 |
def add_config(self, key, type_, default=NOT_SET, env_var=None):
"""Add a configuration setting.
Parameters
----------
key : str
The name of the configuration setting. This must be a valid
Python attribute name i.e. alphanumeric with underscores.
type : f... | [
"def",
"add_config",
"(",
"self",
",",
"key",
",",
"type_",
",",
"default",
"=",
"NOT_SET",
",",
"env_var",
"=",
"None",
")",
":",
"self",
".",
"config",
"[",
"key",
"]",
"=",
"{",
"'type'",
":",
"type_",
"}",
"if",
"env_var",
"is",
"not",
"None",
... | 45.241379 | 0.001493 |
def minus(self, a):
""" Subtract. """
return Vector(self.x-a.x, self.y-a.y, self.z-a.z) | [
"def",
"minus",
"(",
"self",
",",
"a",
")",
":",
"return",
"Vector",
"(",
"self",
".",
"x",
"-",
"a",
".",
"x",
",",
"self",
".",
"y",
"-",
"a",
".",
"y",
",",
"self",
".",
"z",
"-",
"a",
".",
"z",
")"
] | 33.666667 | 0.019417 |
def gen_mac(prefix='AC:DE:48'):
'''
Generates a MAC address with the defined OUI prefix.
Common prefixes:
- ``00:16:3E`` -- Xen
- ``00:18:51`` -- OpenVZ
- ``00:50:56`` -- VMware (manually generated)
- ``52:54:00`` -- QEMU/KVM
- ``AC:DE:48`` -- PRIVATE
References:
- http... | [
"def",
"gen_mac",
"(",
"prefix",
"=",
"'AC:DE:48'",
")",
":",
"return",
"'{0}:{1:02X}:{2:02X}:{3:02X}'",
".",
"format",
"(",
"prefix",
",",
"random",
".",
"randint",
"(",
"0",
",",
"0xff",
")",
",",
"random",
".",
"randint",
"(",
"0",
",",
"0xff",
")",
... | 33.409091 | 0.001323 |
def data(self, index, role):
'''Return data for *index* according to *role*.'''
if not index.isValid():
return None
column = index.column()
item = index.internalPointer()
if role == self.ITEM_ROLE:
return item
elif role == Qt.DisplayRole:
... | [
"def",
"data",
"(",
"self",
",",
"index",
",",
"role",
")",
":",
"if",
"not",
"index",
".",
"isValid",
"(",
")",
":",
"return",
"None",
"column",
"=",
"index",
".",
"column",
"(",
")",
"item",
"=",
"index",
".",
"internalPointer",
"(",
")",
"if",
... | 26.771429 | 0.00206 |
def get_membrane_xml(self, pdb_id):
''' Returns the <MEMBRANE> tag XML for pdb_id if the tag exists.'''
self.tmp_string = None
context = etree.iterparse(io.BytesIO(self.xml_contents), events=('end',), tag=self.PDBTM_entry_tag_type)
try:
fast_iter(context, self._get_membrane_x... | [
"def",
"get_membrane_xml",
"(",
"self",
",",
"pdb_id",
")",
":",
"self",
".",
"tmp_string",
"=",
"None",
"context",
"=",
"etree",
".",
"iterparse",
"(",
"io",
".",
"BytesIO",
"(",
"self",
".",
"xml_contents",
")",
",",
"events",
"=",
"(",
"'end'",
",",... | 50.25 | 0.01467 |
def get_all_roles(path_prefix=None, region=None, key=None, keyid=None,
profile=None):
'''
Get and return all IAM role details, starting at the optional path.
.. versionadded:: 2016.3.0
CLI Example:
salt-call boto_iam.get_all_roles
'''
conn = _get_conn(region=region, k... | [
"def",
"get_all_roles",
"(",
"path_prefix",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=",
... | 33.653846 | 0.002222 |
def rename_document(self, old_path, new_path):
"""
Renames an already opened document (this will not rename the file,
just update the file path and tab title).
Use that function to update a file that has been renamed externally.
:param old_path: old path (path of the widget to ... | [
"def",
"rename_document",
"(",
"self",
",",
"old_path",
",",
"new_path",
")",
":",
"to_rename",
"=",
"[",
"]",
"title",
"=",
"os",
".",
"path",
".",
"split",
"(",
"new_path",
")",
"[",
"1",
"]",
"for",
"widget",
"in",
"self",
".",
"widgets",
"(",
"... | 41.727273 | 0.00213 |
def _create_svc_vm_hosting_devices(self, context, num, template):
"""Creates <num> or less service VM instances based on <template>.
These hosting devices can be bound to a certain tenant or for shared
use. A list with the created hosting device VMs is returned.
"""
hosting_devi... | [
"def",
"_create_svc_vm_hosting_devices",
"(",
"self",
",",
"context",
",",
"num",
",",
"template",
")",
":",
"hosting_devices",
"=",
"[",
"]",
"template_id",
"=",
"template",
"[",
"'id'",
"]",
"credentials_id",
"=",
"template",
"[",
"'default_credentials_id'",
"... | 52.7 | 0.000931 |
def ensure_specification_cols_are_in_dataframe(specification, dataframe):
"""
Checks whether each column in `specification` is in `dataframe`. Raises
ValueError if any of the columns are not in the dataframe.
Parameters
----------
specification : OrderedDict.
Keys are a proper subset of... | [
"def",
"ensure_specification_cols_are_in_dataframe",
"(",
"specification",
",",
"dataframe",
")",
":",
"# Make sure specification is an OrderedDict",
"try",
":",
"assert",
"isinstance",
"(",
"specification",
",",
"OrderedDict",
")",
"except",
"AssertionError",
":",
"raise",... | 41.666667 | 0.000521 |
def detect_sv(items, all_items=None, stage="standard"):
"""Top level parallel target for examining structural variation.
"""
items = [utils.to_single_data(x) for x in items]
items = cwlutils.unpack_tarballs(items, items[0])
svcaller = items[0]["config"]["algorithm"].get("svcaller")
caller_fn = _... | [
"def",
"detect_sv",
"(",
"items",
",",
"all_items",
"=",
"None",
",",
"stage",
"=",
"\"standard\"",
")",
":",
"items",
"=",
"[",
"utils",
".",
"to_single_data",
"(",
"x",
")",
"for",
"x",
"in",
"items",
"]",
"items",
"=",
"cwlutils",
".",
"unpack_tarba... | 43 | 0.002394 |
def build_pdf(path_jinja2, template_name, path_outfile, template_kwargs=None):
'''Helper function for building a pdf from a latex jinja2 template
:param path_jinja2: the root directory for latex jinja2 templates
:param template_name: the relative path, to path_jinja2, to the desired
jinja2 Latex te... | [
"def",
"build_pdf",
"(",
"path_jinja2",
",",
"template_name",
",",
"path_outfile",
",",
"template_kwargs",
"=",
"None",
")",
":",
"latex_template_object",
"=",
"LatexBuild",
"(",
"path_jinja2",
",",
"template_name",
",",
"template_kwargs",
",",
")",
"return",
"lat... | 45.882353 | 0.001256 |
def gapfind(model, solver, epsilon=0.001, v_max=1000, implicit_sinks=True):
"""Identify compounds in the model that cannot be produced.
Yields all compounds that cannot be produced. This method
assumes implicit sinks for all compounds in the model so
the only factor that influences whether a compound c... | [
"def",
"gapfind",
"(",
"model",
",",
"solver",
",",
"epsilon",
"=",
"0.001",
",",
"v_max",
"=",
"1000",
",",
"implicit_sinks",
"=",
"True",
")",
":",
"prob",
"=",
"solver",
".",
"create_problem",
"(",
")",
"# Set integrality tolerance such that w constraints are... | 38.640449 | 0.000284 |
def predict(self, h=5, oos_data=None, intervals=False):
""" Makes forecast with the estimated model
Parameters
----------
h : int (default : 5)
How many steps ahead would you like to forecast?
oos_data : pd.DataFrame
Data for the variables to be used out... | [
"def",
"predict",
"(",
"self",
",",
"h",
"=",
"5",
",",
"oos_data",
"=",
"None",
",",
"intervals",
"=",
"False",
")",
":",
"if",
"self",
".",
"latent_variables",
".",
"estimated",
"is",
"False",
":",
"raise",
"Exception",
"(",
"\"No latent variables estima... | 45.3 | 0.008372 |
def set_bpduguard(self, name, value=False, default=False, disable=False):
"""Configures the bpduguard value for the specified interface
Args:
name (string): The interface identifier to configure. The name
must be the full interface name (eg Ethernet1, not Et1)
... | [
"def",
"set_bpduguard",
"(",
"self",
",",
"name",
",",
"value",
"=",
"False",
",",
"default",
"=",
"False",
",",
"disable",
"=",
"False",
")",
":",
"value",
"=",
"'enable'",
"if",
"value",
"else",
"'disable'",
"string",
"=",
"'spanning-tree bpduguard'",
"c... | 38.933333 | 0.001671 |
def _validate_string(self, input_string, path_to_root, object_title=''):
'''
a helper method for validating properties of a string
:return: input_string
'''
rules_path_to_root = re.sub('\[\d+\]', '[0]', path_to_root)
input_criteria = self.keyMap[rules_path_to_root]... | [
"def",
"_validate_string",
"(",
"self",
",",
"input_string",
",",
"path_to_root",
",",
"object_title",
"=",
"''",
")",
":",
"rules_path_to_root",
"=",
"re",
".",
"sub",
"(",
"'\\[\\d+\\]'",
",",
"'[0]'",
",",
"path_to_root",
")",
"input_criteria",
"=",
"self",... | 47.230769 | 0.001196 |
def get_input_list(self):
"""
Description:
Get input list
Returns an ordered list of all available input keys and names
"""
inputs = [' '] * len(self.command['input'])
for key in self.command['input']:
inputs[self.command['input'][key]['order... | [
"def",
"get_input_list",
"(",
"self",
")",
":",
"inputs",
"=",
"[",
"' '",
"]",
"*",
"len",
"(",
"self",
".",
"command",
"[",
"'input'",
"]",
")",
"for",
"key",
"in",
"self",
".",
"command",
"[",
"'input'",
"]",
":",
"inputs",
"[",
"self",
".",
"... | 32.583333 | 0.012438 |
def get_mesh_dict(self):
"""Returns calculated mesh sampling phonons
Returns
-------
dict
keys: qpoints, weights, frequencies, eigenvectors, and
group_velocities
Each value for the corresponding key is explained as below.
qpoints: ... | [
"def",
"get_mesh_dict",
"(",
"self",
")",
":",
"if",
"self",
".",
"_mesh",
"is",
"None",
":",
"msg",
"=",
"(",
"\"run_mesh has to be done.\"",
")",
"raise",
"RuntimeError",
"(",
"msg",
")",
"retdict",
"=",
"{",
"'qpoints'",
":",
"self",
".",
"_mesh",
"."... | 36.361702 | 0.00114 |
def copy_dir(source, dest, vars, verbosity=1, simulate=False, indent=0,
sub_vars=True, interactive=False, overwrite=True,
template_renderer=None, out_=sys.stdout):
"""
Copies the ``source`` directory to the ``dest`` directory.
``vars``: A dictionary of variables to use in any subs... | [
"def",
"copy_dir",
"(",
"source",
",",
"dest",
",",
"vars",
",",
"verbosity",
"=",
"1",
",",
"simulate",
"=",
"False",
",",
"indent",
"=",
"0",
",",
"sub_vars",
"=",
"True",
",",
"interactive",
"=",
"False",
",",
"overwrite",
"=",
"True",
",",
"templ... | 38.984 | 0.002401 |
def close(self):
"""
Closes this cloud.
"""
if not (yield from super().close()):
return False
for nio in self._nios.values():
if nio and isinstance(nio, NIOUDP):
self.manager.port_manager.release_udp_port(nio.lport, self._project)
... | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"not",
"(",
"yield",
"from",
"super",
"(",
")",
".",
"close",
"(",
")",
")",
":",
"return",
"False",
"for",
"nio",
"in",
"self",
".",
"_nios",
".",
"values",
"(",
")",
":",
"if",
"nio",
"and",
"isins... | 31.071429 | 0.008929 |
def _check_voSet(orb,kwargs,funcName):
"""Function to check whether vo is set, because it's required for funcName"""
if not orb._voSet and kwargs.get('vo',None) is None:
warnings.warn("Method %s(.) requires vo to be given at Orbit initialization or at method evaluation; using default vo which is %f km/s... | [
"def",
"_check_voSet",
"(",
"orb",
",",
"kwargs",
",",
"funcName",
")",
":",
"if",
"not",
"orb",
".",
"_voSet",
"and",
"kwargs",
".",
"get",
"(",
"'vo'",
",",
"None",
")",
"is",
"None",
":",
"warnings",
".",
"warn",
"(",
"\"Method %s(.) requires vo to be... | 75 | 0.01847 |
def findExtname(fimg, extname, extver=None):
"""
Returns the list number of the extension corresponding to EXTNAME given.
"""
i = 0
extnum = None
for chip in fimg:
hdr = chip.header
if 'EXTNAME' in hdr:
if hdr['EXTNAME'].strip() == extname.upper():
if... | [
"def",
"findExtname",
"(",
"fimg",
",",
"extname",
",",
"extver",
"=",
"None",
")",
":",
"i",
"=",
"0",
"extnum",
"=",
"None",
"for",
"chip",
"in",
"fimg",
":",
"hdr",
"=",
"chip",
".",
"header",
"if",
"'EXTNAME'",
"in",
"hdr",
":",
"if",
"hdr",
... | 27.375 | 0.002208 |
def _EvaluateNumberOfElements(self, context):
"""Evaluates number of elements.
Args:
context (DataTypeMapContext): data type map context.
Returns:
int: number of elements.
Raises:
MappingError: if the number of elements cannot be determined.
"""
number_of_elements = None
... | [
"def",
"_EvaluateNumberOfElements",
"(",
"self",
",",
"context",
")",
":",
"number_of_elements",
"=",
"None",
"if",
"self",
".",
"_data_type_definition",
".",
"number_of_elements",
":",
"number_of_elements",
"=",
"self",
".",
"_data_type_definition",
".",
"number_of_e... | 34.055556 | 0.008723 |
def _ensure_data(values, dtype=None):
"""
routine to ensure that our data is of the correct
input dtype for lower-level routines
This will coerce:
- ints -> int64
- uint -> uint64
- bool -> uint64 (TODO this should be uint8)
- datetimelike -> i8
- datetime64tz -> i8 (in local tz)
... | [
"def",
"_ensure_data",
"(",
"values",
",",
"dtype",
"=",
"None",
")",
":",
"# we check some simple dtypes first",
"try",
":",
"if",
"is_object_dtype",
"(",
"dtype",
")",
":",
"return",
"ensure_object",
"(",
"np",
".",
"asarray",
"(",
"values",
")",
")",
",",... | 35.673913 | 0.000296 |
def _newsToDF(n):
'''internal'''
df = pd.DataFrame(n)
_toDatetime(df)
_reindex(df, 'datetime')
return df | [
"def",
"_newsToDF",
"(",
"n",
")",
":",
"df",
"=",
"pd",
".",
"DataFrame",
"(",
"n",
")",
"_toDatetime",
"(",
"df",
")",
"_reindex",
"(",
"df",
",",
"'datetime'",
")",
"return",
"df"
] | 19.833333 | 0.008065 |
def f1_score(y_true, y_pred, average='micro', suffix=False):
"""Compute the F1 score.
The F1 score can be interpreted as a weighted average of the precision and
recall, where an F1 score reaches its best value at 1 and worst score at 0.
The relative contribution of precision and recall to the F1 score ... | [
"def",
"f1_score",
"(",
"y_true",
",",
"y_pred",
",",
"average",
"=",
"'micro'",
",",
"suffix",
"=",
"False",
")",
":",
"true_entities",
"=",
"set",
"(",
"get_entities",
"(",
"y_true",
",",
"suffix",
")",
")",
"pred_entities",
"=",
"set",
"(",
"get_entit... | 36.166667 | 0.002244 |
def _query_pageant(msg):
"""
Communication with the Pageant process is done through a shared
memory-mapped file.
"""
hwnd = _get_pageant_window_object()
if not hwnd:
# Raise a failure to connect exception, pageant isn't running anymore!
return None
# create a name for the mm... | [
"def",
"_query_pageant",
"(",
"msg",
")",
":",
"hwnd",
"=",
"_get_pageant_window_object",
"(",
")",
"if",
"not",
"hwnd",
":",
"# Raise a failure to connect exception, pageant isn't running anymore!",
"return",
"None",
"# create a name for the mmap",
"map_name",
"=",
"\"Page... | 34.5 | 0.000783 |
def download(*packages, **kwargs):
'''
Download packages to the local disk.
refresh
force a refresh if set to True.
If set to False (default) it depends on zypper if a refresh is
executed.
root
operate on a different root directory.
CLI example:
.. code-block:... | [
"def",
"download",
"(",
"*",
"packages",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"packages",
":",
"raise",
"SaltInvocationError",
"(",
"'No packages specified'",
")",
"root",
"=",
"kwargs",
".",
"get",
"(",
"'root'",
",",
"None",
")",
"refresh",
... | 30.346154 | 0.002455 |
def send(MESSAGE, SOCKET, MESSAGE_ID=None,
CODE_FILE=None, CODE_LINE=None, CODE_FUNC=None,
**kwargs):
r"""Send a message to the journal.
>>> journal.send('Hello world')
>>> journal.send('Hello, again, world', FIELD2='Greetings!')
>>> journal.send('Binary message', BINARY=b'\xde\xad\xb... | [
"def",
"send",
"(",
"MESSAGE",
",",
"SOCKET",
",",
"MESSAGE_ID",
"=",
"None",
",",
"CODE_FILE",
"=",
"None",
",",
"CODE_LINE",
"=",
"None",
",",
"CODE_FUNC",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"[",
"'MESSAGE='",
"+",
"MESSAG... | 36.836735 | 0.001079 |
def _jdn(self):
"""Return the Julian date number for the given date."""
if self._last_updated == "gdate":
return conv.gdate_to_jdn(self.gdate)
return conv.hdate_to_jdn(self.hdate) | [
"def",
"_jdn",
"(",
"self",
")",
":",
"if",
"self",
".",
"_last_updated",
"==",
"\"gdate\"",
":",
"return",
"conv",
".",
"gdate_to_jdn",
"(",
"self",
".",
"gdate",
")",
"return",
"conv",
".",
"hdate_to_jdn",
"(",
"self",
".",
"hdate",
")"
] | 42.2 | 0.009302 |
def save(self, force_insert=False, force_update=False, using=None, update_fields=None):
""" Set html field with correct iframe. """
if self.url:
iframe_html = '<iframe src="{}" frameborder="0" title="{}" allowfullscreen></iframe>'
self.html = iframe_html.format(
s... | [
"def",
"save",
"(",
"self",
",",
"force_insert",
"=",
"False",
",",
"force_update",
"=",
"False",
",",
"using",
"=",
"None",
",",
"update_fields",
"=",
"None",
")",
":",
"if",
"self",
".",
"url",
":",
"iframe_html",
"=",
"'<iframe src=\"{}\" frameborder=\"0\... | 50.111111 | 0.008715 |
def update_generators():
'''Update the context of all generators
Ads useful variables and translations into the template context
and interlink translations
'''
for generator in _GENERATOR_DB.keys():
install_templates_translations(generator)
add_variables_to_context(generator)
... | [
"def",
"update_generators",
"(",
")",
":",
"for",
"generator",
"in",
"_GENERATOR_DB",
".",
"keys",
"(",
")",
":",
"install_templates_translations",
"(",
"generator",
")",
"add_variables_to_context",
"(",
"generator",
")",
"interlink_static_files",
"(",
"generator",
... | 36.416667 | 0.002232 |
def is_extension_type(arr):
"""
Check whether an array-like is of a pandas extension class instance.
Extension classes include categoricals, pandas sparse objects (i.e.
classes represented within the pandas library and not ones external
to it like scipy sparse matrices), and datetime-like arrays.
... | [
"def",
"is_extension_type",
"(",
"arr",
")",
":",
"if",
"is_categorical",
"(",
"arr",
")",
":",
"return",
"True",
"elif",
"is_sparse",
"(",
"arr",
")",
":",
"return",
"True",
"elif",
"is_datetime64tz_dtype",
"(",
"arr",
")",
":",
"return",
"True",
"return"... | 25.245614 | 0.000669 |
def expires(duration, vary=None, currtime=time.time):
"""Decorator. Apply on a :class:`wsgiservice.Resource` method to set the
max-age cache control parameter to the given duration. Also calculates
the correct ``Expires`` response header.
:param duration: Age which this resource may have before becomin... | [
"def",
"expires",
"(",
"duration",
",",
"vary",
"=",
"None",
",",
"currtime",
"=",
"time",
".",
"time",
")",
":",
"if",
"isinstance",
"(",
"duration",
",",
"timedelta",
")",
":",
"duration",
"=",
"timedelta_to_seconds",
"(",
"duration",
")",
"@",
"decora... | 38.911765 | 0.000737 |
def _notify_add_at(self, index, length=1):
"""Notify about an AddChange at a caertain index and length."""
slice_ = self._slice_at(index, length)
self._notify_add(slice_) | [
"def",
"_notify_add_at",
"(",
"self",
",",
"index",
",",
"length",
"=",
"1",
")",
":",
"slice_",
"=",
"self",
".",
"_slice_at",
"(",
"index",
",",
"length",
")",
"self",
".",
"_notify_add",
"(",
"slice_",
")"
] | 47.75 | 0.010309 |
def sky(lon=None,lat=None,size=1):
"""
Outputs uniform points on sphere from:
[0 < lon < 360] & [-90 < lat < 90]
"""
if lon is None:
umin,umax = 0,1
else:
lon = np.asarray(lon)
lon = np.radians(lon + 360.*(lon<0))
if lon.size==1: umin=umax=lon/(2*np.pi)
... | [
"def",
"sky",
"(",
"lon",
"=",
"None",
",",
"lat",
"=",
"None",
",",
"size",
"=",
"1",
")",
":",
"if",
"lon",
"is",
"None",
":",
"umin",
",",
"umax",
"=",
"0",
",",
"1",
"else",
":",
"lon",
"=",
"np",
".",
"asarray",
"(",
"lon",
")",
"lon",... | 30.769231 | 0.041212 |
def validate(self, request, data):
"""
Validate response from OpenID server.
Set identity in case of successfull validation.
"""
client = consumer.Consumer(request.session, None)
try:
resp = client.complete(data, request.session['openid_return_to'])
e... | [
"def",
"validate",
"(",
"self",
",",
"request",
",",
"data",
")",
":",
"client",
"=",
"consumer",
".",
"Consumer",
"(",
"request",
".",
"session",
",",
"None",
")",
"try",
":",
"resp",
"=",
"client",
".",
"complete",
"(",
"data",
",",
"request",
".",... | 41.272727 | 0.002153 |
def get(self, query, responseformat="geojson", verbosity="body", build=True):
"""Pass in an Overpass query in Overpass QL."""
# Construct full Overpass query
if build:
full_query = self._construct_ql_query(
query, responseformat=responseformat, verbosity=verbosity
... | [
"def",
"get",
"(",
"self",
",",
"query",
",",
"responseformat",
"=",
"\"geojson\"",
",",
"verbosity",
"=",
"\"body\"",
",",
"build",
"=",
"True",
")",
":",
"# Construct full Overpass query",
"if",
"build",
":",
"full_query",
"=",
"self",
".",
"_construct_ql_qu... | 35.6875 | 0.002273 |
def colorz(fd, n=DEFAULT_NUM_COLORS, min_v=DEFAULT_MINV, max_v=DEFAULT_MAXV,
bold_add=DEFAULT_BOLD_ADD, order_colors=True):
"""
Get the n most dominant colors of an image.
Clamps value to between min_v and max_v.
Creates bold colors using bold_add.
Total number of colors returned is 2*n,... | [
"def",
"colorz",
"(",
"fd",
",",
"n",
"=",
"DEFAULT_NUM_COLORS",
",",
"min_v",
"=",
"DEFAULT_MINV",
",",
"max_v",
"=",
"DEFAULT_MAXV",
",",
"bold_add",
"=",
"DEFAULT_BOLD_ADD",
",",
"order_colors",
"=",
"True",
")",
":",
"img",
"=",
"Image",
".",
"open",
... | 38.380952 | 0.001211 |
def generateOutputInflowFile(self,
out_nc,
start_datetime_utc,
number_of_timesteps,
simulation_time_step_seconds,
in_rapid_connect_file,
... | [
"def",
"generateOutputInflowFile",
"(",
"self",
",",
"out_nc",
",",
"start_datetime_utc",
",",
"number_of_timesteps",
",",
"simulation_time_step_seconds",
",",
"in_rapid_connect_file",
",",
"in_rivid_lat_lon_z_file",
",",
"land_surface_model_description",
",",
"modeling_institu... | 44.882353 | 0.002015 |
def pshp_soundex_first(fname, max_length=4, german=False):
"""Calculate the PSHP Soundex/Viewex Coding of a first name.
This is a wrapper for :py:meth:`PSHPSoundexFirst.encode`.
Parameters
----------
fname : str
The first name to encode
max_length : int
The length of the code r... | [
"def",
"pshp_soundex_first",
"(",
"fname",
",",
"max_length",
"=",
"4",
",",
"german",
"=",
"False",
")",
":",
"return",
"PSHPSoundexFirst",
"(",
")",
".",
"encode",
"(",
"fname",
",",
"max_length",
",",
"german",
")"
] | 23.409091 | 0.000932 |
def message(self):
"""
Return issue message.
"""
message = self.description.format(**self.parameters)
return '{code} {message}'.format(code=self.code, message=message) | [
"def",
"message",
"(",
"self",
")",
":",
"message",
"=",
"self",
".",
"description",
".",
"format",
"(",
"*",
"*",
"self",
".",
"parameters",
")",
"return",
"'{code} {message}'",
".",
"format",
"(",
"code",
"=",
"self",
".",
"code",
",",
"message",
"="... | 33.666667 | 0.009662 |
def reportMatchCompletion(cfg, results, replayData):
"""send information back to the server about the match's winners/losers"""
payload = json.dumps([cfg.flatten(), results, replayData])
ladder = cfg.ladder
return requests.post(
url = c.URL_BASE%(ladder.ipAddress, ladder.serverPort, "matchfinis... | [
"def",
"reportMatchCompletion",
"(",
"cfg",
",",
"results",
",",
"replayData",
")",
":",
"payload",
"=",
"json",
".",
"dumps",
"(",
"[",
"cfg",
".",
"flatten",
"(",
")",
",",
"results",
",",
"replayData",
"]",
")",
"ladder",
"=",
"cfg",
".",
"ladder",
... | 41.555556 | 0.02356 |
def Pager(self, service):
"""A page generator for this service query and the provided service.
This generates a page as a result from using the provided service's query()
method until there are no more results to fetch.
Args:
service: The service object for making a query using this service quer... | [
"def",
"Pager",
"(",
"self",
",",
"service",
")",
":",
"has_page",
"=",
"True",
"while",
"has_page",
":",
"page",
"=",
"service",
".",
"query",
"(",
"self",
")",
"yield",
"page",
"has_page",
"=",
"self",
".",
"HasNext",
"(",
"page",
")",
"if",
"has_p... | 29.105263 | 0.008757 |
def _read_attr(attr_name):
"""
Parse attribute from file 'pefile.py' and avoid importing
this module directly.
__version__, __author__, __contact__,
"""
regex = attr_name + r"\s+=\s+'(.+)'"
if sys.version_info.major == 2:
with open('pefile.py', 'r') as f:
match = re.sear... | [
"def",
"_read_attr",
"(",
"attr_name",
")",
":",
"regex",
"=",
"attr_name",
"+",
"r\"\\s+=\\s+'(.+)'\"",
"if",
"sys",
".",
"version_info",
".",
"major",
"==",
"2",
":",
"with",
"open",
"(",
"'pefile.py'",
",",
"'r'",
")",
"as",
"f",
":",
"match",
"=",
... | 32.8125 | 0.001852 |
def _get_private_key_obj(private_key, passphrase=None):
'''
Returns a private key object based on PEM text.
'''
private_key = _text_or_file(private_key)
private_key = get_pem_entry(private_key, pem_type='(?:RSA )?PRIVATE KEY')
rsaprivkey = M2Crypto.RSA.load_key_string(
private_key, callb... | [
"def",
"_get_private_key_obj",
"(",
"private_key",
",",
"passphrase",
"=",
"None",
")",
":",
"private_key",
"=",
"_text_or_file",
"(",
"private_key",
")",
"private_key",
"=",
"get_pem_entry",
"(",
"private_key",
",",
"pem_type",
"=",
"'(?:RSA )?PRIVATE KEY'",
")",
... | 40.363636 | 0.002203 |
def is_measure(self):
"""Return true if the colum is a dimension"""
from ambry.valuetype.core import ROLE
return self.role == ROLE.MEASURE | [
"def",
"is_measure",
"(",
"self",
")",
":",
"from",
"ambry",
".",
"valuetype",
".",
"core",
"import",
"ROLE",
"return",
"self",
".",
"role",
"==",
"ROLE",
".",
"MEASURE"
] | 39.75 | 0.012346 |
def auto_repr(obj: Any, with_addr: bool = False,
sort_attrs: bool = True, joiner: str = COMMA_SPACE) -> str:
"""
Convenience function for :func:`__repr__`.
Works its way through the object's ``__dict__`` and reports accordingly.
Args:
obj: object to display
with_addr: incl... | [
"def",
"auto_repr",
"(",
"obj",
":",
"Any",
",",
"with_addr",
":",
"bool",
"=",
"False",
",",
"sort_attrs",
":",
"bool",
"=",
"True",
",",
"joiner",
":",
"str",
"=",
"COMMA_SPACE",
")",
"->",
"str",
":",
"if",
"sort_attrs",
":",
"keys",
"=",
"sorted"... | 37.047619 | 0.001253 |
def _bootstrap_debian(name, **kwargs):
'''
Bootstrap a Debian Linux container
'''
version = kwargs.get('version', False)
if not version:
if __grains__['os'].lower() == 'debian':
version = __grains__['osrelease']
else:
version = 'stable'
release_blacklist ... | [
"def",
"_bootstrap_debian",
"(",
"name",
",",
"*",
"*",
"kwargs",
")",
":",
"version",
"=",
"kwargs",
".",
"get",
"(",
"'version'",
",",
"False",
")",
"if",
"not",
"version",
":",
"if",
"__grains__",
"[",
"'os'",
"]",
".",
"lower",
"(",
")",
"==",
... | 34.75 | 0.002334 |
def request_client_list(self, req, msg):
"""Request the list of connected clients.
The list of clients is sent as a sequence of #client-list informs.
Informs
-------
addr : str
The address of the client as host:port with host in dotted quad
notation. If ... | [
"def",
"request_client_list",
"(",
"self",
",",
"req",
",",
"msg",
")",
":",
"# TODO Get list of ClientConnection* instances and implement a standard",
"# 'address-print' method in the ClientConnection class",
"clients",
"=",
"self",
".",
"_client_conns",
"num_clients",
"=",
"l... | 32.189189 | 0.00163 |
def get_mutations(study_id, gene_list, mutation_type=None,
case_id=None):
"""Return mutations as a list of genes and list of amino acid changes.
Parameters
----------
study_id : str
The ID of the cBio study.
Example: 'cellline_ccle_broad' or 'paad_icgc'
gene_list :... | [
"def",
"get_mutations",
"(",
"study_id",
",",
"gene_list",
",",
"mutation_type",
"=",
"None",
",",
"case_id",
"=",
"None",
")",
":",
"genetic_profile",
"=",
"get_genetic_profiles",
"(",
"study_id",
",",
"'mutation'",
")",
"[",
"0",
"]",
"gene_list_str",
"=",
... | 37.439024 | 0.000635 |
def remove_spurious_insertions(scaffolds):
"""Remove all bins whose left and right neighbors belong to the same,
different scaffold.
Example with three such insertions in two different scaffolds:
>>> scaffolds = {
... "scaffold1": [
... ["contig1", 0, 0, 100, 1],
... | [
"def",
"remove_spurious_insertions",
"(",
"scaffolds",
")",
":",
"scaffolds",
"=",
"format_info_frags",
"(",
"scaffolds",
")",
"new_scaffolds",
"=",
"{",
"}",
"for",
"name",
",",
"scaffold",
"in",
"scaffolds",
".",
"items",
"(",
")",
":",
"new_scaffold",
"=",
... | 35.423077 | 0.000352 |
def operational(ctx, commands, format, xpath):
""" Execute operational mode command(s).
This function will send operational mode commands to a Junos
device. jaide.utils.clean_lines() is used to determine how we are
receiving commands, and ignore comment lines or blank lines in
a command file.
... | [
"def",
"operational",
"(",
"ctx",
",",
"commands",
",",
"format",
",",
"xpath",
")",
":",
"mp_pool",
"=",
"multiprocessing",
".",
"Pool",
"(",
"multiprocessing",
".",
"cpu_count",
"(",
")",
"*",
"2",
")",
"for",
"ip",
"in",
"ctx",
".",
"obj",
"[",
"'... | 49.5 | 0.00045 |
def _merge_cdicts(self, clut, exdict, separator):
"""Merge callable look-up tables from two objects."""
if not self._full_cname:
return
# Find all callables that are not in self exceptions dictionary
# and create new tokens for them
repl_dict = {}
for key, value in _sorted_keys_items(clu... | [
"def",
"_merge_cdicts",
"(",
"self",
",",
"clut",
",",
"exdict",
",",
"separator",
")",
":",
"if",
"not",
"self",
".",
"_full_cname",
":",
"return",
"# Find all callables that are not in self exceptions dictionary",
"# and create new tokens for them",
"repl_dict",
"=",
... | 39.892857 | 0.000874 |
def set_autocamera(self,mode='density'):
"""
- set_autocamera(mode='density'): By default, Scene defines its
own Camera. However, there is no a general way for doing so. Scene
uses a density criterion for getting the point of view. If this is
not a good option for your problem... | [
"def",
"set_autocamera",
"(",
"self",
",",
"mode",
"=",
"'density'",
")",
":",
"self",
".",
"Camera",
".",
"set_autocamera",
"(",
"self",
".",
"_Particles",
",",
"mode",
"=",
"mode",
")",
"self",
".",
"_camera_params",
"=",
"self",
".",
"Camera",
".",
... | 56.230769 | 0.009421 |
def create(self):
""" Creates the directory and all its parent directories if it does not
exist yet
"""
if self.dirname and not os.path.exists(self.dirname):
os.makedirs(self.dirname) | [
"def",
"create",
"(",
"self",
")",
":",
"if",
"self",
".",
"dirname",
"and",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"dirname",
")",
":",
"os",
".",
"makedirs",
"(",
"self",
".",
"dirname",
")"
] | 37 | 0.008811 |
def read(self, input_stream, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Read the data encoding the Poll request payload and decode it into
its constituent parts.
Args:
input_stream (stream): A data stream containing encoded object
data, supporting a read m... | [
"def",
"read",
"(",
"self",
",",
"input_stream",
",",
"kmip_version",
"=",
"enums",
".",
"KMIPVersion",
".",
"KMIP_1_0",
")",
":",
"super",
"(",
"PollRequestPayload",
",",
"self",
")",
".",
"read",
"(",
"input_stream",
",",
"kmip_version",
"=",
"kmip_version... | 36.611111 | 0.001478 |
def rand_crop(*args, padding_mode='reflection', p:float=1.):
"Randomized version of `crop_pad`."
return crop_pad(*args, **rand_pos, padding_mode=padding_mode, p=p) | [
"def",
"rand_crop",
"(",
"*",
"args",
",",
"padding_mode",
"=",
"'reflection'",
",",
"p",
":",
"float",
"=",
"1.",
")",
":",
"return",
"crop_pad",
"(",
"*",
"args",
",",
"*",
"*",
"rand_pos",
",",
"padding_mode",
"=",
"padding_mode",
",",
"p",
"=",
"... | 56.333333 | 0.023392 |
def elcm_session_delete(irmc_info, session_id, terminate=False):
"""send an eLCM request to remove a session from the session list
:param irmc_info: node info
:param session_id: session id
:param terminate: a running session must be terminated before removing
:raises: ELCMSessionNotFound if the ses... | [
"def",
"elcm_session_delete",
"(",
"irmc_info",
",",
"session_id",
",",
"terminate",
"=",
"False",
")",
":",
"# Terminate the session first if needs to",
"if",
"terminate",
":",
"# Get session status to check",
"session",
"=",
"elcm_session_get_status",
"(",
"irmc_info",
... | 41.757576 | 0.000709 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.