text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def _make_tarfile(self, output_filename, source_dir):
"""Create .tar.gz file
"""
with tarfile.open(output_filename, "w:gz") as tar:
tar.add(source_dir, arcname=os.path.basename(source_dir)) | [
"def",
"_make_tarfile",
"(",
"self",
",",
"output_filename",
",",
"source_dir",
")",
":",
"with",
"tarfile",
".",
"open",
"(",
"output_filename",
",",
"\"w:gz\"",
")",
"as",
"tar",
":",
"tar",
".",
"add",
"(",
"source_dir",
",",
"arcname",
"=",
"os",
"."... | 44.2 | 0.008889 |
def get_evernote_client(self, token=None):
"""
get the token from evernote
"""
if token:
return EvernoteClient(token=token, sandbox=self.sandbox)
else:
return EvernoteClient(consumer_key=self.consumer_key, consumer_secret=self.consumer_secret,
... | [
"def",
"get_evernote_client",
"(",
"self",
",",
"token",
"=",
"None",
")",
":",
"if",
"token",
":",
"return",
"EvernoteClient",
"(",
"token",
"=",
"token",
",",
"sandbox",
"=",
"self",
".",
"sandbox",
")",
"else",
":",
"return",
"EvernoteClient",
"(",
"c... | 39.888889 | 0.008174 |
def loadMoreItems(self, excludeRead=False, continuation=None, loadLimit=20, since=None, until=None):
"""
Load more items using the continuation parameters of previously loaded items.
"""
self.lastLoadOk = False
self.lastLoadLength = 0
if not continuation and not self.... | [
"def",
"loadMoreItems",
"(",
"self",
",",
"excludeRead",
"=",
"False",
",",
"continuation",
"=",
"None",
",",
"loadLimit",
"=",
"20",
",",
"since",
"=",
"None",
",",
"until",
"=",
"None",
")",
":",
"self",
".",
"lastLoadOk",
"=",
"False",
"self",
".",
... | 51.666667 | 0.012685 |
def validate(self, url):
''' takes in a Github repository for validation of preview and
runtime (and possibly tests passing?
'''
# Preview must provide the live URL of the repository
if not url.startswith('http') or not 'github' in url:
bot.error('Test of previe... | [
"def",
"validate",
"(",
"self",
",",
"url",
")",
":",
"# Preview must provide the live URL of the repository",
"if",
"not",
"url",
".",
"startswith",
"(",
"'http'",
")",
"or",
"not",
"'github'",
"in",
"url",
":",
"bot",
".",
"error",
"(",
"'Test of preview must ... | 33 | 0.008421 |
def clear_cache(cls):
"""Call this before closing tk root"""
#Prevent tkinter errors on python 2 ??
for key in cls._cached:
cls._cached[key] = None
cls._cached = {} | [
"def",
"clear_cache",
"(",
"cls",
")",
":",
"#Prevent tkinter errors on python 2 ??",
"for",
"key",
"in",
"cls",
".",
"_cached",
":",
"cls",
".",
"_cached",
"[",
"key",
"]",
"=",
"None",
"cls",
".",
"_cached",
"=",
"{",
"}"
] | 33.833333 | 0.014423 |
def _sampleRange(rng, start, end, step, k):
"""
Equivalent to:
random.sample(xrange(start, end, step), k)
except it uses our random number generator.
This wouldn't need to create the arange if it were implemented in C.
"""
array = numpy.empty(k, dtype="uint32")
rng.sample(numpy.arange(start, end, ste... | [
"def",
"_sampleRange",
"(",
"rng",
",",
"start",
",",
"end",
",",
"step",
",",
"k",
")",
":",
"array",
"=",
"numpy",
".",
"empty",
"(",
"k",
",",
"dtype",
"=",
"\"uint32\"",
")",
"rng",
".",
"sample",
"(",
"numpy",
".",
"arange",
"(",
"start",
",... | 26.846154 | 0.01385 |
def read_voltages(self, voltage_file):
"""import voltages from a volt.dat file
Parameters
----------
voltage_file : string
Path to volt.dat file
"""
measurements_raw = np.loadtxt(
voltage_file,
skiprows=1,
)
measuremen... | [
"def",
"read_voltages",
"(",
"self",
",",
"voltage_file",
")",
":",
"measurements_raw",
"=",
"np",
".",
"loadtxt",
"(",
"voltage_file",
",",
"skiprows",
"=",
"1",
",",
")",
"measurements",
"=",
"np",
".",
"atleast_2d",
"(",
"measurements_raw",
")",
"# extrac... | 37.181818 | 0.000794 |
def compute_K_analytical(dataframe, spacing):
"""Given an electrode spacing, compute geometrical factors using the
equation for the homogeneous half-space (Neumann-equation)
If a dataframe is given, use the column (a, b, m, n). Otherwise, expect an
Nx4 arrray.
Parameters
----------
datafra... | [
"def",
"compute_K_analytical",
"(",
"dataframe",
",",
"spacing",
")",
":",
"if",
"isinstance",
"(",
"dataframe",
",",
"pd",
".",
"DataFrame",
")",
":",
"configs",
"=",
"dataframe",
"[",
"[",
"'a'",
",",
"'b'",
",",
"'m'",
",",
"'n'",
"]",
"]",
".",
"... | 33.870968 | 0.000926 |
def get_info(self):
'Retrieve the data from CrossRef.'
escaped_doi = urllib2.quote(self.doi, '')
html = get_resource("www.crossref.org", '/guestquery?queryType=doi&restype=unixref&doi=%s&doi_search=Search' % escaped_doi)
xml_matches = []
for m in re.finditer('(<doi_records>.*?</... | [
"def",
"get_info",
"(",
"self",
")",
":",
"escaped_doi",
"=",
"urllib2",
".",
"quote",
"(",
"self",
".",
"doi",
",",
"''",
")",
"html",
"=",
"get_resource",
"(",
"\"www.crossref.org\"",
",",
"'/guestquery?queryType=doi&restype=unixref&doi=%s&doi_search=Search'",
"%"... | 47.333333 | 0.008287 |
def frobenius_norm(self):
""" Frobenius norm (||data - USV||) for a data matrix and a low rank
approximation given by SVH using rank k for U and V
Returns:
frobenius norm: F = ||data - USV||
"""
if scipy.sparse.issparse(self.data):
err = self.... | [
"def",
"frobenius_norm",
"(",
"self",
")",
":",
"if",
"scipy",
".",
"sparse",
".",
"issparse",
"(",
"self",
".",
"data",
")",
":",
"err",
"=",
"self",
".",
"data",
"-",
"self",
".",
"U",
"*",
"self",
".",
"S",
"*",
"self",
".",
"V",
"err",
"=",... | 37.6875 | 0.012945 |
def cron(self, pattern, name, *args, **kwargs):
"""
A function to setup a RQ job as a cronjob::
@rq.job('low', timeout=60)
def add(x, y):
return x + y
add.cron('* * * * *', 'add-some-numbers', 1, 2, timeout=10)
:param \\*args: The positional... | [
"def",
"cron",
"(",
"self",
",",
"pattern",
",",
"name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"queue_name",
"=",
"kwargs",
".",
"pop",
"(",
"'queue'",
",",
"self",
".",
"queue_name",
")",
"timeout",
"=",
"kwargs",
".",
"pop",
"(",
... | 33.298246 | 0.001024 |
def groups_for_perm(
cls,
instance,
perm_name,
group_ids=None,
limit_group_permissions=False,
db_session=None,
):
"""
return PermissionTuples for groups that have given
permission for the resource, perm_name is __any_permission__ then
u... | [
"def",
"groups_for_perm",
"(",
"cls",
",",
"instance",
",",
"perm_name",
",",
"group_ids",
"=",
"None",
",",
"limit_group_permissions",
"=",
"False",
",",
"db_session",
"=",
"None",
",",
")",
":",
"# noqa",
"db_session",
"=",
"get_db_session",
"(",
"db_session... | 32.808511 | 0.001889 |
def fit(self, data, method='kmeans', **kwargs):
"""
fit classifiers from large dataset.
Parameters
----------
data : dict
A dict of data for clustering. Must contain
items with the same name as analytes used for
clustering.
method : st... | [
"def",
"fit",
"(",
"self",
",",
"data",
",",
"method",
"=",
"'kmeans'",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"method",
"=",
"method",
"ds_fit",
"=",
"self",
".",
"fitting_data",
"(",
"data",
")",
"mdict",
"=",
"{",
"'kmeans'",
":",
"self... | 34.884615 | 0.002145 |
def _align_intervals(int_hier, lab_hier, t_min=0.0, t_max=None):
'''Align a hierarchical annotation to span a fixed start and end time.
Parameters
----------
int_hier : list of list of intervals
lab_hier : list of list of str
Hierarchical segment annotations, encoded as a
list of li... | [
"def",
"_align_intervals",
"(",
"int_hier",
",",
"lab_hier",
",",
"t_min",
"=",
"0.0",
",",
"t_max",
"=",
"None",
")",
":",
"return",
"[",
"list",
"(",
"_",
")",
"for",
"_",
"in",
"zip",
"(",
"*",
"[",
"util",
".",
"adjust_intervals",
"(",
"np",
".... | 38.75 | 0.000899 |
def magphase_function(f='1.0/(1+1j*x)', xmin=-1, xmax=1, steps=200, p='x', g=None, erange=False, **kwargs):
"""
Plots function(s) magnitude and phase over the specified range.
Parameters
----------
f='1.0/(1+1j*x)'
Complex-valued function or list of functions to plot.
... | [
"def",
"magphase_function",
"(",
"f",
"=",
"'1.0/(1+1j*x)'",
",",
"xmin",
"=",
"-",
"1",
",",
"xmax",
"=",
"1",
",",
"steps",
"=",
"200",
",",
"p",
"=",
"'x'",
",",
"g",
"=",
"None",
",",
"erange",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":... | 42.363636 | 0.008395 |
def run_with_retcodes(argv):
"""
Run luigi with command line parsing, but raise ``SystemExit`` with the configured exit code.
Note: Usually you use the luigi binary directly and don't call this function yourself.
:param argv: Should (conceptually) be ``sys.argv[1:]``
"""
logger = logging.getLo... | [
"def",
"run_with_retcodes",
"(",
"argv",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"'luigi-interface'",
")",
"with",
"luigi",
".",
"cmdline_parser",
".",
"CmdlineParser",
".",
"global_instance",
"(",
"argv",
")",
":",
"retcodes",
"=",
"retcode... | 39.145833 | 0.002077 |
def add_section(self, section, friendly_name = None):
"""Adds a section and optionally gives it a friendly name.."""
if not isinstance(section, BASESTRING): # Make sure the user isn't expecting to use something stupid as a key.
raise ValueError(section)
# See if we've got this section already:
if sectio... | [
"def",
"add_section",
"(",
"self",
",",
"section",
",",
"friendly_name",
"=",
"None",
")",
":",
"if",
"not",
"isinstance",
"(",
"section",
",",
"BASESTRING",
")",
":",
"# Make sure the user isn't expecting to use something stupid as a key.\r",
"raise",
"ValueError",
"... | 45.642857 | 0.029141 |
def _parse_response_for_dict(response):
''' Extracts name-values from response header. Filter out the standard
http headers.'''
if response is None:
return None
http_headers = ['server', 'date', 'location', 'host',
'via', 'proxy-connection', 'connection']
return_dict = _... | [
"def",
"_parse_response_for_dict",
"(",
"response",
")",
":",
"if",
"response",
"is",
"None",
":",
"return",
"None",
"http_headers",
"=",
"[",
"'server'",
",",
"'date'",
",",
"'location'",
",",
"'host'",
",",
"'via'",
",",
"'proxy-connection'",
",",
"'connecti... | 33.533333 | 0.001934 |
def insert_bool(param, command_args):
'''
:param param:
:param command_args:
:return:
'''
index = 0
found = False
for lelem in command_args:
if lelem == '--' and not found:
break
if lelem == param:
found = True
break
index = index + 1
if found:
command_args.insert(in... | [
"def",
"insert_bool",
"(",
"param",
",",
"command_args",
")",
":",
"index",
"=",
"0",
"found",
"=",
"False",
"for",
"lelem",
"in",
"command_args",
":",
"if",
"lelem",
"==",
"'--'",
"and",
"not",
"found",
":",
"break",
"if",
"lelem",
"==",
"param",
":",... | 17.894737 | 0.027933 |
def send_acks(self, message):
"""
send acks to the service
:param message: EventHub_pb2.Message
:return: None
"""
if isinstance(message, EventHub_pb2.Message):
ack = EventHub_pb2.Ack(partition=message.partition, offset=message.offset)
self.grpc_man... | [
"def",
"send_acks",
"(",
"self",
",",
"message",
")",
":",
"if",
"isinstance",
"(",
"message",
",",
"EventHub_pb2",
".",
"Message",
")",
":",
"ack",
"=",
"EventHub_pb2",
".",
"Ack",
"(",
"partition",
"=",
"message",
".",
"partition",
",",
"offset",
"=",
... | 44.4 | 0.008824 |
def __normalize_list(self, msg):
"""Split message to list by commas and trim whitespace."""
if isinstance(msg, list):
msg = "".join(msg)
return list(map(lambda x: x.strip(), msg.split(","))) | [
"def",
"__normalize_list",
"(",
"self",
",",
"msg",
")",
":",
"if",
"isinstance",
"(",
"msg",
",",
"list",
")",
":",
"msg",
"=",
"\"\"",
".",
"join",
"(",
"msg",
")",
"return",
"list",
"(",
"map",
"(",
"lambda",
"x",
":",
"x",
".",
"strip",
"(",
... | 44.4 | 0.00885 |
def list_joined_topics(self, start=0):
"""
已加入的所有小组的话题列表
:param start: 翻页
:return: 带下一页的列表
"""
xml = self.api.xml(API_GROUP_HOME, params={'start': start})
return build_list_result(self._parse_topic_table(xml, 'title,comment,created,group'), xml) | [
"def",
"list_joined_topics",
"(",
"self",
",",
"start",
"=",
"0",
")",
":",
"xml",
"=",
"self",
".",
"api",
".",
"xml",
"(",
"API_GROUP_HOME",
",",
"params",
"=",
"{",
"'start'",
":",
"start",
"}",
")",
"return",
"build_list_result",
"(",
"self",
".",
... | 33.555556 | 0.012903 |
def path_from_keywords(keywords,into='path'):
'''
turns keyword pairs into path or filename
if `into=='path'`, then keywords are separted by underscores, else keywords are used to create a directory hierarchy
'''
subdirs = []
def prepare_string(s):
s = str(s)
s = re.sub('[]... | [
"def",
"path_from_keywords",
"(",
"keywords",
",",
"into",
"=",
"'path'",
")",
":",
"subdirs",
"=",
"[",
"]",
"def",
"prepare_string",
"(",
"s",
")",
":",
"s",
"=",
"str",
"(",
"s",
")",
"s",
"=",
"re",
".",
"sub",
"(",
"'[][{},*\"'",
"+",
"f\"'{os... | 42.444444 | 0.017914 |
def adjust_whitespace(text):
"""remove the left-whitespace margin of a block of Python code."""
state = [False, False]
(backslashed, triplequoted) = (0, 1)
def in_multi_line(line):
start_state = (state[backslashed] or state[triplequoted])
if re.search(r"\\$", line):
state[... | [
"def",
"adjust_whitespace",
"(",
"text",
")",
":",
"state",
"=",
"[",
"False",
",",
"False",
"]",
"(",
"backslashed",
",",
"triplequoted",
")",
"=",
"(",
"0",
",",
"1",
")",
"def",
"in_multi_line",
"(",
"line",
")",
":",
"start_state",
"=",
"(",
"sta... | 29.894737 | 0.000568 |
def _authenticate_ssh(org):
"""Try authenticating via ssh, if succesful yields a User, otherwise raises Error."""
# Try to get username from git config
username = os.environ.get(f"{org.upper()}_USERNAME")
# Require ssh-agent
child = pexpect.spawn("ssh -T git@github.com", encoding="utf8")
# GitHu... | [
"def",
"_authenticate_ssh",
"(",
"org",
")",
":",
"# Try to get username from git config",
"username",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"f\"{org.upper()}_USERNAME\"",
")",
"# Require ssh-agent",
"child",
"=",
"pexpect",
".",
"spawn",
"(",
"\"ssh -T git@gith... | 39.285714 | 0.002367 |
def print_traceback(self):
"""
Print the traceback of the exception wrapped by the AbbreviatedException.
"""
traceback.print_exception(self.etype, self.value, self.traceback) | [
"def",
"print_traceback",
"(",
"self",
")",
":",
"traceback",
".",
"print_exception",
"(",
"self",
".",
"etype",
",",
"self",
".",
"value",
",",
"self",
".",
"traceback",
")"
] | 40.4 | 0.014563 |
def rebuildGrid( self ):
"""
Rebuilds the ruler data.
"""
vruler = self.verticalRuler()
hruler = self.horizontalRuler()
rect = self._buildData['grid_rect']
# process the vertical ruler
h_lines = []
h_alt = [... | [
"def",
"rebuildGrid",
"(",
"self",
")",
":",
"vruler",
"=",
"self",
".",
"verticalRuler",
"(",
")",
"hruler",
"=",
"self",
".",
"horizontalRuler",
"(",
")",
"rect",
"=",
"self",
".",
"_buildData",
"[",
"'grid_rect'",
"]",
"# process the vertical ruler\r",
"h... | 35.473684 | 0.019053 |
def plot_gain_offsets(dio_cross,dio_chan_per_coarse=8,feedtype='l',ax1=None,ax2=None,legend=True,**kwargs):
'''
Plots the calculated gain offsets of each coarse channel along with
the time averaged power spectra of the X and Y feeds
'''
#Get ON-OFF ND spectra
Idiff,Qdiff,Udiff,Vdiff,freqs = get_... | [
"def",
"plot_gain_offsets",
"(",
"dio_cross",
",",
"dio_chan_per_coarse",
"=",
"8",
",",
"feedtype",
"=",
"'l'",
",",
"ax1",
"=",
"None",
",",
"ax2",
"=",
"None",
",",
"legend",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"#Get ON-OFF ND spectra",
"I... | 35.510204 | 0.040268 |
def save(self, filename=None, deleteid3=False):
"""Save metadata blocks to a file.
If no filename is given, the one most recently loaded is used.
"""
if filename is None:
filename = self.filename
f = open(filename, 'rb+')
try:
# Ensure we've got... | [
"def",
"save",
"(",
"self",
",",
"filename",
"=",
"None",
",",
"deleteid3",
"=",
"False",
")",
":",
"if",
"filename",
"is",
"None",
":",
"filename",
"=",
"self",
".",
"filename",
"f",
"=",
"open",
"(",
"filename",
",",
"'rb+'",
")",
"try",
":",
"# ... | 35.852459 | 0.00089 |
def all(self):
"""
SQLA like 'all' method, will populate all rows and apply all
filters and orders to it.
"""
items = list()
if not self._filters_cmd:
items = self.store.get(self.query_class)
else:
for item in self.store.get(self.qu... | [
"def",
"all",
"(",
"self",
")",
":",
"items",
"=",
"list",
"(",
")",
"if",
"not",
"self",
".",
"_filters_cmd",
":",
"items",
"=",
"self",
".",
"store",
".",
"get",
"(",
"self",
".",
"query_class",
")",
"else",
":",
"for",
"item",
"in",
"self",
".... | 37.826087 | 0.002242 |
def _preprocess_input(test, ref, mask=None):
"""Wrapper to the metric
Parameters
----------
ref : np.ndarray
the reference image
test : np.ndarray
the tested image
mask : np.ndarray, optional
the mask for the ROI
Notes
-----
Compute the metric only on magnet... | [
"def",
"_preprocess_input",
"(",
"test",
",",
"ref",
",",
"mask",
"=",
"None",
")",
":",
"test",
"=",
"np",
".",
"abs",
"(",
"np",
".",
"copy",
"(",
"test",
")",
")",
".",
"astype",
"(",
"'float64'",
")",
"ref",
"=",
"np",
".",
"abs",
"(",
"np"... | 22.628571 | 0.001211 |
async def stop(self, force: bool=False) -> None:
'''Cancel the task if it hasn't yet started, or tell it to
gracefully stop running if it has.'''
Log.debug('stopping task %s', self.name)
self.running = False
if force:
self.task.cancel() | [
"async",
"def",
"stop",
"(",
"self",
",",
"force",
":",
"bool",
"=",
"False",
")",
"->",
"None",
":",
"Log",
".",
"debug",
"(",
"'stopping task %s'",
",",
"self",
".",
"name",
")",
"self",
".",
"running",
"=",
"False",
"if",
"force",
":",
"self",
"... | 31.333333 | 0.013793 |
def run_wait(name, location='\\'):
r'''
Run a scheduled task and return when the task finishes
:param str name: The name of the task to run.
:param str location: A string value representing the location of the task.
Default is '\\' which is the root for the task scheduler
(C:\Windows\S... | [
"def",
"run_wait",
"(",
"name",
",",
"location",
"=",
"'\\\\'",
")",
":",
"# Check for existing folder",
"if",
"name",
"not",
"in",
"list_tasks",
"(",
"location",
")",
":",
"return",
"'{0} not found in {1}'",
".",
"format",
"(",
"name",
",",
"location",
")",
... | 27.272727 | 0.000644 |
def is_disabled(self, name):
"""Check if a given service name is disabled """
if self.services and name in self.services:
return self.services[name]['config'] == 'disabled'
return False | [
"def",
"is_disabled",
"(",
"self",
",",
"name",
")",
":",
"if",
"self",
".",
"services",
"and",
"name",
"in",
"self",
".",
"services",
":",
"return",
"self",
".",
"services",
"[",
"name",
"]",
"[",
"'config'",
"]",
"==",
"'disabled'",
"return",
"False"... | 43.4 | 0.00905 |
def prev_listing(self, limit=None):
"""GETs previous :class:`Listing` directed to by this :class:`Listing`. Returns :class:`Listing` object.
:param limit: max number of entries to get
"""
if self.before:
return self._reddit._limit_get(self._path, eparams={'before': ... | [
"def",
"prev_listing",
"(",
"self",
",",
"limit",
"=",
"None",
")",
":",
"if",
"self",
".",
"before",
":",
"return",
"self",
".",
"_reddit",
".",
"_limit_get",
"(",
"self",
".",
"_path",
",",
"eparams",
"=",
"{",
"'before'",
":",
"self",
".",
"before... | 46.444444 | 0.011737 |
def patch_persistent_volume(self, name, body, **kwargs): # noqa: E501
"""patch_persistent_volume # noqa: E501
partially update the specified PersistentVolume # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_... | [
"def",
"patch_persistent_volume",
"(",
"self",
",",
"name",
",",
"body",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"se... | 57.666667 | 0.001421 |
def create_track(self, href=None, media_url=None, label=None,
audio_channel=None):
"""Add a new track to a bundle. Note that the total number of
allowable tracks is limited. See the API documentation for
details.
'href' the relative href to the tracks list. May not... | [
"def",
"create_track",
"(",
"self",
",",
"href",
"=",
"None",
",",
"media_url",
"=",
"None",
",",
"label",
"=",
"None",
",",
"audio_channel",
"=",
"None",
")",
":",
"# Argument error checking.",
"assert",
"href",
"is",
"not",
"None",
"assert",
"media_url",
... | 34.711111 | 0.001868 |
def _parse(self, str):
""" Parses the text data from an XML element defined by tag.
"""
str = replace_entities(str)
str = strip_tags(str)
str = collapse_spaces(str)
return str | [
"def",
"_parse",
"(",
"self",
",",
"str",
")",
":",
"str",
"=",
"replace_entities",
"(",
"str",
")",
"str",
"=",
"strip_tags",
"(",
"str",
")",
"str",
"=",
"collapse_spaces",
"(",
"str",
")",
"return",
"str"
] | 25.888889 | 0.016598 |
def _get(url, use_kerberos=None, debug=False):
"""Perform a GET query against the CIS
"""
from ligo.org import request
# perform query
try:
response = request(url, debug=debug, use_kerberos=use_kerberos)
except HTTPError:
raise ValueError("Channel not found at URL %s "
... | [
"def",
"_get",
"(",
"url",
",",
"use_kerberos",
"=",
"None",
",",
"debug",
"=",
"False",
")",
":",
"from",
"ligo",
".",
"org",
"import",
"request",
"# perform query",
"try",
":",
"response",
"=",
"request",
"(",
"url",
",",
"debug",
"=",
"debug",
",",
... | 33.375 | 0.001821 |
def single(window, config):
"""Single theme
===== Header =====
= items =
==================
"""
cordx = round(config.get('cordx', 0))
color = config.get('color', red)
icon = config.get('icon', '=')
align = config.get('align', 'left')
term = window.term
width = roun... | [
"def",
"single",
"(",
"window",
",",
"config",
")",
":",
"cordx",
"=",
"round",
"(",
"config",
".",
"get",
"(",
"'cordx'",
",",
"0",
")",
")",
"color",
"=",
"config",
".",
"get",
"(",
"'color'",
",",
"red",
")",
"icon",
"=",
"config",
".",
"get",... | 30.047619 | 0.000767 |
def get_all_api_keys(self, **kwargs): # noqa: E501
"""Get all API keys # noqa: E501
An endpoint for retrieving API keys in an array, optionally filtered by the owner. **Example usage:** `curl https://api.us-east-1.mbedcloud.com/v3/api-keys -H 'Authorization: Bearer API_KEY'` # noqa: E501
T... | [
"def",
"get_all_api_keys",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'asynchronous'",
")",
":",
"return",
"self",
".",
"get_all_api_keys_with_h... | 55.576923 | 0.001361 |
def random_draw(self, size=None):
"""Draw random samples of the hyperparameters.
Parameters
----------
size : None, int or array-like, optional
The number/shape of samples to draw. If None, only one sample is
returned. Default is None.
"""
... | [
"def",
"random_draw",
"(",
"self",
",",
"size",
"=",
"None",
")",
":",
"return",
"scipy",
".",
"asarray",
"(",
"[",
"numpy",
".",
"random",
".",
"uniform",
"(",
"low",
"=",
"b",
"[",
"0",
"]",
",",
"high",
"=",
"b",
"[",
"1",
"]",
",",
"size",
... | 40.9 | 0.009569 |
def add_single_feature_methods(cls):
"""Custom decorator intended for :class:`~vision.helpers.VisionHelpers`.
This metaclass adds a `{feature}` method for every feature
defined on the Feature enum.
"""
# Sanity check: This only makes sense if we are building the GAPIC
# subclass and have enums ... | [
"def",
"add_single_feature_methods",
"(",
"cls",
")",
":",
"# Sanity check: This only makes sense if we are building the GAPIC",
"# subclass and have enums already attached.",
"if",
"not",
"hasattr",
"(",
"cls",
",",
"\"enums\"",
")",
":",
"return",
"cls",
"# Add each single-fe... | 35.96875 | 0.000846 |
def target(self):
"""
Returns the label associated with each item in data.
"""
return [
os.path.basename(os.path.dirname(f)) for f in self.files
] | [
"def",
"target",
"(",
"self",
")",
":",
"return",
"[",
"os",
".",
"path",
".",
"basename",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"f",
")",
")",
"for",
"f",
"in",
"self",
".",
"files",
"]"
] | 27.428571 | 0.010101 |
def write_configs(self):
"""Generate the configurations needed for pipes."""
utils.banner("Generating Configs")
if not self.runway_dir:
app_configs = configs.process_git_configs(git_short=self.git_short)
else:
app_configs = configs.process_runway_configs(runway_di... | [
"def",
"write_configs",
"(",
"self",
")",
":",
"utils",
".",
"banner",
"(",
"\"Generating Configs\"",
")",
"if",
"not",
"self",
".",
"runway_dir",
":",
"app_configs",
"=",
"configs",
".",
"process_git_configs",
"(",
"git_short",
"=",
"self",
".",
"git_short",
... | 46.5 | 0.008439 |
def convert_to_oqhazardlib(
self, tom, simple_mesh_spacing=1.0,
complex_mesh_spacing=2.0, area_discretisation=10.0,
use_defaults=False):
"""
Converts the source model to an iterator of sources of :class:
openquake.hazardlib.source.base.BaseSeismicSource
... | [
"def",
"convert_to_oqhazardlib",
"(",
"self",
",",
"tom",
",",
"simple_mesh_spacing",
"=",
"1.0",
",",
"complex_mesh_spacing",
"=",
"2.0",
",",
"area_discretisation",
"=",
"10.0",
",",
"use_defaults",
"=",
"False",
")",
":",
"oq_source_model",
"=",
"[",
"]",
"... | 42.058824 | 0.001367 |
def set_args(args):
"""Set computed command arguments.
Parameters
----------
args : `argparse.Namespace`
Command arguments.
base : `iterable` of `type`
Generator mixins.
Raises
------
ValueError
If output file is stdout and progress bars are enabled.
"""
... | [
"def",
"set_args",
"(",
"args",
")",
":",
"try",
":",
"if",
"args",
".",
"output",
"is",
"sys",
".",
"stdout",
"and",
"args",
".",
"progress",
":",
"raise",
"ValueError",
"(",
"'args.output is stdout and args.progress'",
")",
"except",
"AttributeError",
":",
... | 23.844444 | 0.000895 |
def get_host(self, retry_count=3):
"""
The function for retrieving host information for an IP address.
Args:
retry_count (:obj:`int`): The number of times to retry in case
socket errors, timeouts, connection resets, etc. are
encountered. Defaults to 3... | [
"def",
"get_host",
"(",
"self",
",",
"retry_count",
"=",
"3",
")",
":",
"try",
":",
"default_timeout_set",
"=",
"False",
"if",
"not",
"socket",
".",
"getdefaulttimeout",
"(",
")",
":",
"socket",
".",
"setdefaulttimeout",
"(",
"self",
".",
"timeout",
")",
... | 30.672131 | 0.001554 |
async def post(self, path, data={}, send_raw=False, **params):
'''sends post request
Parameters
----------
path : str
same as get_url
query : kargs dict
additional info to pass to get_url
See Also
--------
get_url :
Returns
-------
requests.models.Response
... | [
"async",
"def",
"post",
"(",
"self",
",",
"path",
",",
"data",
"=",
"{",
"}",
",",
"send_raw",
"=",
"False",
",",
"*",
"*",
"params",
")",
":",
"url",
"=",
"self",
".",
"get_url",
"(",
"path",
",",
"*",
"*",
"params",
")",
"jstr",
"=",
"json",
... | 24.702703 | 0.009474 |
def _is_download(ending):
"""Check if file ending is considered as download."""
list = [
'PDF',
'DOC',
'TXT',
'PPT',
'XLSX',
'MP3',
'SVG',
'7Z',
'HTML',
'TEX',
'MPP',
'... | [
"def",
"_is_download",
"(",
"ending",
")",
":",
"list",
"=",
"[",
"'PDF'",
",",
"'DOC'",
",",
"'TXT'",
",",
"'PPT'",
",",
"'XLSX'",
",",
"'MP3'",
",",
"'SVG'",
",",
"'7Z'",
",",
"'HTML'",
",",
"'TEX'",
",",
"'MPP'",
",",
"'ODT'",
",",
"'RAR'",
",",... | 21.310345 | 0.001548 |
def visit_default(self, node):
"""check the node line number and check it if not yet done"""
if not node.is_statement:
return
if not node.root().pure_python:
return # XXX block visit of child nodes
prev_sibl = node.previous_sibling()
if prev_sibl is not N... | [
"def",
"visit_default",
"(",
"self",
",",
"node",
")",
":",
"if",
"not",
"node",
".",
"is_statement",
":",
"return",
"if",
"not",
"node",
".",
"root",
"(",
")",
".",
"pure_python",
":",
"return",
"# XXX block visit of child nodes",
"prev_sibl",
"=",
"node",
... | 38.45 | 0.001268 |
def translate(self, hWndFrom = HWND_DESKTOP, hWndTo = HWND_DESKTOP):
"""
Translate coordinates from one window to another.
@see: L{client_to_screen}, L{screen_to_client}
@type hWndFrom: int or L{HWND} or L{system.Window}
@param hWndFrom: Window handle to translate from.
... | [
"def",
"translate",
"(",
"self",
",",
"hWndFrom",
"=",
"HWND_DESKTOP",
",",
"hWndTo",
"=",
"HWND_DESKTOP",
")",
":",
"points",
"=",
"[",
"(",
"self",
".",
"left",
",",
"self",
".",
"top",
")",
",",
"(",
"self",
".",
"right",
",",
"self",
".",
"bott... | 39.578947 | 0.01039 |
def to_dict_hook(obj):
"""Convert internal objects to a serializable representation.
During serialization if the object has the hook method `to_dict` it will be
automatically called and metadata for decoding will be added. This allows
for the translation of objects trees of arbitrary depth. E.g.:
... | [
"def",
"to_dict_hook",
"(",
"obj",
")",
":",
"if",
"hasattr",
"(",
"obj",
",",
"'to_dict'",
")",
":",
"result",
"=",
"obj",
".",
"to_dict",
"(",
")",
"assert",
"isinstance",
"(",
"result",
",",
"dict",
")",
",",
"'to_dict must return a dictionary'",
"resul... | 33.972973 | 0.000773 |
def _music_lib_search(self, search, start, max_items):
"""Perform a music library search and extract search numbers.
You can get an overview of all the relevant search prefixes (like
'A:') and their meaning with the request:
.. code ::
response = device.contentDirectory.Brows... | [
"def",
"_music_lib_search",
"(",
"self",
",",
"search",
",",
"start",
",",
"max_items",
")",
":",
"response",
"=",
"self",
".",
"contentDirectory",
".",
"Browse",
"(",
"[",
"(",
"'ObjectID'",
",",
"search",
")",
",",
"(",
"'BrowseFlag'",
",",
"'BrowseDirec... | 35.536585 | 0.001336 |
async def call_command(bot: NoneBot, ctx: Context_T,
name: Union[str, CommandName_T], *,
current_arg: str = '',
args: Optional[CommandArgs_T] = None,
check_perm: bool = True,
disable_interaction: bool = Fa... | [
"async",
"def",
"call_command",
"(",
"bot",
":",
"NoneBot",
",",
"ctx",
":",
"Context_T",
",",
"name",
":",
"Union",
"[",
"str",
",",
"CommandName_T",
"]",
",",
"*",
",",
"current_arg",
":",
"str",
"=",
"''",
",",
"args",
":",
"Optional",
"[",
"Comma... | 43.848485 | 0.000676 |
def update_now_playing(
self,
artist,
title,
album=None,
album_artist=None,
duration=None,
track_number=None,
mbid=None,
context=None,
):
"""
Used to notify Last.fm that a user has started listening to a track.
Para... | [
"def",
"update_now_playing",
"(",
"self",
",",
"artist",
",",
"title",
",",
"album",
"=",
"None",
",",
"album_artist",
"=",
"None",
",",
"duration",
"=",
"None",
",",
"track_number",
"=",
"None",
",",
"mbid",
"=",
"None",
",",
"context",
"=",
"None",
"... | 32.545455 | 0.002034 |
def handle_message(self, response, ignore_subscribe_messages=False):
"""
Parses a pub/sub message. If the channel or pattern was subscribed to
with a message handler, the handler is invoked instead of a parsed
message being returned.
"""
message_type = nativestr(response[... | [
"def",
"handle_message",
"(",
"self",
",",
"response",
",",
"ignore_subscribe_messages",
"=",
"False",
")",
":",
"message_type",
"=",
"nativestr",
"(",
"response",
"[",
"0",
"]",
")",
"if",
"message_type",
"==",
"'pmessage'",
":",
"message",
"=",
"{",
"'type... | 35.529412 | 0.001074 |
def decode_intervals(self, encoded, duration=None, multi=True, sparse=False,
transition=None, p_state=None, p_init=None):
'''Decode labeled intervals into (start, end, value) triples
Parameters
----------
encoded : np.ndarray, shape=(n_frames, m)
Fra... | [
"def",
"decode_intervals",
"(",
"self",
",",
"encoded",
",",
"duration",
"=",
"None",
",",
"multi",
"=",
"True",
",",
"sparse",
"=",
"False",
",",
"transition",
"=",
"None",
",",
"p_state",
"=",
"None",
",",
"p_init",
"=",
"None",
")",
":",
"if",
"np... | 42.416667 | 0.0012 |
def init_package(path=None, name='manage'):
"""Initialize (import) the submodules, and recursively the
subpackages, of a "manage" package at ``path``.
``path`` may be specified as either a system directory path or a
list of these.
If ``path`` is unspecified, it is inferred from the already-importe... | [
"def",
"init_package",
"(",
"path",
"=",
"None",
",",
"name",
"=",
"'manage'",
")",
":",
"if",
"path",
"is",
"None",
":",
"manager",
"=",
"sys",
".",
"modules",
"[",
"name",
"]",
"init_package",
"(",
"manager",
".",
"__path__",
",",
"name",
")",
"ret... | 30 | 0.001404 |
def to_volume(self):
"""Return a 3D volume of the data"""
if hasattr(self.header.definitions, "Lattice"):
X, Y, Z = self.header.definitions.Lattice
else:
raise ValueError("Unable to determine data size")
volume = self.decoded_data.reshape(Z, Y, X)
... | [
"def",
"to_volume",
"(",
"self",
")",
":",
"if",
"hasattr",
"(",
"self",
".",
"header",
".",
"definitions",
",",
"\"Lattice\"",
")",
":",
"X",
",",
"Y",
",",
"Z",
"=",
"self",
".",
"header",
".",
"definitions",
".",
"Lattice",
"else",
":",
"raise",
... | 36.222222 | 0.008982 |
def read_table(data, fields):
"""Read a table structure.
These are used by Blizzard to collect pieces of data together. Each
value is prefixed by two bytes, first denoting (doubled) index and the
second denoting some sort of key -- so far it has always been '09'. The
actual value follows as a Varia... | [
"def",
"read_table",
"(",
"data",
",",
"fields",
")",
":",
"def",
"read_field",
"(",
"field_name",
")",
":",
"data",
".",
"read",
"(",
"2",
")",
"table",
"[",
"field_name",
"]",
"=",
"vlq2int",
"(",
"data",
")",
"/",
"2",
"# Discard unknown fields.",
"... | 38.8 | 0.001006 |
def get_cookies_from_cache(username):
"""
Returns a RequestsCookieJar containing the cached cookies for the given
user.
"""
logging.debug('Trying to get cookies from the cache.')
path = get_cookies_cache_path(username)
cj = requests.cookies.RequestsCookieJar()
try:
cached_cj = ... | [
"def",
"get_cookies_from_cache",
"(",
"username",
")",
":",
"logging",
".",
"debug",
"(",
"'Trying to get cookies from the cache.'",
")",
"path",
"=",
"get_cookies_cache_path",
"(",
"username",
")",
"cj",
"=",
"requests",
".",
"cookies",
".",
"RequestsCookieJar",
"(... | 29.1 | 0.001664 |
def process(self):
"""
populate the report from the xml
:return:
"""
suites = None
if isinstance(self.tree, ET.Element):
root = self.tree
else:
root = self.tree.getroot()
if root.tag == "testrun":
root = root[0]
... | [
"def",
"process",
"(",
"self",
")",
":",
"suites",
"=",
"None",
"if",
"isinstance",
"(",
"self",
".",
"tree",
",",
"ET",
".",
"Element",
")",
":",
"root",
"=",
"self",
".",
"tree",
"else",
":",
"root",
"=",
"self",
".",
"tree",
".",
"getroot",
"(... | 42.659341 | 0.001762 |
def message(msg, *args):
'''Program message output.'''
clear_progress()
text = (msg % args)
sys.stdout.write(text + '\n') | [
"def",
"message",
"(",
"msg",
",",
"*",
"args",
")",
":",
"clear_progress",
"(",
")",
"text",
"=",
"(",
"msg",
"%",
"args",
")",
"sys",
".",
"stdout",
".",
"write",
"(",
"text",
"+",
"'\\n'",
")"
] | 25 | 0.03876 |
def scan_dir_for_template_files(search_dir):
"""
Return a map of "likely service/template name" to "template file".
This includes all the template files in fixtures and in services.
"""
template_files = {}
cf_dir = os.path.join(search_dir, 'cloudformation')
for type in os.listdir(cf_dir):
... | [
"def",
"scan_dir_for_template_files",
"(",
"search_dir",
")",
":",
"template_files",
"=",
"{",
"}",
"cf_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"search_dir",
",",
"'cloudformation'",
")",
"for",
"type",
"in",
"os",
".",
"listdir",
"(",
"cf_dir",
")... | 41.846154 | 0.001799 |
def update_qsd(url, qsd=None, remove=None):
"""
Update or remove keys from a query string in a URL
:param url: URL to update
:param qsd: dict of keys to update, a None value leaves it unchanged
:param remove: list of keys to remove, or "*" to remove all
note: updated keys are nev... | [
"def",
"update_qsd",
"(",
"url",
",",
"qsd",
"=",
"None",
",",
"remove",
"=",
"None",
")",
":",
"qsd",
"=",
"qsd",
"or",
"{",
"}",
"remove",
"=",
"remove",
"or",
"[",
"]",
"# parse current query string",
"parsed",
"=",
"urlparse",
"(",
"url",
")",
"c... | 29.875 | 0.001013 |
def reset_option(self, key, subkey):
"""Resets a single option to the default values.
:param str key: First identifier of the option.
:param str subkey: Second identifier of the option.
:raise:
:NotRegisteredError: If ``key`` or ``subkey`` do not define any
... | [
"def",
"reset_option",
"(",
"self",
",",
"key",
",",
"subkey",
")",
":",
"if",
"not",
"self",
".",
"open",
":",
"return",
"key",
",",
"subkey",
"=",
"_lower_keys",
"(",
"key",
",",
"subkey",
")",
"_entry_must_exist",
"(",
"self",
".",
"gc",
",",
"key... | 35.5 | 0.002286 |
def get_string_from_data(self, offset, data):
"""Get an ASCII string from within the data."""
# OC Patch
b = None
try:
b = data[offset]
except IndexError:
return ''
s = ''
while ord(b):
s += b
... | [
"def",
"get_string_from_data",
"(",
"self",
",",
"offset",
",",
"data",
")",
":",
"# OC Patch",
"b",
"=",
"None",
"try",
":",
"b",
"=",
"data",
"[",
"offset",
"]",
"except",
"IndexError",
":",
"return",
"''",
"s",
"=",
"''",
"while",
"ord",
"(",
"b",... | 21.142857 | 0.012931 |
def simple_nearest_indices(xs,res):
'''
Simple nearest interpolator that interpolates based on
the minima and maxima of points based on the passed
resolution in res.
Parameters:
-----------
xs -- A collection of `ndim` arrays of points.
res -- List of resolutions.
'''
maxs = [... | [
"def",
"simple_nearest_indices",
"(",
"xs",
",",
"res",
")",
":",
"maxs",
"=",
"[",
"max",
"(",
"a",
")",
"for",
"a",
"in",
"xs",
"]",
"mins",
"=",
"[",
"min",
"(",
"a",
")",
"for",
"a",
"in",
"xs",
"]",
"XS",
"=",
"[",
"np",
".",
"linspace",... | 29.210526 | 0.020942 |
def stuff(packet):
"""
Add byte stuffing to TSIP packet.
:param packet: TSIP packet with byte stuffing. The packet must already
have been stripped or `ValueError` will be raised.
:type packet: Binary string.
:return: Packet with byte stuffing.
"""
if is_framed(packet):
rais... | [
"def",
"stuff",
"(",
"packet",
")",
":",
"if",
"is_framed",
"(",
"packet",
")",
":",
"raise",
"ValueError",
"(",
"'packet contains leading DLE and trailing DLE/ETX'",
")",
"else",
":",
"return",
"packet",
".",
"replace",
"(",
"CHR_DLE",
",",
"CHR_DLE",
"+",
"C... | 31.357143 | 0.002212 |
def help(self, event, command_name=None):
"""
Shows the help message for the bot. Takes an optional command name
which when given, will show help for that command.
"""
if command_name is None:
return ("Type !commands for a list of all commands. Type "
... | [
"def",
"help",
"(",
"self",
",",
"event",
",",
"command_name",
"=",
"None",
")",
":",
"if",
"command_name",
"is",
"None",
":",
"return",
"(",
"\"Type !commands for a list of all commands. Type \"",
"\"!help [command] to see help for a specific command.\"",
")",
"try",
"... | 42.571429 | 0.002188 |
def to_text(obj, encoding='utf-8', errors=None, nonstring='simplerepr'):
"""Make sure that a string is a text string
:arg obj: An object to make sure is a text string. In most cases this
will be either a text string or a byte string. However, with
``nonstring='simplerepr'``, this can be used ... | [
"def",
"to_text",
"(",
"obj",
",",
"encoding",
"=",
"'utf-8'",
",",
"errors",
"=",
"None",
",",
"nonstring",
"=",
"'simplerepr'",
")",
":",
"if",
"isinstance",
"(",
"obj",
",",
"text_type",
")",
":",
"return",
"obj",
"if",
"errors",
"in",
"_COMPOSED_ERRO... | 44.494382 | 0.001235 |
def related_obj_to_dict(obj, **kwargs):
""" Covert a known related object to a dictionary. """
# Explicitly discard formatter kwarg, should not be cascaded down.
kwargs.pop('formatter', None)
# If True, remove fields that start with an underscore (e.g. _secret)
suppress_private_attr = kwargs.get("... | [
"def",
"related_obj_to_dict",
"(",
"obj",
",",
"*",
"*",
"kwargs",
")",
":",
"# Explicitly discard formatter kwarg, should not be cascaded down.",
"kwargs",
".",
"pop",
"(",
"'formatter'",
",",
"None",
")",
"# If True, remove fields that start with an underscore (e.g. _secret)"... | 33.444444 | 0.000646 |
def get_all_users(path_prefix='/', region=None, key=None, keyid=None,
profile=None):
'''
Get and return all IAM user details, starting at the optional path.
.. versionadded:: 2016.3.0
CLI Example:
salt-call boto_iam.get_all_users
'''
conn = _get_conn(region=region, ke... | [
"def",
"get_all_users",
"(",
"path_prefix",
"=",
"'/'",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
")",
":",
"conn",
"=",
"_get_conn",
"(",
"region",
"=",
"region",
",",
"key",
"=",
... | 33.846154 | 0.00221 |
def Search(self,key):
"""Search group list by providing partial name, ID, description or other key.
>>> clc.v2.Datacenter().Groups().Search("Default Group")
[<clc.APIv2.group.Group object at 0x1065b0f50>, <clc.APIv2.group.Group object at 0x1065b0d10>]
"""
results = []
for group in self.groups:
if grou... | [
"def",
"Search",
"(",
"self",
",",
"key",
")",
":",
"results",
"=",
"[",
"]",
"for",
"group",
"in",
"self",
".",
"groups",
":",
"if",
"group",
".",
"id",
".",
"lower",
"(",
")",
".",
"find",
"(",
"key",
".",
"lower",
"(",
")",
")",
"!=",
"-",... | 36.133333 | 0.032374 |
def values(self, limit=None, page=None):
"""
convenience method to get just the values from the query (same as get().values())
if you want to get all values, you can use: self.all().values()
"""
return self.get(limit=limit, page=page).values() | [
"def",
"values",
"(",
"self",
",",
"limit",
"=",
"None",
",",
"page",
"=",
"None",
")",
":",
"return",
"self",
".",
"get",
"(",
"limit",
"=",
"limit",
",",
"page",
"=",
"page",
")",
".",
"values",
"(",
")"
] | 39.714286 | 0.010563 |
def decrypt_verify(encrypted, session_keys=None):
"""Decrypts the given ciphertext string and returns both the
signatures (if any) and the plaintext.
:param bytes encrypted: the mail to decrypt
:param list[str] session_keys: a list OpenPGP session keys
:returns: the signatures and decrypted plainte... | [
"def",
"decrypt_verify",
"(",
"encrypted",
",",
"session_keys",
"=",
"None",
")",
":",
"if",
"session_keys",
"is",
"not",
"None",
":",
"try",
":",
"return",
"_decrypt_verify_session_keys",
"(",
"encrypted",
",",
"session_keys",
")",
"except",
"GPGProblem",
":",
... | 37.666667 | 0.001439 |
def _parse(string):
"""
Parses given XML document content.
Returns the resulting root XML element node or None if the given XML
content is empty.
@param string: XML document content to parse.
@type string: I{bytes}
@return: Resulting root XML element node or None.
@rtype: L{Element}|I{... | [
"def",
"_parse",
"(",
"string",
")",
":",
"if",
"string",
":",
"return",
"suds",
".",
"sax",
".",
"parser",
".",
"Parser",
"(",
")",
".",
"parse",
"(",
"string",
"=",
"string",
")"
] | 26.4 | 0.002439 |
def request_openbus(self, service, endpoint, **kwargs):
"""Make a request to the given endpoint of the ``openbus`` server.
This returns the plain JSON (dict) response which can then be parsed
using one of the implemented types.
Args:
service (str): Service to fetch ('bus' o... | [
"def",
"request_openbus",
"(",
"self",
",",
"service",
",",
"endpoint",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"service",
"==",
"'bus'",
":",
"endpoints",
"=",
"ENDPOINTS_BUS",
"elif",
"service",
"==",
"'geo'",
":",
"endpoints",
"=",
"ENDPOINTS_GEO",
"el... | 32.289474 | 0.001582 |
def mult_inv(a, b):
"""
Calculate the multiplicative inverse a**-1 % b.
This function works for n >= 5 where n is prime.
"""
# in addition to the normal setup, we also remember b
last_b, x, last_x, y, last_y = b, 0, 1, 1, 0
while b != 0:
q = a // b
a, b = b, a % b
x,... | [
"def",
"mult_inv",
"(",
"a",
",",
"b",
")",
":",
"# in addition to the normal setup, we also remember b",
"last_b",
",",
"x",
",",
"last_x",
",",
"y",
",",
"last_y",
"=",
"b",
",",
"0",
",",
"1",
",",
"1",
",",
"0",
"while",
"b",
"!=",
"0",
":",
"q",... | 27.941176 | 0.002037 |
def qteBindKeyApplet(self, keysequence, macroName: str,
appletObj: QtmacsApplet):
"""
Bind ``macroName`` to all widgets in ``appletObj``.
This method does not affect the key bindings of other applets,
or other instances of the same applet.
The ``keysequ... | [
"def",
"qteBindKeyApplet",
"(",
"self",
",",
"keysequence",
",",
"macroName",
":",
"str",
",",
"appletObj",
":",
"QtmacsApplet",
")",
":",
"# Convert the key sequence into a QtmacsKeysequence object, or",
"# raise a QtmacsKeysequenceError if the conversion is",
"# impossible.",
... | 38.803571 | 0.001346 |
def write_feed_dangerously(
feed: Feed, outpath: str, nodes: Optional[Collection[str]] = None
) -> str:
"""Naively write a feed to a zipfile
This function provides no sanity checks. Use it at
your own risk.
"""
nodes = DEFAULT_NODES if nodes is None else nodes
try:
tmpdir = tempfile... | [
"def",
"write_feed_dangerously",
"(",
"feed",
":",
"Feed",
",",
"outpath",
":",
"str",
",",
"nodes",
":",
"Optional",
"[",
"Collection",
"[",
"str",
"]",
"]",
"=",
"None",
")",
"->",
"str",
":",
"nodes",
"=",
"DEFAULT_NODES",
"if",
"nodes",
"is",
"None... | 26.21875 | 0.001149 |
def spf_rec(rdata):
'''
Validate and parse DNS record data for SPF record(s)
:param rdata: DNS record data
:return: dict w/fields
'''
spf_fields = rdata.split(' ')
if not spf_fields.pop(0).startswith('v=spf'):
raise ValueError('Not an SPF record')
res = OrderedDict()
mods = ... | [
"def",
"spf_rec",
"(",
"rdata",
")",
":",
"spf_fields",
"=",
"rdata",
".",
"split",
"(",
"' '",
")",
"if",
"not",
"spf_fields",
".",
"pop",
"(",
"0",
")",
".",
"startswith",
"(",
"'v=spf'",
")",
":",
"raise",
"ValueError",
"(",
"'Not an SPF record'",
"... | 29.113208 | 0.000627 |
def autoencoder_discrete_pong():
"""Discrete autoencoder model for compressing pong frames."""
hparams = autoencoder_ordered_discrete()
hparams.num_hidden_layers = 3
hparams.bottleneck_bits = 24
hparams.batch_size = 2
hparams.gan_loss_factor = 0.01
hparams.bottleneck_l2_factor = 0.001
hparams.add_hparam... | [
"def",
"autoencoder_discrete_pong",
"(",
")",
":",
"hparams",
"=",
"autoencoder_ordered_discrete",
"(",
")",
"hparams",
".",
"num_hidden_layers",
"=",
"3",
"hparams",
".",
"bottleneck_bits",
"=",
"24",
"hparams",
".",
"batch_size",
"=",
"2",
"hparams",
".",
"gan... | 36.4 | 0.02681 |
def get(self, sid):
"""
Constructs a ModelBuildContext
:param sid: The unique string that identifies the resource
:returns: twilio.rest.autopilot.v1.assistant.model_build.ModelBuildContext
:rtype: twilio.rest.autopilot.v1.assistant.model_build.ModelBuildContext
"""
... | [
"def",
"get",
"(",
"self",
",",
"sid",
")",
":",
"return",
"ModelBuildContext",
"(",
"self",
".",
"_version",
",",
"assistant_sid",
"=",
"self",
".",
"_solution",
"[",
"'assistant_sid'",
"]",
",",
"sid",
"=",
"sid",
",",
")"
] | 41.2 | 0.011876 |
def parse_args():
"""
Parse commandline arguments.
"""
def exclusive_group(group, name, default, help):
destname = name.replace('-', '_')
subgroup = group.add_mutually_exclusive_group(required=False)
subgroup.add_argument(f'--{name}', dest=f'{destname}',
... | [
"def",
"parse_args",
"(",
")",
":",
"def",
"exclusive_group",
"(",
"group",
",",
"name",
",",
"default",
",",
"help",
")",
":",
"destname",
"=",
"name",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")",
"subgroup",
"=",
"group",
".",
"add_mutually_exclusive_g... | 53.114286 | 0.000088 |
def getrange(self):
"""Retrieve the dataset min and max values.
Args::
no argument
Returns::
(min, max) tuple (attribute 'valid_range')
Note that those are the values as stored
by the 'setrange' method. 'getrange' does *NOT* compute the
min ... | [
"def",
"getrange",
"(",
"self",
")",
":",
"# Obtain SDS data type.",
"try",
":",
"sds_name",
",",
"rank",
",",
"dim_sizes",
",",
"data_type",
",",
"n_attrs",
"=",
"self",
".",
"info",
"(",
")",
"except",
"HDF4Error",
":",
"raise",
"HDF4Error",
"(",
"'getra... | 31.686747 | 0.001844 |
def proc_val(key, val):
"""
Static helper method to convert Feff parameters to proper types, e.g.
integers, floats, lists, etc.
Args:
key: Feff parameter key
val: Actual value of Feff parameter.
"""
list_type_keys = list(VALID_FEFF_TAGS)
... | [
"def",
"proc_val",
"(",
"key",
",",
"val",
")",
":",
"list_type_keys",
"=",
"list",
"(",
"VALID_FEFF_TAGS",
")",
"del",
"list_type_keys",
"[",
"list_type_keys",
".",
"index",
"(",
"\"ELNES\"",
")",
"]",
"del",
"list_type_keys",
"[",
"list_type_keys",
".",
"i... | 32.654545 | 0.001081 |
def sort(self, key=None, reverse=False):
"""
Sort a structure in place. The parameters have the same meaning as in
list.sort. By default, sites are sorted by the electronegativity of
the species. The difference between this method and
get_sorted_structure (which also works in ISt... | [
"def",
"sort",
"(",
"self",
",",
"key",
"=",
"None",
",",
"reverse",
"=",
"False",
")",
":",
"self",
".",
"_sites",
".",
"sort",
"(",
"key",
"=",
"key",
",",
"reverse",
"=",
"reverse",
")"
] | 50.117647 | 0.002304 |
def change_ref(self, gm=None, r0=None, lmax=None):
"""
Return a new SHGravCoeffs class instance with a different reference gm
or r0.
Usage
-----
clm = x.change_ref([gm, r0, lmax])
Returns
-------
clm : SHGravCoeffs class instance.
Parame... | [
"def",
"change_ref",
"(",
"self",
",",
"gm",
"=",
"None",
",",
"r0",
"=",
"None",
",",
"lmax",
"=",
"None",
")",
":",
"if",
"lmax",
"is",
"None",
":",
"lmax",
"=",
"self",
".",
"lmax",
"clm",
"=",
"self",
".",
"pad",
"(",
"lmax",
")",
"if",
"... | 33.38 | 0.001746 |
def retry_until_not_none_or_limit_reached(method, limit, sleep_s=1,
catch_exceptions=()):
"""Executes a method until the retry limit is hit or not None is returned."""
return retry_until_valid_or_limit_reached(
method, limit, lambda x: x is not None, sleep_s, catch_ex... | [
"def",
"retry_until_not_none_or_limit_reached",
"(",
"method",
",",
"limit",
",",
"sleep_s",
"=",
"1",
",",
"catch_exceptions",
"=",
"(",
")",
")",
":",
"return",
"retry_until_valid_or_limit_reached",
"(",
"method",
",",
"limit",
",",
"lambda",
"x",
":",
"x",
... | 65 | 0.009119 |
def dist_mlipns(src, tar, threshold=0.25, max_mismatches=2):
"""Return the MLIPNS distance between two strings.
This is a wrapper for :py:meth:`MLIPNS.dist`.
Parameters
----------
src : str
Source string for comparison
tar : str
Target string for comparison
threshold : floa... | [
"def",
"dist_mlipns",
"(",
"src",
",",
"tar",
",",
"threshold",
"=",
"0.25",
",",
"max_mismatches",
"=",
"2",
")",
":",
"return",
"MLIPNS",
"(",
")",
".",
"dist",
"(",
"src",
",",
"tar",
",",
"threshold",
",",
"max_mismatches",
")"
] | 25.75 | 0.00104 |
def paramsarray(self):
"""All free model parameters as 1-dimensional `numpy.ndarray`.
You are allowed to update model parameters by direct
assignment of this property."""
# Return copy of `_paramsarray` because setter checks if changed
if self._paramsarray is not None:
... | [
"def",
"paramsarray",
"(",
"self",
")",
":",
"# Return copy of `_paramsarray` because setter checks if changed",
"if",
"self",
".",
"_paramsarray",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_paramsarray",
".",
"copy",
"(",
")",
"nparams",
"=",
"len",
"(",
... | 47.333333 | 0.002301 |
def compute_exported_specifications(svc_ref):
# type: (pelix.framework.ServiceReference) -> List[str]
"""
Computes the list of specifications exported by the given service
:param svc_ref: A ServiceReference
:return: The list of exported specifications (or an empty list)
"""
if svc_ref.get_p... | [
"def",
"compute_exported_specifications",
"(",
"svc_ref",
")",
":",
"# type: (pelix.framework.ServiceReference) -> List[str]",
"if",
"svc_ref",
".",
"get_property",
"(",
"pelix",
".",
"remote",
".",
"PROP_EXPORT_NONE",
")",
":",
"# The export of this service is explicitly forbi... | 36.886364 | 0.0012 |
def get_books_by_comment(self, comment_id):
"""Gets the list of ``Book`` objects mapped to a ``Comment``.
arg: comment_id (osid.id.Id): ``Id`` of a ``Comment``
return: (osid.commenting.BookList) - list of books
raise: NotFound - ``comment_id`` is not found
raise: NullArgume... | [
"def",
"get_books_by_comment",
"(",
"self",
",",
"comment_id",
")",
":",
"# Implemented from template for",
"# osid.resource.ResourceBinSession.get_bins_by_resource",
"mgr",
"=",
"self",
".",
"_get_provider_manager",
"(",
"'COMMENTING'",
",",
"local",
"=",
"True",
")",
"l... | 48.777778 | 0.002235 |
def keyEvent(self, key, down=1):
"""For most ordinary keys, the "keysym" is the same as the corresponding ASCII value.
Other common keys are shown in the KEY_ constants."""
self.transport.write(pack("!BBxxI", 4, down, key)) | [
"def",
"keyEvent",
"(",
"self",
",",
"key",
",",
"down",
"=",
"1",
")",
":",
"self",
".",
"transport",
".",
"write",
"(",
"pack",
"(",
"\"!BBxxI\"",
",",
"4",
",",
"down",
",",
"key",
")",
")"
] | 61 | 0.012146 |
def memory_usage(method):
"""Log memory usage before and after a method."""
def wrapper(*args, **kwargs):
logging.info('Memory before method %s is %s.',
method.__name__, runtime.memory_usage().current())
result = method(*args, **kwargs)
logging.info('Memory after method %s is %s',
... | [
"def",
"memory_usage",
"(",
"method",
")",
":",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"logging",
".",
"info",
"(",
"'Memory before method %s is %s.'",
",",
"method",
".",
"__name__",
",",
"runtime",
".",
"memory_usage",
"("... | 40.8 | 0.009592 |
def main():
"""Main function"""
# Configure the logger
log = logging.getLogger('SIP.EC.PCI.DB')
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter(
'%(name)-20s | %(filename)-15s | %(levelname)-5s | %(message)s'))
log.addHandler(handler)
log.setLevel(os.getenv('... | [
"def",
"main",
"(",
")",
":",
"# Configure the logger",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"'SIP.EC.PCI.DB'",
")",
"handler",
"=",
"logging",
".",
"StreamHandler",
"(",
")",
"handler",
".",
"setFormatter",
"(",
"logging",
".",
"Formatter",
"(",
"'... | 38.538462 | 0.001949 |
def tropocollagen(
cls, aa=28, major_radius=5.0, major_pitch=85.0, auto_build=True):
"""Creates a model of a collagen triple helix.
Parameters
----------
aa : int, optional
Number of amino acids per minor helix.
major_radius : float, optional
... | [
"def",
"tropocollagen",
"(",
"cls",
",",
"aa",
"=",
"28",
",",
"major_radius",
"=",
"5.0",
",",
"major_pitch",
"=",
"85.0",
",",
"auto_build",
"=",
"True",
")",
":",
"instance",
"=",
"cls",
".",
"from_parameters",
"(",
"n",
"=",
"3",
",",
"aa",
"=",
... | 40.961538 | 0.001835 |
def SayString(self, text, delay=0):
"""Enter some text.
:param text: the text you want to enter.
"""
self._delay(delay)
cmd = Command("SayString", 'SayString "%s"' % text)
self.add(cmd) | [
"def",
"SayString",
"(",
"self",
",",
"text",
",",
"delay",
"=",
"0",
")",
":",
"self",
".",
"_delay",
"(",
"delay",
")",
"cmd",
"=",
"Command",
"(",
"\"SayString\"",
",",
"'SayString \"%s\"'",
"%",
"text",
")",
"self",
".",
"add",
"(",
"cmd",
")"
] | 29.375 | 0.012397 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.