text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def get_session(username, password, cookie_path=COOKIE_PATH, cache=True,
cache_expiry=300, cache_path=CACHE_PATH, driver='phantomjs'):
"""Get session, existing or new."""
class USPSAuth(AuthBase): # pylint: disable=too-few-public-methods
"""USPS authorization storage."""
def __... | [
"def",
"get_session",
"(",
"username",
",",
"password",
",",
"cookie_path",
"=",
"COOKIE_PATH",
",",
"cache",
"=",
"True",
",",
"cache_expiry",
"=",
"300",
",",
"cache_path",
"=",
"CACHE_PATH",
",",
"driver",
"=",
"'phantomjs'",
")",
":",
"class",
"USPSAuth"... | 39.034483 | 0.000862 |
def get_apkid(apkfile):
"""Read (appid, versionCode, versionName) from an APK
This first tries to do quick binary XML parsing to just get the
values that are needed. It will fallback to full androguard
parsing, which is slow, if it can't find the versionName value or
versionName is set to a Androi... | [
"def",
"get_apkid",
"(",
"apkfile",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"apkfile",
")",
":",
"log",
".",
"error",
"(",
"\"'{apkfile}' does not exist!\"",
".",
"format",
"(",
"apkfile",
"=",
"apkfile",
")",
")",
"appid",
"=",
"... | 45.076923 | 0.002088 |
def _getNextArticleBatch(self):
"""download next batch of articles based on the article uris in the uri list"""
# try to get more uris, if none
self._articlePage += 1
# if we have already obtained all pages, then exit
if self._totalPages != None and self._articlePage > self._tota... | [
"def",
"_getNextArticleBatch",
"(",
"self",
")",
":",
"# try to get more uris, if none",
"self",
".",
"_articlePage",
"+=",
"1",
"# if we have already obtained all pages, then exit",
"if",
"self",
".",
"_totalPages",
"!=",
"None",
"and",
"self",
".",
"_articlePage",
">"... | 50.052632 | 0.008256 |
def _add_missing_rows(self, indexes):
"""
Given a list of indexes, find all the indexes that are not currently in the Series and make a new row for
that index by appending to the Series. This does not maintain sorted order for the index.
:param indexes: list of indexes
:return: ... | [
"def",
"_add_missing_rows",
"(",
"self",
",",
"indexes",
")",
":",
"new_indexes",
"=",
"[",
"x",
"for",
"x",
"in",
"indexes",
"if",
"x",
"not",
"in",
"self",
".",
"_index",
"]",
"for",
"x",
"in",
"new_indexes",
":",
"self",
".",
"_add_row",
"(",
"x",... | 41.363636 | 0.008602 |
def collect_blame_info(cls, matches):
"""Runs git blame on files, for the specified sets of line ranges.
If no line range tuples are provided, it will do all lines.
"""
old_area = None
for filename, ranges in matches:
area, name = os.path.split(filename)
... | [
"def",
"collect_blame_info",
"(",
"cls",
",",
"matches",
")",
":",
"old_area",
"=",
"None",
"for",
"filename",
",",
"ranges",
"in",
"matches",
":",
"area",
",",
"name",
"=",
"os",
".",
"path",
".",
"split",
"(",
"filename",
")",
"if",
"not",
"area",
... | 39.5 | 0.00206 |
def find_non_contiguous(all_items):
"""Find any items that have slots that aren't contiguous"""
non_contiguous = []
for item in all_items:
if item.slots.count() < 2:
# No point in checking
continue
last_slot = None
for slot in item.slots.all().order_by('end_ti... | [
"def",
"find_non_contiguous",
"(",
"all_items",
")",
":",
"non_contiguous",
"=",
"[",
"]",
"for",
"item",
"in",
"all_items",
":",
"if",
"item",
".",
"slots",
".",
"count",
"(",
")",
"<",
"2",
":",
"# No point in checking",
"continue",
"last_slot",
"=",
"No... | 35.333333 | 0.001838 |
def addRow(self, *row):
"""
Add a row to the table. All items are converted to strings.
@type row: tuple
@keyword row: Each argument is a cell in the table.
"""
row = [ str(item) for item in row ]
len_row = [ len(item) for item in row ]
width = s... | [
"def",
"addRow",
"(",
"self",
",",
"*",
"row",
")",
":",
"row",
"=",
"[",
"str",
"(",
"item",
")",
"for",
"item",
"in",
"row",
"]",
"len_row",
"=",
"[",
"len",
"(",
"item",
")",
"for",
"item",
"in",
"row",
"]",
"width",
"=",
"self",
".",
"__w... | 35.75 | 0.02861 |
def form(value):
"""
Format numbers in a nice way.
>>> form(0)
'0'
>>> form(0.0)
'0.0'
>>> form(0.0001)
'1.000E-04'
>>> form(1003.4)
'1,003'
>>> form(103.4)
'103'
>>> form(9.3)
'9.30000'
>>> form(-1.2)
'-1.2'
"""
if isinstance(value, FLOAT + INT):... | [
"def",
"form",
"(",
"value",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"FLOAT",
"+",
"INT",
")",
":",
"if",
"value",
"<=",
"0",
":",
"return",
"str",
"(",
"value",
")",
"elif",
"value",
"<",
".001",
":",
"return",
"'%.3E'",
"%",
"value",
"... | 24.365854 | 0.000962 |
def get_module_names(path_dir, exclude=None):
if exclude is None: exclude = _default_exclude
"Search a given `path_dir` and return all the modules contained inside except those in `exclude`"
files = sorted(path_dir.glob('*'), key=lambda x: (x.is_dir(), x.name), reverse=True) # directories first
res = [f... | [
"def",
"get_module_names",
"(",
"path_dir",
",",
"exclude",
"=",
"None",
")",
":",
"if",
"exclude",
"is",
"None",
":",
"exclude",
"=",
"_default_exclude",
"files",
"=",
"sorted",
"(",
"path_dir",
".",
"glob",
"(",
"'*'",
")",
",",
"key",
"=",
"lambda",
... | 57.333333 | 0.018598 |
def two_swap_helper(j, k, num_qubits, qubit_map):
"""
Generate the permutation matrix that permutes two single-particle Hilbert
spaces into adjacent positions.
ALWAYS swaps j TO k. Recall that Hilbert spaces are ordered in decreasing
qubit index order. Hence, j > k implies that j is to the left of ... | [
"def",
"two_swap_helper",
"(",
"j",
",",
"k",
",",
"num_qubits",
",",
"qubit_map",
")",
":",
"if",
"not",
"(",
"0",
"<=",
"j",
"<",
"num_qubits",
"and",
"0",
"<=",
"k",
"<",
"num_qubits",
")",
":",
"raise",
"ValueError",
"(",
"\"Permutation SWAP index no... | 39.869565 | 0.002129 |
def clean_code(code, comments=True, macros=False, pragmas=False):
"""
Naive comment and macro striping from source code
:param comments: If True, all comments are stripped from code
:param macros: If True, all macros are stripped from code
:param pragmas: If True, all pragmas are stripped from code... | [
"def",
"clean_code",
"(",
"code",
",",
"comments",
"=",
"True",
",",
"macros",
"=",
"False",
",",
"pragmas",
"=",
"False",
")",
":",
"if",
"macros",
"or",
"pragmas",
":",
"lines",
"=",
"code",
".",
"split",
"(",
"'\\n'",
")",
"in_macro",
"=",
"False"... | 38.043478 | 0.001671 |
def get_by_identifier(self, identifier):
"""Gets blocks by identifier
Args:
identifier (str): Should be any of: username, phone_number, email.
See: https://auth0.com/docs/api/management/v2#!/User_Blocks/get_user_blocks
"""
params = {'identifier': identifier}
... | [
"def",
"get_by_identifier",
"(",
"self",
",",
"identifier",
")",
":",
"params",
"=",
"{",
"'identifier'",
":",
"identifier",
"}",
"return",
"self",
".",
"client",
".",
"get",
"(",
"self",
".",
"_url",
"(",
")",
",",
"params",
"=",
"params",
")"
] | 30.083333 | 0.008065 |
def new_workunit(self, name, labels=None, cmd='', log_config=None):
"""Creates a (hierarchical) subunit of work for the purpose of timing and reporting.
- name: A short name for this work. E.g., 'resolve', 'compile', 'scala', 'zinc'.
- labels: An optional iterable of labels. The reporters can use this to d... | [
"def",
"new_workunit",
"(",
"self",
",",
"name",
",",
"labels",
"=",
"None",
",",
"cmd",
"=",
"''",
",",
"log_config",
"=",
"None",
")",
":",
"parent",
"=",
"self",
".",
"_threadlocal",
".",
"current_workunit",
"with",
"self",
".",
"new_workunit_under_pare... | 45.833333 | 0.008547 |
def start_host(session=None):
"""Promote the current process into python plugin host for Nvim.
Start msgpack-rpc event loop for `session`, listening for Nvim requests
and notifications. It registers Nvim commands for loading/unloading
python plugins.
The sys.stdout and sys.stderr streams are redir... | [
"def",
"start_host",
"(",
"session",
"=",
"None",
")",
":",
"plugins",
"=",
"[",
"]",
"for",
"arg",
"in",
"sys",
".",
"argv",
":",
"_",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"arg",
")",
"if",
"ext",
"==",
"'.py'",
":",
"plug... | 33.245283 | 0.000551 |
def getBackgroundRange(fitParams):
'''
return minimum, average, maximum of the background peak
'''
smn, _, _ = getSignalParameters(fitParams)
bg = fitParams[0]
_, avg, std = bg
bgmn = max(0, avg - 3 * std)
if avg + 4 * std < smn:
bgmx = avg + 4 * std
if avg + 3 ... | [
"def",
"getBackgroundRange",
"(",
"fitParams",
")",
":",
"smn",
",",
"_",
",",
"_",
"=",
"getSignalParameters",
"(",
"fitParams",
")",
"bg",
"=",
"fitParams",
"[",
"0",
"]",
"_",
",",
"avg",
",",
"std",
"=",
"bg",
"bgmn",
"=",
"max",
"(",
"0",
",",... | 24.631579 | 0.002058 |
def cmd(send, msg, args):
"""Gets a definition from urban dictionary.
Syntax: {command} <[#<num>] <term>|--blacklist (word)|--unblacklist (word)>
"""
key = args['config']['api']['bitlykey']
parser = arguments.ArgParser(args['config'])
parser.add_argument('--blacklist')
parser.add_argument(... | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"key",
"=",
"args",
"[",
"'config'",
"]",
"[",
"'api'",
"]",
"[",
"'bitlykey'",
"]",
"parser",
"=",
"arguments",
".",
"ArgParser",
"(",
"args",
"[",
"'config'",
"]",
")",
"parser",
".",
... | 31.96875 | 0.000949 |
def computePWCorrelations(spikeTrains, removeAutoCorr):
"""
Computes pairwise correlations from spikeTrains
@param spikeTrains (array) spike trains obtained from the activation of cells in the TM
the array dimensions are: numCells x timeSteps
@param removeAutoCorr (boolean) if true, auto-correlation... | [
"def",
"computePWCorrelations",
"(",
"spikeTrains",
",",
"removeAutoCorr",
")",
":",
"numCells",
"=",
"np",
".",
"shape",
"(",
"spikeTrains",
")",
"[",
"0",
"]",
"corrMatrix",
"=",
"np",
".",
"zeros",
"(",
"(",
"numCells",
",",
"numCells",
")",
")",
"num... | 45.375 | 0.022482 |
def run(file, access_key, secret_key, **kwargs):
"""命令行运行huobitrade"""
if file:
import sys
file_path, file_name = os.path.split(file)
sys.path.append(file_path)
strategy_module = importlib.import_module(os.path.splitext(file_name)[0])
init = getattr(strategy_module, 'init... | [
"def",
"run",
"(",
"file",
",",
"access_key",
",",
"secret_key",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"file",
":",
"import",
"sys",
"file_path",
",",
"file_name",
"=",
"os",
".",
"path",
".",
"split",
"(",
"file",
")",
"sys",
".",
"path",
".",
... | 28.230769 | 0.001504 |
def grid_list(data):
'''
#=================================================
/process the grid data
/convert to list data for poly fitting
#=================================================
'''
a = []
b = []
M = []
for i in data:
a.append(i[0]) # np.array([i[1] for i in d... | [
"def",
"grid_list",
"(",
"data",
")",
":",
"a",
"=",
"[",
"]",
"b",
"=",
"[",
"]",
"M",
"=",
"[",
"]",
"for",
"i",
"in",
"data",
":",
"a",
".",
"append",
"(",
"i",
"[",
"0",
"]",
")",
"# np.array([i[1] for i in data], dtype=np.float64)",
"b",
".",
... | 33.8 | 0.001439 |
def to_rgba(colors, alpha):
"""
Covert hex colors to rgba values.
Parameters
----------
colors : iterable | str
colors to convert
alphas : iterable | float
alpha values
Returns
-------
out : ndarray | tuple
rgba color(s)
Notes
-----
Matplotlib p... | [
"def",
"to_rgba",
"(",
"colors",
",",
"alpha",
")",
":",
"def",
"is_iterable",
"(",
"var",
")",
":",
"return",
"cbook",
".",
"iterable",
"(",
"var",
")",
"and",
"not",
"is_string",
"(",
"var",
")",
"def",
"has_alpha",
"(",
"c",
")",
":",
"if",
"isi... | 26.43662 | 0.000514 |
def tmp_file(suffix=u"", root=None):
"""
Return a (handler, path) tuple
for a temporary file with given suffix created by ``tempfile``.
:param string suffix: the suffix (e.g., the extension) of the file
:param string root: path to the root temporary directory;
if ``None``, t... | [
"def",
"tmp_file",
"(",
"suffix",
"=",
"u\"\"",
",",
"root",
"=",
"None",
")",
":",
"if",
"root",
"is",
"None",
":",
"root",
"=",
"custom_tmp_dir",
"(",
")",
"return",
"tempfile",
".",
"mkstemp",
"(",
"suffix",
"=",
"suffix",
",",
"dir",
"=",
"root",... | 36.714286 | 0.001898 |
def get_client(self, client_type):
"""get_client.
"""
if client_type not in self._client_cache:
client_class = self._get_class(client_type)
self._client_cache[client_type] = self._get_client_instance(client_class)
return self._client_cache[client_type] | [
"def",
"get_client",
"(",
"self",
",",
"client_type",
")",
":",
"if",
"client_type",
"not",
"in",
"self",
".",
"_client_cache",
":",
"client_class",
"=",
"self",
".",
"_get_class",
"(",
"client_type",
")",
"self",
".",
"_client_cache",
"[",
"client_type",
"]... | 43.142857 | 0.00974 |
def build_api_url(
cls, path, query_params=None, api_base_url=None, api_version=None
):
"""Construct an API url given a few components, some optional.
Typically, you shouldn't need to use this method.
:type path: str
:param path: The path to the resource (ie, ``'/b/bucket-n... | [
"def",
"build_api_url",
"(",
"cls",
",",
"path",
",",
"query_params",
"=",
"None",
",",
"api_base_url",
"=",
"None",
",",
"api_version",
"=",
"None",
")",
":",
"url",
"=",
"cls",
".",
"API_URL_TEMPLATE",
".",
"format",
"(",
"api_base_url",
"=",
"(",
"api... | 35.842105 | 0.002144 |
def shuffle_genome(genome, cat, fraction = float(100), plot = True, \
alpha = 0.1, beta = 100000, \
min_length = 1000, max_length = 200000):
"""
randomly shuffle genome
"""
header = '>randomized_%s' % (genome.name)
sequence = list(''.join([i[1] for i in parse_fasta(genome)]))
len... | [
"def",
"shuffle_genome",
"(",
"genome",
",",
"cat",
",",
"fraction",
"=",
"float",
"(",
"100",
")",
",",
"plot",
"=",
"True",
",",
"alpha",
"=",
"0.1",
",",
"beta",
"=",
"100000",
",",
"min_length",
"=",
"1000",
",",
"max_length",
"=",
"200000",
")",... | 34.411765 | 0.010526 |
def getlayer(self, cls, nb=1, _track=None, _subclass=None, **flt):
"""Return the nb^th layer that is an instance of cls, matching flt
values.
"""
if _subclass is None:
_subclass = self.match_subclass or None
if _subclass:
match = lambda cls1, cls2: issubclass(cls1... | [
"def",
"getlayer",
"(",
"self",
",",
"cls",
",",
"nb",
"=",
"1",
",",
"_track",
"=",
"None",
",",
"_subclass",
"=",
"None",
",",
"*",
"*",
"flt",
")",
":",
"if",
"_subclass",
"is",
"None",
":",
"_subclass",
"=",
"self",
".",
"match_subclass",
"or",... | 40.136364 | 0.002211 |
def execNetstatCmd(self, *args):
"""Execute ps command with positional params args and return result as
list of lines.
@param *args: Positional params for netstat command.
@return: List of output lines
"""
out = util.exec_command([netstatCmd,] + li... | [
"def",
"execNetstatCmd",
"(",
"self",
",",
"*",
"args",
")",
":",
"out",
"=",
"util",
".",
"exec_command",
"(",
"[",
"netstatCmd",
",",
"]",
"+",
"list",
"(",
"args",
")",
")",
"return",
"out",
".",
"splitlines",
"(",
")"
] | 35.2 | 0.01662 |
def remove_row(self, row_number: int=-1):
"""
Removes a specified row of data
:param row_number: the row to remove (defaults to the last row)
:return: None
"""
if len(self._rows) == 0:
return
row = self._rows.pop(row_number)
for widget in row... | [
"def",
"remove_row",
"(",
"self",
",",
"row_number",
":",
"int",
"=",
"-",
"1",
")",
":",
"if",
"len",
"(",
"self",
".",
"_rows",
")",
"==",
"0",
":",
"return",
"row",
"=",
"self",
".",
"_rows",
".",
"pop",
"(",
"row_number",
")",
"for",
"widget"... | 26 | 0.011429 |
def register_class(cls):
"""Regsiter this class in the `LinkFactory` """
if cls.appname in LinkFactory._class_dict:
return
LinkFactory.register(cls.appname, cls) | [
"def",
"register_class",
"(",
"cls",
")",
":",
"if",
"cls",
".",
"appname",
"in",
"LinkFactory",
".",
"_class_dict",
":",
"return",
"LinkFactory",
".",
"register",
"(",
"cls",
".",
"appname",
",",
"cls",
")"
] | 38.6 | 0.010152 |
def completion_hints(config, prompt, session, context, current, arguments):
# type: (CompletionInfo, str, ShellSession, BundleContext, str, List[str]) -> List[str]
"""
Returns the possible completions of the current argument
:param config: Configuration of the current completion
:param prompt: The ... | [
"def",
"completion_hints",
"(",
"config",
",",
"prompt",
",",
"session",
",",
"context",
",",
"current",
",",
"arguments",
")",
":",
"# type: (CompletionInfo, str, ShellSession, BundleContext, str, List[str]) -> List[str]",
"if",
"not",
"current",
":",
"# No word yet, so th... | 33.779661 | 0.000975 |
def from_string(cls, string, relpath=None, encoding=None, is_sass=None):
"""Read Sass source from the contents of a string.
The origin is always None. `relpath` defaults to "string:...".
"""
if isinstance(string, six.text_type):
# Already decoded; we don't know what encodin... | [
"def",
"from_string",
"(",
"cls",
",",
"string",
",",
"relpath",
"=",
"None",
",",
"encoding",
"=",
"None",
",",
"is_sass",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"string",
",",
"six",
".",
"text_type",
")",
":",
"# Already decoded; we don't know ... | 38.757576 | 0.001526 |
def naturaldate(value):
"""Like naturalday, but will append a year for dates that are a year
ago or more."""
try:
value = date(value.year, value.month, value.day)
except AttributeError:
# Passed value wasn't date-ish
return value
except (OverflowError, ValueError):
# ... | [
"def",
"naturaldate",
"(",
"value",
")",
":",
"try",
":",
"value",
"=",
"date",
"(",
"value",
".",
"year",
",",
"value",
".",
"month",
",",
"value",
".",
"day",
")",
"except",
"AttributeError",
":",
"# Passed value wasn't date-ish",
"return",
"value",
"exc... | 33.466667 | 0.001938 |
def i2m(self, pkt, x):
"""Convert internal value to machine value"""
if x is None:
# Try to return zero if undefined
x = self.h2i(pkt, 0)
return x | [
"def",
"i2m",
"(",
"self",
",",
"pkt",
",",
"x",
")",
":",
"if",
"x",
"is",
"None",
":",
"# Try to return zero if undefined",
"x",
"=",
"self",
".",
"h2i",
"(",
"pkt",
",",
"0",
")",
"return",
"x"
] | 31.5 | 0.010309 |
def update(self):
"""Update the HVAC state."""
self._controller.update(self._id, wake_if_asleep=False)
data = self._controller.get_climate_params(self._id)
if data:
if time.time() - self.__manual_update_time > 60:
self.__is_auto_conditioning_on = (data
... | [
"def",
"update",
"(",
"self",
")",
":",
"self",
".",
"_controller",
".",
"update",
"(",
"self",
".",
"_id",
",",
"wake_if_asleep",
"=",
"False",
")",
"data",
"=",
"self",
".",
"_controller",
".",
"get_climate_params",
"(",
"self",
".",
"_id",
")",
"if"... | 58.043478 | 0.001474 |
def cuts(self, data,
xtitle=None, ytitle=None, title=None, rtitle=None,
color=None):
"""data: pixel values along a line.
"""
y = data
x = np.arange(len(data))
self.plot(x, y, color=color, drawstyle='steps-mid',
xtitle=xtitle, ytitle=yt... | [
"def",
"cuts",
"(",
"self",
",",
"data",
",",
"xtitle",
"=",
"None",
",",
"ytitle",
"=",
"None",
",",
"title",
"=",
"None",
",",
"rtitle",
"=",
"None",
",",
"color",
"=",
"None",
")",
":",
"y",
"=",
"data",
"x",
"=",
"np",
".",
"arange",
"(",
... | 36.545455 | 0.009709 |
def getActiveJobCountForClientKey(self, clientKey):
""" Return the number of jobs for the given clientKey and a status that is
not completed.
"""
with ConnectionFactory.get() as conn:
query = 'SELECT count(job_id) ' \
'FROM %s ' \
'WHERE client_key = %%s ' \
... | [
"def",
"getActiveJobCountForClientKey",
"(",
"self",
",",
"clientKey",
")",
":",
"with",
"ConnectionFactory",
".",
"get",
"(",
")",
"as",
"conn",
":",
"query",
"=",
"'SELECT count(job_id) '",
"'FROM %s '",
"'WHERE client_key = %%s '",
"' AND status != %%s'",
"%",
"sel... | 38.307692 | 0.009804 |
def map(function, iterable, *args, **kwargs):
"""This function is equivalent to:
>>> [function(x, args[0], args[1],...) for x in iterable]
:param pm_parallel: Force parallelization on/off
:type pm_parallel: bool
:param pm_chunksize: see :py:class:`multiprocessing.pool.Pool`
:ty... | [
"def",
"map",
"(",
"function",
",",
"iterable",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_map_or_starmap",
"(",
"function",
",",
"iterable",
",",
"args",
",",
"kwargs",
",",
"\"map\"",
")"
] | 41.823529 | 0.001376 |
def main():
"""
Connect to an SNI-enabled server and request a specific hostname, specified
by argv[1], of it.
"""
if len(argv) < 2:
print('Usage: %s <hostname>' % (argv[0],))
return 1
client = socket()
print('Connecting...', end="")
stdout.flush()
client.connect(('... | [
"def",
"main",
"(",
")",
":",
"if",
"len",
"(",
"argv",
")",
"<",
"2",
":",
"print",
"(",
"'Usage: %s <hostname>'",
"%",
"(",
"argv",
"[",
"0",
"]",
",",
")",
")",
"return",
"1",
"client",
"=",
"socket",
"(",
")",
"print",
"(",
"'Connecting...'",
... | 28.863636 | 0.001524 |
def bounce_cluster(name):
'''
Bounce all Traffic Server nodes in the cluster. Bouncing Traffic Server
shuts down and immediately restarts Traffic Server, node-by-node.
.. code-block:: yaml
bounce_ats_cluster:
trafficserver.bounce_cluster
'''
ret = {'name': name,
'c... | [
"def",
"bounce_cluster",
"(",
"name",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'changes'",
":",
"{",
"}",
",",
"'result'",
":",
"None",
",",
"'comment'",
":",
"''",
"}",
"if",
"__opts__",
"[",
"'test'",
"]",
":",
"ret",
"[",
"'commen... | 24.125 | 0.001661 |
def save_widget(cls, editor):
"""
Implements SplittableTabWidget.save_widget to actually save the
code editor widget.
If the editor.file.path is None or empty or the file does not exist,
a save as dialog is shown (save as).
:param editor: editor widget to save.
... | [
"def",
"save_widget",
"(",
"cls",
",",
"editor",
")",
":",
"if",
"editor",
".",
"original",
":",
"editor",
"=",
"editor",
".",
"original",
"if",
"editor",
".",
"file",
".",
"path",
"is",
"None",
"or",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"... | 41.674419 | 0.001636 |
def generate_strip_subparser(subparsers):
"""Adds a sub-command parser to `subparsers` to process prepared files
for use with the tacl ngrams command."""
parser = subparsers.add_parser(
'strip', description=constants.STRIP_DESCRIPTION,
epilog=constants.STRIP_EPILOG, formatter_class=Paragraph... | [
"def",
"generate_strip_subparser",
"(",
"subparsers",
")",
":",
"parser",
"=",
"subparsers",
".",
"add_parser",
"(",
"'strip'",
",",
"description",
"=",
"constants",
".",
"STRIP_DESCRIPTION",
",",
"epilog",
"=",
"constants",
".",
"STRIP_EPILOG",
",",
"formatter_cl... | 50.076923 | 0.001508 |
def xception_internal(inputs, hparams):
"""Xception body."""
with tf.variable_scope("xception"):
cur = inputs
if cur.get_shape().as_list()[1] > 200:
# Large image, Xception entry flow
cur = xception_entry(cur, hparams.hidden_size)
else:
# Small image, conv
cur = common_layers.co... | [
"def",
"xception_internal",
"(",
"inputs",
",",
"hparams",
")",
":",
"with",
"tf",
".",
"variable_scope",
"(",
"\"xception\"",
")",
":",
"cur",
"=",
"inputs",
"if",
"cur",
".",
"get_shape",
"(",
")",
".",
"as_list",
"(",
")",
"[",
"1",
"]",
">",
"200... | 28.434783 | 0.011834 |
def _read_syncmap_file(self, path, extension, text=False):
""" Read labels from a SyncMap file """
syncmap = SyncMap(logger=self.logger)
syncmap.read(extension, path, parameters=None)
if text:
return [(f.begin, f.end, u" ".join(f.text_fragment.lines)) for f in syncmap.fragmen... | [
"def",
"_read_syncmap_file",
"(",
"self",
",",
"path",
",",
"extension",
",",
"text",
"=",
"False",
")",
":",
"syncmap",
"=",
"SyncMap",
"(",
"logger",
"=",
"self",
".",
"logger",
")",
"syncmap",
".",
"read",
"(",
"extension",
",",
"path",
",",
"parame... | 58 | 0.009709 |
def _build_offset(offset, kwargs, default):
"""
Builds the offset argument for event rules.
"""
if offset is None:
if not kwargs:
return default # use the default.
else:
return _td_check(datetime.timedelta(**kwargs))
elif kwargs:
raise ValueError('Can... | [
"def",
"_build_offset",
"(",
"offset",
",",
"kwargs",
",",
"default",
")",
":",
"if",
"offset",
"is",
"None",
":",
"if",
"not",
"kwargs",
":",
"return",
"default",
"# use the default.",
"else",
":",
"return",
"_td_check",
"(",
"datetime",
".",
"timedelta",
... | 33.533333 | 0.001934 |
def execute(self, context):
"""
Call the OpsgenieAlertHook to post message
"""
self.hook = OpsgenieAlertHook(self.opsgenie_conn_id)
self.hook.execute(self._build_opsgenie_payload()) | [
"def",
"execute",
"(",
"self",
",",
"context",
")",
":",
"self",
".",
"hook",
"=",
"OpsgenieAlertHook",
"(",
"self",
".",
"opsgenie_conn_id",
")",
"self",
".",
"hook",
".",
"execute",
"(",
"self",
".",
"_build_opsgenie_payload",
"(",
")",
")"
] | 36 | 0.00905 |
def deploy_windows(host,
port=445,
timeout=900,
username='Administrator',
password=None,
name=None,
sock_dir=None,
conf_file=None,
start_action=None,
... | [
"def",
"deploy_windows",
"(",
"host",
",",
"port",
"=",
"445",
",",
"timeout",
"=",
"900",
",",
"username",
"=",
"'Administrator'",
",",
"password",
"=",
"None",
",",
"name",
"=",
"None",
",",
"sock_dir",
"=",
"None",
",",
"conf_file",
"=",
"None",
","... | 38.633663 | 0.001749 |
def set_default_decoder_parameters():
"""Wraps openjp2 library function opj_set_default_decoder_parameters.
Sets decoding parameters to default values.
Returns
-------
dparam : DecompressionParametersType
Decompression parameters.
"""
ARGTYPES = [ctypes.POINTER(DecompressionParamet... | [
"def",
"set_default_decoder_parameters",
"(",
")",
":",
"ARGTYPES",
"=",
"[",
"ctypes",
".",
"POINTER",
"(",
"DecompressionParametersType",
")",
"]",
"OPENJP2",
".",
"opj_set_default_decoder_parameters",
".",
"argtypes",
"=",
"ARGTYPES",
"OPENJP2",
".",
"opj_set_defau... | 34.529412 | 0.001658 |
def _pulse_method_call(pulse_op, func=None, index_arg=True):
'''Creates following synchronous wrapper for async pa_operation callable:
wrapper(index, ...) -> pulse_op(index, [*]args_func(...))
index_arg=False: wrapper(...) -> pulse_op([*]args_func(...))'''
def _wrapper(self, *args, **kws):
if index_arg:
... | [
"def",
"_pulse_method_call",
"(",
"pulse_op",
",",
"func",
"=",
"None",
",",
"index_arg",
"=",
"True",
")",
":",
"def",
"_wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kws",
")",
":",
"if",
"index_arg",
":",
"if",
"'index'",
"in",
"kws",
... | 51.227273 | 0.027875 |
def weld_replace(array, weld_type, this, to):
"""Replaces 'this' values to 'to' value.
Parameters
----------
array : numpy.ndarray or WeldObject
Input array.
weld_type : WeldType
Type of the data in the array.
this : {int, float, str, bool, bytes}
Scalar to replace.
... | [
"def",
"weld_replace",
"(",
"array",
",",
"weld_type",
",",
"this",
",",
"to",
")",
":",
"if",
"not",
"isinstance",
"(",
"this",
",",
"str",
")",
":",
"this",
"=",
"to_weld_literal",
"(",
"this",
",",
"weld_type",
")",
"to",
"=",
"to_weld_literal",
"("... | 24.875 | 0.001934 |
def load_with_classes(filename, classes):
"""Attempts to load file by trial-and-error using a given list of classes.
Arguments:
filename -- full path to file
classes -- list of classes having a load() method
Returns: DataFile object if loaded successfully, or None if not.
Note: it will st... | [
"def",
"load_with_classes",
"(",
"filename",
",",
"classes",
")",
":",
"ok",
"=",
"False",
"for",
"class_",
"in",
"classes",
":",
"obj",
"=",
"class_",
"(",
")",
"try",
":",
"obj",
".",
"load",
"(",
"filename",
")",
"ok",
"=",
"True",
"# # cannot let I... | 32.825 | 0.002219 |
def eq(self, other):
"""
Construct a Filter returning True for asset/date pairs where the output
of ``self`` matches ``other``.
"""
# We treat this as an error because missing_values have NaN semantics,
# which means this would return an array of all False, which is almos... | [
"def",
"eq",
"(",
"self",
",",
"other",
")",
":",
"# We treat this as an error because missing_values have NaN semantics,",
"# which means this would return an array of all False, which is almost",
"# certainly not what the user wants.",
"if",
"other",
"==",
"self",
".",
"missing_val... | 38.411765 | 0.001494 |
def classifyplot_from_valfile(val_file, outtype="png", title=None, size=None,
samples=None, callers=None):
"""Create a plot from a summarized validation file.
Does new-style plotting of summarized metrics of
false negative rate and false discovery rate.
https://en.wikipedi... | [
"def",
"classifyplot_from_valfile",
"(",
"val_file",
",",
"outtype",
"=",
"\"png\"",
",",
"title",
"=",
"None",
",",
"size",
"=",
"None",
",",
"samples",
"=",
"None",
",",
"callers",
"=",
"None",
")",
":",
"mpl",
".",
"use",
"(",
"'Agg'",
",",
"force",... | 39.473684 | 0.001302 |
def history(self, hash):
"""
Retrieve the ownership tree of all editions of a piece given the hash.
Args:
hash (str): Hash of the file to check. Can be created with the
:class:`File` class
Returns:
dict: Ownsership tree of all editions of a piece... | [
"def",
"history",
"(",
"self",
",",
"hash",
")",
":",
"txs",
"=",
"self",
".",
"_t",
".",
"get",
"(",
"hash",
",",
"max_transactions",
"=",
"10000",
")",
"[",
"'transactions'",
"]",
"tree",
"=",
"defaultdict",
"(",
"list",
")",
"number_editions",
"=",
... | 40.816327 | 0.001953 |
def kill(self):
"""Kill instantiated process
:raises: `AttributeError` if instantiated process doesn't seem to satisfy `constraints <relshell.daemon_shelloperator.DaemonShellOperator>`_
"""
BaseShellOperator._close_process_input_stdin(self._batcmd.batch_to_file_s)
BaseShellOpera... | [
"def",
"kill",
"(",
"self",
")",
":",
"BaseShellOperator",
".",
"_close_process_input_stdin",
"(",
"self",
".",
"_batcmd",
".",
"batch_to_file_s",
")",
"BaseShellOperator",
".",
"_wait_process",
"(",
"self",
".",
"_process",
",",
"self",
".",
"_batcmd",
".",
"... | 55.777778 | 0.011765 |
def get_all_settings(profile, store='local'):
'''
Gets all the properties for the specified profile in the specified store
Args:
profile (str):
The firewall profile to query. Valid options are:
- domain
- public
- private
store (str):
... | [
"def",
"get_all_settings",
"(",
"profile",
",",
"store",
"=",
"'local'",
")",
":",
"ret",
"=",
"dict",
"(",
")",
"ret",
".",
"update",
"(",
"get_settings",
"(",
"profile",
"=",
"profile",
",",
"section",
"=",
"'state'",
",",
"store",
"=",
"store",
")",... | 30.258065 | 0.002066 |
def get_forecast(self):
'''
If configured to do so, make an API request to retrieve the forecast
data for the configured/queried weather station, and return the low and
high temperatures. Otherwise, return two empty strings.
'''
no_data = ('', '')
if self.forecast... | [
"def",
"get_forecast",
"(",
"self",
")",
":",
"no_data",
"=",
"(",
"''",
",",
"''",
")",
"if",
"self",
".",
"forecast",
":",
"query_url",
"=",
"STATION_QUERY_URL",
"%",
"(",
"self",
".",
"api_key",
",",
"'forecast'",
",",
"self",
".",
"station_id",
")"... | 44.615385 | 0.001688 |
def prepare_sentence(self, sentence):
"""Prepare the sentence for segment detection."""
# depending on how the morphological analysis was added, there may be
# phonetic markup. Remove it, if it exists.
for word in sentence:
for analysis in word[ANALYSIS]:
anal... | [
"def",
"prepare_sentence",
"(",
"self",
",",
"sentence",
")",
":",
"# depending on how the morphological analysis was added, there may be",
"# phonetic markup. Remove it, if it exists.",
"for",
"word",
"in",
"sentence",
":",
"for",
"analysis",
"in",
"word",
"[",
"ANALYSIS",
... | 54.111111 | 0.008081 |
def do_not_cache():
""" Return whether we should cache a page render """
from . import index # pylint: disable=cyclic-import
if index.in_progress():
# We are reindexing the site
return True
if request.if_none_match or request.if_modified_since:
# we might be returning a 304 N... | [
"def",
"do_not_cache",
"(",
")",
":",
"from",
".",
"import",
"index",
"# pylint: disable=cyclic-import",
"if",
"index",
".",
"in_progress",
"(",
")",
":",
"# We are reindexing the site",
"return",
"True",
"if",
"request",
".",
"if_none_match",
"or",
"request",
"."... | 30.3125 | 0.002 |
def is_value_from_deprecated_setting(self, setting_name, deprecated_setting_name):
"""
Helps developers to determine where the settings helper got it's value
from when dealing with settings that replace deprecated settings.
Returns ``True`` when the new setting (with the name ``setting_... | [
"def",
"is_value_from_deprecated_setting",
"(",
"self",
",",
"setting_name",
",",
"deprecated_setting_name",
")",
":",
"if",
"not",
"self",
".",
"in_defaults",
"(",
"setting_name",
")",
":",
"self",
".",
"_raise_invalid_setting_name_error",
"(",
"setting_name",
")",
... | 48.060606 | 0.001854 |
def write(self, filepath, magicc_version):
"""
Write an input file to disk.
Parameters
----------
filepath : str
Filepath of the file to write.
magicc_version : int
The MAGICC version for which we want to write files. MAGICC7 and MAGICC6
... | [
"def",
"write",
"(",
"self",
",",
"filepath",
",",
"magicc_version",
")",
":",
"writer",
"=",
"determine_tool",
"(",
"filepath",
",",
"\"writer\"",
")",
"(",
"magicc_version",
"=",
"magicc_version",
")",
"writer",
".",
"write",
"(",
"self",
",",
"filepath",
... | 33.125 | 0.009174 |
def updateMigrationRequestStatus(self, migration_status, migration_request_id):
"""
migration_status:
0=PENDING
1=IN PROGRESS
2=COMPLETED
3=FAILED (will be retried)
9=Terminally FAILED
status change:
0 -> 1
1 -> 2
1 -> 3
1 ... | [
"def",
"updateMigrationRequestStatus",
"(",
"self",
",",
"migration_status",
",",
"migration_request_id",
")",
":",
"conn",
"=",
"self",
".",
"dbi",
".",
"connection",
"(",
")",
"tran",
"=",
"conn",
".",
"begin",
"(",
")",
"try",
":",
"upst",
"=",
"dict",
... | 29.575758 | 0.010913 |
def read_data(self, chan=[], ref_chan=[], grp_name=None, concat_chan=False,
max_s_freq=30000, parent=None):
"""Read data for analysis. Adds data as 'data' in each dict.
Parameters
----------
chan : list of str
active channel names as they appear in record,... | [
"def",
"read_data",
"(",
"self",
",",
"chan",
"=",
"[",
"]",
",",
"ref_chan",
"=",
"[",
"]",
",",
"grp_name",
"=",
"None",
",",
"concat_chan",
"=",
"False",
",",
"max_s_freq",
"=",
"30000",
",",
"parent",
"=",
"None",
")",
":",
"output",
"=",
"[",
... | 41.026316 | 0.00167 |
def fftconv(a, b, axes=(0, 1)):
"""
Compute a multi-dimensional convolution via the Discrete Fourier
Transform. Note that the output has a phase shift relative to the
output of :func:`scipy.ndimage.convolve` with the default ``origin``
parameter.
Parameters
----------
a : array_like
... | [
"def",
"fftconv",
"(",
"a",
",",
"b",
",",
"axes",
"=",
"(",
"0",
",",
"1",
")",
")",
":",
"if",
"np",
".",
"isrealobj",
"(",
"a",
")",
"and",
"np",
".",
"isrealobj",
"(",
"b",
")",
":",
"fft",
"=",
"rfftn",
"ifft",
"=",
"irfftn",
"else",
"... | 26.90625 | 0.001121 |
def _record_values_for_fit_summary_and_statsmodels(self):
"""
Store the various estimation results that are used to describe how well
the estimated model fits the given dataset, and record the values that
are needed for the statsmodels estimation results table. All values are
sto... | [
"def",
"_record_values_for_fit_summary_and_statsmodels",
"(",
"self",
")",
":",
"# Make sure we have all attributes needed to create the results summary",
"needed_attributes",
"=",
"[",
"\"fitted_probs\"",
",",
"\"params\"",
",",
"\"log_likelihood\"",
",",
"\"standard_errors\"",
"]... | 43.243902 | 0.001103 |
def _function_lookup(name, module):
"""Searches the function between the registered ones.
If not found, it imports the module forcing its registration.
"""
try:
return _registered_functions[name]
except KeyError: # force function registering
__import__(module)
mod = sys.mod... | [
"def",
"_function_lookup",
"(",
"name",
",",
"module",
")",
":",
"try",
":",
"return",
"_registered_functions",
"[",
"name",
"]",
"except",
"KeyError",
":",
"# force function registering",
"__import__",
"(",
"module",
")",
"mod",
"=",
"sys",
".",
"modules",
"[... | 30.076923 | 0.002481 |
def remove_patch(self, patch):
""" Remove a patch from the patches list """
self._check_patch(patch)
patchline = self.patch2line[patch]
del self.patch2line[patch]
self.patchlines.remove(patchline) | [
"def",
"remove_patch",
"(",
"self",
",",
"patch",
")",
":",
"self",
".",
"_check_patch",
"(",
"patch",
")",
"patchline",
"=",
"self",
".",
"patch2line",
"[",
"patch",
"]",
"del",
"self",
".",
"patch2line",
"[",
"patch",
"]",
"self",
".",
"patchlines",
... | 38.5 | 0.008475 |
def fill_traversals(traversals, edges, edges_hash=None):
"""
Convert a traversal of a list of edges into a sequence of
traversals where every pair of consecutive node indexes
is an edge in a passed edge list
Parameters
-------------
traversals : sequence of (m,) int
Node indexes of t... | [
"def",
"fill_traversals",
"(",
"traversals",
",",
"edges",
",",
"edges_hash",
"=",
"None",
")",
":",
"# make sure edges are correct type",
"edges",
"=",
"np",
".",
"asanyarray",
"(",
"edges",
",",
"dtype",
"=",
"np",
".",
"int64",
")",
"# make sure edges are sor... | 31.15 | 0.000519 |
def ensembl_to_kegg(organism,kegg_db):
"""
Looks up KEGG mappings of KEGG ids to ensembl ids
:param organism: an organisms as listed in organismsKEGG()
:param kegg_db: a matching KEGG db as reported in databasesKEGG
:returns: a Pandas dataframe of with 'KEGGid' and 'ENSid'.
"""
print("KEG... | [
"def",
"ensembl_to_kegg",
"(",
"organism",
",",
"kegg_db",
")",
":",
"print",
"(",
"\"KEGG API: http://rest.genome.jp/link/\"",
"+",
"kegg_db",
"+",
"\"/\"",
"+",
"organism",
")",
"sys",
".",
"stdout",
".",
"flush",
"(",
")",
"kegg_ens",
"=",
"urlopen",
"(",
... | 34.565217 | 0.019584 |
def add(self, func, priority=0):
""" Add a func to the cmd chain with given priority """
self.chain.append((priority, func))
self.chain.sort(key=lambda x: x[0]) | [
"def",
"add",
"(",
"self",
",",
"func",
",",
"priority",
"=",
"0",
")",
":",
"self",
".",
"chain",
".",
"append",
"(",
"(",
"priority",
",",
"func",
")",
")",
"self",
".",
"chain",
".",
"sort",
"(",
"key",
"=",
"lambda",
"x",
":",
"x",
"[",
"... | 45.25 | 0.01087 |
def compute_stable_poses(mesh,
center_mass=None,
sigma=0.0,
n_samples=1,
threshold=0.0):
"""
Computes stable orientations of a mesh and their quasi-static probabilites.
This method samples the location of th... | [
"def",
"compute_stable_poses",
"(",
"mesh",
",",
"center_mass",
"=",
"None",
",",
"sigma",
"=",
"0.0",
",",
"n_samples",
"=",
"1",
",",
"threshold",
"=",
"0.0",
")",
":",
"# save convex hull mesh to avoid a cache check",
"cvh",
"=",
"mesh",
".",
"convex_hull",
... | 34.440559 | 0.000197 |
def download_layers(self, repo_name, digest=None, destination=None):
''' download layers is a wrapper to do the following for a client loaded
with a manifest for an image:
1. use the manifests to retrieve list of digests (get_digests)
2. atomically download the list to destination (ge... | [
"def",
"download_layers",
"(",
"self",
",",
"repo_name",
",",
"digest",
"=",
"None",
",",
"destination",
"=",
"None",
")",
":",
"from",
"sregistry",
".",
"main",
".",
"workers",
"import",
"Workers",
"from",
"sregistry",
".",
"main",
".",
"workers",
".",
... | 32.155556 | 0.002012 |
def autologin(function, timeout=TIMEOUT):
"""Decorator that will try to login and redo an action before failing."""
@wraps(function)
async def wrapper(self, *args, **kwargs):
"""Wrap a function with timeout."""
try:
async with async_timeout.timeout(timeout):
retur... | [
"def",
"autologin",
"(",
"function",
",",
"timeout",
"=",
"TIMEOUT",
")",
":",
"@",
"wraps",
"(",
"function",
")",
"async",
"def",
"wrapper",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"Wrap a function with timeout.\"\"\"",
"tr... | 36.7 | 0.001328 |
def browse_stations(self, station_category_id):
"""Get the stations for a category from Browse Stations.
Parameters:
station_category_id (str): A station category ID as
found with :meth:`browse_stations_categories`.
Returns:
list: Station dicts.
"""
response = self._call(
mc_calls.BrowseStatio... | [
"def",
"browse_stations",
"(",
"self",
",",
"station_category_id",
")",
":",
"response",
"=",
"self",
".",
"_call",
"(",
"mc_calls",
".",
"BrowseStations",
",",
"station_category_id",
")",
"stations",
"=",
"response",
".",
"body",
".",
"get",
"(",
"'stations'"... | 22.166667 | 0.036058 |
def msg(self, level, s, *args):
"""
Print a debug message with the given level
"""
if s and level <= self.debug:
print "%s%s %s" % (" " * self.indent, s, ' '.join(map(repr, args))) | [
"def",
"msg",
"(",
"self",
",",
"level",
",",
"s",
",",
"*",
"args",
")",
":",
"if",
"s",
"and",
"level",
"<=",
"self",
".",
"debug",
":",
"print",
"\"%s%s %s\"",
"%",
"(",
"\" \"",
"*",
"self",
".",
"indent",
",",
"s",
",",
"' '",
".",
"join"... | 36.666667 | 0.013333 |
def check_password(self, raw_password):
"""Validates the given raw password against the intance's encrypted one.
:param raw_password: Raw password to be checked against.
:type raw_password: unicode
:returns: True if comparison was successful, False otherwise.
:rtype: bool
... | [
"def",
"check_password",
"(",
"self",
",",
"raw_password",
")",
":",
"bcrypt",
"=",
"self",
".",
"get_bcrypt",
"(",
")",
"return",
"bcrypt",
".",
"hashpw",
"(",
"raw_password",
",",
"self",
".",
"value",
")",
"==",
"self",
".",
"value"
] | 43.909091 | 0.008114 |
def toggle(self, key):
""" Toggles a boolean key """
val = self[key]
assert isinstance(val, bool), 'key[%r] = %r is not a bool' % (key, val)
self.pref_update(key, not val) | [
"def",
"toggle",
"(",
"self",
",",
"key",
")",
":",
"val",
"=",
"self",
"[",
"key",
"]",
"assert",
"isinstance",
"(",
"val",
",",
"bool",
")",
",",
"'key[%r] = %r is not a bool'",
"%",
"(",
"key",
",",
"val",
")",
"self",
".",
"pref_update",
"(",
"ke... | 39.8 | 0.009852 |
def models(cls, api_version=DEFAULT_API_VERSION):
"""Module depends on the API version:
* 2016-06-01: :mod:`v2016_06_01.models<azure.mgmt.resource.subscriptions.v2016_06_01.models>`
"""
if api_version == '2016-06-01':
from .v2016_06_01 import models
return mod... | [
"def",
"models",
"(",
"cls",
",",
"api_version",
"=",
"DEFAULT_API_VERSION",
")",
":",
"if",
"api_version",
"==",
"'2016-06-01'",
":",
"from",
".",
"v2016_06_01",
"import",
"models",
"return",
"models",
"raise",
"NotImplementedError",
"(",
"\"APIVersion {} is not av... | 44.777778 | 0.009732 |
def strip_pad(hdu):
"""Remove the padding lines that CFHT adds to headers"""
l = hdu.header.ascardlist()
d = []
for index in range(len(l)):
if l[index].key in __comment_keys and str(l[index])==__cfht_padding:
d.append(index)
d.reverse()
for index in d:
del l[inde... | [
"def",
"strip_pad",
"(",
"hdu",
")",
":",
"l",
"=",
"hdu",
".",
"header",
".",
"ascardlist",
"(",
")",
"d",
"=",
"[",
"]",
"for",
"index",
"in",
"range",
"(",
"len",
"(",
"l",
")",
")",
":",
"if",
"l",
"[",
"index",
"]",
".",
"key",
"in",
"... | 27.083333 | 0.011905 |
def updateAccountValue(self, key, val, currency, accountName):
"""updateAccountValue(EWrapper self, IBString const & key, IBString const & val, IBString const & currency, IBString const & accountName)"""
return _swigibpy.EWrapper_updateAccountValue(self, key, val, currency, accountName) | [
"def",
"updateAccountValue",
"(",
"self",
",",
"key",
",",
"val",
",",
"currency",
",",
"accountName",
")",
":",
"return",
"_swigibpy",
".",
"EWrapper_updateAccountValue",
"(",
"self",
",",
"key",
",",
"val",
",",
"currency",
",",
"accountName",
")"
] | 100.333333 | 0.013201 |
def get_model(model, ctx, opt):
"""Model initialization."""
kwargs = {'ctx': ctx, 'pretrained': opt.use_pretrained, 'classes': classes}
if model.startswith('resnet'):
kwargs['thumbnail'] = opt.use_thumbnail
elif model.startswith('vgg'):
kwargs['batch_norm'] = opt.batch_norm
net = mo... | [
"def",
"get_model",
"(",
"model",
",",
"ctx",
",",
"opt",
")",
":",
"kwargs",
"=",
"{",
"'ctx'",
":",
"ctx",
",",
"'pretrained'",
":",
"opt",
".",
"use_pretrained",
",",
"'classes'",
":",
"classes",
"}",
"if",
"model",
".",
"startswith",
"(",
"'resnet'... | 34.055556 | 0.001587 |
def spawn(self):
"""Spawn the fake executable using subprocess.Popen."""
self._process = subprocess.Popen(
[self.path], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
self.addCleanup(self._process_kill) | [
"def",
"spawn",
"(",
"self",
")",
":",
"self",
".",
"_process",
"=",
"subprocess",
".",
"Popen",
"(",
"[",
"self",
".",
"path",
"]",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"STDOUT",
")",
"self",
".",
"... | 47.4 | 0.008299 |
async def release(data):
"""
Release a session
:param data: Information obtained from a POST request.
The content type is application/json.
The correct packet form should be as follows:
{
'token': UUID token from current session start
'command': 'release'
}
"""
global se... | [
"async",
"def",
"release",
"(",
"data",
")",
":",
"global",
"session",
"if",
"not",
"feature_flags",
".",
"use_protocol_api_v2",
"(",
")",
":",
"session",
".",
"adapter",
".",
"remove_instrument",
"(",
"'left'",
")",
"session",
".",
"adapter",
".",
"remove_i... | 30.1 | 0.00161 |
def list_nodes_min(call=None):
'''
Return a list of the VMs that are on the provider. Only a list of VM names,
and their state, is returned. This is the minimum amount of information
needed to check for existing VMs.
'''
if call == 'action':
raise SaltCloudSystemExit(
'The li... | [
"def",
"list_nodes_min",
"(",
"call",
"=",
"None",
")",
":",
"if",
"call",
"==",
"'action'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The list_nodes_min function must be called with -f or --function.'",
")",
"ret",
"=",
"{",
"}",
"location",
"=",
"get_location",
... | 28.09375 | 0.001075 |
def _find_topics_with_wrong_rp(topics, zk, default_min_isr):
"""Returns topics with wrong replication factor."""
topics_with_wrong_rf = []
for topic_name, partitions in topics.items():
min_isr = get_min_isr(zk, topic_name) or default_min_isr
replication_factor = len(partitions[0].replicas)
... | [
"def",
"_find_topics_with_wrong_rp",
"(",
"topics",
",",
"zk",
",",
"default_min_isr",
")",
":",
"topics_with_wrong_rf",
"=",
"[",
"]",
"for",
"topic_name",
",",
"partitions",
"in",
"topics",
".",
"items",
"(",
")",
":",
"min_isr",
"=",
"get_min_isr",
"(",
"... | 31.777778 | 0.001698 |
def simulate_run(res, rstate=None, return_idx=False, approx=False):
"""
Probes **combined uncertainties** (statistical and sampling) on a nested
sampling run by wrapping :meth:`jitter_run` and :meth:`resample_run`.
Parameters
----------
res : :class:`~dynesty.results.Results` instance
T... | [
"def",
"simulate_run",
"(",
"res",
",",
"rstate",
"=",
"None",
",",
"return_idx",
"=",
"False",
",",
"approx",
"=",
"False",
")",
":",
"if",
"rstate",
"is",
"None",
":",
"rstate",
"=",
"np",
".",
"random",
"# Resample run.",
"new_res",
",",
"samp_idx",
... | 31.227273 | 0.000706 |
def load(cls, data):
"""Construct a Constant class from it's dict data.
.. versionadded:: 0.0.2
"""
if len(data) == 1:
for key, value in data.items():
if "__classname__" not in value: # pragma: no cover
raise ValueError
na... | [
"def",
"load",
"(",
"cls",
",",
"data",
")",
":",
"if",
"len",
"(",
"data",
")",
"==",
"1",
":",
"for",
"key",
",",
"value",
"in",
"data",
".",
"items",
"(",
")",
":",
"if",
"\"__classname__\"",
"not",
"in",
"value",
":",
"# pragma: no cover",
"rai... | 35.043478 | 0.002415 |
def format_by_pattern(numobj, number_format, user_defined_formats):
"""Formats a phone number using client-defined formatting rules."
Note that if the phone number has a country calling code of zero or an
otherwise invalid country calling code, we cannot work out things like
whether there should be a n... | [
"def",
"format_by_pattern",
"(",
"numobj",
",",
"number_format",
",",
"user_defined_formats",
")",
":",
"country_code",
"=",
"numobj",
".",
"country_code",
"nsn",
"=",
"national_significant_number",
"(",
"numobj",
")",
"if",
"not",
"_has_valid_country_calling_code",
"... | 54.540984 | 0.002362 |
def findpath(self, points, curvature=1.0):
"""Constructs a path between the given list of points.
Interpolates the list of points and determines
a smooth bezier path betweem them.
The curvature parameter offers some control on
how separate segments are stitched together:
... | [
"def",
"findpath",
"(",
"self",
",",
"points",
",",
"curvature",
"=",
"1.0",
")",
":",
"# The list of points consists of Point objects,",
"# but it shouldn't crash on something straightforward",
"# as someone supplying a list of (x,y)-tuples.",
"for",
"i",
",",
"pt",
"in",
"e... | 34.493151 | 0.000772 |
def runStickyEregressionsInStata(infile_name,interval_size,meas_err,sticky,all_specs,stata_exe):
'''
Runs regressions for the main tables of the StickyC paper in Stata and produces a
LaTeX table with results for one "panel". Running in Stata allows production of
the KP-statistic, for which there is curr... | [
"def",
"runStickyEregressionsInStata",
"(",
"infile_name",
",",
"interval_size",
",",
"meas_err",
",",
"sticky",
",",
"all_specs",
",",
"stata_exe",
")",
":",
"dofile",
"=",
"\"StickyETimeSeries.do\"",
"infile_name_full",
"=",
"os",
".",
"path",
".",
"abspath",
"(... | 42.896552 | 0.011002 |
def hot(self, limit=None):
"""GETs hot links from this subreddit. Calls :meth:`narwal.Reddit.hot`.
:param limit: max number of links to return
"""
return self._reddit.hot(self.display_name, limit=limit) | [
"def",
"hot",
"(",
"self",
",",
"limit",
"=",
"None",
")",
":",
"return",
"self",
".",
"_reddit",
".",
"hot",
"(",
"self",
".",
"display_name",
",",
"limit",
"=",
"limit",
")"
] | 39.833333 | 0.016393 |
def get_buildroot(self, build_id):
"""
Build the buildroot entry of the metadata.
:return: dict, partial metadata
"""
docker_info = self.tasker.get_info()
host_arch, docker_version = get_docker_architecture(self.tasker)
buildroot = {
'id': 1,
... | [
"def",
"get_buildroot",
"(",
"self",
",",
"build_id",
")",
":",
"docker_info",
"=",
"self",
".",
"tasker",
".",
"get_info",
"(",
")",
"host_arch",
",",
"docker_version",
"=",
"get_docker_architecture",
"(",
"self",
".",
"tasker",
")",
"buildroot",
"=",
"{",
... | 27.888889 | 0.00154 |
def verify_fft_options(opt, parser):
"""Parses the FFT options and verifies that they are
reasonable.
Parameters
----------
opt : object
Result of parsing the CLI with OptionParser, or any object with the
required attributes.
parser : object
OptionParser instance.
... | [
"def",
"verify_fft_options",
"(",
"opt",
",",
"parser",
")",
":",
"if",
"len",
"(",
"opt",
".",
"fft_backends",
")",
">",
"0",
":",
"_all_backends",
"=",
"get_backend_names",
"(",
")",
"for",
"backend",
"in",
"opt",
".",
"fft_backends",
":",
"if",
"backe... | 29.125 | 0.001385 |
def exists(instance_id=None, name=None, tags=None, region=None, key=None,
keyid=None, profile=None, in_states=None, filters=None):
'''
Given an instance id, check to see if the given instance id exists.
Returns True if the given instance with the given id, name, or tags
exists; otherwise, Fa... | [
"def",
"exists",
"(",
"instance_id",
"=",
"None",
",",
"name",
"=",
"None",
",",
"tags",
"=",
"None",
",",
"region",
"=",
"None",
",",
"key",
"=",
"None",
",",
"keyid",
"=",
"None",
",",
"profile",
"=",
"None",
",",
"in_states",
"=",
"None",
",",
... | 34.869565 | 0.002427 |
def assign(self, check=None, content_object=None, generic=False):
"""
Assign a permission to a user.
To assign permission for all checks: let check=None.
To assign permission for all objects: let content_object=None.
If generic is True then "check" will be suffixed with _modeln... | [
"def",
"assign",
"(",
"self",
",",
"check",
"=",
"None",
",",
"content_object",
"=",
"None",
",",
"generic",
"=",
"False",
")",
":",
"result",
"=",
"[",
"]",
"if",
"not",
"content_object",
":",
"content_objects",
"=",
"(",
"self",
".",
"model",
",",
... | 38.588235 | 0.000595 |
def set_edist_powerlaw(self, emin_mev, emax_mev, delta, ne_cc):
"""Set the energy distribution function to a power law.
**Call signature**
*emin_mev*
The minimum energy of the distribution, in MeV
*emax_mev*
The maximum energy of the distribution, in MeV
*de... | [
"def",
"set_edist_powerlaw",
"(",
"self",
",",
"emin_mev",
",",
"emax_mev",
",",
"delta",
",",
"ne_cc",
")",
":",
"if",
"not",
"(",
"emin_mev",
">=",
"0",
")",
":",
"raise",
"ValueError",
"(",
"'must have emin_mev >= 0; got %r'",
"%",
"(",
"emin_mev",
",",
... | 38.580645 | 0.002447 |
def initialize_res(residue):
'''Creates a new structure containing a single amino acid. The type and
geometry of the amino acid are determined by the argument, which has to be
either a geometry object or a single-letter amino acid code.
The amino acid will be placed into chain A of model 0.'''
... | [
"def",
"initialize_res",
"(",
"residue",
")",
":",
"if",
"isinstance",
"(",
"residue",
",",
"Geo",
")",
":",
"geo",
"=",
"residue",
"else",
":",
"geo",
"=",
"geometry",
"(",
"residue",
")",
"segID",
"=",
"1",
"AA",
"=",
"geo",
".",
"residue_name",
"C... | 30.976471 | 0.033125 |
def traverse_trees_recursive(odb, tree_shas, path_prefix):
"""
:return: list with entries according to the given binary tree-shas.
The result is encoded in a list
of n tuple|None per blob/commit, (n == len(tree_shas)), where
* [0] == 20 byte sha
* [1] == mode as int
* [2]... | [
"def",
"traverse_trees_recursive",
"(",
"odb",
",",
"tree_shas",
",",
"path_prefix",
")",
":",
"trees_data",
"=",
"[",
"]",
"nt",
"=",
"len",
"(",
"tree_shas",
")",
"for",
"tree_sha",
"in",
"tree_shas",
":",
"if",
"tree_sha",
"is",
"None",
":",
"data",
"... | 40.818182 | 0.002175 |
def _gluster_output_cleanup(result):
'''
Gluster versions prior to 6 have a bug that requires tricking
isatty. This adds "gluster> " to the output. Strip it off and
produce clean xml for ElementTree.
'''
ret = ''
for line in result.splitlines():
if line.startswith('gluster>'):
... | [
"def",
"_gluster_output_cleanup",
"(",
"result",
")",
":",
"ret",
"=",
"''",
"for",
"line",
"in",
"result",
".",
"splitlines",
"(",
")",
":",
"if",
"line",
".",
"startswith",
"(",
"'gluster>'",
")",
":",
"ret",
"+=",
"line",
"[",
"9",
":",
"]",
".",
... | 29.5 | 0.002053 |
def runExperiment(args):
"""
Runs the experiment. The code is organized around what we need for specific
figures in the paper.
args is a dict representing the various parameters. We do it this way to
support multiprocessing. The function returns the args dict updated with a
number of additional keys conta... | [
"def",
"runExperiment",
"(",
"args",
")",
":",
"numObjects",
"=",
"args",
".",
"get",
"(",
"\"numObjects\"",
",",
"10",
")",
"numSequences",
"=",
"args",
".",
"get",
"(",
"\"numSequences\"",
",",
"10",
")",
"numFeatures",
"=",
"args",
".",
"get",
"(",
... | 37.019048 | 0.014907 |
def get_items(self):
"""Get a list of objects describing the content of `self`.
:return: the list of objects.
:returntype: `list` of `MucItemBase` (`MucItem` and/or `MucStatus`)
"""
if not self.xmlnode.children:
return []
ret=[]
n=self.xmlnode.childre... | [
"def",
"get_items",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"xmlnode",
".",
"children",
":",
"return",
"[",
"]",
"ret",
"=",
"[",
"]",
"n",
"=",
"self",
".",
"xmlnode",
".",
"children",
"while",
"n",
":",
"ns",
"=",
"n",
".",
"ns",
"("... | 30.761905 | 0.013514 |
def SInt(value, width):
"""
Convert a bitstring `value` of `width` bits to a signed integer
representation.
:param value: The value to convert.
:type value: int or long or BitVec
:param int width: The width of the bitstring to consider
:return: The converted value
:rtype int or long or ... | [
"def",
"SInt",
"(",
"value",
",",
"width",
")",
":",
"return",
"Operators",
".",
"ITEBV",
"(",
"width",
",",
"Bit",
"(",
"value",
",",
"width",
"-",
"1",
")",
"==",
"1",
",",
"GetNBits",
"(",
"value",
",",
"width",
")",
"-",
"2",
"**",
"width",
... | 35.428571 | 0.001965 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.