text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def has_staff_rights_on_course(self, course, username=None, include_superadmins=True):
"""
Check if a user can be considered as having staff rights for a course
:type course: webapp.custom.courses.WebAppCourse
:param username: the username. If None, the username of the currently logged i... | [
"def",
"has_staff_rights_on_course",
"(",
"self",
",",
"course",
",",
"username",
"=",
"None",
",",
"include_superadmins",
"=",
"True",
")",
":",
"if",
"username",
"is",
"None",
":",
"username",
"=",
"self",
".",
"session_username",
"(",
")",
"return",
"(",
... | 57.166667 | 0.008608 |
def render(self, name, value, attrs=None, renderer=None):
"""
Render the default widget and initialize select2.
"""
output = [super(TagAutoComplete, self).render(name, value, attrs)]
output.append('<script type="text/javascript">')
output.append('(function($) {')
... | [
"def",
"render",
"(",
"self",
",",
"name",
",",
"value",
",",
"attrs",
"=",
"None",
",",
"renderer",
"=",
"None",
")",
":",
"output",
"=",
"[",
"super",
"(",
"TagAutoComplete",
",",
"self",
")",
".",
"render",
"(",
"name",
",",
"value",
",",
"attrs... | 46.555556 | 0.002339 |
def get_game_for_worker(map_name, directory_id):
"""Get game for the given worker (directory) id."""
if map_name == "v100unfriendly":
games = ["chopper_command", "boxing", "asterix", "seaquest"]
worker_per_game = 5
elif map_name == "human_nice":
games = gym_env.ATARI_GAMES_WITH_HUMAN_SCORE_NICE
wo... | [
"def",
"get_game_for_worker",
"(",
"map_name",
",",
"directory_id",
")",
":",
"if",
"map_name",
"==",
"\"v100unfriendly\"",
":",
"games",
"=",
"[",
"\"chopper_command\"",
",",
"\"boxing\"",
",",
"\"asterix\"",
",",
"\"seaquest\"",
"]",
"worker_per_game",
"=",
"5",... | 39.785714 | 0.015789 |
def _filter_by_normal(tumor_counts, normal_counts, data):
"""Filter count files based on normal frequency and median depth, avoiding high depth regions.
For frequency, restricts normal positions to those between 0.4 and 0.65
For depth, matches approach used in AMBER to try and avoid problematic genomic re... | [
"def",
"_filter_by_normal",
"(",
"tumor_counts",
",",
"normal_counts",
",",
"data",
")",
":",
"from",
"bcbio",
".",
"heterogeneity",
"import",
"bubbletree",
"fparams",
"=",
"bubbletree",
".",
"NORMAL_FILTER_PARAMS",
"tumor_out",
"=",
"\"%s-normfilter%s\"",
"%",
"uti... | 59.852941 | 0.002418 |
def reload(self, config=None, debug=False):
""" load/reload configuration
@dict: configuration of ldapcherry
"""
try:
# log configuration handling
# get log level
# (if not in configuration file, log level is set to debug)
level = get_logle... | [
"def",
"reload",
"(",
"self",
",",
"config",
"=",
"None",
",",
"debug",
"=",
"False",
")",
":",
"try",
":",
"# log configuration handling",
"# get log level",
"# (if not in configuration file, log level is set to debug)",
"level",
"=",
"get_loglevel",
"(",
"self",
"."... | 29.953846 | 0.000995 |
def _retrieve_info(self, http):
"""Retrieves service account info for invalid credentials.
Args:
http: an object to be used to make HTTP requests.
"""
if self.invalid:
info = _metadata.get_service_account_info(
http,
service_accoun... | [
"def",
"_retrieve_info",
"(",
"self",
",",
"http",
")",
":",
"if",
"self",
".",
"invalid",
":",
"info",
"=",
"_metadata",
".",
"get_service_account_info",
"(",
"http",
",",
"service_account",
"=",
"self",
".",
"service_account_email",
"or",
"'default'",
")",
... | 36.846154 | 0.004073 |
def update(self, quote_id, product_data, store_view=None):
"""
Allows you to update one or several products in the shopping cart
(quote).
:param quote_id: Shopping cart ID (quote ID)
:param product_data, list of dicts of product details, see def add()
:param store_view: ... | [
"def",
"update",
"(",
"self",
",",
"quote_id",
",",
"product_data",
",",
"store_view",
"=",
"None",
")",
":",
"return",
"bool",
"(",
"self",
".",
"call",
"(",
"'cart_product.update'",
",",
"[",
"quote_id",
",",
"product_data",
",",
"store_view",
"]",
")",
... | 37.785714 | 0.005535 |
def _set_period(self, period):
"""
Set the period for the timestamp. If period is 0 or None, no period
will be used.
"""
self._period = period
if period:
self._period_seconds = tempora.get_period_seconds(self._period)
self._date_format = tempora.get_date_format_string(
self._period_secon... | [
"def",
"_set_period",
"(",
"self",
",",
"period",
")",
":",
"self",
".",
"_period",
"=",
"period",
"if",
"period",
":",
"self",
".",
"_period_seconds",
"=",
"tempora",
".",
"get_period_seconds",
"(",
"self",
".",
"_period",
")",
"self",
".",
"_date_format"... | 28.923077 | 0.036082 |
def calculate_similarity(container1=None,
container2=None,
comparison=None,
metric=None):
'''calculate_similarity will calculate similarity of two containers
by files content, default will calculate
2.0*len(intersect) / to... | [
"def",
"calculate_similarity",
"(",
"container1",
"=",
"None",
",",
"container2",
"=",
"None",
",",
"comparison",
"=",
"None",
",",
"metric",
"=",
"None",
")",
":",
"if",
"metric",
"is",
"None",
":",
"metric",
"=",
"information_coefficient",
"if",
"compariso... | 35.290323 | 0.004448 |
def expand_state_definition(source, loc, tokens):
"""
Parse action to convert statemachine to corresponding Python classes and methods
"""
indent = " " * (pp.col(loc, source) - 1)
statedef = []
# build list of states
states = set()
fromTo = {}
for tn in tokens.transitions:
s... | [
"def",
"expand_state_definition",
"(",
"source",
",",
"loc",
",",
"tokens",
")",
":",
"indent",
"=",
"\" \"",
"*",
"(",
"pp",
".",
"col",
"(",
"loc",
",",
"source",
")",
"-",
"1",
")",
"statedef",
"=",
"[",
"]",
"# build list of states",
"states",
"=",... | 31.275862 | 0.002672 |
def _parse_and_return_quoted_string(self):
"""
Parses a string that has quotation marks so it may contain
special characters and escape sequences.
:return: (unescaped_string, quoted=True, end_of_string_pos)
"""
result = []
pos = self.pos + 1
segment_begin ... | [
"def",
"_parse_and_return_quoted_string",
"(",
"self",
")",
":",
"result",
"=",
"[",
"]",
"pos",
"=",
"self",
".",
"pos",
"+",
"1",
"segment_begin",
"=",
"pos",
"my_chr",
"=",
"my_unichr",
"if",
"isinstance",
"(",
"self",
".",
"text",
",",
"my_unicode",
... | 40.324324 | 0.001963 |
def _system_call(cmd, stdoutfilename=None):
"""Execute the command `cmd`
Parameters
----------
cmd : str
The string containing the command to be run.
stdoutfilename : str
Name of the file to save stdout to or None
(default) to not save to file
stderrfilename : str
... | [
"def",
"_system_call",
"(",
"cmd",
",",
"stdoutfilename",
"=",
"None",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"logger",
".",
"debug",
"(",
"'system call: %s'",
"%",
"cmd",
")",
"if",
"stdoutfilename",
":",
"with",
"open... | 35.295455 | 0.000627 |
def compute_partition_size(result, processes):
"""
Attempts to compute the partition size to evenly distribute work across processes. Defaults to
1 if the length of result cannot be determined.
:param result: Result to compute on
:param processes: Number of processes to use
:return: Best partit... | [
"def",
"compute_partition_size",
"(",
"result",
",",
"processes",
")",
":",
"try",
":",
"return",
"max",
"(",
"math",
".",
"ceil",
"(",
"len",
"(",
"result",
")",
"/",
"processes",
")",
",",
"1",
")",
"except",
"TypeError",
":",
"return",
"1"
] | 33.076923 | 0.004525 |
def radiance_to_bt(arr, wc_, a__, b__):
"""Convert to BT.
"""
return a__ + b__ * (C2 * wc_ / (da.log(1 + (C1 * (wc_ ** 3) / arr)))) | [
"def",
"radiance_to_bt",
"(",
"arr",
",",
"wc_",
",",
"a__",
",",
"b__",
")",
":",
"return",
"a__",
"+",
"b__",
"*",
"(",
"C2",
"*",
"wc_",
"/",
"(",
"da",
".",
"log",
"(",
"1",
"+",
"(",
"C1",
"*",
"(",
"wc_",
"**",
"3",
")",
"/",
"arr",
... | 35 | 0.006993 |
def get_ordered_entries(self, queryset=False):
"""
Custom ordering. First we get the average views and rating for
the categories's entries. Second we created a rank by multiplying
both. Last, we sort categories by this rank from top to bottom.
Example:
- Cat_1
... | [
"def",
"get_ordered_entries",
"(",
"self",
",",
"queryset",
"=",
"False",
")",
":",
"if",
"queryset",
":",
"self",
".",
"queryset",
"=",
"queryset",
"else",
":",
"self",
".",
"queryset",
"=",
"EntryCategory",
".",
"objects",
".",
"all",
"(",
")",
"if",
... | 40.642857 | 0.001144 |
def finder(target, matchlist, foldermode=0, regex=False, recursive=True):
"""
function for finding files/folders in folders and their subdirectories
Parameters
----------
target: str or list of str
a directory, zip- or tar-archive or a list of them to be searched
matchlist: list
... | [
"def",
"finder",
"(",
"target",
",",
"matchlist",
",",
"foldermode",
"=",
"0",
",",
"regex",
"=",
"False",
",",
"recursive",
"=",
"True",
")",
":",
"if",
"foldermode",
"not",
"in",
"[",
"0",
",",
"1",
",",
"2",
"]",
":",
"raise",
"ValueError",
"(",... | 38.581633 | 0.006189 |
def lookup_color(color):
"""
Returns the hex color for any valid css color name
>>> lookup_color('aliceblue')
'F0F8FF'
"""
if color is None: return
color = color.lower()
if color in COLOR_MAP:
return COLOR_MAP[color]
return color | [
"def",
"lookup_color",
"(",
"color",
")",
":",
"if",
"color",
"is",
"None",
":",
"return",
"color",
"=",
"color",
".",
"lower",
"(",
")",
"if",
"color",
"in",
"COLOR_MAP",
":",
"return",
"COLOR_MAP",
"[",
"color",
"]",
"return",
"color"
] | 22.25 | 0.010791 |
def deterministic_generate_k(generator_order, secret_exponent, val, hash_f=hashlib.sha256):
"""
:param generator_order: result from :method:`pycoin.ecdsa.Generator.Generator.order`,
necessary to ensure the k value is within bound
:param secret_exponent: an integer secret_exponent to generate the k v... | [
"def",
"deterministic_generate_k",
"(",
"generator_order",
",",
"secret_exponent",
",",
"val",
",",
"hash_f",
"=",
"hashlib",
".",
"sha256",
")",
":",
"n",
"=",
"generator_order",
"bln",
"=",
"bit_length",
"(",
"n",
")",
"order_size",
"=",
"(",
"bln",
"+",
... | 35.380952 | 0.003929 |
def differential_pressure_meter_beta(D, D2, meter_type):
r'''Calculates the beta ratio of a differential pressure meter.
Parameters
----------
D : float
Upstream internal pipe diameter, [m]
D2 : float
Diameter of orifice, or venturi meter orifice, or flow tube orifice,
... | [
"def",
"differential_pressure_meter_beta",
"(",
"D",
",",
"D2",
",",
"meter_type",
")",
":",
"if",
"meter_type",
"in",
"beta_simple_meters",
":",
"beta",
"=",
"D2",
"/",
"D",
"elif",
"meter_type",
"==",
"CONE_METER",
":",
"beta",
"=",
"diameter_ratio_cone_meter"... | 31.105263 | 0.006563 |
def destroy(self):
"""
Gracefully close the window
"""
sdl2.SDL_GL_DeleteContext(self.context)
sdl2.SDL_DestroyWindow(self.window)
sdl2.SDL_Quit() | [
"def",
"destroy",
"(",
"self",
")",
":",
"sdl2",
".",
"SDL_GL_DeleteContext",
"(",
"self",
".",
"context",
")",
"sdl2",
".",
"SDL_DestroyWindow",
"(",
"self",
".",
"window",
")",
"sdl2",
".",
"SDL_Quit",
"(",
")"
] | 27.714286 | 0.01 |
def merge_resolve(branch, fast_forward=False, commit=True, options=None):
"""Merge that branch into current branch
If git raises an error, and the error is for conflicts
then read the error message looking for any resolved conflicts
Remove the resolved conflicts from the error message
If al... | [
"def",
"merge_resolve",
"(",
"branch",
",",
"fast_forward",
"=",
"False",
",",
"commit",
"=",
"True",
",",
"options",
"=",
"None",
")",
":",
"def",
"get_resolution",
"(",
"resolved",
"=",
"None",
")",
":",
"return",
"resolved",
"with",
"git_continuer",
"("... | 42.588235 | 0.001351 |
def __get_owner_unix(self):
"""
Return the name of the owner of this file or directory. Follow
symbolic links.
.. seealso:: :attr:`owner`
"""
st = self.stat()
return pwd.getpwuid(st.st_uid).pw_name | [
"def",
"__get_owner_unix",
"(",
"self",
")",
":",
"st",
"=",
"self",
".",
"stat",
"(",
")",
"return",
"pwd",
".",
"getpwuid",
"(",
"st",
".",
"st_uid",
")",
".",
"pw_name"
] | 27.333333 | 0.007874 |
def set_duration(self, rule):
"""Set the duration according to rule.
rule: str
The rule operating on the variable ``dur``.
rule is an expression like::
>>> rule = 'dur == 150 or dur > 822'
setting a duration rule assuming a pack sp::
>>> sp.set_du... | [
"def",
"set_duration",
"(",
"self",
",",
"rule",
")",
":",
"self",
".",
"conconf",
".",
"set_condition",
"(",
"'duration'",
",",
"rule",
")",
"if",
"not",
"self",
".",
"no_auto",
":",
"self",
".",
"make_mask",
"(",
")"
] | 27.090909 | 0.00216 |
def generate_html_files(*args):
'''
Generate the templates for adding, editing, viewing.
:return: None
'''
_ = args
for tag_key, tag_list in SWITCH_DICS.items():
if tag_key.startswith('dic_') and (not tag_key.endswith('00')):
__write_add_tmpl(tag_key, tag_list)
__... | [
"def",
"generate_html_files",
"(",
"*",
"args",
")",
":",
"_",
"=",
"args",
"for",
"tag_key",
",",
"tag_list",
"in",
"SWITCH_DICS",
".",
"items",
"(",
")",
":",
"if",
"tag_key",
".",
"startswith",
"(",
"'dic_'",
")",
"and",
"(",
"not",
"tag_key",
".",
... | 32.928571 | 0.00211 |
def _claim_in_progress_and_claim_channels(self, grpc_channel, channels):
""" Claim all 'pending' payments in progress and after we claim given channels """
# first we get the list of all 'payments in progress' in case we 'lost' some payments.
payments = self._call_GetListInProgress(grpc_channel)... | [
"def",
"_claim_in_progress_and_claim_channels",
"(",
"self",
",",
"grpc_channel",
",",
"channels",
")",
":",
"# first we get the list of all 'payments in progress' in case we 'lost' some payments.",
"payments",
"=",
"self",
".",
"_call_GetListInProgress",
"(",
"grpc_channel",
")"... | 71.444444 | 0.009217 |
def bulge_to_arcs(lines,
bulge,
bulge_idx,
is_closed=False,
metadata=None):
"""
Polylines can have "vertex bulge," which means the polyline
has an arc tangent to segments, rather than meeting at a
vertex.
From Autodesk referenc... | [
"def",
"bulge_to_arcs",
"(",
"lines",
",",
"bulge",
",",
"bulge_idx",
",",
"is_closed",
"=",
"False",
",",
"metadata",
"=",
"None",
")",
":",
"# make sure lines are 2D array",
"lines",
"=",
"np",
".",
"asanyarray",
"(",
"lines",
",",
"dtype",
"=",
"np",
".... | 31.201439 | 0.000223 |
def get_version(self, filename=None, version=-1, session=None, **kwargs):
"""Get a file from GridFS by ``"filename"`` or metadata fields.
Returns a version of the file in GridFS whose filename matches
`filename` and whose metadata fields match the supplied keyword
arguments, as an insta... | [
"def",
"get_version",
"(",
"self",
",",
"filename",
"=",
"None",
",",
"version",
"=",
"-",
"1",
",",
"session",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"query",
"=",
"kwargs",
"if",
"filename",
"is",
"not",
"None",
":",
"query",
"[",
"\"fil... | 43.960784 | 0.000873 |
def replace_all_caps(x:Collection[str]) -> Collection[str]:
"Replace tokens in ALL CAPS in `x` by their lower version and add `TK_UP` before."
res = []
for t in x:
if t.isupper() and len(t) > 1: res.append(TK_UP); res.append(t.lower())
else: res.append(t)
return res | [
"def",
"replace_all_caps",
"(",
"x",
":",
"Collection",
"[",
"str",
"]",
")",
"->",
"Collection",
"[",
"str",
"]",
":",
"res",
"=",
"[",
"]",
"for",
"t",
"in",
"x",
":",
"if",
"t",
".",
"isupper",
"(",
")",
"and",
"len",
"(",
"t",
")",
">",
"... | 41.714286 | 0.020134 |
def diagnostics(self):
'Log some system diagnostics before/after setup for ease of debugging'
# The builder's repr is not used in a command to avoid pointlessly
# invalidating Docker's build cache.
return self.step('Diagnostics', [
self.comment('Builder {0}'.format(repr(self)... | [
"def",
"diagnostics",
"(",
"self",
")",
":",
"# The builder's repr is not used in a command to avoid pointlessly",
"# invalidating Docker's build cache.",
"return",
"self",
".",
"step",
"(",
"'Diagnostics'",
",",
"[",
"self",
".",
"comment",
"(",
"'Builder {0}'",
".",
"fo... | 55.090909 | 0.00487 |
def data_filler_company(self, number_of_rows, cursor, conn):
'''creates and fills the table with company data
'''
companies_data = []
try:
for i in range(0, number_of_rows):
companies_data.append((rnd_id_generator(self), self.faker.co... | [
"def",
"data_filler_company",
"(",
"self",
",",
"number_of_rows",
",",
"cursor",
",",
"conn",
")",
":",
"companies_data",
"=",
"[",
"]",
"try",
":",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"number_of_rows",
")",
":",
"companies_data",
".",
"append",
"(... | 48.15 | 0.010183 |
def __process_by_ccore(self):
"""!
@brief Performs cluster analysis using C/C++ implementation.
"""
result = wrapper.fcm_algorithm(self.__data, self.__centers, self.__m, self.__tolerance, self.__itermax)
self.__clusters = result[wrapper.fcm_package_indexer.INDEX_CLUSTERS... | [
"def",
"__process_by_ccore",
"(",
"self",
")",
":",
"result",
"=",
"wrapper",
".",
"fcm_algorithm",
"(",
"self",
".",
"__data",
",",
"self",
".",
"__centers",
",",
"self",
".",
"__m",
",",
"self",
".",
"__tolerance",
",",
"self",
".",
"__itermax",
")",
... | 47 | 0.008351 |
def interpolate(self, year):
"""Interpolate missing values in timeseries (linear interpolation)
Parameters
----------
year: int
year to be interpolated
"""
df = self.pivot_table(index=IAMC_IDX, columns=['year'],
values='value', ... | [
"def",
"interpolate",
"(",
"self",
",",
"year",
")",
":",
"df",
"=",
"self",
".",
"pivot_table",
"(",
"index",
"=",
"IAMC_IDX",
",",
"columns",
"=",
"[",
"'year'",
"]",
",",
"values",
"=",
"'value'",
",",
"aggfunc",
"=",
"np",
".",
"sum",
")",
"# d... | 40.789474 | 0.002522 |
def save_supy(
df_output: pandas.DataFrame,
df_state_final: pandas.DataFrame,
freq_s: int = 3600,
site: str = '',
path_dir_save: str = Path('.'),
path_runcontrol: str = None,)->list:
'''Save SuPy run results to files
Parameters
----------
df_output : pand... | [
"def",
"save_supy",
"(",
"df_output",
":",
"pandas",
".",
"DataFrame",
",",
"df_state_final",
":",
"pandas",
".",
"DataFrame",
",",
"freq_s",
":",
"int",
"=",
"3600",
",",
"site",
":",
"str",
"=",
"''",
",",
"path_dir_save",
":",
"str",
"=",
"Path",
"(... | 37.316667 | 0.004787 |
def get_target_forums_for_moved_topics(self, user):
""" Returns a list of forums in which the considered user can add topics that have been
moved from another forum.
"""
return [f for f in self._get_forums_for_user(user, ['can_move_topics', ]) if f.is_forum] | [
"def",
"get_target_forums_for_moved_topics",
"(",
"self",
",",
"user",
")",
":",
"return",
"[",
"f",
"for",
"f",
"in",
"self",
".",
"_get_forums_for_user",
"(",
"user",
",",
"[",
"'can_move_topics'",
",",
"]",
")",
"if",
"f",
".",
"is_forum",
"]"
] | 58 | 0.013605 |
def is_mdgel(self):
"""File has MD Gel format."""
# TODO: this likely reads the second page from file
try:
ismdgel = self.pages[0].is_mdgel or self.pages[1].is_mdgel
if ismdgel:
self.is_uniform = False
return ismdgel
except IndexError:
... | [
"def",
"is_mdgel",
"(",
"self",
")",
":",
"# TODO: this likely reads the second page from file",
"try",
":",
"ismdgel",
"=",
"self",
".",
"pages",
"[",
"0",
"]",
".",
"is_mdgel",
"or",
"self",
".",
"pages",
"[",
"1",
"]",
".",
"is_mdgel",
"if",
"ismdgel",
... | 33.5 | 0.005814 |
def get_extra_files():
"""returns a list of files that should be watched by the Flask server
when in debug mode to trigger a reload of the server
"""
FILES_TO_SKIP = ["src/gdbgui.js"]
THIS_DIR = os.path.dirname(os.path.abspath(__file__))
extra_dirs = [THIS_DIR]
extra_files = []
for extra... | [
"def",
"get_extra_files",
"(",
")",
":",
"FILES_TO_SKIP",
"=",
"[",
"\"src/gdbgui.js\"",
"]",
"THIS_DIR",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"__file__",
")",
")",
"extra_dirs",
"=",
"[",
"THIS_DIR",
"]",
... | 43 | 0.001339 |
def validate_comma_separated_emails(value):
"""
Validate every email address in a comma separated list of emails.
"""
if not isinstance(value, (tuple, list)):
raise ValidationError('Email list must be a list/tuple.')
for email in value:
try:
validate_email_with_name(emai... | [
"def",
"validate_comma_separated_emails",
"(",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"raise",
"ValidationError",
"(",
"'Email list must be a list/tuple.'",
")",
"for",
"email",
"in",
"value",
... | 35.166667 | 0.002309 |
def stream_fastq(file_handler):
''' Generator which gives all four lines if a fastq read as one string
'''
next_element = ''
for i, line in enumerate(file_handler):
next_element += line
if i % 4 == 3:
yield next_element
next_element = '' | [
"def",
"stream_fastq",
"(",
"file_handler",
")",
":",
"next_element",
"=",
"''",
"for",
"i",
",",
"line",
"in",
"enumerate",
"(",
"file_handler",
")",
":",
"next_element",
"+=",
"line",
"if",
"i",
"%",
"4",
"==",
"3",
":",
"yield",
"next_element",
"next_... | 31.666667 | 0.003413 |
def subseparable_conv(inputs, filters, kernel_size, **kwargs):
"""Sub-separable convolution. If separability == 0 it's a separable_conv."""
def conv_fn(inputs, filters, kernel_size, **kwargs):
"""Sub-separable convolution, splits into separability-many blocks."""
separability = None
if "separability" i... | [
"def",
"subseparable_conv",
"(",
"inputs",
",",
"filters",
",",
"kernel_size",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"conv_fn",
"(",
"inputs",
",",
"filters",
",",
"kernel_size",
",",
"*",
"*",
"kwargs",
")",
":",
"\"\"\"Sub-separable convolution, splits i... | 42.027778 | 0.00969 |
def addFilename( self, filename ):
"""
Adds a new filename to the top of the list. If the filename is \
already loaded, it will be moved to the front of the list.
:param filename | <str>
"""
filename = os.path.normpath(nativestring(filename))
... | [
"def",
"addFilename",
"(",
"self",
",",
"filename",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"normpath",
"(",
"nativestring",
"(",
"filename",
")",
")",
"if",
"filename",
"in",
"self",
".",
"_filenames",
":",
"self",
".",
"_filenames",
".",
"... | 33.625 | 0.014467 |
def _CronJobFromRow(self, row):
"""Creates a cronjob object from a database result row."""
(job, create_time, enabled, forced_run_requested, last_run_status,
last_run_time, current_run_id, state, leased_until, leased_by) = row
job = rdf_cronjobs.CronJob.FromSerializedString(job)
job.current_run_id... | [
"def",
"_CronJobFromRow",
"(",
"self",
",",
"row",
")",
":",
"(",
"job",
",",
"create_time",
",",
"enabled",
",",
"forced_run_requested",
",",
"last_run_status",
",",
"last_run_time",
",",
"current_run_id",
",",
"state",
",",
"leased_until",
",",
"leased_by",
... | 48.117647 | 0.002398 |
def update_records(self, qs, batch_size=1000, **kwargs):
"""
Updates multiple records.
This method is optimized for speed. It takes a QuerySet and the same
arguments as QuerySet.update(). Optionnaly, you can specify the size
of the batch send to Algolia with batch_size (default ... | [
"def",
"update_records",
"(",
"self",
",",
"qs",
",",
"batch_size",
"=",
"1000",
",",
"*",
"*",
"kwargs",
")",
":",
"tmp",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"name",
"=",
"self",
".",
"__transl... | 35.28125 | 0.001724 |
def serialize_wrapped_key(key_provider, wrapping_algorithm, wrapping_key_id, encrypted_wrapped_key):
"""Serializes EncryptedData into a Wrapped EncryptedDataKey.
:param key_provider: Info for Wrapping MasterKey
:type key_provider: aws_encryption_sdk.structures.MasterKeyInfo
:param wrapping_algorithm: W... | [
"def",
"serialize_wrapped_key",
"(",
"key_provider",
",",
"wrapping_algorithm",
",",
"wrapping_key_id",
",",
"encrypted_wrapped_key",
")",
":",
"if",
"encrypted_wrapped_key",
".",
"iv",
"is",
"None",
":",
"key_info",
"=",
"wrapping_key_id",
"key_ciphertext",
"=",
"enc... | 49.903226 | 0.005073 |
def find(name, where):
"""
>>> from hl7apy.core import Segment
>>> from hl7apy import find_reference
>>> find_reference('UNKNOWN', (Segment, ), '2.3.1') # doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
ChildNotFound: No child named UNKNOWN
"""
for cls in wh... | [
"def",
"find",
"(",
"name",
",",
"where",
")",
":",
"for",
"cls",
"in",
"where",
":",
"try",
":",
"return",
"{",
"'ref'",
":",
"get",
"(",
"name",
",",
"cls",
".",
"__name__",
")",
",",
"'name'",
":",
"name",
",",
"'cls'",
":",
"cls",
"}",
"exc... | 31.866667 | 0.004065 |
def provider_factory(factory=_sentinel, scope=NoneScope):
'''
Decorator to create a provider using the given factory, and scope.
Can also be used in a non-decorator manner.
:param scope: Scope key, factory, or instance
:type scope: object or callable
:return: decorator
:rtype: decorator
... | [
"def",
"provider_factory",
"(",
"factory",
"=",
"_sentinel",
",",
"scope",
"=",
"NoneScope",
")",
":",
"if",
"factory",
"is",
"_sentinel",
":",
"return",
"functools",
".",
"partial",
"(",
"provider_factory",
",",
"scope",
"=",
"scope",
")",
"provider",
"=",
... | 33.142857 | 0.002096 |
def get_projected_fields(self, req):
"""
Returns the projected fields from request.
"""
try:
args = getattr(req, 'args', {})
return ','.join(json.loads(args.get('projections')))
except (AttributeError, TypeError):
return None | [
"def",
"get_projected_fields",
"(",
"self",
",",
"req",
")",
":",
"try",
":",
"args",
"=",
"getattr",
"(",
"req",
",",
"'args'",
",",
"{",
"}",
")",
"return",
"','",
".",
"join",
"(",
"json",
".",
"loads",
"(",
"args",
".",
"get",
"(",
"'projection... | 29.3 | 0.006623 |
def get_version(pep440=False):
"""Tracks the version number.
pep440: bool
When True, this function returns a version string suitable for
a release as defined by PEP 440. When False, the githash (if
available) will be appended to the version string.
The file VERSION holds the versio... | [
"def",
"get_version",
"(",
"pep440",
"=",
"False",
")",
":",
"git_version",
"=",
"format_git_describe",
"(",
"call_git_describe",
"(",
")",
",",
"pep440",
"=",
"pep440",
")",
"if",
"git_version",
"is",
"None",
":",
"# not a git repository",
"return",
"read_relea... | 39.28 | 0.000994 |
def _windows_remotes_on(port, which_end):
r'''
Windows specific helper function.
Returns set of ipv4 host addresses of remote established connections
on local or remote tcp port.
Parses output of shell 'netstat' to get connections
C:\>netstat -n
Active Connections
Proto Local Add... | [
"def",
"_windows_remotes_on",
"(",
"port",
",",
"which_end",
")",
":",
"remotes",
"=",
"set",
"(",
")",
"try",
":",
"data",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"'netstat'",
",",
"'-n'",
"]",
")",
"# pylint: disable=minimum-python-version",
"excep... | 33.861111 | 0.001595 |
def get_service_location_info(self, service_location_id):
"""
Request service location info
Parameters
----------
service_location_id : int
Returns
-------
dict
"""
url = urljoin(URLS['servicelocation'], service_location_id, "info")
... | [
"def",
"get_service_location_info",
"(",
"self",
",",
"service_location_id",
")",
":",
"url",
"=",
"urljoin",
"(",
"URLS",
"[",
"'servicelocation'",
"]",
",",
"service_location_id",
",",
"\"info\"",
")",
"headers",
"=",
"{",
"\"Authorization\"",
":",
"\"Bearer {}\... | 27.823529 | 0.00409 |
def add_child(self, group_lookup_attribute_value):
""" Attempts to add a child to the AD group.
:param group_lookup_attribute_value: The value for the LDAP_GROUPS_GROUP_LOOKUP_ATTRIBUTE.
:type group_lookup_attribute_value: str
:raises: **GroupDoesNotExist** if the provided group ... | [
"def",
"add_child",
"(",
"self",
",",
"group_lookup_attribute_value",
")",
":",
"add_child",
"=",
"{",
"'member'",
":",
"(",
"MODIFY_ADD",
",",
"[",
"self",
".",
"_get_group_dn",
"(",
"group_lookup_attribute_value",
")",
"]",
")",
"}",
"self",
".",
"_attempt_m... | 60.529412 | 0.008612 |
def remove_label_from_pr(repo: GithubRepository,
pull_id: int,
label: str) -> bool:
"""
References:
https://developer.github.com/v3/issues/labels/#remove-a-label-from-an-issue
"""
url = ("https://api.github.com/repos/{}/{}/issues/{}/labels/{}"
... | [
"def",
"remove_label_from_pr",
"(",
"repo",
":",
"GithubRepository",
",",
"pull_id",
":",
"int",
",",
"label",
":",
"str",
")",
"->",
"bool",
":",
"url",
"=",
"(",
"\"https://api.github.com/repos/{}/{}/issues/{}/labels/{}\"",
"\"?access_token={}\"",
".",
"format",
"... | 36.814815 | 0.00098 |
def get_stream_if_exists(self, stream_id):
"""Return a reference to a stream with the given ``stream_id`` if it exists
This works similar to :py:meth:`get_stream` but will return None if the
stream is not already created.
:param stream_id: The path of the stream on Device Cloud
... | [
"def",
"get_stream_if_exists",
"(",
"self",
",",
"stream_id",
")",
":",
"stream",
"=",
"self",
".",
"get_stream",
"(",
"stream_id",
")",
"try",
":",
"stream",
".",
"get_data_type",
"(",
"use_cached",
"=",
"True",
")",
"except",
"NoSuchStreamException",
":",
... | 38.3 | 0.003822 |
def predict(self, p, x):
"""
Parameters
----------
p: ndarray
(Ns, d) array of predictor variables (Ns samples, d dimensions)
for regression
x: ndarray
ndarray of (x, y) points. Needs to be a (Ns, 2) array
corresponding to the lon/l... | [
"def",
"predict",
"(",
"self",
",",
"p",
",",
"x",
")",
":",
"return",
"self",
".",
"krige_residual",
"(",
"x",
")",
"+",
"self",
".",
"regression_model",
".",
"predict",
"(",
"p",
")"
] | 30.5 | 0.00318 |
def add_op_request_access_to_group(self, name, namespace=None,
permission=None, key_name=None,
object_prefix_permissions=None):
"""
Adds the requested permissions to the current service's Ceph key,
allowing the key to ... | [
"def",
"add_op_request_access_to_group",
"(",
"self",
",",
"name",
",",
"namespace",
"=",
"None",
",",
"permission",
"=",
"None",
",",
"key_name",
"=",
"None",
",",
"object_prefix_permissions",
"=",
"None",
")",
":",
"self",
".",
"ops",
".",
"append",
"(",
... | 49 | 0.004215 |
def normalize_LCSH(subject):
"""Normalize a LCSH subject heading prior to indexing."""
# Strip then divide on -- which is a delimiter for LCSH;
# rejoin after stripping parts.
subject_parts = subject.strip().split('--')
joined_subject = ' -- '.join([part.strip() for part in subject_parts])
# Ch... | [
"def",
"normalize_LCSH",
"(",
"subject",
")",
":",
"# Strip then divide on -- which is a delimiter for LCSH;",
"# rejoin after stripping parts.",
"subject_parts",
"=",
"subject",
".",
"strip",
"(",
")",
".",
"split",
"(",
"'--'",
")",
"joined_subject",
"=",
"' -- '",
".... | 41.153846 | 0.001828 |
def rasterize(self,
pitch,
origin,
resolution=None,
fill=True,
width=None,
**kwargs):
"""
Rasterize a Path2D object into a boolean image ("mode 1").
Parameters
------------
... | [
"def",
"rasterize",
"(",
"self",
",",
"pitch",
",",
"origin",
",",
"resolution",
"=",
"None",
",",
"fill",
"=",
"True",
",",
"width",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"image",
"=",
"raster",
".",
"rasterize",
"(",
"self",
",",
"pitch... | 34.655172 | 0.007744 |
def logStream(fileHandle, shortName, printFunction=logger.info):
"""Writes out a formatted version of the given log stream.
"""
printFunction("Reporting file: %s" % shortName)
line = fileHandle.readline()
while line != '':
if line[-1] == '\n':
line = line[:-1]
printFuncti... | [
"def",
"logStream",
"(",
"fileHandle",
",",
"shortName",
",",
"printFunction",
"=",
"logger",
".",
"info",
")",
":",
"printFunction",
"(",
"\"Reporting file: %s\"",
"%",
"shortName",
")",
"line",
"=",
"fileHandle",
".",
"readline",
"(",
")",
"while",
"line",
... | 36.636364 | 0.002421 |
def filter(self, userinfo, user_info_claims=None):
"""
Return only those claims that are asked for.
It's a best effort task; if essential claims are not present
no error is flagged.
:param userinfo: A dictionary containing the available info for one user
:param user_info... | [
"def",
"filter",
"(",
"self",
",",
"userinfo",
",",
"user_info_claims",
"=",
"None",
")",
":",
"if",
"user_info_claims",
"is",
"None",
":",
"return",
"copy",
".",
"copy",
"(",
"userinfo",
")",
"else",
":",
"result",
"=",
"{",
"}",
"missing",
"=",
"[",
... | 35.692308 | 0.003148 |
def minute_trend_times(start, end):
"""Expand a [start, end) interval for use in querying for minute trends
NDS2 requires start and end times for minute trends to be a multiple of
60 (to exactly match the time of a minute-trend sample), so this function
expands the given ``[start, end)`` interval to th... | [
"def",
"minute_trend_times",
"(",
"start",
",",
"end",
")",
":",
"if",
"start",
"%",
"60",
":",
"start",
"=",
"int",
"(",
"start",
")",
"//",
"60",
"*",
"60",
"if",
"end",
"%",
"60",
":",
"end",
"=",
"int",
"(",
"end",
")",
"//",
"60",
"*",
"... | 28.37037 | 0.001263 |
def add_net32string(self, string):
"""
>>> r = b'\\x00\\x00\\x00\\x01x'
>>> OutBuffer().add_net32string(b"x").getvalue() == r
True
@type string: bytes
@param string: maximum length must fit in a 32bit integer
@returns: self
@raises OmapiSizeLimitError:
"""
if len(string) >= (1 << 32):
raise Valu... | [
"def",
"add_net32string",
"(",
"self",
",",
"string",
")",
":",
"if",
"len",
"(",
"string",
")",
">=",
"(",
"1",
"<<",
"32",
")",
":",
"raise",
"ValueError",
"(",
"\"string too long\"",
")",
"return",
"self",
".",
"add_net32int",
"(",
"len",
"(",
"stri... | 27.428571 | 0.035264 |
def enter(self, container_alias):
'''
a method to open up a terminal inside a running container
:param container_alias: string with name or id of container
:return: None
'''
title = '%s.enter' % self.__class__.__name__
# validate inputs
... | [
"def",
"enter",
"(",
"self",
",",
"container_alias",
")",
":",
"title",
"=",
"'%s.enter'",
"%",
"self",
".",
"__class__",
".",
"__name__",
"# validate inputs\r",
"input_fields",
"=",
"{",
"'container_alias'",
":",
"container_alias",
"}",
"for",
"key",
",",
"va... | 31 | 0.005794 |
def StartService(service_name):
"""Start a Windows service with the given name.
Args:
service_name: string The name of the service to be started.
"""
try:
win32serviceutil.StartService(service_name)
logging.info("Service '%s' started.", service_name)
except pywintypes.error as e:
if getattr(e... | [
"def",
"StartService",
"(",
"service_name",
")",
":",
"try",
":",
"win32serviceutil",
".",
"StartService",
"(",
"service_name",
")",
"logging",
".",
"info",
"(",
"\"Service '%s' started.\"",
",",
"service_name",
")",
"except",
"pywintypes",
".",
"error",
"as",
"... | 38 | 0.011986 |
def reset(self):
"""Reset the state of this updater for a new optimisation problem."""
self.__init__(self.alpha, self.beta1, self.beta2, self.epsilon) | [
"def",
"reset",
"(",
"self",
")",
":",
"self",
".",
"__init__",
"(",
"self",
".",
"alpha",
",",
"self",
".",
"beta1",
",",
"self",
".",
"beta2",
",",
"self",
".",
"epsilon",
")"
] | 54.666667 | 0.012048 |
def create_colspec(self, columns, overflow_default=None):
""" Produce a full format columns spec dictionary. The overrides spec
can be a partial columns spec as described in the __init__ method's
depiction of the .columns attribute. """
spec = [{
"width": None,
"... | [
"def",
"create_colspec",
"(",
"self",
",",
"columns",
",",
"overflow_default",
"=",
"None",
")",
":",
"spec",
"=",
"[",
"{",
"\"width\"",
":",
"None",
",",
"\"minwidth\"",
":",
"self",
".",
"column_minwidth",
",",
"\"padding\"",
":",
"self",
".",
"column_p... | 42.055556 | 0.002584 |
def isuncertainties(arg_list):
"""
check if the input list contains any elements with uncertainties class
:param arg_list: list of arguments
:return: True/False
"""
for arg in arg_list:
if isinstance(arg, (list, tuple)) and isinstance(arg[0], uct.UFloat):
return True
... | [
"def",
"isuncertainties",
"(",
"arg_list",
")",
":",
"for",
"arg",
"in",
"arg_list",
":",
"if",
"isinstance",
"(",
"arg",
",",
"(",
"list",
",",
"tuple",
")",
")",
"and",
"isinstance",
"(",
"arg",
"[",
"0",
"]",
",",
"uct",
".",
"UFloat",
")",
":",... | 33.588235 | 0.001704 |
def _readintle(self, length, start):
"""Read bits and interpret as a little-endian signed int."""
ui = self._readuintle(length, start)
if not ui >> (length - 1):
# Top bit not set, number is positive
return ui
# Top bit is set, so number is negative
tmp = ... | [
"def",
"_readintle",
"(",
"self",
",",
"length",
",",
"start",
")",
":",
"ui",
"=",
"self",
".",
"_readuintle",
"(",
"length",
",",
"start",
")",
"if",
"not",
"ui",
">>",
"(",
"length",
"-",
"1",
")",
":",
"# Top bit not set, number is positive",
"return... | 40.555556 | 0.005362 |
def validate_netmask(s):
"""Validate that a dotted-quad ip address is a valid netmask.
>>> validate_netmask('0.0.0.0')
True
>>> validate_netmask('128.0.0.0')
True
>>> validate_netmask('255.0.0.0')
True
>>> validate_netmask('255.255.255.255')
True
>>> validate_netmask(BROADCAST)... | [
"def",
"validate_netmask",
"(",
"s",
")",
":",
"if",
"validate_ip",
"(",
"s",
")",
":",
"# Convert to binary string, strip '0b' prefix, 0 pad to 32 bits",
"mask",
"=",
"bin",
"(",
"ip2network",
"(",
"s",
")",
")",
"[",
"2",
":",
"]",
".",
"zfill",
"(",
"32",... | 25.707317 | 0.000914 |
def print_results(self, results, min_ratio=None, indent=False, pval=0.05, prt=sys.stdout):
"""Print GOEA results with some additional statistics calculated."""
results_adj = self.get_adj_records(results, min_ratio, pval)
self.print_results_adj(results_adj, indent, prt) | [
"def",
"print_results",
"(",
"self",
",",
"results",
",",
"min_ratio",
"=",
"None",
",",
"indent",
"=",
"False",
",",
"pval",
"=",
"0.05",
",",
"prt",
"=",
"sys",
".",
"stdout",
")",
":",
"results_adj",
"=",
"self",
".",
"get_adj_records",
"(",
"result... | 72.5 | 0.010239 |
def uninstalled(name, version=None, uninstall_args=None, override_args=False):
'''
Uninstalls a package
name
The name of the package to be uninstalled
version
Uninstalls a specific version of the package. Defaults to latest
version installed.
uninstall_args
A list of unins... | [
"def",
"uninstalled",
"(",
"name",
",",
"version",
"=",
"None",
",",
"uninstall_args",
"=",
"None",
",",
"override_args",
"=",
"False",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"True",
",",
"'changes'",
":",
"{",
"}",
"... | 30.155844 | 0.000834 |
def get_version():
"""Reads version number.
This workaround is required since __init__ is an entry point exposing
stuff from other modules, which may use dependencies unavailable
in current environment, which in turn will prevent this application
from install.
"""
contents = read(os.path.j... | [
"def",
"get_version",
"(",
")",
":",
"contents",
"=",
"read",
"(",
"os",
".",
"path",
".",
"join",
"(",
"PATH_BASE",
",",
"'srptools'",
",",
"'__init__.py'",
")",
")",
"version",
"=",
"re",
".",
"search",
"(",
"'VERSION = \\(([^)]+)\\)'",
",",
"contents",
... | 37.384615 | 0.006024 |
def _calc_grad_tiled(self, img, t_grad, tile_size=512):
'''Compute the value of tensor t_grad over the image in a tiled way.
Random shifts are applied to the image to blur tile boundaries over
multiple iterations.'''
sz = tile_size
h, w = img.shape[:2]
sx, sy = np.random... | [
"def",
"_calc_grad_tiled",
"(",
"self",
",",
"img",
",",
"t_grad",
",",
"tile_size",
"=",
"512",
")",
":",
"sz",
"=",
"tile_size",
"h",
",",
"w",
"=",
"img",
".",
"shape",
"[",
":",
"2",
"]",
"sx",
",",
"sy",
"=",
"np",
".",
"random",
".",
"ran... | 48.266667 | 0.01084 |
def drawstarslist(self, dictlist, r = 10, colour = None):
"""
Calls drawcircle and writelable for an list of stars.
Provide a list of dictionnaries, where each dictionnary contains "name", "x", and "y".
"""
self.checkforpilimage()
colour = self.defaultco... | [
"def",
"drawstarslist",
"(",
"self",
",",
"dictlist",
",",
"r",
"=",
"10",
",",
"colour",
"=",
"None",
")",
":",
"self",
".",
"checkforpilimage",
"(",
")",
"colour",
"=",
"self",
".",
"defaultcolour",
"(",
"colour",
")",
"self",
".",
"changecolourmode",
... | 36.894737 | 0.031989 |
def get(self, request, *args, **kwargs):
"""Override default get function to use token if there is one to retrieve object. If a
subclass should use their own GET implementation, token_from_kwargs should be called if
that detail view should be accessible via token."""
self.object = self.... | [
"def",
"get",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"object",
"=",
"self",
".",
"get_object",
"(",
")",
"allow_anonymous",
"=",
"kwargs",
".",
"get",
"(",
"\"allow_anonymous\"",
",",
"False",
"... | 43.428571 | 0.004505 |
def get_spot(self, feature=None, **kwargs):
"""
Shortcut to :meth:`get_feature` but with kind='spot'
"""
kwargs.setdefault('kind', 'spot')
return self.get_feature(feature, **kwargs) | [
"def",
"get_spot",
"(",
"self",
",",
"feature",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"setdefault",
"(",
"'kind'",
",",
"'spot'",
")",
"return",
"self",
".",
"get_feature",
"(",
"feature",
",",
"*",
"*",
"kwargs",
")"
] | 36 | 0.00905 |
def error(self, s):
"""
Prints out an error message to stderr.
:param s: The error string to print
:return: None
"""
print(" ERROR: '%s', %s" % (self.src_id, s), file=sys.stderr) | [
"def",
"error",
"(",
"self",
",",
"s",
")",
":",
"print",
"(",
"\" ERROR: '%s', %s\"",
"%",
"(",
"self",
".",
"src_id",
",",
"s",
")",
",",
"file",
"=",
"sys",
".",
"stderr",
")"
] | 31.714286 | 0.008772 |
def bulk_get(cls, files, api=None):
"""
Retrieve files with specified ids in bulk
:param files: Files to be retrieved.
:param api: Api instance.
:return: List of FileBulkRecord objects.
"""
api = api or cls._API
file_ids = [Transform.to_file(file_) for fil... | [
"def",
"bulk_get",
"(",
"cls",
",",
"files",
",",
"api",
"=",
"None",
")",
":",
"api",
"=",
"api",
"or",
"cls",
".",
"_API",
"file_ids",
"=",
"[",
"Transform",
".",
"to_file",
"(",
"file_",
")",
"for",
"file_",
"in",
"files",
"]",
"data",
"=",
"{... | 38.642857 | 0.00361 |
def transfer(self, asset_transfer_specs, btc_transfer_spec, fees):
"""
Creates a transaction for sending assets and bitcoins.
:param list[(bytes, TransferParameters)] asset_transfer_specs: A list of tuples. In each tuple:
- The first element is the ID of an asset.
- The ... | [
"def",
"transfer",
"(",
"self",
",",
"asset_transfer_specs",
",",
"btc_transfer_spec",
",",
"fees",
")",
":",
"inputs",
"=",
"[",
"]",
"outputs",
"=",
"[",
"]",
"asset_quantities",
"=",
"[",
"]",
"for",
"asset_id",
",",
"transfer_spec",
"in",
"asset_transfer... | 48.88 | 0.004412 |
def get_alias(self, alias):
"""
RETURN REFERENCE TO ALIAS (MANY INDEXES)
USER MUST BE SURE NOT TO SEND UPDATES
"""
aliases = self.get_aliases()
if alias in aliases.alias:
settings = self.settings.copy()
settings.alias = alias
settings.i... | [
"def",
"get_alias",
"(",
"self",
",",
"alias",
")",
":",
"aliases",
"=",
"self",
".",
"get_aliases",
"(",
")",
"if",
"alias",
"in",
"aliases",
".",
"alias",
":",
"settings",
"=",
"self",
".",
"settings",
".",
"copy",
"(",
")",
"settings",
".",
"alias... | 40.25 | 0.008097 |
def _request_tls(self):
"""Request a TLS-encrypted connection.
[initiating entity only]"""
self.requested = True
element = ElementTree.Element(STARTTLS_TAG)
self.stream.write_element(element) | [
"def",
"_request_tls",
"(",
"self",
")",
":",
"self",
".",
"requested",
"=",
"True",
"element",
"=",
"ElementTree",
".",
"Element",
"(",
"STARTTLS_TAG",
")",
"self",
".",
"stream",
".",
"write_element",
"(",
"element",
")"
] | 32.285714 | 0.008621 |
def get_cfg_template(auth, url, folder=None):
"""
Function takes no input and returns a list of dictionaries containing the configuration
templates in the root folder of the icc configuration template library.
:param auth: requests auth object #usually auth.creds from auth pyhpeimc.auth.class
:par... | [
"def",
"get_cfg_template",
"(",
"auth",
",",
"url",
",",
"folder",
"=",
"None",
")",
":",
"if",
"folder",
"is",
"None",
":",
"get_cfg_template_url",
"=",
"\"/imcrs/icc/confFile/list\"",
"else",
":",
"folder_id",
"=",
"get_folder_id",
"(",
"folder",
",",
"auth"... | 36.232143 | 0.003839 |
def frequency(data, output='spectraldensity', scaling='power', sides='one',
taper=None, halfbandwidth=3, NW=None, duration=None,
overlap=0.5, step=None, detrend='linear', n_fft=None,
log_trans=False, centend='mean'):
"""Compute the
power spectral density (PSD, output='s... | [
"def",
"frequency",
"(",
"data",
",",
"output",
"=",
"'spectraldensity'",
",",
"scaling",
"=",
"'power'",
",",
"sides",
"=",
"'one'",
",",
"taper",
"=",
"None",
",",
"halfbandwidth",
"=",
"3",
",",
"NW",
"=",
"None",
",",
"duration",
"=",
"None",
",",
... | 39.266667 | 0.001325 |
def has_object_permission(self, request, view, obj=None):
"""Check object permissions based on filters."""
filter_and_actions = self._get_filter_and_actions(
request.query_params.get('sign'),
view.action,
'{}.{}'.format(obj._meta.app_label, obj._meta.model_name))
... | [
"def",
"has_object_permission",
"(",
"self",
",",
"request",
",",
"view",
",",
"obj",
"=",
"None",
")",
":",
"filter_and_actions",
"=",
"self",
".",
"_get_filter_and_actions",
"(",
"request",
".",
"query_params",
".",
"get",
"(",
"'sign'",
")",
",",
"view",
... | 47.8 | 0.004107 |
def get_each_method_maximun_cpu_mem(self):
"""获取每个方法中的cpu和内存耗费最值点."""
# 本函数用于丰富self.method_exec_info的信息:存入cpu、mem最值点
self.method_exec_info = deepcopy(self.data.get("method_exec_info", []))
method_exec_info = deepcopy(self.method_exec_info) # 用来辅助循环
method_index, cpu_max, cpu_max... | [
"def",
"get_each_method_maximun_cpu_mem",
"(",
"self",
")",
":",
"# 本函数用于丰富self.method_exec_info的信息:存入cpu、mem最值点",
"self",
".",
"method_exec_info",
"=",
"deepcopy",
"(",
"self",
".",
"data",
".",
"get",
"(",
"\"method_exec_info\"",
",",
"[",
"]",
")",
")",
"method_e... | 50.971429 | 0.00275 |
def upload_new_file_version(self, name, folder_id, file_id, file_path):
"""Upload a new version of a file into a folder.
Use function for small file otherwise there is the chunk_upload_file() function.
Args::
name (str): Name of the file on your Box storage.
folder_id ... | [
"def",
"upload_new_file_version",
"(",
"self",
",",
"name",
",",
"folder_id",
",",
"file_id",
",",
"file_path",
")",
":",
"try",
":",
"return",
"self",
".",
"__do_upload_file",
"(",
"name",
",",
"folder_id",
",",
"file_path",
",",
"file_id",
")",
"except",
... | 34.870968 | 0.0045 |
def add_rulegroup(self, rulegroup):
"""Adds a rulegroup to this segment."""
body = rulegroup
response = self._post("/segments/%s/rules.json" %
self.segment_id, json.dumps(body)) | [
"def",
"add_rulegroup",
"(",
"self",
",",
"rulegroup",
")",
":",
"body",
"=",
"rulegroup",
"response",
"=",
"self",
".",
"_post",
"(",
"\"/segments/%s/rules.json\"",
"%",
"self",
".",
"segment_id",
",",
"json",
".",
"dumps",
"(",
"body",
")",
")"
] | 45.4 | 0.008658 |
def create_scope(self, info, scope_id):
"""CreateScope.
[Preview API]
:param :class:`<CreateScopeInfo> <azure.devops.v5_0.identity.models.CreateScopeInfo>` info:
:param str scope_id:
:rtype: :class:`<IdentityScope> <azure.devops.v5_0.identity.models.IdentityScope>`
"""
... | [
"def",
"create_scope",
"(",
"self",
",",
"info",
",",
"scope_id",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"scope_id",
"is",
"not",
"None",
":",
"route_values",
"[",
"'scopeId'",
"]",
"=",
"self",
".",
"_serialize",
".",
"url",
"(",
"'scope_id'",
... | 50.647059 | 0.006842 |
def search_tweets_iterable(self, order, callback=None):
""" Returns itself and queries the Twitter API. Is called when using \
an instance of this class as iterable. \
See `Basic usage <basic_usage.html>`_ for examples
:param order: An instance of TwitterOrder class \
(e.g. Twit... | [
"def",
"search_tweets_iterable",
"(",
"self",
",",
"order",
",",
"callback",
"=",
"None",
")",
":",
"if",
"callback",
":",
"if",
"not",
"callable",
"(",
"callback",
")",
":",
"raise",
"TwitterSearchException",
"(",
"1018",
")",
"self",
".",
"__callback",
"... | 37.315789 | 0.002751 |
def can_use_cache(self, target: Target) -> bool:
"""Return True if should attempt to load `target` from cache.
Return False if `target` has to be built, regardless of its cache
status (because cache is disabled, or dependencies are dirty).
"""
# if caching is disabled for t... | [
"def",
"can_use_cache",
"(",
"self",
",",
"target",
":",
"Target",
")",
"->",
"bool",
":",
"# if caching is disabled for this execution, then all targets are dirty",
"if",
"self",
".",
"conf",
".",
"no_build_cache",
":",
"return",
"False",
"# if the target's `cachable` pr... | 49.388889 | 0.002208 |
def get_string_width(self, s):
"Get width of a string in the current font"
s = self.normalize_text(s)
cw=self.current_font['cw']
w=0
l=len(s)
if self.unifontsubset:
for char in s:
char = ord(char)
if len(cw) > char:
... | [
"def",
"get_string_width",
"(",
"self",
",",
"s",
")",
":",
"s",
"=",
"self",
".",
"normalize_text",
"(",
"s",
")",
"cw",
"=",
"self",
".",
"current_font",
"[",
"'cw'",
"]",
"w",
"=",
"0",
"l",
"=",
"len",
"(",
"s",
")",
"if",
"self",
".",
"uni... | 41.904762 | 0.014444 |
def demean(self, mask=NotSpecified, groupby=NotSpecified):
"""
Construct a Factor that computes ``self`` and subtracts the mean from
row of the result.
If ``mask`` is supplied, ignore values where ``mask`` returns False
when computing row means, and output NaN anywhere the mask ... | [
"def",
"demean",
"(",
"self",
",",
"mask",
"=",
"NotSpecified",
",",
"groupby",
"=",
"NotSpecified",
")",
":",
"return",
"GroupedRowTransform",
"(",
"transform",
"=",
"demean",
",",
"transform_args",
"=",
"(",
")",
",",
"factor",
"=",
"self",
",",
"groupby... | 38.073171 | 0.000416 |
def equals(self, other):
"""
Determine if two Index objects contain the same elements.
"""
if self.is_(other):
return True
if not isinstance(other, Index):
return False
if is_object_dtype(self) and not is_object_dtype(other):
# if oth... | [
"def",
"equals",
"(",
"self",
",",
"other",
")",
":",
"if",
"self",
".",
"is_",
"(",
"other",
")",
":",
"return",
"True",
"if",
"not",
"isinstance",
"(",
"other",
",",
"Index",
")",
":",
"return",
"False",
"if",
"is_object_dtype",
"(",
"self",
")",
... | 30.842105 | 0.003311 |
def start(self):
"""Start processing streams."""
def cb():
time_ = time.time()
log.debug('Step {}'.format(time_))
# run a step on all streams
for d in self._dstreams:
d._step(time_)
self._pcb = PeriodicCallback(cb, self.batch_dur... | [
"def",
"start",
"(",
"self",
")",
":",
"def",
"cb",
"(",
")",
":",
"time_",
"=",
"time",
".",
"time",
"(",
")",
"log",
".",
"debug",
"(",
"'Step {}'",
".",
"format",
"(",
"time_",
")",
")",
"# run a step on all streams",
"for",
"d",
"in",
"self",
"... | 29.466667 | 0.004386 |
def _upload_chunk(self, spider):
"""
Do upload items to S3.
"""
if not self.items:
return # Do nothing when items is empty.
f = self._make_fileobj()
# Build object key by replacing variables in object key template.
object_key = self.object_key_temp... | [
"def",
"_upload_chunk",
"(",
"self",
",",
"spider",
")",
":",
"if",
"not",
"self",
".",
"items",
":",
"return",
"# Do nothing when items is empty.",
"f",
"=",
"self",
".",
"_make_fileobj",
"(",
")",
"# Build object key by replacing variables in object key template.",
... | 30.25 | 0.004005 |
def search_upwards(self, fpath=None, repodirname='.svn', upwards={}):
"""
Traverse filesystem upwards, searching for .svn directories
with matching UUIDs (Recursive)
Args:
fpath (str): file path to search upwards from
repodirname (str): directory name to search f... | [
"def",
"search_upwards",
"(",
"self",
",",
"fpath",
"=",
"None",
",",
"repodirname",
"=",
"'.svn'",
",",
"upwards",
"=",
"{",
"}",
")",
":",
"fpath",
"=",
"fpath",
"or",
"self",
".",
"fpath",
"uuid",
"=",
"self",
".",
"unique_id",
"last_path",
"=",
"... | 30.508197 | 0.001041 |
def enqueue(self, item, queue=None):
"""
Enqueue items.
If you define "self.filter" (sequence),
this method put the item to queue after filtering.
"self.filter" operates as blacklist.
This method expects that
"item" argument has dict type "data" attribute.
... | [
"def",
"enqueue",
"(",
"self",
",",
"item",
",",
"queue",
"=",
"None",
")",
":",
"if",
"queue",
"is",
"None",
":",
"queue",
"=",
"self",
".",
"queue",
"is_enqueue_item",
"=",
"True",
"if",
"self",
".",
"invalid_key_list",
"is",
"not",
"None",
":",
"f... | 32.055556 | 0.001682 |
def hasconstraint(self):
"""bool, whether the term has any constraints
"""
constrained = False
for term in self._terms:
constrained = constrained or term.hasconstraint
return constrained | [
"def",
"hasconstraint",
"(",
"self",
")",
":",
"constrained",
"=",
"False",
"for",
"term",
"in",
"self",
".",
"_terms",
":",
"constrained",
"=",
"constrained",
"or",
"term",
".",
"hasconstraint",
"return",
"constrained"
] | 33.142857 | 0.008403 |
def _effective_path(self):
# type: () -> List[str]
"""
Returns a list of paths to search for config files in reverse order of
precedence. In other words: the last path element will override the
settings from the first one.
"""
# default search path
path =... | [
"def",
"_effective_path",
"(",
"self",
")",
":",
"# type: () -> List[str]",
"# default search path",
"path",
"=",
"(",
"[",
"'/etc/%s/%s'",
"%",
"(",
"self",
".",
"group_name",
",",
"self",
".",
"app_name",
")",
"]",
"+",
"self",
".",
"get_xdg_dirs",
"(",
")... | 43.157895 | 0.001789 |
def rstrip_extra(fname):
"""Strip extraneous, non-discriminative filename info from the end of a file.
"""
to_strip = ("_R", ".R", "-R", "_", "fastq", ".", "-")
while fname.endswith(to_strip):
for x in to_strip:
if fname.endswith(x):
fname = fname[:len(fname) - len(x)... | [
"def",
"rstrip_extra",
"(",
"fname",
")",
":",
"to_strip",
"=",
"(",
"\"_R\"",
",",
"\".R\"",
",",
"\"-R\"",
",",
"\"_\"",
",",
"\"fastq\"",
",",
"\".\"",
",",
"\"-\"",
")",
"while",
"fname",
".",
"endswith",
"(",
"to_strip",
")",
":",
"for",
"x",
"i... | 35.1 | 0.005556 |
def split_layers(lower, upper, __fval=None, **fval):
"""Split 2 layers previously bound.
This call un-links calls bind_top_down and bind_bottom_up. It is the opposite of # noqa: E501
bind_layers.
Please have a look at their docs:
- help(split_bottom_up)
- help(split_top_down)
"""
if ... | [
"def",
"split_layers",
"(",
"lower",
",",
"upper",
",",
"__fval",
"=",
"None",
",",
"*",
"*",
"fval",
")",
":",
"if",
"__fval",
"is",
"not",
"None",
":",
"fval",
".",
"update",
"(",
"__fval",
")",
"split_bottom_up",
"(",
"lower",
",",
"upper",
",",
... | 33.692308 | 0.002222 |
def update_colors(self, colors):
'''Update the colors inplace'''
self.colors = np.array(colors, dtype='uint8')
prim_colors = self._gen_colors(self.colors)
self._color_vbo.set_data(prim_colors)
self.widget.update() | [
"def",
"update_colors",
"(",
"self",
",",
"colors",
")",
":",
"self",
".",
"colors",
"=",
"np",
".",
"array",
"(",
"colors",
",",
"dtype",
"=",
"'uint8'",
")",
"prim_colors",
"=",
"self",
".",
"_gen_colors",
"(",
"self",
".",
"colors",
")",
"self",
"... | 36.571429 | 0.01145 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.