text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def create(dataset, symbol, degree):
"""
Create a model object from the data set for the property specified by
the supplied symbol, using the specified polynomial degree.
:param dataset: a DataSet object
:param symbol: the symbol of the property to be described, e.g. 'rho'
... | [
"def",
"create",
"(",
"dataset",
",",
"symbol",
",",
"degree",
")",
":",
"x_vals",
"=",
"dataset",
".",
"data",
"[",
"'T'",
"]",
".",
"tolist",
"(",
")",
"y_vals",
"=",
"dataset",
".",
"data",
"[",
"symbol",
"]",
".",
"tolist",
"(",
")",
"coeffs",
... | 38.961538 | 21.423077 |
def slugify(value, allow_unicode=False):
"""Normalizes string, converts to lowercase, removes non-alpha characters,
and converts spaces to hyphens.
:param value: string
:param allow_unicode: allow utf8 characters
:type allow_unicode: bool
:return: slugified string
:rtype: str
:Example:... | [
"def",
"slugify",
"(",
"value",
",",
"allow_unicode",
"=",
"False",
")",
":",
"value",
"=",
"str",
"(",
"value",
")",
"if",
"allow_unicode",
":",
"value",
"=",
"unicodedata",
".",
"normalize",
"(",
"'NFKC'",
",",
"value",
")",
"value",
"=",
"re",
".",
... | 33.791667 | 18.75 |
def _coords2vec(self, coords):
"""
Converts from sky coordinates to unit vectors. Before conversion to unit
vectors, the coordiantes are transformed to the coordinate system used
internally by the :obj:`UnstructuredDustMap`, which can be set during
initialization of the class.
... | [
"def",
"_coords2vec",
"(",
"self",
",",
"coords",
")",
":",
"# c = coords.transform_to(self._frame)",
"# vec = np.empty((c.shape[0], 2), dtype='f8')",
"# vec[:,0] = coordinates.Longitude(coords.l, wrap_angle=360.*units.deg).deg[:]",
"# vec[:,1] = coords.b.deg[:]",
"# return np.radians(vec)",... | 38.8125 | 21.875 |
def get_msi_token_webapp(resource):
"""Get a MSI token from inside a webapp or functions.
Env variable will look like:
- MSI_ENDPOINT = http://127.0.0.1:41741/MSI/token/
- MSI_SECRET = 69418689F1E342DD946CB82994CDA3CB
"""
try:
msi_endpoint = os.environ['MSI_ENDPOINT']
msi_secre... | [
"def",
"get_msi_token_webapp",
"(",
"resource",
")",
":",
"try",
":",
"msi_endpoint",
"=",
"os",
".",
"environ",
"[",
"'MSI_ENDPOINT'",
"]",
"msi_secret",
"=",
"os",
".",
"environ",
"[",
"'MSI_SECRET'",
"]",
"except",
"KeyError",
"as",
"err",
":",
"err_msg",... | 35.804878 | 20.439024 |
def get_formatter(name):
"""
Looks up a formatter class given a prefix to it.
The names are sorted, and the first matching class is returned.
"""
for k in sorted(_FORMATTERS):
if k.startswith(name):
return _FORMATTERS[k] | [
"def",
"get_formatter",
"(",
"name",
")",
":",
"for",
"k",
"in",
"sorted",
"(",
"_FORMATTERS",
")",
":",
"if",
"k",
".",
"startswith",
"(",
"name",
")",
":",
"return",
"_FORMATTERS",
"[",
"k",
"]"
] | 31.625 | 9.875 |
def GET(self, token=None, salt_token=None):
r'''
An HTTP stream of the Salt master event bus
This stream is formatted per the Server Sent Events (SSE) spec. Each
event is formatted as JSON.
.. http:get:: /events
:status 200: |200|
:status 401: |401|
... | [
"def",
"GET",
"(",
"self",
",",
"token",
"=",
"None",
",",
"salt_token",
"=",
"None",
")",
":",
"cookies",
"=",
"cherrypy",
".",
"request",
".",
"cookie",
"auth_token",
"=",
"token",
"or",
"salt_token",
"or",
"(",
"cookies",
"[",
"'session_id'",
"]",
"... | 42.225 | 29.1125 |
def read (self, stream):
"""Reads PCapPacketHeader data from the given stream."""
self._data = stream.read(self._size)
if len(self._data) >= self._size:
values = struct.unpack(self._swap + self._format, self._data)
else:
values = None, None, None, None
self.ts_sec =... | [
"def",
"read",
"(",
"self",
",",
"stream",
")",
":",
"self",
".",
"_data",
"=",
"stream",
".",
"read",
"(",
"self",
".",
"_size",
")",
"if",
"len",
"(",
"self",
".",
"_data",
")",
">=",
"self",
".",
"_size",
":",
"values",
"=",
"struct",
".",
"... | 31.846154 | 15.076923 |
def get_balances():
'''
Gets information about fund in the user's account. This method returns the
following information: Available Balance, Account Balance, Earned Amount,
Withdrawable Amount and Funds Required for AutoRenew.
.. note::
If a domain setup with automatic renewal is expiring w... | [
"def",
"get_balances",
"(",
")",
":",
"opts",
"=",
"salt",
".",
"utils",
".",
"namecheap",
".",
"get_opts",
"(",
"'namecheap.users.getBalances'",
")",
"response_xml",
"=",
"salt",
".",
"utils",
".",
"namecheap",
".",
"get_request",
"(",
"opts",
")",
"if",
... | 34.038462 | 30.115385 |
def join_summaries(summary_frames, selected_summaries, keep_old_header=False):
"""parse the summaries and combine based on column (selected_summaries)"""
selected_summaries_dict = create_selected_summaries_dict(selected_summaries)
frames = []
keys = []
for key in summary_frames:
keys.append... | [
"def",
"join_summaries",
"(",
"summary_frames",
",",
"selected_summaries",
",",
"keep_old_header",
"=",
"False",
")",
":",
"selected_summaries_dict",
"=",
"create_selected_summaries_dict",
"(",
"selected_summaries",
")",
"frames",
"=",
"[",
"]",
"keys",
"=",
"[",
"]... | 34.935484 | 20.483871 |
def createPartyFromName(apps, name):
'''
For creating/matching TransactionParty objects using names alone.
Look for staff members with the same name and match to them first if there is
exactly one match. Then, look for users and match them if there is exactly one
match. Otherwise, just generate a T... | [
"def",
"createPartyFromName",
"(",
"apps",
",",
"name",
")",
":",
"TransactionParty",
"=",
"apps",
".",
"get_model",
"(",
"'financial'",
",",
"'TransactionParty'",
")",
"StaffMember",
"=",
"apps",
".",
"get_model",
"(",
"'core'",
",",
"'StaffMember'",
")",
"Us... | 34.444444 | 21.688889 |
def _initialize_statevector(self):
"""Set the initial statevector for simulation"""
if self._initial_statevector is None:
# Set to default state of all qubits in |0>
self._statevector = np.zeros(2 ** self._number_of_qubits,
dtype=complex)
... | [
"def",
"_initialize_statevector",
"(",
"self",
")",
":",
"if",
"self",
".",
"_initial_statevector",
"is",
"None",
":",
"# Set to default state of all qubits in |0>",
"self",
".",
"_statevector",
"=",
"np",
".",
"zeros",
"(",
"2",
"**",
"self",
".",
"_number_of_qub... | 48.833333 | 14.666667 |
def _create_rule(path, rule):
# type: (List[Type[Rule]], Type[Rule]) -> Type[ReducedUnitRule]
"""
Create ReducedUnitRule based on sequence of unit rules and end, generating rule.
:param path: Sequence of unit rules.
:param rule: Rule that is attached after sequence of unit rules.
:return: Reduce... | [
"def",
"_create_rule",
"(",
"path",
",",
"rule",
")",
":",
"# type: (List[Type[Rule]], Type[Rule]) -> Type[ReducedUnitRule]",
"created",
"=",
"type",
"(",
"'Reduced['",
"+",
"rule",
".",
"__name__",
"+",
"']'",
",",
"(",
"ReducedUnitRule",
",",
")",
",",
"ReducedU... | 42.266667 | 15.466667 |
def keypress(self, size, key):
"""Handle marking messages as read and keeping client active."""
# Set the client as active.
self._coroutine_queue.put(self._client.set_active())
# Mark the newest event as read.
self._coroutine_queue.put(self._conversation.update_read_timestamp())... | [
"def",
"keypress",
"(",
"self",
",",
"size",
",",
"key",
")",
":",
"# Set the client as active.",
"self",
".",
"_coroutine_queue",
".",
"put",
"(",
"self",
".",
"_client",
".",
"set_active",
"(",
")",
")",
"# Mark the newest event as read.",
"self",
".",
"_cor... | 39.555556 | 17.111111 |
def _update_params(self, constants):
"""Update params and return new influence."""
for k, v in constants.items():
self.params[k]['value'] *= v
influence = self._calculate_influence(self.params['infl']['value'])
return influence * self.params['lr']['value'] | [
"def",
"_update_params",
"(",
"self",
",",
"constants",
")",
":",
"for",
"k",
",",
"v",
"in",
"constants",
".",
"items",
"(",
")",
":",
"self",
".",
"params",
"[",
"k",
"]",
"[",
"'value'",
"]",
"*=",
"v",
"influence",
"=",
"self",
".",
"_calculate... | 42.142857 | 13.428571 |
def put(self, items, panic=True):
"""
Load a single row into the target table.
:param list items: A list of values in the row corresponding to the
fields specified by :code:`self.columns`
:param bool panic: If :code:`True`, when an error is encountered it will be
... | [
"def",
"put",
"(",
"self",
",",
"items",
",",
"panic",
"=",
"True",
")",
":",
"if",
"not",
"self",
".",
"initiated",
":",
"self",
".",
"_initiate",
"(",
")",
"try",
":",
"row_status",
"=",
"self",
".",
"mload",
".",
"put_row",
"(",
"self",
".",
"... | 43.64 | 18.76 |
def CreateConfigHBuilder(env):
"""Called if necessary just before the building targets phase begins."""
action = SCons.Action.Action(_createConfigH,
_stringConfigH)
sconfigHBld = SCons.Builder.Builder(action=action)
env.Append( BUILDERS={'SConfigHBuilder':sconfigHBld} )
... | [
"def",
"CreateConfigHBuilder",
"(",
"env",
")",
":",
"action",
"=",
"SCons",
".",
"Action",
".",
"Action",
"(",
"_createConfigH",
",",
"_stringConfigH",
")",
"sconfigHBld",
"=",
"SCons",
".",
"Builder",
".",
"Builder",
"(",
"action",
"=",
"action",
")",
"e... | 51.625 | 9.625 |
def verify_link_in_task_graph(chain, decision_link, task_link):
"""Compare the runtime task definition against the decision task graph.
Args:
chain (ChainOfTrust): the chain we're operating on.
decision_link (LinkOfTrust): the decision task link
task_link (LinkOfTrust): the task link we... | [
"def",
"verify_link_in_task_graph",
"(",
"chain",
",",
"decision_link",
",",
"task_link",
")",
":",
"log",
".",
"info",
"(",
"\"Verifying the {} {} task definition is part of the {} {} task graph...\"",
".",
"format",
"(",
"task_link",
".",
"name",
",",
"task_link",
"."... | 43.565217 | 28.173913 |
def append(self, text):
"""Append line to the end
"""
cursor = QTextCursor(self._doc)
cursor.movePosition(QTextCursor.End)
cursor.insertBlock()
cursor.insertText(text) | [
"def",
"append",
"(",
"self",
",",
"text",
")",
":",
"cursor",
"=",
"QTextCursor",
"(",
"self",
".",
"_doc",
")",
"cursor",
".",
"movePosition",
"(",
"QTextCursor",
".",
"End",
")",
"cursor",
".",
"insertBlock",
"(",
")",
"cursor",
".",
"insertText",
"... | 29.857143 | 6.142857 |
def tween(self, t):
"""
t is number between 0 and 1 to indicate how far the tween has progressed
"""
if t is None:
return None
if self.method in self.method_to_tween:
return self.method_to_tween[self.method](t)
elif self.method in self.method_1par... | [
"def",
"tween",
"(",
"self",
",",
"t",
")",
":",
"if",
"t",
"is",
"None",
":",
"return",
"None",
"if",
"self",
".",
"method",
"in",
"self",
".",
"method_to_tween",
":",
"return",
"self",
".",
"method_to_tween",
"[",
"self",
".",
"method",
"]",
"(",
... | 39.866667 | 20.266667 |
def RfiltersBM(dataset,database,host=rbiomart_host):
"""
Lists BioMart filters through a RPY2 connection.
:param dataset: a dataset listed in RdatasetsBM()
:param database: a database listed in RdatabasesBM()
:param host: address of the host server, default='www.ensembl.org'
:returns: nothing
... | [
"def",
"RfiltersBM",
"(",
"dataset",
",",
"database",
",",
"host",
"=",
"rbiomart_host",
")",
":",
"biomaRt",
"=",
"importr",
"(",
"\"biomaRt\"",
")",
"ensemblMart",
"=",
"biomaRt",
".",
"useMart",
"(",
"database",
",",
"host",
"=",
"host",
")",
"ensembl",... | 33.2 | 17.333333 |
def refresh(self, module=None):
"""Recompute the salience values of the Activations on the Agenda
and then reorder the agenda.
The Python equivalent of the CLIPS refresh-agenda command.
If no Module is specified, the current one is used.
"""
module = module._mdl if modu... | [
"def",
"refresh",
"(",
"self",
",",
"module",
"=",
"None",
")",
":",
"module",
"=",
"module",
".",
"_mdl",
"if",
"module",
"is",
"not",
"None",
"else",
"ffi",
".",
"NULL",
"lib",
".",
"EnvRefreshAgenda",
"(",
"self",
".",
"_env",
",",
"module",
")"
] | 35.181818 | 19 |
def put_object(self,
mpath,
content=None,
path=None,
file=None,
content_length=None,
content_type="application/octet-stream",
durability_level=None):
"""PutObject
https://... | [
"def",
"put_object",
"(",
"self",
",",
"mpath",
",",
"content",
"=",
"None",
",",
"path",
"=",
"None",
",",
"file",
"=",
"None",
",",
"content_length",
"=",
"None",
",",
"content_type",
"=",
"\"application/octet-stream\"",
",",
"durability_level",
"=",
"None... | 37.287879 | 17.454545 |
def run_once_per_node(func):
"""
Decorator preventing wrapped function from running more than
once per host (not just interpreter session).
Using env.patch = True will allow the wrapped function to be run
if it has been previously executed, but not otherwise
Stores the result of a function... | [
"def",
"run_once_per_node",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"decorated",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"hasattr",
"(",
"env",
",",
"'patch'",
")",
":",
"env",
".",
"patch",
"=",
"F... | 38.107143 | 18.035714 |
def genInterval(self,
month=(),
day=(),
week=(),
weekday=(),
hour=(),
minute=()):
'''Generate list of config dictionarie(s) that represent a interval of time. Used to be passed into add() or r... | [
"def",
"genInterval",
"(",
"self",
",",
"month",
"=",
"(",
")",
",",
"day",
"=",
"(",
")",
",",
"week",
"=",
"(",
")",
",",
"weekday",
"=",
"(",
")",
",",
"hour",
"=",
"(",
")",
",",
"minute",
"=",
"(",
")",
")",
":",
"dic",
"=",
"{",
"'M... | 41.46 | 23.22 |
def show(what='contents', calc_id=-1, extra=()):
"""
Show the content of a datastore (by default the last one).
"""
datadir = datastore.get_datadir()
if what == 'all': # show all
if not os.path.exists(datadir):
return
rows = []
for calc_id in datastore.get_calc_i... | [
"def",
"show",
"(",
"what",
"=",
"'contents'",
",",
"calc_id",
"=",
"-",
"1",
",",
"extra",
"=",
"(",
")",
")",
":",
"datadir",
"=",
"datastore",
".",
"get_datadir",
"(",
")",
"if",
"what",
"==",
"'all'",
":",
"# show all",
"if",
"not",
"os",
".",
... | 36.631579 | 15.368421 |
def client(*args, **kwargs):
"""
Create a low-level service client by name using the default session.
Socket level timeouts are preconfigured according to the defaults set via
the `fleece.boto3.set_default_timeout()` function, or they can also be set
explicitly for a client by passing the `timeout`,... | [
"def",
"client",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"timeout",
"=",
"kwargs",
".",
"pop",
"(",
"'timeout'",
",",
"DEFAULT_TIMEOUT",
")",
"connect_timeout",
"=",
"kwargs",
".",
"pop",
"(",
"'connect_timeout'",
",",
"DEFAULT_CONNECT_TIMEOUT",... | 48.6875 | 20.6875 |
def register_route(self, route_rules, label=None):
"""Registers a routing rule.
:param RouteRule|list[RouteRule] route_rules:
:param str|unicode label: Label to mark the given set of rules.
This can be used in conjunction with ``do_goto`` rule action.
* http://uwsgi.re... | [
"def",
"register_route",
"(",
"self",
",",
"route_rules",
",",
"label",
"=",
"None",
")",
":",
"route_rules",
"=",
"listify",
"(",
"route_rules",
")",
"if",
"route_rules",
"and",
"label",
":",
"self",
".",
"_set",
"(",
"route_rules",
"[",
"0",
"]",
".",
... | 32.8 | 24.45 |
def as_plain_ordered_dict(self):
"""return a deep copy of this config as a plain OrderedDict
The config tree should be fully resolved.
This is useful to get an object with no special semantics such as path expansion for the keys.
In particular this means that keys that contain dots are... | [
"def",
"as_plain_ordered_dict",
"(",
"self",
")",
":",
"def",
"plain_value",
"(",
"v",
")",
":",
"if",
"isinstance",
"(",
"v",
",",
"list",
")",
":",
"return",
"[",
"plain_value",
"(",
"e",
")",
"for",
"e",
"in",
"v",
"]",
"elif",
"isinstance",
"(",
... | 42.227273 | 23.409091 |
def load_inference_roidbs(self, name):
"""
Args:
name (str): name of one inference dataset, e.g. 'minival2014'
Returns:
roidbs (list[dict]):
Each dict corresponds to one image to run inference on. The
following keys in the dict are expected:
... | [
"def",
"load_inference_roidbs",
"(",
"self",
",",
"name",
")",
":",
"return",
"COCODetection",
".",
"load_many",
"(",
"cfg",
".",
"DATA",
".",
"BASEDIR",
",",
"name",
",",
"add_gt",
"=",
"False",
")"
] | 36.2 | 24.2 |
def _init_itemid2name(self):
"""Print gene symbols instead of gene IDs, if provided."""
if not hasattr(self.args, 'id2sym'):
return None
fin_id2sym = self.args.id2sym
if fin_id2sym is not None and os.path.exists(fin_id2sym):
id2sym = {}
cmpl = re.compi... | [
"def",
"_init_itemid2name",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
".",
"args",
",",
"'id2sym'",
")",
":",
"return",
"None",
"fin_id2sym",
"=",
"self",
".",
"args",
".",
"id2sym",
"if",
"fin_id2sym",
"is",
"not",
"None",
"and",
"os... | 41.285714 | 11 |
def download_url(url, root, filename=None, md5=None):
"""Download a file from a url and place it in root.
Args:
url (str): URL to download file from
root (str): Directory to place downloaded file in
filename (str, optional): Name to save the file under. If None, use the basename of the ... | [
"def",
"download_url",
"(",
"url",
",",
"root",
",",
"filename",
"=",
"None",
",",
"md5",
"=",
"None",
")",
":",
"from",
"six",
".",
"moves",
"import",
"urllib",
"root",
"=",
"os",
".",
"path",
".",
"expanduser",
"(",
"root",
")",
"if",
"not",
"fil... | 35.621622 | 18.432432 |
def commented(self, user):
""" True if comment was added in given time frame """
for comment in self.comments:
# Description (comment #0) is not considered as a comment
if comment["count"] == 0:
continue
if (comment.get('author', comment.get('creator')... | [
"def",
"commented",
"(",
"self",
",",
"user",
")",
":",
"for",
"comment",
"in",
"self",
".",
"comments",
":",
"# Description (comment #0) is not considered as a comment",
"if",
"comment",
"[",
"\"count\"",
"]",
"==",
"0",
":",
"continue",
"if",
"(",
"comment",
... | 47.909091 | 18.545455 |
def prune_hashes(self, hashes, list_type):
"""Prune any hashes not in source resource or change list."""
discarded = []
for hash in hashes:
if (hash in self.hashes):
self.hashes.discard(hash)
discarded.append(hash)
self.logger.info("Not calcula... | [
"def",
"prune_hashes",
"(",
"self",
",",
"hashes",
",",
"list_type",
")",
":",
"discarded",
"=",
"[",
"]",
"for",
"hash",
"in",
"hashes",
":",
"if",
"(",
"hash",
"in",
"self",
".",
"hashes",
")",
":",
"self",
".",
"hashes",
".",
"discard",
"(",
"ha... | 50 | 14.777778 |
def while_until_true(interval, max_attempts):
"""Decorator that executes a function until it returns True.
Executes wrapped function at every number of seconds specified by interval,
until wrapped function either returns True or max_attempts are exhausted,
whichever comes 1st.
The difference betwe... | [
"def",
"while_until_true",
"(",
"interval",
",",
"max_attempts",
")",
":",
"def",
"decorator",
"(",
"f",
")",
":",
"logger",
".",
"debug",
"(",
"\"started\"",
")",
"def",
"sleep_looper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"max_a... | 39.115942 | 23.246377 |
def render_html(self, *args, **kwargs):
"""
Renders the template.
:rtype: str
"""
static_url = '%s://%s%s' % (self.request.scheme, self.request.get_host(), settings.STATIC_URL)
media_url = '%s://%s%s' % (self.request.scheme, self.request.get_host(), settings.MEDIA_URL)
... | [
"def",
"render_html",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"static_url",
"=",
"'%s://%s%s'",
"%",
"(",
"self",
".",
"request",
".",
"scheme",
",",
"self",
".",
"request",
".",
"get_host",
"(",
")",
",",
"settings",
".",
... | 41 | 23.714286 |
def on_task(self, task, response):
'''Deal one task'''
start_time = time.time()
response = rebuild_response(response)
try:
assert 'taskid' in task, 'need taskid in task'
project = task['project']
updatetime = task.get('project_updatetime', None)
... | [
"def",
"on_task",
"(",
"self",
",",
"task",
",",
"response",
")",
":",
"start_time",
"=",
"time",
".",
"time",
"(",
")",
"response",
"=",
"rebuild_response",
"(",
"response",
")",
"try",
":",
"assert",
"'taskid'",
"in",
"task",
",",
"'need taskid in task'"... | 42.470588 | 18.313725 |
def optimize(self, angles0, target):
"""Calculate an optimum argument of an objective function."""
def new_objective(angles):
return self.f(angles, target)
return scipy.optimize.minimize(
new_objective,
angles0,
**self.optimizer_opt).x | [
"def",
"optimize",
"(",
"self",
",",
"angles0",
",",
"target",
")",
":",
"def",
"new_objective",
"(",
"angles",
")",
":",
"return",
"self",
".",
"f",
"(",
"angles",
",",
"target",
")",
"return",
"scipy",
".",
"optimize",
".",
"minimize",
"(",
"new_obje... | 33.333333 | 10.111111 |
def load_kallisto(self):
"""
Load Kallisto transcript quantification data for a cohort
Parameters
----------
Returns
-------
kallisto_data : Pandas dataframe
Pandas dataframe with Kallisto data for all patients
columns include patient_id,... | [
"def",
"load_kallisto",
"(",
"self",
")",
":",
"kallisto_data",
"=",
"pd",
".",
"concat",
"(",
"[",
"self",
".",
"_load_single_patient_kallisto",
"(",
"patient",
")",
"for",
"patient",
"in",
"self",
"]",
",",
"copy",
"=",
"False",
")",
"if",
"self",
".",... | 32.774194 | 25.677419 |
def info(name, path=None):
'''
Returns information about a container
path
path to the container parent directory
default: /var/lib/lxc (system)
.. versionadded:: 2015.8.0
CLI Example:
.. code-block:: bash
salt '*' lxc.info name
'''
cachekey = 'lxc.info.{0... | [
"def",
"info",
"(",
"name",
",",
"path",
"=",
"None",
")",
":",
"cachekey",
"=",
"'lxc.info.{0}{1}'",
".",
"format",
"(",
"name",
",",
"path",
")",
"try",
":",
"return",
"__context__",
"[",
"cachekey",
"]",
"except",
"KeyError",
":",
"_ensure_exists",
"(... | 35.993056 | 17.104167 |
def natural_keys(input_str: str) -> List[Union[int, str]]:
"""
Converts a string into a list of integers and strings to support natural sorting (see natural_sort).
For example: natural_keys('abc123def') -> ['abc', '123', 'def']
:param input_str: string to convert
:return: list of strings and intege... | [
"def",
"natural_keys",
"(",
"input_str",
":",
"str",
")",
"->",
"List",
"[",
"Union",
"[",
"int",
",",
"str",
"]",
"]",
":",
"return",
"[",
"try_int_or_force_to_lower_case",
"(",
"substr",
")",
"for",
"substr",
"in",
"re",
".",
"split",
"(",
"r'(\\d+)'",... | 46.444444 | 22.888889 |
def _make_triangles_lines(shape, wrapx=False, wrapy=False):
"""Transform rectangular regular grid into triangles.
:param x: {x2d}
:param y: {y2d}
:param z: {z2d}
:param bool wrapx: when True, the x direction is assumed to wrap, and polygons are drawn between the end end begin points
:param bool... | [
"def",
"_make_triangles_lines",
"(",
"shape",
",",
"wrapx",
"=",
"False",
",",
"wrapy",
"=",
"False",
")",
":",
"nx",
",",
"ny",
"=",
"shape",
"mx",
"=",
"nx",
"if",
"wrapx",
"else",
"nx",
"-",
"1",
"my",
"=",
"ny",
"if",
"wrapy",
"else",
"ny",
"... | 31.549296 | 18.394366 |
def get_current_history_length(self):
u'''Return the number of lines currently in the history.
(This is different from get_history_length(), which returns
the maximum number of lines that will be written to a history file.)'''
value = len(self.history)
log(u"get_current_his... | [
"def",
"get_current_history_length",
"(",
"self",
")",
":",
"value",
"=",
"len",
"(",
"self",
".",
"history",
")",
"log",
"(",
"u\"get_current_history_length:%d\"",
"%",
"value",
")",
"return",
"value"
] | 51.142857 | 19.142857 |
def ensure_environment(variables):
"""
Check os.environ to ensure that a given collection of
variables has been set.
:param variables: A collection of environment variable names
:returns: os.environ
:raises IncompleteEnvironment: if any variables are not set, with
the exception's ``vari... | [
"def",
"ensure_environment",
"(",
"variables",
")",
":",
"missing",
"=",
"[",
"v",
"for",
"v",
"in",
"variables",
"if",
"v",
"not",
"in",
"os",
".",
"environ",
"]",
"if",
"missing",
":",
"formatted",
"=",
"', '",
".",
"join",
"(",
"missing",
")",
"me... | 37.470588 | 17.352941 |
def UNIFAC_groups(self):
r'''Dictionary of UNIFAC subgroup: count groups for the original
UNIFAC subgroups, as determined by `DDBST's online service <http://www.ddbst.com/unifacga.html>`_.
Examples
--------
>>> pprint(Chemical('Cumene').UNIFAC_groups)
{1: 2, 9: 5, 13: 1}... | [
"def",
"UNIFAC_groups",
"(",
"self",
")",
":",
"if",
"self",
".",
"__UNIFAC_groups",
":",
"return",
"self",
".",
"__UNIFAC_groups",
"else",
":",
"load_group_assignments_DDBST",
"(",
")",
"if",
"self",
".",
"InChI_Key",
"in",
"DDBST_UNIFAC_assignments",
":",
"sel... | 37.444444 | 21.666667 |
def get_request(self, request):
"""Sets token-based auth headers."""
request.transport_user = self.username
request.transport_password = self.api_key
return request | [
"def",
"get_request",
"(",
"self",
",",
"request",
")",
":",
"request",
".",
"transport_user",
"=",
"self",
".",
"username",
"request",
".",
"transport_password",
"=",
"self",
".",
"api_key",
"return",
"request"
] | 38.4 | 8.4 |
def setup_prompt(self,
prompt_name,
prefix='default',
capture_exit_code=False,
loglevel=logging.DEBUG):
"""Use this when you've opened a new shell to set the PS1 to something
sane. By default, it sets up the default expect so you don't have to
... | [
"def",
"setup_prompt",
"(",
"self",
",",
"prompt_name",
",",
"prefix",
"=",
"'default'",
",",
"capture_exit_code",
"=",
"False",
",",
"loglevel",
"=",
"logging",
".",
"DEBUG",
")",
":",
"shutit",
"=",
"self",
".",
"shutit",
"local_prompt",
"=",
"prefix",
"... | 51.979381 | 22.072165 |
def min(self, key=None):
"""
Find the minimum item in this RDD.
:param key: A function used to generate key for comparing
>>> rdd = sc.parallelize([2.0, 5.0, 43.0, 10.0])
>>> rdd.min()
2.0
>>> rdd.min(key=str)
10.0
"""
if key is None:
... | [
"def",
"min",
"(",
"self",
",",
"key",
"=",
"None",
")",
":",
"if",
"key",
"is",
"None",
":",
"return",
"self",
".",
"reduce",
"(",
"min",
")",
"return",
"self",
".",
"reduce",
"(",
"lambda",
"a",
",",
"b",
":",
"min",
"(",
"a",
",",
"b",
","... | 26.533333 | 17.866667 |
def read(self, size):
"""
Read wrapper.
Parameters
----------
size : int
Number of bytes to read.
"""
try:
return_val = self.handle.read(size)
if return_val == '':
print()
print("Piksi disconnected... | [
"def",
"read",
"(",
"self",
",",
"size",
")",
":",
"try",
":",
"return_val",
"=",
"self",
".",
"handle",
".",
"read",
"(",
"size",
")",
"if",
"return_val",
"==",
"''",
":",
"print",
"(",
")",
"print",
"(",
"\"Piksi disconnected\"",
")",
"print",
"(",... | 23.409091 | 14.863636 |
def pset_field(item_type, optional=False, initial=()):
"""
Create checked ``PSet`` field.
:param item_type: The required type for the items in the set.
:param optional: If true, ``None`` can be used as a value for
this field.
:param initial: Initial value to pass to factory if no value is g... | [
"def",
"pset_field",
"(",
"item_type",
",",
"optional",
"=",
"False",
",",
"initial",
"=",
"(",
")",
")",
":",
"return",
"_sequence_field",
"(",
"CheckedPSet",
",",
"item_type",
",",
"optional",
",",
"initial",
")"
] | 36.642857 | 19.928571 |
def store_source_info(self, calc_times):
"""
Save (weight, num_sites, calc_time) inside the source_info dataset
"""
if calc_times:
source_info = self.datastore['source_info']
arr = numpy.zeros((len(source_info), 3), F32)
ids, vals = zip(*sorted(calc_ti... | [
"def",
"store_source_info",
"(",
"self",
",",
"calc_times",
")",
":",
"if",
"calc_times",
":",
"source_info",
"=",
"self",
".",
"datastore",
"[",
"'source_info'",
"]",
"arr",
"=",
"numpy",
".",
"zeros",
"(",
"(",
"len",
"(",
"source_info",
")",
",",
"3",... | 42.5 | 10.333333 |
def execute_scheduler(self):
"""Main entry point for the scheduler. This method will start two scheduled jobs, `schedule_jobs` which takes
care of scheduling the actual SQS messaging and `process_status_queue` which will track the current status
of the jobs as workers are executing them
... | [
"def",
"execute_scheduler",
"(",
"self",
")",
":",
"try",
":",
"# Schedule periodic scheduling of jobs",
"self",
".",
"scheduler",
".",
"add_job",
"(",
"self",
".",
"schedule_jobs",
",",
"trigger",
"=",
"'interval'",
",",
"name",
"=",
"'schedule_jobs'",
",",
"mi... | 34.16129 | 17.064516 |
def secure_authorized_channel(
credentials, request, target, ssl_credentials=None, **kwargs):
"""Creates a secure authorized gRPC channel.
This creates a channel with SSL and :class:`AuthMetadataPlugin`. This
channel can be used to create a stub that can make authorized requests.
Example::
... | [
"def",
"secure_authorized_channel",
"(",
"credentials",
",",
"request",
",",
"target",
",",
"ssl_credentials",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# Create the metadata plugin for inserting the authorization header.",
"metadata_plugin",
"=",
"AuthMetadataPlugin... | 40.642857 | 25.303571 |
def to_str(delta, extended=False):
"""Format a datetime.timedelta to a duration string"""
total_seconds = delta.total_seconds()
sign = "-" if total_seconds < 0 else ""
nanoseconds = abs(total_seconds * _second_size)
if total_seconds < 1:
result_str = _to_str_small(nanoseconds, extended)
... | [
"def",
"to_str",
"(",
"delta",
",",
"extended",
"=",
"False",
")",
":",
"total_seconds",
"=",
"delta",
".",
"total_seconds",
"(",
")",
"sign",
"=",
"\"-\"",
"if",
"total_seconds",
"<",
"0",
"else",
"\"\"",
"nanoseconds",
"=",
"abs",
"(",
"total_seconds",
... | 32.076923 | 17.153846 |
def recursive_derived(self):
"""list of all :class:`derive classes <hierarchy_info_t>`"""
if self._recursive_derived is None:
to_go = self.derived[:]
all_derived = []
while to_go:
derive = to_go.pop()
if derive not in all_derived:
... | [
"def",
"recursive_derived",
"(",
"self",
")",
":",
"if",
"self",
".",
"_recursive_derived",
"is",
"None",
":",
"to_go",
"=",
"self",
".",
"derived",
"[",
":",
"]",
"all_derived",
"=",
"[",
"]",
"while",
"to_go",
":",
"derive",
"=",
"to_go",
".",
"pop",... | 41.833333 | 8 |
def Parse(self, stat, file_object, knowledge_base):
"""Parse the status file."""
_, _ = stat, knowledge_base
packages = []
sw_data = utils.ReadFileBytesAsUnicode(file_object)
try:
for pkg in self._deb822.Packages.iter_paragraphs(sw_data.splitlines()):
if self.installed_re.match(pkg["S... | [
"def",
"Parse",
"(",
"self",
",",
"stat",
",",
"file_object",
",",
"knowledge_base",
")",
":",
"_",
",",
"_",
"=",
"stat",
",",
"knowledge_base",
"packages",
"=",
"[",
"]",
"sw_data",
"=",
"utils",
".",
"ReadFileBytesAsUnicode",
"(",
"file_object",
")",
... | 37.869565 | 15.173913 |
def create_flavor(self, name):
"""Create a new baremetal flavor.
:param name: the name of the flavor
"""
self.add_environment_file(user='stack', filename='stackrc')
self.run('openstack flavor create --id auto --ram 4096 --disk 40 --vcpus 1 baremetal', user='stack', success_statu... | [
"def",
"create_flavor",
"(",
"self",
",",
"name",
")",
":",
"self",
".",
"add_environment_file",
"(",
"user",
"=",
"'stack'",
",",
"filename",
"=",
"'stackrc'",
")",
"self",
".",
"run",
"(",
"'openstack flavor create --id auto --ram 4096 --disk 40 --vcpus 1 baremetal'... | 63.777778 | 38 |
def lstring_as_obj(true_or_false=None):
"""Toggles whether lstrings should be treated as strings or as objects.
When FieldArrays is first loaded, the default is True.
Parameters
----------
true_or_false : {None|bool}
Pass True to map lstrings to objects; False otherwise. If None
pro... | [
"def",
"lstring_as_obj",
"(",
"true_or_false",
"=",
"None",
")",
":",
"if",
"true_or_false",
"is",
"not",
"None",
":",
"_default_types_status",
"[",
"'lstring_as_obj'",
"]",
"=",
"true_or_false",
"# update the typeDict",
"numpy",
".",
"typeDict",
"[",
"u'lstring'",
... | 37.526316 | 19.736842 |
def fixed_poch(a, n):
"""Implementation of the Pochhammer symbol :math:`(a)_n` which handles negative integer arguments properly.
Need conditional statement because scipy's impelementation of the Pochhammer
symbol is wrong for negative integer arguments. This function uses the
definition from
h... | [
"def",
"fixed_poch",
"(",
"a",
",",
"n",
")",
":",
"# Old form, calls gamma function:",
"# if a < 0.0 and a % 1 == 0 and n <= -a:",
"# p = (-1.0)**n * scipy.misc.factorial(-a) / scipy.misc.factorial(-a - n)",
"# else:",
"# p = scipy.special.poch(a, n)",
"# return p",
"if",
"(",... | 34.185185 | 19.444444 |
def _allocate_address(self, instance):
"""Allocates a free public ip address to the given instance
:param instance: instance to assign address to
:type instance: py:class:`boto.ec2.instance.Reservation`
:return: public ip address
"""
connection = self._connect()
... | [
"def",
"_allocate_address",
"(",
"self",
",",
"instance",
")",
":",
"connection",
"=",
"self",
".",
"_connect",
"(",
")",
"free_addresses",
"=",
"[",
"ip",
"for",
"ip",
"in",
"connection",
".",
"get_all_addresses",
"(",
")",
"if",
"not",
"ip",
".",
"inst... | 37.692308 | 16.846154 |
def simple_lesk(context_sentence: str, ambiguous_word: str,
pos: str = None, lemma=True, stem=False, hyperhypo=True,
stop=True, context_is_lemmatized=False,
nbest=False, keepscore=False, normalizescore=False,
from_cache=True) -> "wn.Synset":
"""
Si... | [
"def",
"simple_lesk",
"(",
"context_sentence",
":",
"str",
",",
"ambiguous_word",
":",
"str",
",",
"pos",
":",
"str",
"=",
"None",
",",
"lemma",
"=",
"True",
",",
"stem",
"=",
"False",
",",
"hyperhypo",
"=",
"True",
",",
"stop",
"=",
"True",
",",
"co... | 51.666667 | 18.777778 |
def handle_options():
'''Handle options.
'''
parser = OptionParser()
parser.set_defaults(cmaglin=False)
parser.set_defaults(single=False)
parser.set_defaults(alpha_cov=False)
parser.add_option('-x',
'--xmin',
dest='xmin',
help... | [
"def",
"handle_options",
"(",
")",
":",
"parser",
"=",
"OptionParser",
"(",
")",
"parser",
".",
"set_defaults",
"(",
"cmaglin",
"=",
"False",
")",
"parser",
".",
"set_defaults",
"(",
"single",
"=",
"False",
")",
"parser",
".",
"set_defaults",
"(",
"alpha_c... | 34.439252 | 9.149533 |
def OauthGetAccessToken(self):
"""
Use token_verifier to obtain an access token for the user. If this function returns True, the clients __oauth_token__ member
contains the access token.
@return (boolean) - Boolean indicating whether OauthGetRequestToken wa... | [
"def",
"OauthGetAccessToken",
"(",
"self",
")",
":",
"self",
".",
"__setAuthenticationMethod__",
"(",
"'authenticating_oauth'",
")",
"# obtain access token\r",
"oauth_request",
"=",
"oauth",
".",
"OAuthRequest",
".",
"from_consumer_and_token",
"(",
"self",
".",
"__oauth... | 54.71875 | 34.59375 |
def parse(cls, s, schema_only=False):
"""
Parse an ARFF File already loaded into a string.
"""
a = cls()
a.state = 'comment'
a.lineno = 1
for l in s.splitlines():
a.parseline(l)
a.lineno += 1
if schema_only and a.state == 'data'... | [
"def",
"parse",
"(",
"cls",
",",
"s",
",",
"schema_only",
"=",
"False",
")",
":",
"a",
"=",
"cls",
"(",
")",
"a",
".",
"state",
"=",
"'comment'",
"a",
".",
"lineno",
"=",
"1",
"for",
"l",
"in",
"s",
".",
"splitlines",
"(",
")",
":",
"a",
".",... | 29.714286 | 13.714286 |
def hacking_no_old_style_class(logical_line, noqa):
r"""Check for old style classes.
Examples:
Okay: class Foo(object):\n pass
Okay: class Foo(Bar, Baz):\n pass
Okay: class Foo(object, Baz):\n pass
Okay: class Foo(somefunc()):\n pass
H238: class Bar:\n pass
H238: class Ba... | [
"def",
"hacking_no_old_style_class",
"(",
"logical_line",
",",
"noqa",
")",
":",
"if",
"noqa",
":",
"return",
"line",
"=",
"core",
".",
"import_normalize",
"(",
"logical_line",
".",
"strip",
"(",
")",
")",
"if",
"line",
".",
"startswith",
"(",
"\"class \"",
... | 35.411765 | 14.176471 |
def stop_refreshing_token(self):
"""
The timer needs to be canceled if the application is terminating, if not the timer will keep going.
"""
with self.lock:
self.timer_stopped = True
self.timer.cancel() | [
"def",
"stop_refreshing_token",
"(",
"self",
")",
":",
"with",
"self",
".",
"lock",
":",
"self",
".",
"timer_stopped",
"=",
"True",
"self",
".",
"timer",
".",
"cancel",
"(",
")"
] | 36 | 14.857143 |
def asyncPipeSubstr(context=None, _INPUT=None, conf=None, **kwargs):
"""A string module that asynchronously returns a substring. Loopable.
Parameters
----------
context : pipe2py.Context object
_INPUT : twisted Deferred iterable of items or strings
conf : {
'from': {'type': 'number', va... | [
"def",
"asyncPipeSubstr",
"(",
"context",
"=",
"None",
",",
"_INPUT",
"=",
"None",
",",
"conf",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"conf",
"[",
"'start'",
"]",
"=",
"conf",
".",
"pop",
"(",
"'from'",
",",
"dict",
".",
"get",
"(",
"co... | 39.47619 | 24.904762 |
def host(value):
""" Validates that the value is a valid network location """
if not value:
return (True, "")
try:
host,port = value.split(":")
except ValueError as _:
return (False, "value needs to be <host>:<port>")
try:
int(port)
except ValueError as _:
... | [
"def",
"host",
"(",
"value",
")",
":",
"if",
"not",
"value",
":",
"return",
"(",
"True",
",",
"\"\"",
")",
"try",
":",
"host",
",",
"port",
"=",
"value",
".",
"split",
"(",
"\":\"",
")",
"except",
"ValueError",
"as",
"_",
":",
"return",
"(",
"Fal... | 26.933333 | 22.4 |
def GetRowMatch(self, attributes):
"""Returns the row number that matches the supplied attributes."""
for row in self.compiled:
try:
for key in attributes:
# Silently skip attributes not present in the index file.
# pylint: disable=E110... | [
"def",
"GetRowMatch",
"(",
"self",
",",
"attributes",
")",
":",
"for",
"row",
"in",
"self",
".",
"compiled",
":",
"try",
":",
"for",
"key",
"in",
"attributes",
":",
"# Silently skip attributes not present in the index file.",
"# pylint: disable=E1103",
"if",
"(",
... | 40.166667 | 13.611111 |
def to_dict(obj):
"""
If value wasn't isn't a primitive scalar or collection then it needs to
either implement to_dict (instances of Serializable) or has member
data matching each required arg of __init__.
"""
if isinstance(obj, dict):
return obj
elif hasattr(obj, "to_dict"):
... | [
"def",
"to_dict",
"(",
"obj",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"dict",
")",
":",
"return",
"obj",
"elif",
"hasattr",
"(",
"obj",
",",
"\"to_dict\"",
")",
":",
"return",
"obj",
".",
"to_dict",
"(",
")",
"try",
":",
"return",
"simple_obje... | 31.4375 | 15.4375 |
def color(
self, text=None, fore=None, back=None, style=None,
no_closing=False):
""" A method that colorizes strings, not Colr objects.
Raises InvalidColr for invalid color names.
The 'reset_all' code is appended if text is given.
"""
has_args = (
... | [
"def",
"color",
"(",
"self",
",",
"text",
"=",
"None",
",",
"fore",
"=",
"None",
",",
"back",
"=",
"None",
",",
"style",
"=",
"None",
",",
"no_closing",
"=",
"False",
")",
":",
"has_args",
"=",
"(",
"(",
"fore",
"is",
"not",
"None",
")",
"or",
... | 36.76087 | 17.956522 |
def dump(data, abspath, pk_protocol=py23.pk_protocol,
overwrite=False, enable_verbose=True):
"""Dump picklable object to file.
Provides multiple choice to customize the behavior.
:param data: picklable python object.
:type data: dict or list
:param abspath: ``save as`` path, file extensio... | [
"def",
"dump",
"(",
"data",
",",
"abspath",
",",
"pk_protocol",
"=",
"py23",
".",
"pk_protocol",
",",
"overwrite",
"=",
"False",
",",
"enable_verbose",
"=",
"True",
")",
":",
"prt",
"(",
"\"\\nDump to '%s' ...\"",
"%",
"abspath",
",",
"enable_verbose",
")",
... | 30.723684 | 22.197368 |
def estimate_from_ssr(histograms, readout_povm, pre_channel_ops, post_channel_ops, settings):
"""
Estimate a quantum process from single shot histograms obtained by preparing specific input
states and measuring bitstrings in the Z-eigenbasis after application of given channel
operators.
... | [
"def",
"estimate_from_ssr",
"(",
"histograms",
",",
"readout_povm",
",",
"pre_channel_ops",
",",
"post_channel_ops",
",",
"settings",
")",
":",
"nqc",
"=",
"len",
"(",
"pre_channel_ops",
"[",
"0",
"]",
".",
"dims",
"[",
"0",
"]",
")",
"pauli_basis",
"=",
"... | 51.5 | 28.5 |
def websocket(self, uri, *args, **kwargs):
"""Create a websocket route from a decorated function
:param uri: endpoint at which the socket endpoint will be accessible.
:type uri: str
:param args: captures all of the positional arguments passed in
:type args: tuple(Any)
:pa... | [
"def",
"websocket",
"(",
"self",
",",
"uri",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"setdefault",
"(",
"'host'",
",",
"None",
")",
"kwargs",
".",
"setdefault",
"(",
"'strict_slashes'",
",",
"None",
")",
"kwargs",
".",
"se... | 41 | 15.956522 |
def get_annotation(self, id_):
"""Data for a specific annotation."""
endpoint = "annotations/{id}".format(id=id_)
return self._make_request(endpoint) | [
"def",
"get_annotation",
"(",
"self",
",",
"id_",
")",
":",
"endpoint",
"=",
"\"annotations/{id}\"",
".",
"format",
"(",
"id",
"=",
"id_",
")",
"return",
"self",
".",
"_make_request",
"(",
"endpoint",
")"
] | 42.5 | 6.25 |
def channel(self, channel_id=None, synchronous=False):
"""
Fetch a Channel object identified by the numeric channel_id, or
create that object if it doesn't already exist. If channel_id is not
None but no channel exists for that id, will raise InvalidChannel. If
there are alread... | [
"def",
"channel",
"(",
"self",
",",
"channel_id",
"=",
"None",
",",
"synchronous",
"=",
"False",
")",
":",
"if",
"channel_id",
"is",
"None",
":",
"# adjust for channel 0",
"if",
"len",
"(",
"self",
".",
"_channels",
")",
"-",
"1",
">=",
"self",
".",
"_... | 45.971429 | 18.142857 |
def _organize_qc_files(program, qc_dir):
"""Organize outputs from quality control runs into a base file and secondary outputs.
Provides compatibility with CWL output. Returns None if no files created during processing.
"""
base_files = {"fastqc": "fastqc_report.html",
"qualimap_rnaseq... | [
"def",
"_organize_qc_files",
"(",
"program",
",",
"qc_dir",
")",
":",
"base_files",
"=",
"{",
"\"fastqc\"",
":",
"\"fastqc_report.html\"",
",",
"\"qualimap_rnaseq\"",
":",
"\"qualimapReport.html\"",
",",
"\"qualimap\"",
":",
"\"qualimapReport.html\"",
"}",
"if",
"os",... | 48.875 | 17.3125 |
def raise_error(self, message, *params, **key_params):
"""
Raise a parse error.
"""
s = 'Parser error in '
self.xml_node_stack.reverse()
if len(self.xml_node_stack) > 1:
node = self.xml_node_stack[0]
s += '<{0}'.format(node.tag)
... | [
"def",
"raise_error",
"(",
"self",
",",
"message",
",",
"*",
"params",
",",
"*",
"*",
"key_params",
")",
":",
"s",
"=",
"'Parser error in '",
"self",
".",
"xml_node_stack",
".",
"reverse",
"(",
")",
"if",
"len",
"(",
"self",
".",
"xml_node_stack",
")",
... | 31.4 | 14.8 |
def get_device_elements(self):
"""Get the DOM elements for the device list."""
plain = self._aha_request('getdevicelistinfos')
dom = xml.dom.minidom.parseString(plain)
_LOGGER.debug(dom)
return dom.getElementsByTagName("device") | [
"def",
"get_device_elements",
"(",
"self",
")",
":",
"plain",
"=",
"self",
".",
"_aha_request",
"(",
"'getdevicelistinfos'",
")",
"dom",
"=",
"xml",
".",
"dom",
".",
"minidom",
".",
"parseString",
"(",
"plain",
")",
"_LOGGER",
".",
"debug",
"(",
"dom",
"... | 43.833333 | 9.333333 |
def distance(vec1, vec2):
"""Calculate the distance between two Vectors"""
if isinstance(vec1, Vector2) \
and isinstance(vec2, Vector2):
dist_vec = vec2 - vec1
return dist_vec.length()
else:
raise TypeError("vec1 and vec2 must be Vector2's") | [
"def",
"distance",
"(",
"vec1",
",",
"vec2",
")",
":",
"if",
"isinstance",
"(",
"vec1",
",",
"Vector2",
")",
"and",
"isinstance",
"(",
"vec2",
",",
"Vector2",
")",
":",
"dist_vec",
"=",
"vec2",
"-",
"vec1",
"return",
"dist_vec",
".",
"length",
"(",
"... | 38.75 | 10.25 |
def edit(self, id_equip, nome, id_tipo_equipamento, id_modelo, maintenance=None):
"""Change Equipment from by the identifier.
:param id_equip: Identifier of the Equipment. Integer value and greater than zero.
:param nome: Equipment name. String with a minimum 3 and maximum of 30 characters
... | [
"def",
"edit",
"(",
"self",
",",
"id_equip",
",",
"nome",
",",
"id_tipo_equipamento",
",",
"id_modelo",
",",
"maintenance",
"=",
"None",
")",
":",
"equip_map",
"=",
"dict",
"(",
")",
"equip_map",
"[",
"'id_equip'",
"]",
"=",
"id_equip",
"equip_map",
"[",
... | 45.552632 | 29.552632 |
def color_nodes(graph, labelattr='label', brightness=.878,
outof=None, sat_adjust=None):
""" Colors edges and nodes by nid """
import plottool as pt
import utool as ut
node_to_lbl = nx.get_node_attributes(graph, labelattr)
unique_lbls = sorted(set(node_to_lbl.values()))
ncolors =... | [
"def",
"color_nodes",
"(",
"graph",
",",
"labelattr",
"=",
"'label'",
",",
"brightness",
"=",
".878",
",",
"outof",
"=",
"None",
",",
"sat_adjust",
"=",
"None",
")",
":",
"import",
"plottool",
"as",
"pt",
"import",
"utool",
"as",
"ut",
"node_to_lbl",
"="... | 42.432432 | 19.378378 |
def IsEnabled(self, *args, **kwargs):
"check if all menu items are enabled"
for i in range(self.GetMenuItemCount()):
it = self.FindItemByPosition(i)
if not it.IsEnabled():
return False
return True | [
"def",
"IsEnabled",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"GetMenuItemCount",
"(",
")",
")",
":",
"it",
"=",
"self",
".",
"FindItemByPosition",
"(",
"i",
")",
"if",
"not",
"... | 37.285714 | 8.428571 |
def main(self):
"""
Run all the methods required for pipeline outputs
"""
self.fasta_records()
self.fasta_stats()
self.find_largest_contig()
self.find_genome_length()
self.find_num_contigs()
self.find_n50()
self.perform_pilon()
self... | [
"def",
"main",
"(",
"self",
")",
":",
"self",
".",
"fasta_records",
"(",
")",
"self",
".",
"fasta_stats",
"(",
")",
"self",
".",
"find_largest_contig",
"(",
")",
"self",
".",
"find_genome_length",
"(",
")",
"self",
".",
"find_num_contigs",
"(",
")",
"sel... | 27.333333 | 10.666667 |
async def copy_to(self, dest, container, buffering = True):
"""
Coroutine method to copy content from this stream to another stream.
"""
if self.eof:
await dest.write(u'' if self.isunicode else b'', True)
elif self.errored:
await dest.error(container)
... | [
"async",
"def",
"copy_to",
"(",
"self",
",",
"dest",
",",
"container",
",",
"buffering",
"=",
"True",
")",
":",
"if",
"self",
".",
"eof",
":",
"await",
"dest",
".",
"write",
"(",
"u''",
"if",
"self",
".",
"isunicode",
"else",
"b''",
",",
"True",
")... | 36.37037 | 14.740741 |
def alt_names(names: str) -> Callable[..., Any]:
"""Add alternative names to you custom commands.
`names` is a single string with a space separated list of aliases for the
decorated command.
"""
names_split = names.split()
def decorator(func: Callable[..., Any]) -> Callable[..., Any]:
... | [
"def",
"alt_names",
"(",
"names",
":",
"str",
")",
"->",
"Callable",
"[",
"...",
",",
"Any",
"]",
":",
"names_split",
"=",
"names",
".",
"split",
"(",
")",
"def",
"decorator",
"(",
"func",
":",
"Callable",
"[",
"...",
",",
"Any",
"]",
")",
"->",
... | 32.833333 | 19.25 |
def _let_to_py_ast(ctx: GeneratorContext, node: Let) -> GeneratedPyAST:
"""Return a Python AST Node for a `let*` expression."""
assert node.op == NodeOp.LET
with ctx.new_symbol_table("let"):
let_body_ast: List[ast.AST] = []
for binding in node.bindings:
init_node = binding.init
... | [
"def",
"_let_to_py_ast",
"(",
"ctx",
":",
"GeneratorContext",
",",
"node",
":",
"Let",
")",
"->",
"GeneratedPyAST",
":",
"assert",
"node",
".",
"op",
"==",
"NodeOp",
".",
"LET",
"with",
"ctx",
".",
"new_symbol_table",
"(",
"\"let\"",
")",
":",
"let_body_as... | 37.6 | 18.085714 |
def get_data(context, resource, **kwargs):
"""Retrieve data field from a resource"""
url_suffix = ''
if 'keys' in kwargs and kwargs['keys']:
url_suffix = '/?keys=%s' % ','.join(kwargs.pop('keys'))
uri = '%s/%s/%s/data%s' % (context.dci_cs_api, resource,
kwargs.po... | [
"def",
"get_data",
"(",
"context",
",",
"resource",
",",
"*",
"*",
"kwargs",
")",
":",
"url_suffix",
"=",
"''",
"if",
"'keys'",
"in",
"kwargs",
"and",
"kwargs",
"[",
"'keys'",
"]",
":",
"url_suffix",
"=",
"'/?keys=%s'",
"%",
"','",
".",
"join",
"(",
... | 34.416667 | 22.166667 |
def recarray2dict(recarray):
"""Return numpy.recarray as dict."""
# TODO: subarrays
result = {}
for descr, value in zip(recarray.dtype.descr, recarray):
name, dtype = descr[:2]
if dtype[1] == 'S':
value = bytes2str(stripnull(value))
elif value.ndim < 2:
va... | [
"def",
"recarray2dict",
"(",
"recarray",
")",
":",
"# TODO: subarrays",
"result",
"=",
"{",
"}",
"for",
"descr",
",",
"value",
"in",
"zip",
"(",
"recarray",
".",
"dtype",
".",
"descr",
",",
"recarray",
")",
":",
"name",
",",
"dtype",
"=",
"descr",
"[",... | 31.333333 | 13.166667 |
def _single_true(iterable):
'''This returns True if only one True-ish element exists in `iterable`.
Parameters
----------
iterable : iterable
Returns
-------
bool
True if only one True-ish element exists in `iterable`. False otherwise.
'''
# return True if exactly one t... | [
"def",
"_single_true",
"(",
"iterable",
")",
":",
"# return True if exactly one true found",
"iterator",
"=",
"iter",
"(",
"iterable",
")",
"# consume from \"i\" until first true or it's exhausted",
"has_true",
"=",
"any",
"(",
"iterator",
")",
"# carry on consuming until ano... | 21.846154 | 27.384615 |
def get_virtualenv_path(self, requirements_option: RequirementsOptions, requirements_hash: Optional[str]) -> Path:
"""
Returns the path to the virtualenv the current state of the repository.
"""
if requirements_option == RequirementsOptions.no_requirements:
venv_name = "no_re... | [
"def",
"get_virtualenv_path",
"(",
"self",
",",
"requirements_option",
":",
"RequirementsOptions",
",",
"requirements_hash",
":",
"Optional",
"[",
"str",
"]",
")",
"->",
"Path",
":",
"if",
"requirements_option",
"==",
"RequirementsOptions",
".",
"no_requirements",
"... | 44.2 | 23.4 |
def peek(self):
""" Obtain the next record from this result without consuming it.
This leaves the record in the buffer for further processing.
:returns: the next :class:`.Record` or :const:`None` if none remain
"""
records = self._records
if records:
return r... | [
"def",
"peek",
"(",
"self",
")",
":",
"records",
"=",
"self",
".",
"_records",
"if",
"records",
":",
"return",
"records",
"[",
"0",
"]",
"if",
"not",
"self",
".",
"attached",
"(",
")",
":",
"return",
"None",
"if",
"self",
".",
"attached",
"(",
")",... | 32.666667 | 15.222222 |
def _initialize(self):
"""Read the SharQ configuration and set appropriate
variables. Open a redis connection pool and load all
the Lua scripts.
"""
self._key_prefix = self._config.get('redis', 'key_prefix')
self._job_expire_interval = int(
self._config.get('s... | [
"def",
"_initialize",
"(",
"self",
")",
":",
"self",
".",
"_key_prefix",
"=",
"self",
".",
"_config",
".",
"get",
"(",
"'redis'",
",",
"'key_prefix'",
")",
"self",
".",
"_job_expire_interval",
"=",
"int",
"(",
"self",
".",
"_config",
".",
"get",
"(",
"... | 37.137931 | 17.413793 |
def get_host_usage(self):
"""
get details of CPU, RAM usage of this PC
"""
import psutil
process_names = [proc.name for proc in psutil.process_iter()]
cpu_pct = psutil.cpu_percent(interval=1)
mem = psutil.virtual_memory()
return str(cpu_pct), str(len(pro... | [
"def",
"get_host_usage",
"(",
"self",
")",
":",
"import",
"psutil",
"process_names",
"=",
"[",
"proc",
".",
"name",
"for",
"proc",
"in",
"psutil",
".",
"process_iter",
"(",
")",
"]",
"cpu_pct",
"=",
"psutil",
".",
"cpu_percent",
"(",
"interval",
"=",
"1"... | 40 | 14.555556 |
def setSSID(self, ssid, wifiInterfaceId=1, timeout=1):
"""Set the SSID (name of the Wifi network)
:param str ssid: the SSID/wifi network name
:param int wifiInterfaceId: the id of the Wifi interface
:param float timeout: the timeout to wait for the action to be executed
"""
... | [
"def",
"setSSID",
"(",
"self",
",",
"ssid",
",",
"wifiInterfaceId",
"=",
"1",
",",
"timeout",
"=",
"1",
")",
":",
"namespace",
"=",
"Wifi",
".",
"getServiceType",
"(",
"\"setChannel\"",
")",
"+",
"str",
"(",
"wifiInterfaceId",
")",
"uri",
"=",
"self",
... | 46.272727 | 22.545455 |
def add(self, elt):
"""Generic function to add objects into the scheduler daemon internal lists::
Brok -> self.broks
Check -> self.checks
Notification -> self.actions
EventHandler -> self.actions
For an ExternalCommand, tries to resolve the command
:param elt: e... | [
"def",
"add",
"(",
"self",
",",
"elt",
")",
":",
"if",
"elt",
"is",
"None",
":",
"return",
"logger",
".",
"debug",
"(",
"\"Adding: %s / %s\"",
",",
"elt",
".",
"my_type",
",",
"elt",
".",
"__dict__",
")",
"fun",
"=",
"self",
".",
"__add_actions",
"."... | 32.952381 | 19.52381 |
def cmp_code_objects(version, is_pypy, code_obj1, code_obj2, verify,
name=''):
"""
Compare two code-objects.
This is the main part of this module.
"""
# print code_obj1, type(code_obj2)
assert iscode(code_obj1), \
"cmp_code_object first object type is %s, not code" % ... | [
"def",
"cmp_code_objects",
"(",
"version",
",",
"is_pypy",
",",
"code_obj1",
",",
"code_obj2",
",",
"verify",
",",
"name",
"=",
"''",
")",
":",
"# print code_obj1, type(code_obj2)",
"assert",
"iscode",
"(",
"code_obj1",
")",
",",
"\"cmp_code_object first object type... | 47.586854 | 20.544601 |
def _use_widgets(objs):
''' Whether a collection of Bokeh objects contains a any Widget
Args:
objs (seq[Model or Document]) :
Returns:
bool
'''
from ..models.widgets import Widget
return _any(objs, lambda obj: isinstance(obj, Widget)) | [
"def",
"_use_widgets",
"(",
"objs",
")",
":",
"from",
".",
".",
"models",
".",
"widgets",
"import",
"Widget",
"return",
"_any",
"(",
"objs",
",",
"lambda",
"obj",
":",
"isinstance",
"(",
"obj",
",",
"Widget",
")",
")"
] | 22.166667 | 25.333333 |
def add_note(self, note, octave=None, dynamics={}):
"""Add a note to the container and sorts the notes from low to high.
The note can either be a string, in which case you could also use
the octave and dynamics arguments, or a Note object.
"""
if type(note) == str:
i... | [
"def",
"add_note",
"(",
"self",
",",
"note",
",",
"octave",
"=",
"None",
",",
"dynamics",
"=",
"{",
"}",
")",
":",
"if",
"type",
"(",
"note",
")",
"==",
"str",
":",
"if",
"octave",
"is",
"not",
"None",
":",
"note",
"=",
"Note",
"(",
"note",
","... | 44.565217 | 16.521739 |
def multivariate_neg_logposterior(self,beta):
""" Returns negative log posterior, for a model with a covariance matrix
Parameters
----------
beta : np.array
Contains untransformed starting values for latent_variables
Returns
----------
Negative log ... | [
"def",
"multivariate_neg_logposterior",
"(",
"self",
",",
"beta",
")",
":",
"post",
"=",
"self",
".",
"neg_loglik",
"(",
"beta",
")",
"for",
"k",
"in",
"range",
"(",
"0",
",",
"self",
".",
"z_no",
")",
":",
"if",
"self",
".",
"latent_variables",
".",
... | 34 | 22.857143 |
def initGrid(self):
"""
Initialise the game grid
"""
blinker = [(4, 4), (4, 5), (4, 6)]
toad = [(9, 5), (9, 6), (9, 7), (10, 4), (10, 5), (10, 6)]
glider = [(4, 11), (5, 12), (6, 10), (6, 11), (6, 12)]
r_pentomino = [(10, 60), (9, 61), (10, 61), (11, 61), (9, 62)]... | [
"def",
"initGrid",
"(",
"self",
")",
":",
"blinker",
"=",
"[",
"(",
"4",
",",
"4",
")",
",",
"(",
"4",
",",
"5",
")",
",",
"(",
"4",
",",
"6",
")",
"]",
"toad",
"=",
"[",
"(",
"9",
",",
"5",
")",
",",
"(",
"9",
",",
"6",
")",
",",
"... | 35.736842 | 17.631579 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.