text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def get_package_filename(filename, package_dir=None):
'''Return the filename of the data file.'''
if getattr(sys, 'frozen', False):
package_dir = os.path.join(
sys._MEIPASS,
os.path.basename(os.path.dirname(__file__))
)
elif not package_dir:
package_dir = os.p... | [
"def",
"get_package_filename",
"(",
"filename",
",",
"package_dir",
"=",
"None",
")",
":",
"if",
"getattr",
"(",
"sys",
",",
"'frozen'",
",",
"False",
")",
":",
"package_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"sys",
".",
"_MEIPASS",
",",
"os",... | 34.454545 | 14.272727 |
async def rtm(self) -> AsyncIterator[Event]:
"""Connect to the realtime event API and start yielding events."""
response = cast(RTMStart, await self.api("rtm.start"))
self.me = Auto.generate(response.self_, "Me", recursive=False)
self.team = Auto.generate(response.team, "Team", recursiv... | [
"async",
"def",
"rtm",
"(",
"self",
")",
"->",
"AsyncIterator",
"[",
"Event",
"]",
":",
"response",
"=",
"cast",
"(",
"RTMStart",
",",
"await",
"self",
".",
"api",
"(",
"\"rtm.start\"",
")",
")",
"self",
".",
"me",
"=",
"Auto",
".",
"generate",
"(",
... | 42.217391 | 25.869565 |
def get_section_by_url(url,
include_instructor_not_on_time_schedule=True):
"""
Returns a uw_sws.models.Section object
for the passed section url.
"""
if not course_url_pattern.match(url):
raise InvalidSectionURL(url)
return _json_to_section(
get_resource(u... | [
"def",
"get_section_by_url",
"(",
"url",
",",
"include_instructor_not_on_time_schedule",
"=",
"True",
")",
":",
"if",
"not",
"course_url_pattern",
".",
"match",
"(",
"url",
")",
":",
"raise",
"InvalidSectionURL",
"(",
"url",
")",
"return",
"_json_to_section",
"(",... | 32 | 11.230769 |
def getsystemhooks(self, page=1, per_page=20):
"""
Get all system hooks
:param page: Page number
:param per_page: Records per page
:return: list of hooks
"""
data = {'page': page, 'per_page': per_page}
request = requests.get(
self.hook_url, p... | [
"def",
"getsystemhooks",
"(",
"self",
",",
"page",
"=",
"1",
",",
"per_page",
"=",
"20",
")",
":",
"data",
"=",
"{",
"'page'",
":",
"page",
",",
"'per_page'",
":",
"per_page",
"}",
"request",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"hook_url",... | 29.055556 | 15.722222 |
def _validate_iterable(self, is_iterable, key, value):
"""Validate fields with `iterable` key in schema set to True"""
if is_iterable:
try:
iter(value)
except TypeError:
self._error(key, "Must be iterable (e.g. a list or array)") | [
"def",
"_validate_iterable",
"(",
"self",
",",
"is_iterable",
",",
"key",
",",
"value",
")",
":",
"if",
"is_iterable",
":",
"try",
":",
"iter",
"(",
"value",
")",
"except",
"TypeError",
":",
"self",
".",
"_error",
"(",
"key",
",",
"\"Must be iterable (e.g.... | 42.142857 | 16.285714 |
def _RecurseOverObject(obj, factory, parent=None):
"""Recurses over a nested structure to look for changes in Suds objects.
Args:
obj: A parameter for a SOAP request field which is to be inspected and
will be packed for Suds if an xsi_type is specified, otherwise will be
left unaltered.
fac... | [
"def",
"_RecurseOverObject",
"(",
"obj",
",",
"factory",
",",
"parent",
"=",
"None",
")",
":",
"if",
"_IsSudsIterable",
"(",
"obj",
")",
":",
"# Since in-place modification of the Suds object is taking place, the",
"# iterator should be done over a frozen copy of the unpacked f... | 42.833333 | 18.541667 |
def button_clicked(self, button):
"""Action when button was clicked.
Parameters
----------
button : instance of QPushButton
which button was pressed
"""
if button is self.idx_ok:
# File location
if not self.filename:
m... | [
"def",
"button_clicked",
"(",
"self",
",",
"button",
")",
":",
"if",
"button",
"is",
"self",
".",
"idx_ok",
":",
"# File location",
"if",
"not",
"self",
".",
"filename",
":",
"msg",
"=",
"'Select location for data export file.'",
"error_dialog",
"=",
"QErrorMess... | 41.267544 | 21.491228 |
def encode(lng, lat, precision=10, bits_per_char=6):
"""Encode a lng/lat position as a geohash using a hilbert curve
This function encodes a lng/lat coordinate to a geohash of length `precision`
on a corresponding a hilbert curve. Each character encodes `bits_per_char` bits
per character (allowed are 2... | [
"def",
"encode",
"(",
"lng",
",",
"lat",
",",
"precision",
"=",
"10",
",",
"bits_per_char",
"=",
"6",
")",
":",
"assert",
"_LNG_INTERVAL",
"[",
"0",
"]",
"<=",
"lng",
"<=",
"_LNG_INTERVAL",
"[",
"1",
"]",
"assert",
"_LAT_INTERVAL",
"[",
"0",
"]",
"<=... | 40.583333 | 24.972222 |
def transform(self, X=None, y=None):
"""
Transform an image using an Affine transform with the given
shear parameters. Return the transform if X=None.
Arguments
---------
X : ANTsImage
Image to transform
y : ANTsImage (optional)
Another... | [
"def",
"transform",
"(",
"self",
",",
"X",
"=",
"None",
",",
"y",
"=",
"None",
")",
":",
"# convert to radians and unpack",
"shear",
"=",
"[",
"math",
".",
"pi",
"/",
"180",
"*",
"s",
"for",
"s",
"in",
"self",
".",
"shear",
"]",
"shear_x",
",",
"sh... | 35.023256 | 17.953488 |
def parse_param(param, include_desc=False):
"""Parse a single typed parameter statement."""
param_def, _colon, desc = param.partition(':')
if not include_desc:
desc = None
else:
desc = desc.lstrip()
if _colon == "":
raise ValidationError("Invalid parameter declaration in do... | [
"def",
"parse_param",
"(",
"param",
",",
"include_desc",
"=",
"False",
")",
":",
"param_def",
",",
"_colon",
",",
"desc",
"=",
"param",
".",
"partition",
"(",
"':'",
")",
"if",
"not",
"include_desc",
":",
"desc",
"=",
"None",
"else",
":",
"desc",
"=",
... | 40.111111 | 29.166667 |
def get(self, key, default=None):
"""
Retreive a value from the cache. In the event the value
does not exist, return the ``default``.
"""
key = self.make_key(key)
if self.debug:
return default
try:
value = self.database[key]
excep... | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"default",
"=",
"None",
")",
":",
"key",
"=",
"self",
".",
"make_key",
"(",
"key",
")",
"if",
"self",
".",
"debug",
":",
"return",
"default",
"try",
":",
"value",
"=",
"self",
".",
"database",
"[",
"key... | 26.222222 | 13.888889 |
def glob_all(folder: str, filt: str) -> List[str]:
"""Recursive glob"""
import os
import fnmatch
matches = []
for root, dirnames, filenames in os.walk(folder):
for filename in fnmatch.filter(filenames, filt):
matches.append(os.path.join(root, filename))
return matches | [
"def",
"glob_all",
"(",
"folder",
":",
"str",
",",
"filt",
":",
"str",
")",
"->",
"List",
"[",
"str",
"]",
":",
"import",
"os",
"import",
"fnmatch",
"matches",
"=",
"[",
"]",
"for",
"root",
",",
"dirnames",
",",
"filenames",
"in",
"os",
".",
"walk"... | 33.777778 | 16.666667 |
def route_filter_get(name, resource_group, **kwargs):
'''
.. versionadded:: 2019.2.0
Get details about a specific route filter.
:param name: The name of the route table to query.
:param resource_group: The resource group name assigned to the
route filter.
CLI Example:
.. code-bl... | [
"def",
"route_filter_get",
"(",
"name",
",",
"resource_group",
",",
"*",
"*",
"kwargs",
")",
":",
"expand",
"=",
"kwargs",
".",
"get",
"(",
"'expand'",
")",
"netconn",
"=",
"__utils__",
"[",
"'azurearm.get_client'",
"]",
"(",
"'network'",
",",
"*",
"*",
... | 25.5 | 24.558824 |
def set_axes(self, channels, ax):
"""
channels : iterable of string
each value corresponds to a channel names
names must be unique
"""
# To make sure displayed as hist
if len(set(channels)) == 1:
channels = channels[0],
self.current_ch... | [
"def",
"set_axes",
"(",
"self",
",",
"channels",
",",
"ax",
")",
":",
"# To make sure displayed as hist",
"if",
"len",
"(",
"set",
"(",
"channels",
")",
")",
"==",
"1",
":",
"channels",
"=",
"channels",
"[",
"0",
"]",
",",
"self",
".",
"current_channels"... | 30.272727 | 9.545455 |
def requires(self):
""" Index all pages. """
for url in NEWSPAPERS:
yield IndexPage(url=url, date=self.date) | [
"def",
"requires",
"(",
"self",
")",
":",
"for",
"url",
"in",
"NEWSPAPERS",
":",
"yield",
"IndexPage",
"(",
"url",
"=",
"url",
",",
"date",
"=",
"self",
".",
"date",
")"
] | 33.25 | 10.75 |
def mdct(x, L):
"""Modified Discrete Cosine Transform (MDCT)
Returns the Modified Discrete Cosine Transform with fixed
window size L of the signal x.
The window is based on a sine window.
Parameters
----------
x : ndarray, shape (N,)
The signal
L : int
The window lengt... | [
"def",
"mdct",
"(",
"x",
",",
"L",
")",
":",
"x",
"=",
"np",
".",
"asarray",
"(",
"x",
",",
"dtype",
"=",
"np",
".",
"float",
")",
"N",
"=",
"x",
".",
"size",
"# Number of frequency channels",
"K",
"=",
"L",
"//",
"2",
"# Test length",
"if",
"N",... | 20.948718 | 21.217949 |
def run(self, messages):
"""Returns some analytics about this autograder run."""
statistics = {}
statistics['time'] = str(datetime.now())
statistics['time-utc'] = str(datetime.utcnow())
statistics['unlock'] = self.args.unlock
if self.args.question:
statistics... | [
"def",
"run",
"(",
"self",
",",
"messages",
")",
":",
"statistics",
"=",
"{",
"}",
"statistics",
"[",
"'time'",
"]",
"=",
"str",
"(",
"datetime",
".",
"now",
"(",
")",
")",
"statistics",
"[",
"'time-utc'",
"]",
"=",
"str",
"(",
"datetime",
".",
"ut... | 38.833333 | 18.888889 |
def _get_magnitude_scaling_term(self, C, mag):
"""
Returns the magnitude scaling term defined in equation 3
"""
if mag < 6.75:
return C["a1_lo"] + C["a2_lo"] * mag + C["a3"] *\
((8.5 - mag) ** 2.0)
else:
return C["a1_hi"] + C["a2_hi"] * mag... | [
"def",
"_get_magnitude_scaling_term",
"(",
"self",
",",
"C",
",",
"mag",
")",
":",
"if",
"mag",
"<",
"6.75",
":",
"return",
"C",
"[",
"\"a1_lo\"",
"]",
"+",
"C",
"[",
"\"a2_lo\"",
"]",
"*",
"mag",
"+",
"C",
"[",
"\"a3\"",
"]",
"*",
"(",
"(",
"8.5... | 36.1 | 12.5 |
def set_state_from_exit_status(self, status, notif_period, hosts, services):
"""Set the state in UP, WARNING, CRITICAL, UNKNOWN or UNREACHABLE
according to the status of a check result.
:param status: integer between 0 and 4
:type status: int
:return: None
"""
no... | [
"def",
"set_state_from_exit_status",
"(",
"self",
",",
"status",
",",
"notif_period",
",",
"hosts",
",",
"services",
")",
":",
"now",
"=",
"time",
".",
"time",
"(",
")",
"# we should put in last_state the good last state:",
"# if not just change the state by an problem/im... | 41.785714 | 17.671429 |
def _push_textbuffer(self):
"""Push the textbuffer onto the stack as a Text node and clear it."""
if self._textbuffer:
self._stack.append(tokens.Text(text="".join(self._textbuffer)))
self._textbuffer = [] | [
"def",
"_push_textbuffer",
"(",
"self",
")",
":",
"if",
"self",
".",
"_textbuffer",
":",
"self",
".",
"_stack",
".",
"append",
"(",
"tokens",
".",
"Text",
"(",
"text",
"=",
"\"\"",
".",
"join",
"(",
"self",
".",
"_textbuffer",
")",
")",
")",
"self",
... | 48 | 13.4 |
def _get_completions(self):
"""Return a list of possible completions for the string ending at the point.
Also set begidx and endidx in the process."""
completions = []
self.begidx = self.l_buffer.point
self.endidx = self.l_buffer.point
buf=self.l_buffer.line_buffer
... | [
"def",
"_get_completions",
"(",
"self",
")",
":",
"completions",
"=",
"[",
"]",
"self",
".",
"begidx",
"=",
"self",
".",
"l_buffer",
".",
"point",
"self",
".",
"endidx",
"=",
"self",
".",
"l_buffer",
".",
"point",
"buf",
"=",
"self",
".",
"l_buffer",
... | 41.74 | 12.92 |
def delete(
self,
endpoint,
timeout=None,
allow_redirects=None,
validate=True,
headers=None,
):
"""*Sends a DELETE request to the endpoint.*
The endpoint is joined with the URL given on library init (if any).
If endpoint starts with ``http://`... | [
"def",
"delete",
"(",
"self",
",",
"endpoint",
",",
"timeout",
"=",
"None",
",",
"allow_redirects",
"=",
"None",
",",
"validate",
"=",
"True",
",",
"headers",
"=",
"None",
",",
")",
":",
"endpoint",
"=",
"self",
".",
"_input_string",
"(",
"endpoint",
"... | 35.756098 | 24.902439 |
def write(self, data):
'''
Write method used by internal tarfile instance to output data.
This method blocks tarfile execution once internal buffer is full.
As this method is blocking, it is used inside the same thread of
:meth:`fill`.
:param data: bytes to write to int... | [
"def",
"write",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"_add",
".",
"wait",
"(",
")",
"self",
".",
"_data",
"+=",
"data",
"if",
"len",
"(",
"self",
".",
"_data",
")",
">",
"self",
".",
"_want",
":",
"self",
".",
"_add",
".",
"clear",
... | 31.210526 | 20.473684 |
def getItem(self, index, altItem=None):
""" Returns the TreeItem for the given index. Returns the altItem if the index is invalid.
"""
if index.isValid():
item = index.internalPointer()
if item:
return item
#return altItem if altItem is not None e... | [
"def",
"getItem",
"(",
"self",
",",
"index",
",",
"altItem",
"=",
"None",
")",
":",
"if",
"index",
".",
"isValid",
"(",
")",
":",
"item",
"=",
"index",
".",
"internalPointer",
"(",
")",
"if",
"item",
":",
"return",
"item",
"#return altItem if altItem is ... | 37.5 | 15.6 |
def eval(self, now=None):
'''
Evaluate and execute the schedule
:param datetime now: Override current time with a datetime object instance``
'''
log.trace('==== evaluating schedule now %s =====', now)
loop_interval = self.opts['loop_interval']
if not isinstanc... | [
"def",
"eval",
"(",
"self",
",",
"now",
"=",
"None",
")",
":",
"log",
".",
"trace",
"(",
"'==== evaluating schedule now %s ====='",
",",
"now",
")",
"loop_interval",
"=",
"self",
".",
"opts",
"[",
"'loop_interval'",
"]",
"if",
"not",
"isinstance",
"(",
"lo... | 40.53121 | 19.132484 |
def dpar(self, cl=1):
"""Return dpar-style executable assignment for parameter
Default is to write CL version of code; if cl parameter is
false, writes Python executable code instead.
"""
sval = self.toString(self.value, quoted=1)
if not cl:
if sval == "": sv... | [
"def",
"dpar",
"(",
"self",
",",
"cl",
"=",
"1",
")",
":",
"sval",
"=",
"self",
".",
"toString",
"(",
"self",
".",
"value",
",",
"quoted",
"=",
"1",
")",
"if",
"not",
"cl",
":",
"if",
"sval",
"==",
"\"\"",
":",
"sval",
"=",
"\"None\"",
"s",
"... | 34.545455 | 14.090909 |
def load_modules_from_python(self, route_list):
"""Load modules from the native python source."""
for name, modpath in route_list:
if ':' in modpath:
path, attr = modpath.split(':', 1)
else:
path, attr = modpath, None
self.commands[name... | [
"def",
"load_modules_from_python",
"(",
"self",
",",
"route_list",
")",
":",
"for",
"name",
",",
"modpath",
"in",
"route_list",
":",
"if",
"':'",
"in",
"modpath",
":",
"path",
",",
"attr",
"=",
"modpath",
".",
"split",
"(",
"':'",
",",
"1",
")",
"else"... | 43.25 | 9.375 |
def get_parent_dir(name):
"""Get the parent directory of a filename."""
parent_dir = os.path.dirname(os.path.dirname(name))
if parent_dir:
return parent_dir
return os.path.abspath('.') | [
"def",
"get_parent_dir",
"(",
"name",
")",
":",
"parent_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"name",
")",
")",
"if",
"parent_dir",
":",
"return",
"parent_dir",
"return",
"os",
".",
"path",
".",
"a... | 33.833333 | 12.666667 |
def get_machine_group_applied_configs(self, project_name, group_name):
""" get the logtail config names applied in a machine group
Unsuccessful opertaion will cause an LogException.
:type project_name: string
:param project_name: the Project name
:type group_name: strin... | [
"def",
"get_machine_group_applied_configs",
"(",
"self",
",",
"project_name",
",",
"group_name",
")",
":",
"headers",
"=",
"{",
"}",
"params",
"=",
"{",
"}",
"resource",
"=",
"\"/machinegroups/\"",
"+",
"group_name",
"+",
"\"/configs\"",
"(",
"resp",
",",
"hea... | 36.35 | 21.25 |
def get_hash(path, hash_alg="sha256"):
"""Get the hash of the file at ``path``.
I'd love to make this async, but evidently file i/o is always ready
Args:
path (str): the path to the file to hash.
hash_alg (str, optional): the algorithm to use. Defaults to 'sha256'.
Returns:
s... | [
"def",
"get_hash",
"(",
"path",
",",
"hash_alg",
"=",
"\"sha256\"",
")",
":",
"h",
"=",
"hashlib",
".",
"new",
"(",
"hash_alg",
")",
"with",
"open",
"(",
"path",
",",
"\"rb\"",
")",
"as",
"f",
":",
"for",
"chunk",
"in",
"iter",
"(",
"functools",
".... | 29 | 20.722222 |
def create(self,params=None, headers=None):
"""Create a creditor bank account.
Creates a new creditor bank account object.
Args:
params (dict, optional): Request body.
Returns:
ListResponse of CreditorBankAccount instances
"""
path = '/credi... | [
"def",
"create",
"(",
"self",
",",
"params",
"=",
"None",
",",
"headers",
"=",
"None",
")",
":",
"path",
"=",
"'/creditor_bank_accounts'",
"if",
"params",
"is",
"not",
"None",
":",
"params",
"=",
"{",
"self",
".",
"_envelope_key",
"(",
")",
":",
"param... | 33.916667 | 18.458333 |
def save_xml(self, doc, element):
'''Save this configuration set into an xml.dom.Element object.'''
element.setAttributeNS(RTS_NS, RTS_NS_S + 'id', self.id)
for c in self._config_data:
new_element = doc.createElementNS(RTS_NS,
RTS_NS_S + ... | [
"def",
"save_xml",
"(",
"self",
",",
"doc",
",",
"element",
")",
":",
"element",
".",
"setAttributeNS",
"(",
"RTS_NS",
",",
"RTS_NS_S",
"+",
"'id'",
",",
"self",
".",
"id",
")",
"for",
"c",
"in",
"self",
".",
"_config_data",
":",
"new_element",
"=",
... | 52.375 | 15.375 |
def find_endurance_tier_iops_per_gb(volume):
"""Find the tier for the given endurance volume (IOPS per GB)
:param volume: The volume for which the tier level is desired
:return: Returns a float value indicating the IOPS per GB for the volume
"""
tier = volume['storageTierLevel']
iops_per_gb = 0... | [
"def",
"find_endurance_tier_iops_per_gb",
"(",
"volume",
")",
":",
"tier",
"=",
"volume",
"[",
"'storageTierLevel'",
"]",
"iops_per_gb",
"=",
"0.25",
"if",
"tier",
"==",
"\"LOW_INTENSITY_TIER\"",
":",
"iops_per_gb",
"=",
"0.25",
"elif",
"tier",
"==",
"\"READHEAVY_... | 31.285714 | 17.857143 |
def heuristic_search(graph, start, goal, heuristic):
"""
A* search algorithm.
A set of heuristics is available under C{graph.algorithms.heuristics}. User-created heuristics
are allowed too.
@type graph: graph, digraph
@param graph: Graph
@type start: node
@param start: Sta... | [
"def",
"heuristic_search",
"(",
"graph",
",",
"start",
",",
"goal",
",",
"heuristic",
")",
":",
"# The queue stores priority, node, cost to reach, and parent.",
"queue",
"=",
"[",
"(",
"0",
",",
"start",
",",
"0",
",",
"None",
")",
"]",
"# This dictionary maps que... | 29.852941 | 22 |
def merge_pdfs(pdf_filepaths, out_filepath):
""" Merge all the PDF files in `pdf_filepaths` in a new PDF file `out_filepath`.
Parameters
----------
pdf_filepaths: list of str
Paths to PDF files.
out_filepath: str
Path to the result PDF file.
Returns
-------
path: str
... | [
"def",
"merge_pdfs",
"(",
"pdf_filepaths",
",",
"out_filepath",
")",
":",
"merger",
"=",
"PdfFileMerger",
"(",
")",
"for",
"pdf",
"in",
"pdf_filepaths",
":",
"merger",
".",
"append",
"(",
"PdfFileReader",
"(",
"open",
"(",
"pdf",
",",
"'rb'",
")",
")",
"... | 21.913043 | 20.043478 |
def emit(signal, *args, **kwargs):
"""
Emits a single signal to call callbacks registered to respond to that signal.
Optionally accepts args and kwargs that are passed directly to callbacks.
:param signal: Signal to send
"""
for callback in set(receivers[signal]): # Make a copy in case of any ... | [
"def",
"emit",
"(",
"signal",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"callback",
"in",
"set",
"(",
"receivers",
"[",
"signal",
"]",
")",
":",
"# Make a copy in case of any ninja signals",
"_call",
"(",
"callback",
",",
"args",
"=",
"... | 41.666667 | 20.777778 |
def mcp_als(X, rank, mask, random_state=None, init='randn', **options):
"""Fits CP Decomposition with missing data using Alternating Least Squares (ALS).
Parameters
----------
X : (I_1, ..., I_N) array_like
A tensor with ``X.ndim >= 3``.
rank : integer
The `rank` sets the number of... | [
"def",
"mcp_als",
"(",
"X",
",",
"rank",
",",
"mask",
",",
"random_state",
"=",
"None",
",",
"init",
"=",
"'randn'",
",",
"*",
"*",
"options",
")",
":",
"# Check inputs.",
"optim_utils",
".",
"_check_cpd_inputs",
"(",
"X",
",",
"rank",
")",
"# Initialize... | 37.348214 | 25.491071 |
def com_google_fonts_check_name_familyname_first_char(ttFont):
"""Make sure family name does not begin with a digit.
Font family names which start with a numeral are often not
discoverable in Windows applications.
"""
from fontbakery.utils import get_name_entry_strings
failed = False
for familyname... | [
"def",
"com_google_fonts_check_name_familyname_first_char",
"(",
"ttFont",
")",
":",
"from",
"fontbakery",
".",
"utils",
"import",
"get_name_entry_strings",
"failed",
"=",
"False",
"for",
"familyname",
"in",
"get_name_entry_strings",
"(",
"ttFont",
",",
"NameID",
".",
... | 40.5 | 16.5 |
def _candidate_tempdir_list():
"""Generate a list of candidate temporary directories which
_get_default_tempdir will try."""
dirlist = []
# First, try the environment.
for envname in 'TMPDIR', 'TEMP', 'TMP':
dirname = _os.getenv(envname)
if dirname: dirlist.append(dirname)
# F... | [
"def",
"_candidate_tempdir_list",
"(",
")",
":",
"dirlist",
"=",
"[",
"]",
"# First, try the environment.",
"for",
"envname",
"in",
"'TMPDIR'",
",",
"'TEMP'",
",",
"'TMP'",
":",
"dirname",
"=",
"_os",
".",
"getenv",
"(",
"envname",
")",
"if",
"dirname",
":",... | 28.583333 | 17.583333 |
def apply_transformation(self, structure, return_ranked_list=False):
"""
Args:
structure (Structure): Input structure to dope
Returns:
[{"structure": Structure, "energy": float}]
"""
comp = structure.composition
logger.info("Composition: %s" % com... | [
"def",
"apply_transformation",
"(",
"self",
",",
"structure",
",",
"return_ranked_list",
"=",
"False",
")",
":",
"comp",
"=",
"structure",
".",
"composition",
"logger",
".",
"info",
"(",
"\"Composition: %s\"",
"%",
"comp",
")",
"for",
"sp",
"in",
"comp",
":"... | 46.188406 | 19.753623 |
def tsallis(alphas, Ks, dim, required, clamp=True, to_self=False):
r'''
Estimate the Tsallis-alpha divergence between distributions, based on kNN
distances: (\int p^alpha q^(1-\alpha) - 1) / (\alpha - 1)
If clamp (the default), enforces the estimate is nonnegative.
Returns an array of shape (num_... | [
"def",
"tsallis",
"(",
"alphas",
",",
"Ks",
",",
"dim",
",",
"required",
",",
"clamp",
"=",
"True",
",",
"to_self",
"=",
"False",
")",
":",
"alphas",
"=",
"np",
".",
"reshape",
"(",
"alphas",
",",
"(",
"-",
"1",
",",
"1",
")",
")",
"alpha_est",
... | 29.764706 | 24.470588 |
def get_lr(lr, epoch, steps, factor):
"""Get learning rate based on schedule."""
for s in steps:
if epoch >= s:
lr *= factor
return lr | [
"def",
"get_lr",
"(",
"lr",
",",
"epoch",
",",
"steps",
",",
"factor",
")",
":",
"for",
"s",
"in",
"steps",
":",
"if",
"epoch",
">=",
"s",
":",
"lr",
"*=",
"factor",
"return",
"lr"
] | 26.833333 | 14.166667 |
def validate_ipv6(self, id_vlan):
"""Validates ACL - IPv6 of VLAN from its identifier.
Assigns 1 to 'acl_valida_v6'.
:param id_vlan: Identifier of the Vlan. Integer value and greater than zero.
:return: None
:raise InvalidParameterError: Vlan identifier is null and invalid.
... | [
"def",
"validate_ipv6",
"(",
"self",
",",
"id_vlan",
")",
":",
"if",
"not",
"is_valid_int_param",
"(",
"id_vlan",
")",
":",
"raise",
"InvalidParameterError",
"(",
"u'The identifier of Vlan is invalid or was not informed.'",
")",
"url",
"=",
"'vlan/'",
"+",
"str",
"(... | 35.041667 | 24.583333 |
def flatten(self, D):
'''flatten a nested dictionary D to a flat dictionary
nested keys are separated by '.'
'''
if not isinstance(D, dict):
return D
result = {}
for k,v in D.items():
if isinstance(v, dict):
for _k,_v in self.fla... | [
"def",
"flatten",
"(",
"self",
",",
"D",
")",
":",
"if",
"not",
"isinstance",
"(",
"D",
",",
"dict",
")",
":",
"return",
"D",
"result",
"=",
"{",
"}",
"for",
"k",
",",
"v",
"in",
"D",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"v",... | 25.882353 | 19.176471 |
def flushOutBoxes(self) -> None:
"""
Clear the outBoxes and transmit batched messages to remotes.
"""
removedRemotes = []
for rid, msgs in self.outBoxes.items():
try:
dest = self.remotes[rid].name
except KeyError:
removedRem... | [
"def",
"flushOutBoxes",
"(",
"self",
")",
"->",
"None",
":",
"removedRemotes",
"=",
"[",
"]",
"for",
"rid",
",",
"msgs",
"in",
"self",
".",
"outBoxes",
".",
"items",
"(",
")",
":",
"try",
":",
"dest",
"=",
"self",
".",
"remotes",
"[",
"rid",
"]",
... | 47.155172 | 16.775862 |
def get_asset_content_lookup_session_for_repository(self, repository_id=None):
"""Gets the ``OsidSession`` associated with the asset content lookup service for
the given repository.
arg: repository_id (osid.id.Id): the ``Id`` of the repository
return: (osid.repository.AssetLookupSess... | [
"def",
"get_asset_content_lookup_session_for_repository",
"(",
"self",
",",
"repository_id",
"=",
"None",
")",
":",
"return",
"AssetContentLookupSession",
"(",
"self",
".",
"_provider_manager",
".",
"get_asset_content_lookup_session_for_repository",
"(",
"repository_id",
")",... | 50.5 | 20.05 |
def bulk_copy(self, ids):
"""Bulk copy a set of configs.
:param ids: Int list of config IDs.
:return: :class:`configs.Config <configs.Config>` list
"""
schema = self.GET_SCHEMA
return self.service.bulk_copy(self.base, self.RESOURCE, ids, schema) | [
"def",
"bulk_copy",
"(",
"self",
",",
"ids",
")",
":",
"schema",
"=",
"self",
".",
"GET_SCHEMA",
"return",
"self",
".",
"service",
".",
"bulk_copy",
"(",
"self",
".",
"base",
",",
"self",
".",
"RESOURCE",
",",
"ids",
",",
"schema",
")"
] | 35.875 | 15.5 |
def p_file_project(self, project):
"""Helper function for parsing doap:project name and homepage.
and setting them using the file builder.
"""
for _, _, name in self.graph.triples((project, self.doap_namespace['name'], None)):
self.builder.set_file_atrificat_of_project(self.d... | [
"def",
"p_file_project",
"(",
"self",
",",
"project",
")",
":",
"for",
"_",
",",
"_",
",",
"name",
"in",
"self",
".",
"graph",
".",
"triples",
"(",
"(",
"project",
",",
"self",
".",
"doap_namespace",
"[",
"'name'",
"]",
",",
"None",
")",
")",
":",
... | 61.666667 | 22.888889 |
def convert_linear_problem_to_dual(model, sloppy=False, infinity=None, maintain_standard_form=True, prefix="dual_", dual_model=None): # NOQA
"""
A mathematical optimization problem can be viewed as a primal and a dual problem. If the primal problem is
a minimization problem the dual is a maximization probl... | [
"def",
"convert_linear_problem_to_dual",
"(",
"model",
",",
"sloppy",
"=",
"False",
",",
"infinity",
"=",
"None",
",",
"maintain_standard_form",
"=",
"True",
",",
"prefix",
"=",
"\"dual_\"",
",",
"dual_model",
"=",
"None",
")",
":",
"# NOQA",
"if",
"dual_model... | 50.422222 | 29.266667 |
def text(cls, text, *, resize=None, single_use=None, selective=None):
"""
Creates a new button with the given text.
Args:
resize (`bool`):
If present, the entire keyboard will be reconfigured to
be resized and be smaller if there are not many buttons.... | [
"def",
"text",
"(",
"cls",
",",
"text",
",",
"*",
",",
"resize",
"=",
"None",
",",
"single_use",
"=",
"None",
",",
"selective",
"=",
"None",
")",
":",
"return",
"cls",
"(",
"types",
".",
"KeyboardButton",
"(",
"text",
")",
",",
"resize",
"=",
"resi... | 44.619048 | 24.142857 |
def _json_safe(cls, value):
"""Return a JSON safe value"""
# Date
if type(value) == date:
return str(value)
# Datetime
elif type(value) == datetime:
return value.strftime('%Y-%m-%d %H:%M:%S')
# Object Id
elif isinstance(value, ObjectId):
... | [
"def",
"_json_safe",
"(",
"cls",
",",
"value",
")",
":",
"# Date",
"if",
"type",
"(",
"value",
")",
"==",
"date",
":",
"return",
"str",
"(",
"value",
")",
"# Datetime",
"elif",
"type",
"(",
"value",
")",
"==",
"datetime",
":",
"return",
"value",
".",... | 25.666667 | 18.925926 |
def ycoord(self):
"""The y coordinate :class:`xarray.Variable`"""
v = next(self.raw_data.psy.iter_base_variables)
return self.decoder.get_y(v, coords=self.data.coords) | [
"def",
"ycoord",
"(",
"self",
")",
":",
"v",
"=",
"next",
"(",
"self",
".",
"raw_data",
".",
"psy",
".",
"iter_base_variables",
")",
"return",
"self",
".",
"decoder",
".",
"get_y",
"(",
"v",
",",
"coords",
"=",
"self",
".",
"data",
".",
"coords",
"... | 47 | 14.75 |
def rank_targets(sample_frame, ref_targets, ref_sample):
"""Uses the geNorm algorithm to determine the most stably expressed
genes from amongst ref_targets in your sample.
See Vandesompele et al.'s 2002 Genome Biology paper for information about
the algorithm: http://dx.doi.org/10.1186/gb-2002-3-7-rese... | [
"def",
"rank_targets",
"(",
"sample_frame",
",",
"ref_targets",
",",
"ref_sample",
")",
":",
"table",
"=",
"collect_expression",
"(",
"sample_frame",
",",
"ref_targets",
",",
"ref_sample",
")",
"all_samples",
"=",
"sample_frame",
"[",
"'Sample'",
"]",
".",
"uniq... | 43.380952 | 19.52381 |
def _convert_from_pandas(self, pdf, schema, timezone):
"""
Convert a pandas.DataFrame to list of records that can be used to make a DataFrame
:return list of records
"""
if timezone is not None:
from pyspark.sql.types import _check_series_convert_timestamps_tz_local... | [
"def",
"_convert_from_pandas",
"(",
"self",
",",
"pdf",
",",
"schema",
",",
"timezone",
")",
":",
"if",
"timezone",
"is",
"not",
"None",
":",
"from",
"pyspark",
".",
"sql",
".",
"types",
"import",
"_check_series_convert_timestamps_tz_local",
"copied",
"=",
"Fa... | 49.47619 | 19.904762 |
def __quarters(self, from_date=None):
"""Get a set of quarters with available items from a given index date.
:param from_date:
:return: list of `pandas.Period` corresponding to quarters
"""
s = Search(using=self._es_conn, index=self._es_index)
if from_date:
#... | [
"def",
"__quarters",
"(",
"self",
",",
"from_date",
"=",
"None",
")",
":",
"s",
"=",
"Search",
"(",
"using",
"=",
"self",
".",
"_es_conn",
",",
"index",
"=",
"self",
".",
"_es_index",
")",
"if",
"from_date",
":",
"# Work around to solve conversion problem of... | 36.538462 | 22.115385 |
def Length(min=None, max=None, min_message="Must have a length of at least {min}", max_message="Must have a length of at most {max}"):
"""
Creates a validator that checks if the given value's length is in the
specified range, inclusive. (Returns the original value.)
See :func:`.Range`.
"""
vali... | [
"def",
"Length",
"(",
"min",
"=",
"None",
",",
"max",
"=",
"None",
",",
"min_message",
"=",
"\"Must have a length of at least {min}\"",
",",
"max_message",
"=",
"\"Must have a length of at most {max}\"",
")",
":",
"validator",
"=",
"Range",
"(",
"min",
",",
"max",... | 37.066667 | 21.866667 |
def initializer(func):
"""
Automatically assigns the parameters.
http://stackoverflow.com/questions/1389180/python-automatically-initialize-instance-variables
>>> class process:
... @initializer
... def __init__(self, cmd, reachable=False, user='root'):
... pass
>>> p = ... | [
"def",
"initializer",
"(",
"func",
")",
":",
"names",
",",
"varargs",
",",
"keywords",
",",
"defaults",
"=",
"inspect",
".",
"getargspec",
"(",
"func",
")",
"from",
"functools",
"import",
"wraps",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
... | 33.387097 | 19.258065 |
def _generic_callable(group_idx, a, size, fill_value, dtype=None,
func=lambda g: g, **kwargs):
"""groups a by inds, and then applies foo to each group in turn, placing
the results in an array."""
groups = _array(group_idx, a, size, ())
ret = np.full(size, fill_value, dtype=dtype or... | [
"def",
"_generic_callable",
"(",
"group_idx",
",",
"a",
",",
"size",
",",
"fill_value",
",",
"dtype",
"=",
"None",
",",
"func",
"=",
"lambda",
"g",
":",
"g",
",",
"*",
"*",
"kwargs",
")",
":",
"groups",
"=",
"_array",
"(",
"group_idx",
",",
"a",
",... | 41.181818 | 13.272727 |
def unpack(fmt, data, endian=None, target=None):
"""
Unpack the string (presumably packed by pack(fmt, ...)) according to the
given format. The actual unpacking is performed by ``struct.unpack``
but the byte order will be set according to the given `endian`, `target`
or byte order of the global targ... | [
"def",
"unpack",
"(",
"fmt",
",",
"data",
",",
"endian",
"=",
"None",
",",
"target",
"=",
"None",
")",
":",
"endian",
"=",
"endian",
"if",
"endian",
"is",
"not",
"None",
"else",
"target",
".",
"endian",
"if",
"target",
"is",
"not",
"None",
"else",
... | 43.5 | 22.3 |
def kwargs_from_keyword(from_kwargs,to_kwargs,keyword,clean_origin=True):
"""
Looks for keys of the format keyword_value.
And return a dictionary with {keyword:value} format
Parameters:
-----------
from_kwargs : dict
Original dictionary
to_kwargs : dict
Dictionary where the items will be appended
key... | [
"def",
"kwargs_from_keyword",
"(",
"from_kwargs",
",",
"to_kwargs",
",",
"keyword",
",",
"clean_origin",
"=",
"True",
")",
":",
"for",
"k",
"in",
"list",
"(",
"from_kwargs",
".",
"keys",
"(",
")",
")",
":",
"if",
"'{0}_'",
".",
"format",
"(",
"keyword",
... | 28.652174 | 16.652174 |
def _tokenize(self, text):
"""Tokenize the text into a list of sentences with a list of words.
:param text: raw text
:return: tokenized text
:rtype : list
"""
sentences = []
tokens = []
for word in self._clean_accents(text).split(' '):
tokens.... | [
"def",
"_tokenize",
"(",
"self",
",",
"text",
")",
":",
"sentences",
"=",
"[",
"]",
"tokens",
"=",
"[",
"]",
"for",
"word",
"in",
"self",
".",
"_clean_accents",
"(",
"text",
")",
".",
"split",
"(",
"' '",
")",
":",
"tokens",
".",
"append",
"(",
"... | 29.333333 | 13.333333 |
def _get_efron_values_single(self, X, T, E, weights, beta):
"""
Calculates the first and second order vector differentials, with respect to beta.
Note that X, T, E are assumed to be sorted on T!
A good explanation for Efron. Consider three of five subjects who fail at the time.
... | [
"def",
"_get_efron_values_single",
"(",
"self",
",",
"X",
",",
"T",
",",
"E",
",",
"weights",
",",
"beta",
")",
":",
"n",
",",
"d",
"=",
"X",
".",
"shape",
"hessian",
"=",
"np",
".",
"zeros",
"(",
"(",
"d",
",",
"d",
")",
")",
"gradient",
"=",
... | 37.126984 | 22.142857 |
def GetRootFileEntry(self):
"""Retrieves the root file entry.
Returns:
CPIOFileEntry: a file entry or None if not available.
"""
path_spec = cpio_path_spec.CPIOPathSpec(
location=self.LOCATION_ROOT, parent=self._path_spec.parent)
return self.GetFileEntryByPathSpec(path_spec) | [
"def",
"GetRootFileEntry",
"(",
"self",
")",
":",
"path_spec",
"=",
"cpio_path_spec",
".",
"CPIOPathSpec",
"(",
"location",
"=",
"self",
".",
"LOCATION_ROOT",
",",
"parent",
"=",
"self",
".",
"_path_spec",
".",
"parent",
")",
"return",
"self",
".",
"GetFileE... | 33.555556 | 15.555556 |
def finder(target, matchlist, foldermode=0, regex=False, recursive=True):
"""
function for finding files/folders in folders and their subdirectories
Parameters
----------
target: str or list of str
a directory, zip- or tar-archive or a list of them to be searched
matchlist: list
... | [
"def",
"finder",
"(",
"target",
",",
"matchlist",
",",
"foldermode",
"=",
"0",
",",
"regex",
"=",
"False",
",",
"recursive",
"=",
"True",
")",
":",
"if",
"foldermode",
"not",
"in",
"[",
"0",
",",
"1",
",",
"2",
"]",
":",
"raise",
"ValueError",
"(",... | 38.581633 | 21.112245 |
def build_command_groups(self, block):
"""
Creates block modification commands, grouped by start index,
with the text to apply them on.
"""
text = block['text']
commands = sorted(self.build_commands(block))
grouped = groupby(commands, Command.key)
listed ... | [
"def",
"build_command_groups",
"(",
"self",
",",
"block",
")",
":",
"text",
"=",
"block",
"[",
"'text'",
"]",
"commands",
"=",
"sorted",
"(",
"self",
".",
"build_commands",
"(",
"block",
")",
")",
"grouped",
"=",
"groupby",
"(",
"commands",
",",
"Command... | 32.590909 | 18.136364 |
def mail2blogger(entry, **kwargs):
"""This signal handler cross-posts published ``Entry``'s to Blogger. For
this to work, the following settings must be non-False; e.g.:
BLARGG = {
'mail2blogger': True,
'mail2blogger_email': 'user@example.com',
}
"""
enabled = b... | [
"def",
"mail2blogger",
"(",
"entry",
",",
"*",
"*",
"kwargs",
")",
":",
"enabled",
"=",
"blargg_settings",
".",
"get",
"(",
"'mail2blogger'",
",",
"False",
")",
"recipient",
"=",
"blargg_settings",
".",
"get",
"(",
"'mail2blogger_email'",
",",
"None",
")",
... | 35.913043 | 16.652174 |
def download(self, id, attid): # pylint: disable=invalid-name,redefined-builtin
"""Download a device's attachment.
:param id: Device ID as an int.
:param attid: Attachment ID as an int.
:rtype: tuple `(io.BytesIO, 'filename')`
"""
resp = self.service.get_id(self._base(id... | [
"def",
"download",
"(",
"self",
",",
"id",
",",
"attid",
")",
":",
"# pylint: disable=invalid-name,redefined-builtin",
"resp",
"=",
"self",
".",
"service",
".",
"get_id",
"(",
"self",
".",
"_base",
"(",
"id",
")",
",",
"attid",
",",
"params",
"=",
"{",
"... | 40.461538 | 17.923077 |
def getMouse(self):
"""
Waits for a mouse click.
"""
# FIXME: this isn't working during an executing cell
self.mouse_x.value = -1
self.mouse_y.value = -1
while self.mouse_x.value == -1 and self.mouse_y.value == -1:
time.sleep(.1)
return (self.m... | [
"def",
"getMouse",
"(",
"self",
")",
":",
"# FIXME: this isn't working during an executing cell",
"self",
".",
"mouse_x",
".",
"value",
"=",
"-",
"1",
"self",
".",
"mouse_y",
".",
"value",
"=",
"-",
"1",
"while",
"self",
".",
"mouse_x",
".",
"value",
"==",
... | 34.4 | 12.4 |
def _log_players(self, players):
"""
:param players: list of catan.game.Player objects
"""
self._logln('players: {0}'.format(len(players)))
for p in self._players:
self._logln('name: {0}, color: {1}, seat: {2}'.format(p.name, p.color, p.seat)) | [
"def",
"_log_players",
"(",
"self",
",",
"players",
")",
":",
"self",
".",
"_logln",
"(",
"'players: {0}'",
".",
"format",
"(",
"len",
"(",
"players",
")",
")",
")",
"for",
"p",
"in",
"self",
".",
"_players",
":",
"self",
".",
"_logln",
"(",
"'name: ... | 41.285714 | 14.428571 |
def AddStorageMediaImageOptions(self, argument_group):
"""Adds the storage media image options to the argument group.
Args:
argument_group (argparse._ArgumentGroup): argparse argument group.
"""
argument_group.add_argument(
'--partitions', '--partition', dest='partitions', action='store',... | [
"def",
"AddStorageMediaImageOptions",
"(",
"self",
",",
"argument_group",
")",
":",
"argument_group",
".",
"add_argument",
"(",
"'--partitions'",
",",
"'--partition'",
",",
"dest",
"=",
"'partitions'",
",",
"action",
"=",
"'store'",
",",
"type",
"=",
"str",
",",... | 51.826087 | 25.434783 |
def git_versions_from_keywords(keywords, tag_prefix, verbose):
"""Get version information from git keywords."""
if not keywords:
raise NotThisMethod("no keywords at all, weird")
date = keywords.get("date")
if date is not None:
# git-2.2.0 added "%cI", which expands to an ISO-8601 -compli... | [
"def",
"git_versions_from_keywords",
"(",
"keywords",
",",
"tag_prefix",
",",
"verbose",
")",
":",
"if",
"not",
"keywords",
":",
"raise",
"NotThisMethod",
"(",
"\"no keywords at all, weird\"",
")",
"date",
"=",
"keywords",
".",
"get",
"(",
"\"date\"",
")",
"if",... | 51.264151 | 21.075472 |
def send_message(self, peer: Peer, text: str, reply: int=None, link_preview: bool=None,
on_success: callable=None, reply_markup: botapi.ReplyMarkup=None):
"""
Send message to peer.
:param peer: Peer to send message to.
:param text: Text to send.
:param reply:... | [
"def",
"send_message",
"(",
"self",
",",
"peer",
":",
"Peer",
",",
"text",
":",
"str",
",",
"reply",
":",
"int",
"=",
"None",
",",
"link_preview",
":",
"bool",
"=",
"None",
",",
"on_success",
":",
"callable",
"=",
"None",
",",
"reply_markup",
":",
"b... | 48.611111 | 24.722222 |
def register_type_name(t, name):
""" Register a human-friendly name for the given type. This will be used in Invalid errors
:param t: The type to register
:type t: type
:param name: Name for the type
:type name: unicode
"""
assert isinstance(t, type)
assert isinstance(name, unicode)
... | [
"def",
"register_type_name",
"(",
"t",
",",
"name",
")",
":",
"assert",
"isinstance",
"(",
"t",
",",
"type",
")",
"assert",
"isinstance",
"(",
"name",
",",
"unicode",
")",
"__type_names",
"[",
"t",
"]",
"=",
"name"
] | 30.272727 | 11.636364 |
def roll_estimate(RAW_IMU,GPS_RAW_INT=None,ATTITUDE=None,SENSOR_OFFSETS=None, ofs=None, mul=None,smooth=0.7):
'''estimate roll from accelerometer'''
rx = RAW_IMU.xacc * 9.81 / 1000.0
ry = RAW_IMU.yacc * 9.81 / 1000.0
rz = RAW_IMU.zacc * 9.81 / 1000.0
if ATTITUDE is not None and GPS_RAW_INT is not No... | [
"def",
"roll_estimate",
"(",
"RAW_IMU",
",",
"GPS_RAW_INT",
"=",
"None",
",",
"ATTITUDE",
"=",
"None",
",",
"SENSOR_OFFSETS",
"=",
"None",
",",
"ofs",
"=",
"None",
",",
"mul",
"=",
"None",
",",
"smooth",
"=",
"0.7",
")",
":",
"rx",
"=",
"RAW_IMU",
".... | 41.9 | 14.9 |
def reset(self):
"""Attempts to reset the dongle to a known state.
When called, this method will reset the internal state of the object, and
disconnect any active connections.
"""
logger.debug('resetting dongle state')
self._clear()
if self.api is not None:
... | [
"def",
"reset",
"(",
"self",
")",
":",
"logger",
".",
"debug",
"(",
"'resetting dongle state'",
")",
"self",
".",
"_clear",
"(",
")",
"if",
"self",
".",
"api",
"is",
"not",
"None",
":",
"self",
".",
"_set_state",
"(",
"Dongle",
".",
"_STATE_RESET",
")"... | 39.428571 | 24 |
def enriched(self, thresh=0.05, idx=True):
"""
Enriched features.
{threshdoc}
"""
return self.upregulated(thresh=thresh, idx=idx) | [
"def",
"enriched",
"(",
"self",
",",
"thresh",
"=",
"0.05",
",",
"idx",
"=",
"True",
")",
":",
"return",
"self",
".",
"upregulated",
"(",
"thresh",
"=",
"thresh",
",",
"idx",
"=",
"idx",
")"
] | 23.428571 | 13.142857 |
def remove(path, **kwargs):
r'''
Remove the directory from the SYSTEM path
Returns:
boolean True if successful, False if unsuccessful
rehash : True
If the registry was updated, and this value is set to ``True``, sends a
WM_SETTINGCHANGE broadcast to refresh the environment vari... | [
"def",
"remove",
"(",
"path",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"=",
"salt",
".",
"utils",
".",
"args",
".",
"clean_kwargs",
"(",
"*",
"*",
"kwargs",
")",
"rehash_",
"=",
"kwargs",
".",
"pop",
"(",
"'rehash'",
",",
"True",
")",
"if",
"... | 27.364865 | 21.554054 |
def infer_dtype_from_array(arr, pandas_dtype=False):
"""
infer the dtype from a scalar or array
Parameters
----------
arr : scalar or array
pandas_dtype : bool, default False
whether to infer dtype including pandas extension types.
If False, array belongs to pandas extension typ... | [
"def",
"infer_dtype_from_array",
"(",
"arr",
",",
"pandas_dtype",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"arr",
",",
"np",
".",
"ndarray",
")",
":",
"return",
"arr",
".",
"dtype",
",",
"arr",
"if",
"not",
"is_list_like",
"(",
"arr",
")",
":",... | 25.127273 | 19.309091 |
def replace_suffixes_1(self, word):
"""
Find the longest suffix among the ones specified
and perform the required action.
"""
length = len(word)
if word.endswith("sses"):
return word[:-2]
elif word.endswith("ied") or word.endswith("ies"):
... | [
"def",
"replace_suffixes_1",
"(",
"self",
",",
"word",
")",
":",
"length",
"=",
"len",
"(",
"word",
")",
"if",
"word",
".",
"endswith",
"(",
"\"sses\"",
")",
":",
"return",
"word",
"[",
":",
"-",
"2",
"]",
"elif",
"word",
".",
"endswith",
"(",
"\"i... | 30.193548 | 16.645161 |
def extract_pathvars(callback):
'''Extract the path variables from an Resource operation.
Return {'mandatory': [<list-of-pnames>], 'optional': [<list-of-pnames>]}
'''
mandatory = []
optional = []
# We loop on the signature because the order of the parameters is
# important, and signature is... | [
"def",
"extract_pathvars",
"(",
"callback",
")",
":",
"mandatory",
"=",
"[",
"]",
"optional",
"=",
"[",
"]",
"# We loop on the signature because the order of the parameters is",
"# important, and signature is an OrderedDict, while annotations is a",
"# regular dictionary",
"for",
... | 40.68 | 21.4 |
def set_tile(self, row, col, value):
"""
Set the tile at position row, col to have the given value.
"""
#print('set_tile: y=', row, 'x=', col)
if col < 0:
print("ERROR - x less than zero", col)
col = 0
#return
if col > s... | [
"def",
"set_tile",
"(",
"self",
",",
"row",
",",
"col",
",",
"value",
")",
":",
"#print('set_tile: y=', row, 'x=', col)",
"if",
"col",
"<",
"0",
":",
"print",
"(",
"\"ERROR - x less than zero\"",
",",
"col",
")",
"col",
"=",
"0",
"#return",
"if",
"col",
">... | 29.28 | 14.6 |
def handle_provider(self, provider_factory, note):
"""Get value from provider as requested by note."""
# Implementation in separate method to support accurate book-keeping.
basenote, name = self.parse_note(note)
# _handle_provider could be even shorter if
# Injector.apply() work... | [
"def",
"handle_provider",
"(",
"self",
",",
"provider_factory",
",",
"note",
")",
":",
"# Implementation in separate method to support accurate book-keeping.",
"basenote",
",",
"name",
"=",
"self",
".",
"parse_note",
"(",
"note",
")",
"# _handle_provider could be even short... | 40.25641 | 18.641026 |
def get_bounding_box(self, lon, lat, trt=None, mag=None):
"""
Build a bounding box around the given lon, lat by computing the
maximum_distance at the given tectonic region type and magnitude.
:param lon: longitude
:param lat: latitude
:param trt: tectonic region type, po... | [
"def",
"get_bounding_box",
"(",
"self",
",",
"lon",
",",
"lat",
",",
"trt",
"=",
"None",
",",
"mag",
"=",
"None",
")",
":",
"if",
"trt",
"is",
"None",
":",
"# take the greatest integration distance",
"maxdist",
"=",
"max",
"(",
"self",
"(",
"trt",
",",
... | 44.833333 | 15.5 |
def containerIsRunning(name_or_id):
'''Check if container with the given name or ID (str) is running. No side
effects. Idempotent. Returns True if running, False if not.'''
require_str("name_or_id", name_or_id)
try:
container = getContainer(name_or_id)
# Refer to the latest status list ... | [
"def",
"containerIsRunning",
"(",
"name_or_id",
")",
":",
"require_str",
"(",
"\"name_or_id\"",
",",
"name_or_id",
")",
"try",
":",
"container",
"=",
"getContainer",
"(",
"name_or_id",
")",
"# Refer to the latest status list here: https://docs.docker.com/engine/",
"# api/... | 34.3 | 16.3 |
def kindpath(self, kind):
"""Returns a path to the resources for a given input kind.
:param `kind`: The kind of input:
- "ad": Active Directory
- "monitor": Files and directories
- "registry": Windows Registry
- "script": Scripts
- "splun... | [
"def",
"kindpath",
"(",
"self",
",",
"kind",
")",
":",
"if",
"kind",
"==",
"'tcp'",
":",
"return",
"UrlEncoded",
"(",
"'tcp/raw'",
",",
"skip_encode",
"=",
"True",
")",
"elif",
"kind",
"==",
"'splunktcp'",
":",
"return",
"UrlEncoded",
"(",
"'tcp/cooked'",
... | 24.833333 | 20.472222 |
def get(cls, exp, files=None):
"""
:param str|unicode exp: Haskell expression to evaluate.
:param dict[str|unicode, str|unicode] files: Dictionary of file names->contents
:rtype: TryHaskell.Result
"""
return cls.parse(cls.raw(exp, files=files)) | [
"def",
"get",
"(",
"cls",
",",
"exp",
",",
"files",
"=",
"None",
")",
":",
"return",
"cls",
".",
"parse",
"(",
"cls",
".",
"raw",
"(",
"exp",
",",
"files",
"=",
"files",
")",
")"
] | 40.857143 | 14 |
def Array(dtype, size=None, ref=False):
"""Factory function that creates typed Array or ArrayRef objects
dtype - the data type of the array (as string).
Supported types are: Byte, Int16, UInt16, Int32, UInt32, Int64, UInt64, Real32, Real64
size - the size of the array. Must be positive integer.
"""
def... | [
"def",
"Array",
"(",
"dtype",
",",
"size",
"=",
"None",
",",
"ref",
"=",
"False",
")",
":",
"def",
"getArrayType",
"(",
"self",
")",
":",
"\"\"\"A little function to replace the getType() method of arrays\n\n It returns a string representation of the array element type ins... | 27.657895 | 21.5 |
def SetPassword(self,password):
"""Request change of password.
The API request requires supplying the current password. For this we issue a call
to retrieve the credentials so note there will be an activity log for retrieving the
credentials associated with any SetPassword entry
>>> s.SetPassword("newpassw... | [
"def",
"SetPassword",
"(",
"self",
",",
"password",
")",
":",
"# 0: {op: \"set\", member: \"password\", value: {current: \" r`5Mun/vT:qZ]2?z\", password: \"Savvis123!\"}}",
"if",
"self",
".",
"data",
"[",
"'status'",
"]",
"!=",
"\"active\"",
":",
"raise",
"(",
"clc",
".",... | 46.526316 | 34.052632 |
def revoke_cert(
ca_name,
CN,
cacert_path=None,
ca_filename=None,
cert_path=None,
cert_filename=None,
crl_file=None,
digest='sha256',
):
'''
Revoke a certificate.
.. versionadded:: 2015.8.0
ca_name
Name of the CA.
CN
... | [
"def",
"revoke_cert",
"(",
"ca_name",
",",
"CN",
",",
"cacert_path",
"=",
"None",
",",
"ca_filename",
"=",
"None",
",",
"cert_path",
"=",
"None",
",",
"cert_filename",
"=",
"None",
",",
"crl_file",
"=",
"None",
",",
"digest",
"=",
"'sha256'",
",",
")",
... | 30.424581 | 20.703911 |
def retrieve_descriptor(descriptor):
"""Retrieve descriptor.
"""
the_descriptor = descriptor
if the_descriptor is None:
the_descriptor = {}
if isinstance(the_descriptor, six.string_types):
try:
if os.path.isfile(the_descriptor):
with open(the_descriptor,... | [
"def",
"retrieve_descriptor",
"(",
"descriptor",
")",
":",
"the_descriptor",
"=",
"descriptor",
"if",
"the_descriptor",
"is",
"None",
":",
"the_descriptor",
"=",
"{",
"}",
"if",
"isinstance",
"(",
"the_descriptor",
",",
"six",
".",
"string_types",
")",
":",
"t... | 39.684211 | 19.315789 |
def findkey(d, *keys):
"""
Get a value from a dictionary based on a list of keys and/or list indexes.
Parameters
----------
d: dict
A Python dictionary
keys: list
A list of key names, or list indexes
Returns
-------
dict
The composite dictionary object at ... | [
"def",
"findkey",
"(",
"d",
",",
"*",
"keys",
")",
":",
"if",
"keys",
":",
"keys",
"=",
"list",
"(",
"keys",
")",
"key",
"=",
"keys",
".",
"pop",
"(",
"0",
")",
"return",
"findkey",
"(",
"d",
"[",
"key",
"]",
",",
"*",
"keys",
")",
"else",
... | 19.9375 | 23.395833 |
def markVisibilityOfSignals(ctx, ctxName, signals, interfaceSignals):
"""
* check if all signals are driven by something
* mark signals with hidden = False if they are connecting statements
or if they are external interface
"""
for sig in signals:
driver_cnt = len(sig.drivers)
... | [
"def",
"markVisibilityOfSignals",
"(",
"ctx",
",",
"ctxName",
",",
"signals",
",",
"interfaceSignals",
")",
":",
"for",
"sig",
"in",
"signals",
":",
"driver_cnt",
"=",
"len",
"(",
"sig",
".",
"drivers",
")",
"has_comb_driver",
"=",
"False",
"if",
"driver_cnt... | 38.52381 | 14.142857 |
def _iterate_rules(rules, topology, max_iter):
"""Iteratively run all the rules until the white- and backlists converge.
Parameters
----------
rules : dict
A dictionary mapping rule names (typically atomtype names) to
SMARTSGraphs that evaluate those rules.
topology : simtk.openmm.a... | [
"def",
"_iterate_rules",
"(",
"rules",
",",
"topology",
",",
"max_iter",
")",
":",
"atoms",
"=",
"list",
"(",
"topology",
".",
"atoms",
"(",
")",
")",
"for",
"_",
"in",
"range",
"(",
"max_iter",
")",
":",
"max_iter",
"-=",
"1",
"found_something",
"=",
... | 35.034483 | 14.965517 |
def executable_path(conn, executable):
"""
Remote validator that accepts a connection object to ensure that a certain
executable is available returning its full path if so.
Otherwise an exception with thorough details will be raised, informing the
user that the executable was not found.
"""
... | [
"def",
"executable_path",
"(",
"conn",
",",
"executable",
")",
":",
"executable_path",
"=",
"conn",
".",
"remote_module",
".",
"which",
"(",
"executable",
")",
"if",
"not",
"executable_path",
":",
"raise",
"ExecutableNotFound",
"(",
"executable",
",",
"conn",
... | 39.916667 | 16.916667 |
def chunk_count(self):
"""Return a count of the chunks in this world folder."""
c = 0
for r in self.iter_regions():
c += r.chunk_count()
return c | [
"def",
"chunk_count",
"(",
"self",
")",
":",
"c",
"=",
"0",
"for",
"r",
"in",
"self",
".",
"iter_regions",
"(",
")",
":",
"c",
"+=",
"r",
".",
"chunk_count",
"(",
")",
"return",
"c"
] | 30.666667 | 13.333333 |
def strip_output(nb):
"""
strip the outputs from a notebook object
"""
for cell in nb.worksheets[0].cells:
if 'outputs' in cell:
cell['outputs'] = []
if 'prompt_number' in cell:
cell['prompt_number'] = None
return nb | [
"def",
"strip_output",
"(",
"nb",
")",
":",
"for",
"cell",
"in",
"nb",
".",
"worksheets",
"[",
"0",
"]",
".",
"cells",
":",
"if",
"'outputs'",
"in",
"cell",
":",
"cell",
"[",
"'outputs'",
"]",
"=",
"[",
"]",
"if",
"'prompt_number'",
"in",
"cell",
"... | 26.7 | 7.5 |
def get_friend_info(self):
"""Return information about this friend, including personal notes.
The personal note can be added or overwritten with :meth:friend, but
only if the user has reddit Gold.
:returns: The json response from the server.
"""
url = self.reddit_s... | [
"def",
"get_friend_info",
"(",
"self",
")",
":",
"url",
"=",
"self",
".",
"reddit_session",
".",
"config",
"[",
"'friend_v1'",
"]",
".",
"format",
"(",
"user",
"=",
"self",
".",
"name",
")",
"data",
"=",
"{",
"'id'",
":",
"self",
".",
"name",
"}",
... | 39.083333 | 22.333333 |
def Page_setDocumentContent(self, frameId, html):
"""
Function path: Page.setDocumentContent
Domain: Page
Method name: setDocumentContent
WARNING: This function is marked 'Experimental'!
Parameters:
Required arguments:
'frameId' (type: FrameId) -> Frame id to set HTML for.
'html' (ty... | [
"def",
"Page_setDocumentContent",
"(",
"self",
",",
"frameId",
",",
"html",
")",
":",
"assert",
"isinstance",
"(",
"html",
",",
"(",
"str",
",",
")",
")",
",",
"\"Argument 'html' must be of type '['str']'. Received type: '%s'\"",
"%",
"type",
"(",
"html",
")",
"... | 30.590909 | 18.5 |
def get_modelnames() -> List[str]:
"""Return a sorted |list| containing all application model names.
>>> from hydpy.auxs.xmltools import XSDWriter
>>> print(XSDWriter.get_modelnames()) # doctest: +ELLIPSIS
[...'dam_v001', 'dam_v002', 'dam_v003', 'dam_v004', 'dam_v005',...]
""... | [
"def",
"get_modelnames",
"(",
")",
"->",
"List",
"[",
"str",
"]",
":",
"return",
"sorted",
"(",
"str",
"(",
"fn",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
")",
"for",
"fn",
"in",
"os",
".",
"listdir",
"(",
"models",
".",
"__path__",
"[",
"... | 49.2 | 18 |
def _finish(self):
"""
Closes and waits for subprocess to exit.
"""
if self._process.returncode is None:
self._process.stdin.flush()
self._process.stdin.close()
self._process.wait()
self.closed = True | [
"def",
"_finish",
"(",
"self",
")",
":",
"if",
"self",
".",
"_process",
".",
"returncode",
"is",
"None",
":",
"self",
".",
"_process",
".",
"stdin",
".",
"flush",
"(",
")",
"self",
".",
"_process",
".",
"stdin",
".",
"close",
"(",
")",
"self",
".",... | 30.222222 | 6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.