text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def entry_set(self, predicate=None):
"""
Returns a list clone of the mappings contained in this map.
**Warning:
The list is NOT backed by the map, so changes to the map are NOT reflected in the list, and vice-versa.**
:param predicate: (Predicate), predicate for the map to filt... | [
"def",
"entry_set",
"(",
"self",
",",
"predicate",
"=",
"None",
")",
":",
"if",
"predicate",
":",
"predicate_data",
"=",
"self",
".",
"_to_data",
"(",
"predicate",
")",
"return",
"self",
".",
"_encode_invoke",
"(",
"map_entries_with_predicate_codec",
",",
"pre... | 45 | 31 |
def _set_fcoe_fip_advertisement(self, v, load=False):
"""
Setter method for fcoe_fip_advertisement, mapped from YANG variable /fcoe/fcoe_fabric_map/fcoe_fip_advertisement (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_fcoe_fip_advertisement is considered as ... | [
"def",
"_set_fcoe_fip_advertisement",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
... | 79.56 | 40.12 |
def cast_problem(problem):
"""
Casts problem object with known interface as OptProblem.
Parameters
----------
problem : Object
"""
# Optproblem
if isinstance(problem,OptProblem):
return problem
# Other
else:
# Type Base
if (not hasattr(... | [
"def",
"cast_problem",
"(",
"problem",
")",
":",
"# Optproblem",
"if",
"isinstance",
"(",
"problem",
",",
"OptProblem",
")",
":",
"return",
"problem",
"# Other",
"else",
":",
"# Type Base",
"if",
"(",
"not",
"hasattr",
"(",
"problem",
",",
"'G'",
")",
"or"... | 24.740741 | 20.222222 |
def on_view_change_start(self):
"""
Notifies node about the fact that view changed to let it
prepare for election
"""
self.view_changer.start_view_change_ts = self.utc_epoch()
for replica in self.replicas.values():
replica.on_view_change_start()
logge... | [
"def",
"on_view_change_start",
"(",
"self",
")",
":",
"self",
".",
"view_changer",
".",
"start_view_change_ts",
"=",
"self",
".",
"utc_epoch",
"(",
")",
"for",
"replica",
"in",
"self",
".",
"replicas",
".",
"values",
"(",
")",
":",
"replica",
".",
"on_view... | 43.419355 | 21.935484 |
def kudos(self):
"""
:class:`list` of :class:`stravalib.model.ActivityKudos` objects for this activity.
"""
if self._kudos is None:
self.assert_bind_client()
self._kudos = self.bind_client.get_activity_kudos(self.id)
return self._kudos | [
"def",
"kudos",
"(",
"self",
")",
":",
"if",
"self",
".",
"_kudos",
"is",
"None",
":",
"self",
".",
"assert_bind_client",
"(",
")",
"self",
".",
"_kudos",
"=",
"self",
".",
"bind_client",
".",
"get_activity_kudos",
"(",
"self",
".",
"id",
")",
"return"... | 36.5 | 16.25 |
def prepare(host, default_protocol='telnet', **kwargs):
"""
Creates an instance of the protocol by either parsing the given
URL-formatted hostname using :class:`Exscript.util.url`, or according to
the options of the given :class:`Exscript.Host`.
:type host: str or Host
:param host: A URL-forma... | [
"def",
"prepare",
"(",
"host",
",",
"default_protocol",
"=",
"'telnet'",
",",
"*",
"*",
"kwargs",
")",
":",
"host",
"=",
"to_host",
"(",
"host",
",",
"default_protocol",
"=",
"default_protocol",
")",
"protocol",
"=",
"host",
".",
"get_protocol",
"(",
")",
... | 40.454545 | 16.363636 |
def Read(self):
"""See base class."""
buf = ctypes.create_string_buffer(self.desc.internal_max_in_report_len)
num_read = wintypes.DWORD()
ret = kernel32.ReadFile(
self.dev, buf, len(buf), ctypes.byref(num_read), None)
if num_read.value != self.desc.internal_max_in_report_len:
raise er... | [
"def",
"Read",
"(",
"self",
")",
":",
"buf",
"=",
"ctypes",
".",
"create_string_buffer",
"(",
"self",
".",
"desc",
".",
"internal_max_in_report_len",
")",
"num_read",
"=",
"wintypes",
".",
"DWORD",
"(",
")",
"ret",
"=",
"kernel32",
".",
"ReadFile",
"(",
... | 37 | 23.8125 |
def make_citation_dict(td):
"""
Update a citation dictionary by editing the Author field
:param td: A BixTex format citation dict or a term
:return:
"""
from datetime import datetime
if isinstance(td, dict):
d = td
name = d['name_link']
else:
d = td.as_dict()
... | [
"def",
"make_citation_dict",
"(",
"td",
")",
":",
"from",
"datetime",
"import",
"datetime",
"if",
"isinstance",
"(",
"td",
",",
"dict",
")",
":",
"d",
"=",
"td",
"name",
"=",
"d",
"[",
"'name_link'",
"]",
"else",
":",
"d",
"=",
"td",
".",
"as_dict",
... | 25.463768 | 21.289855 |
def create_project(self,
project_name,
dataset_name,
hostname,
is_public,
s3backend=0,
kvserver='localhost',
kvengine='MySQL',
mdengine=... | [
"def",
"create_project",
"(",
"self",
",",
"project_name",
",",
"dataset_name",
",",
"hostname",
",",
"is_public",
",",
"s3backend",
"=",
"0",
",",
"kvserver",
"=",
"'localhost'",
",",
"kvengine",
"=",
"'MySQL'",
",",
"mdengine",
"=",
"'MySQL'",
",",
"descri... | 34.26 | 15.66 |
def get_cache_key(path):
"""
Create a cache key by concatenating the prefix with a hash of the path.
"""
# Python 2/3 support for path hashing
try:
path_hash = hashlib.md5(path).hexdigest()
except TypeError:
path_hash = hashlib.md5(path.encode('utf-8')).hexdigest()
return set... | [
"def",
"get_cache_key",
"(",
"path",
")",
":",
"# Python 2/3 support for path hashing",
"try",
":",
"path_hash",
"=",
"hashlib",
".",
"md5",
"(",
"path",
")",
".",
"hexdigest",
"(",
")",
"except",
"TypeError",
":",
"path_hash",
"=",
"hashlib",
".",
"md5",
"(... | 34.5 | 14.5 |
def traceroute_batch(input_list, results={}, method="udp", cmd_arguments=None,
delay_time=0.1, max_threads=100):
"""
This is a parallel version of the traceroute primitive.
:param input_list: the input is a list of domain names
:param method: the packet type used for traceroute, UD... | [
"def",
"traceroute_batch",
"(",
"input_list",
",",
"results",
"=",
"{",
"}",
",",
"method",
"=",
"\"udp\"",
",",
"cmd_arguments",
"=",
"None",
",",
"delay_time",
"=",
"0.1",
",",
"max_threads",
"=",
"100",
")",
":",
"threads",
"=",
"[",
"]",
"thread_erro... | 36.716667 | 20.883333 |
def text_dict_write(fpath, dict_):
"""
Very naive, but readable way of storing a dictionary on disk
FIXME: This broke on RoseMary's big dataset. Not sure why. It gave bad
syntax. And the SyntaxError did not seem to be excepted.
"""
#dict_ = text_dict_read(fpath)
#dict_[key] = val
dict_te... | [
"def",
"text_dict_write",
"(",
"fpath",
",",
"dict_",
")",
":",
"#dict_ = text_dict_read(fpath)",
"#dict_[key] = val",
"dict_text2",
"=",
"util_str",
".",
"repr4",
"(",
"dict_",
",",
"strvals",
"=",
"False",
")",
"if",
"VERBOSE",
":",
"print",
"(",
"'[cache] '",... | 37.583333 | 12.583333 |
def write_edges(
edges: Mapping[str, Any],
filename: str,
jsonlines: bool = False,
gzipflag: bool = False,
yaml: bool = False,
):
"""Write edges to file
Args:
edges (Mapping[str, Any]): in edges JSON Schema format
filename (str): filename to write
jsonlines (bool): o... | [
"def",
"write_edges",
"(",
"edges",
":",
"Mapping",
"[",
"str",
",",
"Any",
"]",
",",
"filename",
":",
"str",
",",
"jsonlines",
":",
"bool",
"=",
"False",
",",
"gzipflag",
":",
"bool",
"=",
"False",
",",
"yaml",
":",
"bool",
"=",
"False",
",",
")",... | 25.411765 | 16.647059 |
def process_raw_data(cls, raw_data):
"""Create a new model using raw API response."""
properties = raw_data["properties"]
qos_settings = properties.get("qosSettings", {})
properties["qosSettings"] = VirtualSwtichQosSettings.from_raw_data(
raw_data=qos_settings)
return... | [
"def",
"process_raw_data",
"(",
"cls",
",",
"raw_data",
")",
":",
"properties",
"=",
"raw_data",
"[",
"\"properties\"",
"]",
"qos_settings",
"=",
"properties",
".",
"get",
"(",
"\"qosSettings\"",
",",
"{",
"}",
")",
"properties",
"[",
"\"qosSettings\"",
"]",
... | 53.428571 | 14 |
def _recv_callback(self, msg):
"""
Method is called when there is a message coming from a Mongrel2 server.
This message should be a valid Request String.
"""
m2req = MongrelRequest.parse(msg[0])
MongrelConnection(m2req, self._sending_stream, self.request_callback,
... | [
"def",
"_recv_callback",
"(",
"self",
",",
"msg",
")",
":",
"m2req",
"=",
"MongrelRequest",
".",
"parse",
"(",
"msg",
"[",
"0",
"]",
")",
"MongrelConnection",
"(",
"m2req",
",",
"self",
".",
"_sending_stream",
",",
"self",
".",
"request_callback",
",",
"... | 46.875 | 16.625 |
def _start_ubridge_capture(self, adapter_number, output_file):
"""
Start a packet capture in uBridge.
:param adapter_number: adapter number
:param output_file: PCAP destination file for the capture
"""
adapter = "bridge{}".format(adapter_number)
if not self.ubri... | [
"def",
"_start_ubridge_capture",
"(",
"self",
",",
"adapter_number",
",",
"output_file",
")",
":",
"adapter",
"=",
"\"bridge{}\"",
".",
"format",
"(",
"adapter_number",
")",
"if",
"not",
"self",
".",
"ubridge",
":",
"raise",
"DockerError",
"(",
"\"Cannot start t... | 44.416667 | 24.583333 |
def limits(self, value, square=False):
"""TODO: doc + server side implementation"""
if isinstance(value, six.string_types):
import re
match = re.match(r"(\d*)(\D*)", value)
if match is None:
raise ValueError("do not understand limit specifier %r, examp... | [
"def",
"limits",
"(",
"self",
",",
"value",
",",
"square",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"six",
".",
"string_types",
")",
":",
"import",
"re",
"match",
"=",
"re",
".",
"match",
"(",
"r\"(\\d*)(\\D*)\"",
",",
"value",
... | 44.375 | 14.875 |
def dump_jwks(kbl, target, private=False):
"""
Write a JWK to a file. Will ignore symmetric keys !!
:param kbl: List of KeyBundles
:param target: Name of the file to which everything should be written
:param private: Should also the private parts be exported
"""
keys = []
for kb in kbl... | [
"def",
"dump_jwks",
"(",
"kbl",
",",
"target",
",",
"private",
"=",
"False",
")",
":",
"keys",
"=",
"[",
"]",
"for",
"kb",
"in",
"kbl",
":",
"keys",
".",
"extend",
"(",
"[",
"k",
".",
"serialize",
"(",
"private",
")",
"for",
"k",
"in",
"kb",
".... | 26.8 | 20.24 |
def list(self, argv):
"""List all current search jobs if no jobs specified, otherwise
list the properties of the specified jobs."""
def read(job):
for key in sorted(job.content.keys()):
# Ignore some fields that make the output hard to read and
# t... | [
"def",
"list",
"(",
"self",
",",
"argv",
")",
":",
"def",
"read",
"(",
"job",
")",
":",
"for",
"key",
"in",
"sorted",
"(",
"job",
".",
"content",
".",
"keys",
"(",
")",
")",
":",
"# Ignore some fields that make the output hard to read and",
"# that are avail... | 35.473684 | 17.631579 |
def slice_slice(old_slice, applied_slice, size):
"""Given a slice and the size of the dimension to which it will be applied,
index it with another slice to return a new slice equivalent to applying
the slices sequentially
"""
step = (old_slice.step or 1) * (applied_slice.step or 1)
# For now, u... | [
"def",
"slice_slice",
"(",
"old_slice",
",",
"applied_slice",
",",
"size",
")",
":",
"step",
"=",
"(",
"old_slice",
".",
"step",
"or",
"1",
")",
"*",
"(",
"applied_slice",
".",
"step",
"or",
"1",
")",
"# For now, use the hack of turning old_slice into an ndarray... | 39 | 19.4 |
def is_url(text):
""" Check if the given text looks like a URL. """
if text is None:
return False
text = text.lower()
return text.startswith('http://') or text.startswith('https://') or \
text.startswith('urn:') or text.startswith('file://') | [
"def",
"is_url",
"(",
"text",
")",
":",
"if",
"text",
"is",
"None",
":",
"return",
"False",
"text",
"=",
"text",
".",
"lower",
"(",
")",
"return",
"text",
".",
"startswith",
"(",
"'http://'",
")",
"or",
"text",
".",
"startswith",
"(",
"'https://'",
"... | 38.142857 | 19.142857 |
def send_message(frm=None, to=None, text=None):
"""Shortcut to send a sms using libnexmo api.
:param frm: The originator of the message
:param to: The message's recipient
:param text: The text message body
Example usage:
>>> send_message(to='+33123456789', text='My sms message body')
"""... | [
"def",
"send_message",
"(",
"frm",
"=",
"None",
",",
"to",
"=",
"None",
",",
"text",
"=",
"None",
")",
":",
"assert",
"to",
"is",
"not",
"None",
"assert",
"text",
"is",
"not",
"None",
"if",
"frm",
"is",
"None",
":",
"frm",
"=",
"settings",
".",
"... | 25.04 | 20.96 |
def get_confidence(self):
"""return confidence based on existing data"""
# if we didn't receive any character in our consideration range,
# return negative answer
if self._mTotalChars <= 0 or self._mFreqChars <= MINIMUM_DATA_THRESHOLD:
return SURE_NO
if self._mTotalC... | [
"def",
"get_confidence",
"(",
"self",
")",
":",
"# if we didn't receive any character in our consideration range,",
"# return negative answer",
"if",
"self",
".",
"_mTotalChars",
"<=",
"0",
"or",
"self",
".",
"_mFreqChars",
"<=",
"MINIMUM_DATA_THRESHOLD",
":",
"return",
"... | 40.133333 | 20.8 |
def to_safe_str(s):
"""
converts some (tr) non-ascii chars to ascii counterparts,
then return the result as lowercase
"""
# TODO: This is insufficient as it doesn't do anything for other non-ascii chars
return re.sub(r'[^0-9a-zA-Z]+', '_', s.strip().replace(u'ğ', 'g').replace(u'ö', 'o').replace(... | [
"def",
"to_safe_str",
"(",
"s",
")",
":",
"# TODO: This is insufficient as it doesn't do anything for other non-ascii chars",
"return",
"re",
".",
"sub",
"(",
"r'[^0-9a-zA-Z]+'",
",",
"'_'",
",",
"s",
".",
"strip",
"(",
")",
".",
"replace",
"(",
"u'ğ',",
" ",
"g')... | 55.8 | 26.8 |
def _build_loop(self, lexer):
"""Build saveframe loop.
:param lexer: instance of lexical analyzer.
:type lexer: :func:`~nmrstarlib.bmrblex.bmrblex`
:return: Fields and values of the loop.
:rtype: :py:class:`tuple`
"""
fields = []
values = []
toke... | [
"def",
"_build_loop",
"(",
"self",
",",
"lexer",
")",
":",
"fields",
"=",
"[",
"]",
"values",
"=",
"[",
"]",
"token",
"=",
"next",
"(",
"lexer",
")",
"while",
"token",
"[",
"0",
"]",
"==",
"u\"_\"",
":",
"fields",
".",
"append",
"(",
"token",
"["... | 32.64 | 20.6 |
def _add_disease_association_attributes(self, att_ind_start, att_mappings):
"""Add disease association information to the attribute mapping dictionary.
:param int att_ind_start: Start index for enumerating the attributes.
:param dict att_mappings: Dictionary of mappings between vertices and enu... | [
"def",
"_add_disease_association_attributes",
"(",
"self",
",",
"att_ind_start",
",",
"att_mappings",
")",
":",
"disease_mappings",
"=",
"self",
".",
"get_disease_mappings",
"(",
"att_ind_start",
")",
"for",
"vertex",
"in",
"self",
".",
"graph",
".",
"vs",
":",
... | 59.166667 | 25.333333 |
def onSelect_specimen(self, event):
"""
update figures and text when a new specimen is selected
"""
self.selected_meas = []
self.select_specimen(str(self.specimens_box.GetValue()))
if self.ie_open:
self.ie.change_selected(self.current_fit)
self.update_... | [
"def",
"onSelect_specimen",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"selected_meas",
"=",
"[",
"]",
"self",
".",
"select_specimen",
"(",
"str",
"(",
"self",
".",
"specimens_box",
".",
"GetValue",
"(",
")",
")",
")",
"if",
"self",
".",
"ie_ope... | 35.888889 | 11 |
def handle(client_message, handle_event_member=None, handle_event_member_list=None, handle_event_member_attribute_change=None, to_object=None):
""" Event handler """
message_type = client_message.get_message_type()
if message_type == EVENT_MEMBER and handle_event_member is not None:
member = MemberC... | [
"def",
"handle",
"(",
"client_message",
",",
"handle_event_member",
"=",
"None",
",",
"handle_event_member_list",
"=",
"None",
",",
"handle_event_member_attribute_change",
"=",
"None",
",",
"to_object",
"=",
"None",
")",
":",
"message_type",
"=",
"client_message",
"... | 57.409091 | 21.818182 |
def model(self,
voltages=True,
sensitivities=False,
potentials=False,
output_directory=None,
silent=False,
):
"""Forward model the tomodir and read in the results
"""
self._check_state()
if self.can_model... | [
"def",
"model",
"(",
"self",
",",
"voltages",
"=",
"True",
",",
"sensitivities",
"=",
"False",
",",
"potentials",
"=",
"False",
",",
"output_directory",
"=",
"None",
",",
"silent",
"=",
"False",
",",
")",
":",
"self",
".",
"_check_state",
"(",
")",
"if... | 36.694444 | 16.333333 |
def fix_queue_critical(self):
"""
This function tries to fix critical events originating from the queue submission system.
Returns the number of tasks that have been fixed.
"""
count = 0
for task in self.iflat_tasks(status=self.S_QCRITICAL):
logger.info("Will... | [
"def",
"fix_queue_critical",
"(",
"self",
")",
":",
"count",
"=",
"0",
"for",
"task",
"in",
"self",
".",
"iflat_tasks",
"(",
"status",
"=",
"self",
".",
"S_QCRITICAL",
")",
":",
"logger",
".",
"info",
"(",
"\"Will try to fix task %s\"",
"%",
"str",
"(",
... | 34.8125 | 19.9375 |
def get_bgcolor(self, index):
"""Background color depending on value"""
value = self.get_value(index)
if index.column() < 3:
color = ReadOnlyCollectionsModel.get_bgcolor(self, index)
else:
if self.remote:
color_name = value['color']
... | [
"def",
"get_bgcolor",
"(",
"self",
",",
"index",
")",
":",
"value",
"=",
"self",
".",
"get_value",
"(",
"index",
")",
"if",
"index",
".",
"column",
"(",
")",
"<",
"3",
":",
"color",
"=",
"ReadOnlyCollectionsModel",
".",
"get_bgcolor",
"(",
"self",
",",... | 35.769231 | 11.923077 |
def set_scenario_status(scenario_id, status, **kwargs):
"""
Set the status of a scenario.
"""
user_id = kwargs.get('user_id')
_check_can_edit_scenario(scenario_id, kwargs['user_id'])
scenario_i = _get_scenario(scenario_id, user_id)
scenario_i.status = status
db.DBSession.flush()
... | [
"def",
"set_scenario_status",
"(",
"scenario_id",
",",
"status",
",",
"*",
"*",
"kwargs",
")",
":",
"user_id",
"=",
"kwargs",
".",
"get",
"(",
"'user_id'",
")",
"_check_can_edit_scenario",
"(",
"scenario_id",
",",
"kwargs",
"[",
"'user_id'",
"]",
")",
"scena... | 23 | 19 |
def remove_bookmark(self, time):
"""User removes bookmark.
Parameters
----------
time : tuple of float
start and end of the new bookmark, in s
"""
self.annot.remove_bookmark(time=time)
self.update_annotations() | [
"def",
"remove_bookmark",
"(",
"self",
",",
"time",
")",
":",
"self",
".",
"annot",
".",
"remove_bookmark",
"(",
"time",
"=",
"time",
")",
"self",
".",
"update_annotations",
"(",
")"
] | 27 | 12.6 |
def get_params(self, pnames=None):
""" Return a list of Parameter objects
Parameters
----------
pname : list or None
If a list get the Parameter objects with those names
If none, get all the Parameter objects
Returns
-------
params : lis... | [
"def",
"get_params",
"(",
"self",
",",
"pnames",
"=",
"None",
")",
":",
"l",
"=",
"[",
"]",
"if",
"pnames",
"is",
"None",
":",
"pnames",
"=",
"self",
".",
"params",
".",
"keys",
"(",
")",
"for",
"pname",
"in",
"pnames",
":",
"p",
"=",
"self",
"... | 22 | 19.576923 |
def scale2x(self, surface):
"""
Scales using the AdvanceMAME Scale2X algorithm which does a
'jaggie-less' scale of bitmap graphics.
"""
assert(self._scale == 2)
return self._pygame.transform.scale2x(surface) | [
"def",
"scale2x",
"(",
"self",
",",
"surface",
")",
":",
"assert",
"(",
"self",
".",
"_scale",
"==",
"2",
")",
"return",
"self",
".",
"_pygame",
".",
"transform",
".",
"scale2x",
"(",
"surface",
")"
] | 35.571429 | 9.857143 |
def handle_user(self, params):
"""
Handle the USER command which identifies the user to the server.
"""
params = params.split(' ', 3)
if len(params) != 4:
raise IRCError.from_name(
'needmoreparams',
'USER :Not enough parameters')
... | [
"def",
"handle_user",
"(",
"self",
",",
"params",
")",
":",
"params",
"=",
"params",
".",
"split",
"(",
"' '",
",",
"3",
")",
"if",
"len",
"(",
"params",
")",
"!=",
"4",
":",
"raise",
"IRCError",
".",
"from_name",
"(",
"'needmoreparams'",
",",
"'USER... | 27.9375 | 13.8125 |
def _get_parser(self, env):
""" Creates base argument parser.
`env`
Runtime ``Environment`` instance.
* Raises ``HelpBanner`` exception when certain conditions apply.
Returns ``FocusArgumentParser`` object.
"""
version_str = 'focus vers... | [
"def",
"_get_parser",
"(",
"self",
",",
"env",
")",
":",
"version_str",
"=",
"'focus version '",
"+",
"__version__",
"usage_str",
"=",
"'focus [-h] [-v] [--no-color] <command> [<args>]'",
"# setup parser",
"parser",
"=",
"FocusArgParser",
"(",
"description",
"=",
"(",
... | 39 | 23.202899 |
def correlation_matrix(nums_with_uncert):
"""
Calculate the correlation matrix of uncertain variables, oriented by the
order of the inputs
Parameters
----------
nums_with_uncert : array-like
A list of variables that have an associated uncertainty
Returns
-------
cor... | [
"def",
"correlation_matrix",
"(",
"nums_with_uncert",
")",
":",
"ufuncs",
"=",
"list",
"(",
"map",
"(",
"to_uncertain_func",
",",
"nums_with_uncert",
")",
")",
"data",
"=",
"np",
".",
"vstack",
"(",
"[",
"ufunc",
".",
"_mcpts",
"for",
"ufunc",
"in",
"ufunc... | 27.533333 | 18.533333 |
def enabled(name='allprofiles'):
'''
Enable all the firewall profiles (Windows only)
Args:
profile (Optional[str]): The name of the profile to enable. Default is
``allprofiles``. Valid options are:
- allprofiles
- domainprofile
- privateprofile
... | [
"def",
"enabled",
"(",
"name",
"=",
"'allprofiles'",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"True",
",",
"'changes'",
":",
"{",
"}",
",",
"'comment'",
":",
"''",
"}",
"profile_map",
"=",
"{",
"'domainprofile'",
":",
"... | 29.162162 | 20.27027 |
def parse_directives(lexer: Lexer, is_const: bool) -> List[DirectiveNode]:
"""Directives[Const]: Directive[?Const]+"""
directives: List[DirectiveNode] = []
append = directives.append
while peek(lexer, TokenKind.AT):
append(parse_directive(lexer, is_const))
return directives | [
"def",
"parse_directives",
"(",
"lexer",
":",
"Lexer",
",",
"is_const",
":",
"bool",
")",
"->",
"List",
"[",
"DirectiveNode",
"]",
":",
"directives",
":",
"List",
"[",
"DirectiveNode",
"]",
"=",
"[",
"]",
"append",
"=",
"directives",
".",
"append",
"whil... | 42.285714 | 10.714286 |
def rows_from_csv(filename, predicate=None, encoding='utf-8'):
"""\
Returns an iterator over all rows in the provided CSV `filename`.
`filename`
Absolute path to a file to read the cables from.
The file must be a CSV file with the following columns:
<identifier>, <creation-date>, <r... | [
"def",
"rows_from_csv",
"(",
"filename",
",",
"predicate",
"=",
"None",
",",
"encoding",
"=",
"'utf-8'",
")",
":",
"pred",
"=",
"predicate",
"or",
"bool",
"with",
"open",
"(",
"filename",
",",
"'rb'",
")",
"as",
"f",
":",
"for",
"row",
"in",
"_UnicodeR... | 55.625 | 29.5 |
def consume_asset(event, agreement_id, did, service_agreement, consumer_account, consume_callback):
"""
Consumption of an asset after get the event call.
:param event: AttributeDict with the event data.
:param agreement_id: id of the agreement, hex str
:param did: DID, str
:param service_agreem... | [
"def",
"consume_asset",
"(",
"event",
",",
"agreement_id",
",",
"did",
",",
"service_agreement",
",",
"consumer_account",
",",
"consume_callback",
")",
":",
"logger",
".",
"debug",
"(",
"f\"consuming asset after event {event}.\"",
")",
"if",
"consume_callback",
":",
... | 37.714286 | 19 |
def _store_compressed_sequence_to_node(self, node):
"""
make a compressed representation of a pair of sequences only counting
the number of times a particular pair of states (e.g. (A,T)) is observed
the the aligned sequences of parent and child.
Parameters
-----------
... | [
"def",
"_store_compressed_sequence_to_node",
"(",
"self",
",",
"node",
")",
":",
"seq_pairs",
",",
"multiplicity",
"=",
"self",
".",
"gtr",
".",
"compress_sequence_pair",
"(",
"node",
".",
"up",
".",
"cseq",
",",
"node",
".",
"cseq",
",",
"pattern_multiplicity... | 46.5 | 26.6 |
def coords_from_query(query):
"""Transform a query line into a (lng, lat) pair of coordinates."""
try:
coords = json.loads(query)
except ValueError:
query = query.replace(',', ' ')
vals = query.split()
coords = [float(v) for v in vals]
return tuple(coords[:2]) | [
"def",
"coords_from_query",
"(",
"query",
")",
":",
"try",
":",
"coords",
"=",
"json",
".",
"loads",
"(",
"query",
")",
"except",
"ValueError",
":",
"query",
"=",
"query",
".",
"replace",
"(",
"','",
",",
"' '",
")",
"vals",
"=",
"query",
".",
"split... | 33.333333 | 10.333333 |
def _remove_hidden_parts(projected_surface):
"""Removes parts of a projected surface that are not visible.
Args:
projected_surface (surface): the surface to use
Returns:
surface: A projected surface.
"""
surface = np.copy(projected_surface)
surface[~_make_occlusion_mask(project... | [
"def",
"_remove_hidden_parts",
"(",
"projected_surface",
")",
":",
"surface",
"=",
"np",
".",
"copy",
"(",
"projected_surface",
")",
"surface",
"[",
"~",
"_make_occlusion_mask",
"(",
"projected_surface",
")",
"]",
"=",
"np",
".",
"nan",
"return",
"surface"
] | 29.083333 | 17.083333 |
def main():
'''Calculate the depth of a liquid in centimeters using a HCSR04 sensor
and a Raspberry Pi'''
trig_pin = 17
echo_pin = 27
# Default values
# unit = 'metric'
# temperature = 20
# round_to = 1
hole_depth = 80 # centimeters
# Create a distance reading with the hc... | [
"def",
"main",
"(",
")",
":",
"trig_pin",
"=",
"17",
"echo_pin",
"=",
"27",
"# Default values",
"# unit = 'metric'",
"# temperature = 20",
"# round_to = 1",
"hole_depth",
"=",
"80",
"# centimeters",
"# Create a distance reading with the hcsr04 sensor module",
"value",
"=",
... | 29.030303 | 21.151515 |
def flag(name=None):
"""
Creates the grammar for a Flag (F) field, accepting only 'Y', 'N' or 'U'.
:param name: name for the field
:return: grammar for the flag field
"""
if name is None:
name = 'Flag Field'
# Basic field
field = pp.Regex('[YNU]')
# Name
field.setName... | [
"def",
"flag",
"(",
"name",
"=",
"None",
")",
":",
"if",
"name",
"is",
"None",
":",
"name",
"=",
"'Flag Field'",
"# Basic field",
"field",
"=",
"pp",
".",
"Regex",
"(",
"'[YNU]'",
")",
"# Name",
"field",
".",
"setName",
"(",
"name",
")",
"field",
"."... | 17.7 | 22.7 |
def clear(self, username, project):
"""Clear the cache for given project."""
method = 'DELETE'
url = ('/project/{username}/{project}/build-cache?'
'circle-token={token}'.format(username=username,
project=project,
... | [
"def",
"clear",
"(",
"self",
",",
"username",
",",
"project",
")",
":",
"method",
"=",
"'DELETE'",
"url",
"=",
"(",
"'/project/{username}/{project}/build-cache?'",
"'circle-token={token}'",
".",
"format",
"(",
"username",
"=",
"username",
",",
"project",
"=",
"p... | 49 | 16.111111 |
def get(self, community_id):
"""Get the details of the specified community.
.. http:get:: /communities/(string:id)
Returns a JSON dictionary with the details of the specified
community.
**Request**:
.. sourcecode:: http
GET /communities/co... | [
"def",
"get",
"(",
"self",
",",
"community_id",
")",
":",
"community",
"=",
"Community",
".",
"get",
"(",
"community_id",
")",
"if",
"not",
"community",
":",
"abort",
"(",
"404",
")",
"etag",
"=",
"community",
".",
"version_id",
"self",
".",
"check_etag"... | 36.209302 | 12.046512 |
def get_schema_input_version(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
get_schema = ET.Element("get_schema")
config = get_schema
input = ET.SubElement(get_schema, "input")
version = ET.SubElement(input, "version")
version.te... | [
"def",
"get_schema_input_version",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"get_schema",
"=",
"ET",
".",
"Element",
"(",
"\"get_schema\"",
")",
"config",
"=",
"get_schema",
"input",
"=",
... | 35.5 | 9.583333 |
def get_all(symbol):
"""
Get all available quote data for the given ticker symbol.
Returns a dictionary.
"""
ids = \
'ydb2r1b3qpoc1d1cd2c6t1k2p2c8m5c3m6gm7hm8k1m3lm4l1t8w1g1w4g3p' \
'1g4mg5m2g6kvjj1j5j3k4f6j6nk5n4ws1xj2va5b6k3t7a2t615l2el3e7v1' \
'e8v7e9s6b4j4p5p6rr2r5r6r7s7... | [
"def",
"get_all",
"(",
"symbol",
")",
":",
"ids",
"=",
"'ydb2r1b3qpoc1d1cd2c6t1k2p2c8m5c3m6gm7hm8k1m3lm4l1t8w1g1w4g3p'",
"'1g4mg5m2g6kvjj1j5j3k4f6j6nk5n4ws1xj2va5b6k3t7a2t615l2el3e7v1'",
"'e8v7e9s6b4j4p5p6rr2r5r6r7s7'",
"values",
"=",
"_request",
"(",
"symbol",
",",
"ids",
")",
... | 34.468085 | 8.914894 |
def is_closed(self) -> Optional[bool]:
"""For Magnet Sensor; True if Closed, False if Open."""
if self._device_type is not None and self._device_type == DeviceType.DoorMagnet:
return bool(self._current_status & 0x01)
return None | [
"def",
"is_closed",
"(",
"self",
")",
"->",
"Optional",
"[",
"bool",
"]",
":",
"if",
"self",
".",
"_device_type",
"is",
"not",
"None",
"and",
"self",
".",
"_device_type",
"==",
"DeviceType",
".",
"DoorMagnet",
":",
"return",
"bool",
"(",
"self",
".",
"... | 52 | 16.6 |
def _create_skeleton_3(pc, l, num_section):
"""
Bottom level: {"measurement": [], "model": [{summary, distributions, ensemble}]}
Fill in measurement and model tables with N number of EMPTY meas, summary, ensemble, and distributions.
:param str pc: Paleo or Chron "mode"
:param list l:
:param dict... | [
"def",
"_create_skeleton_3",
"(",
"pc",
",",
"l",
",",
"num_section",
")",
":",
"logger_excel",
".",
"info",
"(",
"\"enter create_skeleton_inner_2\"",
")",
"# Table Template: Model",
"template_model",
"=",
"{",
"\"summaryTable\"",
":",
"{",
"}",
",",
"\"ensembleTabl... | 43.636364 | 26.227273 |
def emg_tkeo(emg):
"""
Calculates the Teager–Kaiser Energy operator.
Parameters
----------
emg : array
raw EMG signal.
Returns
-------
tkeo : 1D array_like
signal processed by the Teager–Kaiser Energy operator.
Notes
-----
*Authors*
- Marcos Duarte
... | [
"def",
"emg_tkeo",
"(",
"emg",
")",
":",
"emg",
"=",
"np",
".",
"asarray",
"(",
"emg",
")",
"tkeo",
"=",
"np",
".",
"copy",
"(",
"emg",
")",
"# Teager–Kaiser Energy operator",
"tkeo",
"[",
"1",
":",
"-",
"1",
"]",
"=",
"emg",
"[",
"1",
":",
"-",
... | 17.375 | 25.625 |
def OnActivateCard(self, card):
"""Called when a card is activated by double-clicking
on the card or reader tree control or toolbar.
In this sample, we just connect to the card on the first activation."""
SimpleSCardAppEventObserver.OnActivateCard(self, card)
self.feedbacktext.Se... | [
"def",
"OnActivateCard",
"(",
"self",
",",
"card",
")",
":",
"SimpleSCardAppEventObserver",
".",
"OnActivateCard",
"(",
"self",
",",
"card",
")",
"self",
".",
"feedbacktext",
".",
"SetLabel",
"(",
"'Activated card: '",
"+",
"repr",
"(",
"card",
")",
")",
"se... | 55.714286 | 10.857143 |
def predict_topk(self, dataset, output_type="probability", k=3, batch_size=64):
"""
Return top-k predictions for the ``dataset``, using the trained model.
Predictions are returned as an SFrame with three columns: `id`,
`class`, and `probability`, `margin`, or `rank`, depending on the ``... | [
"def",
"predict_topk",
"(",
"self",
",",
"dataset",
",",
"output_type",
"=",
"\"probability\"",
",",
"k",
"=",
"3",
",",
"batch_size",
"=",
"64",
")",
":",
"if",
"not",
"isinstance",
"(",
"dataset",
",",
"(",
"_tc",
".",
"SFrame",
",",
"_tc",
".",
"S... | 40.875 | 21.75 |
def backup(host=None, core_name=None, append_core_to_path=False):
'''
Tell solr make a backup. This method can be mis-leading since it uses the
backup API. If an error happens during the backup you are not notified.
The status: 'OK' in the response simply means that solr received the
request succe... | [
"def",
"backup",
"(",
"host",
"=",
"None",
",",
"core_name",
"=",
"None",
",",
"append_core_to_path",
"=",
"False",
")",
":",
"path",
"=",
"__opts__",
"[",
"'solr.backup_path'",
"]",
"num_backups",
"=",
"__opts__",
"[",
"'solr.num_backups'",
"]",
"if",
"path... | 39.084746 | 20.983051 |
def plot_zed(ZED, datablock, angle, s, units):
"""
function to make equal area plot and zijderveld plot
Parameters
_________
ZED : dictionary with keys for plots
eqarea : figure number for equal area projection
zijd : figure number for zijderveld plot
demag : figure numb... | [
"def",
"plot_zed",
"(",
"ZED",
",",
"datablock",
",",
"angle",
",",
"s",
",",
"units",
")",
":",
"for",
"fignum",
"in",
"list",
"(",
"ZED",
".",
"keys",
"(",
")",
")",
":",
"fig",
"=",
"plt",
".",
"figure",
"(",
"num",
"=",
"ZED",
"[",
"fignum"... | 35.957746 | 18.43662 |
def _addSexSpecificity(self, subject_id, sex):
"""
Add sex specificity to a subject (eg association node)
In our modeling we use this to add a qualifier to a triple
for example, this genotype to phenotype association
is specific to this sex (see MGI, IMPC)
This expects ... | [
"def",
"_addSexSpecificity",
"(",
"self",
",",
"subject_id",
",",
"sex",
")",
":",
"self",
".",
"graph",
".",
"addTriple",
"(",
"subject_id",
",",
"self",
".",
"globaltt",
"[",
"'has_sex_specificty'",
"]",
",",
"sex",
")"
] | 36.333333 | 21.111111 |
def execute(self, *args, **kwargs):
"""
Initializes and runs the tool.
This is shorhand to parse command line arguments, then calling:
self.setup(parsed_arguments)
self.process()
"""
args = self.parser.parse_args(*args, **kwargs)
self.process(args... | [
"def",
"execute",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"args",
"=",
"self",
".",
"parser",
".",
"parse_args",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"process",
"(",
"args",
")"
] | 31.2 | 12 |
def array(source_array, ctx=None, dtype=None):
"""Creates an array from any object exposing the array interface.
Parameters
----------
source_array : array_like
An object exposing the array interface, an object whose `__array__`
method returns an array, or any (nested) sequence.
ctx... | [
"def",
"array",
"(",
"source_array",
",",
"ctx",
"=",
"None",
",",
"dtype",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"source_array",
",",
"NDArray",
")",
":",
"dtype",
"=",
"source_array",
".",
"dtype",
"if",
"dtype",
"is",
"None",
"else",
"dtyp... | 37.677419 | 21.032258 |
def great_circle_dist(lat1, lon1, lat2, lon2):
"""
Get the distance (in meters) between two lat/lon points
via the Haversine formula.
Parameters
----------
lat1, lon1, lat2, lon2 : float
Latitude and longitude in degrees.
Returns
-------
dist : float
Distance in met... | [
"def",
"great_circle_dist",
"(",
"lat1",
",",
"lon1",
",",
"lat2",
",",
"lon2",
")",
":",
"radius",
"=",
"6372795",
"# meters",
"lat1",
"=",
"math",
".",
"radians",
"(",
"lat1",
")",
"lon1",
"=",
"math",
".",
"radians",
"(",
"lon1",
")",
"lat2",
"=",... | 23.424242 | 20.757576 |
def analytical(src, rec, res, freqtime, solution='fs', signal=None, ab=11,
aniso=None, epermH=None, epermV=None, mpermH=None, mpermV=None,
verb=2):
r"""Return the analytical full- or half-space solution.
Calculate the electromagnetic frequency- or time-domain field due to
infi... | [
"def",
"analytical",
"(",
"src",
",",
"rec",
",",
"res",
",",
"freqtime",
",",
"solution",
"=",
"'fs'",
",",
"signal",
"=",
"None",
",",
"ab",
"=",
"11",
",",
"aniso",
"=",
"None",
",",
"epermH",
"=",
"None",
",",
"epermV",
"=",
"None",
",",
"mpe... | 42.617117 | 25.040541 |
def on_close_shortcut(self, *args):
"""Close selected state machine (triggered by shortcut)"""
state_machine_m = self.model.get_selected_state_machine_model()
if state_machine_m is None:
return
self.on_close_clicked(None, state_machine_m, None, force=False) | [
"def",
"on_close_shortcut",
"(",
"self",
",",
"*",
"args",
")",
":",
"state_machine_m",
"=",
"self",
".",
"model",
".",
"get_selected_state_machine_model",
"(",
")",
"if",
"state_machine_m",
"is",
"None",
":",
"return",
"self",
".",
"on_close_clicked",
"(",
"N... | 49.333333 | 15.666667 |
def update_picks(self, games=None, points=None):
'''
games can be dict of {game.id: winner_id} for all picked games to update
'''
if games:
game_dict = {g.id: g for g in self.gameset.games.filter(id__in=games)}
game_picks = {pick.game.id: pick for pick in self.gam... | [
"def",
"update_picks",
"(",
"self",
",",
"games",
"=",
"None",
",",
"points",
"=",
"None",
")",
":",
"if",
"games",
":",
"game_dict",
"=",
"{",
"g",
".",
"id",
":",
"g",
"for",
"g",
"in",
"self",
".",
"gameset",
".",
"games",
".",
"filter",
"(",
... | 39.4 | 21.5 |
def find_common(self, l):
"""
Find common parts in thelist items ex: 'ab' for ['abcd','abce','abf']
requires an ordered list
"""
if len(l) == 1:
return l[0]
init = l[0]
for item in l[1:]:
for i, (x, y) in enumerate(zip(init, item)):
... | [
"def",
"find_common",
"(",
"self",
",",
"l",
")",
":",
"if",
"len",
"(",
"l",
")",
"==",
"1",
":",
"return",
"l",
"[",
"0",
"]",
"init",
"=",
"l",
"[",
"0",
"]",
"for",
"item",
"in",
"l",
"[",
"1",
":",
"]",
":",
"for",
"i",
",",
"(",
"... | 26 | 17.111111 |
def remove_constraint(self, name):
"""Remove a constraint from the problem"""
index = self._get_constraint_index(name)
# Remove from matrix
self._A = np.delete(self.A, index, 0)
# Remove from upper_bounds
self.upper_bounds = np.delete(self.upper_bounds, index)
# R... | [
"def",
"remove_constraint",
"(",
"self",
",",
"name",
")",
":",
"index",
"=",
"self",
".",
"_get_constraint_index",
"(",
"name",
")",
"# Remove from matrix",
"self",
".",
"_A",
"=",
"np",
".",
"delete",
"(",
"self",
".",
"A",
",",
"index",
",",
"0",
")... | 40.454545 | 7.181818 |
def child_task(self):
'''child process - this holds all the GUI elements'''
mp_util.child_close_fds()
import matplotlib
import wx_processguard
from wx_loader import wx
from live_graph_ui import GraphFrame
matplotlib.use('WXAgg')
app = wx.App(Fals... | [
"def",
"child_task",
"(",
"self",
")",
":",
"mp_util",
".",
"child_close_fds",
"(",
")",
"import",
"matplotlib",
"import",
"wx_processguard",
"from",
"wx_loader",
"import",
"wx",
"from",
"live_graph_ui",
"import",
"GraphFrame",
"matplotlib",
".",
"use",
"(",
"'W... | 28.571429 | 15.285714 |
def mode_date(self, rows: List[Row], column: DateColumn) -> Date:
"""
Takes a list of rows and a column and returns the most frequent value under
that column in those rows.
"""
most_frequent_list = self._get_most_frequent_values(rows, column)
if not most_frequent_list:
... | [
"def",
"mode_date",
"(",
"self",
",",
"rows",
":",
"List",
"[",
"Row",
"]",
",",
"column",
":",
"DateColumn",
")",
"->",
"Date",
":",
"most_frequent_list",
"=",
"self",
".",
"_get_most_frequent_values",
"(",
"rows",
",",
"column",
")",
"if",
"not",
"most... | 47.583333 | 16.25 |
def run_jar(jar_name, more_args=None, properties=None, hadoop_conf_dir=None,
keep_streams=True):
"""
Run a jar on Hadoop (``hadoop jar`` command).
All arguments are passed to :func:`run_cmd` (``args = [jar_name] +
more_args``) .
"""
if hu.is_readable(jar_name):
args = [jar_n... | [
"def",
"run_jar",
"(",
"jar_name",
",",
"more_args",
"=",
"None",
",",
"properties",
"=",
"None",
",",
"hadoop_conf_dir",
"=",
"None",
",",
"keep_streams",
"=",
"True",
")",
":",
"if",
"hu",
".",
"is_readable",
"(",
"jar_name",
")",
":",
"args",
"=",
"... | 32.777778 | 17.444444 |
def _retrieve_certificate(self, access_token, timeout=3):
"""
Generates a new private key and certificate request, submits the request to be
signed by the SLCS CA and returns the certificate.
"""
logger.debug("Retrieve certificate with token.")
# Generate a new key pair
... | [
"def",
"_retrieve_certificate",
"(",
"self",
",",
"access_token",
",",
"timeout",
"=",
"3",
")",
":",
"logger",
".",
"debug",
"(",
"\"Retrieve certificate with token.\"",
")",
"# Generate a new key pair",
"key_pair",
"=",
"crypto",
".",
"PKey",
"(",
")",
"key_pair... | 37.045455 | 20.909091 |
def itemgetter(k, ellipsis=False, key=None):
"""
Looks up ``k`` as an index of the column's value.
If ``k`` is a ``slice`` type object, then ``ellipsis`` can be given as a string to use to
indicate truncation. Alternatively, ``ellipsis`` can be set to ``True`` to use a default
``'...'``.
If a... | [
"def",
"itemgetter",
"(",
"k",
",",
"ellipsis",
"=",
"False",
",",
"key",
"=",
"None",
")",
":",
"def",
"helper",
"(",
"instance",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"default_value",
"=",
"kwargs",
".",
"get",
"(",
"'default_value'"... | 37.736842 | 24.315789 |
def _ParseRecordLogline(self, parser_mediator, structure):
"""Parses a logline record structure and produces events.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
structure (pyparsing.ParseResults): structure... | [
"def",
"_ParseRecordLogline",
"(",
"self",
",",
"parser_mediator",
",",
"structure",
")",
":",
"date_time",
"=",
"dfdatetime_time_elements",
".",
"TimeElementsInMilliseconds",
"(",
")",
"try",
":",
"datetime_iso8601",
"=",
"self",
".",
"_GetISO8601String",
"(",
"str... | 40.064516 | 21.290323 |
def get_response_code(url, timeout=10):
'''
Visit the URL and return the HTTP response code in 'int'
'''
try:
req = urllib2.urlopen(url, timeout=timeout)
except HTTPError, e:
return e.getcode()
except Exception, _:
fail("Couldn't reach the URL '%s'" % url)
else:
... | [
"def",
"get_response_code",
"(",
"url",
",",
"timeout",
"=",
"10",
")",
":",
"try",
":",
"req",
"=",
"urllib2",
".",
"urlopen",
"(",
"url",
",",
"timeout",
"=",
"timeout",
")",
"except",
"HTTPError",
",",
"e",
":",
"return",
"e",
".",
"getcode",
"(",... | 28 | 18.666667 |
def is_question_answered(self, question_id):
"""has the question matching item_id been answered and not skipped"""
question_map = self._get_question_map(question_id) # will raise NotFound()
if 'missingResponse' in question_map['responses'][0]:
return False
else:
... | [
"def",
"is_question_answered",
"(",
"self",
",",
"question_id",
")",
":",
"question_map",
"=",
"self",
".",
"_get_question_map",
"(",
"question_id",
")",
"# will raise NotFound()",
"if",
"'missingResponse'",
"in",
"question_map",
"[",
"'responses'",
"]",
"[",
"0",
... | 46.428571 | 18.285714 |
def _run_program(self, bin, fastafile, params=None):
"""
Run Trawler and predict motifs from a FASTA file.
Parameters
----------
bin : str
Command used to run the tool.
fastafile : str
Name of the FASTA input file.
params : dict,... | [
"def",
"_run_program",
"(",
"self",
",",
"bin",
",",
"fastafile",
",",
"params",
"=",
"None",
")",
":",
"params",
"=",
"self",
".",
"_parse_params",
"(",
"params",
")",
"tmp",
"=",
"NamedTemporaryFile",
"(",
"mode",
"=",
"\"w\"",
",",
"dir",
"=",
"self... | 31.518987 | 17.037975 |
def add_field(self, name: str, value: str, inline: bool = True) -> None:
"""
Adds an embed field.
Parameters
----------
name: str
Name attribute of the embed field.
value: str
Value attribute of the embed field.
inline: bool
... | [
"def",
"add_field",
"(",
"self",
",",
"name",
":",
"str",
",",
"value",
":",
"str",
",",
"inline",
":",
"bool",
"=",
"True",
")",
"->",
"None",
":",
"field",
"=",
"{",
"'name'",
":",
"name",
",",
"'value'",
":",
"value",
",",
"'inline'",
":",
"in... | 23.347826 | 19.26087 |
def verify_item_signature(signature_attribute, encrypted_item, verification_key, crypto_config):
# type: (dynamodb_types.BINARY_ATTRIBUTE, dynamodb_types.ITEM, DelegatedKey, CryptoConfig) -> None
"""Verify the item signature.
:param dict signature_attribute: Item signature DynamoDB attribute value
:par... | [
"def",
"verify_item_signature",
"(",
"signature_attribute",
",",
"encrypted_item",
",",
"verification_key",
",",
"crypto_config",
")",
":",
"# type: (dynamodb_types.BINARY_ATTRIBUTE, dynamodb_types.ITEM, DelegatedKey, CryptoConfig) -> None",
"signature",
"=",
"signature_attribute",
"... | 46.789474 | 24.473684 |
def getComponentExceptionSummary(self, tmaster, component_name, instances=[], callback=None):
"""
Get the summary of exceptions for component_name and list of instances.
Empty instance list will fetch all exceptions.
"""
if not tmaster or not tmaster.host or not tmaster.stats_port:
return
... | [
"def",
"getComponentExceptionSummary",
"(",
"self",
",",
"tmaster",
",",
"component_name",
",",
"instances",
"=",
"[",
"]",
",",
"callback",
"=",
"None",
")",
":",
"if",
"not",
"tmaster",
"or",
"not",
"tmaster",
".",
"host",
"or",
"not",
"tmaster",
".",
... | 40.381818 | 18.127273 |
def colorize(self, col, row, value=None):
'Returns curses attribute for the given col/row/value'
# colorstack = tuple(c.coloropt for c in self.getColorizers() if wrapply(c.func, self, col, row, value))
colorstack = []
for colorizer in self.getColorizers():
try:
... | [
"def",
"colorize",
"(",
"self",
",",
"col",
",",
"row",
",",
"value",
"=",
"None",
")",
":",
"# colorstack = tuple(c.coloropt for c in self.getColorizers() if wrapply(c.func, self, col, row, value))",
"colorstack",
"=",
"[",
"]",
"for",
"colorizer",
"in",
"self",
... | 39.066667 | 24.666667 |
def to_mef(data, channels, sc_list, sc_channels = None):
"""
Transform flow cytometry data using a standard curve function.
This function accepts a list of standard curves (`sc_list`) and a list
of channels to which those standard curves should be applied
(`sc_channels`). `to_mef` automatically che... | [
"def",
"to_mef",
"(",
"data",
",",
"channels",
",",
"sc_list",
",",
"sc_channels",
"=",
"None",
")",
":",
"# Default sc_channels",
"if",
"sc_channels",
"is",
"None",
":",
"if",
"data",
".",
"ndim",
"==",
"1",
":",
"sc_channels",
"=",
"range",
"(",
"data"... | 35.393258 | 19.707865 |
def _remove(self, telegram):
"""
Remove telegram from buffer and incomplete data preceding it. This
is easier than validating the data before adding it to the buffer.
:param str telegram:
:return:
"""
# Remove data leading up to the telegram and the telegram itsel... | [
"def",
"_remove",
"(",
"self",
",",
"telegram",
")",
":",
"# Remove data leading up to the telegram and the telegram itself.",
"index",
"=",
"self",
".",
"_buffer",
".",
"index",
"(",
"telegram",
")",
"+",
"len",
"(",
"telegram",
")",
"self",
".",
"_buffer",
"="... | 38 | 19.272727 |
def inline(self) -> str:
"""
Return inline string format of the instance
:return:
"""
return "{0}:{1}".format(self.index, ' '.join([str(p) for p in self.parameters])) | [
"def",
"inline",
"(",
"self",
")",
"->",
"str",
":",
"return",
"\"{0}:{1}\"",
".",
"format",
"(",
"self",
".",
"index",
",",
"' '",
".",
"join",
"(",
"[",
"str",
"(",
"p",
")",
"for",
"p",
"in",
"self",
".",
"parameters",
"]",
")",
")"
] | 28.714286 | 19.857143 |
def dump_config(self):
"""Pretty print the configuration dict to stdout."""
yaml_content = self.get_merged_config()
print('YAML Configuration\n%s\n' % yaml_content.read())
try:
self.load()
print('Python Configuration\n%s\n' % pretty(self.yamldocs))
except ... | [
"def",
"dump_config",
"(",
"self",
")",
":",
"yaml_content",
"=",
"self",
".",
"get_merged_config",
"(",
")",
"print",
"(",
"'YAML Configuration\\n%s\\n'",
"%",
"yaml_content",
".",
"read",
"(",
")",
")",
"try",
":",
"self",
".",
"load",
"(",
")",
"print",... | 40.636364 | 18.818182 |
def to_special_value(self, value):
"""Checks if value is a special SPDX value such as
NONE, NOASSERTION or UNKNOWN if so returns proper model.
else returns value"""
if value == self.spdx_namespace.none:
return utils.SPDXNone()
elif value == self.spdx_namespace.noasser... | [
"def",
"to_special_value",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"==",
"self",
".",
"spdx_namespace",
".",
"none",
":",
"return",
"utils",
".",
"SPDXNone",
"(",
")",
"elif",
"value",
"==",
"self",
".",
"spdx_namespace",
".",
"noassertion",
... | 39.583333 | 9.833333 |
def make_ccys(db):
'''
Create the currency dictionary
'''
dfr = 4
dollar = r'\u0024'
peso = r'\u20b1'
kr = r'kr'
insert = db.insert
# G10 & SCANDI
insert('EUR', '978', 'EU', 1,
'Euro', dfr, 'EU', '30/360', 'ACT/360',
future='FE', symbol=r'\u20ac', html='&#x... | [
"def",
"make_ccys",
"(",
"db",
")",
":",
"dfr",
"=",
"4",
"dollar",
"=",
"r'\\u0024'",
"peso",
"=",
"r'\\u20b1'",
"kr",
"=",
"r'kr'",
"insert",
"=",
"db",
".",
"insert",
"# G10 & SCANDI",
"insert",
"(",
"'EUR'",
",",
"'978'",
",",
"'EU'",
",",
"1",
"... | 39.958333 | 11.446429 |
def catalogue_mt_filter(self, mt_table, flag=None):
"""
Filter the catalogue using a magnitude-time table. The table has
two columns and n-rows.
:param nump.ndarray mt_table:
Magnitude time table with n-rows where column 1 is year and column
2 is magnitude
... | [
"def",
"catalogue_mt_filter",
"(",
"self",
",",
"mt_table",
",",
"flag",
"=",
"None",
")",
":",
"if",
"flag",
"is",
"None",
":",
"# No flag defined, therefore all events are initially valid",
"flag",
"=",
"np",
".",
"ones",
"(",
"self",
".",
"get_number_events",
... | 36.904762 | 19.857143 |
def _get_id_from_username(self, username):
"""Looks up a username's id
:param string username: Username to lookup
:returns: The id that matches username.
"""
_mask = "mask[id, username]"
_filter = {'users': {'username': utils.query_filter(username)}}
user = self.... | [
"def",
"_get_id_from_username",
"(",
"self",
",",
"username",
")",
":",
"_mask",
"=",
"\"mask[id, username]\"",
"_filter",
"=",
"{",
"'users'",
":",
"{",
"'username'",
":",
"utils",
".",
"query_filter",
"(",
"username",
")",
"}",
"}",
"user",
"=",
"self",
... | 41.4 | 17.533333 |
def hide_arp_holder_arp_entry_interfacetype_Port_channel_Port_channel(self, **kwargs):
"""Auto Generated Code
"""
config = ET.Element("config")
hide_arp_holder = ET.SubElement(config, "hide-arp-holder", xmlns="urn:brocade.com:mgmt:brocade-arp")
arp_entry = ET.SubElement(hide_arp_... | [
"def",
"hide_arp_holder_arp_entry_interfacetype_Port_channel_Port_channel",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"ET",
".",
"Element",
"(",
"\"config\"",
")",
"hide_arp_holder",
"=",
"ET",
".",
"SubElement",
"(",
"config",
",",
"\"hide-ar... | 53.866667 | 23.4 |
def _get_merged_params_string(self):
"""Returns the merged nextflow params string from a dictionary object.
The params dict should be a set of key:value pairs with the
parameter name, and the default parameter value::
self.params = {
"genomeSize": 2.1,
... | [
"def",
"_get_merged_params_string",
"(",
"self",
")",
":",
"params_temp",
"=",
"{",
"}",
"for",
"p",
"in",
"self",
".",
"processes",
":",
"logger",
".",
"debug",
"(",
"\"[{}] Adding parameters: {}\"",
".",
"format",
"(",
"p",
".",
"template",
",",
"p",
"."... | 30.3 | 24.825 |
def get_requirements_file_from_url(url):
"""fetches the requiremets from the url"""
response = requests.get(url)
if response.status_code == 200:
return StringIO(response.text)
else:
return StringIO("") | [
"def",
"get_requirements_file_from_url",
"(",
"url",
")",
":",
"response",
"=",
"requests",
".",
"get",
"(",
"url",
")",
"if",
"response",
".",
"status_code",
"==",
"200",
":",
"return",
"StringIO",
"(",
"response",
".",
"text",
")",
"else",
":",
"return",... | 28.375 | 12.375 |
def merge_featurecollection(*jsons):
"""
merge features into one featurecollection
Keyword arguments:
jsons -- jsons object list
return geojson featurecollection
"""
features = []
for json in jsons:
if json['type'] == 'FeatureCollection':
for feature in json['fea... | [
"def",
"merge_featurecollection",
"(",
"*",
"jsons",
")",
":",
"features",
"=",
"[",
"]",
"for",
"json",
"in",
"jsons",
":",
"if",
"json",
"[",
"'type'",
"]",
"==",
"'FeatureCollection'",
":",
"for",
"feature",
"in",
"json",
"[",
"'features'",
"]",
":",
... | 27.733333 | 12.666667 |
def _R2deriv(self,R,z,phi=0.,t=0.):
"""
NAME:
_Rderiv
PURPOSE:
evaluate the second radial derivative for this potential
INPUT:
R - Galactocentric cylindrical radius
z - vertical height
phi - azimuth
t - time
OUTPUT... | [
"def",
"_R2deriv",
"(",
"self",
",",
"R",
",",
"z",
",",
"phi",
"=",
"0.",
",",
"t",
"=",
"0.",
")",
":",
"r2",
"=",
"R",
"**",
"2.",
"+",
"z",
"**",
"2.",
"rb",
"=",
"nu",
".",
"sqrt",
"(",
"r2",
"+",
"self",
".",
"b2",
")",
"return",
... | 29.15 | 15.35 |
def probConn (self, preCellsTags, postCellsTags, connParam):
from .. import sim
''' Generates connections between all pre and post-syn cells based on probability values'''
if sim.cfg.verbose: print('Generating set of probabilistic connections (rule: %s) ...' % (connParam['label']))
allRands = self.gen... | [
"def",
"probConn",
"(",
"self",
",",
"preCellsTags",
",",
"postCellsTags",
",",
"connParam",
")",
":",
"from",
".",
".",
"import",
"sim",
"if",
"sim",
".",
"cfg",
".",
"verbose",
":",
"print",
"(",
"'Generating set of probabilistic connections (rule: %s) ...'",
... | 76.020408 | 51.44898 |
def set_schedule(self, schedule):
"""Takes the output from `auto` and sets the attributes
"""
self.Tmax = schedule['tmax']
self.Tmin = schedule['tmin']
self.steps = int(schedule['steps'])
self.updates = int(schedule['updates']) | [
"def",
"set_schedule",
"(",
"self",
",",
"schedule",
")",
":",
"self",
".",
"Tmax",
"=",
"schedule",
"[",
"'tmax'",
"]",
"self",
".",
"Tmin",
"=",
"schedule",
"[",
"'tmin'",
"]",
"self",
".",
"steps",
"=",
"int",
"(",
"schedule",
"[",
"'steps'",
"]",... | 38.428571 | 3.571429 |
def cumulative_statistics(self):
"""
Access the cumulative_statistics
:returns: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStatisticsList
:rtype: twilio.rest.taskrouter.v1.workspace.worker.workers_cumulative_statistics.WorkersCumulativeStat... | [
"def",
"cumulative_statistics",
"(",
"self",
")",
":",
"if",
"self",
".",
"_cumulative_statistics",
"is",
"None",
":",
"self",
".",
"_cumulative_statistics",
"=",
"WorkersCumulativeStatisticsList",
"(",
"self",
".",
"_version",
",",
"workspace_sid",
"=",
"self",
"... | 46.461538 | 24 |
def find_cards(self, source=None, **filters):
"""
Generate a card pool with all cards matching specified filters
"""
if not filters:
new_filters = self.filters.copy()
else:
new_filters = filters.copy()
for k, v in new_filters.items():
if isinstance(v, LazyValue):
new_filters[k] = v.evaluate(so... | [
"def",
"find_cards",
"(",
"self",
",",
"source",
"=",
"None",
",",
"*",
"*",
"filters",
")",
":",
"if",
"not",
"filters",
":",
"new_filters",
"=",
"self",
".",
"filters",
".",
"copy",
"(",
")",
"else",
":",
"new_filters",
"=",
"filters",
".",
"copy",... | 24.8 | 14.4 |
async def dist(self, mesg):
'''
Distribute an existing event tuple.
Args:
mesg ((str,dict)): An event tuple.
Example:
await base.dist( ('foo',{'bar':'baz'}) )
'''
if self.isfini:
return ()
ret = []
for func in self... | [
"async",
"def",
"dist",
"(",
"self",
",",
"mesg",
")",
":",
"if",
"self",
".",
"isfini",
":",
"return",
"(",
")",
"ret",
"=",
"[",
"]",
"for",
"func",
"in",
"self",
".",
"_syn_funcs",
".",
"get",
"(",
"mesg",
"[",
"0",
"]",
",",
"(",
")",
")"... | 25.088235 | 22.5 |
def track_field(field):
"""
Returns whether the given field should be tracked by Auditlog.
Untracked fields are many-to-many relations and relations to the Auditlog LogEntry model.
:param field: The field to check.
:type field: Field
:return: Whether the given field should be tracked.
:rty... | [
"def",
"track_field",
"(",
"field",
")",
":",
"from",
"auditlog",
".",
"models",
"import",
"LogEntry",
"# Do not track many to many relations",
"if",
"field",
".",
"many_to_many",
":",
"return",
"False",
"# Do not track relations to LogEntry",
"if",
"getattr",
"(",
"f... | 29.52 | 23.04 |
def mark(self, channel_name, ts):
""" https://api.slack.com/methods/channels.mark
"""
channel_id = self.get_channel_id(channel_name)
self.params.update({
'channel': channel_id,
'ts': ts,
})
return FromUrl('https://slack.com/api/channels.... | [
"def",
"mark",
"(",
"self",
",",
"channel_name",
",",
"ts",
")",
":",
"channel_id",
"=",
"self",
".",
"get_channel_id",
"(",
"channel_name",
")",
"self",
".",
"params",
".",
"update",
"(",
"{",
"'channel'",
":",
"channel_id",
",",
"'ts'",
":",
"ts",
",... | 39.888889 | 15.444444 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.