text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def count(self, sub, start=0, end=-1):
"""Return the number of non-overlapping occurrences of substring sub in string[start:end].
Optional arguments start and end are interpreted as in slice notation.
:param str sub: Substring to search.
:param int start: Beginning position.
:p... | [
"def",
"count",
"(",
"self",
",",
"sub",
",",
"start",
"=",
"0",
",",
"end",
"=",
"-",
"1",
")",
":",
"return",
"self",
".",
"value_no_colors",
".",
"count",
"(",
"sub",
",",
"start",
",",
"end",
")"
] | 42.9 | 16.4 |
def wait_until_element_present(self, element, timeout=None):
"""Search element and wait until it is found
:param element: PageElement or element locator as a tuple (locator_type, locator_value) to be found
:param timeout: max time to wait
:returns: the web element if it is present
... | [
"def",
"wait_until_element_present",
"(",
"self",
",",
"element",
",",
"timeout",
"=",
"None",
")",
":",
"return",
"self",
".",
"_wait_until",
"(",
"self",
".",
"_expected_condition_find_element",
",",
"element",
",",
"timeout",
")"
] | 59.2 | 28.9 |
def group_survival_table_from_events(
groups, durations, event_observed, birth_times=None, limit=-1
): # pylint: disable=too-many-locals
"""
Joins multiple event series together into DataFrames. A generalization of
`survival_table_from_events` to data with groups. Previously called `group_event_series`... | [
"def",
"group_survival_table_from_events",
"(",
"groups",
",",
"durations",
",",
"event_observed",
",",
"birth_times",
"=",
"None",
",",
"limit",
"=",
"-",
"1",
")",
":",
"# pylint: disable=too-many-locals",
"n",
"=",
"np",
".",
"max",
"(",
"groups",
".",
"sha... | 37.546296 | 25.231481 |
def get_instance(self, payload):
"""
Build an instance of CredentialListInstance
:param dict payload: Payload response from the API
:returns: twilio.rest.trunking.v1.trunk.credential_list.CredentialListInstance
:rtype: twilio.rest.trunking.v1.trunk.credential_list.CredentialLis... | [
"def",
"get_instance",
"(",
"self",
",",
"payload",
")",
":",
"return",
"CredentialListInstance",
"(",
"self",
".",
"_version",
",",
"payload",
",",
"trunk_sid",
"=",
"self",
".",
"_solution",
"[",
"'trunk_sid'",
"]",
",",
")"
] | 43.5 | 26.9 |
def create(cls, config_file=None):
""" Return the default configuration.
"""
if cls.instance is None:
cls.instance = cls(config_file)
# Load config file, possibly overwriting the defaults
cls.instance.load_ini()
if config_file and config_file != cls.... | [
"def",
"create",
"(",
"cls",
",",
"config_file",
"=",
"None",
")",
":",
"if",
"cls",
".",
"instance",
"is",
"None",
":",
"cls",
".",
"instance",
"=",
"cls",
"(",
"config_file",
")",
"# Load config file, possibly overwriting the defaults",
"cls",
".",
"instance... | 35 | 20.230769 |
def updateAllKeys(self):
"""Update times for all keys in the layout."""
for kf, key in zip(self.kf_list, self.sorted_key_list()):
kf.update(key, self.dct[key]) | [
"def",
"updateAllKeys",
"(",
"self",
")",
":",
"for",
"kf",
",",
"key",
"in",
"zip",
"(",
"self",
".",
"kf_list",
",",
"self",
".",
"sorted_key_list",
"(",
")",
")",
":",
"kf",
".",
"update",
"(",
"key",
",",
"self",
".",
"dct",
"[",
"key",
"]",
... | 46 | 10.5 |
def convert_outlook_msg(msg_bytes):
"""
Uses the ``msgconvert`` Perl utility to convert an Outlook MS file to
standard RFC 822 format
Args:
msg_bytes (bytes): the content of the .msg file
Returns:
A RFC 822 string
"""
if not is_outlook_msg(msg_bytes):
raise ValueErr... | [
"def",
"convert_outlook_msg",
"(",
"msg_bytes",
")",
":",
"if",
"not",
"is_outlook_msg",
"(",
"msg_bytes",
")",
":",
"raise",
"ValueError",
"(",
"\"The supplied bytes are not an Outlook MSG file\"",
")",
"orig_dir",
"=",
"os",
".",
"getcwd",
"(",
")",
"tmp_dir",
"... | 30.6875 | 18 |
def readdir(self, req, ino, size, off, fi):
"""Read directory
Valid replies:
reply_readdir
reply_err
"""
if ino == 1:
attr = {'st_ino': 1, 'st_mode': S_IFDIR}
entries = [('.', attr), ('..', attr)]
self.reply_readdir(req, size, ... | [
"def",
"readdir",
"(",
"self",
",",
"req",
",",
"ino",
",",
"size",
",",
"off",
",",
"fi",
")",
":",
"if",
"ino",
"==",
"1",
":",
"attr",
"=",
"{",
"'st_ino'",
":",
"1",
",",
"'st_mode'",
":",
"S_IFDIR",
"}",
"entries",
"=",
"[",
"(",
"'.'",
... | 29.307692 | 14.076923 |
def bound_perturbed_gmres(pseudo, p, epsilon, deltas):
'''Compute GMRES perturbation bound based on pseudospectrum
Computes the GMRES bound from [SifEM13]_.
'''
if not numpy.all(numpy.array(deltas) > epsilon):
raise ArgumentError('all deltas have to be greater than epsilon')
bound = []
... | [
"def",
"bound_perturbed_gmres",
"(",
"pseudo",
",",
"p",
",",
"epsilon",
",",
"deltas",
")",
":",
"if",
"not",
"numpy",
".",
"all",
"(",
"numpy",
".",
"array",
"(",
"deltas",
")",
">",
"epsilon",
")",
":",
"raise",
"ArgumentError",
"(",
"'all deltas have... | 30.166667 | 20 |
def semantic_alert(visitor, block):
"""
Format:
{% alert class=error %}
message
{% endalert %}
"""
txt = []
cls = block['kwargs'].get('class', '')
txt.append('<div class="ui %s message">' % cls)
text = visitor.parse_text(block['body'], 'article')
txt.appe... | [
"def",
"semantic_alert",
"(",
"visitor",
",",
"block",
")",
":",
"txt",
"=",
"[",
"]",
"cls",
"=",
"block",
"[",
"'kwargs'",
"]",
".",
"get",
"(",
"'class'",
",",
"''",
")",
"txt",
".",
"append",
"(",
"'<div class=\"ui %s message\">'",
"%",
"cls",
")",... | 24.333333 | 15 |
def set(self, section, option, value=''):
'''
This is overridden from the RawConfigParser merely to change the
default value for the 'value' argument.
'''
self._string_check(value)
super(GitConfigParser, self).set(section, option, value) | [
"def",
"set",
"(",
"self",
",",
"section",
",",
"option",
",",
"value",
"=",
"''",
")",
":",
"self",
".",
"_string_check",
"(",
"value",
")",
"super",
"(",
"GitConfigParser",
",",
"self",
")",
".",
"set",
"(",
"section",
",",
"option",
",",
"value",
... | 39.857143 | 18.428571 |
def step(self, closure=None):
"""Performs a single optimization step.
Arguments:
closure (callable, optional): A closure that reevaluates the model
and returns the loss.
"""
loss = None
if closure is not None:
loss = closure()
for... | [
"def",
"step",
"(",
"self",
",",
"closure",
"=",
"None",
")",
":",
"loss",
"=",
"None",
"if",
"closure",
"is",
"not",
"None",
":",
"loss",
"=",
"closure",
"(",
")",
"for",
"group",
"in",
"self",
".",
"param_groups",
":",
"for",
"p",
"in",
"group",
... | 38.637931 | 23.741379 |
def projection(self, axis):
"""Sums all data along all other axes, then return Hist1D"""
axis = self.get_axis_number(axis)
projected_hist = np.sum(self.histogram, axis=self.other_axes(axis))
return Hist1d.from_histogram(projected_hist, bin_edges=self.bin_edges[axis]) | [
"def",
"projection",
"(",
"self",
",",
"axis",
")",
":",
"axis",
"=",
"self",
".",
"get_axis_number",
"(",
"axis",
")",
"projected_hist",
"=",
"np",
".",
"sum",
"(",
"self",
".",
"histogram",
",",
"axis",
"=",
"self",
".",
"other_axes",
"(",
"axis",
... | 59 | 18.6 |
def match_color_index(self, color):
"""Takes an "R,G,B" string or wx.Color and returns a matching xlwt
color.
"""
from jcvi.utils.webcolors import color_diff
if isinstance(color, int):
return color
if color:
if isinstance(color, six.string_types):
... | [
"def",
"match_color_index",
"(",
"self",
",",
"color",
")",
":",
"from",
"jcvi",
".",
"utils",
".",
"webcolors",
"import",
"color_diff",
"if",
"isinstance",
"(",
"color",
",",
"int",
")",
":",
"return",
"color",
"if",
"color",
":",
"if",
"isinstance",
"(... | 39.166667 | 12.333333 |
def LoadGDAL(filename, no_data=None):
"""Read a GDAL file.
Opens any file GDAL can read, selects the first raster band, and loads it
and its metadata into a RichDEM array of the appropriate data type.
If you need to do something more complicated, look at the source of this
function.
Args:
... | [
"def",
"LoadGDAL",
"(",
"filename",
",",
"no_data",
"=",
"None",
")",
":",
"if",
"not",
"GDAL_AVAILABLE",
":",
"raise",
"Exception",
"(",
"\"richdem.LoadGDAL() requires GDAL.\"",
")",
"allowed_types",
"=",
"{",
"gdal",
".",
"GDT_Byte",
",",
"gdal",
".",
"GDT_I... | 35.520833 | 30.166667 |
def create_virtual_aggregation(geometry, crs):
"""Function to create aggregation layer based on extent.
:param geometry: The geometry to use as an extent.
:type geometry: QgsGeometry
:param crs: The Coordinate Reference System to use for the layer.
:type crs: QgsCoordinateReferenceSystem
:ret... | [
"def",
"create_virtual_aggregation",
"(",
"geometry",
",",
"crs",
")",
":",
"fields",
"=",
"[",
"create_field_from_definition",
"(",
"aggregation_id_field",
")",
",",
"create_field_from_definition",
"(",
"aggregation_name_field",
")",
"]",
"aggregation_layer",
"=",
"cre... | 36.439024 | 18.804878 |
def supprime(cls,table, **kwargs):
""" Remove entries matchin given condition
kwargs is a dict of column name : value , with length ONE.
"""
assert len(kwargs) == 1
field, value = kwargs.popitem()
req = f"""DELETE FROM {table} WHERE {field} = """ + cls.mark_style
... | [
"def",
"supprime",
"(",
"cls",
",",
"table",
",",
"*",
"*",
"kwargs",
")",
":",
"assert",
"len",
"(",
"kwargs",
")",
"==",
"1",
"field",
",",
"value",
"=",
"kwargs",
".",
"popitem",
"(",
")",
"req",
"=",
"f\"\"\"DELETE FROM {table} WHERE {field} = \"\"\"",... | 41.111111 | 6.777778 |
def backing_type_for(value):
"""Returns the DynamoDB backing type for a given python value's type
::
4 -> 'N'
['x', 3] -> 'L'
{2, 4} -> 'SS'
"""
if isinstance(value, str):
vtype = "S"
elif isinstance(value, bytes):
vty... | [
"def",
"backing_type_for",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"vtype",
"=",
"\"S\"",
"elif",
"isinstance",
"(",
"value",
",",
"bytes",
")",
":",
"vtype",
"=",
"\"B\"",
"# NOTE: numbers.Number check must come **AFTER... | 35.868421 | 17.631579 |
def Hf_g(CASRN, AvailableMethods=False, Method=None):
r'''This function handles the retrieval of a chemical's gas heat of
formation. Lookup is based on CASRNs. Will automatically select a data
source to use if no Method is provided; returns None if the data is not
available.
Prefered sources are 'A... | [
"def",
"Hf_g",
"(",
"CASRN",
",",
"AvailableMethods",
"=",
"False",
",",
"Method",
"=",
"None",
")",
":",
"def",
"list_methods",
"(",
")",
":",
"methods",
"=",
"[",
"]",
"if",
"CASRN",
"in",
"ATcT_g",
".",
"index",
":",
"methods",
".",
"append",
"(",... | 33.454545 | 24.831169 |
def GetNextWrittenEventSource(self):
"""Retrieves the next event source that was written after open.
Returns:
EventSource: event source or None if there are no newly written ones.
Raises:
IOError: when the storage writer is closed.
OSError: when the storage writer is closed.
"""
... | [
"def",
"GetNextWrittenEventSource",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_is_open",
":",
"raise",
"IOError",
"(",
"'Unable to read from closed storage writer.'",
")",
"if",
"self",
".",
"_written_event_source_index",
">=",
"len",
"(",
"self",
".",
"_e... | 32.473684 | 21.842105 |
def api_request(self, url, data=None, method='GET', raw=False, file=None):
""" Perform an API request to the given URL, optionally
including the specified data
:type url: String
:param url: the URL to which to make the request
:type data: String
:param data: the data to ... | [
"def",
"api_request",
"(",
"self",
",",
"url",
",",
"data",
"=",
"None",
",",
"method",
"=",
"'GET'",
",",
"raw",
"=",
"False",
",",
"file",
"=",
"None",
")",
":",
"if",
"method",
"is",
"'GET'",
":",
"response",
"=",
"self",
".",
"oauth",
".",
"g... | 36.854167 | 22.479167 |
def directory_generator(dirname, trim=0):
"""
yields a tuple of (relative filename, chunking function). The
chunking function can be called to open and iterate over the
contents of the filename.
"""
def gather(collect, dirname, fnames):
for fname in fnames:
df = join(dirname... | [
"def",
"directory_generator",
"(",
"dirname",
",",
"trim",
"=",
"0",
")",
":",
"def",
"gather",
"(",
"collect",
",",
"dirname",
",",
"fnames",
")",
":",
"for",
"fname",
"in",
"fnames",
":",
"df",
"=",
"join",
"(",
"dirname",
",",
"fname",
")",
"if",
... | 29.764706 | 12.941176 |
def reference_cluster(envs, name):
"""
Return set of all env names referencing or
referenced by given name.
>>> cluster = sorted(reference_cluster([
... {'name': 'base', 'refs': []},
... {'name': 'test', 'refs': ['base']},
... {'name': 'local', 'refs': ['test']},
... ], 'tes... | [
"def",
"reference_cluster",
"(",
"envs",
",",
"name",
")",
":",
"edges",
"=",
"[",
"set",
"(",
"[",
"env",
"[",
"'name'",
"]",
",",
"ref",
"]",
")",
"for",
"env",
"in",
"envs",
"for",
"ref",
"in",
"env",
"[",
"'refs'",
"]",
"]",
"prev",
",",
"c... | 28.242424 | 12.484848 |
def parse_json(pairs):
"""
modified from:
https://stackoverflow.com/questions/956867/how-to-get-string-objects-instead-of-unicode-from-json#34796078
pass this to the object_pairs_hook kwarg of json.load/loads
"""
new_pairs = []
for key, value in pairs:
if isinstance(value, unicode):... | [
"def",
"parse_json",
"(",
"pairs",
")",
":",
"new_pairs",
"=",
"[",
"]",
"for",
"key",
",",
"value",
"in",
"pairs",
":",
"if",
"isinstance",
"(",
"value",
",",
"unicode",
")",
":",
"value",
"=",
"value",
".",
"encode",
"(",
"'utf-8'",
")",
"if",
"i... | 32.6 | 15.533333 |
def wrap(self, row: Union[Mapping[str, Any], Sequence[Any]]):
"""Return row tuple for row."""
return (
self.dataclass(
**{
ident: row[column_name]
for ident, column_name in self.ids_and_column_names.items()
}
... | [
"def",
"wrap",
"(",
"self",
",",
"row",
":",
"Union",
"[",
"Mapping",
"[",
"str",
",",
"Any",
"]",
",",
"Sequence",
"[",
"Any",
"]",
"]",
")",
":",
"return",
"(",
"self",
".",
"dataclass",
"(",
"*",
"*",
"{",
"ident",
":",
"row",
"[",
"column_n... | 35.571429 | 20.642857 |
def en_passant_moves(self, position):
"""
Finds possible en passant moves.
:rtype: list
"""
# if pawn is not on a valid en passant get_location then return None
if self.on_en_passant_valid_location():
for move in itertools.chain(self.add_one_en_passant_move(... | [
"def",
"en_passant_moves",
"(",
"self",
",",
"position",
")",
":",
"# if pawn is not on a valid en passant get_location then return None",
"if",
"self",
".",
"on_en_passant_valid_location",
"(",
")",
":",
"for",
"move",
"in",
"itertools",
".",
"chain",
"(",
"self",
".... | 40 | 24.333333 |
def _determine_monetary_account_id(cls, monetary_account_id=None):
"""
:type monetary_account_id: int
:rtype: int
"""
if monetary_account_id is None:
return context.BunqContext.user_context().primary_monetary_account.id_
return monetary_account_id | [
"def",
"_determine_monetary_account_id",
"(",
"cls",
",",
"monetary_account_id",
"=",
"None",
")",
":",
"if",
"monetary_account_id",
"is",
"None",
":",
"return",
"context",
".",
"BunqContext",
".",
"user_context",
"(",
")",
".",
"primary_monetary_account",
".",
"i... | 27.272727 | 19.818182 |
def run(self, dag):
"""
Pick a convenient layout depending on the best matching
qubit connectivity, and set the property `layout`.
Args:
dag (DAGCircuit): DAG to find layout for.
Raises:
TranspilerError: if dag wider than self.coupling_map
"""
... | [
"def",
"run",
"(",
"self",
",",
"dag",
")",
":",
"num_dag_qubits",
"=",
"sum",
"(",
"[",
"qreg",
".",
"size",
"for",
"qreg",
"in",
"dag",
".",
"qregs",
".",
"values",
"(",
")",
"]",
")",
"if",
"num_dag_qubits",
">",
"self",
".",
"coupling_map",
"."... | 36.909091 | 17.909091 |
def create_df_file_with_query(self, query, output):
""" Dumps in df in chunks to avoid crashes.
"""
chunk_size = 100000
offset = 0
data = defaultdict(lambda : defaultdict(list))
with open(output, 'wb') as outfile:
query = query.replace(';', '')
qu... | [
"def",
"create_df_file_with_query",
"(",
"self",
",",
"query",
",",
"output",
")",
":",
"chunk_size",
"=",
"100000",
"offset",
"=",
"0",
"data",
"=",
"defaultdict",
"(",
"lambda",
":",
"defaultdict",
"(",
"list",
")",
")",
"with",
"open",
"(",
"output",
... | 34.590909 | 9.636364 |
def create_dataset(self, group, chunk_size):
"""Initializes sparse specific datasets"""
group.attrs['format'] = self.dformat
group.attrs['dim'] = self.dim
if chunk_size == 'auto':
group.create_dataset(
'coordinates', (0, 2), dtype=np.float64,
... | [
"def",
"create_dataset",
"(",
"self",
",",
"group",
",",
"chunk_size",
")",
":",
"group",
".",
"attrs",
"[",
"'format'",
"]",
"=",
"self",
".",
"dformat",
"group",
".",
"attrs",
"[",
"'dim'",
"]",
"=",
"self",
".",
"dim",
"if",
"chunk_size",
"==",
"'... | 36.071429 | 16.880952 |
def assert_datasource_protocol(event):
"""Assert that an event meets the protocol for datasource outputs."""
assert event.type in DATASOURCE_TYPE
# Done packets have no dt.
if not event.type == DATASOURCE_TYPE.DONE:
assert isinstance(event.dt, datetime)
assert event.dt.tzinfo == pytz.u... | [
"def",
"assert_datasource_protocol",
"(",
"event",
")",
":",
"assert",
"event",
".",
"type",
"in",
"DATASOURCE_TYPE",
"# Done packets have no dt.",
"if",
"not",
"event",
".",
"type",
"==",
"DATASOURCE_TYPE",
".",
"DONE",
":",
"assert",
"isinstance",
"(",
"event",
... | 34.888889 | 11.666667 |
def drop(self, table):
"""
Drop a table from a database.
Accepts either a string representing a table name or a list of strings
representing a table names.
"""
existing_tables = self.tables
if isinstance(table, (list, set, tuple)):
for t in table:
... | [
"def",
"drop",
"(",
"self",
",",
"table",
")",
":",
"existing_tables",
"=",
"self",
".",
"tables",
"if",
"isinstance",
"(",
"table",
",",
"(",
"list",
",",
"set",
",",
"tuple",
")",
")",
":",
"for",
"t",
"in",
"table",
":",
"self",
".",
"_drop",
... | 30.857143 | 13.428571 |
def parseMemory(memAttribute):
"""
Returns EC2 'memory' string as a float.
Format should always be '#' GiB (example: '244 GiB' or '1,952 GiB').
Amazon loves to put commas in their numbers, so we have to accommodate that.
If the syntax ever changes, this will raise.
:param memAttribute: EC2 JSO... | [
"def",
"parseMemory",
"(",
"memAttribute",
")",
":",
"mem",
"=",
"memAttribute",
".",
"replace",
"(",
"','",
",",
"''",
")",
".",
"split",
"(",
")",
"if",
"mem",
"[",
"1",
"]",
"==",
"'GiB'",
":",
"return",
"float",
"(",
"mem",
"[",
"0",
"]",
")"... | 36.5 | 19.375 |
def _logout_url(request, next_page=None):
"""
Generates CAS logout URL
:param: request RequestObj
:param: next_page Page to redirect after logout.
"""
url = urlparse.urljoin(settings.CAS_SERVER_URL, 'logout')
if next_page and getattr(settings, 'CAS_PROVIDE_URL_TO_LOGOUT', True):
... | [
"def",
"_logout_url",
"(",
"request",
",",
"next_page",
"=",
"None",
")",
":",
"url",
"=",
"urlparse",
".",
"urljoin",
"(",
"settings",
".",
"CAS_SERVER_URL",
",",
"'logout'",
")",
"if",
"next_page",
"and",
"getattr",
"(",
"settings",
",",
"'CAS_PROVIDE_URL_... | 34 | 23.619048 |
def drop_all(self, check_first: bool = True):
"""Drop all tables from the database.
:param bool check_first: Defaults to True, only issue DROPs for tables confirmed to be
present in the target database. Defers to :meth:`sqlalchemy.sql.schema.MetaData.drop_all`
"""
self._metada... | [
"def",
"drop_all",
"(",
"self",
",",
"check_first",
":",
"bool",
"=",
"True",
")",
":",
"self",
".",
"_metadata",
".",
"drop_all",
"(",
"self",
".",
"engine",
",",
"checkfirst",
"=",
"check_first",
")",
"self",
".",
"_store_drop",
"(",
")"
] | 48.5 | 25 |
def get_predicates(self, class_, controller=None):
"""Get full predicate information for given request class, and cache
for subsequent calls.
"""
if class_ not in self._predicates:
if controller is None:
controller = self._find_controller(class_)
e... | [
"def",
"get_predicates",
"(",
"self",
",",
"class_",
",",
"controller",
"=",
"None",
")",
":",
"if",
"class_",
"not",
"in",
"self",
".",
"_predicates",
":",
"if",
"controller",
"is",
"None",
":",
"controller",
"=",
"self",
".",
"_find_controller",
"(",
"... | 44.47619 | 16.714286 |
def statements(self):
'''Return a list of statements
This is done by joining together any rows that
have continuations
'''
# FIXME: no need to do this every time; we should cache the
# result
if len(self.rows) == 0:
return []
current_statemen... | [
"def",
"statements",
"(",
"self",
")",
":",
"# FIXME: no need to do this every time; we should cache the",
"# result",
"if",
"len",
"(",
"self",
".",
"rows",
")",
"==",
"0",
":",
"return",
"[",
"]",
"current_statement",
"=",
"Statement",
"(",
"self",
".",
"rows"... | 37.918919 | 17 |
def execute_notebook(self, name):
"""Loads and then runs a notebook file."""
warnings.filterwarnings("ignore", category=DeprecationWarning)
nb,f = self.load_notebook(name)
self.run_notebook(nb,f)
self.assertTrue(True) | [
"def",
"execute_notebook",
"(",
"self",
",",
"name",
")",
":",
"warnings",
".",
"filterwarnings",
"(",
"\"ignore\"",
",",
"category",
"=",
"DeprecationWarning",
")",
"nb",
",",
"f",
"=",
"self",
".",
"load_notebook",
"(",
"name",
")",
"self",
".",
"run_not... | 36 | 14 |
def parse_parameter_reference(self, tup_tree):
"""
::
<!ELEMENT PARAMETER.REFERENCE (QUALIFIER*)>
<!ATTLIST PARAMETER.REFERENCE
%CIMName;
%ReferenceClass;>
"""
self.check_node(tup_tree, 'PARAMETER.REFERENCE', ('NAME',),
... | [
"def",
"parse_parameter_reference",
"(",
"self",
",",
"tup_tree",
")",
":",
"self",
".",
"check_node",
"(",
"tup_tree",
",",
"'PARAMETER.REFERENCE'",
",",
"(",
"'NAME'",
",",
")",
",",
"(",
"'REFERENCECLASS'",
",",
")",
",",
"(",
"'QUALIFIER'",
",",
")",
"... | 33.391304 | 18.434783 |
def make_field_objects(field_data, names):
# type: (List[Dict[Text, Text]], Names) -> List[Field]
"""We're going to need to make message parameters too."""
field_objects = []
field_names = [] # type: List[Text]
for field in field_data:
if hasattr(field, 'get') and ca... | [
"def",
"make_field_objects",
"(",
"field_data",
",",
"names",
")",
":",
"# type: (List[Dict[Text, Text]], Names) -> List[Field]",
"field_objects",
"=",
"[",
"]",
"field_names",
"=",
"[",
"]",
"# type: List[Text]",
"for",
"field",
"in",
"field_data",
":",
"if",
"hasatt... | 46.225806 | 15.612903 |
def sr1flood(x, promisc=None, filter=None, iface=None, nofilter=0, *args, **kargs): # noqa: E501
"""Flood and receive packets at layer 3 and return only the first answer
prn: function applied to packets received
verbose: set verbosity level
nofilter: put 1 to avoid use of BPF filters
filter: provide a BPF ... | [
"def",
"sr1flood",
"(",
"x",
",",
"promisc",
"=",
"None",
",",
"filter",
"=",
"None",
",",
"iface",
"=",
"None",
",",
"nofilter",
"=",
"0",
",",
"*",
"args",
",",
"*",
"*",
"kargs",
")",
":",
"# noqa: E501",
"s",
"=",
"conf",
".",
"L3socket",
"("... | 43.285714 | 19.071429 |
def all_terms(self):
"""Iterate over all of the terms. The self.terms property has only root level terms. This iterator
iterates over all terms"""
for s_name, s in self.sections.items():
# Yield the section header
if s.name != 'Root':
yield s
... | [
"def",
"all_terms",
"(",
"self",
")",
":",
"for",
"s_name",
",",
"s",
"in",
"self",
".",
"sections",
".",
"items",
"(",
")",
":",
"# Yield the section header",
"if",
"s",
".",
"name",
"!=",
"'Root'",
":",
"yield",
"s",
"# Yield all of the rows for terms in t... | 32.266667 | 15.733333 |
def to_ip(self, values, from_unit):
"""Return values in IP and the units to which the values have been converted."""
if from_unit in self._ip_units:
return values, from_unit
elif from_unit == 'degC-hours':
return self.to_unit(values, 'degF-hours', from_unit), 'degF-hours'... | [
"def",
"to_ip",
"(",
"self",
",",
"values",
",",
"from_unit",
")",
":",
"if",
"from_unit",
"in",
"self",
".",
"_ip_units",
":",
"return",
"values",
",",
"from_unit",
"elif",
"from_unit",
"==",
"'degC-hours'",
":",
"return",
"self",
".",
"to_unit",
"(",
"... | 50.5 | 14 |
def set_dataframe_format(self, new_format):
"""
Set format to use in DataframeEditor.
Args:
new_format (string): e.g. "%.3f"
"""
self.sig_option_changed.emit('dataframe_format', new_format)
self.model.dataframe_format = new_format | [
"def",
"set_dataframe_format",
"(",
"self",
",",
"new_format",
")",
":",
"self",
".",
"sig_option_changed",
".",
"emit",
"(",
"'dataframe_format'",
",",
"new_format",
")",
"self",
".",
"model",
".",
"dataframe_format",
"=",
"new_format"
] | 32.333333 | 13 |
def _wrapusage(self, usage=None, width=0):
"""Textwrap usage instructions.
ARGS:
width = 0 <int>:
Maximum allowed page width. 0 means use default from
self.iMaxHelpWidth.
"""
if not width:
width = self.width
return textwrap.fill('USAGE... | [
"def",
"_wrapusage",
"(",
"self",
",",
"usage",
"=",
"None",
",",
"width",
"=",
"0",
")",
":",
"if",
"not",
"width",
":",
"width",
"=",
"self",
".",
"width",
"return",
"textwrap",
".",
"fill",
"(",
"'USAGE: '",
"+",
"self",
".",
"format_usage",
"(",
... | 34.818182 | 19.545455 |
def locked(dev, target):
""" Gets or sets the lock. """
click.echo("Locked: %s" % dev.locked)
if target is not None:
click.echo("Setting lock: %s" % target)
dev.locked = target | [
"def",
"locked",
"(",
"dev",
",",
"target",
")",
":",
"click",
".",
"echo",
"(",
"\"Locked: %s\"",
"%",
"dev",
".",
"locked",
")",
"if",
"target",
"is",
"not",
"None",
":",
"click",
".",
"echo",
"(",
"\"Setting lock: %s\"",
"%",
"target",
")",
"dev",
... | 33.166667 | 8.5 |
def makeEquilibriumTable(out_filename, four_in_files, CRRA):
'''
Make the equilibrium statistics table for the paper, saving it as a tex file
in the tables folder. Also makes a version for the slides that doesn't use
the table environment, nor include the note at bottom.
Parameters
----------
... | [
"def",
"makeEquilibriumTable",
"(",
"out_filename",
",",
"four_in_files",
",",
"CRRA",
")",
":",
"# Read in statistics from the four files",
"SOEfrictionless",
"=",
"np",
".",
"genfromtxt",
"(",
"results_dir",
"+",
"four_in_files",
"[",
"0",
"]",
"+",
"'Results.csv'",... | 65.36 | 43.34 |
def deliver_hook(target, payload, instance_id=None, hook_id=None, **kwargs):
"""
target: the url to receive the payload.
payload: a python primitive data structure
instance_id: a possibly None "trigger" instance ID
hook_id: the ID of defining Hook object
"""
... | [
"def",
"deliver_hook",
"(",
"target",
",",
"payload",
",",
"instance_id",
"=",
"None",
",",
"hook_id",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"r",
"=",
"requests",
".",
"post",
"(",
"url",
"=",
"target",
",",
"data",
"=",
"json",
".",
"dum... | 33.647059 | 17.647059 |
def print(self, *args, end='\n', file=None):
"""Convenience function so you don't need to remember to put the \n
at the end of the line.
"""
if file is None:
file = self.stdout
s = ' '.join(str(arg) for arg in args) + end
file.write(s) | [
"def",
"print",
"(",
"self",
",",
"*",
"args",
",",
"end",
"=",
"'\\n'",
",",
"file",
"=",
"None",
")",
":",
"if",
"file",
"is",
"None",
":",
"file",
"=",
"self",
".",
"stdout",
"s",
"=",
"' '",
".",
"join",
"(",
"str",
"(",
"arg",
")",
"for"... | 36.375 | 8.375 |
def get_arp_table(self):
"""
Get arp table information.
Return a list of dictionaries having the following set of keys:
* interface (string)
* mac (string)
* ip (string)
* age (float)
For example::
[
{
... | [
"def",
"get_arp_table",
"(",
"self",
")",
":",
"arp_table",
"=",
"[",
"]",
"command",
"=",
"'show arp | exclude Incomplete'",
"output",
"=",
"self",
".",
"_send_command",
"(",
"command",
")",
"# Skip the first line which is a header",
"output",
"=",
"output",
".",
... | 34.367647 | 18.279412 |
def _validate_entities(self, stages):
"""
Purpose: Validate whether the argument 'stages' is of list of Stage objects
:argument: list of Stage objects
"""
if not stages:
raise TypeError(expected_type=Stage, actual_type=type(stages))
if not isinstance(stages,... | [
"def",
"_validate_entities",
"(",
"self",
",",
"stages",
")",
":",
"if",
"not",
"stages",
":",
"raise",
"TypeError",
"(",
"expected_type",
"=",
"Stage",
",",
"actual_type",
"=",
"type",
"(",
"stages",
")",
")",
"if",
"not",
"isinstance",
"(",
"stages",
"... | 30.411765 | 20.058824 |
def send(self, message, socket_):
"""
Sends a message (dict) to the socket. Message consists of a 8-byte len header followed by a msgpack-numpy
encoded dict.
Args:
message: The message dict (e.g. {"cmd": "reset"})
socket_: The python socket object to use.
... | [
"def",
"send",
"(",
"self",
",",
"message",
",",
"socket_",
")",
":",
"if",
"not",
"socket_",
":",
"raise",
"TensorForceError",
"(",
"\"No socket given in call to `send`!\"",
")",
"elif",
"not",
"isinstance",
"(",
"message",
",",
"dict",
")",
":",
"raise",
"... | 42.882353 | 20.294118 |
def _field_value_text(self, field):
"""Return the html representation of the value of the given field"""
if field in self.fields:
return unicode(self.get(field))
else:
return self.get_timemachine_instance(field)._object_name_text() | [
"def",
"_field_value_text",
"(",
"self",
",",
"field",
")",
":",
"if",
"field",
"in",
"self",
".",
"fields",
":",
"return",
"unicode",
"(",
"self",
".",
"get",
"(",
"field",
")",
")",
"else",
":",
"return",
"self",
".",
"get_timemachine_instance",
"(",
... | 45.666667 | 13 |
def _onCompletionListItemSelected(self, index):
"""Item selected. Insert completion to editor
"""
model = self._widget.model()
selectedWord = model.words[index]
textToInsert = selectedWord[len(model.typedText()):]
self._qpart.textCursor().insertText(textToInsert)
... | [
"def",
"_onCompletionListItemSelected",
"(",
"self",
",",
"index",
")",
":",
"model",
"=",
"self",
".",
"_widget",
".",
"model",
"(",
")",
"selectedWord",
"=",
"model",
".",
"words",
"[",
"index",
"]",
"textToInsert",
"=",
"selectedWord",
"[",
"len",
"(",
... | 42 | 7.25 |
def _cleanup(self):
"""Cleanup the stored sessions"""
current_time = time.time()
timeout = self._config.timeout
if current_time - self._last_cleanup_time > timeout:
self.store.cleanup(timeout)
self._last_cleanup_time = current_time | [
"def",
"_cleanup",
"(",
"self",
")",
":",
"current_time",
"=",
"time",
".",
"time",
"(",
")",
"timeout",
"=",
"self",
".",
"_config",
".",
"timeout",
"if",
"current_time",
"-",
"self",
".",
"_last_cleanup_time",
">",
"timeout",
":",
"self",
".",
"store",... | 40.142857 | 8.571429 |
def _read_linguas_from_files(env, linguas_files=None):
""" Parse `LINGUAS` file and return list of extracted languages """
import SCons.Util
import SCons.Environment
global _re_comment
global _re_lang
if not SCons.Util.is_List(linguas_files) \
and not SCons.Util.is_String(linguas_fil... | [
"def",
"_read_linguas_from_files",
"(",
"env",
",",
"linguas_files",
"=",
"None",
")",
":",
"import",
"SCons",
".",
"Util",
"import",
"SCons",
".",
"Environment",
"global",
"_re_comment",
"global",
"_re_lang",
"if",
"not",
"SCons",
".",
"Util",
".",
"is_List",... | 38.619048 | 15.714286 |
def random_word(self, length, prefix=0, start=False, end=False,
flatten=False):
"""
Generate a random word of length from this table.
:param length: the length of the generated word; >= 1;
:param prefix: if greater than 0, the maximum length of the prefix to
... | [
"def",
"random_word",
"(",
"self",
",",
"length",
",",
"prefix",
"=",
"0",
",",
"start",
"=",
"False",
",",
"end",
"=",
"False",
",",
"flatten",
"=",
"False",
")",
":",
"if",
"start",
":",
"word",
"=",
"\">\"",
"length",
"+=",
"1",
"return",
"self"... | 47.172414 | 21.37931 |
def build(self):
"""Builds the index, creating an instance of `lunr.Index`.
This completes the indexing process and should only be called once all
documents have been added to the index.
"""
self._calculate_average_field_lengths()
self._create_field_vectors()
sel... | [
"def",
"build",
"(",
"self",
")",
":",
"self",
".",
"_calculate_average_field_lengths",
"(",
")",
"self",
".",
"_create_field_vectors",
"(",
")",
"self",
".",
"_create_token_set",
"(",
")",
"return",
"Index",
"(",
"inverted_index",
"=",
"self",
".",
"inverted_... | 34.058824 | 14.117647 |
def predict_epitopes_from_args(args):
"""
Returns an epitope collection from the given commandline arguments.
Parameters
----------
args : argparse.Namespace
Parsed commandline arguments for Topiary
"""
mhc_model = mhc_binding_predictor_from_args(args)
variants = variant_collect... | [
"def",
"predict_epitopes_from_args",
"(",
"args",
")",
":",
"mhc_model",
"=",
"mhc_binding_predictor_from_args",
"(",
"args",
")",
"variants",
"=",
"variant_collection_from_args",
"(",
"args",
")",
"gene_expression_dict",
"=",
"rna_gene_expression_dict_from_args",
"(",
"a... | 40.555556 | 16.481481 |
def best_identities(self):
"""Returns identities of the best HSP in alignment. """
if len(self.hsp_list) > 0:
return round(float(self.hsp_list[0].identities) / float(self.hsp_list[0].align_length) * 100, 1) | [
"def",
"best_identities",
"(",
"self",
")",
":",
"if",
"len",
"(",
"self",
".",
"hsp_list",
")",
">",
"0",
":",
"return",
"round",
"(",
"float",
"(",
"self",
".",
"hsp_list",
"[",
"0",
"]",
".",
"identities",
")",
"/",
"float",
"(",
"self",
".",
... | 58 | 22 |
def get_gallery_favorites(self):
"""Get a list of the images in the gallery this user has favorited."""
url = (self._imgur._base_url + "/3/account/{0}/gallery_favorites".format(
self.name))
resp = self._imgur._send_request(url)
return [Image(img, self._imgur) for img in re... | [
"def",
"get_gallery_favorites",
"(",
"self",
")",
":",
"url",
"=",
"(",
"self",
".",
"_imgur",
".",
"_base_url",
"+",
"\"/3/account/{0}/gallery_favorites\"",
".",
"format",
"(",
"self",
".",
"name",
")",
")",
"resp",
"=",
"self",
".",
"_imgur",
".",
"_send... | 53 | 14 |
def compose_info(root_dir, files, hash_fn, aleph_record, urn_nbn=None):
"""
Compose `info` XML file.
Info example::
<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
<info>
<created>2014-07-31T10:58:53</created>
<metadataversion>1.0</metadataversion>
... | [
"def",
"compose_info",
"(",
"root_dir",
",",
"files",
",",
"hash_fn",
",",
"aleph_record",
",",
"urn_nbn",
"=",
"None",
")",
":",
"# compute hash for hashfile",
"with",
"open",
"(",
"hash_fn",
")",
"as",
"f",
":",
"hash_file_md5",
"=",
"hashlib",
".",
"md5",... | 30.730769 | 20.130769 |
def tb2radiance(self, tb_, **kwargs):
"""Get the radiance from the brightness temperature (Tb) given the
band name.
Input:
tb_: Brightness temperature of the band (self.band)
Optional arguments:
lut: If not none, this is a Look Up Table with tb and radiance values
... | [
"def",
"tb2radiance",
"(",
"self",
",",
"tb_",
",",
"*",
"*",
"kwargs",
")",
":",
"lut",
"=",
"kwargs",
".",
"get",
"(",
"'lut'",
",",
"None",
")",
"normalized",
"=",
"kwargs",
".",
"get",
"(",
"'normalized'",
",",
"True",
")",
"if",
"self",
".",
... | 35.981132 | 21.358491 |
def translate_gene(self, gene):
"""
Translate a gene with binary DNA into a base-10 floating point real number.
Parses the DNA in this manner:
1. The first bit determines the sign of the integer portion of the result (0=positive, 1=negative)
2. The next ``significand... | [
"def",
"translate_gene",
"(",
"self",
",",
"gene",
")",
":",
"if",
"self",
".",
"signed",
":",
"sign",
"=",
"1",
"if",
"gene",
".",
"dna",
"[",
"0",
"]",
"==",
"'0'",
"else",
"-",
"1",
"base_start_idx",
"=",
"1",
"else",
":",
"sign",
"=",
"1",
... | 53.333333 | 30.909091 |
def add_arguments(self, parser):
"""
Add arguments to the command parser.
Uses argparse syntax. See documentation at
https://docs.python.org/3/library/argparse.html.
"""
parser.add_argument(
'--start', '-s',
default=0,
type=int,
... | [
"def",
"add_arguments",
"(",
"self",
",",
"parser",
")",
":",
"parser",
".",
"add_argument",
"(",
"'--start'",
",",
"'-s'",
",",
"default",
"=",
"0",
",",
"type",
"=",
"int",
",",
"help",
"=",
"u\"The Submission.id at which to begin updating rows. 0 by default.\""... | 31.36 | 19.44 |
def write(self, ostream, kmip_version=enums.KMIPVersion.KMIP_1_0):
"""
Write the data encoding the ExtensionInformation object to a stream.
Args:
ostream (Stream): A data stream in which to encode object data,
supporting a write method; usually a BytearrayStream obje... | [
"def",
"write",
"(",
"self",
",",
"ostream",
",",
"kmip_version",
"=",
"enums",
".",
"KMIPVersion",
".",
"KMIP_1_0",
")",
":",
"tstream",
"=",
"BytearrayStream",
"(",
")",
"self",
".",
"extension_name",
".",
"write",
"(",
"tstream",
",",
"kmip_version",
"=... | 39.692308 | 21.461538 |
def get_archives(self, offset=None, count=None, session_id=None):
"""Returns an ArchiveList, which is an array of archives that are completed and in-progress,
for your API key.
:param int: offset Optional. The index offset of the first archive. 0 is offset
of the most recently started... | [
"def",
"get_archives",
"(",
"self",
",",
"offset",
"=",
"None",
",",
"count",
"=",
"None",
",",
"session_id",
"=",
"None",
")",
":",
"params",
"=",
"{",
"}",
"if",
"offset",
"is",
"not",
"None",
":",
"params",
"[",
"'offset'",
"]",
"=",
"offset",
"... | 44.342857 | 23.457143 |
def parse_line(self, line):
"""
For each line we are passed, call the XML parser. Returns the
line if we are outside one of the ignored tables, otherwise
returns the empty string.
@param line: the line of the LIGO_LW XML file to be parsed
@type line: string
@return: the line of XML passed ... | [
"def",
"parse_line",
"(",
"self",
",",
"line",
")",
":",
"self",
".",
"__p",
".",
"Parse",
"(",
"line",
")",
"if",
"self",
".",
"__in_table",
":",
"self",
".",
"__silent",
"=",
"1",
"if",
"not",
"self",
".",
"__silent",
":",
"ret",
"=",
"line",
"... | 25.227273 | 19.681818 |
def filterAcceptsRow(self, source_row, source_parent):
"""Exclude items in `self.excludes`"""
model = self.sourceModel()
item = model.items[source_row]
key = getattr(item, "filter", None)
if key is not None:
regex = self.filterRegExp()
if regex.pattern():
... | [
"def",
"filterAcceptsRow",
"(",
"self",
",",
"source_row",
",",
"source_parent",
")",
":",
"model",
"=",
"self",
".",
"sourceModel",
"(",
")",
"item",
"=",
"model",
".",
"items",
"[",
"source_row",
"]",
"key",
"=",
"getattr",
"(",
"item",
",",
"\"filter\... | 41.208333 | 15.541667 |
def add_checker(self, checker):
"""walk to the checker's dir and collect visit and leave methods"""
# XXX : should be possible to merge needed_checkers and add_checker
vcids = set()
lcids = set()
visits = self.visit_events
leaves = self.leave_events
for member in ... | [
"def",
"add_checker",
"(",
"self",
",",
"checker",
")",
":",
"# XXX : should be possible to merge needed_checkers and add_checker",
"vcids",
"=",
"set",
"(",
")",
"lcids",
"=",
"set",
"(",
")",
"visits",
"=",
"self",
".",
"visit_events",
"leaves",
"=",
"self",
"... | 43.413793 | 11.241379 |
def statistics(self):
"""
Get the dictionary with the count of the check-statuses
:return: dict(str -> int)
"""
result = {}
for r in self.results:
result.setdefault(r.status, 0)
result[r.status] += 1
return result | [
"def",
"statistics",
"(",
"self",
")",
":",
"result",
"=",
"{",
"}",
"for",
"r",
"in",
"self",
".",
"results",
":",
"result",
".",
"setdefault",
"(",
"r",
".",
"status",
",",
"0",
")",
"result",
"[",
"r",
".",
"status",
"]",
"+=",
"1",
"return",
... | 25.818182 | 13.454545 |
def get_info(handle):
"""Get information about this current console window (for Microsoft Windows only).
Raises IOError if attempt to get information fails (if there is no console window).
Don't forget to call _WindowsCSBI.initialize() once in your application before calling this method.
... | [
"def",
"get_info",
"(",
"handle",
")",
":",
"# Query Win32 API.",
"csbi",
"=",
"_WindowsCSBI",
".",
"CSBI",
"(",
")",
"try",
":",
"if",
"not",
"_WindowsCSBI",
".",
"WINDLL",
".",
"kernel32",
".",
"GetConsoleScreenBufferInfo",
"(",
"handle",
",",
"ctypes",
".... | 47.810811 | 28.486486 |
def parse(readDataInstance, numberOfEntries):
"""
Returns a L{ImageBoundForwarderRef} array where every element is a L{ImageBoundForwarderRefEntry} object.
@type readDataInstance: L{ReadData}
@param readDataInstance: A L{ReadData} object with the corresponding data to generate ... | [
"def",
"parse",
"(",
"readDataInstance",
",",
"numberOfEntries",
")",
":",
"imageBoundForwarderRefsList",
"=",
"ImageBoundForwarderRef",
"(",
")",
"dLength",
"=",
"len",
"(",
"readDataInstance",
")",
"entryLength",
"=",
"ImageBoundForwarderRefEntry",
"(",
")",
".",
... | 47.517241 | 25.862069 |
def _get_events(self, result):
""""Internal method for being able to run unit tests."""
events = []
for event_data in result:
event = Event.factory(event_data)
if event is not None:
events.append(event)
if isinstance(event, DeviceStateCh... | [
"def",
"_get_events",
"(",
"self",
",",
"result",
")",
":",
"events",
"=",
"[",
"]",
"for",
"event_data",
"in",
"result",
":",
"event",
"=",
"Event",
".",
"factory",
"(",
"event_data",
")",
"if",
"event",
"is",
"not",
"None",
":",
"events",
".",
"app... | 34.545455 | 18.090909 |
def get_ptn(unit):
"""获取文本行的中文字符的个数
Keyword arguments:
unit -- 文本行
Return:
ptn -- 纯文本数
"""
ptn = 0
match_re = re.findall(chinese, unit)
if match_re:
string = ''.join(match_re)
ptn = len(string)
return int(ptn) | [
"def",
"get_ptn",
"(",
"unit",
")",
":",
"ptn",
"=",
"0",
"match_re",
"=",
"re",
".",
"findall",
"(",
"chinese",
",",
"unit",
")",
"if",
"match_re",
":",
"string",
"=",
"''",
".",
"join",
"(",
"match_re",
")",
"ptn",
"=",
"len",
"(",
"string",
")... | 20.857143 | 15.357143 |
def add_topic(self, topic):
"""Add a topic to the list of topics tracked via metadata.
Arguments:
topic (str): topic to track
Returns:
Future: resolves after metadata request/response
"""
if topic in self._topics:
return Future().success(set(... | [
"def",
"add_topic",
"(",
"self",
",",
"topic",
")",
":",
"if",
"topic",
"in",
"self",
".",
"_topics",
":",
"return",
"Future",
"(",
")",
".",
"success",
"(",
"set",
"(",
"self",
".",
"_topics",
")",
")",
"self",
".",
"_topics",
".",
"add",
"(",
"... | 28.5 | 16.714286 |
def _connected(cm, nodes, connection):
"""Test connectivity for the connectivity matrix."""
if nodes is not None:
cm = cm[np.ix_(nodes, nodes)]
num_components, _ = connected_components(cm, connection=connection)
return num_components < 2 | [
"def",
"_connected",
"(",
"cm",
",",
"nodes",
",",
"connection",
")",
":",
"if",
"nodes",
"is",
"not",
"None",
":",
"cm",
"=",
"cm",
"[",
"np",
".",
"ix_",
"(",
"nodes",
",",
"nodes",
")",
"]",
"num_components",
",",
"_",
"=",
"connected_components",... | 36.571429 | 14.571429 |
def adjustChildren(self, delta, secs=False):
"""
Shifts the children for this item by the inputed number of days.
:param delta | <int>
"""
if self.adjustmentsBlocked('children'):
return
if self.itemStyle() != self.ItemStyle.... | [
"def",
"adjustChildren",
"(",
"self",
",",
"delta",
",",
"secs",
"=",
"False",
")",
":",
"if",
"self",
".",
"adjustmentsBlocked",
"(",
"'children'",
")",
":",
"return",
"if",
"self",
".",
"itemStyle",
"(",
")",
"!=",
"self",
".",
"ItemStyle",
".",
"Gro... | 33.653846 | 15.346154 |
def project_path(cls, user, project):
"""Return a fully-qualified project string."""
return google.api_core.path_template.expand(
"users/{user}/projects/{project}", user=user, project=project
) | [
"def",
"project_path",
"(",
"cls",
",",
"user",
",",
"project",
")",
":",
"return",
"google",
".",
"api_core",
".",
"path_template",
".",
"expand",
"(",
"\"users/{user}/projects/{project}\"",
",",
"user",
"=",
"user",
",",
"project",
"=",
"project",
")"
] | 45 | 15.8 |
def remove_api_key_from_groups(self, api_key, body, **kwargs): # noqa: E501
"""Remove API key from groups. # noqa: E501
An endpoint for removing API key from groups. **Example usage:** `curl -X DELETE https://api.us-east-1.mbedcloud.com/v3/api-keys/{apikey-id}/groups -d '[0162056a9a1586f30242590700... | [
"def",
"remove_api_key_from_groups",
"(",
"self",
",",
"api_key",
",",
"body",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'asynchronous'",
")",
":",
"retur... | 62.772727 | 37.090909 |
def _slr_build_parser_table(productionset):
"""SLR method to build parser table"""
result = ParserTable()
statesset = build_states_sets(productionset)
for itemindex, itemset in enumerate(statesset):
LOG.debug("_slr_build_parser_table: Evaluating itemset:" + str(itemset))
for symbol in pr... | [
"def",
"_slr_build_parser_table",
"(",
"productionset",
")",
":",
"result",
"=",
"ParserTable",
"(",
")",
"statesset",
"=",
"build_states_sets",
"(",
"productionset",
")",
"for",
"itemindex",
",",
"itemset",
"in",
"enumerate",
"(",
"statesset",
")",
":",
"LOG",
... | 67.473684 | 31.210526 |
def read_env(path=None, recurse=True, stream=None, verbose=False, override=False):
"""Read a .env file into os.environ.
If .env is not found in the directory from which this method is called,
the default behavior is to recurse up the directory tree until a .env
file is found. If you do ... | [
"def",
"read_env",
"(",
"path",
"=",
"None",
",",
"recurse",
"=",
"True",
",",
"stream",
"=",
"None",
",",
"verbose",
"=",
"False",
",",
"override",
"=",
"False",
")",
":",
"# By default, start search from the same file this function is called",
"if",
"path",
"i... | 47.192308 | 21.923077 |
def start(cls, settings=None):
"""
RUN ME FIRST TO SETUP THE THREADED LOGGING
http://victorlin.me/2012/08/good-logging-practice-in-python/
log - LIST OF PARAMETERS FOR LOGGER(S)
trace - SHOW MORE DETAILS IN EVERY LOG LINE (default False)
cprofile - True==ENABL... | [
"def",
"start",
"(",
"cls",
",",
"settings",
"=",
"None",
")",
":",
"global",
"_Thread",
"if",
"not",
"settings",
":",
"return",
"settings",
"=",
"wrap",
"(",
"settings",
")",
"Log",
".",
"stop",
"(",
")",
"cls",
".",
"settings",
"=",
"settings",
"cl... | 42.421053 | 23.403509 |
def csch(x, context=None):
"""
Return the hyperbolic cosecant of x.
"""
return _apply_function_in_current_context(
BigFloat,
mpfr.mpfr_csch,
(BigFloat._implicit_convert(x),),
context,
) | [
"def",
"csch",
"(",
"x",
",",
"context",
"=",
"None",
")",
":",
"return",
"_apply_function_in_current_context",
"(",
"BigFloat",
",",
"mpfr",
".",
"mpfr_csch",
",",
"(",
"BigFloat",
".",
"_implicit_convert",
"(",
"x",
")",
",",
")",
",",
"context",
",",
... | 20.727273 | 14.545455 |
def get_agents(self, addr=True, agent_cls=None, as_coro=False):
"""Get agents from the slave environments.
:param bool addr:
If ``True``, returns only addresses of the agents, otherwise
returns a :class:`Proxy` object for each agent.
:param agent_cls:
If spe... | [
"def",
"get_agents",
"(",
"self",
",",
"addr",
"=",
"True",
",",
"agent_cls",
"=",
"None",
",",
"as_coro",
"=",
"False",
")",
":",
"async",
"def",
"slave_task",
"(",
"mgr_addr",
",",
"addr",
"=",
"True",
",",
"agent_cls",
"=",
"None",
")",
":",
"r_ma... | 41.083333 | 26.833333 |
def file_matches(filename, patterns):
"""Does this filename match any of the patterns?"""
return any(fnmatch.fnmatch(filename, pat)
or fnmatch.fnmatch(os.path.basename(filename), pat)
for pat in patterns) | [
"def",
"file_matches",
"(",
"filename",
",",
"patterns",
")",
":",
"return",
"any",
"(",
"fnmatch",
".",
"fnmatch",
"(",
"filename",
",",
"pat",
")",
"or",
"fnmatch",
".",
"fnmatch",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"filename",
")",
",",
... | 47.6 | 7.8 |
def confirm_deliveries(self):
"""Set the channel to confirm that each message has been
successfully delivered.
:raises AMQPChannelError: Raises if the channel encountered an error.
:raises AMQPConnectionError: Raises if the connection
encountered an ... | [
"def",
"confirm_deliveries",
"(",
"self",
")",
":",
"self",
".",
"_confirming_deliveries",
"=",
"True",
"confirm_frame",
"=",
"specification",
".",
"Confirm",
".",
"Select",
"(",
")",
"return",
"self",
".",
"rpc_request",
"(",
"confirm_frame",
")"
] | 37.615385 | 17.076923 |
def delete_os_dummy_rtr(self, tenant_id, fw_dict, is_fw_virt=False):
"""Delete the Openstack Dummy router and store the info in DB. """
ret = True
tenant_name = fw_dict.get('tenant_name')
try:
rtr_id = fw_dict.get('router_id')
if not rtr_id:
LOG.er... | [
"def",
"delete_os_dummy_rtr",
"(",
"self",
",",
"tenant_id",
",",
"fw_dict",
",",
"is_fw_virt",
"=",
"False",
")",
":",
"ret",
"=",
"True",
"tenant_name",
"=",
"fw_dict",
".",
"get",
"(",
"'tenant_name'",
")",
"try",
":",
"rtr_id",
"=",
"fw_dict",
".",
"... | 43.461538 | 16.846154 |
def parse_trips(self, xml, requested_time):
"""
Parse the NS API xml result into Trip objects
"""
obj = xmltodict.parse(xml)
trips = []
if 'error' in obj:
print('Error in trips: ' + obj['error']['message'])
return None
try:
fo... | [
"def",
"parse_trips",
"(",
"self",
",",
"xml",
",",
"requested_time",
")",
":",
"obj",
"=",
"xmltodict",
".",
"parse",
"(",
"xml",
")",
"trips",
"=",
"[",
"]",
"if",
"'error'",
"in",
"obj",
":",
"print",
"(",
"'Error in trips: '",
"+",
"obj",
"[",
"'... | 29.55 | 18.65 |
def contains_empty(features):
"""Check features data are not empty
:param features: The features data to check.
:type features: list of numpy arrays.
:return: True if one of the array is empty, False else.
"""
if not features:
return True
for feature in features:
if featur... | [
"def",
"contains_empty",
"(",
"features",
")",
":",
"if",
"not",
"features",
":",
"return",
"True",
"for",
"feature",
"in",
"features",
":",
"if",
"feature",
".",
"shape",
"[",
"0",
"]",
"==",
"0",
":",
"return",
"True",
"return",
"False"
] | 24.2 | 17.333333 |
def max_runs_reached(self):
"""
:return: whether all file paths have been processed max_runs times
"""
if self._max_runs == -1: # Unlimited runs.
return False
for file_path in self._file_paths:
if self._run_count[file_path] < self._max_runs:
... | [
"def",
"max_runs_reached",
"(",
"self",
")",
":",
"if",
"self",
".",
"_max_runs",
"==",
"-",
"1",
":",
"# Unlimited runs.",
"return",
"False",
"for",
"file_path",
"in",
"self",
".",
"_file_paths",
":",
"if",
"self",
".",
"_run_count",
"[",
"file_path",
"]"... | 36.333333 | 14.166667 |
def main(args=None):
"""Main"""
vs = [(v-100)*0.001 for v in range(200)]
for f in ['IM.channel.nml','Kd.channel.nml']:
nml_doc = pynml.read_neuroml2_file(f)
for ct in nml_doc.ComponentType:
ys = []
for v in vs:
req_variables = {'v':'%sV'%v,... | [
"def",
"main",
"(",
"args",
"=",
"None",
")",
":",
"vs",
"=",
"[",
"(",
"v",
"-",
"100",
")",
"*",
"0.001",
"for",
"v",
"in",
"range",
"(",
"200",
")",
"]",
"for",
"f",
"in",
"[",
"'IM.channel.nml'",
",",
"'Kd.channel.nml'",
"]",
":",
"nml_doc",
... | 30.103448 | 19 |
def ivorn_prefix_present(session, ivorn_prefix):
"""
Predicate, returns whether there is an entry in the database with matching
IVORN prefix.
"""
n_matches = session.query(Voevent.ivorn).filter(
Voevent.ivorn.like('{}%'.format(ivorn_prefix))).count()
return bool(n_matches) | [
"def",
"ivorn_prefix_present",
"(",
"session",
",",
"ivorn_prefix",
")",
":",
"n_matches",
"=",
"session",
".",
"query",
"(",
"Voevent",
".",
"ivorn",
")",
".",
"filter",
"(",
"Voevent",
".",
"ivorn",
".",
"like",
"(",
"'{}%'",
".",
"format",
"(",
"ivorn... | 37.75 | 15.25 |
def push_concurrency_history_item(self, state, number_concurrent_threads):
"""Adds a new concurrency-history-item to the history item list
A concurrent history item stores information about the point in time where a certain number of states is
launched concurrently
(e.g. in a barrier co... | [
"def",
"push_concurrency_history_item",
"(",
"self",
",",
"state",
",",
"number_concurrent_threads",
")",
":",
"last_history_item",
"=",
"self",
".",
"get_last_history_item",
"(",
")",
"return_item",
"=",
"ConcurrencyItem",
"(",
"state",
",",
"self",
".",
"get_last_... | 54.866667 | 26.866667 |
def _add_process_guards(self, engine):
"""Add multiprocessing guards.
Forces a connection to be reconnected if it is detected
as having been shared to a sub-process.
"""
@sqlalchemy.event.listens_for(engine, "connect")
def connect(dbapi_connection, connection_record):
... | [
"def",
"_add_process_guards",
"(",
"self",
",",
"engine",
")",
":",
"@",
"sqlalchemy",
".",
"event",
".",
"listens_for",
"(",
"engine",
",",
"\"connect\"",
")",
"def",
"connect",
"(",
"dbapi_connection",
",",
"connection_record",
")",
":",
"connection_record",
... | 47.166667 | 25.291667 |
def is_resource_protected(self, request, **kwargs):
"""
Returns true if and only if the resource's URL is *not* exempt and *is* protected.
"""
exempt_urls = self.get_exempt_url_patterns()
protected_urls = self.get_protected_url_patterns()
path = request.path_info.lstrip('... | [
"def",
"is_resource_protected",
"(",
"self",
",",
"request",
",",
"*",
"*",
"kwargs",
")",
":",
"exempt_urls",
"=",
"self",
".",
"get_exempt_url_patterns",
"(",
")",
"protected_urls",
"=",
"self",
".",
"get_protected_url_patterns",
"(",
")",
"path",
"=",
"requ... | 33.705882 | 20.411765 |
def move(self, entries, directory):
"""
Move one or more entries (file or directory) to the destination
directory
:param list entries: a list of source entries (:class:`.BaseFile`
object)
:param directory: destination directory
:return: whether the action is ... | [
"def",
"move",
"(",
"self",
",",
"entries",
",",
"directory",
")",
":",
"fcids",
"=",
"[",
"]",
"for",
"entry",
"in",
"entries",
":",
"if",
"isinstance",
"(",
"entry",
",",
"File",
")",
":",
"fcid",
"=",
"entry",
".",
"fid",
"elif",
"isinstance",
"... | 36.966667 | 14.433333 |
def value( self, node, parent=None ):
"""Return value used to compare size of this node"""
# this is the *weighted* size/contribution of the node
try:
return node['contribution']
except KeyError, err:
contribution = int(node.get('totsize',0)/float( len(node.get('... | [
"def",
"value",
"(",
"self",
",",
"node",
",",
"parent",
"=",
"None",
")",
":",
"# this is the *weighted* size/contribution of the node ",
"try",
":",
"return",
"node",
"[",
"'contribution'",
"]",
"except",
"KeyError",
",",
"err",
":",
"contribution",
"=",
"int"... | 45.777778 | 15.111111 |
def schedule_hostgroup_host_downtime(self, hostgroup, start_time, end_time, fixed,
trigger_id, duration, author, comment):
"""Schedule a downtime for each host of a hostgroup
Format of the line that triggers function call::
SCHEDULE_HOSTGROUP_HOST_DOWNTI... | [
"def",
"schedule_hostgroup_host_downtime",
"(",
"self",
",",
"hostgroup",
",",
"start_time",
",",
"end_time",
",",
"fixed",
",",
"trigger_id",
",",
"duration",
",",
"author",
",",
"comment",
")",
":",
"for",
"host_id",
"in",
"hostgroup",
".",
"get_hosts",
"(",... | 43.16129 | 16.83871 |
def requires_authentication(fn):
"""
Requires that the calling Subject be authenticated before allowing access.
"""
@functools.wraps(fn)
def wrap(*args, **kwargs):
subject = WebYosai.get_current_subject()
if not subject.authenticated:
msg... | [
"def",
"requires_authentication",
"(",
"fn",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"fn",
")",
"def",
"wrap",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"subject",
"=",
"WebYosai",
".",
"get_current_subject",
"(",
")",
"if",
"not",
... | 33.933333 | 20.333333 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.